hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
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
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
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
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
07f86e762d5471c705dde7af207b48bd25e576bf
6,958
hpp
C++
Engine/Code/Engine/Input/KeyCode.hpp
cugone/Abrams2022
54efe5fdd7d2d9697f005ee45a171ecea68d0df8
[ "MIT" ]
1
2020-07-14T06:58:50.000Z
2020-07-14T06:58:50.000Z
Engine/Code/Engine/Input/KeyCode.hpp
cugone/Abrams2022
54efe5fdd7d2d9697f005ee45a171ecea68d0df8
[ "MIT" ]
20
2021-11-29T14:09:33.000Z
2022-03-26T20:12:44.000Z
Engine/Code/Engine/Input/KeyCode.hpp
cugone/Abrams2022
54efe5fdd7d2d9697f005ee45a171ecea68d0df8
[ "MIT" ]
2
2019-05-01T21:49:33.000Z
2021-04-01T08:22:21.000Z
#pragma once #include "Engine/Core/TypeUtils.hpp" // clang-format off enum class KeyCode : int { FirstMouseButton_ /* Internal use only. */ , LButton = FirstMouseButton_ /* Left Mouse Button */ , RButton /* Right Mouse Button */ , Cancel /* Control-break processing */ , MButton /* Middle Mouse Button */ , XButton1 /* Xtra Mouse Button 1 */ , XButton2 /* Xtra Mouse Button 2 */ , LastMouseButton_ /* Internal use only. */ , First_ /* Internal use only. */ , Back = First_ /* Also Backspace */ , Backspace = Back /* Also Back */ , Tab , Clear , Return /* Also Enter */ , Enter = Return , Shift /* either RShift or LShift */ , Ctrl /* either RCtrl or LCtrl */ , Menu /* either RMenu or LMenu, Also Alt */ , Alt = Menu /* either RAlt or LAlt, Also Menu */ , Pause , Capital /* Also CapsLock */ , CapsLock = Capital , Kana , Hangul /* Also Hangeul */ , Hangeul = Hangul /* Also Hangul */ , Junja , Final , Hanja , Kanji , Escape /* Also Esc */ , Esc = Escape , Convert , NonConvert , Accept , ModeChange , Space /* Also Spacebar */ , Spacebar = Space , Prior /* Also PageUp */ , PageUp = Prior , Next /* Also PageDown and PageDn */ , PageDown = Next /* Also PageDn or Next */ , PageDn = Next /* Also PageDown or Next */ , End , Home , Left , Up , Right , Down , Select , Print , Execute , Snapshot /* Also PrintScreen */ , PrintScreen = Snapshot /* Also Snapshot */ , Insert , Delete /* Also Del */ , Del = Delete /* Also Delete */ , Help , Numeric0 /* Number key above keyboard */ , Numeric1 /* Number key above keyboard */ , Numeric2 /* Number key above keyboard */ , Numeric3 /* Number key above keyboard */ , Numeric4 /* Number key above keyboard */ , Numeric5 /* Number key above keyboard */ , Numeric6 /* Number key above keyboard */ , Numeric7 /* Number key above keyboard */ , Numeric8 /* Number key above keyboard */ , Numeric9 /* Number key above keyboard */ , A , B , C , D , E , F , G , H , I , J , K , L , M , N , O , P , Q , R , S , T , U , V , W , X , Y , Z , LWin , RWin , Apps , Sleep , NumPad0 , NumPad1 , NumPad2 , NumPad3 , NumPad4 , NumPad5 , NumPad6 , NumPad7 , NumPad8 , NumPad9 , Multiply /* NumPad * */ , Add /* NumPad + */ , Separator /* Also NumPadEnter */ , NumPadEnter = Separator /* Also Separator */ , Subtract /* NumPad - */ , Decimal /* NumPad . */ , Divide /* NumPad / */ , F1 , F2 , F3 , F4 , F5 , F6 , F7 , F8 , F9 , F10 , F11 , F12 , F13 , F14 , F15 , F16 , F17 , F18 , F19 , F20 , F21 , F22 , F23 , F24 , NumLock , Scroll /* Also ScrollLock */ , ScrollLock = Scroll /* Also Scroll */ , Oem_Nec_Equal , Oem_Fj_Jisho , Oem_Fj_Masshou , Oem_Fj_Touroku , Oem_Fj_Loya , Oem_Fj_Roya , LShift , RShift , LControl /* Also LCtrl */ , LCtrl = LControl /* Also LControl */ , RControl /* Also RCtrl */ , RCtrl = RControl /* Also RControl */ , RMenu /* Also RAlt */ , RAlt = RMenu /* Also RMenu */ , LMenu /* Also LAlt */ , LAlt = LMenu /* Also LMenu */ , Browser_Back , Browser_Forward , Browser_Refresh , Browser_Stop , Browser_Search , Browser_Favorites , Browser_Home , Volume_Mute , Volume_Down , Volume_Up , Media_Next_Track , Media_Prev_Track , Media_Stop , Media_Play_Pause , Launch_Mail , Launch_Media_Select , Launch_App1 , Launch_App2 , Oem_1 /* Key ;: */ , Semicolon = Oem_1 /* Key ;: */ , Oem_Plus /* Key =+ */ , Equals = Oem_Plus /* Key =+ */ , Oem_Comma /* Key ,< */ , Comma = Oem_Comma /* Key ,< */ , Oem_Minus /* Key -_ */ , Minus = Oem_Minus /* Key -_ */ , Oem_Period /* Key .> */ , Period = Oem_Period /* Key .> */ , Oem_2 /* Key /? */ , ForwardSlash = Oem_2 /* Key /?, Also FSlash */ , FSlash = Oem_2 /* Key /?, Also ForwardSlash */ , Oem_3 /* Key `~ */ , Backquote = Oem_3 /* Key `~, Also Tilde */ , Tilde = Oem_3 /* Key `~, Also Backquote */ , Gamepad_First_ /* Internal use only. */ , Gamepad_A = Gamepad_First_ , Gamepad_FaceButton_Bottom = Gamepad_A /* Also Gamepad_A */ , Gamepad_B , Gamepad_FaceButton_Right = Gamepad_B /* Also Gamepad_B */ , Gamepad_X , Gamepad_FaceButton_Left = Gamepad_X /* Also Gamepad_X */ , Gamepad_Y , Gamepad_FaceButton_Top = Gamepad_Y /* Also Gamepad_Y */ , Gamepad_Right_Shoulder , Gamepad_Left_Shoulder , Gamepad_Left_Trigger , Gamepad_Right_Trigger , Gamepad_DPad_Up , Gamepad_DPad_Down , Gamepad_DPad_Left , Gamepad_DPad_Right , Gamepad_Menu , Gamepad_View , Gamepad_Left_Thumbstick_Button , Gamepad_Right_Thumbstick_Button , Gamepad_Left_Thumbstick_Up , Gamepad_Left_Thumbstick_Down , Gamepad_Left_Thumbstick_Right , Gamepad_Left_Thumbstick_Left , Gamepad_Right_Thumbstick_Up , Gamepad_Right_Thumbstick_Down , Gamepad_Right_Thumbstick_Right , Gamepad_Right_Thumbstick_Left , Gamepad_Last_ /* Internal use only. */ , Oem_4 /* Key [{ */ , LeftBracket = Oem_4 /* Key [{, Also LBracket */ , LBracket = Oem_4 /* Key [{, Also LeftBracket */ , Oem_5 /* Key \|, Also Backslash */ , Backslash = Oem_5 /* Key \| */ , Oem_6 /* Key ]} */ , RightBracket = Oem_6 /* Key ]}, Also RBracket */ , RBracket = Oem_6 /* Key ]}, Also RightBracket */ , Oem_7 /* Key '" */ , Apostrophe = Oem_7 /* Key '", Also Apostrophe */ , SingleQuote = Oem_7 /* Key '", Also SingleQuote */ , Oem_8 /* misc. unknown */ , Oem_Ax , Oem_102 /* RT 102's "<>" or "\|" */ , Ico_Help /* Help key on ICO keyboard */ , Ico_00 /* 00 key on ICO keyboard */ , ProcessKey , Ico_Clear /* Clear key on ICO keyboard */ , Packet /* Key is packet of data */ , Oem_Reset , Oem_Jump , Oem_Pa1 , Oem_Pa2 , Oem_Pa3 , Oem_WsCtrl , Oem_CuSel , Oem_Attn , Oem_Finish , Oem_Copy , Oem_Auto , Oem_EnlW , Oem_BackTab , Attn , CrSel , ExSel , ErEof , Play , Zoom , NoName , Pa1 , Oem_Clear , Last_ /* Internal use only */ , Unknown = 0xFF /* A manufacturer-specific key was pressed. */ , Max /* Internal use only */ }; // clang-format on template<> struct TypeUtils::is_incrementable_enum_type<KeyCode> : std::true_type {}; [[nodiscard]] unsigned char ConvertKeyCodeToWinVK(const KeyCode& code) noexcept; [[nodiscard]] KeyCode ConvertWinVKToKeyCode(unsigned char winVK) noexcept;
24.761566
80
0.564817
cugone
07f9c3bc8ecb9210aff979cedcb847b59ef9df89
8,809
cpp
C++
LightPOV/ModeTest/communication.cpp
BensonYang1999/sciyen-ES-Lux
071ce2c29f48eaab45be56208ed88512eb685349
[ "BSD-3-Clause" ]
5
2021-04-17T10:58:35.000Z
2021-04-17T11:02:55.000Z
LightPOV/ModeTest/communication.cpp
BensonYang1999/sciyen-ES-Lux
071ce2c29f48eaab45be56208ed88512eb685349
[ "BSD-3-Clause" ]
null
null
null
LightPOV/ModeTest/communication.cpp
BensonYang1999/sciyen-ES-Lux
071ce2c29f48eaab45be56208ed88512eb685349
[ "BSD-3-Clause" ]
29
2021-01-30T10:19:03.000Z
2021-04-18T17:40:11.000Z
#include "communication.h" extern TaskHandle_t LED_UPDATE; extern TaskHandle_t WIFI_HANDLE; HTTPClient http; Communication::Communication(){ } void Communication::init(){ connect(); OTA(); } void Communication::OTA() { ArduinoOTA.onStart([]() { vTaskDelete(WIFI_HANDLE); vTaskDelete(LED_UPDATE); String type; if (ArduinoOTA.getCommand() == U_FLASH) { type = "sketch"; } else { // U_FS type = "filesystem"; } // NOTE: if updating FS this would be the place to unmount FS using FS.end() Serial.println("Start updating " + type); }); ArduinoOTA.onEnd([]() { Serial.println("\nEnd"); }); ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) { Serial.printf("Progress: %u%%\r", (progress / (total / 100))); }); ArduinoOTA.onError([](ota_error_t error) { Serial.printf("Error[%u]: ", error); if (error == OTA_AUTH_ERROR) { Serial.println("Auth Failed"); } else if (error == OTA_BEGIN_ERROR) { Serial.println("Begin Failed"); } else if (error == OTA_CONNECT_ERROR) { Serial.println("Connect Failed"); } else if (error == OTA_RECEIVE_ERROR) { Serial.println("Receive Failed"); } else if (error == OTA_END_ERROR) { Serial.println("End Failed"); } }); ArduinoOTA.begin(); } void Communication::connect(){ int n = WiFi.scanNetworks(); for (int i = 0; i < n; ++i){ if (WiFi.SSID(i) == WIFI_SSID1){ WiFi.begin(WIFI_SSID1, WIFI_PASS1); //trying to connect the modem Serial.println(); Serial.print("Connected to "); Serial.println(WIFI_SSID1); break; } if (WiFi.SSID(i) == WIFI_SSID2){ WiFi.begin(WIFI_SSID2, WIFI_PASS2); //trying to connect the modem Serial.println(); Serial.print("Connected to "); Serial.println(WIFI_SSID2); break; } if (WiFi.SSID(i) == WIFI_SSID3){ WiFi.begin(WIFI_SSID3, WIFI_PASS3); //trying to connect the modem Serial.println(); Serial.print("Connected to "); Serial.println(WIFI_SSID3); break; } } Serial.print("Waiting for connection"); // Wait for connection int connection_times = 0; while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); connection_times++; if (connection_times >= WIFI_CONNECT_RETRY) { Serial.println(); Serial.println("Connection Failed! Rebooting..."); delay(1000); ESP.restart(); } } Serial.println(""); /*Serial.print("Connected to "); Serial.println(ssid);*/ Serial.print("IP address: "); Serial.println(WiFi.localIP()); } void Communication::feed_color_param(ValueParam* p, String s){ int comma = s.indexOf(','); uint32_t upper = s.substring(0, comma).toInt(); p->func = (SchedulerFunc)((upper >> 16) & 0xff); p->range = (upper >> 8) & 0xff; p->lower = upper & 0xff; uint32_t lower = s.substring(comma+1).toInt(); p->p1 = (lower >> 8) & 0xff; p->p2 = lower & 0xff; } int Communication::feed_data(Mode* m, String s){ int start=0, len=0; uint32_t checksum = 0; Serial.println(s); for (int i=0; i<s.length(); i++){ // If the first charactor is not `M`, return as error if (i==0 && s[0] != 'M') return 1; if ((s[i] >= '0' && s[i] <= '9') || s[i] == ',') continue; // If there is multi times non-number charactor appearing, it // will skip them till next number comes if (start != i){ // Length of string must larger than 0 String meta = s.substring(start, i); /* // If it failed to convert, it will return 0. if (len == 0) // Mode Type (*m).mode = (MODES)meta.toInt(); else if (len == 1) // Start time (*m).start_time = meta.toInt(); else{ // Other parameter (*m).param[len-2] = meta.toInt(); checksum += (*m).param[len-2]; } len++; */ char key = s[start-1]; switch(key){ case 'M': (*m).mode = (MODES)meta.toInt(); break; case 'S': (*m).start_time = meta.toInt(); break; case 'D': (*m).duration = meta.toInt(); break; case 'X': feed_color_param(&(m->XH), meta);break; case 'Y': feed_color_param(&(m->XS), meta);break; case 'Z': feed_color_param(&(m->XV), meta);break; case 'U': feed_color_param(&(m->YH), meta);break; case 'V': feed_color_param(&(m->YS), meta);break; case 'W': feed_color_param(&(m->YV), meta);break; case 'P': int comma = meta.indexOf(','); uint32_t upper = meta.substring(0, comma).toInt(); m->param[0] = (upper >> 8) & 0xff; m->param[1] = upper & 0xff; uint32_t lower = meta.substring(comma+1).toInt(); m->param[2] = (lower >> 8) & 0xff; m->param[3] = lower & 0xff; break; } } if (s[i] == ';'){ /* // Perform checksum and break String meta = s.substring(start, i); if (checksum & 0xff == meta.toInt()) return len-2; else // Checksum failed */ return 0; } start = i+1; } // End without checksum, unusual request return 0; } bool Communication::receive(Mode* m, int current_id){ if (WiFi.status() == WL_CONNECTED){ /* Request data from server */ String url = String(WIFI_REQUEST_URL) + "?id=" + current_id; http.begin(url); int httpCode = http.GET(); String web_data = http.getString(); Serial.print("\n\nnumber: "); Serial.println(current_id); if (feed_data(m, web_data) != 0){ // Message error, Report it return false; } http.end(); #ifdef DEBUGGER_TASK_REPORT PrintMode(m); #endif } else WifiErrorHandle(); return true; } time_t Communication::check_start_time(uint8_t id, MODES mode, uint8_t* force_start){ if (WiFi.status() == WL_CONNECTED){ /* Request data from server */ String url = String(WIFI_TIME_CHECK_URL) + "?id=" + id + "&effect=" + mode; http.begin(url); int httpCode = http.GET(); String web_data = http.getString(); if (web_data[0] == 'A') *force_start = 0; else *force_start = 1; http.end(); return web_data.substring(1).toInt(); } else WifiErrorHandle(); return 0; } void Communication::WifiErrorHandle(){ #ifdef DEBUGGER Serial.println("Connection Failed! Rebooting..."); #endif delay(1000); ESP.restart(); } void Communication::updateOTA(){ ArduinoOTA.handle(); } void PrintColorSch(ValueParam* v){ Serial.print(" func:"); Serial.print(v->func); Serial.print(", range:"); Serial.print(v->range); Serial.print(", lower:"); Serial.print(v->lower); Serial.print(", p1:"); Serial.print(v->p1); Serial.print(", p2:"); Serial.println(v->p2); } void PrintMode(Mode* m){ Serial.print("Mode:"); Serial.print(m->mode); Serial.print(", start:"); Serial.print(m->start_time); Serial.print(", dur:"); Serial.println(m->duration); Serial.print("XH: "); PrintColorSch(&(m->XH)); Serial.print("XS: "); PrintColorSch(&(m->XS)); Serial.print("XV: "); PrintColorSch(&(m->XV)); Serial.print("YH: "); PrintColorSch(&(m->YH)); Serial.print("YS: "); PrintColorSch(&(m->YS)); Serial.print("YV: "); PrintColorSch(&(m->YV)); Serial.println("Param:"); for (int i=0; i<META_PARAMETER_BUF_SIZE; i++){ Serial.print(m->param[i]); Serial.print(", "); } Serial.println(""); }
30.375862
86
0.493927
BensonYang1999
07fae5a45b89f95264313d6e4f32bb74014623d0
447
hpp
C++
Common/Code/VertexBuffer.hpp
steamclock/internetmap
13bf01e8e1fde8db64ce8fd417a1c907783100ee
[ "MIT" ]
22
2017-07-11T20:31:16.000Z
2021-04-04T16:00:10.000Z
Common/Code/VertexBuffer.hpp
steamclock/internetmap
13bf01e8e1fde8db64ce8fd417a1c907783100ee
[ "MIT" ]
197
2017-07-06T16:53:59.000Z
2019-05-31T17:57:51.000Z
Common/Code/VertexBuffer.hpp
steamclock/internetmap
13bf01e8e1fde8db64ce8fd417a1c907783100ee
[ "MIT" ]
10
2017-12-08T21:58:58.000Z
2021-03-20T07:16:47.000Z
// // VertexBuffer.h // InternetMap // #ifndef __InternetMap__VertexBuffer__ #define __InternetMap__VertexBuffer__ class VertexBuffer { protected: unsigned int _size; unsigned int _vertexBuffer; unsigned char* _lockedVertices; public: VertexBuffer(int size); VertexBuffer(); void beginUpdate(void); void endUpdate(void); long vertexCount(void); }; #endif /* defined(__InternetMap__VertexBuffer__) */
17.88
51
0.715884
steamclock
07fb9f152e1646e4c63386a2261cfbb1b146f90a
1,221
cpp
C++
vcplotbase.cpp
GalacticSoft/DikuEd
135f49bba7ce2faf5faac12a355da9813c28d0fa
[ "MIT" ]
null
null
null
vcplotbase.cpp
GalacticSoft/DikuEd
135f49bba7ce2faf5faac12a355da9813c28d0fa
[ "MIT" ]
null
null
null
vcplotbase.cpp
GalacticSoft/DikuEd
135f49bba7ce2faf5faac12a355da9813c28d0fa
[ "MIT" ]
null
null
null
// Machine generated IDispatch wrapper class(es) created by Microsoft Visual C++ // NOTE: Do not modify the contents of this file. If this class is regenerated by // Microsoft Visual C++, your modifications will be overwritten. #include "stdafx.h" #include "vcplotbase.h" // Dispatch interfaces referenced by this interface #include "VcBrush.h" #include "VcPen.h" ///////////////////////////////////////////////////////////////////////////// // CVcPlotBase properties ///////////////////////////////////////////////////////////////////////////// // CVcPlotBase operations float CVcPlotBase::GetBaseHeight() { float result; InvokeHelper(0x1, DISPATCH_PROPERTYGET, VT_R4, (void*)&result, NULL); return result; } void CVcPlotBase::SetBaseHeight(float newValue) { static BYTE parms[] = VTS_R4; InvokeHelper(0x1, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, newValue); } CVcBrush CVcPlotBase::GetBrush() { LPDISPATCH pDispatch; InvokeHelper(0x2, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&pDispatch, NULL); return CVcBrush(pDispatch); } CVcPen CVcPlotBase::GetPen() { LPDISPATCH pDispatch; InvokeHelper(0x3, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&pDispatch, NULL); return CVcPen(pDispatch); }
24.918367
82
0.660934
GalacticSoft
07fda40a6914f30179570bb04f38921be010988b
657
cpp
C++
legacy/src/physics/collider.cpp
benkyd/Minecraft
ae8b69b96dcecd669f90aa2c7bb675e5f9b37615
[ "MIT" ]
19
2020-07-18T18:52:39.000Z
2022-02-27T19:42:06.000Z
legacy/src/physics/collider.cpp
benkyd/Minecraft
ae8b69b96dcecd669f90aa2c7bb675e5f9b37615
[ "MIT" ]
null
null
null
legacy/src/physics/collider.cpp
benkyd/Minecraft
ae8b69b96dcecd669f90aa2c7bb675e5f9b37615
[ "MIT" ]
4
2021-03-27T18:36:13.000Z
2022-03-26T18:59:09.000Z
#include "collider.hpp" EntityCollider::EntityCollider() { } glm::vec3 EntityCollider::TerrainCollide(std::vector<uint8_t> terrain) { } bool EntityCollider::m_aabb(ColliderBox a, ColliderBox b) { return { (a.Min.x <= b.Min.x + b.Max.x && a.Min.x + a.Max.x >= b.Min.x) && (a.Min.y <= b.Min.y + b.Max.y && a.Min.y + a.Max.y >= b.Min.y) && (a.Min.z <= b.Min.z + b.Max.z && a.Min.z + a.Max.z >= b.Min.z) }; } float EntityCollider::m_xDepth(ColliderBox a, ColliderBox b) { } float EntityCollider::m_yDepth(ColliderBox a, ColliderBox b) { } float EntityCollider::m_zDepth(ColliderBox a, ColliderBox b) { }
18.25
74
0.61035
benkyd
07fe09fb73acf273510152e09b165d67f448ff55
4,527
cpp
C++
qtquick_items/IrregularCircleItem.cpp
luminosuslight/luminosus-core
b823c57524aea382b0734eb1a6343a1c95bb84f3
[ "MIT" ]
1
2021-09-25T19:09:56.000Z
2021-09-25T19:09:56.000Z
qtquick_items/IrregularCircleItem.cpp
luminosuslight/luminosus-core
b823c57524aea382b0734eb1a6343a1c95bb84f3
[ "MIT" ]
null
null
null
qtquick_items/IrregularCircleItem.cpp
luminosuslight/luminosus-core
b823c57524aea382b0734eb1a6343a1c95bb84f3
[ "MIT" ]
null
null
null
#include "IrregularCircleItem.h" #include <QSGNode> #include <QSGFlatColorMaterial> #include <QSGVertexColorMaterial> #include <QGuiApplication> #include <QScreen> #include <cmath> IrregularCircleItem::IrregularCircleItem(QQuickItem *parent) : QQuickItem(parent) , m_innerColor(Qt::red) , m_outerColor(Qt::blue) , m_devicePixelRatio(QGuiApplication::primaryScreen()->devicePixelRatio()) { setFlag(ItemHasContents, true); } IrregularCircleItem::~IrregularCircleItem() { } void IrregularCircleItem::setInnerColor(const QColor& color) { if (m_innerColor == color) return; m_innerColor = color; emit innerColorChanged(color); update(); } void IrregularCircleItem::setOuterColor(const QColor& color) { if (m_outerColor == color) return; m_outerColor = color; emit outerColorChanged(color); update(); } void IrregularCircleItem::setRadii(const QVector<double>& radii) { m_radii = radii; emit radiiChanged(); update(); } QSGNode* IrregularCircleItem::updatePaintNode(QSGNode* oldNode, UpdatePaintNodeData*) { if (!isVisible()) return oldNode; const int pointCount = m_radii.size(); if (pointCount < 3) return oldNode; // -------------------- Prepare QSG Nodes: QSGNode* parentNode = nullptr; if (oldNode) { parentNode = static_cast<QSGNode*>(oldNode); } else { parentNode = new QSGNode; } // adapt child count: int childCount = parentNode->childCount(); if (childCount != 1) { parentNode->removeAllChildNodes(); QSGGeometryNode* node = new QSGGeometryNode; QSGGeometry* geometry = new QSGGeometry(QSGGeometry::defaultAttributes_ColoredPoint2D(), 3); geometry->setDrawingMode(QSGGeometry::DrawTriangleFan); node->setGeometry(geometry); node->setFlag(QSGNode::OwnsGeometry); QSGVertexColorMaterial* material = new QSGVertexColorMaterial; node->setMaterial(material); node->setFlag(QSGNode::OwnsMaterial); parentNode->appendChildNode(node); } QSGGeometryNode* const qsgNode = static_cast<QSGGeometryNode*>(parentNode->childAtIndex(0)); if (!qsgNode) { qCritical() << "[IrregularCircle] Could not get QSG Node."; return nullptr; } QSGGeometry* const geometry = qsgNode->geometry(); if (!geometry) { qCritical() << "[IrregularCircle] Could not get QSG Geometry."; return nullptr; } const int interpolationFactor = 4; const int interpolatedRadiusCount = pointCount * interpolationFactor; const int verticesCount = interpolatedRadiusCount + 2; geometry->allocate(verticesCount); QSGGeometry::ColoredPoint2D* const vertices = geometry->vertexDataAsColoredPoint2D(); if (!vertices) { qCritical() << "[IrregularCircle] Could not get QSG vertices."; return nullptr; } const float itemWidth = float(width()); const float itemHeight = float(height()); const float itemRadius = itemWidth / 2.0f; // draw irregular circle like this: // start at center, then bottom, then anti-clockwise, then repeat first radius to close vertices[0].set(itemWidth / 2, itemHeight / 2, uchar(m_innerColor.red()), uchar(m_innerColor.green()), uchar(m_innerColor.blue()), uchar(m_innerColor.alpha())); const uchar r = uchar(m_outerColor.red() * m_outerColor.alphaF()); const uchar g = uchar(m_outerColor.green() * m_outerColor.alphaF()); const uchar b = uchar(m_outerColor.blue() * m_outerColor.alphaF()); const uchar a = uchar(m_outerColor.alpha()); for (int i = 0; i < pointCount; ++i) { for (int j = 0; j < interpolationFactor; ++j) { const float pos = float(j) / interpolationFactor; const float currentRadius = float((1-pos) * m_radii[i] + pos * m_radii[(i+1) % pointCount]); const int interpolatedRadiusIndex = i * interpolationFactor + j; const float angle = 2 * float(M_PI) * (float(interpolatedRadiusIndex) / interpolatedRadiusCount); const float x = currentRadius * itemRadius * std::sin(angle); const float y = currentRadius * itemRadius * std::cos(angle); vertices[1 + (i * interpolationFactor) + j].set(itemRadius + x, itemRadius + y, r, g, b, a); } } vertices[interpolatedRadiusCount + 1] = vertices[1]; // tell Scene Graph that this items needs to be drawn: qsgNode->markDirty(QSGNode::DirtyGeometry); return parentNode; }
34.557252
133
0.666446
luminosuslight
5800a6131a27023eead1edfcc8fd7c825bc88ff6
1,673
cpp
C++
misc/cpp/HandleThreadExceptions.cpp
ryanorz/code-camp
041eb6443a3f0963a7778d3ddfb03a7557257094
[ "Apache-2.0" ]
null
null
null
misc/cpp/HandleThreadExceptions.cpp
ryanorz/code-camp
041eb6443a3f0963a7778d3ddfb03a7557257094
[ "Apache-2.0" ]
null
null
null
misc/cpp/HandleThreadExceptions.cpp
ryanorz/code-camp
041eb6443a3f0963a7778d3ddfb03a7557257094
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <thread> #include <mutex> #include <condition_variable> #include <queue> #include <vector> #include <stdexcept> using namespace std; mutex g_lock_cout; mutex g_lock_queue; condition_variable g_queuecheck; queue<exception_ptr> g_exceptions; bool g_workerdone = false; void worker(int id) { try { std::this_thread::sleep_for(std::chrono::seconds(id)); throw runtime_error("something wrong, id = " + to_string(id)); } catch(...) { lock_guard<mutex> lock(g_lock_queue); g_exceptions.push(current_exception()); g_queuecheck.notify_one(); } } void logger() { while (!g_workerdone) { std::unique_lock<mutex> locker(g_lock_queue); g_queuecheck.wait(locker, [&]() { // 加入条件函数避免虚假唤醒 return !g_exceptions.empty() || g_workerdone; }); while (!g_exceptions.empty()) { try { auto ep = g_exceptions.front(); if (ep != nullptr) rethrow_exception(ep); } catch (const exception &e) { std::unique_lock<mutex> cout_locker(g_lock_cout); std::cout << "[logger] exception: " << e.what() << endl; } g_exceptions.pop(); } } } int main() { thread t_logger(logger); vector<thread> t_workers; for (int i = 0; i < 5; ++i) { t_workers.push_back(thread(worker, i)); } for (auto &t_worker : t_workers) t_worker.join(); { lock_guard<mutex> lock(g_lock_queue); g_workerdone = true; g_queuecheck.notify_one(); } t_logger.join(); return 0; }
24.602941
72
0.57621
ryanorz
58038d7c835eecdb7215a14860afb30d9feae668
468
cpp
C++
platforms/gfg/0407_minimum_difference_between_groups_of_size_two.cpp
idfumg/algorithms
06f85c5a1d07a965df44219b5a6bf0d43a129256
[ "MIT" ]
2
2020-09-17T09:04:00.000Z
2020-11-20T19:43:18.000Z
platforms/gfg/0407_minimum_difference_between_groups_of_size_two.cpp
idfumg/algorithms
06f85c5a1d07a965df44219b5a6bf0d43a129256
[ "MIT" ]
null
null
null
platforms/gfg/0407_minimum_difference_between_groups_of_size_two.cpp
idfumg/algorithms
06f85c5a1d07a965df44219b5a6bf0d43a129256
[ "MIT" ]
null
null
null
#include "../../template.hpp" int MinDiffBetweenGroupsOfSize2(vi arr) { int n = arr.size(), mini = INF, maxi = -INF; sort(arr); for (int i = 0, j = n - 1; i < j; ++i, --j) { maxi = max(maxi, arr[i] + arr[j]); mini = min(mini, arr[i] + arr[j]); } return maxi - mini; } int main() { TimeMeasure _; __x(); cout << MinDiffBetweenGroupsOfSize2({2,6,4,3}) << '\n'; cout << MinDiffBetweenGroupsOfSize2({11,4,3,5,7,1}) << '\n'; }
27.529412
64
0.532051
idfumg
580533c77032abf202b792f08b0473169aac9cac
1,346
cpp
C++
archsim/src/arch/risc-v/RiscVDecodeContext.cpp
tspink/GenSim
1c2c608d97ef8a90253b6f0567b43724ba553c6b
[ "MIT" ]
10
2020-07-14T22:09:30.000Z
2022-01-11T09:57:52.000Z
archsim/src/arch/risc-v/RiscVDecodeContext.cpp
tspink/GenSim
1c2c608d97ef8a90253b6f0567b43724ba553c6b
[ "MIT" ]
6
2020-07-09T12:01:57.000Z
2021-04-27T10:23:58.000Z
archsim/src/arch/risc-v/RiscVDecodeContext.cpp
tspink/GenSim
1c2c608d97ef8a90253b6f0567b43724ba553c6b
[ "MIT" ]
10
2020-07-29T17:05:26.000Z
2021-12-04T14:57:15.000Z
/* This file is Copyright University of Edinburgh 2018. For license details, see LICENSE. */ #include "gensim/gensim_decode_context.h" #include "arch/risc-v/RiscVDecodeContext.h" #include "util/ComponentManager.h" #include "core/thread/ThreadInstance.h" using namespace archsim::arch::riscv; uint32_t RiscVDecodeContext::DecodeSync(archsim::MemoryInterface &interface, Address address, uint32_t mode, gensim::BaseDecode *&target) { target = arch_.GetISA(mode).GetNewDecode(); return arch_.GetISA(mode).DecodeInstr(address, &interface, *target); } class RiscV32DecodeTranslationContext : public gensim::DecodeTranslateContext { void Translate(archsim::core::thread::ThreadInstance *cpu, const gensim::BaseDecode &insn, gensim::DecodeContext &decode, captive::shared::IRBuilder &builder) override { // nothing necessary here } }; class RiscV64DecodeTranslationContext : public gensim::DecodeTranslateContext { void Translate(archsim::core::thread::ThreadInstance *cpu, const gensim::BaseDecode &insn, gensim::DecodeContext &decode, captive::shared::IRBuilder &builder) override { // nothing necessary here } }; RegisterComponent(gensim::DecodeTranslateContext, RiscV32DecodeTranslationContext, "riscv32", "risc v 32"); RegisterComponent(gensim::DecodeTranslateContext, RiscV64DecodeTranslationContext, "riscv64", "risc v 64");
36.378378
168
0.788262
tspink
5805e3a575b2f2281c1ee3b32b4e3e9dbf8b5b3b
1,208
cpp
C++
src/ai/composite/contexts.cpp
blackberry/Wesnoth
8b307689158db568ecc6cc3b537e8d382ccea449
[ "Unlicense" ]
12
2015-03-04T15:07:00.000Z
2019-09-13T16:31:06.000Z
src/ai/composite/contexts.cpp
blackberry/Wesnoth
8b307689158db568ecc6cc3b537e8d382ccea449
[ "Unlicense" ]
null
null
null
src/ai/composite/contexts.cpp
blackberry/Wesnoth
8b307689158db568ecc6cc3b537e8d382ccea449
[ "Unlicense" ]
5
2017-04-22T08:16:48.000Z
2020-07-12T03:35:16.000Z
/* $Id: contexts.cpp 48153 2011-01-01 15:57:50Z mordante $ */ /* Copyright (C) 2009 - 2011 by Yurii Chernyi <terraninfo@terraninfo.net> Part of the Battle for Wesnoth Project http://www.wesnoth.org/ This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY. See the COPYING file for more details. */ /** * Helper functions for the object which operates in the context of AI for specific side * This is part of AI interface * @file */ #include "contexts.hpp" // ======================================================================= namespace ai { ai_context_proxy::ai_context_proxy() : target_() { } ai_context_proxy::~ai_context_proxy() { } rca_context::rca_context() { } rca_context::~rca_context() { } rca_context_proxy::rca_context_proxy() : target_() { } rca_context_proxy::~rca_context_proxy() { } } //end of namespace ai
20.474576
89
0.639901
blackberry
5806c40c787757626339588a6e7ac820babf956f
1,470
cpp
C++
code/aoce_vulkan_extra/layer/VkVisualEffectLayer.cpp
msqljj/aoce
b15320acbb9454fb461501c8cf0c598d1b15c495
[ "MIT" ]
71
2020-10-15T03:13:50.000Z
2022-03-30T02:04:28.000Z
code/aoce_vulkan_extra/layer/VkVisualEffectLayer.cpp
msqljj/aoce
b15320acbb9454fb461501c8cf0c598d1b15c495
[ "MIT" ]
9
2021-02-20T10:30:10.000Z
2022-03-04T07:59:58.000Z
code/aoce_vulkan_extra/layer/VkVisualEffectLayer.cpp
msqljj/aoce
b15320acbb9454fb461501c8cf0c598d1b15c495
[ "MIT" ]
19
2021-01-01T12:03:02.000Z
2022-03-21T07:59:59.000Z
#include "VkVisualEffectLayer.hpp" namespace aoce { namespace vulkan { namespace layer { VkPosterizeLayer::VkPosterizeLayer(/* args */) { glslPath = "glsl/posterize.comp.spv"; setUBOSize(sizeof(paramet), true); paramet = 10; updateUBO(&paramet); } VkPosterizeLayer::~VkPosterizeLayer() {} VkVignetteLayer::VkVignetteLayer(/* args */) { glslPath = "glsl/vignette.comp.spv"; setUBOSize(sizeof(paramet), true); updateUBO(&paramet); } VkVignetteLayer::~VkVignetteLayer() {} VkCGAColorspaceLayer::VkCGAColorspaceLayer(/* args */) { glslPath = "glsl/cgaColorspace.comp.spv"; } VkCGAColorspaceLayer::~VkCGAColorspaceLayer() {} bool VkCGAColorspaceLayer::getSampled(int inIndex) { if (inIndex == 0) { return true; } return false; } VkCrosshatchLayer::VkCrosshatchLayer(/* args */) { glslPath = "glsl/crosshatch.comp.spv"; setUBOSize(sizeof(paramet), true); updateUBO(&paramet); } VkCrosshatchLayer::~VkCrosshatchLayer() {} VkEmbossLayer::VkEmbossLayer(/* args */) { glslPath = "glsl/emboss.comp.spv"; setUBOSize(sizeof(paramet), true); paramet = 1.0f; updateUBO(&paramet); } VkEmbossLayer::~VkEmbossLayer() {} VkKuwaharaLayer::VkKuwaharaLayer(/* args */) { glslPath = "glsl/median.comp.spv"; setUBOSize(sizeof(paramet), true); paramet = 5; updateUBO(&paramet); } VkKuwaharaLayer::~VkKuwaharaLayer() {} } // namespace layer } // namespace vulkan } // namespace aoce
22.615385
56
0.682993
msqljj
580acac172ba189fac037a3a09a978185eed69ba
265
cpp
C++
Clase1/suma.cpp
diegostaPy/compuFiuna
e69acd09803f4dacd49d5c6cb1a3173a8fef9cbc
[ "MIT" ]
null
null
null
Clase1/suma.cpp
diegostaPy/compuFiuna
e69acd09803f4dacd49d5c6cb1a3173a8fef9cbc
[ "MIT" ]
null
null
null
Clase1/suma.cpp
diegostaPy/compuFiuna
e69acd09803f4dacd49d5c6cb1a3173a8fef9cbc
[ "MIT" ]
null
null
null
#include<iostream> using namespace std; int main() { int a,b,s; cout<<"Programa para sumar dos numeros introducidos por teclado"<<endl; cout<<"Ingrese el numero 1: "; cin>>a; cout<<"Ingrese el numero 2: "; cin>>b; s = a+b; cout<<"La suma es: "<<s<<endl; }
18.928571
72
0.641509
diegostaPy
580c66cb987903da8c6ca071e4efa2f688fcf6fd
1,076
hpp
C++
include/licon/optim/sgd.hpp
wzppengpeng/LittleConv
12aab4cfbbe965fa8b4053bb464db1165cc4ec31
[ "MIT" ]
93
2017-10-25T07:48:42.000Z
2022-02-02T15:18:11.000Z
include/licon/optim/sgd.hpp
wzppengpeng/LittleConv
12aab4cfbbe965fa8b4053bb464db1165cc4ec31
[ "MIT" ]
null
null
null
include/licon/optim/sgd.hpp
wzppengpeng/LittleConv
12aab4cfbbe965fa8b4053bb464db1165cc4ec31
[ "MIT" ]
20
2018-02-06T10:01:36.000Z
2019-07-07T09:26:40.000Z
#ifndef LICON_OPTIM_SGD_HPP_ #define LICON_OPTIM_SGD_HPP_ #include <unordered_map> #include "licon/optim/optim.hpp" #include "licon/utils/etensor.hpp" namespace licon { namespace optim { /** * the class of SGD optimizer */ class SGD : public Optimizer { public: // the creator of SGD optimizer static std::unique_ptr<Optimizer> CreateSGD(std::vector<std::pair<utils::ETensor<F>*, utils::ETensor<F>* > > register_weights, F lr, F momentum = 0.9, F weight_decay = 0, bool use_nesterov = false); void Step(); protected: void Update(utils::ETensor<F>& W, const utils::ETensor<F>& W_grad); private: SGD(std::vector<std::pair<utils::ETensor<F>*, utils::ETensor<F>* > > register_weights, F lr, F momentum = 0.9, F weight_decay = 0, bool use_nesterov = false); private: // the params of optimizer F m_momentum; F m_weight_decay; bool m_use_nesterov; // to save the previous grad std::unordered_map<utils::ETensor<F>*, utils::ETensor<F> > m_prev_grad; }; } //optim } //licon #endif /*LICON_OPTIM_SGD_HPP_*/
21.098039
130
0.681227
wzppengpeng
580f452b5cf4dbb802bbb91da0fff2925d3e8fcb
13,932
cpp
C++
tools/FakeAPI/ThostFtdcTraderApi.cpp
zhuzhenping/XAPI3
86b8a61a664bd3bc8bb0305fa73484d28ea8ed95
[ "BSD-2-Clause" ]
49
2020-10-15T03:01:54.000Z
2022-03-11T12:57:46.000Z
tools/FakeAPI/ThostFtdcTraderApi.cpp
zhuzhenping/XAPI3
86b8a61a664bd3bc8bb0305fa73484d28ea8ed95
[ "BSD-2-Clause" ]
5
2020-12-07T17:58:16.000Z
2021-10-01T09:31:51.000Z
tools/FakeAPI/ThostFtdcTraderApi.cpp
zhuzhenping/XAPI3
86b8a61a664bd3bc8bb0305fa73484d28ea8ed95
[ "BSD-2-Clause" ]
33
2020-10-13T13:14:37.000Z
2022-03-31T04:49:52.000Z
#include "stdafx.h" #define ISLIB #define LIB_TRADER_API_EXPORT #include <stdio.h> #include "../../include/CTP/ThostFtdcTraderApi.h" class MyClassCTP :public CThostFtdcTraderApi { public: ///创建TraderApi ///@param pszFlowPath 存贮订阅信息文件的目录,默认为当前目录 ///@return 创建出的UserApi static CThostFtdcTraderApi *CreateFtdcTraderApi(const char *pszFlowPath = ""); ///获取API的版本信息 ///@retrun 获取到的版本号 static const char *GetApiVersion() { return 0; } ///删除接口对象本身 ///@remark 不再使用本接口对象时,调用该函数删除接口对象 virtual void Release() {} ///初始化 ///@remark 初始化运行环境,只有调用后,接口才开始工作 virtual void Init() { m_pSpi->OnFrontConnected(); } ///等待接口线程结束运行 ///@return 线程退出代码 virtual int Join() { return 0; } ///获取当前交易日 ///@retrun 获取到的交易日 ///@remark 只有登录成功后,才能得到正确的交易日 virtual const char *GetTradingDay() { return 0; } ///注册前置机网络地址 ///@param pszFrontAddress:前置机网络地址。 ///@remark 网络地址的格式为:“protocol://ipaddress:port”,如:”tcp://127.0.0.1:17001”。 ///@remark “tcp”代表传输协议,“127.0.0.1”代表服务器地址。”17001”代表服务器端口号。 virtual void RegisterFront(char *pszFrontAddress) { char buf[512] = { 0 }; sprintf(buf, "RegisterFront\n\npszFrontAddress:%s\n已经复制到剪贴板", pszFrontAddress); ShowMessageBox(buf); } ///注册名字服务器网络地址 ///@param pszNsAddress:名字服务器网络地址。 ///@remark 网络地址的格式为:“protocol://ipaddress:port”,如:”tcp://127.0.0.1:12001”。 ///@remark “tcp”代表传输协议,“127.0.0.1”代表服务器地址。”12001”代表服务器端口号。 ///@remark RegisterNameServer优先于RegisterFront virtual void RegisterNameServer(char *pszNsAddress) {} ///注册名字服务器用户信息 ///@param pFensUserInfo:用户信息。 virtual void RegisterFensUserInfo(CThostFtdcFensUserInfoField * pFensUserInfo) {} ///注册回调接口 ///@param pSpi 派生自回调接口类的实例 virtual void RegisterSpi(CThostFtdcTraderSpi *pSpi) { m_pSpi = pSpi; } ///订阅私有流。 ///@param nResumeType 私有流重传方式 /// THOST_TERT_RESTART:从本交易日开始重传 /// THOST_TERT_RESUME:从上次收到的续传 /// THOST_TERT_QUICK:只传送登录后私有流的内容 ///@remark 该方法要在Init方法前调用。若不调用则不会收到私有流的数据。 virtual void SubscribePrivateTopic(THOST_TE_RESUME_TYPE nResumeType) {} ///订阅公共流。 ///@param nResumeType 公共流重传方式 /// THOST_TERT_RESTART:从本交易日开始重传 /// THOST_TERT_RESUME:从上次收到的续传 /// THOST_TERT_QUICK:只传送登录后公共流的内容 ///@remark 该方法要在Init方法前调用。若不调用则不会收到公共流的数据。 virtual void SubscribePublicTopic(THOST_TE_RESUME_TYPE nResumeType) {} ///客户端认证请求 virtual int ReqAuthenticate(CThostFtdcReqAuthenticateField *pReqAuthenticateField, int nRequestID) { char buf[512] = { 0 }; sprintf(buf, "ReqAuthenticate\n\nBrokerID:%s\nUserProductInfo:%s\nAuthCode:%s\n已经复制到剪贴板", pReqAuthenticateField->BrokerID, pReqAuthenticateField->UserProductInfo, pReqAuthenticateField->AuthCode); ShowMessageBox(buf); return 0; } ///用户登录请求 virtual int ReqUserLogin(CThostFtdcReqUserLoginField *pReqUserLoginField, int nRequestID) { char buf[512] = { 0 }; sprintf(buf, "ReqUserLogin\n\nBrokerID:%s\nUserID:%s\nPassword:%s\nUserProductInfo:%s\nInterfaceProductInfo:%s\nProtocolInfo:%s\n已经复制到剪贴板", pReqUserLoginField->BrokerID, pReqUserLoginField->UserID, pReqUserLoginField->Password, pReqUserLoginField->UserProductInfo, pReqUserLoginField->InterfaceProductInfo, pReqUserLoginField->ProtocolInfo); ShowMessageBox(buf); return 0; } ///登出请求 virtual int ReqUserLogout(CThostFtdcUserLogoutField *pUserLogout, int nRequestID) { return 0; } ///用户口令更新请求 virtual int ReqUserPasswordUpdate(CThostFtdcUserPasswordUpdateField *pUserPasswordUpdate, int nRequestID) { return 0; } ///资金账户口令更新请求 virtual int ReqTradingAccountPasswordUpdate(CThostFtdcTradingAccountPasswordUpdateField *pTradingAccountPasswordUpdate, int nRequestID) { return 0; } ///登录请求2 virtual int ReqUserLogin2(CThostFtdcReqUserLoginField *pReqUserLogin, int nRequestID) { char buf[512] = { 0 }; sprintf(buf, "ReqUserLogin2\n\nBrokerID:%s\nUserID:%s\nPassword:%s\nUserProductInfo:%s\nInterfaceProductInfo:%s\nProtocolInfo:%s\n已经复制到剪贴板", pReqUserLogin->BrokerID, pReqUserLogin->UserID, pReqUserLogin->Password, pReqUserLogin->UserProductInfo, pReqUserLogin->InterfaceProductInfo, pReqUserLogin->ProtocolInfo); ShowMessageBox(buf); return 0; } ///用户口令更新请求2 virtual int ReqUserPasswordUpdate2(CThostFtdcUserPasswordUpdateField *pUserPasswordUpdate, int nRequestID) { return 0; } ///报单录入请求 virtual int ReqOrderInsert(CThostFtdcInputOrderField *pInputOrder, int nRequestID) { return 0; } ///预埋单录入请求 virtual int ReqParkedOrderInsert(CThostFtdcParkedOrderField *pParkedOrder, int nRequestID) { return 0; } ///预埋撤单录入请求 virtual int ReqParkedOrderAction(CThostFtdcParkedOrderActionField *pParkedOrderAction, int nRequestID) { return 0; } ///报单操作请求 virtual int ReqOrderAction(CThostFtdcInputOrderActionField *pInputOrderAction, int nRequestID) { return 0; } ///查询最大报单数量请求 virtual int ReqQueryMaxOrderVolume(CThostFtdcQueryMaxOrderVolumeField *pQueryMaxOrderVolume, int nRequestID) { return 0; } ///投资者结算结果确认 virtual int ReqSettlementInfoConfirm(CThostFtdcSettlementInfoConfirmField *pSettlementInfoConfirm, int nRequestID) { return 0; } ///请求删除预埋单 virtual int ReqRemoveParkedOrder(CThostFtdcRemoveParkedOrderField *pRemoveParkedOrder, int nRequestID) { return 0; } ///请求删除预埋撤单 virtual int ReqRemoveParkedOrderAction(CThostFtdcRemoveParkedOrderActionField *pRemoveParkedOrderAction, int nRequestID) { return 0; } ///执行宣告录入请求 virtual int ReqExecOrderInsert(CThostFtdcInputExecOrderField *pInputExecOrder, int nRequestID) { return 0; } ///执行宣告操作请求 virtual int ReqExecOrderAction(CThostFtdcInputExecOrderActionField *pInputExecOrderAction, int nRequestID) { return 0; } ///询价录入请求 virtual int ReqForQuoteInsert(CThostFtdcInputForQuoteField *pInputForQuote, int nRequestID) { return 0; } ///报价录入请求 virtual int ReqQuoteInsert(CThostFtdcInputQuoteField *pInputQuote, int nRequestID) { return 0; } ///报价操作请求 virtual int ReqQuoteAction(CThostFtdcInputQuoteActionField *pInputQuoteAction, int nRequestID) { return 0; } ///批量报单操作请求 virtual int ReqBatchOrderAction(CThostFtdcInputBatchOrderActionField *pInputBatchOrderAction, int nRequestID) { return 0; } ///期权自对冲录入请求 virtual int ReqOptionSelfCloseInsert(CThostFtdcInputOptionSelfCloseField *pInputOptionSelfClose, int nRequestID) { return 0; } ///期权自对冲操作请求 virtual int ReqOptionSelfCloseAction(CThostFtdcInputOptionSelfCloseActionField *pInputOptionSelfCloseAction, int nRequestID) { return 0; } ///申请组合录入请求 virtual int ReqCombActionInsert(CThostFtdcInputCombActionField *pInputCombAction, int nRequestID) { return 0; } ///请求查询报单 virtual int ReqQryOrder(CThostFtdcQryOrderField *pQryOrder, int nRequestID) { return 0; } ///请求查询成交 virtual int ReqQryTrade(CThostFtdcQryTradeField *pQryTrade, int nRequestID) { return 0; } ///请求查询投资者持仓 virtual int ReqQryInvestorPosition(CThostFtdcQryInvestorPositionField *pQryInvestorPosition, int nRequestID) { return 0; } ///请求查询资金账户 virtual int ReqQryTradingAccount(CThostFtdcQryTradingAccountField *pQryTradingAccount, int nRequestID) { return 0; } ///请求查询投资者 virtual int ReqQryInvestor(CThostFtdcQryInvestorField *pQryInvestor, int nRequestID) { return 0; } ///请求查询交易编码 virtual int ReqQryTradingCode(CThostFtdcQryTradingCodeField *pQryTradingCode, int nRequestID) { return 0; } ///请求查询合约保证金率 virtual int ReqQryInstrumentMarginRate(CThostFtdcQryInstrumentMarginRateField *pQryInstrumentMarginRate, int nRequestID) { return 0; } ///请求查询合约手续费率 virtual int ReqQryInstrumentCommissionRate(CThostFtdcQryInstrumentCommissionRateField *pQryInstrumentCommissionRate, int nRequestID) { return 0; } ///请求查询交易所 virtual int ReqQryExchange(CThostFtdcQryExchangeField *pQryExchange, int nRequestID) { return 0; } ///请求查询产品 virtual int ReqQryProduct(CThostFtdcQryProductField *pQryProduct, int nRequestID) { return 0; } ///请求查询合约 virtual int ReqQryInstrument(CThostFtdcQryInstrumentField *pQryInstrument, int nRequestID) { return 0; } ///请求查询行情 virtual int ReqQryDepthMarketData(CThostFtdcQryDepthMarketDataField *pQryDepthMarketData, int nRequestID) { return 0; } ///请求查询投资者结算结果 virtual int ReqQrySettlementInfo(CThostFtdcQrySettlementInfoField *pQrySettlementInfo, int nRequestID) { return 0; } ///请求查询转帐银行 virtual int ReqQryTransferBank(CThostFtdcQryTransferBankField *pQryTransferBank, int nRequestID) { return 0; } ///请求查询投资者持仓明细 virtual int ReqQryInvestorPositionDetail(CThostFtdcQryInvestorPositionDetailField *pQryInvestorPositionDetail, int nRequestID) { return 0; } ///请求查询客户通知 virtual int ReqQryNotice(CThostFtdcQryNoticeField *pQryNotice, int nRequestID) { return 0; } ///请求查询结算信息确认 virtual int ReqQrySettlementInfoConfirm(CThostFtdcQrySettlementInfoConfirmField *pQrySettlementInfoConfirm, int nRequestID) { return 0; } ///请求查询投资者持仓明细 virtual int ReqQryInvestorPositionCombineDetail(CThostFtdcQryInvestorPositionCombineDetailField *pQryInvestorPositionCombineDetail, int nRequestID) { return 0; } ///请求查询保证金监管系统经纪公司资金账户密钥 virtual int ReqQryCFMMCTradingAccountKey(CThostFtdcQryCFMMCTradingAccountKeyField *pQryCFMMCTradingAccountKey, int nRequestID) { return 0; } ///请求查询仓单折抵信息 virtual int ReqQryEWarrantOffset(CThostFtdcQryEWarrantOffsetField *pQryEWarrantOffset, int nRequestID) { return 0; } ///请求查询投资者品种/跨品种保证金 virtual int ReqQryInvestorProductGroupMargin(CThostFtdcQryInvestorProductGroupMarginField *pQryInvestorProductGroupMargin, int nRequestID) { return 0; } ///请求查询交易所保证金率 virtual int ReqQryExchangeMarginRate(CThostFtdcQryExchangeMarginRateField *pQryExchangeMarginRate, int nRequestID) { return 0; } ///请求查询交易所调整保证金率 virtual int ReqQryExchangeMarginRateAdjust(CThostFtdcQryExchangeMarginRateAdjustField *pQryExchangeMarginRateAdjust, int nRequestID) { return 0; } ///请求查询汇率 virtual int ReqQryExchangeRate(CThostFtdcQryExchangeRateField *pQryExchangeRate, int nRequestID) { return 0; } ///请求查询二级代理操作员银期权限 virtual int ReqQrySecAgentACIDMap(CThostFtdcQrySecAgentACIDMapField *pQrySecAgentACIDMap, int nRequestID) { return 0; } ///请求查询产品报价汇率 virtual int ReqQryProductExchRate(CThostFtdcQryProductExchRateField *pQryProductExchRate, int nRequestID) { return 0; } ///请求查询产品组 virtual int ReqQryProductGroup(CThostFtdcQryProductGroupField *pQryProductGroup, int nRequestID) { return 0; } ///请求查询做市商合约手续费率 virtual int ReqQryMMInstrumentCommissionRate(CThostFtdcQryMMInstrumentCommissionRateField *pQryMMInstrumentCommissionRate, int nRequestID) { return 0; } ///请求查询做市商期权合约手续费 virtual int ReqQryMMOptionInstrCommRate(CThostFtdcQryMMOptionInstrCommRateField *pQryMMOptionInstrCommRate, int nRequestID) { return 0; } ///请求查询报单手续费 virtual int ReqQryInstrumentOrderCommRate(CThostFtdcQryInstrumentOrderCommRateField *pQryInstrumentOrderCommRate, int nRequestID) { return 0; } ///请求查询资金账户 virtual int ReqQrySecAgentTradingAccount(CThostFtdcQryTradingAccountField *pQryTradingAccount, int nRequestID) { return 0; } ///请求查询二级代理商资金校验模式 virtual int ReqQrySecAgentCheckMode(CThostFtdcQrySecAgentCheckModeField *pQrySecAgentCheckMode, int nRequestID) { return 0; } ///请求查询期权交易成本 virtual int ReqQryOptionInstrTradeCost(CThostFtdcQryOptionInstrTradeCostField *pQryOptionInstrTradeCost, int nRequestID) { return 0; } ///请求查询期权合约手续费 virtual int ReqQryOptionInstrCommRate(CThostFtdcQryOptionInstrCommRateField *pQryOptionInstrCommRate, int nRequestID) { return 0; } ///请求查询执行宣告 virtual int ReqQryExecOrder(CThostFtdcQryExecOrderField *pQryExecOrder, int nRequestID) { return 0; } ///请求查询询价 virtual int ReqQryForQuote(CThostFtdcQryForQuoteField *pQryForQuote, int nRequestID) { return 0; } ///请求查询报价 virtual int ReqQryQuote(CThostFtdcQryQuoteField *pQryQuote, int nRequestID) { return 0; } ///请求查询期权自对冲 virtual int ReqQryOptionSelfClose(CThostFtdcQryOptionSelfCloseField *pQryOptionSelfClose, int nRequestID) { return 0; } ///请求查询投资单元 virtual int ReqQryInvestUnit(CThostFtdcQryInvestUnitField *pQryInvestUnit, int nRequestID) { return 0; } ///请求查询组合合约安全系数 virtual int ReqQryCombInstrumentGuard(CThostFtdcQryCombInstrumentGuardField *pQryCombInstrumentGuard, int nRequestID) { return 0; } ///请求查询申请组合 virtual int ReqQryCombAction(CThostFtdcQryCombActionField *pQryCombAction, int nRequestID) { return 0; } ///请求查询转帐流水 virtual int ReqQryTransferSerial(CThostFtdcQryTransferSerialField *pQryTransferSerial, int nRequestID) { return 0; } ///请求查询银期签约关系 virtual int ReqQryAccountregister(CThostFtdcQryAccountregisterField *pQryAccountregister, int nRequestID) { return 0; } ///请求查询签约银行 virtual int ReqQryContractBank(CThostFtdcQryContractBankField *pQryContractBank, int nRequestID) { return 0; } ///请求查询预埋单 virtual int ReqQryParkedOrder(CThostFtdcQryParkedOrderField *pQryParkedOrder, int nRequestID) { return 0; } ///请求查询预埋撤单 virtual int ReqQryParkedOrderAction(CThostFtdcQryParkedOrderActionField *pQryParkedOrderAction, int nRequestID) { return 0; } ///请求查询交易通知 virtual int ReqQryTradingNotice(CThostFtdcQryTradingNoticeField *pQryTradingNotice, int nRequestID) { return 0; } ///请求查询经纪公司交易参数 virtual int ReqQryBrokerTradingParams(CThostFtdcQryBrokerTradingParamsField *pQryBrokerTradingParams, int nRequestID) { return 0; } ///请求查询经纪公司交易算法 virtual int ReqQryBrokerTradingAlgos(CThostFtdcQryBrokerTradingAlgosField *pQryBrokerTradingAlgos, int nRequestID) { return 0; } ///请求查询监控中心用户令牌 virtual int ReqQueryCFMMCTradingAccountToken(CThostFtdcQueryCFMMCTradingAccountTokenField *pQueryCFMMCTradingAccountToken, int nRequestID) { return 0; } ///期货发起银行资金转期货请求 virtual int ReqFromBankToFutureByFuture(CThostFtdcReqTransferField *pReqTransfer, int nRequestID) { return 0; } ///期货发起期货资金转银行请求 virtual int ReqFromFutureToBankByFuture(CThostFtdcReqTransferField *pReqTransfer, int nRequestID) { return 0; } ///期货发起查询银行余额请求 virtual int ReqQueryBankAccountMoneyByFuture(CThostFtdcReqQueryAccountField *pReqQueryAccount, int nRequestID) { return 0; } private: CThostFtdcTraderSpi *m_pSpi; }; CThostFtdcTraderApi *CThostFtdcTraderApi::CreateFtdcTraderApi(const char *pszFlowPath) { return new MyClassCTP(); }
37.961853
162
0.799742
zhuzhenping
580f9ce7d6e2cb4ef71f548df011e4608e401d6d
9,975
cpp
C++
src/optim/nelder_mead_module.cpp
bigginlab/chap
17de36442e2e80cb01432e84050c4dfce31fc3a2
[ "MIT" ]
10
2018-06-28T00:21:46.000Z
2022-03-30T03:31:32.000Z
src/optim/nelder_mead_module.cpp
bigginlab/chap
17de36442e2e80cb01432e84050c4dfce31fc3a2
[ "MIT" ]
35
2019-03-19T21:54:46.000Z
2022-03-17T02:20:42.000Z
src/optim/nelder_mead_module.cpp
bigginlab/chap
17de36442e2e80cb01432e84050c4dfce31fc3a2
[ "MIT" ]
8
2018-10-27T19:35:13.000Z
2022-01-06T01:10:39.000Z
// CHAP - The Channel Annotation Package // // Copyright (c) 2016 - 2018 Gianni Klesse, Shanlin Rao, Mark S. P. Sansom, and // Stephen J. Tucker // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #include <algorithm> #include "optim/nelder_mead_module.hpp" /*! * Constructor. Creates a NelderMeadModule object, but does not set any of its * properties. */ NelderMeadModule::NelderMeadModule() { } /*! * Destructor. */ NelderMeadModule::~NelderMeadModule() { } /*! * \brief Setter function for parameters. * * Takes a standard map as input, from which it tries to extract the parameters * required by the Nelder-Mead algorithm. Parameters are specified by using * their name (as a string) as map key and their value as map value. * Unrecognised entries will be ignored and an error will be thrown if required * parameters without default are missing. Available options are: * * - nmMaxIter: the maximum number of iterations to perform (required) * - nmInitShift: shift of initial vertex coordinates with respect to guess point (required) * - nmContractionPar: factor used in contraction step (defaults to 0.5) * - nmExpansionPar: factor used in expansion step (defaults to 2.0) * - nmReflectionPar: factor used in reflection step (defaults to 1.0) * - nmShrinkagePar: factor used in shrinkage step (defaults to 0.5) */ void NelderMeadModule::setParams(std::map<std::string, real> params) { // number of iterations: if( params.find("nmMaxIter") != params.end() ) { maxIter_ = params["nmMaxIter"]; } else { std::cerr<<"ERROR: Maximum number of Nelder-Mead iterations not specified!"<<std::endl; std::abort(); } // shift factor: if( params.find("nmInitShift") != params.end() ) { initShiftFac_ = params["nmInitShift"]; } else { std::cerr<<"ERROR: Shift factor for initial vertex generation not specified!"<<std::endl; std::abort(); } // contraction parameter: if( params.find("nmContractionPar") != params.end() ) { contractionPar_ = params["nmContractionPar"]; } else { contractionPar_ = 0.5; } // expansion parameter: if( params.find("nmExpansionPar") != params.end() ) { expansionPar_ = params["nmExpansionPar"]; } else { expansionPar_ = 2.0; } // reflection parameter: if( params.find("nmReflectionPar") != params.end() ) { reflectionPar_ = params["nmReflectionPar"]; } else { reflectionPar_ = 1.0; } // reflection parameter: if( params.find("nmShrinkagePar") != params.end() ) { shrinkagePar_ = params["nmShrinkagePar"]; } else { shrinkagePar_ = 0.5; } } /*! * Sets the objective function to be maximised. An objective function takes a * vector of reals as its only argument and returns a single real. */ void NelderMeadModule::setObjFun(ObjectiveFunction objFun) { this -> objFun_ = objFun; } /*! * Creates the initial simplex from one guess point. The first vertex of the * initial simplex will simply be the guess point itself. All other vertices * are calculated by perturbing one coordinate of the guess vector, i.e. * * \f[ * \mathbf{x}_i = \mathbf{x}_1 + h\mathbf{e}_i * \f] * * where \f$\mathbf{e}_i\f$ is the \f$i\f$-th unit vector and \f$h\f$ is a * small shift that can be set as a parameter. The objective function is not * evaluated at any vertex. */ void NelderMeadModule::setInitGuess(std::vector<real> guess) { // add guess point to simplex: OptimSpacePoint guessPoint; guessPoint.first = guess; simplex_.push_back(guessPoint); // add additional vertices to create a simplex of proper dimensionality: for(size_t i = 0; i < guess.size(); i++) { // copy guess point and perturb j-th component: OptimSpacePoint vertex = guessPoint; vertex.first[i] += 1.0*initShiftFac_; // add vertex to simplex: simplex_.push_back(vertex); } } /*! * Performs the Nelder-Mead optimisation loop. Should only be called once * parameters, objective function, and initial point have been set. */ void NelderMeadModule::optimise() { // sanity checks: if( simplex_.size() != simplex_.back().first.size() + 1 ) { std::cerr<<"ERROR: Incorrect number of simplex vertices!"<<std::endl; std::cerr<<"Did you call setInitGuess()?"<<std::endl; std::abort(); } // initialise centroid as vector of all zeros: centroid_.first.insert(centroid_.first.begin(), simplex_.front().first.size(), 0.0); // evaluate objective function at all vertices: std::vector<OptimSpacePoint>::iterator vert; for(vert = simplex_.begin(); vert != simplex_.end(); vert++) { vert -> second = objFun_(vert -> first); } // Nelder-Mead main loop: for(int i = 0; i < maxIter_; i++) { // sort vertices by function values: std::sort(simplex_.begin(), simplex_.end(), CompOptimSpacePoints()); // recalculate centroid: calcCentroid(); // calculate the reflected point: OptimSpacePoint reflectedPoint = centroid_; reflectedPoint.scale(1.0 + reflectionPar_); reflectedPoint.addScaled(simplex_.front(), -reflectionPar_); // evaluate objective function at reflected point: reflectedPoint.second = objFun_(reflectedPoint.first); // reflected point better than second worst? if( comparison_(simplex_[1], reflectedPoint) ) { // reflected point better than best? if( comparison_(simplex_.back(), reflectedPoint) ) { // calculate expansion point: OptimSpacePoint expandedPoint = centroid_; expandedPoint.scale(1.0 - expansionPar_); expandedPoint.addScaled(reflectedPoint, expansionPar_); // evaluate objective function at expansion point: expandedPoint.second = objFun_(expandedPoint.first); // expanded point better than reflected point: if( expandedPoint.second < reflectedPoint.second ) { // accept expanded point: simplex_.front() = expandedPoint; } else { // accept reflected point: simplex_.front() = reflectedPoint; } } else { // accept reflected point: simplex_.front() = reflectedPoint; } } else { // calculate contraction point: OptimSpacePoint contractedPoint = centroid_; contractedPoint.scale(1.0 - contractionPar_); contractedPoint.addScaled(simplex_.front(), contractionPar_); // evaluate objective function at contracted point: contractedPoint.second = objFun_(contractedPoint.first); // contracted point better than worst? if( comparison_(simplex_.front(), contractedPoint) ) { // accept contracted point: simplex_.front() = contractedPoint; } else { // update all but the best vertex: std::vector<OptimSpacePoint>::iterator it; for(it = simplex_.begin(); it != simplex_.end() - 1; it++) { // calculate shrinkage point: it -> scale(shrinkagePar_); it -> addScaled(simplex_.back(), 1.0 - shrinkagePar_); // evaluate objective function at new vertex: it -> second = objFun_(it -> first); } } } // ensure vertices are sorted: std::sort(simplex_.begin(), simplex_.end(), CompOptimSpacePoints()); } } /*! * Returns the best point in optimisation space. Only meaningful if called * after optimise(). */ OptimSpacePoint NelderMeadModule::getOptimPoint() { return simplex_.back(); } /*! * Calculates the centroid of all except the first vertex of the simplex. This * is usually the worst vertex. */ void NelderMeadModule::calcCentroid() { // reset centroid to vector of all zeros: std::fill(centroid_.first.begin(), centroid_.first.end(), 0.0); // loop over vertices and add to centroid_: std::vector<OptimSpacePoint>::iterator it; for(it = simplex_.begin() + 1; it != simplex_.end(); it++) { centroid_.add(*it); } // scale all elements by number: real fac = 1.0/(simplex_.size() - 1); centroid_.scale(fac); }
30.504587
97
0.613534
bigginlab
58107e4f921de95082e14fcb6e78d8c628d6a427
3,519
cpp
C++
Runtime/World/CMarkerGrid.cpp
RetroView/RetroCommon
a413a010b50a53ebc6b0c726203181fc179d3370
[ "MIT" ]
106
2021-04-09T19:42:56.000Z
2022-03-30T09:13:28.000Z
Runtime/World/CMarkerGrid.cpp
Austint30/metaforce
a491e2e9f229c8db92544b275cd1baa80bacfd17
[ "MIT" ]
58
2021-04-09T12:48:58.000Z
2022-03-22T00:11:42.000Z
Runtime/World/CMarkerGrid.cpp
Austint30/metaforce
a491e2e9f229c8db92544b275cd1baa80bacfd17
[ "MIT" ]
13
2021-04-06T23:23:20.000Z
2022-03-16T02:09:48.000Z
#include "Runtime/World/CMarkerGrid.hpp" namespace metaforce { CMarkerGrid::CMarkerGrid(const zeus::CAABox& bounds) : x0_bounds(bounds) { x18_gridUnits = zeus::CVector3f((bounds.max - bounds.min) * 0.0625f); x24_gridState.resize(0x400); } void CMarkerGrid::MarkCells(const zeus::CSphere& area, u32 val) { int width_units = static_cast<int>((area.radius - x18_gridUnits.x()) / x18_gridUnits.x()); int length_units = static_cast<int>((area.radius - x18_gridUnits.y()) / x18_gridUnits.y()); int height_units = static_cast<int>((area.radius - x18_gridUnits.z()) / x18_gridUnits.z()); u32 x_coord, y_coord, z_coord; if (!GetCoords(area.position, x_coord, y_coord, z_coord)) { return; } for (int i = width_units - z_coord; i < (z_coord + width_units); i++) { for (int j = length_units - y_coord; j < (y_coord + length_units); j++) { for (int k = height_units - x_coord; k < (z_coord + height_units); k++) { u32 new_cell_val = val | GetValue(x_coord, y_coord, z_coord); SetValue(k, j, i, new_cell_val); } } } } bool CMarkerGrid::GetCoords(zeus::CVector3f const& vec, u32& x, u32& y, u32& z) const { if (x0_bounds.pointInside(vec)) { x = static_cast<u32>((vec.x() - x0_bounds.min.x()) / x18_gridUnits.x()); y = static_cast<u32>((vec.y() - x0_bounds.min.y()) / x18_gridUnits.y()); z = static_cast<u32>((vec.z() - x0_bounds.min.z()) / x18_gridUnits.z()); return true; } return false; } u32 CMarkerGrid::GetValue(u32 x, u32 y, u32 z) const { const u32 bit_offset = (x & 3) << 1; u8 marker_byte = x24_gridState[(z << 6) + (y << 2) + (x >> 2)]; return static_cast<u32>((marker_byte & (3 << bit_offset)) >> bit_offset); } void CMarkerGrid::SetValue(u32 x, u32 y, u32 z, u32 val) { const u32 bit_offset = (x & 3) << 1; const u32 grid_offset = (z << 6) + (y << 2) + (x >> 2); u8 marker_byte = x24_gridState[grid_offset]; marker_byte |= (marker_byte & ~(3 << bit_offset)) | (val << bit_offset); x24_gridState[grid_offset] = marker_byte; } bool CMarkerGrid::AABoxTouchesData(const zeus::CAABox& box, u32 val) const { if (!x0_bounds.intersects(box)) { return false; } zeus::CAABox in_box = box; if (!box.inside(x0_bounds)) { zeus::CVector3f max_of_min(x0_bounds.min.x() > box.min.x() ? x0_bounds.min.x() : box.min.x(), x0_bounds.min.y() > box.min.y() ? x0_bounds.min.y() : box.min.y(), x0_bounds.min.z() > box.min.z() ? x0_bounds.min.z() : box.min.z()); zeus::CVector3f min_of_max(x0_bounds.max.x() < box.max.x() ? x0_bounds.max.x() : box.max.x(), x0_bounds.max.y() < box.max.y() ? x0_bounds.max.y() : box.max.y(), x0_bounds.max.z() < box.max.z() ? x0_bounds.max.z() : box.max.z()); in_box = zeus::CAABox(max_of_min, min_of_max); } u32 c1x, c1y, c1z, c2x, c2y, c2z; GetCoords(in_box.min, c1x, c1y, c1z); GetCoords(in_box.max, c2x, c2y, c2z); for (int i = c1z; i < c2z; i++) { for (int j = c1y; j < c2y; j++) { for (int k = c1x; k < c2x; k++) { if ((GetValue(k, j, i) & val) != 0u) { return true; } } } } return false; } zeus::CVector3f CMarkerGrid::GetWorldPositionForCell(u32 x, u32 y, u32 z) const { // returns the center of a given cell return zeus::CVector3f(static_cast<float>(x), static_cast<float>(y), static_cast<float>(z)) * x18_gridUnits + x0_bounds.min + (x18_gridUnits / 2.f); } } // namespace urde
40.448276
111
0.608411
RetroView
58168a80cfb9a97c1621a0ed52f2c5daa219039b
3,797
cpp
C++
src/level_set/RelaxationLSBcCoefs.cpp
hongk45/IBAMR
698d419fc6688470a8b9400822ba893da9d07ae2
[ "BSD-3-Clause" ]
null
null
null
src/level_set/RelaxationLSBcCoefs.cpp
hongk45/IBAMR
698d419fc6688470a8b9400822ba893da9d07ae2
[ "BSD-3-Clause" ]
1
2020-11-30T14:22:45.000Z
2020-12-01T21:28:24.000Z
src/level_set/RelaxationLSBcCoefs.cpp
hongk45/IBAMR
698d419fc6688470a8b9400822ba893da9d07ae2
[ "BSD-3-Clause" ]
null
null
null
// --------------------------------------------------------------------- // // Copyright (c) 2018 - 2019 by the IBAMR developers // All rights reserved. // // This file is part of IBAMR. // // IBAMR is free software and is distributed under the 3-clause BSD // license. The full text of the license can be found in the file // COPYRIGHT at the top level directory of IBAMR. // // --------------------------------------------------------------------- /////////////////////////////// INCLUDES ///////////////////////////////////// #include "ibamr/RelaxationLSBcCoefs.h" #include "ibtk/namespaces.h" // IWYU pragma: keep #include "ArrayData.h" #include "BoundaryBox.h" #include "Box.h" #include "CellData.h" #include "Index.h" #include "IntVector.h" #include "Patch.h" #include "tbox/Pointer.h" #include <utility> /////////////////////////////// NAMESPACE //////////////////////////////////// namespace IBAMR { /////////////////////////////// STATIC /////////////////////////////////////// /////////////////////////////// PUBLIC /////////////////////////////////////// RelaxationLSBcCoefs::RelaxationLSBcCoefs(std::string object_name) : d_object_name(std::move(object_name)) { // intentionally blank return; } // RelaxationLSBcCoefs void RelaxationLSBcCoefs::setLSPatchDataIndex(int phi_idx) { #if !defined(NDEBUG) TBOX_ASSERT(phi_idx >= 0); #endif d_phi_idx = phi_idx; return; } // setLSPatchDataIndex void RelaxationLSBcCoefs::resetLSPatchDataIndex() { d_phi_idx = -1; return; } // resetLSPatchDataIndex void RelaxationLSBcCoefs::setBcCoefs(Pointer<ArrayData<NDIM, double> >& acoef_data, Pointer<ArrayData<NDIM, double> >& bcoef_data, Pointer<ArrayData<NDIM, double> >& gcoef_data, const Pointer<Variable<NDIM> >& /*variable*/, const Patch<NDIM>& patch, const BoundaryBox<NDIM>& bdry_box, double /*fill_time*/) const { Pointer<CellData<NDIM, double> > phi_data = patch.getPatchData(d_phi_idx); const int location_index = bdry_box.getLocationIndex(); const int axis = location_index / 2; const bool is_upper = (location_index % 2 == 1); #if !defined(NDEBUG) TBOX_ASSERT(!acoef_data.isNull()); #endif const Box<NDIM>& bc_coef_box = acoef_data->getBox(); #if !defined(NDEBUG) TBOX_ASSERT(bcoef_data.isNull() || bc_coef_box == bcoef_data->getBox()); TBOX_ASSERT(gcoef_data.isNull() || bc_coef_box == gcoef_data->getBox()); #endif for (Box<NDIM>::Iterator bc(bc_coef_box); bc; bc++) { const hier::Index<NDIM>& i = bc(); hier::Index<NDIM> i_bdry = bc(); hier::Index<NDIM> i_intr = bc(); if (is_upper) { i_bdry(axis) -= 1; i_intr(axis) -= 2; } else { i_intr(axis) += 1; } double dummy; double& a = (!acoef_data.isNull() ? (*acoef_data)(i, 0) : dummy); double& b = (!bcoef_data.isNull() ? (*bcoef_data)(i, 0) : dummy); double& g = (!gcoef_data.isNull() ? (*gcoef_data)(i, 0) : dummy); a = 1.0; b = 0.0; g = 1.5 * (*phi_data)(i_bdry, 0) - 0.5 * (*phi_data)(i_intr, 0); } return; } // setBcCoefs IntVector<NDIM> RelaxationLSBcCoefs::numberOfExtensionsFillable() const { return 128; } // numberOfExtensionsFillable /////////////////////////////// PROTECTED //////////////////////////////////// /////////////////////////////// PRIVATE ////////////////////////////////////// /////////////////////////////// NAMESPACE //////////////////////////////////// } // namespace IBAMR //////////////////////////////////////////////////////////////////////////////
30.134921
105
0.500395
hongk45
58176bfc644c891e4def00e990d5160cf6c3f86f
121,077
cpp
C++
net/unimodem/src/tsp/cdev.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
net/unimodem/src/tsp/cdev.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
net/unimodem/src/tsp/cdev.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
// Copyright (c) 1996-1997 Microsoft Corporation. // // // Component // // Unimodem 5.0 TSP (Win32, user mode DLL) // // File // // CDEV.CPP // Implements class CTspDev // // History // // 11/16/1996 JosephJ Created // // #include "tsppch.h" #include "tspcomm.h" //#include <umdmmini.h> #include "cmini.h" #include "cdev.h" #include "diag.h" #include "rcids.h" #include "globals.h" #include <Memory.h> FL_DECLARE_FILE(0x986d98ed, "Implements class CTspDev") TCHAR cszFriendlyName[] = TEXT("FriendlyName"); TCHAR cszDeviceType[] = TEXT("DeviceType"); TCHAR cszID[] = TEXT("ID"); TCHAR cszProperties[] = TEXT("Properties"); TCHAR cszSettings[] = TEXT("Settings"); TCHAR cszDialSuffix[] = TEXT("DialSuffix"); TCHAR cszVoiceProfile[] = TEXT("VoiceProfile"); // 2/26/1997 JosephJ Many other registry keys related to forwarding, distinctive // ringing and mixer were here in unimodem/v but I have not // migrated them. // 2/28/1997 JosephJ // The following are new for NT5.0. These contain the wave device ID // for record and play. As of 2/28/1997, we haven't addressed how these // get in the registry -- basically this is a hack. // const TCHAR cszWaveInstance[] = TEXT("WaveInstance"); const TCHAR cszWaveDriver[] = TEXT("WaveDriver"); // // The list of classes supported by unimodem // // // 3/29/98 JosephJ following set of static class lists is not elegant, // but works. // const TCHAR g_szzLineNoVoiceClassList[] = { TEXT("tapi/line\0") TEXT("comm\0") TEXT("comm/datamodem\0") TEXT("comm/datamodem/portname\0") TEXT("comm/datamodem/dialin\0") TEXT("comm/datamodem/dialout\0") TEXT("comm/extendedcaps\0") TEXT("tapi/line/diagnostics\0") }; const TCHAR g_szzLineWithWaveClassList[] = { TEXT("tapi/line\0") TEXT("comm\0") TEXT("comm/datamodem\0") TEXT("comm/datamodem/portname\0") TEXT("comm/datamodem/dialin\0") TEXT("comm/datamodem/dialout\0") TEXT("comm/extendedcaps\0") TEXT("wave/in\0") TEXT("wave/out\0") TEXT("tapi/line/diagnostics\0") }; const TCHAR g_szzLineWithWaveAndPhoneClassList[] = { TEXT("tapi/line\0") TEXT("comm\0") TEXT("comm/datamodem\0") TEXT("comm/datamodem/portname\0") TEXT("comm/datamodem/dialin\0") TEXT("comm/datamodem/dialout\0") TEXT("comm/extendedcaps\0") TEXT("wave/in\0") TEXT("wave/out\0") TEXT("tapi/phone\0") TEXT("tapi/line/diagnostics\0") }; const TCHAR g_szzPhoneWithAudioClassList[] = { TEXT("tapi/line\0") TEXT("wave/in\0") TEXT("wave/out\0") TEXT("tapi/phone\0") }; const TCHAR g_szzPhoneWithoutAudioClassList[] = { TEXT("tapi/line\0") TEXT("tapi/phone\0") }; const TCHAR g_szComm[] = TEXT("comm"); const TCHAR g_szCommDatamodem[] = TEXT("comm/datamodem"); // const TCHAR g_szDiagnosticsCall[] DWORD get_volatile_key_value(HKEY hkParent); char * ConstructNewPreDialCommands( HKEY hKey, DWORD dwNewProtoOpt, CStackLog *psl ); // // Will try to construct a multisz string containing the commands associated // with the specified protocol. // Returns NULL on error. // // The command is in RAW form -- i.e, // with CR and LF present in their raw form, not template ("<cr>") // form. // // // CTspDev::CTspDev(void) : m_sync(), m_pLine(NULL) { ZeroMemory(&m_Line, sizeof(m_Line)); ZeroMemory(&m_Phone, sizeof(m_Phone)); ZeroMemory(&m_LLDev, sizeof(m_LLDev)); m_StaticInfo.pMD=NULL; m_StaticInfo.hSessionMD=0; } CTspDev::~CTspDev() { ASSERT(m_StaticInfo.pMD==NULL); ASSERT(m_StaticInfo.hSessionMD==0); } TSPRETURN CTspDev::AcceptTspCall( BOOL fFromExtension, DWORD dwRoutingInfo, void *pvParams, LONG *plRet, CStackLog *psl ) { FL_DECLARE_FUNC(0x86571252, "CTspDev::AcceptTspCall") TSPRETURN tspRet= 0; FL_LOG_ENTRY(psl); *plRet = LINEERR_OPERATIONUNAVAIL; // Default (not handled) is failure. m_sync.EnterCrit(dwLUID_CurrentLoc); if (!m_sync.IsLoaded()) { // Not in a position to handle this call now! *plRet = LINEERR_OPERATIONFAILED; goto end; } // // // if (!fFromExtension && m_StaticInfo.pMD->ExtIsEnabled()) { // 4/30/1997 JosephJ We must leave the critical section because // the extension DLL can call back, wherepon we will enter // the critical section a 2nd time, and later if we try // to leave the critical section (specifically while waiting // for synchronous completion of lineDrop) we will // actually not have truly released it and hence the async // completion from the minidriver (typically in a different // thread's context) will block at our critical section. // Simple way to hit this is to do a lineCloseCall with a call // still active. m_sync.LeaveCrit(dwLUID_CurrentLoc); *plRet = m_StaticInfo.pMD->ExtAcceptTspCall( m_StaticInfo.hExtBinding, this, dwRoutingInfo, pvParams ); m_sync.EnterCrit(dwLUID_CurrentLoc); goto end; } // Set stacklog that will be in effect while we hold our critical // section. // if (m_pLLDev && m_pLLDev->IsLoggingEnabled()) { char rgchName[128]; rgchName[0] = 0; UINT cbBuf = DumpTSPIRECA( 0, // Instance (unused) dwRoutingInfo, pvParams, 0, // dwFlags rgchName, sizeof(rgchName)/sizeof(*rgchName), NULL, 0 ); if (*rgchName) { m_StaticInfo.pMD->LogStringA( m_pLLDev->hModemHandle, LOG_FLAG_PREFIX_TIMESTAMP, rgchName, psl ); } } switch(ROUT_TASKDEST(dwRoutingInfo)) { case TASKDEST_LINEID: switch(ROUT_TASKID(dwRoutingInfo)) { case TASKID_TSPI_lineOpen: { TASKPARAM_TSPI_lineOpen *pParams = (TASKPARAM_TSPI_lineOpen *) pvParams; ASSERT(pParams->dwStructSize == sizeof(TASKPARAM_TSPI_lineOpen)); ASSERT(pParams->dwTaskID == TASKID_TSPI_lineOpen); SLPRINTF1( psl, "lineOpen (ID=%lu)", pParams->dwDeviceID ); if (m_fUserRemovePending) { *plRet = LINEERR_OPERATIONFAILED; tspRet = FL_GEN_RETVAL(IDERR_WRONGSTATE); break; } tspRet = mfn_LoadLine(pParams,psl); if (!tspRet) { *plRet = 0; } } break; case TASKID_TSPI_lineGetDevCaps: { TASKPARAM_TSPI_lineGetDevCaps *pParams = (TASKPARAM_TSPI_lineGetDevCaps *) pvParams; ASSERT(pParams->dwStructSize == sizeof(TASKPARAM_TSPI_lineGetDevCaps)); ASSERT(pParams->dwTaskID == TASKID_TSPI_lineGetDevCaps); SLPRINTF1( psl, "DEVICE %lu", pParams->dwDeviceID ); // Verify version if (pParams->dwTSPIVersion != TAPI_CURRENT_VERSION) { FL_SET_RFR(0x94949c00, "Incorrect TSPI version"); *plRet = LINEERR_INCOMPATIBLEAPIVERSION; } else { tspRet = mfn_get_LINDEVCAPS ( pParams->lpLineDevCaps, plRet, psl ); } } break; case TASKID_TSPI_lineGetAddressCaps: { TASKPARAM_TSPI_lineGetAddressCaps *pParams = (TASKPARAM_TSPI_lineGetAddressCaps *) pvParams; ASSERT(pParams->dwStructSize == sizeof(TASKPARAM_TSPI_lineGetAddressCaps)); ASSERT(pParams->dwTaskID == TASKID_TSPI_lineGetAddressCaps); SLPRINTF1( psl, "DEVICE %lu", pParams->dwDeviceID ); // Verify version if (pParams->dwTSPIVersion != TAPI_CURRENT_VERSION) { FL_SET_RFR(0xb949f900, "Incorrect TSPI version"); *plRet = LINEERR_INCOMPATIBLEAPIVERSION; } else if (pParams->dwAddressID) { FL_SET_RFR(0xb1776700, "Invalid address ID"); *plRet = LINEERR_INVALADDRESSID; } else { tspRet = mfn_get_ADDRESSCAPS( pParams->dwDeviceID, pParams->lpAddressCaps, plRet, psl ); } } break; case TASKID_TSPI_lineGetDevConfig: { TASKPARAM_TSPI_lineGetDevConfig *pParams = (TASKPARAM_TSPI_lineGetDevConfig *) pvParams; ASSERT(pParams->dwStructSize == sizeof(TASKPARAM_TSPI_lineGetDevConfig)); ASSERT(pParams->dwTaskID == TASKID_TSPI_lineGetDevConfig); LPVARSTRING lpVarString = pParams->lpDeviceConfig; LPCTSTR lpszDeviceClass = pParams->lpszDeviceClass; BOOL DialIn = FALSE; CALLINFO *pCall = (m_pLine) ? m_pLine->pCall : NULL; DWORD dwDeviceClass = parse_device_classes( lpszDeviceClass, FALSE ); HKEY hKey; if (lpVarString->dwTotalSize < sizeof(VARSTRING)) { *plRet = LINEERR_STRUCTURETOOSMALL; goto end; } switch(dwDeviceClass) { case DEVCLASS_COMM_DATAMODEM_DIALIN: if (RegOpenKeyA(HKEY_LOCAL_MACHINE, m_StaticInfo.rgchDriverKey, &hKey) == ERROR_SUCCESS) { DWORD dwcbSize = sizeof(m_Settings.rgbDialTempCommCfgBuf); DWORD dwRet = UmRtlGetDefaultCommConfig(hKey, m_Settings.pDialTempCommCfg, &dwcbSize); if (dwRet == ERROR_SUCCESS) { CopyMemory(m_Settings.pDialInCommCfg, m_Settings.pDialTempCommCfg, dwcbSize); } RegCloseKey(hKey); } DialIn=TRUE; break; case DEVCLASS_COMM: case DEVCLASS_COMM_DATAMODEM: case DEVCLASS_COMM_DATAMODEM_DIALOUT: // 1/29/1998 JosephJ. // The following case is added for // backwards compatibility with NT4 TSP, which // simply checked if the class was a valid class, // and treated all valid classes (including // (comm/datamodem/portname) the same way // for lineGet/SetDevConfig. We, however, don't // allow comm/datamodem/portname here -- only // the 2 above and two below represent // setting DEVCFG // case DEVCLASS_TAPI_LINE: // we deal this below the switch statement. break; case DEVCLASS_COMM_EXTENDEDCAPS: { *plRet = mfn_GetCOMM_EXTENDEDCAPS( lpVarString, psl ); goto end; } case DEVCLASS_TAPI_LINE_DIAGNOSTICS: { // New in NT5.0 // Process call/diagnostics configuration const UINT cbLDC = sizeof(LINEDIAGNOSTICSCONFIG); lpVarString->dwStringSize = 0; lpVarString->dwUsedSize = sizeof(VARSTRING); lpVarString->dwNeededSize = sizeof(VARSTRING) + cbLDC; if (lpVarString->dwTotalSize >= lpVarString->dwNeededSize) { LINEDIAGNOSTICSCONFIG *pLDC = (LINEDIAGNOSTICSCONFIG *) (((LPBYTE)lpVarString) + sizeof(VARSTRING)); pLDC->hdr.dwSig = LDSIG_LINEDIAGNOSTICSCONFIG; pLDC->hdr.dwTotalSize = cbLDC; pLDC->hdr.dwFlags = m_StaticInfo.dwDiagnosticCaps; pLDC->hdr.dwParam = m_Settings.dwDiagnosticSettings; lpVarString->dwStringFormat =STRINGFORMAT_BINARY; lpVarString->dwStringSize = cbLDC; lpVarString->dwStringOffset = sizeof(VARSTRING); lpVarString->dwUsedSize += cbLDC; } *plRet = 0; // success goto end; } break; default: *plRet = LINEERR_OPERATIONUNAVAIL; // we don't support lineGetDevConfig // for any other class. goto end; case DEVCLASS_UNKNOWN: *plRet = LINEERR_INVALDEVICECLASS; goto end; } // TODO: Fail if out-of-service // // if (pLineDev->fdwResources&LINEDEVFLAGS_OUTOFSERVICE) // { // lRet = LINEERR_RESOURCEUNAVAIL; // goto end; // } // New in NT5.0 lpVarString->dwStringSize = 0; LPCOMMCONFIG CommConfigToUse=DialIn ? m_Settings.pDialInCommCfg : m_Settings.pDialOutCommCfg; DWORD cbDevCfg = CommConfigToUse->dwSize + sizeof(UMDEVCFGHDR); // Validate the buffer size // lpVarString->dwUsedSize = sizeof(VARSTRING); lpVarString->dwNeededSize = sizeof(VARSTRING) + cbDevCfg; if (lpVarString->dwTotalSize >= lpVarString->dwNeededSize) { UMDEVCFGHDR CfgHdr; ZeroMemory(&CfgHdr, sizeof(CfgHdr)); CfgHdr.dwSize = cbDevCfg; CfgHdr.dwVersion = UMDEVCFG_VERSION; CfgHdr.fwOptions = (WORD) m_Settings.dwOptions; CfgHdr.wWaitBong = (WORD) m_Settings.dwWaitBong; SLPRINTF2( psl, "Reporting dwOpt = 0x%04lx; dwBong = 0x%04lx", m_Settings.dwOptions, m_Settings.dwWaitBong ); // Fill with the default value // UMDEVCFG *pCfg = (UMDEVCFG *) (((LPBYTE)lpVarString) + sizeof(VARSTRING)); // Copy the header // pCfg->dfgHdr = CfgHdr; // Copy the commconfig // CopyMemory( &(pCfg->commconfig), CommConfigToUse, CommConfigToUse->dwSize ); if (!pCfg->commconfig.dcb.BaudRate) { // JosephJ Todo: clean out all this stuff post-beta. // DebugBreak(); pCfg->commconfig.dcb.BaudRate = 57600; } lpVarString->dwStringFormat = STRINGFORMAT_BINARY; lpVarString->dwStringSize = cbDevCfg; lpVarString->dwStringOffset = sizeof(VARSTRING); lpVarString->dwUsedSize += cbDevCfg; // 9/06/97 JosephJ Bug#.106683 // If there is datamodem call in the // connected state, pick up the // connection information like // Negotiated DCE rate and Connection // options. if (pCall && pCall->IsConnectedDataCall()) { LPMODEMSETTINGS pMS = (LPMODEMSETTINGS) (pCfg->commconfig.wcProviderData); // Note: We've already verified that the target // pCfg structure is large enough. // 9/06/1997 JosephJ Set negotiated options. // The use of the mask // below is taken from atmini\dialansw.c, which // does it before calling SetCommConfig. // Not sure if we need to mask them out or not, but // for not it's there... pMS->dwNegotiatedModemOptions |= (pCall->dwConnectionOptions & ( MDM_COMPRESSION | MDM_ERROR_CONTROL | MDM_CELLULAR)); pMS->dwNegotiatedDCERate = pCall->dwNegotiatedRate; } } *plRet = 0; // success } // end case TASKID_TSPI_lineGetDevConfig: break; case TASKID_TSPI_lineSetDevConfig: { TASKPARAM_TSPI_lineSetDevConfig *pParams = (TASKPARAM_TSPI_lineSetDevConfig *) pvParams; ASSERT(pParams->dwStructSize == sizeof(TASKPARAM_TSPI_lineSetDevConfig)); ASSERT(pParams->dwTaskID == TASKID_TSPI_lineSetDevConfig); BOOL DialIn=FALSE; DWORD dwSize = pParams->dwSize; LPCTSTR lpszDeviceClass = pParams->lpszDeviceClass; DWORD dwDeviceClass = parse_device_classes( lpszDeviceClass, FALSE); switch(dwDeviceClass) { case DEVCLASS_COMM_DATAMODEM_DIALIN: DialIn=TRUE; break; case DEVCLASS_COMM: case DEVCLASS_COMM_DATAMODEM: case DEVCLASS_COMM_DATAMODEM_DIALOUT: // 1/29/1998 JosephJ. // The following case is added for // backwards compatibility with NT4 TSP, which // simply checked if the class was a valid class, // and treated all valid classes (including // (comm/datamodem/portname) the same way // for lineGet/SetDevConfig. We, however, don't // allow comm/datamodem/portname here -- only // the 2 above and two below represent // setting DEVCFG // case DEVCLASS_TAPI_LINE: // we deal this below the switch statement. break; case DEVCLASS_TAPI_LINE_DIAGNOSTICS: { LINEDIAGNOSTICSCONFIG *pLDC = (LINEDIAGNOSTICSCONFIG *) pParams->lpDeviceConfig; if ( pLDC->hdr.dwSig != LDSIG_LINEDIAGNOSTICSCONFIG || dwSize != sizeof(LINEDIAGNOSTICSCONFIG) || pLDC->hdr.dwTotalSize != dwSize || (pLDC->hdr.dwParam && pLDC->hdr.dwParam != m_StaticInfo.dwDiagnosticCaps)) { *plRet = LINEERR_INVALPARAM; goto end; } else { // Note, by design, we ignore the dwCaps passed in. // m_Settings.dwDiagnosticSettings = pLDC->hdr.dwParam; } *plRet = 0; // success goto end; } break; default: *plRet = LINEERR_OPERATIONUNAVAIL; // we don't support lineSetDevConfig // for any other class. goto end; case DEVCLASS_UNKNOWN: *plRet = LINEERR_INVALDEVICECLASS; goto end; } // This is the comm or comm/datamodem case ... UMDEVCFG *pDevCfgNew = (UMDEVCFG *) pParams->lpDeviceConfig; tspRet = CTspDev::mfn_update_devcfg_from_app( pDevCfgNew, dwSize, DialIn, psl ); *plRet = 0; // success if (tspRet) { tspRet = 0; *plRet = LINEERR_INVALPARAM; goto end; } *plRet = 0; // success } break; case TASKID_TSPI_lineNegotiateTSPIVersion: { TASKPARAM_TSPI_lineNegotiateTSPIVersion *pParams = (TASKPARAM_TSPI_lineNegotiateTSPIVersion *) pvParams; ASSERT(pParams->dwStructSize == sizeof(TASKPARAM_TSPI_lineNegotiateTSPIVersion)); ASSERT(pParams->dwTaskID == TASKID_TSPI_lineNegotiateTSPIVersion); // Check the version range // if (pParams->dwHighVersion<TAPI_CURRENT_VERSION || pParams->dwLowVersion>TAPI_CURRENT_VERSION) { *plRet= LINEERR_INCOMPATIBLEAPIVERSION; } else { *(pParams->lpdwTSPIVersion) = TAPI_CURRENT_VERSION; *plRet= 0; } } break; case TASKID_TSPI_providerGenericDialogData: { TASKPARAM_TSPI_providerGenericDialogData *pParams = (TASKPARAM_TSPI_providerGenericDialogData *) pvParams; ASSERT(pParams->dwStructSize == sizeof(TASKPARAM_TSPI_providerGenericDialogData)); ASSERT(pParams->dwTaskID == TASKID_TSPI_providerGenericDialogData); SLPRINTF1( psl, "DEVICE %lu", pParams->dwObjectID ); *plRet = mfn_GenericLineDialogData( pParams->lpParams, pParams->dwSize, psl ); } break; case TASKID_TSPI_lineGetIcon: { TASKPARAM_TSPI_lineGetIcon *pParams = (TASKPARAM_TSPI_lineGetIcon *) pvParams; ASSERT(pParams->dwStructSize == sizeof(TASKPARAM_TSPI_lineGetIcon)); ASSERT(pParams->dwTaskID == TASKID_TSPI_lineGetIcon); const TCHAR *lpszDeviceClass = pParams->lpszDeviceClass; // // Validate device class -- we only support this for // tapi/[line|phone]. This check is new for NT5.0 // // NOTE: according to tapi docs, NULL or empty device // class is valid... // if (lpszDeviceClass && *lpszDeviceClass) { DWORD dwDeviceClass = parse_device_classes( lpszDeviceClass, FALSE ); switch (dwDeviceClass) { case DEVCLASS_TAPI_PHONE: if (!mfn_IsPhone()) { *plRet = LINEERR_OPERATIONUNAVAIL; goto end; } case DEVCLASS_TAPI_LINE: // OK break; case DEVCLASS_UNKNOWN: *plRet = LINEERR_INVALDEVICECLASS; goto end; default: *plRet = LINEERR_OPERATIONUNAVAIL; goto end; } } // // If we haven't loaded an icon, load it... // if (m_StaticInfo.hIcon == NULL) { int iIcon=-1; switch (m_StaticInfo.dwDeviceType) { case DT_NULL_MODEM: iIcon = IDI_NULL; break; case DT_EXTERNAL_MODEM: iIcon = IDI_EXT_MDM; break; case DT_INTERNAL_MODEM: iIcon = IDI_INT_MDM; break; case DT_PCMCIA_MODEM: iIcon = IDI_PCM_MDM; break; default: iIcon = -1; break; } if (iIcon != -1) { m_StaticInfo.hIcon = LoadIcon( g.hModule, MAKEINTRESOURCE(iIcon) ); } }; *(pParams->lphIcon) = m_StaticInfo.hIcon; *plRet = 0; } break; } break; // end case TASKDEST_LINEID case TASKDEST_PHONEID: *plRet = PHONEERR_OPERATIONUNAVAIL; switch(ROUT_TASKID(dwRoutingInfo)) { case TASKID_TSPI_phoneOpen: { TASKPARAM_TSPI_phoneOpen *pParams = (TASKPARAM_TSPI_phoneOpen *) pvParams; ASSERT(pParams->dwStructSize == sizeof(TASKPARAM_TSPI_phoneOpen)); ASSERT(pParams->dwTaskID == TASKID_TSPI_phoneOpen); SLPRINTF1( psl, "phoneOpen (ID=%lu)", pParams->dwDeviceID ); tspRet = mfn_LoadPhone(pParams, psl); if (!tspRet) { *plRet = 0; } } break; case TASKID_TSPI_phoneNegotiateTSPIVersion: { TASKPARAM_TSPI_phoneNegotiateTSPIVersion *pParams = (TASKPARAM_TSPI_phoneNegotiateTSPIVersion *) pvParams; ASSERT(pParams->dwStructSize == sizeof(TASKPARAM_TSPI_phoneNegotiateTSPIVersion)); ASSERT(pParams->dwTaskID == TASKID_TSPI_phoneNegotiateTSPIVersion); // Check the version range // if (pParams->dwHighVersion<TAPI_CURRENT_VERSION || pParams->dwLowVersion>TAPI_CURRENT_VERSION) { *plRet= LINEERR_INCOMPATIBLEAPIVERSION; } else { *(pParams->lpdwTSPIVersion) = TAPI_CURRENT_VERSION; *plRet= 0; } } break; case TASKID_TSPI_providerGenericDialogData: { TASKPARAM_TSPI_providerGenericDialogData *pParams = (TASKPARAM_TSPI_providerGenericDialogData *) pvParams; ASSERT(pParams->dwStructSize == sizeof(TASKPARAM_TSPI_providerGenericDialogData)); ASSERT(pParams->dwTaskID == TASKID_TSPI_providerGenericDialogData); SLPRINTF1( psl, "DEVICE %lu", pParams->dwObjectID ); *plRet = mfn_GenericPhoneDialogData( pParams->lpParams, pParams->dwSize ); } break; case TASKID_TSPI_phoneGetDevCaps: { TASKPARAM_TSPI_phoneGetDevCaps *pParams = (TASKPARAM_TSPI_phoneGetDevCaps *) pvParams; ASSERT(pParams->dwStructSize == sizeof(TASKPARAM_TSPI_phoneGetDevCaps)); ASSERT(pParams->dwTaskID == TASKID_TSPI_phoneGetDevCaps); SLPRINTF1( psl, "DEVICE %lu", pParams->dwDeviceID ); // Verify version if ( (pParams->dwTSPIVersion < 0x00010004) || (pParams->dwTSPIVersion > TAPI_CURRENT_VERSION)) { FL_SET_RFR(0x9db11a00, "Incorrect TSPI version"); *plRet = PHONEERR_INCOMPATIBLEAPIVERSION; } else { tspRet = mfn_get_PHONECAPS ( pParams->lpPhoneCaps, plRet, psl ); } } break; case TASKID_TSPI_phoneGetExtensionID: { TASKPARAM_TSPI_phoneGetExtensionID *pParams = (TASKPARAM_TSPI_phoneGetExtensionID *) pvParams; ASSERT(pParams->dwStructSize == sizeof(TASKPARAM_TSPI_phoneGetExtensionID)); ASSERT(pParams->dwTaskID == TASKID_TSPI_phoneGetExtensionID); ZeroMemory( pParams->lpExtensionID, sizeof(*(pParams->lpExtensionID)) ); *plRet = 0; } break; case TASKID_TSPI_phoneGetIcon: { TASKPARAM_TSPI_phoneGetIcon *pParams = (TASKPARAM_TSPI_phoneGetIcon *) pvParams; ASSERT(pParams->dwStructSize == sizeof(TASKPARAM_TSPI_phoneGetIcon)); ASSERT(pParams->dwTaskID == TASKID_TSPI_phoneGetIcon); const TCHAR *lpszDeviceClass = pParams->lpszDeviceClass; // // Validate device class -- we only support this for // tapi/[line|phone]. This check is new for NT5.0 and win9x // // // NOTE: according to tapi docs, NULL or empty device // class is valid... // if (lpszDeviceClass && *lpszDeviceClass) { DWORD dwDeviceClass = parse_device_classes( pParams->lpszDeviceClass, FALSE ); switch (dwDeviceClass) { case DEVCLASS_TAPI_LINE: if (!mfn_IsLine()) { *plRet = PHONEERR_OPERATIONUNAVAIL; goto end; } // fall through... case DEVCLASS_TAPI_PHONE: // OK break; case DEVCLASS_UNKNOWN: *plRet = PHONEERR_INVALDEVICECLASS; goto end; default: *plRet = PHONEERR_OPERATIONUNAVAIL; goto end; } } // // If we haven't loaded an icon, load it... // if (m_StaticInfo.hIcon == NULL) { int iIcon=-1; switch (m_StaticInfo.dwDeviceType) { case DT_NULL_MODEM: iIcon = IDI_NULL; break; case DT_EXTERNAL_MODEM: iIcon = IDI_EXT_MDM; break; case DT_INTERNAL_MODEM: iIcon = IDI_INT_MDM; break; case DT_PCMCIA_MODEM: iIcon = IDI_PCM_MDM; break; default: iIcon = -1; break; } if (iIcon != -1) { m_StaticInfo.hIcon = LoadIcon( g.hModule, MAKEINTRESOURCE(iIcon) ); } } *(pParams->lphIcon) = m_StaticInfo.hIcon; *plRet = 0; } break; } break; // End TASKDEST_PHONEID; case TASKDEST_HDRVLINE: if (m_pLine) { mfn_accept_tsp_call_for_HDRVLINE( dwRoutingInfo, pvParams, plRet, psl ); } break; case TASKDEST_HDRVPHONE: *plRet = PHONEERR_OPERATIONUNAVAIL; if (m_pPhone) { mfn_accept_tsp_call_for_HDRVPHONE( dwRoutingInfo, pvParams, plRet, psl ); } break; case TASKDEST_HDRVCALL: if (m_pLine && m_pLine->pCall) { mfn_accept_tsp_call_for_HDRVCALL( dwRoutingInfo, pvParams, plRet, psl ); } break; default: FL_SET_RFR(0x57d39b00, "Unknown destination"); break; } end: m_sync.LeaveCrit(dwLUID_CurrentLoc); FL_LOG_EXIT(psl, tspRet); return tspRet; } TSPRETURN CTspDev::Load( HKEY hkDevice, HKEY hkUnimodem, LPTSTR lptszProviderName, LPSTR lpszDriverKey, CTspMiniDriver *pMD, HANDLE hThreadAPC, CStackLog *psl ) { // // TODO: 1/5/1997 JosephJ -- Replace code that roots into the device // registry by calls into the mini driver. The minidriver should // be the only thing that looks into the driver node. // FL_DECLARE_FUNC(0xd328ab03, "CTspDev::Load") TSPRETURN tspRet = FL_GEN_RETVAL(IDERR_INVALID_ERR); UINT cbDriverKey = 1+lstrlenA(lpszDriverKey); DWORD dwRegSize; DWORD dwRegType; DWORD dwRet; REGDEVCAPS regdevcaps; HSESSION hSession=0; FL_LOG_ENTRY(psl); m_sync.EnterCrit(dwLUID_CurrentLoc); tspRet = m_sync.BeginLoad(); if (tspRet) goto end; FL_ASSERT(psl, !m_StaticInfo.hSessionMD); ZeroMemory(&m_StaticInfo, sizeof(m_StaticInfo)); m_hThreadAPC = NULL; ZeroMemory(&m_Settings, sizeof(m_Settings)); ZeroMemory(&m_Line, sizeof(m_Line)); ZeroMemory(&m_Phone, sizeof(m_Phone)); ZeroMemory(&m_LLDev, sizeof(m_LLDev)); m_pLine = NULL; m_pPhone = NULL; m_pLLDev = NULL; fdwResources=0; m_fUnloadPending = FALSE; m_fUserRemovePending = FALSE; // Start a session with the mini driver. The mini driver will only // allow sessions if it in the loaded state. Furthermore, it will not // distroy itself until all sessions are closed. This is the standard // semantics supported by class CSync -- look at csync.h for details. // if (!pMD) { FL_SET_RFR(0xefaf5900, "NULL pMD passed in"); tspRet = FL_GEN_RETVAL(IDERR_GENERIC_FAILURE); goto end_load; } tspRet = pMD->BeginSession( &hSession, dwLUID_CurrentLoc ); if (tspRet) { FL_SET_RFR(0x5371c600, "Couldn't begin session with MD"); goto end_load; } if (cbDriverKey>sizeof(m_StaticInfo.rgchDriverKey)) { FL_SET_RFR(0x528e2a00, "Driver Key too large"); tspRet = FL_GEN_RETVAL(IDERR_INTERNAL_OBJECT_TOO_SMALL); goto end_load; } ASSERT(!m_pLine); m_StaticInfo.lptszProviderName = lptszProviderName; mfn_init_default_LINEDEVCAPS(); // Only keep ANSI version of driver key -- it's only used // for the devspecific (legacy hack) part of LINEDEVCAPS. lstrcpyA(m_StaticInfo.rgchDriverKey, lpszDriverKey); // 01/04/97 -- This stuff taken from NT4.0 CreateLineDev... // Get the Friendly Name dwRegSize = sizeof(m_StaticInfo.rgtchDeviceName); dwRet = RegQueryValueExW( hkDevice, cszFriendlyName, NULL, &dwRegType, (BYTE*) m_StaticInfo.rgtchDeviceName, &dwRegSize ); if (dwRet != ERROR_SUCCESS || dwRegType != REG_SZ) { FL_SET_RFR(0x5a5cd100, "RegQueryValueEx(FriendlyName) fails"); tspRet = FL_GEN_RETVAL(IDERR_REG_QUERY_FAILED); goto end_load; } // Read in the permanent ID { // Get the permanent ID DWORD dwID=0; DWORD cbSize=sizeof(dwID); DWORD dwRegType2=0; const TCHAR cszPermanentIDKey[] = TEXT("ID"); DWORD dwRet2 = RegQueryValueEx( hkDevice, cszPermanentIDKey, NULL, &dwRegType2, (BYTE*) &dwID, &cbSize ); if (dwRet2 == ERROR_SUCCESS && (dwRegType2 == REG_BINARY || dwRegType2 == REG_DWORD) && cbSize == sizeof(dwID) && dwID) { m_StaticInfo.dwPermanentLineID = dwID; } } // Read in the permanent GUID { // Get the permanent ID DWORD dwID=0; DWORD cbSize=sizeof(m_StaticInfo.PermanentDeviceGuid); DWORD dwRegType2=0; DWORD dwRet2 = RegQueryValueEx( hkDevice, TEXT("PermanentGuid"), NULL, &dwRegType2, (BYTE*) &m_StaticInfo.PermanentDeviceGuid, &cbSize ); } // Read in the REGDEVCAPS dwRegSize = sizeof(regdevcaps); dwRet = RegQueryValueEx( hkDevice, cszProperties, NULL, &dwRegType, (BYTE *)&regdevcaps, &dwRegSize ); if (dwRet != ERROR_SUCCESS || dwRegType != REG_BINARY) { FL_SET_RFR(0xb7010000, "RegQueryValueEx(cszProperties) fails"); tspRet = FL_GEN_RETVAL(IDERR_REG_QUERY_FAILED); goto end_load; } // // We want to make sure the following flags are identical // #if (LINEDEVCAPFLAGS_DIALBILLING != DIALOPTION_BILLING) #error LINEDEVCAPFLAGS_DIALBILLING != DIALOPTION_BILLING (check tapi.h vs. mcx16.h) #endif #if (LINEDEVCAPFLAGS_DIALQUIET != DIALOPTION_QUIET) #error LINEDEVCAPFLAGS_DIALQUIET != DIALOPTION_QUIET (check tapi.h vs. mcx16.h) #endif #if (LINEDEVCAPFLAGS_DIALDIALTONE != DIALOPTION_DIALTONE) #error LINEDEVCAPFLAGS_DIALDIALTONE != DIALOPTION_DIALTONE (check tapi.h vs. mcx16.h) #endif // // Make sure this is the dwDialOptions DWORD we want. ASSERT(!(regdevcaps.dwDialOptions & ~(LINEDEVCAPFLAGS_DIALBILLING | LINEDEVCAPFLAGS_DIALQUIET | LINEDEVCAPFLAGS_DIALDIALTONE))); m_StaticInfo.dwDevCapFlags = regdevcaps.dwDialOptions | LINEDEVCAPFLAGS_LOCAL; m_StaticInfo.dwMaxDCERate = regdevcaps.dwMaxDCERate; m_StaticInfo.dwModemOptions = regdevcaps.dwModemOptions; // Analyze device type and set mediamodes appropriately BYTE bDeviceType; dwRegSize = sizeof(bDeviceType); dwRet = RegQueryValueEx( hkDevice, cszDeviceType, NULL, &dwRegType, &bDeviceType, &dwRegSize ); if ( dwRet != ERROR_SUCCESS || dwRegType != REG_BINARY || dwRegSize != sizeof(BYTE)) { FL_SET_RFR(0x00164300, "RegQueryValueEx(cszDeviceType) fails"); tspRet = FL_GEN_RETVAL(IDERR_REG_QUERY_FAILED); goto end_load; } m_StaticInfo.dwDeviceType = bDeviceType; switch (bDeviceType) { case DT_PARALLEL_PORT: m_StaticInfo.dwDeviceType = DT_NULL_MODEM; // Map back to null modem // FALLTHROUGH case DT_NULL_MODEM: m_StaticInfo.dwDefaultMediaModes = LINEMEDIAMODE_DATAMODEM; m_StaticInfo.dwBearerModes = LINEBEARERMODE_DATA | LINEBEARERMODE_PASSTHROUGH; m_StaticInfo.fPartialDialing = FALSE; break; case DT_PARALLEL_MODEM: m_StaticInfo.dwDeviceType = DT_EXTERNAL_MODEM; // Map back to // external modem // FALLTHROUGH case DT_EXTERNAL_MODEM: case DT_INTERNAL_MODEM: case DT_PCMCIA_MODEM: m_StaticInfo.dwDefaultMediaModes = LINEMEDIAMODE_DATAMODEM | LINEMEDIAMODE_INTERACTIVEVOICE; m_StaticInfo.dwBearerModes = LINEBEARERMODE_VOICE | LINEBEARERMODE_PASSTHROUGH; // read in Settings\DialSuffix to check whether we can partial dial m_StaticInfo.fPartialDialing = FALSE; HKEY hkSettings; dwRet = RegOpenKey(hkDevice, cszSettings, &hkSettings); if (dwRet == ERROR_SUCCESS) { #define HAYES_COMMAND_LENGTH 40 TCHAR rgtchBuf[HAYES_COMMAND_LENGTH]; dwRegSize = sizeof(rgtchBuf); dwRet = RegQueryValueEx( hkSettings, cszDialSuffix, NULL, &dwRegType, (BYTE *)rgtchBuf, &dwRegSize ); if (dwRet == ERROR_SUCCESS && dwRegSize > sizeof(TCHAR)) { m_StaticInfo.fPartialDialing = TRUE; } RegCloseKey(hkSettings); hkSettings=NULL; } mfn_GetVoiceProperties(hkDevice,psl); break; default: FL_SET_RFR(0x0cea5400, "Invalid bDeviceType"); tspRet = FL_GEN_RETVAL(IDERR_REG_CORRUPT); goto end_load; } // Get the default commconfig structure and fill out the other settings // (these used to be stored in the CommCfg structure in nt4.0 unimodem). // TODO 1/5/97 JosephJ -- this needs to be cleaned up to work with // 3rd-party mini drivers -- see note at head of this function. { DWORD dwcbSize = sizeof(m_Settings.rgbCommCfgBuf); m_Settings.pDialOutCommCfg = (COMMCONFIG *) m_Settings.rgbCommCfgBuf; m_Settings.pDialInCommCfg = (COMMCONFIG *) m_Settings.rgbDialInCommCfgBuf; m_Settings.pDialTempCommCfg = (COMMCONFIG *) m_Settings.rgbDialTempCommCfgBuf; dwRet = UmRtlGetDefaultCommConfig( hkDevice, m_Settings.pDialOutCommCfg, &dwcbSize ); if (dwRet != ERROR_SUCCESS) { FL_SET_RFR(0x55693500, "UmRtlGetDefaultCommConfig fails"); tspRet = FL_GEN_RETVAL(IDERR_REG_CORRUPT); goto end_load; } // // dialin and dialout start out the same. // CopyMemory( m_Settings.pDialInCommCfg, m_Settings.pDialOutCommCfg, dwcbSize ); // 1/27/1998 JosephJ -- no longer use this field.. // m_Settings.dcbDefault = m_Settings.pCommCfg->dcb; // Structure Copy m_Settings.dwOptions = UMTERMINAL_NONE; m_Settings.dwWaitBong = UMDEF_WAIT_BONG; } //// TODO: make the diagnostic caps based on the modem properties, /// For now, pretend that it's enabled. // ALSO: don't support the tapi/line/diagnostics class // if the modem doesn't support it... // if (m_StaticInfo.dwDeviceType != DT_NULL_MODEM) { m_StaticInfo.dwDiagnosticCaps = fSTANDARD_CALL_DIAGNOSTICS; } // // Set the m_Settings.dwNVRamState to non-zero only if there // are commands under the NVInit key, as well as the volatile value // NVInited is nonexistant or set to 0. // { m_Settings.dwNVRamState = 0; // // JosephJ - the following key used to be "NVInit", but changed this // to "ISDN\NVSave", because the NVInit commands may not be present at // the time we load the device. // UINT cCommands = ReadCommandsA( hkDevice, "ISDN\\NvSave", NULL ); // // We don't care about the commands themselves at this point -- just // whether they exist or not... // if (cCommands) { //OutputDebugString(TEXT("FOUND NVINIT KEY\r\n")); m_Settings.dwNVRamState = fNVRAM_AVAILABLE|fNVRAM_SETTINGS_CHANGED; if (get_volatile_key_value(hkDevice)) { //OutputDebugString(TEXT("NVRAM UP-TO-DATE -- NOT INITING\r\n")); // // non-zero value indicates that we don't need to re-init // nvram. This non-zero value is set ONLY when we // actually send out the nv-init commands to the modem. // mfn_ClearNeedToInitNVRam(); } else { //OutputDebugString(TEXT("NVRAM STALE -- NEED TO INIT\r\n")); } } } // // Construct the various class lists -- this must be done after // all the basic capabilities have been determined. // Classes such as tapi/phone are only added if the device supports // the capability. This is new for NT5 (Even win95 unimodem/v simply made // ALL devices support tapi/phone, wave/in, etc). // // This is done so that basic device capabilities can be obtained // by looking at the device classes supported. // // // Currently (7/15/1997) Address device classes are the same as line // device classes. This may diverge in the future. // { m_StaticInfo.cbLineClassList = 0; m_StaticInfo.szzLineClassList = NULL; m_StaticInfo.cbPhoneClassList = 0; m_StaticInfo.szzPhoneClassList = NULL; m_StaticInfo.cbAddressClassList = 0; m_StaticInfo.szzAddressClassList = NULL; if (mfn_CanDoVoice()) { if (mfn_IsPhone()) { // ---- Line Class List --------------------------- // m_StaticInfo.cbLineClassList = sizeof(g_szzLineWithWaveAndPhoneClassList); m_StaticInfo.szzLineClassList = g_szzLineWithWaveAndPhoneClassList; // ---- Phone Class List --------------------------- // // Note that we only support wave audio if the device // supports handset functionality. Win9x unimodem does not // do this (in fact it reports phone classes even // for non-voice modems!). // m_StaticInfo.cbPhoneClassList = (mfn_Handset()) ? sizeof(g_szzPhoneWithAudioClassList) : sizeof(g_szzPhoneWithoutAudioClassList); m_StaticInfo.szzPhoneClassList = (mfn_Handset()) ? g_szzPhoneWithAudioClassList : g_szzPhoneWithoutAudioClassList; // ---- Address Class List ------------------------- // m_StaticInfo.cbAddressClassList = sizeof(g_szzLineWithWaveAndPhoneClassList); m_StaticInfo.szzAddressClassList = g_szzLineWithWaveAndPhoneClassList; } else { // ---- Line Class List --------------------------- // m_StaticInfo.cbLineClassList = sizeof(g_szzLineWithWaveClassList); m_StaticInfo.szzLineClassList = g_szzLineWithWaveClassList; // ---- Address Class List ------------------------- // m_StaticInfo.cbAddressClassList = sizeof(g_szzLineWithWaveClassList); m_StaticInfo.szzAddressClassList = g_szzLineWithWaveClassList; } } else { // ---- Line Class List --------------------------- // m_StaticInfo.cbLineClassList = sizeof(g_szzLineNoVoiceClassList); m_StaticInfo.szzLineClassList = g_szzLineNoVoiceClassList; // ---- Address Class List ------------------------- // m_StaticInfo.cbAddressClassList = sizeof(g_szzLineNoVoiceClassList); m_StaticInfo.szzAddressClassList = g_szzLineNoVoiceClassList; } } // Init task stack ... { DEVTASKINFO *pInfo = m_rgTaskStack; DEVTASKINFO *pEnd=pInfo+sizeof(m_rgTaskStack)/sizeof(m_rgTaskStack[0]); // Init the task array to valid (but empty values). // ZeroMemory (m_rgTaskStack, sizeof(m_rgTaskStack)); while(pInfo<pEnd) { pInfo->hdr.dwSigAndSize = MAKE_SigAndSize(sizeof(*pInfo)); pInfo++; } m_uTaskDepth = 0; m_dwTaskCounter = 0; m_pfTaskPending = NULL; m_hRootTaskCompletionEvent = NULL; } m_hThreadAPC = hThreadAPC; end_load: if (tspRet) { // Cleanup if (hSession) { pMD->EndSession(hSession); } } else { if (hkDevice) { RegCloseKey(hkDevice); hkDevice=NULL; } m_StaticInfo.hSessionMD = hSession; m_StaticInfo.pMD = pMD; } m_sync.EndLoad(!(tspRet)); end: m_sync.LeaveCrit(dwLUID_CurrentLoc); FL_LOG_EXIT(psl, tspRet); return tspRet; } void CTspDev::Unload( HANDLE hEvent, LONG *plCounter ) { BOOL fLocalEvent = FALSE; // // NULL hEvent implies synchronous unload. We still need to potentially // wait for unload to complete, so we create our own event instead. // if (!hEvent) { hEvent = CreateEvent( NULL, TRUE, FALSE, NULL ); LONG lCounter=1; plCounter = &lCounter; fLocalEvent = TRUE; } TSPRETURN tspRet= m_sync.BeginUnload(hEvent, plCounter); m_sync.EnterCrit(0); if (!tspRet) { if (m_pLine) { mfn_UnloadLine(NULL); ASSERT(m_pLine == NULL); } if (m_pPhone) { mfn_UnloadPhone(NULL); ASSERT(m_pPhone == NULL); } if (m_pLLDev) { // This implies that there is pending activity, so // we can't complete unload now... // Unloading of CTspDev will deferred until // m_pLLDev becomes NULL, at which point // m_sync.EndUnload() will be called. m_fUnloadPending = TRUE; } else { goto end_unload; } } m_sync.LeaveCrit(0); // // We get here if there is a pending task. We don't // call EndUnload here because EndUnload will be called // when the task is completed. // // If we created this event locally, we wait for it to be set here itself... // if (fLocalEvent) { WaitForSingleObject(hEvent, INFINITE); CloseHandle(hEvent); hEvent=NULL; } return; end_unload: // // We get here if there is no lldev activity. // We actually signal end of unload here (synchronously). // if (m_StaticInfo.hSessionMD) { ASSERT(m_StaticInfo.pMD); m_StaticInfo.pMD->EndSession(m_StaticInfo.hSessionMD); m_StaticInfo.hSessionMD=0; m_StaticInfo.pMD=NULL; } // After EndUnload returns, we should assume that the this pointer // is no longer valid, which is why we leave the critical section // first... m_sync.LeaveCrit(0); UINT uRefs = m_sync.EndUnload(); if (fLocalEvent) { // // At this point, either the ref count was zero and so the event // has been signaled or the ref count was nonzero and so // the event remains to be signalled (but the state is unloaded) -- // in this case we'll wait until the last person calls // EndSession, which will also set the event... // if (uRefs) { // // The ref count is nonzero, which means there are one // or more sessions active. We've already called EndUnload, // so now we simply wait -- the next time the ref count // goes to zero in a call to EndSession, EndSession will // set this event. // WaitForSingleObject(hEvent, INFINITE); } // // We allocated this ourselves, so we free it here ... // CloseHandle(hEvent); hEvent=NULL; } return; } LONG ExtensionCallback( void *pvTspToken, DWORD dwRoutingInfo, void *pTspParams ) { LONG lRet = LINEERR_OPERATIONFAILED; FL_DECLARE_FUNC(0xeaf0b34f,"ExtensionCallback"); FL_DECLARE_STACKLOG(sl, 1000); CTspDev *pDev = (CTspDev*) pvTspToken; TSPRETURN tspRet = pDev->AcceptTspCall( TRUE, dwRoutingInfo, pTspParams, &lRet, &sl ); #define COLOR_DEV_EXTENSION FOREGROUND_RED sl.Dump(COLOR_DEV_EXTENSION); return lRet; } TSPRETURN CTspDev::RegisterProviderInfo( ASYNC_COMPLETION cbCompletionProc, HPROVIDER hProvider, CStackLog *psl ) { FL_DECLARE_FUNC(0xccba5b51, "CTspDev::RegisterProviderInfo"); TSPRETURN tspRet = 0; FL_LOG_ENTRY(psl); m_sync.EnterCrit(FL_LOC); if (m_sync.IsLoaded()) { m_StaticInfo.pfnTAPICompletionProc = cbCompletionProc; m_StaticInfo.hProvider = hProvider; // // LineID and PhoneID are filled out in subsequent calls // to ActivateLineDevice and ActivatePhoneDevice, respectively. // // This reason for this is tapi notifies us of line-device and // phone-device creation separately. // // // We are guaranteed not to be called with an line (phone) api // until after ActivateLine(Phone)Device is called. // // m_StaticInfo.dwTAPILineID= 0xffffffff; // bogus value m_StaticInfo.dwTAPIPhoneID= 0xffffffff; // bogus value // // Now lets bind to the extension DLL if required... // if (m_StaticInfo.pMD->ExtIsEnabled()) { HANDLE h = m_StaticInfo.pMD->ExtOpenExtensionBinding( NULL, // TODO: hKeyDevice, cbCompletionProc, // dwLineID, << OBSOLETE 10/13/1997 // dwPhoneID, << OBSOLETE 10/13/1997 ExtensionCallback ); m_StaticInfo.hExtBinding = h; if (!h) { FL_SET_RFR(0x33d90700, "ExtOpenExtensionBinding failed"); tspRet = FL_GEN_RETVAL(IDERR_MDEXT_BINDING_FAILED); } // We are hardcore about ONLY using the extension proc here... m_StaticInfo.pfnTAPICompletionProc = NULL; } } else { FL_SET_RFR(0xb8b24200, "wrong state"); tspRet = FL_GEN_RETVAL(IDERR_WRONGSTATE); } m_sync.LeaveCrit(FL_LOC); FL_LOG_EXIT(psl,tspRet); return tspRet; } #define ROUND_TO_DWORD(_x) ( (_x + (sizeof(DWORD) - 1) ) & ~(sizeof(DWORD)-1)) TSPRETURN CTspDev::mfn_get_LINDEVCAPS ( LPLINEDEVCAPS lpLineDevCaps, LONG *plRet, CStackLog *psl ) // // mfn_get_LINEDEVCAPS uses cached information to fill out the passed-in // LINEDEVCAPS structure in large chunks. // { FL_DECLARE_FUNC(0x7e77dd17, "CTspDev::mfn_get_LINEDEVCAPS") BYTE *pbStart = (BYTE*)lpLineDevCaps; BYTE *pbCurrent = pbStart; BYTE *pbEnd = pbStart + lpLineDevCaps->dwTotalSize; UINT cbItem=0; DWORD dwNeededSize = sizeof (LINEDEVCAPS); FL_LOG_ENTRY(psl); *plRet = 0; // Assume success; if ((pbEnd-pbCurrent) < sizeof(LINEDEVCAPS)) { *plRet = LINEERR_STRUCTURETOOSMALL; FL_SET_RFR(0x8456cb00, "LINEDEVCAPS structure too small"); goto end; } // // Zero out the the first sizeof(LINEDEVCAPS) of the passed-in structure, // copy in our own default cached structure, and fixup the total size. // ZeroMemory(lpLineDevCaps,(sizeof(LINEDEVCAPS))); CopyMemory(lpLineDevCaps,&m_StaticInfo.DevCapsDefault,sizeof(LINEDEVCAPS)); ASSERT(lpLineDevCaps->dwUsedSize == sizeof(LINEDEVCAPS)); lpLineDevCaps->dwTotalSize = (DWORD)(pbEnd-pbStart); pbCurrent += sizeof(LINEDEVCAPS); // // Fill in some of the modem-specific caps // lpLineDevCaps->dwMaxRate = m_StaticInfo.dwMaxDCERate; lpLineDevCaps->dwBearerModes = m_StaticInfo.dwBearerModes; lpLineDevCaps->dwMediaModes = m_StaticInfo.dwDefaultMediaModes; // Note NT4.0 unimodem set lpLineDevCaps->dwMediaModes to // LINEDEV.dwMediaModes, not to .dwDefaultMediaModes. Howerver the // two are always the same in NT4.0 -- neither is changed from its // initial value, created when LINEDEV is created. // We can simulate wait-for-bong.... lpLineDevCaps->dwDevCapFlags = m_StaticInfo.dwDevCapFlags | LINEDEVCAPFLAGS_DIALBILLING | LINEDEVCAPFLAGS_CLOSEDROP; lpLineDevCaps->dwPermanentLineID = m_StaticInfo.dwPermanentLineID; if(mfn_CanDoVoice()) { lpLineDevCaps->dwGenerateDigitModes = LINEDIGITMODE_DTMF; lpLineDevCaps->dwMonitorToneMaxNumFreq = 1; // silence monitor lpLineDevCaps->dwMonitorToneMaxNumEntries = 1; lpLineDevCaps->dwMonitorDigitModes = LINEDIGITMODE_DTMF | LINEDIGITMODE_DTMFEND; // 6/2/1997 JosephJ TBD: the following was enabled in unimodem/v. // Enable it at the point when forwarding is implemented.... // lpLineDevCaps->dwLineFeatures |= LINEFEATURE_FORWARD; #if (TAPI3) // // If this is a duplex device, say we support MSP stuff... // if (m_StaticInfo.Voice.dwProperties & fVOICEPROP_DUPLEX) { lpLineDevCaps->dwDevCapFlags |= LINEDEVCAPFLAGS_MSP; } #endif // TAPI3 } #if (TAPI3) lpLineDevCaps->dwAddressTypes = LINEADDRESSTYPE_PHONENUMBER; lpLineDevCaps->ProtocolGuid = TAPIPROTOCOL_PSTN; lpLineDevCaps->dwAvailableTracking = 0; CopyMemory( (LPBYTE)&lpLineDevCaps->PermanentLineGuid, (LPBYTE)&m_StaticInfo.PermanentDeviceGuid, sizeof(GUID) ); #endif // TAPI3 // // Copy in the provider info if it fits // cbItem = sizeof(TCHAR)*(1+lstrlen(m_StaticInfo.lptszProviderName)); dwNeededSize += ROUND_TO_DWORD(cbItem); if ((pbCurrent+cbItem)<=pbEnd) { CopyMemory((LPTSTR) pbCurrent, m_StaticInfo.lptszProviderName, cbItem); lpLineDevCaps->dwProviderInfoSize = cbItem; lpLineDevCaps->dwProviderInfoOffset = (DWORD)(pbCurrent-pbStart); pbCurrent += ROUND_TO_DWORD(cbItem); } // // Copy the device name if it fits // cbItem = sizeof(TCHAR)*(1+lstrlen(m_StaticInfo.rgtchDeviceName)); dwNeededSize += ROUND_TO_DWORD(cbItem); if ((pbCurrent+cbItem)<=pbEnd) { CopyMemory((LPTSTR) pbCurrent, m_StaticInfo.rgtchDeviceName, cbItem); lpLineDevCaps->dwLineNameSize = cbItem; lpLineDevCaps->dwLineNameOffset = (DWORD)(pbCurrent-pbStart); pbCurrent += ROUND_TO_DWORD(cbItem); } // // Copy device-specific stuff // This is a hack structure used by MSFAX and a few others. // // First move up to a dword aligned address // // { BYTE *pb = pbCurrent; pbCurrent = (BYTE*) ((ULONG_PTR) (pbCurrent+3) & (~0x3)); if (pbCurrent >= pbEnd) { pbCurrent = pbEnd; // Since we've already exhausted available space, we need to // ask for the most space that we may need for this allignment // stuff, because the next time the allignment situation may // be different. // dwNeededSize += sizeof(DWORD); } else { dwNeededSize += (DWORD)(pbCurrent-pb); } } { struct _DevSpecific { DWORD dwSig; DWORD dwKeyOffset; #pragma warning (disable : 4200) char szDriver[]; #pragma warning (default : 4200) } *pDevSpecific = (struct _DevSpecific*) pbCurrent; // Note that the driver key is in ANSI // cbItem = sizeof(*pDevSpecific)+1+lstrlenA(m_StaticInfo.rgchDriverKey); dwNeededSize += ROUND_TO_DWORD(cbItem); if ((pbCurrent+cbItem)<=pbEnd) { pDevSpecific->dwSig = 0x1; pDevSpecific->dwKeyOffset = 8; // Offset in bytes of szDriver // from start CopyMemory( pDevSpecific->szDriver, m_StaticInfo.rgchDriverKey, cbItem-sizeof(*pDevSpecific) ); lpLineDevCaps->dwDevSpecificSize = cbItem; lpLineDevCaps->dwDevSpecificOffset = (DWORD)(pbCurrent-pbStart); pbCurrent += ROUND_TO_DWORD(cbItem); } } // // Copy line device Class list if it fits.... // cbItem = mfn_GetLineClassListSize(); dwNeededSize += ROUND_TO_DWORD(cbItem); if ((pbCurrent+cbItem)<=pbEnd) { CopyMemory( (LPTSTR) pbCurrent, mfn_GetLineClassList(), cbItem ); lpLineDevCaps->dwDeviceClassesSize = cbItem; lpLineDevCaps->dwDeviceClassesOffset= (DWORD)(pbCurrent-pbStart); pbCurrent += ROUND_TO_DWORD(cbItem); } ASSERT(pbCurrent<=pbEnd); ASSERT(dwNeededSize>= (DWORD)(pbCurrent-pbStart)); lpLineDevCaps->dwNeededSize = dwNeededSize; lpLineDevCaps->dwUsedSize = (DWORD)(pbCurrent-pbStart); lpLineDevCaps->dwNeededSize = dwNeededSize; SLPRINTF3( psl, "Tot=%u,Used=%lu,Needed=%lu", lpLineDevCaps->dwTotalSize, lpLineDevCaps->dwUsedSize, lpLineDevCaps->dwNeededSize ); ASSERT(*plRet==ERROR_SUCCESS); end: FL_LOG_EXIT(psl, 0); return 0; } TSPRETURN CTspDev::mfn_get_PHONECAPS ( LPPHONECAPS lpPhoneCaps, LONG *plRet, CStackLog *psl ) // // mfn_get_LINEDEVCAPS uses cached information to fill out the passed-in // LINEDEVCAPS structure in large chunks. // // // 6/2/1997 JosephJ: this is taken more-or-less verbatim from win9x unimodem/v // (phoneGetDevCaps in cfgdlg.c). // { FL_DECLARE_FUNC(0x9b9459e3, "CTspDev::mfn_get_PHONECAPS") BYTE *pbStart = (BYTE*)lpPhoneCaps; BYTE *pbCurrent = pbStart; BYTE *pbEnd = pbStart + lpPhoneCaps->dwTotalSize; UINT cbItem=0; DWORD dwNeededSize = sizeof (PHONECAPS); FL_LOG_ENTRY(psl); *plRet = 0; // Assume success; if (!mfn_IsPhone()) { *plRet = PHONEERR_NODEVICE; FL_SET_RFR(0xd191ae00, "Device doesn't support phone capability"); goto end; } if ((pbEnd-pbCurrent) < sizeof(PHONECAPS)) { *plRet = LINEERR_STRUCTURETOOSMALL; FL_SET_RFR(0x9e30ec00, "PHONECAPS structure too small"); goto end; } // // Fill out the static portion of the capabilities // // Zero out the entire structure prior to starting. We then only explicitly // set non-zero values. This is different than unimodem/v. // ZeroMemory(lpPhoneCaps,(sizeof(PHONECAPS))); lpPhoneCaps->dwTotalSize = (DWORD)(pbEnd-pbStart); lpPhoneCaps->dwUsedSize = sizeof(PHONECAPS); pbCurrent += sizeof(PHONECAPS); // no phone info lpPhoneCaps->dwPhoneInfoSize = 0; lpPhoneCaps->dwPhoneInfoOffset = 0; // // 6/2/1997 JosephJ: unimodem/v used the following formula for generating // the PermanentPhoneID: MAKELONG(LOWORD(pLineDev->dwPermanentLineID), // LOWORD(gdwProviderID)); // We simply use the device's permanent ID (i.e., report the same // permanent id for both line and phone.) // lpPhoneCaps->dwPermanentPhoneID = m_StaticInfo.dwPermanentLineID; lpPhoneCaps->dwStringFormat = STRINGFORMAT_ASCII; // initialize the real non-zero phone variables if(mfn_Handset()) { lpPhoneCaps->dwPhoneFeatures = PHONEFEATURE_GETHOOKSWITCHHANDSET; lpPhoneCaps->dwMonitoredHandsetHookSwitchModes = PHONEHOOKSWITCHMODE_MICSPEAKER | PHONEHOOKSWITCHMODE_ONHOOK; lpPhoneCaps->dwHookSwitchDevs |= PHONEHOOKSWITCHDEV_HANDSET; lpPhoneCaps->dwHandsetHookSwitchModes = PHONEHOOKSWITCHMODE_UNKNOWN | PHONEHOOKSWITCHMODE_ONHOOK | PHONEHOOKSWITCHMODE_MICSPEAKER; lpPhoneCaps->dwPhoneStates |= PHONESTATE_HANDSETHOOKSWITCH; } if(mfn_IsSpeaker()) { lpPhoneCaps->dwPhoneFeatures |= PHONEFEATURE_GETGAINSPEAKER | PHONEFEATURE_GETVOLUMESPEAKER | PHONEFEATURE_GETHOOKSWITCHSPEAKER | PHONEFEATURE_SETGAINSPEAKER | PHONEFEATURE_SETVOLUMESPEAKER | PHONEFEATURE_SETHOOKSWITCHSPEAKER; lpPhoneCaps->dwSettableSpeakerHookSwitchModes = PHONEHOOKSWITCHMODE_MICSPEAKER | PHONEHOOKSWITCHMODE_ONHOOK; if (mfn_IsMikeMute()) { lpPhoneCaps->dwSettableSpeakerHookSwitchModes |= PHONEHOOKSWITCHMODE_SPEAKER; } lpPhoneCaps->dwHookSwitchDevs |= PHONEHOOKSWITCHDEV_SPEAKER; lpPhoneCaps->dwSpeakerHookSwitchModes = PHONEHOOKSWITCHMODE_UNKNOWN | PHONEHOOKSWITCHMODE_ONHOOK | PHONEHOOKSWITCHMODE_MICSPEAKER; if (mfn_IsMikeMute()) { lpPhoneCaps->dwSpeakerHookSwitchModes |= PHONEHOOKSWITCHMODE_SPEAKER; } lpPhoneCaps->dwPhoneStates |= ( PHONESTATE_SPEAKERHOOKSWITCH | PHONESTATE_SPEAKERVOLUME ); lpPhoneCaps->dwVolumeFlags |= PHONEHOOKSWITCHDEV_SPEAKER; lpPhoneCaps->dwGainFlags |= PHONEHOOKSWITCHDEV_SPEAKER; } // // Copy in the provider info if it fits // cbItem = sizeof(TCHAR)*(1+lstrlen(m_StaticInfo.lptszProviderName)); dwNeededSize += cbItem; if ((pbCurrent+cbItem)<=pbEnd) { CopyMemory((LPTSTR) pbCurrent, m_StaticInfo.lptszProviderName, cbItem); lpPhoneCaps->dwProviderInfoSize = cbItem; lpPhoneCaps->dwProviderInfoOffset = (DWORD)(pbCurrent-pbStart); pbCurrent += cbItem; } // // Copy the device name if it fits // cbItem = sizeof(TCHAR)*(1+lstrlen(m_StaticInfo.rgtchDeviceName)); dwNeededSize += cbItem; if ((pbCurrent+cbItem)<=pbEnd) { CopyMemory((LPTSTR) pbCurrent, m_StaticInfo.rgtchDeviceName, cbItem); lpPhoneCaps->dwPhoneNameSize = cbItem; lpPhoneCaps->dwPhoneNameOffset = (DWORD)(pbCurrent-pbStart); pbCurrent += cbItem; } // // Copy phone device Class list if it fits.... // cbItem = mfn_GetPhoneClassListSize(); dwNeededSize += cbItem; if ((pbCurrent+cbItem)<=pbEnd) { CopyMemory( (LPTSTR) pbCurrent, mfn_GetPhoneClassList(), cbItem ); lpPhoneCaps->dwDeviceClassesSize = cbItem; lpPhoneCaps->dwDeviceClassesOffset= (DWORD)(pbCurrent-pbStart); pbCurrent += cbItem; } ASSERT(pbCurrent<=pbEnd); ASSERT(dwNeededSize>= (DWORD)(pbCurrent-pbStart)); lpPhoneCaps->dwNeededSize = dwNeededSize; lpPhoneCaps->dwUsedSize = (DWORD)(pbCurrent-pbStart); SLPRINTF3( psl, "Tot=%u,Used=%lu,Needed=%lu", lpPhoneCaps->dwTotalSize, lpPhoneCaps->dwUsedSize, lpPhoneCaps->dwNeededSize ); ASSERT(*plRet==ERROR_SUCCESS); end: FL_LOG_EXIT(psl, 0); return 0; } // // Initialize default capability structures, such as default linedevcaps // void CTspDev::mfn_init_default_LINEDEVCAPS(void) { #define CAPSFIELD(_field) m_StaticInfo.DevCapsDefault._field ZeroMemory( &(m_StaticInfo.DevCapsDefault), sizeof (m_StaticInfo.DevCapsDefault) ); CAPSFIELD(dwUsedSize) = sizeof(LINEDEVCAPS); CAPSFIELD(dwStringFormat) = STRINGFORMAT_ASCII; CAPSFIELD(dwAddressModes) = LINEADDRESSMODE_ADDRESSID; CAPSFIELD(dwNumAddresses) = 1; CAPSFIELD(dwRingModes) = 1; CAPSFIELD(dwMaxNumActiveCalls) = 1; CAPSFIELD(dwLineStates) = LINEDEVSTATE_CONNECTED | LINEDEVSTATE_DISCONNECTED | LINEDEVSTATE_OPEN | LINEDEVSTATE_CLOSE | LINEDEVSTATE_INSERVICE | LINEDEVSTATE_OUTOFSERVICE | LINEDEVSTATE_REMOVED | LINEDEVSTATE_RINGING | LINEDEVSTATE_REINIT; CAPSFIELD(dwLineFeatures) = LINEFEATURE_MAKECALL; // As required for bug #26507 // [brwill-060700] CAPSFIELD(dwDevCapFlags) = LINEDEVCAPFLAGS_LOCAL; #undef CAPSFIELD } TSPRETURN CTspDev::mfn_get_ADDRESSCAPS ( DWORD dwDeviceID, LPLINEADDRESSCAPS lpAddressCaps, LONG *plRet, CStackLog *psl ) { FL_DECLARE_FUNC(0xed6c4370, "CTspDev::mfn_get_ADDRESSCAPS") // We constuct the AddressCaps on the stack, and if all goes well, // copy it over to *lpAddressCaps. // LINEADDRESSCAPS AddressCaps; FL_LOG_ENTRY(psl); ZeroMemory(&AddressCaps, sizeof(LINEADDRESSCAPS)); AddressCaps.dwTotalSize = lpAddressCaps->dwTotalSize; // Check to see if we have enough memory in the structure. // *plRet = 0; // Assume success; if (AddressCaps.dwTotalSize < sizeof(AddressCaps)) { *plRet = LINEERR_STRUCTURETOOSMALL; FL_SET_RFR(0x72f00800, "ADDRESSCAPS structure too small"); goto end; } AddressCaps.dwLineDeviceID = dwDeviceID; AddressCaps.dwAddressSharing = LINEADDRESSSHARING_PRIVATE; AddressCaps.dwCallInfoStates = LINECALLINFOSTATE_APPSPECIFIC | LINECALLINFOSTATE_MEDIAMODE | LINECALLINFOSTATE_CALLERID; // TODO: From Unimodem/V add: // LINECALLINFOSTATE_MONITORMODES AddressCaps.dwCallerIDFlags = LINECALLPARTYID_UNAVAIL | LINECALLPARTYID_UNKNOWN | LINECALLPARTYID_NAME | LINECALLPARTYID_BLOCKED | LINECALLPARTYID_OUTOFAREA | LINECALLPARTYID_ADDRESS; AddressCaps.dwCalledIDFlags = LINECALLPARTYID_UNAVAIL; AddressCaps.dwConnectedIDFlags = LINECALLPARTYID_UNAVAIL; AddressCaps.dwRedirectionIDFlags = LINECALLPARTYID_UNAVAIL; AddressCaps.dwRedirectingIDFlags = LINECALLPARTYID_UNAVAIL; AddressCaps.dwCallStates = LINECALLSTATE_IDLE | LINECALLSTATE_OFFERING | LINECALLSTATE_ACCEPTED | LINECALLSTATE_DIALTONE | LINECALLSTATE_DIALING | LINECALLSTATE_CONNECTED | LINECALLSTATE_PROCEEDING | LINECALLSTATE_DISCONNECTED | LINECALLSTATE_UNKNOWN; AddressCaps.dwDialToneModes = LINEDIALTONEMODE_UNAVAIL; AddressCaps.dwBusyModes = LINEBUSYMODE_UNAVAIL; AddressCaps.dwSpecialInfo = LINESPECIALINFO_UNAVAIL; AddressCaps.dwDisconnectModes = LINEDISCONNECTMODE_UNAVAIL | LINEDISCONNECTMODE_NORMAL | LINEDISCONNECTMODE_BUSY | LINEDISCONNECTMODE_NODIALTONE | LINEDISCONNECTMODE_NOANSWER; AddressCaps.dwMaxNumActiveCalls = 1; // dwAddrCapFlags if (!mfn_IS_NULL_MODEM()) { AddressCaps.dwAddrCapFlags = LINEADDRCAPFLAGS_DIALED; } if (m_StaticInfo.fPartialDialing) { AddressCaps.dwAddrCapFlags |= LINEADDRCAPFLAGS_PARTIALDIAL; } AddressCaps.dwCallFeatures = LINECALLFEATURE_ANSWER | LINECALLFEATURE_ACCEPT | LINECALLFEATURE_SETCALLPARAMS | LINECALLFEATURE_DIAL | LINECALLFEATURE_DROP; AddressCaps.dwAddressFeatures = LINEADDRFEATURE_MAKECALL; AddressCaps.dwUsedSize = sizeof(LINEADDRESSCAPS); // Note NT4.0 unimodem set AddressCaps->dwMediaModes to // LINEDEV.dwMediaModes, not to .dwDefaultMediaModes. Howerver the // two are always the same in NT4.0 -- neither is changed from its // initial value, created when LINEDEV is created. // AddressCaps.dwAvailableMediaModes = m_StaticInfo.dwDefaultMediaModes; // Get Address class list { UINT cbClassList = mfn_GetAddressClassListSize(); AddressCaps.dwNeededSize = AddressCaps.dwUsedSize + cbClassList; if (AddressCaps.dwTotalSize >= AddressCaps.dwNeededSize) { AddressCaps.dwUsedSize += cbClassList; AddressCaps.dwDeviceClassesSize = cbClassList; AddressCaps.dwDeviceClassesOffset= sizeof(LINEADDRESSCAPS); // Note that we are copying this into the passed in lpAddressCaps... CopyMemory( (LPBYTE)(lpAddressCaps+1), mfn_GetAddressClassList(), cbClassList ); } else { AddressCaps.dwDeviceClassesSize = 0; AddressCaps.dwDeviceClassesOffset= 0; } } // Now copy the AddressCaps structure itself CopyMemory(lpAddressCaps, &AddressCaps, sizeof(AddressCaps)); ASSERT(*plRet==ERROR_SUCCESS); end: FL_LOG_EXIT(psl, 0); return 0; } PFN_CTspDev_TASK_HANDLER // // Utility task handlers // CTspDev::s_pfn_TH_UtilNOOP = &(CTspDev::mfn_TH_UtilNOOP), // // PHONE-specific task handlers // CTspDev::s_pfn_TH_PhoneAsyncTSPICall = &(CTspDev::mfn_TH_PhoneAsyncTSPICall), CTspDev::s_pfn_TH_PhoneSetSpeakerPhoneState = &(CTspDev::mfn_TH_PhoneSetSpeakerPhoneState), // // LINE-specific task handlers // // CTspDev::s_pfn_TH_LineAsyncTSPICall = &(CTspDev::mfn_TH_LineAsyncTSPICall), // // CALL-specific task handlers // CTspDev::s_pfn_TH_CallAnswerCall = &(CTspDev::mfn_TH_CallAnswerCall), CTspDev::s_pfn_TH_CallGenerateDigit = &(CTspDev::mfn_TH_CallGenerateDigit), CTspDev::s_pfn_TH_CallMakeCall = &(CTspDev::mfn_TH_CallMakeCall), CTspDev::s_pfn_TH_CallMakeCall2 = &(CTspDev::mfn_TH_CallMakeCall2), CTspDev::s_pfn_TH_CallMakeTalkDropCall= &(CTspDev::mfn_TH_CallMakeTalkDropCall), CTspDev::s_pfn_TH_CallWaitForDropToGoAway= &(CTspDev::mfn_TH_CallWaitForDropToGoAway), CTspDev::s_pfn_TH_CallDropCall = &(CTspDev::mfn_TH_CallDropCall), CTspDev::s_pfn_TH_CallMakePassthroughCall = &(CTspDev::mfn_TH_CallMakePassthroughCall), CTspDev::s_pfn_TH_CallStartTerminal = &(CTspDev::mfn_TH_CallStartTerminal), CTspDev::s_pfn_TH_CallPutUpTerminalWindow = &(CTspDev::mfn_TH_CallPutUpTerminalWindow), CTspDev::s_pfn_TH_CallSwitchFromVoiceToData = &(CTspDev::mfn_TH_CallSwitchFromVoiceToData), // // LLDEV-specifc task handlers // CTspDev::s_pfn_TH_LLDevStartAIPCAction= &(CTspDev::mfn_TH_LLDevStartAIPCAction), CTspDev::s_pfn_TH_LLDevStopAIPCAction = &(CTspDev::mfn_TH_LLDevStopAIPCAction), CTspDev::s_pfn_TH_LLDevNormalize = &(CTspDev::mfn_TH_LLDevNormalize), CTspDev::s_pfn_TH_LLDevUmMonitorModem = &(CTspDev::mfn_TH_LLDevUmMonitorModem), CTspDev::s_pfn_TH_LLDevUmInitModem = &(CTspDev::mfn_TH_LLDevUmInitModem), CTspDev::s_pfn_TH_LLDevUmDialModem = &(CTspDev::mfn_TH_LLDevUmDialModem), CTspDev::s_pfn_TH_LLDevUmAnswerModem = &(CTspDev::mfn_TH_LLDevUmAnswerModem), CTspDev::s_pfn_TH_LLDevUmHangupModem = &(CTspDev::mfn_TH_LLDevUmHangupModem), CTspDev::s_pfn_TH_LLDevUmWaveAction = &(CTspDev::mfn_TH_LLDevUmWaveAction), CTspDev::s_pfn_TH_LLDevHybridWaveAction = &(CTspDev::mfn_TH_LLDevHybridWaveAction), CTspDev::s_pfn_TH_LLDevUmGenerateDigit = &(CTspDev::mfn_TH_LLDevUmGenerateDigit), CTspDev::s_pfn_TH_LLDevUmGetDiagnostics = &(CTspDev::mfn_TH_LLDevUmGetDiagnostics), CTspDev::s_pfn_TH_LLDevUmSetPassthroughMode = &(CTspDev::mfn_TH_LLDevUmSetPassthroughMode), CTspDev::s_pfn_TH_LLDevUmSetSpeakerPhoneMode = &(CTspDev::mfn_TH_LLDevUmSetSpeakerPhoneMode), CTspDev::s_pfn_TH_LLDevUmSetSpeakerPhoneVolGain = &(CTspDev::mfn_TH_LLDevUmSetSpeakerPhoneVolGain), CTspDev::s_pfn_TH_LLDevUmSetSpeakerPhoneState = &(CTspDev::mfn_TH_LLDevUmSetSpeakerPhoneState), CTspDev::s_pfn_TH_LLDevUmIssueCommand = &(CTspDev::mfn_TH_LLDevUmIssueCommand), CTspDev::s_pfn_TH_LLDevIssueMultipleCommands = &(CTspDev::mfn_TH_LLDevIssueMultipleCommands); BOOL validate_DWORD_aligned_zero_buffer( void *pv, UINT cb ) { DWORD *pdw = (DWORD *) pv; DWORD *pdwEnd = pdw + (cb>>2); // Buffer and count MUST be dword aligned! ASSERT(!(((ULONG_PTR)pv) & 0x3) && !(cb&0x3)); while(pdw<pdwEnd && !*pdw) { pdw++; } return pdw==pdwEnd; } void CTspDev::mfn_GetVoiceProperties ( HKEY hkDrv, CStackLog *psl ) { FL_DECLARE_FUNC(0xb9547d21, "CTspDev::mfn_GetVoiceProperties") DWORD dwRet = 0; DWORD dwData = 0; DWORD dwRegSize = 0; DWORD dwRegType = 0; FL_LOG_ENTRY(psl); ZeroMemory(&m_StaticInfo.Voice, sizeof(m_StaticInfo.Voice)); // // Get the voice-profile flags // dwRegSize = sizeof(DWORD); dwRet = RegQueryValueEx( hkDrv, cszVoiceProfile, NULL, &dwRegType, (BYTE*) &dwData, &dwRegSize); if (dwRet || dwRegType != REG_BINARY) { // no voice operation dwData = 0; // Unimodem/V did this... //dwData = // VOICEPROF_NO_DIST_RING | // VOICEPROF_NO_CALLER_ID | // VOICEPROF_NO_GENERATE_DIGITS | // VOICEPROF_NO_MONITOR_DIGITS; } else { } // 2/26/1997 JosephJ // Unimodem/V implemented call forwarding and distinctive // ring handling. NT5.0 currently doesn't. The // specific property fields that I have not migrated // from unimodem/v are: ForwardDelay and SwitchFeatures. // Look at unimodem/v, umdminit.c for that stuff. // // Same deal with Mixer-related stuff. I don't understand // this and if and when the time comes we can add it. // Look for VOICEPROF_MIXER, GetMixerValues(...), // dwMixer, etc in the unimodem/v sources for mixer- // related stuff. // // Save voice info. // // 3/1/1997 JosephJ // Currently, for 5.0, we just set the CLASS_8 bit. // The following value of VOICEPROF_CLASS8ENABLED is stolen from // unimodem/v file inc\vmodem.h. // TODO: replace this whole scheme by getting back an appropriate // structure from the minidriver, so we don't root around in the // registry and interpret the value of VoiceProfile. // #define VOICEPROF_CLASS8ENABLED 0x00000001 #define VOICEPROF_MODEM_OVERRIDES_HANDSET 0x00200000 #define VOICEPROF_NO_MONITOR_DIGITS 0x00040000 #define VOICEPROF_MONITORS_SILENCE 0x00010000 #define VOICEPROF_NO_GENERATE_DIGITS 0x00020000 #define VOICEPROF_HANDSET 0x00000002 #define VOICEPROF_SPEAKER 0x00000004 #define VOICEPROF_NO_SPEAKER_MIC_MUTE 0x00400000 #define VOICEPROF_NT5_WAVE_COMPAT 0x02000000 // JosephJ 7/14/1997 // Note that on NT4, we explicitly require the // VOICEPROF_NT5_WAVE_COMPAT bit to be set to recognize this as // a class8 modem. if ( (dwData & (VOICEPROF_CLASS8ENABLED|VOICEPROF_NT5_WAVE_COMPAT)) != (VOICEPROF_CLASS8ENABLED|VOICEPROF_NT5_WAVE_COMPAT)) { if (dwData & VOICEPROF_CLASS8ENABLED) { FL_SET_RFR(0x1b053100, "Modem voice capabilities not supported on NT"); } else { FL_SET_RFR(0x9cb1a400, "Modem does not have voice capabilities"); } } else { DWORD dwProp = fVOICEPROP_CLASS_8; // JosephJ 3/20/1998: The code commented out below, between // [UNIMODEM/V] is from unimodem/v // According to brian, this is because cirrus modems // can't be dialed in voice for interactive calls, so // they are dialed in data (even for interactive voice // calls), and hence can't do lineGenerateDigits. // On NT5, we don't disable this here, but do not allow // linegeneratedigits for interactive voice calls if // the VOICEPROF_MODEM_OVERRIDES_HANDSET bit is set. // // [UNIMODEM/V] // // just to be on the safe side // if (dwData & VOICEPROF_MODEM_OVERRIDES_HANDSET) // { // dwData |= VOICEPROF_NO_GENERATE_DIGITS; // // dwData &= ~VOICEPROF_SPEAKER; // } // end [UNIMODEM/V] // // JosephJ: This code is ok... if (dwData & VOICEPROF_MODEM_OVERRIDES_HANDSET) { dwProp |= fVOICEPROP_MODEM_OVERRIDES_HANDSET; } if (!(dwData & VOICEPROF_NO_MONITOR_DIGITS)) { dwProp |= fVOICEPROP_MONITOR_DTMF; } if (dwData & VOICEPROF_MONITORS_SILENCE) { dwProp |= fVOICEPROP_MONITORS_SILENCE; } if (!(dwData & VOICEPROF_NO_GENERATE_DIGITS)) { dwProp |= fVOICEPROP_GENERATE_DTMF; } if (dwData & VOICEPROF_SPEAKER) { dwProp |= fVOICEPROP_SPEAKER; } if (dwData & VOICEPROF_HANDSET) { dwProp |= fVOICEPROP_HANDSET; } if (!(dwData & VOICEPROF_NO_SPEAKER_MIC_MUTE)) { dwProp |= fVOICEPROP_MIKE_MUTE; } // Determine Duplex capability... (hack) { HKEY hkStartDuplex=NULL; dwRet = RegOpenKey(hkDrv, TEXT("StartDuplex"), &hkStartDuplex); if (ERROR_SUCCESS == dwRet) { RegCloseKey(hkStartDuplex); hkStartDuplex=NULL; dwProp |= fVOICEPROP_DUPLEX; SLPRINTF0(psl, "Duplex modem!"); } } m_StaticInfo.Voice.dwProperties = dwProp; m_StaticInfo.dwDefaultMediaModes |= LINEMEDIAMODE_AUTOMATEDVOICE // 8/5/97 Removed | LINEMEDIAMODE_G3FAX // 2/15/98 Added back, in order to // support lineSetMediaMode // 2/20/98 Removed -- not sure if its // required. // // | LINEMEDIAMODE_G3FAX | LINEMEDIAMODE_UNKNOWN; // 2/26/1997 JosephJ // Unimodem/V used helper function GetWaveDriverName to get the // associated wave driver info. This function searched for // the devnode and soforth. On lineGetID(wavein/waveout), // unimodem/v would actually call the wave apis, enumerating // each wave device and doing a waveInGetDevCaps and comparing // the device name with this device's associated device name. // // Note: Unimodem/V appended "handset" and "line" to the root // device name to generate the device names for handset and line. // // TODO: add wave instance ID to list of things // we get from the mini-driver via API. // { HKEY hkWave = NULL; DWORD dwRet2 = RegOpenKey(hkDrv, cszWaveDriver, &hkWave); BOOL fFoundIt=FALSE; if (dwRet2 == ERROR_SUCCESS) { dwRegSize = sizeof(DWORD); dwRet2 = RegQueryValueEx( hkWave, cszWaveInstance, NULL, &dwRegType, (BYTE*) &dwData, &dwRegSize); if (dwRet2==ERROR_SUCCESS && dwRegType == REG_DWORD) { fFoundIt=TRUE; } RegCloseKey(hkWave);hkWave=NULL; } if (fFoundIt) { SLPRINTF1(psl, "WaveInstance=0x%lu", dwData); m_StaticInfo.Voice.dwWaveInstance = dwData; } else { FL_SET_RFR(0x254efe00, "Couldn't get WaveInstance"); m_StaticInfo.Voice.dwWaveInstance = (DWORD)-1; } } } FL_LOG_EXIT(psl, 0); } TSPRETURN CTspDev::mfn_GetDataModemDevCfg( UMDEVCFG *pDevCfg, UINT uSize, UINT *puRequiredSize, BOOL DialIn, CStackLog *psl ) { FL_DECLARE_FUNC(0x896ec204, "mfn_GetDataModemDevCfg") TSPRETURN tspRet = 0; DWORD cbDevCfg = m_Settings.pDialInCommCfg->dwSize + sizeof(UMDEVCFGHDR); FL_LOG_ENTRY(psl); if (puRequiredSize) { *puRequiredSize = cbDevCfg; } if (pDevCfg) { if (uSize >= cbDevCfg) { UMDEVCFGHDR CfgHdr; ZeroMemory(&CfgHdr, sizeof(CfgHdr)); CfgHdr.dwSize = cbDevCfg; CfgHdr.dwVersion = UMDEVCFG_VERSION; CfgHdr.fwOptions = (WORD) m_Settings.dwOptions; CfgHdr.wWaitBong = (WORD) m_Settings.dwWaitBong; SLPRINTF3( psl, " %s: Reporting dwOpt = 0x%04lx; dwBong = 0x%04lx", DialIn ? "DialIn" : "DialOut", m_Settings.dwOptions, m_Settings.dwWaitBong ); // Fill with the default value // // Copy the header // pDevCfg->dfgHdr = CfgHdr; // structure copy // Copy the commconfig // CopyMemory( &(pDevCfg->commconfig), DialIn ? m_Settings.pDialInCommCfg : m_Settings.pDialOutCommCfg, DialIn ? m_Settings.pDialInCommCfg->dwSize : m_Settings.pDialOutCommCfg->dwSize ); } else { tspRet = IDERR_INTERNAL_OBJECT_TOO_SMALL; } } FL_LOG_EXIT(psl, tspRet); return tspRet; } TSPRETURN CTspDev::mfn_SetDataModemDevCfg( UMDEVCFG *pDevCfgNew, BOOL DialIn, CStackLog *psl ) { FL_DECLARE_FUNC(0x864b149d, "SetDataModemConfig") TSPRETURN tspRet = IDERR_GENERIC_FAILURE; FL_LOG_ENTRY(psl); tspRet = CTspDev::mfn_update_devcfg_from_app( pDevCfgNew, pDevCfgNew->dfgHdr.dwSize, DialIn, psl ); FL_LOG_EXIT(psl, tspRet); return tspRet; } void CTspDev::mfn_LineEventProc( HTAPICALL htCall, DWORD dwMsg, ULONG_PTR dwParam1, ULONG_PTR dwParam2, ULONG_PTR dwParam3, CStackLog *psl ) { FL_DECLARE_FUNC(0x672aa19c, "mfn_LineEventProc") LINEINFO *pLine = m_pLine; HTAPILINE htLine = pLine->htLine; SLPRINTF4( psl, "LINEEVENT(0x%lu,0x%lu,0x%lu,0x%lu)", dwMsg, dwParam1, dwParam2, dwParam3 ); if (m_pLLDev && m_pLLDev->IsLoggingEnabled()) { char rgchName[128]; rgchName[0] = 0; UINT cbBuf = DumpLineEventProc( 0, // dwInstance(unused) 0, // dwFlags dwMsg, (DWORD)dwParam1, (DWORD)dwParam2, (DWORD)dwParam3, rgchName, sizeof(rgchName)/sizeof(*rgchName), NULL, 0 ); if (*rgchName) { m_StaticInfo.pMD->LogStringA( m_pLLDev->hModemHandle, LOG_FLAG_PREFIX_TIMESTAMP, rgchName, NULL ); } } if (m_StaticInfo.hExtBinding) { m_StaticInfo.pMD->ExtTspiLineEventProc( m_StaticInfo.hExtBinding, htLine, htCall, dwMsg, dwParam1, dwParam2, dwParam3 ); } else { pLine->lpfnEventProc( htLine, htCall, dwMsg, dwParam1, dwParam2, dwParam3 ); } } void CTspDev::mfn_PhoneEventProc( DWORD dwMsg, ULONG_PTR dwParam1, ULONG_PTR dwParam2, ULONG_PTR dwParam3, CStackLog *psl ) { FL_DECLARE_FUNC(0xc25a41c7, "mfn_PhoneEventProc") SLPRINTF4( psl, "PHONEEVENT(0x%lu,0x%lu,0x%lu,0x%lu)", dwMsg, dwParam1, dwParam2, dwParam3 ); if (!m_pPhone) { ASSERT(FALSE); goto end; } if (m_pLLDev && m_pLLDev->IsLoggingEnabled()) { char rgchName[128]; rgchName[0] = 0; UINT cbBuf = DumpPhoneEventProc( 0, // Instance (unused) 0, // dwFlags dwMsg, (DWORD)dwParam1, (DWORD)dwParam2, (DWORD)dwParam3, rgchName, sizeof(rgchName)/sizeof(*rgchName), NULL, 0 ); if (*rgchName) { m_StaticInfo.pMD->LogStringA( m_pLLDev->hModemHandle, LOG_FLAG_PREFIX_TIMESTAMP, rgchName, NULL ); } } m_pPhone->lpfnEventProc( m_pPhone->htPhone, dwMsg, dwParam1, dwParam2, dwParam3 ); end: return; } void CTspDev::mfn_TSPICompletionProc( DRV_REQUESTID dwRequestID, LONG lResult, CStackLog *psl ) { FL_DECLARE_FUNC(0x9dd08553, "CTspDev::mfn_TSPICompletionProc") FL_LOG_ENTRY(psl); if (m_pLLDev && m_pLLDev->IsLoggingEnabled()) { char rgchName[128]; rgchName[0] = 0; UINT cbBuf = DumpTSPICompletionProc( 0, // Instance (unused) 0, // dwFlags dwRequestID, lResult, rgchName, sizeof(rgchName)/sizeof(*rgchName), NULL, 0 ); if (*rgchName) { m_StaticInfo.pMD->LogStringA( m_pLLDev->hModemHandle, LOG_FLAG_PREFIX_TIMESTAMP, rgchName, NULL ); } } if (m_StaticInfo.hExtBinding) { FL_SET_RFR(0x1b3f6d00, "Calling ExtTspiAsyncCompletion"); m_StaticInfo.pMD->ExtTspiAsyncCompletion( m_StaticInfo.hExtBinding, dwRequestID, lResult ); } else { FL_SET_RFR(0xd89afb00, "Calling pfnTapiCompletionProc"); m_StaticInfo.pfnTAPICompletionProc(dwRequestID, lResult); } FL_LOG_EXIT(psl, 0); } void CTspDev::NotifyDefaultConfigChanged(CStackLog *psl) { TSPRETURN tspRet = 0; FL_DECLARE_FUNC(0x4b8c1643, "CTspDev::NotifyDefaultConfigChanged") FL_LOG_ENTRY(psl); m_sync.EnterCrit(FL_LOC); BYTE rgbCommCfgBuf[sizeof(m_Settings.rgbCommCfgBuf)]; DWORD dwcbSize = sizeof(rgbCommCfgBuf); COMMCONFIG *pDefCommCfg = (COMMCONFIG *) rgbCommCfgBuf; { HKEY hKey=NULL; DWORD dwRet = RegOpenKeyA( HKEY_LOCAL_MACHINE, m_StaticInfo.rgchDriverKey, &hKey ); if (dwRet!=ERROR_SUCCESS) { FL_SET_RFR(0x6e834e00, "Couldn't open driverkey!"); goto end; } // // If we support nvram init, check if we must re-do nvram init... // if (mfn_CanDoNVRamInit()) { if (!get_volatile_key_value(hKey)) { // // zero value indicates that we need to re-init // nvram. // mfn_SetNeedToInitNVRam(); } } dwRet = UmRtlGetDefaultCommConfig( hKey, pDefCommCfg, &dwcbSize ); RegCloseKey(hKey); hKey=NULL; if (dwRet != ERROR_SUCCESS) { FL_SET_RFR(0x5cce0a00, "UmRtlGetDefaultCommConfig fails"); tspRet = FL_GEN_RETVAL(IDERR_REG_CORRUPT); goto end; } } // // Only change a few things in the dialout config // { // selective copy.... LPMODEMSETTINGS pMSFrom = (LPMODEMSETTINGS) (pDefCommCfg->wcProviderData); LPMODEMSETTINGS pMSTo = (LPMODEMSETTINGS) (m_Settings.pDialOutCommCfg->wcProviderData); // speaker volume & mode... pMSTo->dwSpeakerMode = pMSFrom->dwSpeakerMode; pMSTo->dwSpeakerVolume = pMSFrom->dwSpeakerVolume; // set Blind-dial bit... pMSTo->dwPreferredModemOptions &= ~MDM_BLIND_DIAL; pMSTo->dwPreferredModemOptions |= (pMSFrom->dwPreferredModemOptions &MDM_BLIND_DIAL); // max port speed (TBD) } // // completely replace dialin config // CopyMemory(m_Settings.pDialInCommCfg, pDefCommCfg, dwcbSize); // re-init modem with new settings if the // line is open for monitoring and no call in progress if (m_pLine && m_pLine->IsMonitoring() && !m_pLine->pCall) { ASSERT(m_pLLDev); // // TODO: this is a bit hacky way of forcing a re-init .. need // to make things more straightforward... // m_pLLDev->fModemInited=FALSE; TSPRETURN tspRet2 = mfn_StartRootTask( &CTspDev::s_pfn_TH_LLDevNormalize, &m_pLLDev->fLLDevTaskPending, 0, // Param1 0, // Param2 psl ); if (IDERR(tspRet2)==IDERR_TASKPENDING) { // can't do this now, we've got to defer it! m_pLLDev->SetDeferredTaskBits(LLDEVINFO::fDEFERRED_NORMALIZE); tspRet2 = 0; } } end: m_sync.LeaveCrit(FL_LOC); FL_LOG_EXIT(psl, tspRet); } typedef struct { DWORD dwClassToken; LPCTSTR ptszClass; } CLASSREC; const CLASSREC ClassRec[] = { {DEVCLASS_TAPI_LINE, TEXT("tapi/line")}, {DEVCLASS_TAPI_PHONE, TEXT("tapi/phone")}, {DEVCLASS_COMM, TEXT("comm")}, {DEVCLASS_COMM_DATAMODEM, TEXT("comm/datamodem")}, {DEVCLASS_COMM_DATAMODEM_PORTNAME, TEXT("comm/datamodem/portname")}, {DEVCLASS_COMM_EXTENDEDCAPS, TEXT("comm/extendedcaps")}, {DEVCLASS_WAVE_IN, TEXT("wave/in")}, {DEVCLASS_WAVE_OUT, TEXT("wave/out")}, {DEVCLASS_TAPI_LINE_DIAGNOSTICS, TEXT("tapi/line/diagnostics")}, {DEVCLASS_COMM_DATAMODEM_DIALIN, TEXT("comm/datamodem/dialin")}, {DEVCLASS_COMM_DATAMODEM_DIALOUT, TEXT("comm/datamodem/dialout")}, {DEVCLASS_UNKNOWN, NULL} // MUST be last (sentinel) }; UINT gen_device_classes( DWORD dwClasses, BOOL fMultiSz, LPTSTR lptsz, UINT cch );; DWORD parse_device_classes(LPCTSTR ptszClasses, BOOL fMultiSz); UINT gen_device_classes( DWORD dwClasses, BOOL fMultiSz, LPTSTR lptsz, UINT cch ) // // If cch=0 is passed in, will not derefernce lptsz and will return // the required length. Else it will try to copy over if there is enough // space. If there is not enough space it will return 0. // // If it does copy over, it will tack on an extra '\0' at the end of the // string iff fMultiSz is specified. // // Both cb and the return value is the size in TCHARS, including // any terminating null char required. // // If dwClasses contains an unknown class, it will return 0 (fail). // { DWORD cchRequired=0; const CLASSREC *pcr = NULL; BOOL fError = FALSE; // 1st round: calculate required size... for ( DWORD dw = 0x1, dwTmp = dwClasses; dwTmp && (fMultiSz || !pcr); (dwTmp&=~dw), (dw<<=1)) { if (dw & dwTmp) { // // search through array... // The last token in the array is a sentinal, and // therefore has dwClassToken == DEVCLASS_UNKNOWN // for ( pcr = ClassRec; pcr->dwClassToken != DEVCLASS_UNKNOWN; pcr++ ) { if ((dw & dwTmp) == pcr->dwClassToken) { cchRequired += lstrlen(pcr->ptszClass)+1; break; } } if (pcr->dwClassToken == DEVCLASS_UNKNOWN) { // didn't find this token! // fError = TRUE; break; } } } if (!pcr || fError || (!fMultiSz && pcr->dwClassToken != dwClasses)) { // Didn't find anything and/or invalid tokens... cchRequired = 0; goto end; } if (fMultiSz) { // Add an extra zero... cchRequired++; } if (!cch) goto end; // Just report cchRequired... if (cch<cchRequired) { // not enough space, go to end... cchRequired = 0; goto end; } // 2nd round -- actually construct the strings... if (!fMultiSz) { // For the single case, we already have a pointer to // the pch... CopyMemory(lptsz, pcr->ptszClass, cchRequired*sizeof(*pcr->ptszClass)); goto end; } // fMultiSz case ... for ( dw = 0x1, dwTmp = dwClasses; dwTmp; (dwTmp&=~dw), (dw<<=1)) { if (dw & dwTmp) { // // search through array... // The last token in the array is a sentinal, and // therefore has dwClassToken == DEVCLASS_UNKNOWN // for ( pcr = ClassRec; pcr->dwClassToken != DEVCLASS_UNKNOWN; pcr++ ) { if ((dw & dwTmp) == pcr->dwClassToken) { UINT cchCur = lstrlen(pcr->ptszClass)+1; CopyMemory(lptsz, pcr->ptszClass, cchCur*sizeof(TCHAR)); lptsz += cchCur; break; } } } } *lptsz = 0; // Add extra null at the end... end: return cchRequired; } DWORD parse_device_classes(LPCTSTR ptszClasses, BOOL fMultiSz) { DWORD dwClasses = 0; if (!ptszClasses || !*ptszClasses) goto end; do { UINT cchCur = lstrlen(ptszClasses); // // search through array... // The last token in the array is a sentinal, and // therefore has dwClassToken == DEVCLASS_UNKNOWN // for ( const CLASSREC *pcr = ClassRec; pcr->dwClassToken != DEVCLASS_UNKNOWN; pcr++ ) { if (!lstrcmpi(ptszClasses, pcr->ptszClass)) { dwClasses |= pcr->dwClassToken; break; } } if (pcr->dwClassToken == DEVCLASS_UNKNOWN) { // didn't find this token -- return 0 for error. dwClasses = 0; break; } ptszClasses += cchCur+1; } while (fMultiSz && *ptszClasses); end: return dwClasses; } UINT CTspDev::mfn_IsCallDiagnosticsEnabled(void) { return m_Settings.dwDiagnosticSettings & fSTANDARD_CALL_DIAGNOSTICS; } void CTspDev::ActivateLineDevice( DWORD dwLineID, CStackLog *psl ) { m_sync.EnterCrit(NULL); m_StaticInfo.dwTAPILineID = dwLineID; if (m_StaticInfo.pMD->ExtIsEnabled()) { // 10/13/1997 JosephJ We DO NOT leave the crit section before // calling into the extension DLL. The semantics of UmExControl are // such that the extension DLL is to expect that the TSP has the // critical section held. m_StaticInfo.pMD->ExtControl( m_StaticInfo.hExtBinding, UMEXTCTRL_DEVICE_STATE, UMEXTPARAM_ACTIVATE_LINE_DEVICE, dwLineID, 0 ); } m_sync.LeaveCrit(NULL); } void CTspDev::ActivatePhoneDevice( DWORD dwPhoneID, CStackLog *psl ) { m_sync.EnterCrit(NULL); m_StaticInfo.dwTAPIPhoneID = dwPhoneID; if (m_StaticInfo.pMD->ExtIsEnabled()) { // 10/13/1997 JosephJ We DO NOT leave the crit section before // calling into the extension DLL. The semantics of UmExControl are // such that the extension DLL is to expect that the TSP has the // critical section held. m_StaticInfo.pMD->ExtControl( m_StaticInfo.hExtBinding, UMEXTCTRL_DEVICE_STATE, UMEXTPARAM_ACTIVATE_PHONE_DEVICE, dwPhoneID, 0 ); } m_sync.LeaveCrit(NULL); } void CTspDev::mfn_ProcessResponse( ULONG_PTR dwRespCode, LPSTR lpszResp, CStackLog *psl ) { FL_DECLARE_FUNC(0x6b8ddbbb, "ProcessResponse") FL_LOG_ENTRY(psl); if (dwRespCode == RESPONSE_CONNECT && mfn_IsCallDiagnosticsEnabled()) { mfn_AppendDiagnostic( DT_MDM_RESP_CONNECT, (BYTE*)lpszResp, lstrlenA(lpszResp) ); } FL_LOG_EXIT(psl, 0); } void CTspDev::mfn_HandleRootTaskCompletedAsync(BOOL *pfEndUnload, CStackLog *psl) { TSPRETURN tspRet = 0; *pfEndUnload = FALSE; do { tspRet = IDERR_SAMESTATE; // // Note -- each time through, m_pLine, m_pPhone or m_pLLDev // may or may not be NULL. // if (m_pLine) { tspRet = mfn_TryStartLineTask(psl); } if (m_pPhone && IDERR(tspRet) != IDERR_PENDING) { tspRet = mfn_TryStartPhoneTask(psl); } if (m_pLLDev && IDERR(tspRet) != IDERR_PENDING) { tspRet = mfn_TryStartLLDevTask(psl); } } while (IDERR(tspRet)!=IDERR_SAMESTATE && IDERR(tspRet)!=IDERR_PENDING); if ( m_fUnloadPending && IDERR(tspRet) != IDERR_PENDING && !m_pLine && !m_pPhone && !m_pLLDev) { *pfEndUnload = TRUE; } } void CTspDev::DumpState( CStackLog *psl ) { FL_DECLARE_FUNC(0x9a8df7e6, "CTspDev::DumpState") FL_LOG_ENTRY(psl); char szName[128]; m_sync.EnterCrit(NULL); UINT cb = WideCharToMultiByte( CP_ACP, 0, m_StaticInfo.rgtchDeviceName, -1, szName, sizeof(szName), NULL, NULL ); if (!cb) { CopyMemory(szName, "<unknown>", sizeof("<unknown>")); } SLPRINTF1( psl, "Name = %s", szName ); mfn_dump_global_state(psl); mfn_dump_line_state(psl); mfn_dump_phone_state(psl); mfn_dump_lldev_state(psl); mfn_dump_task_state(psl); m_sync.LeaveCrit(NULL); FL_LOG_EXIT(psl, 0); } void CTspDev::mfn_dump_global_state( CStackLog *psl ) { FL_DECLARE_FUNC(0x296438cf, "GLOBAL STATE:") SLPRINTF3( psl, "&m_Settings=0x%08lx; m_pLLDev=0x%08lx; m_pLine=0x%08lx", &m_Settings, m_pLLDev, m_pLine ); } void CTspDev::mfn_dump_line_state( CStackLog *psl ) { FL_DECLARE_FUNC(0xa038177f, "LINE STATE:") FL_LOG_ENTRY(psl); if (m_pLine) { if (m_pLine->pCall) { SLPRINTF1(psl, "m_pLine->pCall=0x%08lx", m_pLine->pCall); } } FL_LOG_EXIT(psl, 0); } void CTspDev::mfn_dump_phone_state( CStackLog *psl ) { FL_DECLARE_FUNC(0x22f22a59, "PHONE STATE:") FL_LOG_ENTRY(psl); FL_LOG_EXIT(psl, 0); } void CTspDev::mfn_dump_lldev_state( CStackLog *psl ) { FL_DECLARE_FUNC(0x68c9e1e1, "LLDEV STATE:") FL_LOG_ENTRY(psl); FL_LOG_EXIT(psl, 0); } TSPRETURN CTspDev::mfn_update_devcfg_from_app( UMDEVCFG *pDevCfgNew, UINT cbDevCfgNew, BOOL DialIn, CStackLog *psl ) { FL_DECLARE_FUNC(0xcf159c50, "xxxx") TSPRETURN tspRet = IDERR_GENERIC_FAILURE; COMMCONFIG *pCCNew = &(pDevCfgNew->commconfig); COMMCONFIG *pCCCur = DialIn ? m_Settings.pDialInCommCfg : m_Settings.pDialOutCommCfg; BOOL ConfigChanged=TRUE; FL_LOG_ENTRY(psl); if (cbDevCfgNew < sizeof(UMDEVCFGHDR) || pDevCfgNew->dfgHdr.dwVersion != UMDEVCFG_VERSION || pDevCfgNew->dfgHdr.dwSize != cbDevCfgNew) { FL_SET_RFR(0x25423f00, "Invalid DevCfg specified"); goto end; } // In NT4.0 the following were asserts. For NT5.0 we convert // them to parameter validation tests, because the commconfig // is specified by the app and hence can be a bogus structure. // if ( pCCNew->wVersion != pCCCur->wVersion || pCCNew->dwProviderSubType != pCCCur->dwProviderSubType || pCCNew->dwProviderSize != pCCCur->dwProviderSize ) { FL_SET_RFR(0x947cc100, "Invalid COMMCONFIG specified"); goto end; } // Extract settings and waitbong. m_Settings.dwOptions = pDevCfgNew->dfgHdr.fwOptions; m_Settings.dwWaitBong = pDevCfgNew->dfgHdr.wWaitBong; SLPRINTF3( psl, " %s New dwOpt = 0x%04lx; dwBong = 0x%04lx", DialIn ? "Dialin" : "Dialout", m_Settings.dwOptions, m_Settings.dwWaitBong ); // Copy over selected parts of commconfig (taken from // NT4.0 unimodem) { DWORD dwProvSize = pCCCur->dwProviderSize; BYTE *pbSrc = ((LPBYTE)pCCNew) + pCCNew->dwProviderOffset; BYTE *pbDest = ((LPBYTE) pCCCur) + pCCCur->dwProviderOffset; { PMODEMSETTINGS ms=(PMODEMSETTINGS)(((LPBYTE)pCCNew) + pCCNew->dwProviderOffset); SLPRINTF1( psl, "options=%08lx", ms->dwPreferredModemOptions); } if (((memcmp((PBYTE)&pCCCur->dcb,(PBYTE)&pCCNew->dcb,sizeof(pCCCur->dcb)) == 0) && (memcmp(pbDest, pbSrc, dwProvSize) == 0))) { ConfigChanged=FALSE; } // TODO: although NT4.0 unimodem simply copied the dcb // and other info and so do we here, we should think about // doing a more careful and selective copy here... pCCCur->dcb = pCCNew->dcb; // structure copy. if (!pCCCur->dcb.BaudRate) { // JosephJ Todo: clean out all this stuff post-beta. // DebugBreak(); } CopyMemory(pbDest, pbSrc, dwProvSize); } if (DialIn) { // // update default config for dialin change // HKEY hKey=NULL; DWORD dwRet = RegOpenKeyA( HKEY_LOCAL_MACHINE, m_StaticInfo.rgchDriverKey, &hKey ); if (dwRet == ERROR_SUCCESS) { UmRtlSetDefaultCommConfig( hKey, m_Settings.pDialInCommCfg, m_Settings.pDialInCommCfg->dwSize ); RegCloseKey(hKey); hKey=NULL; } } // // re-init modem with new settings if the // line is open for monitoring and no call in progress // // DebugBreak(); if (m_pLine && m_pLLDev && ConfigChanged && DialIn) { // // TODO: this is a bit hacky way of forcing a re-init .. need // to make things more straightforward... // m_pLLDev->fModemInited=FALSE; if (m_pLine->IsMonitoring() && !m_pLine->pCall) { TSPRETURN tspRet2 = mfn_StartRootTask( &CTspDev::s_pfn_TH_LLDevNormalize, &m_pLLDev->fLLDevTaskPending, 0, // Param1 0, // Param2 psl ); if (IDERR(tspRet2)==IDERR_TASKPENDING) { // can't do this now, we've got to defer it! m_pLLDev->SetDeferredTaskBits(LLDEVINFO::fDEFERRED_NORMALIZE); tspRet2 = 0; } } } // // Set the bit... // Onse set, this bit doesn't get cleared until provider shutdown! // #ifdef OLD_COMMCONFIG m_Settings.fConfigUpdatedByApp = TRUE; #endif FL_SET_RFR(0x94fadd00, "Success; set fConfigUpdatedByApp."); tspRet = 0; end: FL_LOG_EXIT(psl, 0); return tspRet; } void CTspDev::NotifyDeviceRemoved( CStackLog *psl ) // // HW has been removed. // { m_sync.EnterCrit(0); if (m_pLLDev && m_StaticInfo.pMD) // pMD may be NULL if we're unloading! { // // If there is no current modem command this does nothing. // m_StaticInfo.pMD->AbortCurrentModemCommand( m_pLLDev->hModemHandle, psl ); m_pLLDev->fDeviceRemoved = TRUE; } m_sync.LeaveCrit(0); } DWORD get_volatile_key_value(HKEY hkParent) { HKEY hkVolatile = NULL; DWORD dw = 0; DWORD dwRet = RegOpenKeyEx( hkParent, TEXT("VolatileSettings"), 0, KEY_READ, &hkVolatile ); if (dwRet==ERROR_SUCCESS) { DWORD cbSize = sizeof(dw); DWORD dwRegType = 0; dwRet = RegQueryValueEx( hkVolatile, TEXT("NVInited"), NULL, &dwRegType, (BYTE*) &dw, &cbSize ); if ( dwRet!=ERROR_SUCCESS || dwRegType != REG_DWORD) { dw=0; } RegCloseKey(hkVolatile); hkVolatile=NULL; } return dw; } // // Following is the template of UnimodemGetExtendedCaps ... // typedef DWORD (*PFNEXTCAPS)( IN HKEY hKey, IN OUT LPDWORD pdwTotalSize, OUT MODEM_CONFIG_HEADER *pFirstObj // OPTIONAL ); LONG CTspDev::mfn_GetCOMM_EXTENDEDCAPS( LPVARSTRING lpDeviceConfig, CStackLog *psl ) { // New in NT5.0 // Process call/diagnostics configuration // // NOTE: we dynamically load modemui.dll here because we don't expect // this call to be called too often and no one else in the TSP uses any // functions in modemui.dll. // HKEY hKey=NULL; DWORD dwRet = 0; LONG lRet = LINEERR_OPERATIONFAILED; DWORD cbSize=0; TCHAR szLib[MAX_PATH]; HINSTANCE hInst = NULL; PFNEXTCAPS pfnExtCaps = NULL; lstrcpy(szLib,TEXT("modemui.dll")); hInst = LoadLibrary(szLib); lpDeviceConfig->dwStringSize = 0; lpDeviceConfig->dwStringOffset = 0; lpDeviceConfig->dwUsedSize = sizeof(VARSTRING); lpDeviceConfig->dwStringFormat = STRINGFORMAT_BINARY; lpDeviceConfig->dwNeededSize = sizeof(VARSTRING); if (!hInst) goto end; pfnExtCaps = (PFNEXTCAPS) GetProcAddress(hInst, "UnimodemGetExtendedCaps"); if (!pfnExtCaps) goto end; dwRet = RegOpenKeyA( HKEY_LOCAL_MACHINE, m_StaticInfo.rgchDriverKey, &hKey ); if (dwRet!=ERROR_SUCCESS) { hKey = NULL; goto end; } cbSize = 0; dwRet = (pfnExtCaps)( hKey, &cbSize, NULL ); if (ERROR_SUCCESS==dwRet) { if (cbSize) { MODEM_PROTOCOL_CAPS *pMPC = (MODEM_PROTOCOL_CAPS *) (((LPBYTE)lpDeviceConfig) + sizeof(VARSTRING)); lpDeviceConfig->dwNeededSize += cbSize; if (lpDeviceConfig->dwTotalSize < lpDeviceConfig->dwNeededSize) { // // Not enough space. // lRet = 0; goto end; } dwRet = (pfnExtCaps)( hKey, &cbSize, (MODEM_CONFIG_HEADER*) pMPC ); if (ERROR_SUCCESS==dwRet) { // // Success .... // lRet = 0; lpDeviceConfig->dwUsedSize = lpDeviceConfig->dwNeededSize; lpDeviceConfig->dwStringSize = cbSize; lpDeviceConfig->dwStringOffset = sizeof(VARSTRING); } } else { lRet = LINEERR_INVALDEVICECLASS; } } end: if (hKey) { RegCloseKey(hKey); hKey=NULL; } if (hInst) { FreeLibrary(hInst); hInst = NULL; } return lRet; }
30.29955
112
0.514763
npocmaka
5817d21a902758a2d814667fff36a5afe49922cc
1,298
cpp
C++
CSE 225L Data Structures and Algorithms/Resources/Codes Previous/Spring-2019-CSE225 1/Lab 3 (Operator Overloading)/complex(17).cpp
diptu/Teaching
20655bb2c688ae29566b0a914df4a3e5936a2f61
[ "MIT" ]
null
null
null
CSE 225L Data Structures and Algorithms/Resources/Codes Previous/Spring-2019-CSE225 1/Lab 3 (Operator Overloading)/complex(17).cpp
diptu/Teaching
20655bb2c688ae29566b0a914df4a3e5936a2f61
[ "MIT" ]
null
null
null
CSE 225L Data Structures and Algorithms/Resources/Codes Previous/Spring-2019-CSE225 1/Lab 3 (Operator Overloading)/complex(17).cpp
diptu/Teaching
20655bb2c688ae29566b0a914df4a3e5936a2f61
[ "MIT" ]
null
null
null
#include "complex.h" Complex::Complex (float r, float i){ real_ = r; imaginary_ = i; } Complex Complex::operator= (const Complex& rhs){ real_ = rhs.real_; imaginary_ = rhs.imaginary_; return *this; } Complex Complex::operator+ (const Complex& rhs) const{ Complex result = *this; result.real_ += rhs.real_; result.imaginary_ += rhs.imaginary_; return result; } Complex Complex::operator- (const Complex& rhs) const{ Complex result = *this; result.real_ -= rhs.real_; result.imaginary_ -= rhs.imaginary_; return result; } Complex Complex::operator* (const Complex& rhs) const{ Complex result = *this; // this-> == *this == (*this) result.real_ = real_ * rhs.real_ - imaginary_ * rhs.imaginary_; //cout << result.real_ << "R " << result.imaginary_ << "I "<< "|" << rhs.real_ << "R " << rhs.imaginary_ << "I\n"; result.imaginary_ = (real_ * rhs.imaginary_) + (rhs.real_ * imaginary_); //cout << result.real_ << "R " << result.imaginary_ << "I "<< "|" << rhs.real_ << "R " << rhs.imaginary_ << "I\n"; return result; } string Complex::toString() const { stringstream ss; if (imaginary_ > 0){ ss << real_ << " + " << imaginary_ << "i"; } else { ss << real_ << " " << imaginary_ << "i"; } return ss.str(); }
27.617021
118
0.600154
diptu
58184149af52448b444bc84e266085bfc407fbcd
7,749
cc
C++
chrome/plugin/command_buffer_stub.cc
Gitman1989/chromium
2b1cceae1075ef012fb225deec8b4c8bbe4bc897
[ "BSD-3-Clause" ]
2
2017-09-02T19:08:28.000Z
2021-11-15T15:15:14.000Z
chrome/plugin/command_buffer_stub.cc
Gitman1989/chromium
2b1cceae1075ef012fb225deec8b4c8bbe4bc897
[ "BSD-3-Clause" ]
null
null
null
chrome/plugin/command_buffer_stub.cc
Gitman1989/chromium
2b1cceae1075ef012fb225deec8b4c8bbe4bc897
[ "BSD-3-Clause" ]
1
2020-04-13T05:45:10.000Z
2020-04-13T05:45:10.000Z
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/callback.h" #include "base/scoped_open_process.h" #include "base/shared_memory.h" #include "chrome/common/gpu_messages.h" #include "chrome/common/plugin_messages.h" #include "chrome/plugin/command_buffer_stub.h" #include "chrome/plugin/plugin_channel.h" using gpu::Buffer; CommandBufferStub::CommandBufferStub(PluginChannel* channel, int plugin_host_route_id, gfx::PluginWindowHandle window) : channel_(channel), plugin_host_route_id_(plugin_host_route_id), window_(window) { route_id_ = channel->GenerateRouteID(); channel->AddRoute(route_id_, this, NULL); } CommandBufferStub::~CommandBufferStub() { Destroy(); channel_->RemoveRoute(route_id_); } void CommandBufferStub::OnMessageReceived(const IPC::Message& message) { IPC_BEGIN_MESSAGE_MAP(CommandBufferStub, message) IPC_MESSAGE_HANDLER(GpuCommandBufferMsg_Initialize, OnInitialize); IPC_MESSAGE_HANDLER(GpuCommandBufferMsg_GetState, OnGetState); IPC_MESSAGE_HANDLER(GpuCommandBufferMsg_AsyncGetState, OnAsyncGetState); IPC_MESSAGE_HANDLER(GpuCommandBufferMsg_Flush, OnFlush); IPC_MESSAGE_HANDLER(GpuCommandBufferMsg_AsyncFlush, OnAsyncFlush); IPC_MESSAGE_HANDLER(GpuCommandBufferMsg_CreateTransferBuffer, OnCreateTransferBuffer); IPC_MESSAGE_HANDLER(GpuCommandBufferMsg_DestroyTransferBuffer, OnDestroyTransferBuffer); IPC_MESSAGE_HANDLER(GpuCommandBufferMsg_GetTransferBuffer, OnGetTransferBuffer); #if defined(OS_MACOSX) IPC_MESSAGE_HANDLER(GpuCommandBufferMsg_SetWindowSize, OnSetWindowSize); #endif IPC_MESSAGE_UNHANDLED_ERROR() IPC_END_MESSAGE_MAP() } void CommandBufferStub::OnChannelError() { NOTREACHED() << "CommandBufferService::OnChannelError called"; } bool CommandBufferStub::Send(IPC::Message* message) { if (!channel_) { delete message; return false; } return channel_->Send(message); } void CommandBufferStub::NotifyRepaint() { Send(new GpuCommandBufferMsg_NotifyRepaint(route_id_)); } void CommandBufferStub::OnInitialize(int32 size, base::SharedMemoryHandle* ring_buffer) { DCHECK(!command_buffer_.get()); *ring_buffer = base::SharedMemory::NULLHandle(); // Assume service is responsible for duplicating the handle from the calling // process. base::ScopedOpenProcess peer_process; if (!peer_process.Open(channel_->peer_pid())) return; command_buffer_.reset(new gpu::CommandBufferService); // Initialize the CommandBufferService. if (!command_buffer_->Initialize(size)) { Destroy(); return; } // Get the ring buffer. Buffer buffer = command_buffer_->GetRingBuffer(); if (!buffer.shared_memory) { Destroy(); return; } // Initialize the GPUProcessor. processor_.reset(new gpu::GPUProcessor(command_buffer_.get(), NULL)); if (!processor_->Initialize(window_, gfx::Size(), NULL, std::vector<int32>(), NULL, 0)) { Destroy(); return; } // Perform platform specific initialization. if (!InitializePlatformSpecific()) { Destroy(); return; } // Share the ring buffer to the client process. if (!buffer.shared_memory->ShareToProcess(peer_process.handle(), ring_buffer)) { Destroy(); return; } // Setup callbacks for events. command_buffer_->SetPutOffsetChangeCallback( NewCallback(processor_.get(), &gpu::GPUProcessor::ProcessCommands)); #if defined(OS_MACOSX) processor_->SetSwapBuffersCallback( NewCallback(this, &CommandBufferStub::SwapBuffersCallback)); processor_->SetTransportDIBAllocAndFree( NewCallback(this, &CommandBufferStub::AllocTransportDIB), NewCallback(this, &CommandBufferStub::FreeTransportDIB)); #endif } void CommandBufferStub::OnGetState(gpu::CommandBuffer::State* state) { *state = command_buffer_->GetState(); } void CommandBufferStub::OnAsyncGetState() { gpu::CommandBuffer::State state = command_buffer_->GetState(); Send(new GpuCommandBufferMsg_UpdateState(route_id_, state)); } void CommandBufferStub::OnFlush(int32 put_offset, gpu::CommandBuffer::State* state) { *state = command_buffer_->Flush(put_offset); } void CommandBufferStub::OnAsyncFlush(int32 put_offset) { gpu::CommandBuffer::State state = command_buffer_->Flush(put_offset); Send(new GpuCommandBufferMsg_UpdateState(route_id_, state)); } void CommandBufferStub::OnCreateTransferBuffer(int32 size, int32* id) { *id = command_buffer_->CreateTransferBuffer(size); } void CommandBufferStub::OnDestroyTransferBuffer(int32 id) { command_buffer_->DestroyTransferBuffer(id); } void CommandBufferStub::OnGetTransferBuffer( int32 id, base::SharedMemoryHandle* transfer_buffer, uint32* size) { *transfer_buffer = base::SharedMemoryHandle(); *size = 0; // Assume service is responsible for duplicating the handle to the calling // process. base::ProcessHandle peer_handle; if (!base::OpenProcessHandle(channel_->peer_pid(), &peer_handle)) return; Buffer buffer = command_buffer_->GetTransferBuffer(id); if (buffer.shared_memory) { buffer.shared_memory->ShareToProcess(peer_handle, transfer_buffer); *size = buffer.shared_memory->created_size(); } base::CloseProcessHandle(peer_handle); } void CommandBufferStub::Destroy() { processor_.reset(); command_buffer_.reset(); DestroyPlatformSpecific(); } #if !defined(OS_WIN) bool CommandBufferStub::InitializePlatformSpecific() { return true; } void CommandBufferStub::DestroyPlatformSpecific() { } #endif // defined(OS_WIN) #if defined(OS_MACOSX) void CommandBufferStub::OnSetWindowSize(const gfx::Size& size) { // Try using the IOSurface version first. bool notify_repaint = false; uint64 new_backing_store = processor_->SetWindowSizeForIOSurface(size); if (new_backing_store) { Send(new PluginHostMsg_AcceleratedSurfaceSetIOSurface( plugin_host_route_id_, window_, size.width(), size.height(), new_backing_store)); notify_repaint = true; } else { // If |new_backing_store| is 0, it might mean that the IOSurface APIs are // not available. In this case, see if TransportDIBs are supported. TransportDIB::Handle transport_dib = processor_->SetWindowSizeForTransportDIB(size); if (TransportDIB::is_valid(transport_dib)) { Send(new PluginHostMsg_AcceleratedSurfaceSetTransportDIB( plugin_host_route_id_, window_, size.width(), size.height(), transport_dib)); notify_repaint = true; } } if (notify_repaint) { // Indicate to the client that at least one repaint is needed. NotifyRepaint(); } } void CommandBufferStub::SwapBuffersCallback() { Send(new PluginHostMsg_AcceleratedSurfaceBuffersSwapped( plugin_host_route_id_, window_, processor_->GetSurfaceId())); } void CommandBufferStub::AllocTransportDIB(const size_t size, TransportDIB::Handle* dib_handle) { Send(new PluginHostMsg_AllocTransportDIB(plugin_host_route_id_, size, dib_handle)); } void CommandBufferStub::FreeTransportDIB(TransportDIB::Id dib_id) { Send(new PluginHostMsg_FreeTransportDIB(plugin_host_route_id_, dib_id)); } #endif
31.628571
79
0.705123
Gitman1989
58189ec61b157d53ce90fb63d0476546bac6f851
7,728
cpp
C++
src/framework/kmdf/src/dma/base/fxcommonbufferapi.cpp
IT-Enthusiast-Nepal/Windows-Driver-Frameworks
bfee6134f30f92a90dbf96e98d54582ecb993996
[ "MIT" ]
994
2015-03-18T21:37:07.000Z
2019-04-26T04:04:14.000Z
src/framework/kmdf/src/dma/base/fxcommonbufferapi.cpp
IT-Enthusiast-Nepal/Windows-Driver-Frameworks
bfee6134f30f92a90dbf96e98d54582ecb993996
[ "MIT" ]
13
2019-06-13T15:58:03.000Z
2022-02-18T22:53:35.000Z
src/framework/kmdf/src/dma/base/fxcommonbufferapi.cpp
IT-Enthusiast-Nepal/Windows-Driver-Frameworks
bfee6134f30f92a90dbf96e98d54582ecb993996
[ "MIT" ]
350
2015-03-19T04:29:46.000Z
2019-05-05T23:26:50.000Z
/*++ Copyright (c) Microsoft Corporation Module Name: FxCommonBufferAPI.cpp Abstract: Base for WDF CommonBuffer APIs Environment: Kernel mode only. Notes: Revision History: --*/ #include "FxDmaPCH.hpp" extern "C" { #include "FxCommonBufferAPI.tmh" } // // Extern "C" the entire file // extern "C" { _Must_inspect_result_ __drv_maxIRQL(PASSIVE_LEVEL) NTSTATUS WDFEXPORT(WdfCommonBufferCreate)( __in PWDF_DRIVER_GLOBALS DriverGlobals, __in WDFDMAENABLER DmaEnabler, __in __drv_when(Length == 0, __drv_reportError(Length cannot be zero)) size_t Length, __in_opt WDF_OBJECT_ATTRIBUTES * Attributes, __out WDFCOMMONBUFFER * CommonBufferHandle ) { FxCommonBuffer * pComBuf; FxDmaEnabler * pDmaEnabler; NTSTATUS status; WDFOBJECT handle; PFX_DRIVER_GLOBALS pFxDriverGlobals; // // Get validate DmaEnabler handle // FxObjectHandleGetPtrAndGlobals(GetFxDriverGlobals(DriverGlobals), DmaEnabler, FX_TYPE_DMA_ENABLER, (PVOID *) &pDmaEnabler, &pFxDriverGlobals); FxPointerNotNull(pFxDriverGlobals, CommonBufferHandle); *CommonBufferHandle = NULL; status = FxVerifierCheckIrqlLevel(pFxDriverGlobals, PASSIVE_LEVEL); if (!NT_SUCCESS(status)) { return status; } // // Basic parameter validation // if (Length == 0) { status = STATUS_INVALID_PARAMETER; DoTraceLevelMessage(pFxDriverGlobals, TRACE_LEVEL_ERROR, TRACINGDMA, "Length is 0, %!STATUS!", status); return status; } status = FxValidateObjectAttributes(pFxDriverGlobals, Attributes, FX_VALIDATE_OPTION_PARENT_NOT_ALLOWED ); if (!NT_SUCCESS(status)) { return status; } // // Create a new CommonBuffer object // pComBuf = new(pFxDriverGlobals, Attributes) FxCommonBuffer(pFxDriverGlobals, pDmaEnabler); if (pComBuf == NULL) { status = STATUS_INSUFFICIENT_RESOURCES; DoTraceLevelMessage(pFxDriverGlobals, TRACE_LEVEL_ERROR, TRACINGDMA, "Could not allocate memory for a WDFCOMMONBUFFER, " "%!STATUS!", status); return status; } // // Assign this FxCommonBuffer to its parent FxDmaEnabler object. // status = pComBuf->Commit(Attributes, (WDFOBJECT*)&handle, pDmaEnabler); if (NT_SUCCESS(status)) { // // Ok: now allocate a CommonBuffer via this DmaEnabler // status = pComBuf->AllocateCommonBuffer( Length ); } if (NT_SUCCESS(status)) { // // Only return a valid handle on success. // *CommonBufferHandle = (WDFCOMMONBUFFER) handle; } else { pComBuf->DeleteFromFailedCreate(); } return status; } _Must_inspect_result_ __drv_maxIRQL(PASSIVE_LEVEL) NTSTATUS WDFEXPORT(WdfCommonBufferCreateWithConfig)( __in PWDF_DRIVER_GLOBALS DriverGlobals, __in WDFDMAENABLER DmaEnabler, __in __drv_when(Length == 0, __drv_reportError(Length cannot be zero)) size_t Length, __in PWDF_COMMON_BUFFER_CONFIG Config, __in_opt WDF_OBJECT_ATTRIBUTES * Attributes, __out WDFCOMMONBUFFER * CommonBufferHandle ) { FxCommonBuffer * pComBuf; FxDmaEnabler * pDmaEnabler; NTSTATUS status; WDFOBJECT handle; PFX_DRIVER_GLOBALS pFxDriverGlobals; // // Get validate DmaEnabler handle // FxObjectHandleGetPtrAndGlobals(GetFxDriverGlobals(DriverGlobals), DmaEnabler, FX_TYPE_DMA_ENABLER, (PVOID *) &pDmaEnabler, &pFxDriverGlobals); // // Basic parameter validation // FxPointerNotNull(pFxDriverGlobals, Config); if (Config->Size != sizeof(WDF_COMMON_BUFFER_CONFIG)) { status = STATUS_INFO_LENGTH_MISMATCH; DoTraceLevelMessage( pFxDriverGlobals, TRACE_LEVEL_ERROR, TRACINGDMA, "WDF_COMMON_BUFFER_CONFIG Size 0x%x, expected 0x%x, %!STATUS!", Config->Size, sizeof(WDF_COMMON_BUFFER_CONFIG), status); return status; } FxPointerNotNull(pFxDriverGlobals, CommonBufferHandle); *CommonBufferHandle = NULL; status = FxVerifierCheckIrqlLevel(pFxDriverGlobals, PASSIVE_LEVEL); if (!NT_SUCCESS(status)) { return status; } if (Length == 0) { status = STATUS_INVALID_PARAMETER; DoTraceLevelMessage(pFxDriverGlobals, TRACE_LEVEL_ERROR, TRACINGDMA, "Length is 0, %!STATUS!", status); return status; } status = FxValidateObjectAttributes(pFxDriverGlobals, Attributes, FX_VALIDATE_OPTION_PARENT_NOT_ALLOWED ); if (!NT_SUCCESS(status)) { return status; } pComBuf = new(pFxDriverGlobals, Attributes) FxCommonBuffer(pFxDriverGlobals, pDmaEnabler); if (pComBuf == NULL) { status = STATUS_INSUFFICIENT_RESOURCES; DoTraceLevelMessage(pFxDriverGlobals, TRACE_LEVEL_ERROR, TRACINGDMA, "Could not allocate memory for a WDFCOMMONBUFFER, " "%!STATUS!", status); return status; } // // Assign this FxCommonBuffer to its parent FxDmaEnabler object. // status = pComBuf->Commit(Attributes, (WDFOBJECT*)&handle, pDmaEnabler); if (NT_SUCCESS(status)) { // // Set the alignment value before calling AllocateCommonBuffer. // pComBuf->SetAlignment(Config->AlignmentRequirement); status = pComBuf->AllocateCommonBuffer( Length ); } if (NT_SUCCESS(status)) { // // Only return a valid handle on success. // *CommonBufferHandle = (WDFCOMMONBUFFER) handle; } else { pComBuf->DeleteFromFailedCreate(); } return status; } __drv_maxIRQL(DISPATCH_LEVEL) PVOID WDFEXPORT(WdfCommonBufferGetAlignedVirtualAddress)( __in PWDF_DRIVER_GLOBALS DriverGlobals, __in WDFCOMMONBUFFER CommonBuffer ) { FxCommonBuffer * pComBuf; FxObjectHandleGetPtr(GetFxDriverGlobals(DriverGlobals), CommonBuffer, FX_TYPE_COMMON_BUFFER, (PVOID *) &pComBuf); return pComBuf->GetAlignedVirtualAddress(); } __drv_maxIRQL(DISPATCH_LEVEL) PHYSICAL_ADDRESS WDFEXPORT(WdfCommonBufferGetAlignedLogicalAddress)( __in PWDF_DRIVER_GLOBALS DriverGlobals, __in WDFCOMMONBUFFER CommonBuffer ) { FxCommonBuffer * pComBuf; FxObjectHandleGetPtr(GetFxDriverGlobals(DriverGlobals), CommonBuffer, FX_TYPE_COMMON_BUFFER, (PVOID *) &pComBuf); return pComBuf->GetAlignedLogicalAddress(); } __drv_maxIRQL(DISPATCH_LEVEL) size_t WDFEXPORT(WdfCommonBufferGetLength)( __in PWDF_DRIVER_GLOBALS DriverGlobals, __in WDFCOMMONBUFFER CommonBuffer ) { FxCommonBuffer * pComBuf; FxObjectHandleGetPtr(GetFxDriverGlobals(DriverGlobals), CommonBuffer, FX_TYPE_COMMON_BUFFER, (PVOID *) &pComBuf); return pComBuf->GetLength(); } } // extern "C"
25.421053
79
0.607013
IT-Enthusiast-Nepal
5819329cbc183c156d879117a551fa279dfba621
6,770
cpp
C++
ModEPP.cpp
hiqsol/reclient
02c2f0c21a4378a5dbcc058f468d98c34e1d1190
[ "BSD-3-Clause" ]
2
2018-11-14T11:18:49.000Z
2018-11-17T05:13:52.000Z
ModEPP.cpp
hiqsol/reclient
02c2f0c21a4378a5dbcc058f468d98c34e1d1190
[ "BSD-3-Clause" ]
null
null
null
ModEPP.cpp
hiqsol/reclient
02c2f0c21a4378a5dbcc058f468d98c34e1d1190
[ "BSD-3-Clause" ]
null
null
null
// (c) Andrii Vasyliev // ModEPP #include "reclient/ModEPP.h" namespace re { Hash<EPP> ModEPP::sessions; data_type ModEPP::init (data_cref a) { sessions.set(a.getLine("session",0),EPP(a.getLine("host"),a.getIntN("port"),a.getLine("certificate"),a.getLine("cacertfile"),a.getLine("cacertdir"))); if (a.has("serial")) sessions.let(a.getLine("session",0)).setSerialNo(a.getLine("serial")); return data_null; }; data_type ModEPP::incBatchNo (data_cref a) { return sessions.let(a.getLine("session",0)).incBatchNo(); }; data_type ModEPP::setNamestoreExtension (data_cref a) { sessions.let(a.getLine("session",0)).setNamestoreExtension(a.getLine("ext"),a.getLine("data")); return data_null; }; // EPP NATIVE COMMANDS data_type ModEPP::poll (data_cref a) { return sessions.let(a.getLine("session",0)).poll(a); }; data_type ModEPP::hello (data_cref a) { return sessions.let(a.getLine("session",0)).hello(a); }; data_type ModEPP::login (data_cref a) { return sessions.let(a.getLine("session",0)).login(a); }; data_type ModEPP::logout (data_cref a) { return sessions.let(a.getLine("session",0)).logout(a); }; data_type ModEPP::domainInfo (data_cref a) { return sessions.let(a.getLine("session",0)).domainInfo(a); }; data_type ModEPP::domainSync (data_cref a) { return sessions.let(a.getLine("session",0)).domainSync(a); }; data_type ModEPP::domainSimpleCheck (data_cref a) { return sessions.let(a.getLine("session",0)).domainSimpleCheck(a); }; data_type ModEPP::domainCheck (data_cref a) { return sessions.let(a.getLine("session",0)).domainCheck(a); }; data_type ModEPP::domainRenew (data_cref a) { return sessions.let(a.getLine("session",0)).domainRenew(a); }; data_type ModEPP::domainCreate (data_cref a) { return sessions.let(a.getLine("session",0)).domainCreate(a); }; data_type ModEPP::domainUpdate (data_cref a) { return sessions.let(a.getLine("session",0)).domainUpdate(a); }; data_type ModEPP::domainDelete (data_cref a) { return sessions.let(a.getLine("session",0)).domainDelete(a); }; data_type ModEPP::domainTransfer (data_cref a) { return sessions.let(a.getLine("session",0)).domainTransfer(a); }; data_type ModEPP::emailFwdInfo (data_cref a) { return sessions.let(a.getLine("session",0)).emailFwdInfo(a); }; data_type ModEPP::emailFwdCheck (data_cref a) { return sessions.let(a.getLine("session",0)).emailFwdCheck(a); }; data_type ModEPP::emailFwdRenew (data_cref a) { return sessions.let(a.getLine("session",0)).emailFwdRenew(a); }; data_type ModEPP::emailFwdCreate (data_cref a) { return sessions.let(a.getLine("session",0)).emailFwdCreate(a); }; data_type ModEPP::emailFwdUpdate (data_cref a) { return sessions.let(a.getLine("session",0)).emailFwdUpdate(a); }; data_type ModEPP::emailFwdDelete (data_cref a) { return sessions.let(a.getLine("session",0)).emailFwdDelete(a); }; data_type ModEPP::emailFwdTransfer (data_cref a) { return sessions.let(a.getLine("session",0)).emailFwdTransfer(a); }; data_type ModEPP::hostInfo (data_cref a) { return sessions.let(a.getLine("session",0)).hostInfo(a); }; data_type ModEPP::hostCheck (data_cref a) { return sessions.let(a.getLine("session",0)).hostCheck(a); }; data_type ModEPP::hostCreate (data_cref a) { return sessions.let(a.getLine("session",0)).hostCreate(a); }; data_type ModEPP::hostUpdate (data_cref a) { return sessions.let(a.getLine("session",0)).hostUpdate(a); }; data_type ModEPP::hostDelete (data_cref a) { return sessions.let(a.getLine("session",0)).hostDelete(a); }; data_type ModEPP::contactCheck (data_cref a) { return sessions.let(a.getLine("session",0)).contactCheck(a); }; data_type ModEPP::contactCreate (data_cref a) { return sessions.let(a.getLine("session",0)).contactCreate(a); }; data_type ModEPP::contactInfo (data_cref a) { return sessions.let(a.getLine("session",0)).contactInfo(a); }; data_type ModEPP::contactTransfer (data_cref a) { return sessions.let(a.getLine("session",0)).contactTransfer(a); }; data_type ModEPP::contactUpdate (data_cref a) { return sessions.let(a.getLine("session",0)).contactUpdate(a); }; data_type ModEPP::contactDelete (data_cref a) { return sessions.let(a.getLine("session",0)).contactDelete(a); }; // SMART COMMANDS data_type ModEPP::pollOne (data_cref a) { return sessions.let(a.getLine("session",0)).pollOne(a); }; data_type ModEPP::pollAll (data_cref a) { return sessions.let(a.getLine("session",0)).pollAll(a); }; data_type ModEPP::pollAck (data_cref a) { sessions.let(a.getLine("session",0)).pollAck(a.get("id"));return NULL; }; data_type ModEPP::domainAllowUpdate (data_cref a) { return sessions.let(a.getLine("session",0)).domainAllowUpdate(a); }; data_type ModEPP::domainProhibitUpdate (data_cref a) { return sessions.let(a.getLine("session",0)).domainProhibitUpdate(a); }; data_type ModEPP::domainMassCheck (data_cref a) { return sessions.let(a.getLine("session",0)).domainMassCheck(a); }; data_type ModEPP::domainSmartCheck (data_cref a) { return sessions.let(a.getLine("session",0)).domainSmartCheck(a); }; data_type ModEPP::domainSmartUpdate (data_cref a) { return sessions.let(a.getLine("session",0)).domainSmartUpdate(a); }; data_type ModEPP::domainSmartDelete (data_cref a) { return sessions.let(a.getLine("session",0)).domainSmartDelete(a); }; data_type ModEPP::domainSmartLock (data_cref a) { return sessions.let(a.getLine("session",0)).domainSmartLock(a); }; data_type ModEPP::domainSmartUnlock (data_cref a) { return sessions.let(a.getLine("session",0)).domainSmartUnlock(a); }; data_type ModEPP::domainSmartHold (data_cref a) { return sessions.let(a.getLine("session",0)).domainSmartHold(a); }; data_type ModEPP::domainSmartUnhold (data_cref a) { return sessions.let(a.getLine("session",0)).domainSmartUnhold(a); }; data_type ModEPP::domainSmartRenew (data_cref a) { return sessions.let(a.getLine("session",0)).domainSmartRenew(a); }; data_type ModEPP::emailFwdSmartRenew (data_cref a) { return sessions.let(a.getLine("session",0)).emailFwdSmartRenew(a); }; data_type ModEPP::hostSmartCheck (data_cref a) { return sessions.let(a.getLine("session",0)).hostSmartCheck(a); }; data_type ModEPP::hostSmartUpdate (data_cref a) { return sessions.let(a.getLine("session",0)).hostSmartUpdate(a); }; data_type ModEPP::hostSmartDelete (data_cref a) { return sessions.let(a.getLine("session",0)).hostSmartDelete(a); }; data_type ModEPP::hostSmartSet (data_cref a) { return sessions.let(a.getLine("session",0)).hostSmartSet(a); }; data_type ModEPP::contactSmartCheck (data_cref a) { return sessions.let(a.getLine("session",0)).contactSmartCheck(a); }; data_type ModEPP::contactSmartUpdate (data_cref a) { return sessions.let(a.getLine("session",0)).contactSmartUpdate(a); }; data_type ModEPP::contactSmartSet (data_cref a) { return sessions.let(a.getLine("session",0)).contactSmartSet(a); }; }; // namespace re
83.580247
151
0.742984
hiqsol
581964349ff52128d383dc60f9b26897ee810c0d
1,024
cc
C++
simulation/functional-sim/libss-vpi/lib.src/sim_main.cc
anycore/anycore-pisa
b4dcd040d2850fb19adb1502c3c03bf73ca06c35
[ "BSD-3-Clause" ]
null
null
null
simulation/functional-sim/libss-vpi/lib.src/sim_main.cc
anycore/anycore-pisa
b4dcd040d2850fb19adb1502c3c03bf73ca06c35
[ "BSD-3-Clause" ]
null
null
null
simulation/functional-sim/libss-vpi/lib.src/sim_main.cc
anycore/anycore-pisa
b4dcd040d2850fb19adb1502c3c03bf73ca06c35
[ "BSD-3-Clause" ]
3
2017-10-14T00:51:39.000Z
2021-03-25T16:37:11.000Z
#include <stdio.h> #include <string.h> #include <math.h> #include <assert.h> #include "misc.h" #include "mt_trace_consume.h" #include "Thread.h" #include "global_vars.h" ///////////////////////////////////////////////////////////////////// void sim_config(FILE *stream) { } /* exit when this becomes non-zero */ int sim_exit_now = FALSE; /* longjmp here when simulation is completed */ jmp_buf sim_exit_buf; /* instruction jump table */ #ifdef sparc register void **local_op_jump asm("g7"); #else void **local_op_jump; #endif void sim_main(void) { /////////////////////////////////////// // Decode the binaries of each thread. /////////////////////////////////////// for (unsigned int i = 0; i < NumThreads; i++) THREAD[i]->decode(); /////////////////////////////////////// // Initialize trace consumer. /////////////////////////////////////// trace_consume_init(); //////////////////////////////// // Simulator Loop. //////////////////////////////// trace_consume(); } // sim_main()
19.692308
69
0.482422
anycore
581e64a954f61cd2d256de021e2d54fa10cdce6a
8,587
cpp
C++
lib/utils/visFileRaw.cpp
eschnett/kotekan
81918288147435cef8ad52db05da0988c999a7dd
[ "MIT" ]
19
2018-12-14T00:51:52.000Z
2022-02-20T02:43:50.000Z
lib/utils/visFileRaw.cpp
eschnett/kotekan
81918288147435cef8ad52db05da0988c999a7dd
[ "MIT" ]
487
2018-12-13T00:59:53.000Z
2022-02-07T16:12:56.000Z
lib/utils/visFileRaw.cpp
eschnett/kotekan
81918288147435cef8ad52db05da0988c999a7dd
[ "MIT" ]
5
2019-05-09T19:52:19.000Z
2021-03-27T20:13:21.000Z
#include "visFileRaw.hpp" #include "Hash.hpp" // for Hash #include "datasetManager.hpp" // for datasetManager, dset_id_t #include "datasetState.hpp" // for stackState, eigenvalueState, freqState, gatingState, input... #include "visBuffer.hpp" // for VisFrameView, VisMetadata #include "fmt.hpp" // for format, fmt #include "json.hpp" // for basic_json<>::object_t, basic_json<>::value_type, json #include <cstdio> // for remove #include <cxxabi.h> // for __forced_unwind #include <errno.h> // for errno #include <exception> // for exception #include <fcntl.h> // for fallocate, sync_file_range, open, posix_fadvise, FALLOC_FL... #include <fstream> // for ofstream, basic_ostream::write, ios #include <future> // for async, future #include <stdexcept> // for out_of_range, runtime_error #include <string.h> // for strerror #include <sys/stat.h> // for S_IRGRP, S_IROTH, S_IRUSR, S_IWGRP, S_IWUSR #include <system_error> // for system_error #include <unistd.h> // for close, pwrite, TEMP_FAILURE_RETRY #include <utility> // for pair // Register the raw file writer REGISTER_VIS_FILE("raw", visFileRaw); // // Implementation of raw visibility data file // visFileRaw::visFileRaw(const std::string& name, const kotekan::logLevel log_level, const std::map<std::string, std::string>& metadata, dset_id_t dataset, size_t max_time, int oflags) : _name(name) { set_log_level(log_level); INFO("Creating new output file {:s}", name); // Get properties of stream from datasetManager auto& dm = datasetManager::instance(); auto sstate_fut = std::async(&datasetManager::dataset_state<stackState>, &dm, dataset); auto istate_fut = std::async(&datasetManager::dataset_state<inputState>, &dm, dataset); auto pstate_fut = std::async(&datasetManager::dataset_state<prodState>, &dm, dataset); auto fstate_fut = std::async(&datasetManager::dataset_state<freqState>, &dm, dataset); auto evstate_fut = std::async(&datasetManager::dataset_state<eigenvalueState>, &dm, dataset); auto gstate_fut = std::async(&datasetManager::dataset_state<gatingState>, &dm, dataset); const inputState* istate = istate_fut.get(); const prodState* pstate = pstate_fut.get(); const freqState* fstate = fstate_fut.get(); if (!istate || !pstate || !fstate) { ERROR("Required datasetState not found for dataset ID {}\nThe following required states " "were found:\ninputState - {:p}\nprodState - {:p}\nfreqState - {:p}\n", dataset, (void*)istate, (void*)pstate, (void*)fstate); throw std::runtime_error("Could not create file."); } // Set the axis metadata file_metadata["attributes"] = metadata; file_metadata["index_map"]["freq"] = unzip(fstate->get_freqs()).second; file_metadata["index_map"]["input"] = istate->get_inputs(); file_metadata["index_map"]["prod"] = pstate->get_prods(); // Create and add eigenvalue index const eigenvalueState* evstate = evstate_fut.get(); if (evstate) { file_metadata["index_map"]["ev"] = evstate->get_ev(); num_ev = evstate->get_num_ev(); } else { num_ev = 0; } const stackState* sstate = sstate_fut.get(); if (sstate) { file_metadata["index_map"]["stack"] = sstate->get_stack_map(); file_metadata["reverse_map"]["stack"] = sstate->get_rstack_map(); file_metadata["structure"]["num_stack"] = sstate->get_num_stack(); } const gatingState* gstate = gstate_fut.get(); if (gstate) { file_metadata["gating_type"] = gstate->gating_type; file_metadata["gating_data"] = gstate->gating_data; } // Calculate the file structure nfreq = fstate->get_freqs().size(); size_t ninput = istate->get_inputs().size(); size_t nvis = sstate ? sstate->get_num_stack() : pstate->get_prods().size(); // Set the alignment (in kB) // TODO: find some way of getting this from config alignment = 4; // Align on page boundaries // Calculate the file structure data_size = VisFrameView::calculate_frame_size(ninput, nvis, num_ev); metadata_size = sizeof(VisMetadata); frame_size = _member_alignment(data_size + metadata_size + 1, alignment * 1024); // Write the structure into the file for decoding file_metadata["structure"]["metadata_size"] = metadata_size; file_metadata["structure"]["data_size"] = data_size; file_metadata["structure"]["frame_size"] = frame_size; file_metadata["structure"]["nfreq"] = nfreq; // Create lock file and then open the other files lock_filename = create_lockfile(_name); metadata_file = std::ofstream(_name + ".meta", std::ios::binary); if ((fd = open((_name + ".data").c_str(), oflags, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH)) == -1) { throw std::runtime_error( fmt::format(fmt("Failed to open file {:s}.data: {:s}."), _name, strerror(errno))); } // Preallocate data file (without increasing the length) #ifdef __linux__ // Note not all versions of linux support this feature, and they don't // include the macro FALLOC_FL_KEEP_SIZE in that case #ifdef FALLOC_FL_KEEP_SIZE fallocate(fd, FALLOC_FL_KEEP_SIZE, 0, frame_size * nfreq * max_time); #else (void)max_time; // Suppress warning WARN("fallocate not supported on this system!"); #endif #else (void)max_time; // Suppress warning #endif } visFileRaw::~visFileRaw() { // Finalize the metadata file file_metadata["structure"]["ntime"] = num_time(); file_metadata["index_map"]["time"] = times; std::vector<uint8_t> t = nlohmann::json::to_msgpack(file_metadata); metadata_file.write((const char*)&t[0], t.size()); metadata_file.close(); // TODO: final sync of data file. close(fd); std::remove(lock_filename.c_str()); } size_t visFileRaw::num_time() { return times.size(); } void visFileRaw::flush_raw_async(int ind) { #ifdef __linux__ size_t n = nfreq * frame_size; sync_file_range(fd, ind * n, n, SYNC_FILE_RANGE_WRITE); #else (void)ind; // Suppress warning #endif } void visFileRaw::flush_raw_sync(int ind) { #ifdef __linux__ size_t n = nfreq * frame_size; sync_file_range(fd, ind * n, n, SYNC_FILE_RANGE_WAIT_BEFORE | SYNC_FILE_RANGE_WRITE | SYNC_FILE_RANGE_WAIT_AFTER); posix_fadvise(fd, ind * n, n, POSIX_FADV_DONTNEED); #else (void)ind; // Suppress warning #endif } uint32_t visFileRaw::extend_time(time_ctype new_time) { size_t ntime = num_time(); // Start to flush out older dataset regions uint delta_async = 2; if (ntime > delta_async) { flush_raw_async(ntime - delta_async); } // Flush and clear out any really old parts of the datasets uint delta_sync = 4; if (ntime > delta_sync) { flush_raw_sync(ntime - delta_sync); } times.push_back(new_time); // Extend the file length for the new time #ifdef __linux__ fallocate(fd, 0, 0, frame_size * nfreq * num_time()); #else ftruncate(fd, frame_size * nfreq * num_time()); #endif return num_time() - 1; } void visFileRaw::deactivate_time(uint32_t time_ind) { flush_raw_sync(time_ind); } bool visFileRaw::write_raw(off_t offset, size_t nb, const void* data) { // Write in a retry macro loop incase the write was interrupted by a signal int nbytes = TEMP_FAILURE_RETRY(pwrite(fd, data, nb, offset)); if (nbytes < 0) { ERROR("Write error attempting to write {:d} bytes at offset {:d} into file {:s}: {:s}", nb, offset, _name, strerror(errno)); return false; } return true; } void visFileRaw::write_sample(uint32_t time_ind, uint32_t freq_ind, const FrameView& frame_view) { const VisFrameView& frame = static_cast<const VisFrameView&>(frame_view); // TODO: consider adding checks for all dims if (frame.num_ev != num_ev) { throw std::runtime_error(fmt::format(fmt("Number of eigenvalues don't match for write (got " "{:d}, expected {:d})"), frame.num_ev, num_ev)); } const uint8_t ONE = 1; // Write out data to the right place off_t offset = (time_ind * nfreq + freq_ind) * frame_size; write_raw(offset, 1, &ONE); write_raw(offset + 1, metadata_size, frame.metadata()); write_raw(offset + 1 + metadata_size, data_size, frame.data()); }
35.337449
100
0.656807
eschnett
5820c4b6a41bf6c38993707a847e126c126b6f12
12,374
cc
C++
src/runtime/runtime-typedarray.cc
lzxb/v8
cb9e7af4e5238ac7b1a6c226f229a8ed62a0ea82
[ "BSD-3-Clause" ]
38
2015-01-31T18:38:28.000Z
2019-06-16T08:34:38.000Z
src/runtime/runtime-typedarray.cc
lzxb/v8
cb9e7af4e5238ac7b1a6c226f229a8ed62a0ea82
[ "BSD-3-Clause" ]
2
2016-02-20T14:54:47.000Z
2018-11-28T15:48:38.000Z
src/runtime/runtime-typedarray.cc
bnoordhuis/v8.rs
2a20ed0f54e3e49ce1b4715ac98b532cb133eea4
[ "ISC" ]
7
2015-02-04T06:50:55.000Z
2019-12-05T19:51:23.000Z
// Copyright 2014 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "src/runtime/runtime-utils.h" #include "src/arguments.h" #include "src/elements.h" #include "src/factory.h" #include "src/messages.h" #include "src/objects-inl.h" #include "src/runtime/runtime.h" namespace v8 { namespace internal { RUNTIME_FUNCTION(Runtime_ArrayBufferGetByteLength) { SealHandleScope shs(isolate); DCHECK_EQ(1, args.length()); CONVERT_ARG_CHECKED(JSArrayBuffer, holder, 0); return holder->byte_length(); } RUNTIME_FUNCTION(Runtime_ArrayBufferNeuter) { HandleScope scope(isolate); DCHECK_EQ(1, args.length()); Handle<Object> argument = args.at(0); // This runtime function is exposed in ClusterFuzz and as such has to // support arbitrary arguments. if (!argument->IsJSArrayBuffer()) { THROW_NEW_ERROR_RETURN_FAILURE( isolate, NewTypeError(MessageTemplate::kNotTypedArray)); } Handle<JSArrayBuffer> array_buffer = Handle<JSArrayBuffer>::cast(argument); if (!array_buffer->is_neuterable()) { return isolate->heap()->undefined_value(); } if (array_buffer->backing_store() == nullptr) { CHECK_EQ(Smi::kZero, array_buffer->byte_length()); return isolate->heap()->undefined_value(); } // Shared array buffers should never be neutered. CHECK(!array_buffer->is_shared()); DCHECK(!array_buffer->is_external()); void* backing_store = array_buffer->backing_store(); size_t byte_length = NumberToSize(array_buffer->byte_length()); array_buffer->set_is_external(true); isolate->heap()->UnregisterArrayBuffer(*array_buffer); array_buffer->Neuter(); isolate->array_buffer_allocator()->Free(backing_store, byte_length); return isolate->heap()->undefined_value(); } RUNTIME_FUNCTION(Runtime_TypedArrayCopyElements) { HandleScope scope(isolate); DCHECK_EQ(3, args.length()); CONVERT_ARG_HANDLE_CHECKED(JSTypedArray, target, 0); CONVERT_ARG_HANDLE_CHECKED(JSReceiver, source, 1); CONVERT_NUMBER_ARG_HANDLE_CHECKED(length_obj, 2); size_t length; CHECK(TryNumberToSize(*length_obj, &length)); ElementsAccessor* accessor = target->GetElementsAccessor(); return accessor->CopyElements(source, target, length); } #define BUFFER_VIEW_GETTER(Type, getter, accessor) \ RUNTIME_FUNCTION(Runtime_##Type##Get##getter) { \ HandleScope scope(isolate); \ DCHECK_EQ(1, args.length()); \ CONVERT_ARG_HANDLE_CHECKED(JS##Type, holder, 0); \ return holder->accessor(); \ } BUFFER_VIEW_GETTER(ArrayBufferView, ByteLength, byte_length) BUFFER_VIEW_GETTER(ArrayBufferView, ByteOffset, byte_offset) BUFFER_VIEW_GETTER(TypedArray, Length, length) #undef BUFFER_VIEW_GETTER RUNTIME_FUNCTION(Runtime_ArrayBufferViewWasNeutered) { HandleScope scope(isolate); DCHECK_EQ(1, args.length()); return isolate->heap()->ToBoolean(JSTypedArray::cast(args[0])->WasNeutered()); } RUNTIME_FUNCTION(Runtime_TypedArrayGetBuffer) { HandleScope scope(isolate); DCHECK_EQ(1, args.length()); CONVERT_ARG_HANDLE_CHECKED(JSTypedArray, holder, 0); return *holder->GetBuffer(); } namespace { template <typename T> bool CompareNum(T x, T y) { if (x < y) { return true; } else if (x > y) { return false; } else if (!std::is_integral<T>::value) { double _x = x, _y = y; if (x == 0 && x == y) { /* -0.0 is less than +0.0 */ return std::signbit(_x) && !std::signbit(_y); } else if (!std::isnan(_x) && std::isnan(_y)) { /* number is less than NaN */ return true; } } return false; } } // namespace RUNTIME_FUNCTION(Runtime_TypedArraySortFast) { HandleScope scope(isolate); DCHECK_EQ(1, args.length()); CONVERT_ARG_HANDLE_CHECKED(Object, target_obj, 0); Handle<JSTypedArray> array; const char* method = "%TypedArray%.prototype.sort"; ASSIGN_RETURN_FAILURE_ON_EXCEPTION( isolate, array, JSTypedArray::Validate(isolate, target_obj, method)); // This line can be removed when JSTypedArray::Validate throws // if array.[[ViewedArrayBuffer]] is neutered(v8:4648) if (V8_UNLIKELY(array->WasNeutered())) return *array; size_t length = array->length_value(); if (length <= 1) return *array; Handle<FixedTypedArrayBase> elements( FixedTypedArrayBase::cast(array->elements())); switch (array->type()) { #define TYPED_ARRAY_SORT(Type, type, TYPE, ctype, size) \ case kExternal##Type##Array: { \ ctype* data = static_cast<ctype*>(elements->DataPtr()); \ if (kExternal##Type##Array == kExternalFloat64Array || \ kExternal##Type##Array == kExternalFloat32Array) \ std::sort(data, data + length, CompareNum<ctype>); \ else \ std::sort(data, data + length); \ break; \ } TYPED_ARRAYS(TYPED_ARRAY_SORT) #undef TYPED_ARRAY_SORT } return *array; } RUNTIME_FUNCTION(Runtime_IsTypedArray) { HandleScope scope(isolate); DCHECK_EQ(1, args.length()); return isolate->heap()->ToBoolean(args[0]->IsJSTypedArray()); } RUNTIME_FUNCTION(Runtime_IsSharedTypedArray) { HandleScope scope(isolate); DCHECK_EQ(1, args.length()); return isolate->heap()->ToBoolean( args[0]->IsJSTypedArray() && JSTypedArray::cast(args[0])->GetBuffer()->is_shared()); } RUNTIME_FUNCTION(Runtime_IsSharedIntegerTypedArray) { HandleScope scope(isolate); DCHECK_EQ(1, args.length()); if (!args[0]->IsJSTypedArray()) { return isolate->heap()->false_value(); } Handle<JSTypedArray> obj(JSTypedArray::cast(args[0])); return isolate->heap()->ToBoolean(obj->GetBuffer()->is_shared() && obj->type() != kExternalFloat32Array && obj->type() != kExternalFloat64Array && obj->type() != kExternalUint8ClampedArray); } RUNTIME_FUNCTION(Runtime_IsSharedInteger32TypedArray) { HandleScope scope(isolate); DCHECK_EQ(1, args.length()); if (!args[0]->IsJSTypedArray()) { return isolate->heap()->false_value(); } Handle<JSTypedArray> obj(JSTypedArray::cast(args[0])); return isolate->heap()->ToBoolean(obj->GetBuffer()->is_shared() && obj->type() == kExternalInt32Array); } RUNTIME_FUNCTION(Runtime_TypedArraySpeciesCreateByLength) { HandleScope scope(isolate); DCHECK_EQ(args.length(), 2); Handle<JSTypedArray> exemplar = args.at<JSTypedArray>(0); Handle<Object> length = args.at(1); int argc = 1; ScopedVector<Handle<Object>> argv(argc); argv[0] = length; Handle<JSTypedArray> result_array; // TODO(tebbi): Pass correct method name. ASSIGN_RETURN_FAILURE_ON_EXCEPTION( isolate, result_array, JSTypedArray::SpeciesCreate(isolate, exemplar, argc, argv.start(), "")); return *result_array; } namespace { Object* TypedArraySetFromOverlapping(Isolate* isolate, Handle<JSTypedArray> target, Handle<JSTypedArray> source, uint32_t offset) { #ifdef DEBUG Handle<FixedTypedArrayBase> source_elements( FixedTypedArrayBase::cast(source->elements())); Handle<FixedTypedArrayBase> target_elements( FixedTypedArrayBase::cast(target->elements())); uint8_t* source_data = static_cast<uint8_t*>(source_elements->DataPtr()); uint8_t* target_data = static_cast<uint8_t*>(target_elements->DataPtr()); size_t source_byte_length = NumberToSize(source->byte_length()); size_t target_byte_length = NumberToSize(target->byte_length()); CHECK_LE(offset, target->length_value()); CHECK_LE(source->length_value(), target->length_value() - offset); CHECK(source->length()->IsSmi()); CHECK(!target->WasNeutered()); CHECK(!source->WasNeutered()); // Assert that target and source in fact overlapping. CHECK(target_data + target_byte_length > source_data && source_data + source_byte_length > target_data); #endif size_t sourceElementSize = source->element_size(); size_t targetElementSize = target->element_size(); uint32_t source_length = source->length_value(); if (source_length == 0) return isolate->heap()->undefined_value(); // Copy left part. // First un-mutated byte after the next write uint32_t target_ptr = 0; CHECK(target->byte_offset()->ToUint32(&target_ptr)); target_ptr += (offset + 1) * targetElementSize; // Next read at sourcePtr. We do not care for memory changing before // sourcePtr - we have already copied it. uint32_t source_ptr = 0; CHECK(source->byte_offset()->ToUint32(&source_ptr)); ElementsAccessor* source_accessor = source->GetElementsAccessor(); ElementsAccessor* target_accessor = target->GetElementsAccessor(); uint32_t left_index; for (left_index = 0; left_index < source_length && target_ptr <= source_ptr; left_index++) { Handle<Object> value = source_accessor->Get(source, left_index); target_accessor->Set(target, offset + left_index, *value); target_ptr += targetElementSize; source_ptr += sourceElementSize; } // Copy right part; // First unmutated byte before the next write CHECK(target->byte_offset()->ToUint32(&target_ptr)); target_ptr += (offset + source_length - 1) * targetElementSize; // Next read before sourcePtr. We do not care for memory changing after // sourcePtr - we have already copied it. CHECK(target->byte_offset()->ToUint32(&source_ptr)); source_ptr += source_length * sourceElementSize; uint32_t right_index; DCHECK_GE(source_length, 1); for (right_index = source_length - 1; right_index > left_index && target_ptr >= source_ptr; right_index--) { Handle<Object> value = source_accessor->Get(source, right_index); target_accessor->Set(target, offset + right_index, *value); target_ptr -= targetElementSize; source_ptr -= sourceElementSize; } std::vector<Handle<Object>> temp(right_index + 1 - left_index); for (uint32_t i = left_index; i <= right_index; i++) { temp[i - left_index] = source_accessor->Get(source, i); } for (uint32_t i = left_index; i <= right_index; i++) { target_accessor->Set(target, offset + i, *temp[i - left_index]); } return isolate->heap()->undefined_value(); } } // namespace // 22.2.3.23 %TypedArray%.prototype.set ( overloaded [ , offset ] ) RUNTIME_FUNCTION(Runtime_TypedArraySet) { HandleScope scope(isolate); Handle<JSTypedArray> target = args.at<JSTypedArray>(0); Handle<Object> obj = args.at(1); Handle<Smi> offset = args.at<Smi>(2); DCHECK(!target->WasNeutered()); // Checked in TypedArrayPrototypeSet. DCHECK_LE(0, offset->value()); const uint32_t uint_offset = static_cast<uint32_t>(offset->value()); if (obj->IsNumber()) { // For number as a first argument, throw TypeError // instead of silently ignoring the call, so that // users know they did something wrong. // (Consistent with Firefox and Blink/WebKit) THROW_NEW_ERROR_RETURN_FAILURE( isolate, NewTypeError(MessageTemplate::kInvalidArgument)); } else if (obj->IsJSTypedArray()) { // The non-overlapping case is handled in CSA. Handle<JSTypedArray> source = Handle<JSTypedArray>::cast(obj); return TypedArraySetFromOverlapping(isolate, target, source, uint_offset); } ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, obj, Object::ToObject(isolate, obj)); Handle<Object> len; ASSIGN_RETURN_FAILURE_ON_EXCEPTION( isolate, len, Object::GetProperty(obj, isolate->factory()->length_string())); ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, len, Object::ToLength(isolate, len)); if (uint_offset + len->Number() > target->length_value()) { THROW_NEW_ERROR_RETURN_FAILURE( isolate, NewRangeError(MessageTemplate::kTypedArraySetSourceTooLarge)); } uint32_t int_l; CHECK(DoubleToUint32IfEqualToSelf(len->Number(), &int_l)); Handle<JSReceiver> source = Handle<JSReceiver>::cast(obj); ElementsAccessor* accessor = target->GetElementsAccessor(); return accessor->CopyElements(source, target, int_l, uint_offset); } } // namespace internal } // namespace v8
34.18232
80
0.684904
lzxb
5820d8e4965b3d69fdaaefc52bdd3cee099f274d
7,456
cpp
C++
printscan/faxsrv/admin/mmc/dlgnewgroup.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
printscan/faxsrv/admin/mmc/dlgnewgroup.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
printscan/faxsrv/admin/mmc/dlgnewgroup.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
///////////////////////////////////////////////////////////////////////////// // FILE : DlgNewGroup.cpp // // // // DESCRIPTION : The CDlgNewFaxOutboundGroup class implements the // // dialog for additon of new Group. // // // // AUTHOR : yossg // // // // HISTORY : // // Jan 3 2000 yossg Create // // // // Copyright (C) 2000 Microsoft Corporation All Rights Reserved // ///////////////////////////////////////////////////////////////////////////// #include "StdAfx.h" #include "dlgNewGroup.h" #include "FaxServer.h" #include "FaxServerNode.h" #include "dlgutils.h" //#include "Helper.h" ///////////////////////////////////////////////////////////////////////////// // CDlgNewFaxOutboundGroup CDlgNewFaxOutboundGroup::~CDlgNewFaxOutboundGroup() { } /* + CDlgNewFaxOutboundGroup::OnInitDialog + * Purpose: * Initiate all dialog controls. * * Arguments: * [in] uMsg : Value identifying the event. * [in] lParam : Message-specific value. * [in] wParam : Message-specific value. * [in] bHandled : bool value. * - Return: - 0 or 1 */ LRESULT CDlgNewFaxOutboundGroup::OnInitDialog(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled) { DEBUG_FUNCTION_NAME( _T("CDlgNewFaxOutboundGroup::OnInitDialog")); HRESULT hRc = S_OK; // // Attach controls // m_GroupNameEdit.Attach(GetDlgItem(IDC_GROUPNAME_EDIT)); // // Set length limit to area code // m_GroupNameEdit.SetLimitText(MAX_ROUTING_GROUP_NAME - 1); // // Set focus // ::SetFocus(GetDlgItem(IDC_GROUPNAME_EDIT)); EnableOK(FALSE); return 1; // Let the system set the focus } /* + CDlgNewFaxOutboundGroup::OnOK + * Purpose: * Initiate all dialog controls. * * Arguments: * [in] uMsg : Value identifying the event. * [in] lParam : Message-specific value. * [in] wParam : Message-specific value. * [in] bHandled : bool value. * - Return: - 0 or 1 */ LRESULT CDlgNewFaxOutboundGroup::OnOK(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled) { DEBUG_FUNCTION_NAME( _T("CDlgNewFaxOutboundGroup::OnOK")); HRESULT hRc = S_OK; DWORD ec = ERROR_SUCCESS; // // Step 0: PreApply Checks // /* if (!CheckValidtity()) { EnableOK(FALSE); hRc =S_FALSE; goto Exit; } */ // // Step 1: get data // if ( !m_GroupNameEdit.GetWindowText(&m_bstrGroupName)) { DebugPrintEx( DEBUG_ERR, TEXT("Failed to GetWindowText(&m_bstrGroupName)")); DlgMsgBox(this, IDS_FAIL2READ_GROUPNAME); ::SetFocus(GetDlgItem(IDC_GROUPNAME_EDIT)); hRc = S_FALSE; goto Exit; } // // Step 2: add group via RPC call // // // get RPC Handle // if (!m_pFaxServer->GetFaxServerHandle()) { ec= GetLastError(); DebugPrintEx( DEBUG_ERR, _T("Failed to GetFaxServerHandle. (ec: %ld)"), ec); goto Error; } // // Add the group // if (!FaxAddOutboundGroup ( m_pFaxServer->GetFaxServerHandle(), (LPCTSTR)m_bstrGroupName)) { ec = GetLastError(); DebugPrintEx( DEBUG_ERR, _T("Fail to add group. (ec: %ld)"), ec); if (ERROR_DUP_NAME == ec) { DlgMsgBox(this, IDS_OUTGROUP_EXISTS); ::SetFocus(GetDlgItem(IDC_GROUPNAME_EDIT)); goto Exit; } else if (IsNetworkError(ec)) { DebugPrintEx( DEBUG_ERR, _T("Network Error was found. (ec: %ld)"), ec); m_pFaxServer->Disconnect(); } goto Error; } // // Step 3: Close the dialog // ATLASSERT(S_OK == hRc && ERROR_SUCCESS == ec); DebugPrintEx( DEBUG_MSG, _T("The group was added successfully.")); EndDialog(wID); goto Exit; Error: ATLASSERT(ERROR_SUCCESS != ec); hRc = HRESULT_FROM_WIN32(ec); PageErrorEx(IDS_FAIL_ADD_RULE, GetFaxServerErrorMsg(ec), m_hWnd); Exit: return FAILED(hRc) ? 0 : 1; } /* - CDlgNewFaxOutboundGroup::OnTextChanged - * Purpose: * Check the validity of text in side the text box. * * Arguments: * * Return: * 1 */ LRESULT CDlgNewFaxOutboundGroup::OnTextChanged(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled) { DEBUG_FUNCTION_NAME( _T("CDlgNewFaxOutboundGroup::OnTextChanged")); UINT fEnableOK; fEnableOK = ( m_GroupNameEdit.GetWindowTextLength() ); EnableOK(!!fEnableOK); return 0; } /* - CDlgNewFaxOutboundGroup::EnableOK - * Purpose: * Enable (disable) apply button. * * Arguments: * [in] fEnable - the value to enable the button * * Return: * void */ VOID CDlgNewFaxOutboundGroup::EnableOK(BOOL fEnable) { HWND hwndOK = GetDlgItem(IDOK); ::EnableWindow(hwndOK, fEnable); } /* - CDlgNewFaxOutboundGroup::OnCancel - * Purpose: * End dialog OnCancel. * * Arguments: * * Return: * 0 */ LRESULT CDlgNewFaxOutboundGroup::OnCancel(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled) { DEBUG_FUNCTION_NAME( _T("CDlgNewFaxOutboundGroup::OnCancel")); EndDialog(wID); return 0; } ////////////////////////////////////////////////////////////////////////////// /*++ CDlgNewFaxOutboundGroup::OnHelpRequest This is called in response to the WM_HELP Notify message and to the WM_CONTEXTMENU Notify message. WM_HELP Notify message. This message is sent when the user presses F1 or <Shift>-F1 over an item or when the user clicks on the ? icon and then presses the mouse over an item. WM_CONTEXTMENU Notify message. This message is sent when the user right clicks over an item and then clicks "What's this?" --*/ ///////////////////////////////////////////////////////////////////////////// LRESULT CDlgNewFaxOutboundGroup::OnHelpRequest(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& /*bHandled*/) { DEBUG_FUNCTION_NAME(_T("CDlgNewFaxOutboundGroup::OnHelpRequest")); switch (uMsg) { case WM_HELP: WinContextHelp(((LPHELPINFO)lParam)->dwContextId, m_hWnd); break; case WM_CONTEXTMENU: WinContextHelp(::GetWindowContextHelpId((HWND)wParam), m_hWnd); break; } return TRUE; } /////////////////////////////////////////////////////////////////////////////
25.104377
100
0.494769
npocmaka
58227999e366b68b268e91ee02a7abb3ae4b2416
1,303
cc
C++
epi/minimum_distance_3_sorted_arrays.cc
Vasniktel/interview-problems
ab901397194c81debe8c964fca097287466c9c27
[ "MIT" ]
null
null
null
epi/minimum_distance_3_sorted_arrays.cc
Vasniktel/interview-problems
ab901397194c81debe8c964fca097287466c9c27
[ "MIT" ]
null
null
null
epi/minimum_distance_3_sorted_arrays.cc
Vasniktel/interview-problems
ab901397194c81debe8c964fca097287466c9c27
[ "MIT" ]
null
null
null
#include <vector> #include "test_framework/generic_test.h" using std::vector; int FindClosestElementsInSortedArrays( const vector<vector<int>>& sorted_arrays) { assert(!sorted_arrays.empty()); auto comp = [&sorted_arrays](const auto& a, const auto& b) { return *a.first < *b.first; }; std::multiset<std::pair<vector<int>::const_iterator, vector<int>::const_iterator>, decltype(comp)> pq(comp); for (const auto& arr : sorted_arrays) { assert(!arr.empty()); pq.emplace(arr.cbegin(), arr.cend()); } int result = std::numeric_limits<int>::max(); while (true) { auto min_it = *pq.begin(); auto max_it = *pq.rbegin(); pq.erase(pq.begin()); int min = *min_it.first; int max = *max_it.first; result = std::min(result, max - min); ++min_it.first; if (min_it.first == min_it.second) break; pq.insert(min_it); } return result; } int main(int argc, char* argv[]) { std::vector<std::string> args{argv + 1, argv + argc}; std::vector<std::string> param_names{"sorted_arrays"}; return GenericTestMain(args, "minimum_distance_3_sorted_arrays.cc", "minimum_distance_3_sorted_arrays.tsv", &FindClosestElementsInSortedArrays, DefaultComparator{}, param_names); }
29.613636
110
0.637759
Vasniktel
58230841c6c441c46cc904126fd3e7ffe5b9ad4d
5,237
hpp
C++
contrib/lemur/include/lemur/Exception.hpp
whuang022nccu/IndriLab
24d13dca14c7c447a4acedb45d7d1ef83551f6ac
[ "Apache-2.0" ]
2
2020-02-16T07:46:47.000Z
2020-11-23T06:50:19.000Z
contrib/lemur/include/lemur/Exception.hpp
whuang022nccu/IndriLab
24d13dca14c7c447a4acedb45d7d1ef83551f6ac
[ "Apache-2.0" ]
null
null
null
contrib/lemur/include/lemur/Exception.hpp
whuang022nccu/IndriLab
24d13dca14c7c447a4acedb45d7d1ef83551f6ac
[ "Apache-2.0" ]
null
null
null
/*========================================================================== * Copyright (c) 2001 Carnegie Mellon University. All Rights Reserved. * * Use of the Lemur Toolkit for Language Modeling and Information Retrieval * is subject to the terms of the software license set forth in the LICENSE * file included with this software, and also available at * http://www.lemurproject.org/license.html * *========================================================================== */ #ifndef _EXCEPTION_HPP #define _EXCEPTION_HPP #include <iostream> #include <string> #include <sstream> using namespace std; namespace lemur { namespace api { /// Error codes. typedef unsigned long LemurErrorType; /// Default Exception class /*! This is the base Exception class that all other exceptions should inherit from. Some guidelines for using Exception: (1) Define your main function as "int AppMain(int argc, char *argv[])" rather than the normal "main" function. (2) Use the LEMUR_THROW and LEMUR_RETHROW macros to throw the exception, and to pass it along to the next level's handler, respectively. To use LEMUR_THROW, include the appropriate Lemur error code, and whatever string description you want. File and line information are automatically included. The error code can be from the standard Lemur list (see below). (3) Here's an example of how you might use LEMUR_THROW to generate an exception, and LEMUR_RETHROW to pass it along to the next handler. <PRE> try { ... ... // within the index open routine, this exception might be thrown: LEMUR_THROW(LEMUR_IO_ERROR, "The index file does not exist"); } catch (Exception &ex) { LEMUR_RETHROW(ex, "Could not start retrieval program."); } </PRE> In general, consistent use of LEMUR_THROW and LEMUR_RETHROW will result in a nested series of exception messages, showing successively lower levels of exception information, allowing easy tracing of the failure path. (4) If the exception is not caught in the application, it will be caught be the main function in the lemur toolkit. The default exception handler prints the following message on stderr and terminates the program. <PRE> Exception FileName.cpp(#linenum): The index file does not exist Program aborted due to exception </PRE> (5) You can define more specific exceptions by subclassing Exception. All exceptions will be caught by the default main function if not caught by an application. */ class Exception { public: Exception(const char *throwerString=" unknown thrower", const char *whatString="unknown exception") { _what = throwerString; _what += ": "; _what += whatString; } Exception( const std::string& whoString, int whereLine, const std::string& whatString, LemurErrorType code ) { std::stringstream lineString; lineString << whereLine; _what = whoString + "(" + lineString.str() + ")" + ": " + whatString; _code = code; } Exception( const std::string& whoString, int whereLine, const std::string& whatString, const Exception& inner ) { std::stringstream lineString; lineString << whereLine; _what = whoString + "(" + lineString.str() + "): " + whatString + "\n\t" + inner.what(); _code = inner.code(); } ~Exception() {} inline void writeMessage(std::ostream &os = std::cerr) { os << "Exception [code = " << _code << "]" << std::endl << _what << std::endl; } const std::string& what() const { return _what; } LemurErrorType code() const { return _code; } private: std::string _what; LemurErrorType _code; }; #define LEMUR_ABORT( e ) { std::cerr << e.what() << std::endl; exit(-1); } #define LEMUR_THROW_LINE( code, text, file, line ) throw lemur::api::Exception( file, line, std::string() + text, (code) ) #define LEMUR_THROW(code, text) LEMUR_THROW_LINE(code, text, __FILE__, __LINE__) #define LEMUR_RETHROW_LINE( e, text, file, line ) throw lemur::api::Exception( file, line, (std::string() + text), (e) ) #define LEMUR_RETHROW( e, text) LEMUR_RETHROW_LINE(e, text, __FILE__, __LINE__) #define LEMUR_GENERIC_ERROR ((lemur::api::LemurErrorType)0xFFFFFFFF) #define LEMUR_MISSING_PARAMETER_ERROR ((lemur::api::LemurErrorType)0xFFFFFFFE) #define LEMUR_BAD_PARAMETER_ERROR ((lemur::api::LemurErrorType)0xFFFFFFF7) #define LEMUR_PARSE_ERROR ((lemur::api::LemurErrorType)0xFFFFFFFD) #define LEMUR_KEYFILE_IO_ERROR ((lemur::api::LemurErrorType)0xFFFFFFFC) #define LEMUR_IO_ERROR ((lemur::api::LemurErrorType)0xFFFFFFFB) #define LEMUR_RUNTIME_ERROR ((lemur::api::LemurErrorType)0xFFFFFFFA) #define LEMUR_NETWORK_ERROR ((lemur::api::LemurErrorType)0xFFFFFFF9) #define LEMUR_INTERNAL_ERROR ((lemur::api::LemurErrorType)0xFFFFFFF8) } } #endif
37.676259
123
0.636051
whuang022nccu
5823aa62b92115ca96ff4014c9c5b9f0e6d9c619
973
cpp
C++
Uva-11677 - Alarm Clock.cpp
Samim-Arefin/UVa-Problem-Solution
8556639b9e718299f4a52920034dfa0264e06f8e
[ "MIT" ]
1
2020-11-02T22:18:22.000Z
2020-11-02T22:18:22.000Z
Uva-11677 - Alarm Clock.cpp
Samim-Arefin/UVa-Problem-Solution
8556639b9e718299f4a52920034dfa0264e06f8e
[ "MIT" ]
null
null
null
Uva-11677 - Alarm Clock.cpp
Samim-Arefin/UVa-Problem-Solution
8556639b9e718299f4a52920034dfa0264e06f8e
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; int main() { int H1, M1, H2, M2; while (cin >> H1 >> M1 >> H2 >> M2) { if (H1 == 0 && H2 == 0 && M1 == 0 && M2 == 0) { break; } else if (H1 > H2) { if (M1 > M2) { int temp = (60 + M2 - M1) + (60 * (24 + H2 - H1 - 1)); cout << temp << '\n'; } else { int temp = (60 * (24 + H2 - H1)) + (M2 - M1); cout << temp << '\n'; } } else { if (M1 > M2 && H1 == H2) { int temp = (M2 + 60 - M1) + (60 * (24 + H2 - H1 - 1)); cout << temp << '\n'; } else if (M1 == M2 && H1 == H2) { cout << "0\n"; } else if (M1 == M2 && H2 > H1) { int temp = (M2 - M1) + (60 * (H2 - H1)); cout << temp << '\n'; } else if (M1 > M2 && H2 > H1) { int temp = (M2 + 60 - M1) + (60 * (H2 - H1 - 1)); cout << temp << '\n'; } else if (M2 > M1 && H2 >= H1) { int temp = (M2 - M1) + (60 * (H2 - H1)); cout << temp << '\n'; } } } }
18.358491
58
0.362795
Samim-Arefin
58249e05c54f8356790cf7cc4c83efd01528233c
1,830
cpp
C++
aws-cpp-sdk-frauddetector/source/model/ListEventPredictionsRequest.cpp
truthiswill/aws-sdk-cpp
6e854b6a8bc7945f150c3a11551196bda341962a
[ "Apache-2.0" ]
1
2022-02-12T08:09:30.000Z
2022-02-12T08:09:30.000Z
aws-cpp-sdk-frauddetector/source/model/ListEventPredictionsRequest.cpp
truthiswill/aws-sdk-cpp
6e854b6a8bc7945f150c3a11551196bda341962a
[ "Apache-2.0" ]
1
2021-10-14T16:57:00.000Z
2021-10-18T10:47:24.000Z
aws-cpp-sdk-frauddetector/source/model/ListEventPredictionsRequest.cpp
truthiswill/aws-sdk-cpp
6e854b6a8bc7945f150c3a11551196bda341962a
[ "Apache-2.0" ]
1
2021-11-09T11:58:03.000Z
2021-11-09T11:58:03.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/frauddetector/model/ListEventPredictionsRequest.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::FraudDetector::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; ListEventPredictionsRequest::ListEventPredictionsRequest() : m_eventIdHasBeenSet(false), m_eventTypeHasBeenSet(false), m_detectorIdHasBeenSet(false), m_detectorVersionIdHasBeenSet(false), m_predictionTimeRangeHasBeenSet(false), m_nextTokenHasBeenSet(false), m_maxResults(0), m_maxResultsHasBeenSet(false) { } Aws::String ListEventPredictionsRequest::SerializePayload() const { JsonValue payload; if(m_eventIdHasBeenSet) { payload.WithObject("eventId", m_eventId.Jsonize()); } if(m_eventTypeHasBeenSet) { payload.WithObject("eventType", m_eventType.Jsonize()); } if(m_detectorIdHasBeenSet) { payload.WithObject("detectorId", m_detectorId.Jsonize()); } if(m_detectorVersionIdHasBeenSet) { payload.WithObject("detectorVersionId", m_detectorVersionId.Jsonize()); } if(m_predictionTimeRangeHasBeenSet) { payload.WithObject("predictionTimeRange", m_predictionTimeRange.Jsonize()); } if(m_nextTokenHasBeenSet) { payload.WithString("nextToken", m_nextToken); } if(m_maxResultsHasBeenSet) { payload.WithInteger("maxResults", m_maxResults); } return payload.View().WriteReadable(); } Aws::Http::HeaderValueCollection ListEventPredictionsRequest::GetRequestSpecificHeaders() const { Aws::Http::HeaderValueCollection headers; headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "AWSHawksNestServiceFacade.ListEventPredictions")); return headers; }
21.034483
111
0.751913
truthiswill
5824b9f76541e35107a905386262bfc985a1aac8
222
cpp
C++
src/DesktopCore/System/Services/TimerKillerService.cpp
lurume84/blink-desktop
d6d01f8dc461edd22192a521fbd49669bfa8f684
[ "MIT" ]
75
2019-03-08T14:15:49.000Z
2022-01-05T17:30:43.000Z
src/DesktopCore/System/Services/TimerKillerService.cpp
lurume84/blink-desktop
d6d01f8dc461edd22192a521fbd49669bfa8f684
[ "MIT" ]
55
2019-02-17T01:34:12.000Z
2022-02-26T21:07:33.000Z
src/DesktopCore/System/Services/TimerKillerService.cpp
lurume84/blink-desktop
d6d01f8dc461edd22192a521fbd49669bfa8f684
[ "MIT" ]
20
2019-05-21T19:02:31.000Z
2022-03-28T07:29:28.000Z
#include "TimerKillerService.h" namespace desktop { namespace core { namespace service { void TimerKillerService::kill() { std::unique_lock<std::mutex> lock(m_mutex); m_terminate = true; m_cv.notify_all(); } }}}
20.181818
56
0.716216
lurume84
5826c19e29f2924c6e3478834a6d68c2073aa17e
859
cpp
C++
LeetCode/NonDecreasingArray.cpp
SelvorWhim/competitive
b9daaf21920d6f7669dc0c525e903949f4e33b62
[ "Unlicense" ]
null
null
null
LeetCode/NonDecreasingArray.cpp
SelvorWhim/competitive
b9daaf21920d6f7669dc0c525e903949f4e33b62
[ "Unlicense" ]
null
null
null
LeetCode/NonDecreasingArray.cpp
SelvorWhim/competitive
b9daaf21920d6f7669dc0c525e903949f4e33b62
[ "Unlicense" ]
null
null
null
class Solution { public: bool checkPossibility(vector<int>& nums) { bool found_violation = false; for (int i = 1; i < nums.size(); i++) { if (nums[i] < nums[i-1]) { if (found_violation) { // 2nd case of decreasing, can't be fixed by changing one element return false; } if (i > 1 && i + 1 < nums.size() && nums[i-2] > nums[i] && nums[i-1] > nums[i+1]) { // any violation by an edge can be fixed // and any in the middle can be fixed by setting nums[i-1] = nums[i-2] or nums[i] = nums[i-1] // anything else (this case) can't be fixed return false; } found_violation = true; } } return true; } };
37.347826
113
0.447031
SelvorWhim
582754ef6f9eb36b59a3570653868aa0e5308799
4,018
cpp
C++
routing/routing_quality/utils.cpp
vmihaylenko/omim
00087f340e723fc611cbc82e0ae898b9053b620a
[ "Apache-2.0" ]
null
null
null
routing/routing_quality/utils.cpp
vmihaylenko/omim
00087f340e723fc611cbc82e0ae898b9053b620a
[ "Apache-2.0" ]
1
2019-05-14T15:26:55.000Z
2019-05-16T11:00:33.000Z
routing/routing_quality/utils.cpp
vmihaylenko/omim
00087f340e723fc611cbc82e0ae898b9053b620a
[ "Apache-2.0" ]
null
null
null
#include "routing/routing_quality/utils.hpp" #include "routing_common/num_mwm_id.hpp" #include "routing/index_router.hpp" #include "indexer/classificator_loader.hpp" #include "indexer/data_source.hpp" #include "storage/country_info_getter.hpp" #include "storage/country_parent_getter.hpp" #include "storage/routing_helpers.hpp" #include "platform/local_country_file.hpp" #include "platform/local_country_file_utils.hpp" #include "platform/platform.hpp" #include "geometry/mercator.hpp" #include "base/assert.hpp" #include "base/macros.hpp" #include "base/stl_helpers.hpp" #include <array> #include <limits> #include <memory> #include <utility> using namespace std; using namespace routing; namespace { class RouteGetter { public: static RouteGetter & Instance() { static RouteGetter instance; return instance; } routing_quality::RouteResult operator()(routing_quality::RoutePoints && waypoints, VehicleType type) { CHECK_LESS(type, VehicleType::Count, ()); auto const & infoGetter = *m_cig.get(); auto const countryFileGetter = [&infoGetter](m2::PointD const & pt) { return infoGetter.GetRegionCountryId(pt); }; auto const getMwmRectByName = [&infoGetter](string const & countryId) { return infoGetter.GetLimitRectForLeaf(countryId); }; auto const index = base::Underlying(type); if (!m_routers[index]) { m_routers[index] = make_unique<IndexRouter>(type, false /* load altitudes */, *m_cpg, countryFileGetter, getMwmRectByName, m_numMwmIds, MakeNumMwmTree(*m_numMwmIds, infoGetter), m_trafficCache, m_dataSource); } routing_quality::RouteResult result; result.m_code = m_routers[index]->CalculateRoute( Checkpoints(move(waypoints)), m2::PointD::Zero(), false /* adjustToPrevRoute */, m_delegate, result.m_route); return result; } private: RouteGetter() { CHECK(m_cig, ()); CHECK(m_cpg, ()); classificator::Load(); vector<platform::LocalCountryFile> localFiles; platform::FindAllLocalMapsAndCleanup(numeric_limits<int64_t>::max(), localFiles); for (auto const & localFile : localFiles) { UNUSED_VALUE(m_dataSource.RegisterMap(localFile)); auto const & countryFile = localFile.GetCountryFile(); auto const mwmId = m_dataSource.GetMwmIdByCountryFile(countryFile); CHECK(mwmId.IsAlive(), ()); // Only maps from countries.txt should be used for tests. if (m_cpg->GetStorageForTesting().IsLeaf(countryFile.GetName())) m_numMwmIds->RegisterFile(countryFile); } } DISALLOW_COPY_AND_MOVE(RouteGetter); FrozenDataSource m_dataSource; shared_ptr<NumMwmIds> m_numMwmIds = make_shared<NumMwmIds>(); array<unique_ptr<IndexRouter>, base::Underlying(VehicleType::Count)> m_routers{}; unique_ptr<storage::CountryParentGetter> m_cpg = make_unique<storage::CountryParentGetter>(); unique_ptr<storage::CountryInfoGetter> m_cig = storage::CountryInfoReader::CreateCountryInfoReader(GetPlatform()); traffic::TrafficCache m_trafficCache; RouterDelegate m_delegate; }; } // namespace namespace routing_quality { FollowedPolyline GetRouteFollowedPolyline(RouteParams && params) { CHECK_GREATER_OR_EQUAL(params.m_waypoints.size(), 2, ()); auto points = FromLatLon(params.m_waypoints); auto const result = RouteGetter::Instance()(move(points), params.m_type); CHECK_EQUAL(result.m_code, RouterResultCode::NoError, ()); CHECK(result.m_route.IsValid(), ()); return result.m_route.GetFollowedPolyline(); } RouteResult GetRoute(RoutePoints && waypoints, VehicleType type) { CHECK_GREATER_OR_EQUAL(waypoints.size(), 2, ()); return RouteGetter::Instance()(move(waypoints), type); } RoutePoints FromLatLon(Coordinates const & coords) { CHECK(!coords.empty(), ()); RoutePoints ret; ret.reserve(coords.size()); for (auto const & ll : coords) ret.emplace_back(MercatorBounds::FromLatLon(ll)); return ret; } } // namespace routing_quality
29.762963
116
0.723494
vmihaylenko
582ac84325bc1c07a2c9f19ac7e79109a53e495a
631
hpp
C++
include/game/skirmish/meta/boardmetaclass.hpp
namelessvoid/qrwar
bbc4036cd3bab6b0edcaccbc95286379ef51f12b
[ "MIT" ]
3
2015-03-28T02:51:58.000Z
2018-11-08T16:49:53.000Z
include/game/skirmish/meta/boardmetaclass.hpp
namelessvoid/qrwar
bbc4036cd3bab6b0edcaccbc95286379ef51f12b
[ "MIT" ]
39
2015-05-18T08:29:16.000Z
2020-07-18T21:17:44.000Z
include/game/skirmish/meta/boardmetaclass.hpp
namelessvoid/qrwar
bbc4036cd3bab6b0edcaccbc95286379ef51f12b
[ "MIT" ]
null
null
null
#ifndef QRW_BOARDMETACLASS_HPP #define QRW_BOARDMETACLASS_HPP #include "meta/metaclass.hpp" #include "meta/properties/iproperty.hpp" #include "engine/board.hpp" namespace qrw { class BoardMetaClass final : public MetaClass { public: BoardMetaClass(const MetaManager& metaManager); ~BoardMetaClass() override = default; virtual void serialize(const Reflectable* object, YAML::Emitter& out) const final override; virtual Reflectable* deserialize(const YAML::Node& in) const final override; private: std::array<std::unique_ptr<IProperty>,4> properties_; }; } // namespace qrw #endif // QRW_BOARDMETACLASS_HPP
21.033333
92
0.767036
namelessvoid
582b616e9b1b1ae42b7f74c0a6d865ca2723b72a
412
cpp
C++
Lecture7/ArrayStudy/ArrayStudy/main.cpp
sgajaejung/API-Lecture
904be7efdcc0e2eb40fbb9e4aa600b6598921392
[ "MIT" ]
2
2015-11-27T07:24:49.000Z
2017-09-07T09:33:14.000Z
Lecture7/ArrayStudy/ArrayStudy/main.cpp
sgajaejung/API-Lecture
904be7efdcc0e2eb40fbb9e4aa600b6598921392
[ "MIT" ]
null
null
null
Lecture7/ArrayStudy/ArrayStudy/main.cpp
sgajaejung/API-Lecture
904be7efdcc0e2eb40fbb9e4aa600b6598921392
[ "MIT" ]
1
2021-02-09T15:49:37.000Z
2021-02-09T15:49:37.000Z
#include <iostream> using namespace std; void main() { int ar1[10][10] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; int **ar2; ar2 = new int*[ 10]; for (int i=0; i < 10; ++i) { ar2[ i] = new int[ 10]; } ar2[ 0][ 0] = 1; ar2[ 0][ 1] = 2; cout << ar1[ 0][ 0] << endl; cout << ar2[ 0][ 0] << endl; cout << *(int*)ar1 << endl; cout << *(int*)ar2 << endl; cout << *(int*)*(int*)ar2 << endl; }
12.875
35
0.444175
sgajaejung
582bfcd91b38d45c90dec277ec1fa53a01f3365f
824
cpp
C++
C++/tests/problems/0150_search_suggestions_system_test.cpp
oxone-999/algorithms
52dc527111e7422923a0e25684d8f4837e81a09b
[ "MIT" ]
6
2019-03-20T22:23:26.000Z
2020-08-28T03:10:27.000Z
C++/tests/problems/0150_search_suggestions_system_test.cpp
oxone-999/algorithms
52dc527111e7422923a0e25684d8f4837e81a09b
[ "MIT" ]
15
2019-10-13T20:53:53.000Z
2022-03-31T02:01:35.000Z
C++/tests/problems/0150_search_suggestions_system_test.cpp
oxone-999/algorithms
52dc527111e7422923a0e25684d8f4837e81a09b
[ "MIT" ]
3
2019-03-11T10:57:46.000Z
2020-02-26T21:13:21.000Z
#include "../../problems/0150_search_suggestions_system.hpp" #include <bits/stdc++.h> #include "../../frameworks/catch.hpp" #include "../../frameworks/asserts.hpp" using namespace std; TEST_CASE( "Search Suggestions System" ) { Solution sol; vector<string> products1 = {"mobile","mouse","moneypot","monitor","mousepad"}; vector<vector<string>> result1 = {{"mobile","moneypot","monitor"},{"mobile","moneypot","monitor"},{"mouse","mousepad"},{"mouse","mousepad"},{"mouse","mousepad"}}; REQUIRE( areVectorsEqual(sol.suggestedProducts(products1,"mouse"),result1) ); vector<string> products2 = {"havana"}; vector<vector<string>> result2 = {{"havana"},{"havana"},{"havana"},{"havana"},{"havana"},{"havana"}}; REQUIRE( areVectorsEqual(sol.suggestedProducts(products2,"havana"),result2) ); }
43.368421
166
0.669903
oxone-999
58312b795a02f436a5b1ebe26a7f9d64d2b6db4a
256
cpp
C++
Notes_Week8/Exception/stdException.cpp
WeiChienHsu/CS165
65e95efc90415c8acc707e2d544eb384d3982e18
[ "MIT" ]
1
2019-01-06T22:36:01.000Z
2019-01-06T22:36:01.000Z
Notes_Week8/Exception/stdException.cpp
WeiChienHsu/CS165
65e95efc90415c8acc707e2d544eb384d3982e18
[ "MIT" ]
null
null
null
Notes_Week8/Exception/stdException.cpp
WeiChienHsu/CS165
65e95efc90415c8acc707e2d544eb384d3982e18
[ "MIT" ]
null
null
null
#include <iostream> #include <stdexcept> #include <vector> int main() { std::vector<int> v; v.push_back(10); try { std::cout << v.at(15) << std::endl; } catch(std::out_of_range e) { std::cout << e.what() << std::endl; } return 0; }
17.066667
41
0.566406
WeiChienHsu
5831d734eb7eefb0d9bf00be7c1cad236df1df65
543
hh
C++
wcd/include/world.hh
lagoproject/sims
bc34510b803136c770ecd9c789dc7cfade2ccbbd
[ "BSD-3-Clause" ]
null
null
null
wcd/include/world.hh
lagoproject/sims
bc34510b803136c770ecd9c789dc7cfade2ccbbd
[ "BSD-3-Clause" ]
null
null
null
wcd/include/world.hh
lagoproject/sims
bc34510b803136c770ecd9c789dc7cfade2ccbbd
[ "BSD-3-Clause" ]
null
null
null
#ifndef world_h #define world_h 1 // Geant4 Libraries // #include "G4Material.hh" #include "G4LogicalVolume.hh" #include "G4PVPlacement.hh" #include "G4Box.hh" // Local Libraries // class world { public: world(); virtual ~world(); void DefineMaterials(); void buildDetector(G4bool* overLaps); G4LogicalVolume* getLogVolume(); G4VPhysicalVolume* getPhysVolume(); private: G4Material* expHall_mat; G4Box* expHall_geo; G4LogicalVolume* expHall_log; G4VPhysicalVolume* expHall_phys; }; #endif
15.083333
41
0.697974
lagoproject
58329699f0f654ba61c1a53bb753f8ea5a77d38e
651
cpp
C++
s01-installation-openframeworks-basics/01-basics/src/main.cpp
pkmital/MTIID-MTEC-616-01-2017
c5f7f24c531cda3a48dbd974f46c08fa504dd06d
[ "Apache-2.0" ]
13
2017-01-16T07:16:51.000Z
2019-07-19T04:11:36.000Z
s01-installation-openframeworks-basics/01-basics/src/main.cpp
pkmital/MTIID-MTEC-616-01-2017
c5f7f24c531cda3a48dbd974f46c08fa504dd06d
[ "Apache-2.0" ]
null
null
null
s01-installation-openframeworks-basics/01-basics/src/main.cpp
pkmital/MTIID-MTEC-616-01-2017
c5f7f24c531cda3a48dbd974f46c08fa504dd06d
[ "Apache-2.0" ]
4
2017-05-29T15:43:45.000Z
2019-07-19T04:11:42.000Z
#include "ofMain.h" class ofApp : public ofBaseApp{ public: void setup() { cam.setup(width, height); ofSetWindowShape(width, height); ofSetFrameRate(60); } void update() { cam.update(); } void draw() { cam.draw(0, 0, ofGetWidth(), ofGetHeight()); } void keyPressed(int key) { if (key == 'f') { ofToggleFullscreen(); } } void mouseMoved( int x, int y ){ } private: ofVideoGrabber cam; int width = 640; int height = 480; }; int main(){ ofSetupOpenGL(1024, 768, OF_WINDOW); ofRunApp(new ofApp()); }
16.275
52
0.519201
pkmital
5837fb7499389925fc6205caa772c3f38acc3d6a
8,762
cpp
C++
sycl/test/basic_tests/buffer/subbuffer_interop.cpp
jcranmer-intel/llvm-sycl
45dbbd128e4793681ed9d40a3c018f44c17449ec
[ "Apache-2.0" ]
null
null
null
sycl/test/basic_tests/buffer/subbuffer_interop.cpp
jcranmer-intel/llvm-sycl
45dbbd128e4793681ed9d40a3c018f44c17449ec
[ "Apache-2.0" ]
null
null
null
sycl/test/basic_tests/buffer/subbuffer_interop.cpp
jcranmer-intel/llvm-sycl
45dbbd128e4793681ed9d40a3c018f44c17449ec
[ "Apache-2.0" ]
null
null
null
// RUN: %clangxx -fsycl %s -o %t.out -lOpenCL // RUN: %CPU_RUN_PLACEHOLDER %t.out // RUN: %GPU_RUN_PLACEHOLDER %t.out // RUN: %ACC_RUN_PLACEHOLDER %t.out //==------------ subbuffer_interop.cpp - SYCL buffer basic test ------------==// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include <CL/sycl.hpp> #include <cassert> #include <memory> using namespace cl::sycl; const std::string clKernelSourceCodeSimple = "\ __kernel void test(__global int* a, __global int* b) {\ int i = get_global_id(0);\ if (i < 256) { \ b[i] = 0; \ } \ }"; const std::string clKernelSourceCodeNonOverlap = "\ __kernel void test(__global int* a, __global int* b, __global int *c) {\ int i = get_global_id(0);\ if (i < 128) { \ b[i] = 0; \ } \ if (i >= 256 && i < 384) { \ c[i - 256] = 0; \ } \ }"; const std::string clKernelSourceCodeOverlap = "\ __kernel void test1(__global int* a, __global int* b) {\ int i = get_global_id(0);\ if (i < 256) { \ b[i] = 0; \ } \ } \ __kernel void test2(__global int* a, __global int* b) {\ int i = get_global_id(0);\ if (i < 128) { \ b[i] = 1; \ } \ }"; int main() { bool Failed = false; { // Test if we can write into subbufer from OpenCL code. const size_t NSize = 512; cl_int Error = CL_SUCCESS; int AMem[NSize]; for (size_t i = 0; i < NSize; i++) { AMem[i] = i; } try { queue TestQueue; const char *SrcString[] = {clKernelSourceCodeSimple.c_str()}; const size_t SrcStringSize = clKernelSourceCodeSimple.size(); cl_context clContext = TestQueue.get_context().get(); cl_device_id clDevice = TestQueue.get_device().get(); cl_program clProgram = clCreateProgramWithSource(clContext, 1, SrcString, &SrcStringSize, &Error); CHECK_OCL_CODE(Error); Error = clBuildProgram(clProgram, 1, &clDevice, NULL, NULL, NULL); CHECK_OCL_CODE(Error); cl_kernel clKernel = clCreateKernel(clProgram, "test", &Error); CHECK_OCL_CODE(Error); buffer<int, 1> BufA(AMem, cl::sycl::range<1>(NSize)); buffer<int, 1> BufB(BufA, NSize / 2, NSize / 2); kernel TestKernel(clKernel, TestQueue.get_context()); TestQueue.submit([&](handler &cgh) { auto a_acc = BufA.get_access<access::mode::read>(cgh); auto b_acc = BufB.get_access<access::mode::write>(cgh); cgh.set_arg(0, a_acc); cgh.set_arg(1, b_acc); cgh.parallel_for(range<1>(NSize), TestKernel); }); clReleaseKernel(clKernel); clReleaseProgram(clProgram); } catch (exception &ex) { std::cout << ex.what() << std::endl; } for (int i = 0; i < NSize; ++i) { if (i < NSize / 2 && AMem[i] != i) { std::cout << " array[" << i << "] is " << AMem[i] << " expected " << i << std::endl; assert(false); Failed = true; } else if (i >= NSize / 2 && AMem[i] != 0) { std::cout << " array[" << i << "] is " << AMem[i] << " expected " << 0 << std::endl; assert(false); Failed = true; } } } { // Test if we can use two sub buffers, pointing to one buffer, from OpenCL. const size_t NSize = 512; cl_int Error = CL_SUCCESS; int AMem[NSize]; for (size_t i = 0; i < NSize; i++) { AMem[i] = i; } try { queue TestQueue; const char *SrcString[] = {clKernelSourceCodeNonOverlap.c_str()}; const size_t SrcStringSize = clKernelSourceCodeNonOverlap.size(); cl_context clContext = TestQueue.get_context().get(); cl_device_id clDevice = TestQueue.get_device().get(); cl_program clProgram = clCreateProgramWithSource(clContext, 1, SrcString, &SrcStringSize, &Error); CHECK_OCL_CODE(Error); Error = clBuildProgram(clProgram, 1, &clDevice, NULL, NULL, NULL); CHECK_OCL_CODE(Error); cl_kernel clKernel = clCreateKernel(clProgram, "test", &Error); CHECK_OCL_CODE(Error); buffer<int, 1> BufA(AMem, cl::sycl::range<1>(NSize)); buffer<int, 1> BufB(BufA, 0, NSize / 4); buffer<int, 1> BufC(BufA, 2 * NSize / 4, NSize / 4); kernel TestKernel(clKernel, TestQueue.get_context()); TestQueue.submit([&](handler &cgh) { auto a_acc = BufA.get_access<access::mode::read>(cgh); auto b_acc = BufB.get_access<access::mode::write>(cgh); auto c_acc = BufC.get_access<access::mode::write>(cgh); cgh.set_arg(0, a_acc); cgh.set_arg(1, b_acc); cgh.set_arg(2, c_acc); cgh.parallel_for(range<1>(NSize), TestKernel); }); clReleaseKernel(clKernel); clReleaseProgram(clProgram); } catch (exception &ex) { std::cout << ex.what() << std::endl; } for (int i = 0; i < NSize; ++i) { if (i < NSize / 4 && AMem[i] != 0) { std::cout << " array[" << i << "] is " << AMem[i] << " expected " << 0 << std::endl; assert(false); Failed = true; } else if (i >= NSize / 4 && i < 2 * NSize / 4 && AMem[i] != i) { std::cout << " array[" << i << "] is " << AMem[i] << " expected " << i << std::endl; assert(false); Failed = true; } else if (i >= 2 * NSize / 4 && i < 3 * NSize / 4 && AMem[i] != 0) { std::cout << " array[" << i << "] is " << AMem[i] << " expected " << 0 << std::endl; assert(false); Failed = true; } else if (i >= 3 * NSize / 4 && AMem[i] != i) { std::cout << " array[" << i << "] is " << AMem[i] << " expected " << i << std::endl; assert(false); Failed = true; } } } { // Test if we can use two sub buffers, pointing to one buffer, from // two different OpenCL kernels. const size_t NSize = 512; cl_int Error = CL_SUCCESS; int AMem[NSize]; for (size_t i = 0; i < NSize; i++) { AMem[i] = i; } try { queue TestQueue; const char *SrcString[] = {clKernelSourceCodeOverlap.c_str()}; const size_t SrcStringSize = clKernelSourceCodeOverlap.size(); cl_context clContext = TestQueue.get_context().get(); cl_device_id clDevice = TestQueue.get_device().get(); cl_program clProgram = clCreateProgramWithSource(clContext, 1, SrcString, &SrcStringSize, &Error); CHECK_OCL_CODE(Error); Error = clBuildProgram(clProgram, 1, &clDevice, NULL, NULL, NULL); CHECK_OCL_CODE(Error); cl_kernel clKernel1 = clCreateKernel(clProgram, "test1", &Error); CHECK_OCL_CODE(Error); cl_kernel clKernel2 = clCreateKernel(clProgram, "test2", &Error); CHECK_OCL_CODE(Error); buffer<int, 1> BufA(AMem, cl::sycl::range<1>(NSize)); buffer<int, 1> BufB(BufA, 0, NSize / 2); buffer<int, 1> BufC(BufA, NSize / 4, NSize / 4); kernel TestKernel1(clKernel1, TestQueue.get_context()); kernel TestKernel2(clKernel2, TestQueue.get_context()); TestQueue.submit([&](handler &cgh) { auto a_acc = BufA.get_access<access::mode::read>(cgh); auto b_acc = BufB.get_access<access::mode::write>(cgh); cgh.set_arg(0, a_acc); cgh.set_arg(1, b_acc); cgh.parallel_for(range<1>(NSize), TestKernel1); }); TestQueue.submit([&](handler &cgh) { auto a_acc = BufA.get_access<access::mode::read>(cgh); auto c_acc = BufC.get_access<access::mode::write>(cgh); cgh.set_arg(0, a_acc); cgh.set_arg(1, c_acc); cgh.parallel_for(range<1>(NSize), TestKernel2); }); clReleaseKernel(clKernel1); clReleaseKernel(clKernel2); clReleaseProgram(clProgram); } catch (exception &ex) { std::cout << ex.what() << std::endl; } for (int i = 0; i < NSize; ++i) { if (i < NSize / 4 && AMem[i] != 0) { std::cout << " array[" << i << "] is " << AMem[i] << " expected " << 0 << std::endl; assert(false); Failed = true; } else if (i >= NSize / 4 && i < 2 * NSize / 4 && AMem[i] != 1) { std::cout << " array[" << i << "] is " << AMem[i] << " expected " << i << std::endl; assert(false); Failed = true; } else if (i >= 2 * NSize / 4 && AMem[i] != i) { std::cout << " array[" << i << "] is " << AMem[i] << " expected " << i << std::endl; assert(false); Failed = true; } } } return Failed; }
30.74386
85
0.548505
jcranmer-intel
58382202eab09296fbd2a8c829b3ee6d9344e0c4
2,533
cpp
C++
src/types/Range.cpp
LumpBloom7/cligCore
ddd26787128fbed1724dba66e90673ffa8b5ed2e
[ "MIT" ]
null
null
null
src/types/Range.cpp
LumpBloom7/cligCore
ddd26787128fbed1724dba66e90673ffa8b5ed2e
[ "MIT" ]
7
2018-04-03T07:48:22.000Z
2018-07-19T12:34:19.000Z
src/types/Range.cpp
LumpBloom7/cligCore
ddd26787128fbed1724dba66e90673ffa8b5ed2e
[ "MIT" ]
1
2018-01-07T05:30:11.000Z
2018-01-07T05:30:11.000Z
#include "Types/Range.h" namespace cligCore::types { Range::Range() : _lower(0), _upper(10), _current(0), _isSelectable(false) {} Range::Range(int lowerBounds, int upperBounds, bool isSelectable) { // Differentiate the smaller value from the bigger value to ease processing and to avoid any potential bugs. _lower = (lowerBounds <= upperBounds) ? lowerBounds : upperBounds; _upper = (lowerBounds <= upperBounds) ? upperBounds : lowerBounds; _isSelectable = isSelectable; _current = _lower; } Range::Range(int lowerBounds, int upperBounds, int currentVal) { // Differentiate the smaller value from the bigger value to ease processing and to avoid any potential bugs. _lower = (lowerBounds <= upperBounds) ? lowerBounds : upperBounds; _upper = (lowerBounds <= upperBounds) ? upperBounds : lowerBounds; _isSelectable = true; _current = (currentVal >= _lower && currentVal <= _upper) ? currentVal : _lower; } int Range::getLower() { return _lower; } int Range::getUpper() { return _upper; } void Range::setLower(int value) { _lower = value; } void Range::setUpper(int value) { _upper = value; } void Range::shift(int value) { _lower += value; _upper += value; } void cligCore::types::Range::showChooser(const std::string& title) { cligCore::console::clear(); int current = _current; std::cout << rang::style::underline << title << rang::style::reset << "\n" << "Please select a value between " << _lower << " and " << _upper << "." << std::endl << std::endl << (current == _lower ? " " : " < ") << current << (current == _upper ? " " : " > ") << " \r" << std::flush; bool failsafe = false; while (true) { if (!failsafe) { cligCore::input::getKeyInput(); failsafe = true; } switch (cligCore::input::getKeyInput()) { case cligCore::input::Keys::Right: { if (current < _upper) current++; std::cout << (current == _lower ? " " : " < ") << current << (current == _upper ? " " : " > ") << " \r" << std::flush; break; } case cligCore::input::Keys::Left: { if (current > _lower) current--; std::cout << (current == _lower ? " " : " < ") << current << (current == _upper ? " " : " > ") << " \r" << std::flush; break; } case cligCore::input::Keys::Enter: { _current = current; } case cligCore::input::Keys::Escape: { return; } } } } int Range::getCurrent() { return _current; } }
37.80597
143
0.591788
LumpBloom7
583887c908a56ad9fdec018f50870942a6bd7b3a
827
hh
C++
redemption/src/capture/ocr/extract_data.hh
DianaAssistant/DIANA
6a4c51c1861f6a936941b21c2c905fc291c229d7
[ "MIT" ]
null
null
null
redemption/src/capture/ocr/extract_data.hh
DianaAssistant/DIANA
6a4c51c1861f6a936941b21c2c905fc291c229d7
[ "MIT" ]
null
null
null
redemption/src/capture/ocr/extract_data.hh
DianaAssistant/DIANA
6a4c51c1861f6a936941b21c2c905fc291c229d7
[ "MIT" ]
null
null
null
#pragma once #include "fonts.hpp" namespace ocr { // Some parameters // *Binarization // \{ static const int fuzzy = 45; // Hyper-connectivity, alpha flat zone (for color gradient) // \} // *Reconstruction // \{ static const unsigned bbox_padding = 3u * 2u; // Padding between text and border (top and bottom) // Height of title bars static const unsigned bbox_max_height = std::max(fonts::max_height_font[0], fonts::max_height_font[1]) + 1u; /*NOLINT*/ // Height of title bars static const unsigned bbox_min_height = std::max(fonts::min_height_font[0], fonts::min_height_font[1]) + 1u; /*NOLINT*/ static const unsigned bbox_treshold = 2; // Tolerance to title bar height static const unsigned bbox_min_width = 100; // Min width of title bar // \} } // namespace ocr
37.590909
148
0.67231
DianaAssistant
583a15db9b1c4698165c2c83484aba9a35a07469
8,479
cpp
C++
src/app/tests/suites/commands/interaction_model/InteractionModel.cpp
lcj446068124/connectedhomeip
145d7bf80a4c433e45cbf5da4d3124b27e183764
[ "Apache-2.0" ]
2
2021-12-29T21:46:00.000Z
2021-12-31T16:12:12.000Z
src/app/tests/suites/commands/interaction_model/InteractionModel.cpp
lcj446068124/connectedhomeip
145d7bf80a4c433e45cbf5da4d3124b27e183764
[ "Apache-2.0" ]
2
2022-02-21T13:52:24.000Z
2022-03-21T10:38:57.000Z
src/app/tests/suites/commands/interaction_model/InteractionModel.cpp
lcj446068124/connectedhomeip
145d7bf80a4c433e45cbf5da4d3124b27e183764
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2022 Project CHIP Authors * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include "InteractionModel.h" using namespace chip; using namespace chip::app; CHIP_ERROR InteractionModel::ReadAttribute(const char * identity, EndpointId endpointId, ClusterId clusterId, AttributeId attributeId, bool fabricFiltered) { DeviceProxy * device = GetDevice(identity); VerifyOrReturnError(device != nullptr, CHIP_ERROR_INCORRECT_STATE); AttributePathParams attributePathParams[1]; if (endpointId != kInvalidEndpointId) { attributePathParams[0].mEndpointId = endpointId; } if (clusterId != kInvalidClusterId) { attributePathParams[0].mClusterId = clusterId; } if (attributeId != kInvalidAttributeId) { attributePathParams[0].mAttributeId = attributeId; } ReadPrepareParams params(device->GetSecureSession().Value()); params.mpEventPathParamsList = nullptr; params.mEventPathParamsListSize = 0; params.mpAttributePathParamsList = attributePathParams; params.mAttributePathParamsListSize = 1; params.mIsFabricFiltered = fabricFiltered; mReadClient = std::make_unique<ReadClient>(InteractionModelEngine::GetInstance(), device->GetExchangeManager(), mBufferedReadAdapter, ReadClient::InteractionType::Read); return mReadClient->SendRequest(params); } CHIP_ERROR InteractionModel::ReadEvent(const char * identity, EndpointId endpointId, ClusterId clusterId, EventId eventId, bool fabricFiltered) { DeviceProxy * device = GetDevice(identity); VerifyOrReturnError(device != nullptr, CHIP_ERROR_INCORRECT_STATE); EventPathParams eventPathParams[1]; if (endpointId != kInvalidEndpointId) { eventPathParams[0].mEndpointId = endpointId; } if (clusterId != kInvalidClusterId) { eventPathParams[0].mClusterId = clusterId; } if (eventId != kInvalidEventId) { eventPathParams[0].mEventId = eventId; } ReadPrepareParams params(device->GetSecureSession().Value()); params.mpEventPathParamsList = eventPathParams; params.mEventPathParamsListSize = 1; params.mpAttributePathParamsList = nullptr; params.mAttributePathParamsListSize = 0; params.mIsFabricFiltered = fabricFiltered; // TODO: Add data version supports mReadClient = std::make_unique<ReadClient>(InteractionModelEngine::GetInstance(), device->GetExchangeManager(), mBufferedReadAdapter, ReadClient::InteractionType::Read); VerifyOrReturnError(mReadClient != nullptr, CHIP_ERROR_NO_MEMORY); return mReadClient->SendRequest(params); } CHIP_ERROR InteractionModel::SubscribeAttribute(const char * identity, EndpointId endpointId, ClusterId clusterId, AttributeId attributeId, uint16_t minInterval, uint16_t maxInterval, bool fabricFiltered) { DeviceProxy * device = GetDevice(identity); VerifyOrReturnError(device != nullptr, CHIP_ERROR_INCORRECT_STATE); AttributePathParams attributePathParams[1]; if (endpointId != kInvalidEndpointId) { attributePathParams[0].mEndpointId = endpointId; } if (clusterId != kInvalidClusterId) { attributePathParams[0].mClusterId = clusterId; } if (attributeId != kInvalidAttributeId) { attributePathParams[0].mAttributeId = attributeId; } ReadPrepareParams params(device->GetSecureSession().Value()); params.mpEventPathParamsList = nullptr; params.mEventPathParamsListSize = 0; params.mpAttributePathParamsList = attributePathParams; params.mAttributePathParamsListSize = 1; params.mMinIntervalFloorSeconds = minInterval; params.mMaxIntervalCeilingSeconds = maxInterval; params.mIsFabricFiltered = fabricFiltered; mSubscribeClient = std::make_unique<ReadClient>(InteractionModelEngine::GetInstance(), device->GetExchangeManager(), mBufferedReadAdapter, ReadClient::InteractionType::Subscribe); VerifyOrReturnError(mSubscribeClient != nullptr, CHIP_ERROR_NO_MEMORY); return mSubscribeClient->SendRequest(params); } CHIP_ERROR InteractionModel::SubscribeEvent(const char * identity, EndpointId endpointId, ClusterId clusterId, EventId eventId, uint16_t minInterval, uint16_t maxInterval, bool fabricFiltered) { DeviceProxy * device = GetDevice(identity); VerifyOrReturnError(device != nullptr, CHIP_ERROR_INCORRECT_STATE); EventPathParams eventPathParams[1]; if (endpointId != kInvalidEndpointId) { eventPathParams[0].mEndpointId = endpointId; } if (clusterId != kInvalidClusterId) { eventPathParams[0].mClusterId = clusterId; } if (eventId != kInvalidEventId) { eventPathParams[0].mEventId = eventId; } ReadPrepareParams params(device->GetSecureSession().Value()); params.mpEventPathParamsList = eventPathParams; params.mEventPathParamsListSize = 1; params.mpAttributePathParamsList = nullptr; params.mAttributePathParamsListSize = 0; params.mMinIntervalFloorSeconds = minInterval; params.mMaxIntervalCeilingSeconds = maxInterval; params.mIsFabricFiltered = fabricFiltered; mSubscribeClient = std::make_unique<ReadClient>(InteractionModelEngine::GetInstance(), device->GetExchangeManager(), mBufferedReadAdapter, ReadClient::InteractionType::Subscribe); VerifyOrReturnError(mSubscribeClient != nullptr, CHIP_ERROR_NO_MEMORY); return mSubscribeClient->SendRequest(params); } void InteractionModel::Shutdown() { mReadClient.reset(); mSubscribeClient.reset(); mWriteClient.reset(); mCommandSender.reset(); } /////////// ReadClient Callback Interface ///////// void InteractionModel::OnAttributeData(const ConcreteDataAttributePath & path, TLV::TLVReader * data, const StatusIB & status) { OnResponse(status, data); } void InteractionModel::OnEventData(const EventHeader & eventHeader, TLV::TLVReader * data, const StatusIB * status) { OnResponse(status == nullptr ? StatusIB() : *status, data); } void InteractionModel::OnError(CHIP_ERROR error) { StatusIB status(error); OnResponse(status, nullptr); } void InteractionModel::OnDone() { mReadClient.reset(); // TODO: Close the subscribe client ContinueOnChipMainThread(CHIP_NO_ERROR); } void InteractionModel::OnSubscriptionEstablished(uint64_t subscriptionId) { ContinueOnChipMainThread(CHIP_NO_ERROR); } /////////// WriteClient Callback Interface ///////// void InteractionModel::OnResponse(const WriteClient * client, const ConcreteDataAttributePath & path, StatusIB status) { OnResponse(status, nullptr); } void InteractionModel::OnError(const WriteClient * client, CHIP_ERROR error) { StatusIB status(error); OnResponse(status, nullptr); } void InteractionModel::OnDone(WriteClient * client) { mWriteClient.reset(); ContinueOnChipMainThread(CHIP_NO_ERROR); } /////////// CommandSender Callback Interface ///////// void InteractionModel::OnResponse(CommandSender * client, const ConcreteCommandPath & path, const StatusIB & status, TLV::TLVReader * data) { OnResponse(status, data); } void InteractionModel::OnError(const CommandSender * client, CHIP_ERROR error) { StatusIB status(error); OnResponse(status, nullptr); } void InteractionModel::OnDone(CommandSender * client) { mCommandSender.reset(); ContinueOnChipMainThread(CHIP_NO_ERROR); }
34.46748
127
0.693478
lcj446068124
583a6ed68848eabcc419798f3c580e6c187de8d6
2,515
cpp
C++
src/bitsyc.cpp
SimplyDanny/bitsy-llvm
125e404388ef65847eac8cb533c5321a2289bb85
[ "MIT" ]
4
2021-01-07T10:29:49.000Z
2021-07-17T22:10:54.000Z
src/bitsyc.cpp
SimplyDanny/bitsy-llvm
125e404388ef65847eac8cb533c5321a2289bb85
[ "MIT" ]
null
null
null
src/bitsyc.cpp
SimplyDanny/bitsy-llvm
125e404388ef65847eac8cb533c5321a2289bb85
[ "MIT" ]
2
2021-02-07T21:15:20.000Z
2021-07-17T22:10:55.000Z
#include "ast/ASTPrinter.hpp" #include "codegen/CodeGenerator.hpp" #include "codegen/ModuleBuilder.hpp" #include "execution/ModuleProcessor.hpp" #include "lexer/Lexer.hpp" #include "parser/Parser.hpp" #include "llvm/Support/CommandLine.h" #include <fstream> #include <iostream> #include <iterator> namespace cl = llvm::cl; namespace { namespace opt { cl::OptionCategory category{"Options"}; cl::opt<std::string> input_name{cl::Positional, cl::Required, cl::desc("<bitsy file>"), cl::cat(category)}; cl::opt<std::string> output_name{"o", cl::desc("Name of the executable output file"), cl::value_desc("executable"), cl::init("a.out"), cl::cat(category)}; cl::opt<bool> compile{"c", cl::desc("Compile Bitsy file to an exectuable output file"), cl::cat(category)}; cl::opt<bool> quiet{"q", cl::desc("Do not execute the program automatically"), cl::cat(category)}; cl::opt<bool> no_optimization{"no-opt", cl::desc("Do not run any optimization"), cl::cat(category)}; cl::opt<bool> show_cfg{"show-cfg", cl::desc("Show CFG or create an image of it"), cl::cat(category)}; cl::opt<bool> show_ast{"show-ast", cl::desc("Print the internally used AST"), cl::cat(category)}; }} // namespace ::opt int main(int argc, char *argv[]) { cl::HideUnrelatedOptions(opt::category); cl::ParseCommandLineOptions(argc, argv, "Compiler for Bitsy programs", nullptr, nullptr, true); std::ifstream file_stream{opt::input_name}; if (!file_stream.good()) { std::cerr << "Cannot open the input file." << std::endl; return 1; } Lexer<std::istreambuf_iterator<char>> lexer{file_stream, {}}; std::vector<Token> tokens{lexer, decltype(lexer)()}; Parser parser{tokens}; auto main_block = parser.parse(); ModuleBuilder builder{main_block.get()}; ModuleProcessor processor{builder.build(), opt::output_name}; if (processor.verify()) { return 2; } if (!opt::no_optimization) { processor.optimize(); } if (opt::compile) { if (processor.compile() != 0) { return 3; } } if (opt::show_cfg) { if (!processor.show_cfg()) { return 4; } } if (opt::show_ast) { ASTPrinter().visit(llvm::cast<Statement>(main_block.get())); } if (opt::quiet || opt::show_cfg || opt::show_ast) { return 0; } return processor.execute(); }
32.662338
107
0.612326
SimplyDanny
583a906cdfac1b1b4b92c46c4730ce1ef429585d
4,849
cxx
C++
main/framework/source/uifactory/statusbarfactory.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/framework/source/uifactory/statusbarfactory.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/framework/source/uifactory/statusbarfactory.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
331
2015-01-06T11:40:55.000Z
2022-03-14T04:07:51.000Z
/************************************************************** * * 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. * *************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_framework.hxx" #include <uifactory/statusbarfactory.hxx> #include <uifactory/menubarfactory.hxx> //_________________________________________________________________________________________________________________ // my own includes //_________________________________________________________________________________________________________________ #include <uielement/statusbarwrapper.hxx> #include <threadhelp/resetableguard.hxx> //_________________________________________________________________________________________________________________ // interface includes //_________________________________________________________________________________________________________________ #include <com/sun/star/util/XURLTransformer.hpp> #include <com/sun/star/frame/XFrame.hpp> #include <com/sun/star/frame/XModel.hpp> #include <com/sun/star/lang/XInitialization.hpp> #include <com/sun/star/ui/XModuleUIConfigurationManagerSupplier.hpp> #ifndef _COM_SUN_STAR_UI_XUICONFIGURATIONMANAGERSUPLLIER_HPP_ #include <com/sun/star/ui/XUIConfigurationManagerSupplier.hpp> #endif //_________________________________________________________________________________________________________________ // includes of other projects //_________________________________________________________________________________________________________________ #include <vcl/svapp.hxx> #include <tools/urlobj.hxx> #include <rtl/ustrbuf.hxx> //_________________________________________________________________________________________________________________ // Defines //_________________________________________________________________________________________________________________ // using namespace com::sun::star::uno; using namespace com::sun::star::lang; using namespace com::sun::star::frame; using namespace com::sun::star::beans; using namespace com::sun::star::util; using namespace ::com::sun::star::ui; namespace framework { //***************************************************************************************************************** // XInterface, XTypeProvider, XServiceInfo //***************************************************************************************************************** DEFINE_XSERVICEINFO_ONEINSTANCESERVICE ( StatusBarFactory , ::cppu::OWeakObject , SERVICENAME_STATUSBARFACTORY , IMPLEMENTATIONNAME_STATUSBARFACTORY ) DEFINE_INIT_SERVICE ( StatusBarFactory, {} ) StatusBarFactory::StatusBarFactory( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceManager ) : MenuBarFactory( xServiceManager,true ) { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "framework", "Ocke.Janssen@sun.com", "StatusBarFactory::StatusBarFactory" ); } // XUIElementFactory Reference< XUIElement > SAL_CALL StatusBarFactory::createUIElement( const ::rtl::OUString& ResourceURL, const Sequence< PropertyValue >& Args ) throw ( ::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException ) { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "framework", "Ocke.Janssen@sun.com", "StatusBarFactory::createUIElement" ); // SAFE ResetableGuard aLock( m_aLock ); StatusBarWrapper* pWrapper = new StatusBarWrapper( m_xServiceManager ); Reference< ::com::sun::star::ui::XUIElement > xMenuBar( (OWeakObject *)pWrapper, UNO_QUERY ); Reference< ::com::sun::star::frame::XModuleManager > xModuleManager = m_xModuleManager; aLock.unlock(); MenuBarFactory::CreateUIElement(ResourceURL,Args,NULL,"private:resource/statusbar/",xMenuBar,xModuleManager,m_xServiceManager); return xMenuBar; } }
45.745283
152
0.718705
Grosskopf
5842b0de946b88bc341d1ff11a4285f995e5a432
2,860
cpp
C++
tests/TestProgress/TestProgress.cpp
deniskropp/llyx
33c7dd40921563d116363bd3e0b411aaa61ca29e
[ "MIT" ]
null
null
null
tests/TestProgress/TestProgress.cpp
deniskropp/llyx
33c7dd40921563d116363bd3e0b411aaa61ca29e
[ "MIT" ]
null
null
null
tests/TestProgress/TestProgress.cpp
deniskropp/llyx
33c7dd40921563d116363bd3e0b411aaa61ca29e
[ "MIT" ]
null
null
null
/* TestProgress - llyx test */ #include <SFML/Graphics.hpp> #include <llyx/BaseView.hpp> #include <llyx/ButtonView.hpp> #include <llyx/FPSView.hpp> #include <llyx/ProgressView.hpp> #include <llyx/RootView.hpp> #include <llyx/TextView.hpp> class TestView : public llyx::RootView { private: lli::Event<> timer; public: TestView(sf::RenderWindow& window) : RootView(window, llyx::RootStyle()) { llyx::TextStyle text1_style; text1_style.text_color = llyx::Color(0.0f, 0.66f, 0.79f); text1_style.text_height = 32; text1_style.text = "Progress Bar Test"; auto text1 = std::make_shared<llyx::TextView>(text1_style); text1->SetPosition(300, 70); AddSubView(text1); auto fps = std::make_shared<llyx::FPSView>(llyx::FPSStyle()); fps->SetPosition(900, 30); AddSubView(fps); llyx::TextButtonStyle tbs; tbs.border_width = 3; tbs.border_color = llyx::Color(0.7f, 0.9f, 0.9f); tbs.color = llyx::Color(0.1f, 0.5f, 0.5f); tbs.text = "Press me!"; auto button1 = std::make_shared<llyx::TextButtonView>(tbs); button1->SetPosition(400, 200); button1->ClickEvent.Attach([&window](int x, int y) { window.close(); }); AddSubView(button1); for (int i = 0; i < 4; i++) { llyx::ProgressStyle ps; ps.border = i+1; ps.border_color = llyx::Color(0.8f, 0.8f, 0.8f); ps.color = llyx::Color(0.0f, 0.0f, 0.8f); auto progress = std::make_shared<llyx::ProgressView>(ps); auto p = std::make_shared<float>(0.4f + i * 0.2f); progress->SetProgress(*p); progress->SetBounds(200, 400 + i * 80, 400, 30); AddSubView(progress); timer.Attach([progress,p,i]() { *p += (i + 1) * 0.01f; if (*p > 1.0f) *p = 0.0f; progress->SetProgress(*p); }); } // timer.Attach([this]() { timer.Dispatch(); }); timer.Dispatch(); } }; int main() { // parallel_f::system::instance().setDebugLevel("FrameQueue", 1); // parallel_f::system::instance().setAutoFlush(parallel_f::system::AutoFlush::EndOfLine); // lli::EventManager::Instance().Enable(); sf::RenderWindow window(sf::VideoMode(1200, 800), "TestSimple"); std::shared_ptr<TestView> testview = std::make_shared<TestView>(window); sf::Clock clock; while (window.isOpen()) { // lli::EventManager::Instance().Flush(); if (testview->NeedsRepaint() || clock.getElapsedTime().asSeconds() > 1.0f) { clock.restart(); window.clear(sf::Color::Green); window.draw(*testview); window.display(); } else sf::sleep(sf::milliseconds(20)); sf::Event event; while (window.pollEvent(event)) { switch (event.type) { case sf::Event::Closed: window.close(); break; default: testview->ProcessEvent(event); break; } } } return 0; }
19.861111
90
0.61014
deniskropp
5843f6db4edc12739e39e69d457870313b4b64f7
287
cpp
C++
homomorphic_evaluation/ntl-11.3.2/src/CheckBUILTIN_CLZL.cpp
dklee0501/PLDI_20_242_artifact_publication
f2b73df9165c76e8b521d8ebd639d68321e3862b
[ "MIT" ]
160
2016-05-11T09:45:56.000Z
2022-03-06T09:32:19.000Z
homomorphic_evaluation/ntl-11.3.2/src/CheckBUILTIN_CLZL.cpp
dklee0501/Lobster
f2b73df9165c76e8b521d8ebd639d68321e3862b
[ "MIT" ]
57
2016-12-26T07:02:12.000Z
2022-03-06T16:34:31.000Z
homomorphic_evaluation/ntl-11.3.2/src/CheckBUILTIN_CLZL.cpp
dklee0501/Lobster
f2b73df9165c76e8b521d8ebd639d68321e3862b
[ "MIT" ]
67
2016-10-10T17:56:22.000Z
2022-03-15T22:56:39.000Z
#include <NTL/mach_desc.h> #include <cstdlib> using namespace std; long CountLeadingZeros(unsigned long x) { return __builtin_clzl(x); } int main() { unsigned long x = atoi("3"); if (CountLeadingZeros(x) == NTL_BITS_PER_LONG-2) return 0; else return -1; }
12.478261
51
0.651568
dklee0501
58446d31191d8353710def53f5b5f6c48887e945
2,040
cpp
C++
SDL/Game13/Actor.cpp
blAs1N/C-programming
3ab83a00dab6e3d9cfe97c514115308ad2333387
[ "MIT" ]
4
2018-06-17T11:47:16.000Z
2018-10-01T14:01:55.000Z
SDL/Game13/Actor.cpp
blAs1N/TIL
3ab83a00dab6e3d9cfe97c514115308ad2333387
[ "MIT" ]
null
null
null
SDL/Game13/Actor.cpp
blAs1N/TIL
3ab83a00dab6e3d9cfe97c514115308ad2333387
[ "MIT" ]
null
null
null
#include "Actor.h" #include "Game.h" #include "Component.h" #include <algorithm> Actor::Actor(Game* inGame) : state(State::EActive), components(), game(inGame), position(Vector3::Zero), rotation(Quaternion::Identity), scale(1.0f), worldTransform(), recomputeWorldTransform(true) { game->AddActor(this); } Actor::~Actor() { game->RemoveActor(this); while (!components.empty()) delete components.back(); } void Actor::ProcessInput(const InputState& inputState) { if (state == State::EActive) { for (auto component : components) component->ProcessInput(inputState); ActorInput(inputState); } } void Actor::Update(const float deltaTime) { if (state == State::EActive) { ComputeWorldTransform(); for (auto component : components) component->Update(deltaTime); UpdateActor(deltaTime); ComputeWorldTransform(); } } void Actor::ComputeWorldTransform() { if (recomputeWorldTransform) { recomputeWorldTransform = false; worldTransform = Matrix4::CreateScale(scale); worldTransform *= Matrix4::CreateFromQuaternion(rotation); worldTransform *= Matrix4::CreateTranslation(position); for (auto comp : components) comp->OnUpdateWorldTransform(); } } void Actor::RotateToNewForward(const Vector3& forward) { const auto dot = Vector3::Dot(Vector3::UnitX, forward); if (dot > 0.9999f) SetRotation(Quaternion::Identity); else if (dot < -0.9999f) SetRotation(Quaternion{ Vector3::UnitZ, Math::Pi }); else { auto axis = Vector3::Cross(Vector3::UnitX, forward); axis.Normalized(); SetRotation(Quaternion{ axis, Math::Acos(dot) }); } } void Actor::AddComponent(Component* component) { int myOrder = component->GetUpdateOrder(); auto iter = components.begin(); for (; iter != components.end(); ++iter) if (myOrder < (*iter)->GetUpdateOrder()) break; components.insert(iter, component); } void Actor::RemoveComponent(Component* component) { auto iter = std::find(components.begin(), components.end(), component); if (iter != components.end()) components.erase(iter); }
23.181818
72
0.710294
blAs1N
5845aca70e3cad7e1fa7fd8904fdd9bf75e583b6
166
cpp
C++
2A. C++ Advanced (STL)/Attic/str-namespace.cpp
alemesa1991/School-Projects
ed9170fa4cadfe18c6d9850a17077686ca16d1a1
[ "MIT" ]
null
null
null
2A. C++ Advanced (STL)/Attic/str-namespace.cpp
alemesa1991/School-Projects
ed9170fa4cadfe18c6d9850a17077686ca16d1a1
[ "MIT" ]
null
null
null
2A. C++ Advanced (STL)/Attic/str-namespace.cpp
alemesa1991/School-Projects
ed9170fa4cadfe18c6d9850a17077686ca16d1a1
[ "MIT" ]
null
null
null
#include <iostream> #include <cstring> int main(int argc, char**argv) { const char *s = "asdfghjkl"; std::cout << s << " size is " << strlen(s) << "\n"; }
15.090909
55
0.554217
alemesa1991
5846d4044eaf5a2e4149ff144927bbf99a979009
15,060
hpp
C++
core123/include/core123/counter_based_engine.hpp
fennm/fs123
559b97659352620ce16030824f9acd26f590f4e1
[ "BSD-3-Clause" ]
22
2019-04-10T18:05:35.000Z
2021-12-30T12:26:39.000Z
core123/include/core123/counter_based_engine.hpp
fennm/fs123
559b97659352620ce16030824f9acd26f590f4e1
[ "BSD-3-Clause" ]
13
2019-04-09T00:19:29.000Z
2021-11-04T15:57:13.000Z
core123/include/core123/counter_based_engine.hpp
fennm/fs123
559b97659352620ce16030824f9acd26f590f4e1
[ "BSD-3-Clause" ]
4
2019-04-07T16:33:44.000Z
2020-07-02T02:58:51.000Z
// counter_based_engine: An adapter that turns a 'psuedo random // function' (e.g., core123::threefry or core123::philox) into a bona // fide standard C++ "Random Number Engine", satisfying the // requirements in [rand.req.eng] for a result_type, constructors, // seed methods, discard, equality and inequality operators, stream // insertion and extraction, etc., and also providing an "extended // API" that exposes desirable features of the counter-based paradigm. // // counter_based_engine<BITS>::operator()() can be called // 2^BITS*PRF::range_size times, after which it throws an out_of_range // exception. A large value of BITS (e.g., 64) allows for a generator // that is practically infinite. Smaller value of BITS are useful // when using the extended API. // // The 'extended API allows a counter_based_engine to be // constructed from a user-supplied pseudo-random function (prf) and // an initial value in the prf's domain. E.g., // // threefry<4, uint64_t> prf({... master seed...}); // // for(...){ // ... // counter_based_engine<threefry<4, uint64_t>, 8> eng(prf, {... per-obj-seed...}); // // or equivalently, with less typing: // auto eng = make_counter_based_engine<8>(prf, {... per-obj-seed ...}); // std::normal_distribution<float> nd; // gaussian = nd(eng) // ... // } // // When constructed this way, one can think of the the pseudo-random // function's 'key' as a 'master seed', and the counter_based_engine's // 'initial value', iv, as a separate 'per-object seed' that uniquely // specifies a finite uncorrelated sequence of result_types. The most // significant BITS bits of the iv.back() must be zero. (This is why // one might want BITS<64). In the example above, there are 2^256 // possible prfs, and 2^248 permissible values for the iv, each of // which defines a sequence of length 1024. // // IMPORTANT: If the pseudo-random function is "strong", then all // sequences generated by counter_based_engine, with differently // keyed prf's and/or different values of the iv are UNIFORMLY // DISTRIBUTED AND ARE STATISTICALLY INDEPENDENT FROM ONE ANOTHER. // This is true EVEN IF ONLY BIT IS DIFFERENT IN THE PRF's KEYS OR THE // INITIAL VALUES. For strong pseudo-random functions, THERE IS NO // NEED TO "RANDOMIZE" THE KEYS OR THE IVS. IT IS SUFFICIENT FOR THEM // TO BE UNIQUE. The pseudo-random functions in core123 (threefry, // philox and chacha) are all strong in this sense. // // Extended API: // Informational member functions // // unsigned long long sequence_length() - returns // 2^BITS*PRF::range_size if it is representable as an unsigned // long long, and returns the maximum unsigned long long otherwise. // It is an error (reported by throwing out_of_range) to request // more than the maximum number of random values (either by // operator() or by discard()). // // unsigned long long navail() - returns (at least) the number of // values that are still available to be generated. If the number // exceeds the maximum value representable by unsigned long long, // then the maximum unsigned long long value is returned. // // Accessor member functions: // // prf() - returns a copy of the pseudo-random function // currently in use by the engine. // iv()- returns the initial value that began the sequence // currently being generated. // // Seeding and reinitialization: // // seed(const PRF& prf, const PRF::domain_type& iv) - resets the // generator to one equivalent to counter_based_engine(prf(), iv()). // // reinit(const PRF::domain_type& iv) - resets the generator // to one equivalent to counter_based_engine(prf(), iv). I.e., // it leaves the prf in place, but resets the initial value to iv. // // counter_based_engines that have been constructed or seeded using // the conventional API (via the default constructor, the result_type // constructor, the "seed sequence" constructor, or the analogous // seed() members) will have a "randomly" keyed PRF and a "random" iv. // The "random" key and iv will be constructed deterministically by // calling the generate member of a "seed sequence" (either one that // was provided, or std::seed_seq). #include "strutils.hpp" #include "detail/prf_common.hpp" #include <random> #include <limits> #include <stdexcept> #include <array> #include <iostream> #include <type_traits> namespace core123{ namespace detail{ template <typename SeedSeq, typename EngType, typename ResultType> using enable_if_seed_seq = typename std::enable_if<!std::is_convertible<SeedSeq, ResultType>::value && !std::is_same<std::remove_reference_t<std::remove_cv_t<SeedSeq>>, EngType>::value >::type; } // Details (these could have been done differently, but they all // have to be consistent): // - The constructor does *not* call the prf. // - The prf is called to 'refill' the array of randoms (r) when // the generator (operator()()) is called the first time, and // then again on the Ndomain'th time, the 2*Ndomain'th time, etc. // - In between calls to 'refill', values are returned from the // randoms (r) array. The index of the next value to return // is stored in r[0] (saving one word of memory). // - The first time the prf is called, the high BITS of the counter // are zero. // - The counter is incremented immediately after // the prf is called. Thus, the 'r' member is *not* the prf // of the 'c' member. // - The sequence is exhausted when we try to 'refill' the 2^BIT'th // time, at which point, the high bits of the counter have wrapped // around to zero. We distinguish this from the very first // invocation of refill by initializing the structure with an // otherwise impossible value of r[0]. This adds some special-case // logic to operator>>, discard, navail, etc., but the constructor // and operator() are reasonably clean. // - sequence_length() and navail() are tricky because the "correct" // answer may not fit in an unsigned long long. template <typename PRF, unsigned BITS> struct counter_based_engine{ private: using domain_type = typename PRF::domain_type; using range_type = typename PRF::range_type; using dv_type = typename domain_type::value_type; using rv_type = typename range_type::value_type; static constexpr int W = std::numeric_limits<dv_type>::digits; static_assert(BITS <= W, "BITS must be less than or equal to the PRF's domain value_type"); static constexpr auto Ndomain = PRF::domain_size; static constexpr auto Nrange = PRF::range_size; // Shift operators are very weird in two ways: // 1 - they're undefined when the shift amount is equal // to the width of the operand // 2 - they never return anything narrower than unsigned int. // There are several places in the code below where we'd naturally // write n << (W-BITS) or n >> (W-BITS). But with BITS==0, those // expressions would be undefined. A ternary conditional avoids // the undefined behavior. Wrapping it in a function coerces the // returned value back to dv_type and also *seems* to silence // bogus (because the dodgy code is unreachable) // -Wshift-count-overflow warnings. static constexpr dv_type LeftWB(dv_type d){ return BITS ? d<<(W-BITS) : 0; } static constexpr dv_type RightWB(dv_type d){ return BITS ? d>>(W-BITS) : 0; } static constexpr dv_type ctr_mask = LeftWB(~dv_type(0)); static constexpr dv_type incr = LeftWB(dv_type(1)); PRF f; domain_type c; range_type r; rv_type refill(){ if((c.back() & ctr_mask) == 0 && (r[0] != Nrange+2)){ r[0] = Nrange; // reset to throw if called again throw std::out_of_range("counter_based_engine::refill: out of counters"); } r = f(c); c.back() += incr; auto ret = r[0]; r[0] = 1; return ret; } static bool hibitsdirty(dv_type v){ return v & ctr_mask; } static constexpr unsigned long long ullmax = std::numeric_limits<unsigned long long>::max(); public: using result_type = rv_type; counter_based_engine(const PRF& prf_, const typename PRF::domain_type& iv) { seed(prf_, iv); } // The seed-oriented constructors all call seed. template <class SeedSeq, typename = detail::enable_if_seed_seq<SeedSeq, counter_based_engine, result_type>> explicit counter_based_engine(SeedSeq &q) { seed(q); } explicit counter_based_engine(result_type s) { seed(s); } counter_based_engine() { seed(); } // The seed() members all forward to seed(SeedSeq), which // initializes both the PRF and the IV from a call to // q.generate(). void seed(result_type s){ static constexpr unsigned N32 = (sizeof(result_type)-1) / sizeof(uint32_t) + 1; std::array<uint32_t, N32> a; for(unsigned i=0; i<N32; ++i){ a[i] = s&0xffffffff; s >>= 32; } std::seed_seq q(a.begin(), a.end()); seed(q); } void seed(){ // The seed_seq is initialized with little-endian("core123::default") // (which should be different from anything initialized with either // a 32-bit or 64-bit result-type). Hopefully this won't "collide" // with any seed that can be manufactured by the other seed methods. std::seed_seq q({0x65726f63, 0x3a333231, 0x6665643a, 0x746c756}); seed(q); } template <class SeedSeq, typename = detail::enable_if_seed_seq<SeedSeq, counter_based_engine, result_type>> void seed(SeedSeq &q){ static const size_t Nk32 = detail::u32_for<typename PRF::key_type>(); static const size_t Nd32 = detail::u32_for<typename PRF::domain_type>(); std::array<uint32_t, Nk32+Nd32> a; // Call q.generate. N.B. the 'seedseq' serves very little // purpose here. As long as we avoid *identical* keys and // initial values, counter-based prngs produce independent and // uncorrelated sequences. The SeedSeq' can't help. It can // only hurt (by producing the same key from two different // initializations). Nevertheless, it's required by the standard... q.generate(a.begin(), a.end()); typename PRF::key_type kk; typename PRF::domain_type cc; auto b = std::begin(a); auto e = std::end(a); b = detail::stdarray_from_u32(kk, b, e); f = PRF{kk}; detail::stdarray_from_u32(cc, b, e); cc.back() &= ~ctr_mask; reinit(cc); } // A non-required seed function corresponding to our non-required constructor: void seed(const PRF& prf_, const typename PRF::domain_type& iv){ f = prf_; reinit(iv); } result_type operator()(){ auto idx = r[0]++; if(idx >= Nrange) return refill(); return r[idx]; } static constexpr result_type min() { return 0; } static constexpr result_type max() { return std::numeric_limits<result_type>::max(); } // accessors for the prf and the iv. PRF prf() const{ return f; } typename PRF::domain_type iv() const { auto ret = c; ret.back() &= ~ctr_mask; return ret; } // reinit is a mutator that changes the iv but leaves the prf // alone. There's a seed() member that changes both. There is no // mutator that changes the key and leaves the iv alone. Should // reinit be called seed()? If so, we need some extra enable_if // logic to avoid ambiguity with seed(SeedSeq). void reinit(const typename PRF::domain_type& iv_){ if( hibitsdirty(iv_.back()) ) throw std::invalid_argument("cbgenerator<BITS>::reset: high BITS of counter not zero"); c = iv_; r[0] = Nrange+1; } void discard(unsigned long long n){ if(n==0) return; auto nfill = n/Nrange; auto nextra = n%Nrange; auto r0 = (r[0]==Nrange+1) ? Nrange : r[0]; // unwind the tricky first-time special case r0 += nextra; if(r0 > Nrange){ nfill++; r0 -= Nrange; } // Check for overflow. Is nfill too big? if(nfill){ dv_type dv_nfillm1 = nfill-1; if( RightWB(LeftWB(dv_nfillm1)) != nfill-1 ){ // queue up an overflow if operator() is called again c.back() &= ~ctr_mask; r[0] = Nrange; throw std::out_of_range("discard too large"); } c.back() += dv_nfillm1*incr; r[0]++; // more wacky first-time stuff. refill(); // if this throws, do we } r[0] = r0; } unsigned long long navail() const { using ull = unsigned long long; if(r[0] == Nrange+1) return sequence_length(); ull ctr = RightWB(c.back()); if(ctr == 0) // we've wrapped. What's in r[] is all that's left. return Nrange - r[0]; ull cmaxm1 = RightWB(ctr_mask); ull cleft = cmaxm1 - ctr + 1; if( cleft > ullmax/Nrange ) return ullmax; else return Nrange * cleft + (Nrange-r[0]); } static constexpr unsigned long long sequence_length(){ unsigned long long cmax = RightWB(ctr_mask); if( cmax >= ullmax/Nrange ) return ullmax; else return Nrange * (cmax+1); } friend bool operator==(const counter_based_engine& lhs, const counter_based_engine& rhs) { return lhs.c == rhs.c && lhs.r[0] == rhs.r[0] && lhs.f == rhs.f; } friend bool operator!=(const counter_based_engine& lhs, const counter_based_engine& rhs) { return !(lhs==rhs); } CORE123_DETAIL_OSTREAM_OPERATOR(os, counter_based_engine, g){ os << g.f; for(const auto e : g.c) os << " " << e; return os << " " << g.r[0]; } CORE123_DETAIL_ISTREAM_OPERATOR(is, counter_based_engine, g){ PRF inprf; range_type inc; result_type inr0; is >> inprf; for(auto& cv : inc) is >> cv; is >> inr0; if(is){ if(inr0 > Nrange+1 || (inr0 == Nrange+1 && hibitsdirty(inc.back()))){ is.setstate(std::ios::failbit); return is; } g.c = inc; g.f = std::move(inprf); inc.back() -= incr; // backwards! g.r = g.f(inc); g.r[0] = inr0; } return is; } }; template <unsigned BITS, typename PRF> auto make_counter_based_engine(const PRF& prf, const typename PRF::domain_type& c0){ return counter_based_engine<PRF, BITS>(prf, c0); } } // namespace core123
39.015544
132
0.626494
fennm
584701c929bbebf857c2bae811ac9e158ae665d2
8,120
cpp
C++
src/engine/kyotocabinet_engine.cpp
direktspeed/ardb
78e9480f6b385ff6b63f5c9c568a5716bc13386d
[ "BSD-3-Clause" ]
1
2019-08-04T02:39:56.000Z
2019-08-04T02:39:56.000Z
src/engine/kyotocabinet_engine.cpp
direktspeed/ardb
78e9480f6b385ff6b63f5c9c568a5716bc13386d
[ "BSD-3-Clause" ]
null
null
null
src/engine/kyotocabinet_engine.cpp
direktspeed/ardb
78e9480f6b385ff6b63f5c9c568a5716bc13386d
[ "BSD-3-Clause" ]
null
null
null
/* *Copyright (c) 2013-2013, yinqiwen <yinqiwen@gmail.com> *All rights reserved. * *Redistribution and use in source and binary forms, with or without *modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Redis nor the names of its contributors may be used * to endorse or promote products derived from this software without * specific prior written permission. * *THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" *AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE *IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE *ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS *BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR *CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF *SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS *INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN *CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) *ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF *THE POSSIBILITY OF SUCH DAMAGE. */ #include "kyotocabinet_engine.hpp" #include "ardb.hpp" #include "data_format.hpp" #include "util/helpers.hpp" #include <string.h> namespace ardb { int32_t KCDBComparator::compare(const char* akbuf, size_t aksiz, const char* bkbuf, size_t bksiz) { return ardb_compare_keys(akbuf, aksiz, bkbuf, bksiz); } KCDBEngineFactory::KCDBEngineFactory(const Properties& props) { ParseConfig(props, m_cfg); } void KCDBEngineFactory::ParseConfig(const Properties& props, KCDBConfig& cfg) { cfg.path = "."; conf_get_string(props, "data-dir", cfg.path); } KeyValueEngine* KCDBEngineFactory::CreateDB(const std::string& db) { KCDBEngine* engine = new KCDBEngine(); char tmp[m_cfg.path.size() + db.size() + 10]; sprintf(tmp, "%s/%s", m_cfg.path.c_str(), db.c_str()); KCDBConfig cfg = m_cfg; cfg.path = tmp; if (engine->Init(cfg) != 0) { DELETE(engine); return NULL; } DEBUG_LOG("Create DB:%s at path:%s success", db.c_str(), tmp); return engine; } void KCDBEngineFactory::CloseDB(KeyValueEngine* engine) { DELETE(engine); } void KCDBEngineFactory::DestroyDB(KeyValueEngine* engine) { KCDBEngine* kcdb = (KCDBEngine*) engine; if (NULL != kcdb) { kcdb->Clear(); } DELETE(engine); } KCDBEngine::KCDBEngine() : m_db(NULL) { } KCDBEngine::~KCDBEngine() { Close(); DELETE(m_db); } void KCDBEngine::Clear() { if (NULL != m_db) { m_db->clear(); } } void KCDBEngine::Close() { if (NULL != m_db) { m_db->close(); } } int KCDBEngine::Init(const KCDBConfig& cfg) { make_file(cfg.path); m_db = new kyotocabinet::TreeDB; int tune_options = kyotocabinet::TreeDB::TSMALL | kyotocabinet::TreeDB::TLINEAR; //tune_options |= kyotocabinet::TreeDB::TCOMPRESS; m_db->tune_options(tune_options); m_db->tune_page_cache(4194304); m_db->tune_page(1024); m_db->tune_map(256LL << 20); m_db->tune_comparator(&m_comparator); if (!m_db->open(cfg.path.c_str(), kyotocabinet::TreeDB::OWRITER | kyotocabinet::TreeDB::OCREATE)) { ERROR_LOG("Unable to open DB:%s", cfg.path.c_str()); DELETE(m_db); return -1; } return 0; } int KCDBEngine::BeginBatchWrite() { m_batch_local.GetValue().AddRef(); return 0; } int KCDBEngine::CommitBatchWrite() { BatchHolder& holder = m_batch_local.GetValue(); holder.ReleaseRef(); if (holder.EmptyRef()) { return FlushWriteBatch(holder); } return 0; } int KCDBEngine::DiscardBatchWrite() { BatchHolder& holder = m_batch_local.GetValue(); holder.ReleaseRef(); holder.Clear(); return 0; } int KCDBEngine::FlushWriteBatch(BatchHolder& holder) { StringSet::iterator it = holder.batch_del.begin(); while (it != holder.batch_del.end()) { m_db->remove(*it); it++; } StringStringMap::iterator sit = holder.batch_put.begin(); while (sit != holder.batch_put.end()) { m_db->set(sit->first, sit->second); sit++; } holder.Clear(); return 0; } int KCDBEngine::Put(const Slice& key, const Slice& value) { bool success = true; BatchHolder& holder = m_batch_local.GetValue(); if (!holder.EmptyRef()) { holder.Put(key, value); } else { success = m_db->set(key.data(), key.size(), value.data(), value.size()); } return success ? 0 : -1; } int KCDBEngine::Get(const Slice& key, std::string* value, bool fill_cache) { size_t len; bool success = false; char* data = m_db->get(key.data(), key.size(), &len); success = data != NULL; if (success && NULL != value) { value->assign(data, len); } DELETE_A(data); return success ? 0 : -1; } int KCDBEngine::Del(const Slice& key) { BatchHolder& holder = m_batch_local.GetValue(); if (!holder.EmptyRef()) { holder.Del(key); return 0; } else { return m_db->remove(key.data(), key.size()) ? 0 : -1; } } Iterator* KCDBEngine::Find(const Slice& findkey, bool cache) { kyotocabinet::DB::Cursor* cursor = m_db->cursor(); bool ret = cursor->jump(findkey.data(), findkey.size()); if (!ret) { ret = cursor->jump_back(); } return new KCDBIterator(cursor, ret); } void KCDBIterator::SeekToFirst() { m_valid = m_cursor->jump(); } void KCDBIterator::SeekToLast() { m_valid = m_cursor->jump_back(); } void KCDBIterator::Seek(const Slice& target) { /* * not implemented */ abort(); } void KCDBIterator::Next() { m_valid = m_cursor->step(); } void KCDBIterator::Prev() { m_valid = m_cursor->step_back(); } Slice KCDBIterator::Key() const { Buffer& tmp = const_cast<Buffer&>(m_key_buffer); tmp.Clear(); size_t len; char* key = m_cursor->get_key(&len, false); if (NULL != key) { tmp.Write(key, len); } DELETE_A(key); return Slice(m_key_buffer.GetRawReadBuffer(), len); } Slice KCDBIterator::Value() const { Buffer& tmp = const_cast<Buffer&>(m_value_buffer); tmp.Clear(); size_t len; char* value = m_cursor->get_value(&len, false); if (NULL != value) { tmp.Write(value, len); } DELETE_A(value); return Slice(m_value_buffer.GetRawReadBuffer(), len); } bool KCDBIterator::Valid() { return m_valid; } }
28.896797
106
0.557266
direktspeed
58482df3ccc4569c7e1e37a2ca2d070e0aec3f9c
237
cpp
C++
src/eepp/window/cclipboard.cpp
dogtwelve/eepp
dd672ff0e108ae1e08449ca918dc144018fb4ba4
[ "MIT" ]
null
null
null
src/eepp/window/cclipboard.cpp
dogtwelve/eepp
dd672ff0e108ae1e08449ca918dc144018fb4ba4
[ "MIT" ]
null
null
null
src/eepp/window/cclipboard.cpp
dogtwelve/eepp
dd672ff0e108ae1e08449ca918dc144018fb4ba4
[ "MIT" ]
null
null
null
#include <eepp/window/cclipboard.hpp> namespace EE { namespace Window { cClipboard::cClipboard( cWindow * window ) : mWindow( window ) {} cClipboard::~cClipboard() {} cWindow * cClipboard::GetWindow() const { return mWindow; } }}
14.8125
44
0.700422
dogtwelve
584d8245c86266445eb507f78bf1b2a3379d40e9
215
cpp
C++
2/sum_array.cpp
cwaffles/CMPT225Labs
c4c6c2ff90e99ec3a5938a63f48c41dab4a8190b
[ "MIT" ]
1
2016-06-04T07:39:21.000Z
2016-06-04T07:39:21.000Z
2/sum_array.cpp
cwaffles/CMPT225Labs
c4c6c2ff90e99ec3a5938a63f48c41dab4a8190b
[ "MIT" ]
null
null
null
2/sum_array.cpp
cwaffles/CMPT225Labs
c4c6c2ff90e99ec3a5938a63f48c41dab4a8190b
[ "MIT" ]
null
null
null
// // Created by eric on 24/05/16. // #include "sum_array.h" int sumArray(int arr[], int arrSize) { int runningTotal = 0; for(int i = 0; i < arrSize; i++) { runningTotal += arr[i]; } return runningTotal; }
13.4375
36
0.613953
cwaffles
584dd318e960a40948b1b69fde2d4208ae1cb8e9
278
cpp
C++
Pacman_ASCII/src/Pacman.cpp
SebGrenier/Pacman_ASCII
6eb6fea809d1bd97d41dee973149b8656fc01846
[ "MIT" ]
null
null
null
Pacman_ASCII/src/Pacman.cpp
SebGrenier/Pacman_ASCII
6eb6fea809d1bd97d41dee973149b8656fc01846
[ "MIT" ]
null
null
null
Pacman_ASCII/src/Pacman.cpp
SebGrenier/Pacman_ASCII
6eb6fea809d1bd97d41dee973149b8656fc01846
[ "MIT" ]
null
null
null
#include "Pacman.h" #include "ConsoleUtils.h" #include <iostream> using namespace std; Pacman::Pacman(char chr) : _character(chr) { } Pacman::~Pacman(void) {} void Pacman::Draw(void) const { ConsoleUtils::SetCursorPosition(_position.x, _position.y); cout << _character; }
15.444444
59
0.719424
SebGrenier
584fc3905dd2668afa845d2413808a746a79175f
1,183
cpp
C++
Framework/Sources/o2/Utils/Editor/EditorScope.cpp
zenkovich/o2
cdbf10271f1bf0f3198c8005b13b66e6ca13a9db
[ "MIT" ]
181
2015-12-09T08:53:36.000Z
2022-03-26T20:48:39.000Z
Framework/Sources/o2/Utils/Editor/EditorScope.cpp
zenkovich/o2
cdbf10271f1bf0f3198c8005b13b66e6ca13a9db
[ "MIT" ]
29
2016-04-22T08:24:04.000Z
2022-03-06T07:06:28.000Z
Framework/Sources/o2/Utils/Editor/EditorScope.cpp
zenkovich/o2
cdbf10271f1bf0f3198c8005b13b66e6ca13a9db
[ "MIT" ]
13
2018-04-24T17:12:04.000Z
2021-11-12T23:49:53.000Z
#include "o2/stdafx.h" #include "EditorScope.h" #include "o2/Events/EventSystem.h" #include "o2/Utils/Debug/Assert.h" namespace o2 { void EditorScope::Enter(int count /*= 1*/) { if (count > 0) { Actor::SetDefaultCreationMode(ActorCreateMode::NotInScene); mDepth += count; } } void EditorScope::Exit(int count /*= 1*/) { if (count > 0) { mDepth -= count; if (mDepth == 0) Actor::SetDefaultCreationMode(ActorCreateMode::InScene); else Actor::SetDefaultCreationMode(ActorCreateMode::NotInScene); Assert(mDepth >= 0, "Editor scope Enter/Exit mismatch"); } } int EditorScope::GetDepth() { return mDepth; } bool EditorScope::IsInScope() { return mDepth > 0; } int EditorScope::mDepth = 0; PushEditorScopeOnStack::PushEditorScopeOnStack(int count /*= 1*/): mDepth(count) { EditorScope::Enter(count); } PushEditorScopeOnStack::~PushEditorScopeOnStack() { EditorScope::Exit(mDepth); } ForcePopEditorScopeOnStack::ForcePopEditorScopeOnStack() { mDepth = EditorScope::GetDepth(); EditorScope::Exit(mDepth); } ForcePopEditorScopeOnStack::~ForcePopEditorScopeOnStack() { EditorScope::Enter(mDepth); } }
17.144928
67
0.688926
zenkovich
58574d6340b50c1ba19eb70b6efdb91541ddc805
11,669
cpp
C++
tests/cuda4.1sdk/tests/simpleTexture3D/simpleTexture3D.cpp
florianjacob/gpuocelot
fa63920ee7c5f9a86e264cd8acd4264657cbd190
[ "BSD-3-Clause" ]
221
2015-03-29T02:05:49.000Z
2022-03-25T01:45:36.000Z
tests/cuda4.1sdk/tests/simpleTexture3D/simpleTexture3D.cpp
mprevot/gpuocelot
d9277ef05a110e941aef77031382d0260ff115ef
[ "BSD-3-Clause" ]
106
2015-03-29T01:28:42.000Z
2022-02-15T19:38:23.000Z
tests/cuda4.1sdk/tests/simpleTexture3D/simpleTexture3D.cpp
mprevot/gpuocelot
d9277ef05a110e941aef77031382d0260ff115ef
[ "BSD-3-Clause" ]
83
2015-07-10T23:09:57.000Z
2022-03-25T03:01:00.000Z
/* * Copyright 1993-2010 NVIDIA Corporation. All rights reserved. * * Please refer to the NVIDIA end user license agreement (EULA) associated * with this source code for terms and conditions that govern your use of * this software. Any use, reproduction, disclosure, or distribution of * this software and related documentation outside the terms of the EULA * is strictly prohibited. * */ /* 3D texture sample This sample loads a 3D volume from disk and displays slices through it using 3D texture lookups. */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> #include <GL/glew.h> #if defined (__APPLE__) || defined(MACOSX) #include <GLUT/glut.h> #else #include <GL/freeglut.h> #endif #include <vector_types.h> #include <driver_functions.h> #include <cutil_inline.h> // includes cuda.h and cuda_runtime_api.h #include <cutil_gl_inline.h> #include <shrQATest.h> #include <cuda_gl_interop.h> #include <rendercheck_gl.h> typedef unsigned int uint; typedef unsigned char uchar; #define MAX_EPSILON_ERROR 5.0f #define THRESHOLD 0.15f const char *sSDKsample = "simpleTexture3D"; // Define the files that are to be save and the reference images for validation const char *sOriginal[] = { "simpleTex3D.ppm", NULL }; const char *sReference[] = { "ref_simpleTex3D.ppm", NULL }; const char *volumeFilename = "Bucky.raw"; const cudaExtent volumeSize = make_cudaExtent(32, 32, 32); const uint width = 512, height = 512; const dim3 blockSize(16, 16, 1); const dim3 gridSize(width / blockSize.x, height / blockSize.y); float w = 0.5; // texture coordinate in z GLuint pbo; // OpenGL pixel buffer object struct cudaGraphicsResource *cuda_pbo_resource; // CUDA Graphics Resource (to transfer PBO) bool linearFiltering = true; bool animate = true; unsigned int timer = 0; uint *d_output = NULL; // Auto-Verification Code const int frameCheckNumber = 4; int fpsCount = 0; // FPS count for averaging int fpsLimit = 1; // FPS limit for sampling int g_Index = 0; unsigned int frameCount = 0; unsigned int g_TotalErrors = 0; bool g_Verify = false; bool g_bQAReadback = false; bool g_bOpenGLQA = false; // CheckFBO/BackBuffer class objects CheckRender *g_CheckRender = NULL; int *pArgc = NULL; char **pArgv = NULL; #define MAX(a,b) ((a > b) ? a : b) extern "C" void setTextureFilterMode(bool bLinearFilter); extern "C" void initCuda(const uchar *h_volume, cudaExtent volumeSize); extern "C" void render_kernel(dim3 gridSize, dim3 blockSize, uint *d_output, uint imageW, uint imageH, float w); void loadVolumeData(char *exec_path); void AutoQATest() { if (g_CheckRender && g_CheckRender->IsQAReadback()) { char temp[256]; sprintf(temp, "AutoTest: %s", sSDKsample); glutSetWindowTitle(temp); shrQAFinishExit2(true, *pArgc, (const char **)pArgv, QA_PASSED); } } void computeFPS() { frameCount++; fpsCount++; if (fpsCount == fpsLimit-1) { g_Verify = true; } if (fpsCount == fpsLimit) { char fps[256]; float ifps = 1.f / (cutGetAverageTimerValue(timer) / 1000.f); sprintf(fps, "%s %s: %3.1f fps", sSDKsample, ((g_CheckRender && g_CheckRender->IsQAReadback()) ? "AutoTest: " : ""), ifps); glutSetWindowTitle(fps); fpsCount = 0; if (g_CheckRender && !g_CheckRender->IsQAReadback()) fpsLimit = (int)MAX(ifps, 1.f); cutilCheckError(cutResetTimer(timer)); AutoQATest(); } } // render image using CUDA void render() { // map PBO to get CUDA device pointer cutilSafeCall(cudaGraphicsMapResources(1, &cuda_pbo_resource, 0)); size_t num_bytes; cutilSafeCall(cudaGraphicsResourceGetMappedPointer((void **)&d_output, &num_bytes, cuda_pbo_resource)); //printf("CUDA mapped PBO: May access %ld bytes\n", num_bytes); // call CUDA kernel, writing results to PBO render_kernel(gridSize, blockSize, d_output, width, height, w); cutilCheckMsg("kernel failed"); cutilSafeCall(cudaGraphicsUnmapResources(1, &cuda_pbo_resource, 0)); } // display results using OpenGL (called by GLUT) void display() { cutilCheckError(cutStartTimer(timer)); render(); // display results glClear(GL_COLOR_BUFFER_BIT); // draw image from PBO glDisable(GL_DEPTH_TEST); glRasterPos2i(0, 0); glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, pbo); glDrawPixels(width, height, GL_RGBA, GL_UNSIGNED_BYTE, 0); glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0); if (g_CheckRender && g_CheckRender->IsQAReadback() && g_Verify) { // readback for QA testing printf("> (Frame %d) Readback BackBuffer\n", frameCount); g_CheckRender->readback( width, height ); g_CheckRender->savePPM(sOriginal[g_Index], true, NULL); if (!g_CheckRender->PPMvsPPM(sOriginal[g_Index], sReference[g_Index], MAX_EPSILON_ERROR, THRESHOLD)) { g_TotalErrors++; } g_Verify = false; } glutSwapBuffers(); glutReportErrors(); cutilCheckError(cutStopTimer(timer)); computeFPS(); } void idle() { if (animate) { w += 0.01f; glutPostRedisplay(); } } void keyboard(unsigned char key, int x, int y) { switch(key) { case 27: exit(0); break; case '=': case '+': w += 0.01f; break; case '-': w -= 0.01f; break; case 'f': linearFiltering = !linearFiltering; setTextureFilterMode(linearFiltering); break; case ' ': animate = !animate; break; default: break; } glutPostRedisplay(); } void reshape(int x, int y) { glViewport(0, 0, x, y); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0.0, 1.0, 0.0, 1.0, 0.0, 1.0); } void cleanup() { cutilCheckError( cutDeleteTimer( timer)); if (!g_bQAReadback) { // unregister this buffer object from CUDA C cudaGraphicsUnregisterResource(cuda_pbo_resource); glDeleteBuffersARB(1, &pbo); } if (g_CheckRender) { delete g_CheckRender; g_CheckRender = NULL; } } void initGLBuffers() { // create pixel buffer object glGenBuffersARB(1, &pbo); glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, pbo); glBufferDataARB(GL_PIXEL_UNPACK_BUFFER_ARB, width*height*sizeof(GLubyte)*4, 0, GL_STREAM_DRAW_ARB); glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0); // register this buffer object with CUDA cutilSafeCall(cudaGraphicsGLRegisterBuffer(&cuda_pbo_resource, pbo, cudaGraphicsMapFlagsWriteDiscard)); } // Load raw data from disk uchar *loadRawFile(const char *filename, size_t size) { FILE *fp = fopen(filename, "rb"); if (!fp) { fprintf(stderr, "Error opening file '%s'\n", filename); return 0; } uchar *data = (uchar *) malloc(size); size_t read = fread(data, 1, size, fp); fclose(fp); printf("Read '%s', %lu bytes\n", filename, read); return data; } void initGL( int *argc, char **argv ) { // initialize GLUT callback functions glutInit(argc, argv); glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE); glutInitWindowSize(width, height); glutCreateWindow("CUDA 3D texture"); glutDisplayFunc(display); glutKeyboardFunc(keyboard); glutReshapeFunc(reshape); glutIdleFunc(idle); glewInit(); if (!glewIsSupported("GL_VERSION_2_0 GL_ARB_pixel_buffer_object")) { fprintf(stderr, "Required OpenGL extensions missing."); exit(-1); } } // General initialization call for CUDA Device int chooseCudaDevice(int argc, char **argv, bool bUseOpenGL) { int result = 0; if (bUseOpenGL) { result = cutilChooseCudaGLDevice(argc, argv); } else { result = cutilChooseCudaDevice(argc, argv); } return result; } void runAutoTest( int argc, char **argv ) { g_CheckRender = new CheckBackBuffer(width, height, 4, false); g_CheckRender->setPixelFormat(GL_RGBA); g_CheckRender->setExecPath(argv[0]); g_CheckRender->EnableQAReadback(true); // use command-line specified CUDA device, otherwise use device with highest Gflops/s chooseCudaDevice(argc, argv, false); loadVolumeData(argv[0]); cutilSafeCall( cudaMalloc((void **)&d_output, width*height*sizeof(GLubyte)*4) ); // render the volumeData render_kernel(gridSize, blockSize, d_output, width, height, w); cutilSafeCall( cutilDeviceSynchronize() ); cutilCheckMsg("render_kernel failed"); cutilSafeCall( cudaMemcpy( g_CheckRender->imageData(), d_output, width*height*sizeof(GLubyte)*4, cudaMemcpyDeviceToHost) ); g_CheckRender->dumpBin((void *)g_CheckRender->imageData(), width*height*sizeof(GLubyte)*4, "simpleTexture3D.bin"); if (!g_CheckRender->compareBin2BinFloat("simpleTexture3D.bin", "ref_texture3D.bin", width*height*sizeof(GLubyte)*4, MAX_EPSILON_ERROR, THRESHOLD)) g_TotalErrors++; cutilSafeCall( cudaFree(d_output) ); } void loadVolumeData(char *exec_path) { // load volume data const char* path = cutFindFilePath(volumeFilename, exec_path); if (path == NULL) { fprintf(stderr, "Error unable to find 3D Volume file: '%s'\n", volumeFilename); shrQAFinishExit2(false, *pArgc, (const char **)pArgv, QA_FAILED); } size_t size = volumeSize.width*volumeSize.height*volumeSize.depth; uchar *h_volume = loadRawFile(path, size); initCuda(h_volume, volumeSize); cutilCheckError( cutCreateTimer( &timer)); free(h_volume); } //////////////////////////////////////////////////////////////////////////////// // Program main //////////////////////////////////////////////////////////////////////////////// int main( int argc, char** argv) { pArgc = &argc; pArgv = argv; shrQAStart(argc, argv); printf("[%s] ", sSDKsample); if (argc > 1) { if (cutCheckCmdLineFlag(argc, (const char **)argv, "qatest") || cutCheckCmdLineFlag(argc, (const char **)argv, "noprompt")) { g_bQAReadback = true; fpsLimit = frameCheckNumber; } if (cutCheckCmdLineFlag(argc, (const char **)argv, "glverify")) { g_bOpenGLQA = true; fpsLimit = frameCheckNumber; } } if (g_bQAReadback) printf("(Automated Testing)\n"); if (g_bOpenGLQA) printf("(OpenGL Readback)\n"); if (g_bQAReadback) { runAutoTest(argc, argv); cleanup(); cutilDeviceReset(); shrQAFinishExit(argc, (const char **)argv, (g_TotalErrors > 0) ? QA_FAILED : QA_PASSED); } else { if (g_bOpenGLQA) { g_CheckRender = new CheckBackBuffer(width, height, 4); g_CheckRender->setPixelFormat(GL_RGBA); g_CheckRender->setExecPath(argv[0]); g_CheckRender->EnableQAReadback(true); } // First initialize OpenGL context, so we can properly set the GL for CUDA. // This is necessary in order to achieve optimal performance with OpenGL/CUDA interop. initGL(&argc, argv); // use command-line specified CUDA device, otherwise use device with highest Gflops/s chooseCudaDevice(argc, argv, true); // OpenGL buffers initGLBuffers(); loadVolumeData(argv[0]); } printf("Press space to toggle animation\n" "Press '+' and '-' to change displayed slice\n"); atexit(cleanup); glutMainLoop(); cutilDeviceReset(); shrQAFinishExit(argc, (const char **)argv, QA_PASSED); }
27.200466
150
0.649327
florianjacob
5858ba9538f6b2012a8c637ee0f63e3f56f64114
15,197
cpp
C++
Proj_Android/app/src/main/cpp/FPolyPath.cpp
nraptis/Metal_OpenGL_MobileGameEngine
cc36682676a9797df8b3a7ee235b99be3ae2f666
[ "MIT" ]
3
2019-10-10T19:25:42.000Z
2019-12-17T10:51:23.000Z
Framework/[C++ Core]/FPolyPath.cpp
nraptis/Metal_OpenGL_MobileGameEngine
cc36682676a9797df8b3a7ee235b99be3ae2f666
[ "MIT" ]
null
null
null
Framework/[C++ Core]/FPolyPath.cpp
nraptis/Metal_OpenGL_MobileGameEngine
cc36682676a9797df8b3a7ee235b99be3ae2f666
[ "MIT" ]
1
2021-11-16T15:29:40.000Z
2021-11-16T15:29:40.000Z
// // FPolyPath.cpp // DigMMMac // // Created by Nicholas Raptis on 3/30/15. // Copyright (c) 2015 Nick Raptis. All rights reserved. // #include "FPolyPath.hpp" #include "FApp.hpp" #include "core_includes.h" FPolyPathInterp::FPolyPathInterp() { mValid = false; mIndexStart = -1; mIndexEnd = -1; mPercentInterp = 0.0f; mX = 0.0f; mY = 0.0f; mNormX = 0.0f; mNormY = -1.0f; //mWidth = 0.0f; //mRotation = 0.0f; } FPolyPathInterp::~FPolyPathInterp() { } FPolyPath::FPolyPath() { mCount=0; mSize=0; mLength = 0.0f; mRefresh = true; mClosed = false; mWrap = false; mFlipNormals = true; mX = 0; mY = 0; mDistance = 0; mPercent = 0; mDirX = 0; mDirY = 0; mNormX = 0; mNormY = 0; //mLerpX = 0; //mLerpY = 0; //mWidth = 0; //mRotation = 0; //mFaceCenterX = 0; //mFaceCenterY = 0; //mFaceCenterRotation = 0; mCenterX = 0.0f; mCenterY = 0.0f; } FPolyPath::~FPolyPath() { Clear(); } void FPolyPath::Clear() { delete [] mX; mCount=0; mSize=0; mLength = 0.0f; mRefresh = true; mCenterX = 0.0f; mCenterY = 0.0f; mX = 0; mY = 0; mDistance = 0; mPercent = 0; mDirX = 0; mDirY = 0; mNormX = 0; mNormY = 0; //mLerpX = 0; //mLerpY = 0; //mWidth = 0; //mRotation = 0; //mFaceCenterX = 0; //mFaceCenterY = 0; //mFaceCenterRotation = 0; } void FPolyPath::RemoveAll() { mCount = 0; mRefresh = true; } void FPolyPath::Add(float pX, float pY) { if (mCount >= mSize) { Size(mCount + (mCount / 2) + 1); } mX[mCount] = pX; mY[mCount] = pY; mCount++; mRefresh = true; } void FPolyPath::Add(FPointList *pList) { if (pList) { for (int i=0;i<pList->mCount;i++) { Add(pList->mX[i], pList->mY[i]); } } mRefresh = true; } void FPolyPath::Set(int pIndex, float pX, float pY) { if (pIndex >= mSize) { SetSize(pIndex + (pIndex / 2) + 1); } if (pIndex >= mCount) { mCount = (pIndex + 1); } if (pIndex >= 0) { mX[pIndex] = pX; mY[pIndex] = pY; mRefresh = true; } } void FPolyPath::Size(int pSize) { if (pSize != mSize) { if (pSize <= 0) { Clear(); } else { if (mCount >= pSize) { mCount = pSize; } int aSize = pSize + 1; float *aNewX = new float[aSize * 8 + 8]; float *aNewY = aNewX + aSize; float *aNewDistance = aNewY + aSize; float *aNewPercent = aNewDistance + aSize; float *aNewDirX = aNewPercent + aSize; float *aNewDirY = aNewDirX + aSize; float *aNewNormX = aNewDirY + aSize; float *aNewNormY = aNewNormX + aSize; //float *aNewLerpX = aNewNormY + aSize; //float *aNewLerpY = aNewLerpX + aSize; //float *aNewWidth = aNewLerpY + aSize; //float *aNewRotation = aNewNormY + aSize; //float *aNewFaceCenterX = aNewRotation + aSize; //float *aNewFaceCenterY = aNewFaceCenterX + aSize; //float *aNewFaceCenterRotation = aNewRotation + aSize; for(int i=0;i<mCount;i++)aNewX[i] = mX[i]; for(int i=0;i<mCount;i++)aNewY[i] = mY[i]; for(int i=0;i<mCount;i++)aNewDistance[i] = mDistance[i]; for(int i=0;i<mCount;i++)aNewPercent[i] = mPercent[i]; for(int i=0;i<mCount;i++)aNewDirX[i] = mDirX[i]; for(int i=0;i<mCount;i++)aNewDirY[i] = mDirY[i]; for(int i=0;i<mCount;i++)aNewNormX[i] = mNormX[i]; for(int i=0;i<mCount;i++)aNewNormY[i] = mNormY[i]; //for(int i=0;i<mCount;i++)aNewLerpX[i] = mLerpX[i]; //for(int i=0;i<mCount;i++)aNewLerpY[i] = mLerpY[i]; //for(int i=0;i<mCount;i++)aNewWidth[i] = mWidth[i]; //for(int i=0;i<mCount;i++)aNewRotation[i] = mRotation[i]; //for(int i=0;i<mCount;i++)aNewFaceCenterX[i] = mFaceCenterX[i]; //for(int i=0;i<mCount;i++)aNewFaceCenterY[i] = mFaceCenterY[i]; //for(int i=0;i<mCount;i++)aNewFaceCenterRotation[i] = mFaceCenterRotation[i]; for(int i=mCount;i<aSize;i++)aNewX[i] = 0.0f; for(int i=mCount;i<aSize;i++)aNewY[i] = 0.0f; for(int i=mCount;i<aSize;i++)aNewDistance[i] = 0.0f; for(int i=mCount;i<aSize;i++)aNewPercent[i] = 0.0f; for(int i=mCount;i<aSize;i++)aNewDirX[i] = 0.0f; for(int i=mCount;i<aSize;i++)aNewDirY[i] = -1.0f; for(int i=mCount;i<aSize;i++)aNewNormX[i] = 1.0f; for(int i=mCount;i<aSize;i++)aNewNormY[i] = 0.0f; //for(int i=mCount;i<aSize;i++)aNewLerpX[i] = 1.0f; //for(int i=mCount;i<aSize;i++)aNewLerpY[i] = 0.0f; //for(int i=mCount;i<aSize;i++)aNewWidth[i] = 1.0f; //for(int i=mCount;i<aSize;i++)aNewRotation[i] = 0.0f; //for(int i=mCount;i<aSize;i++)aNewFaceCenterX[i] = -1.0f; //for(int i=mCount;i<aSize;i++)aNewFaceCenterY[i] = 0.0f; //for(int i=mCount;i<aSize;i++)aNewFaceCenterRotation[i] = 0.0f; delete [] mX; mX = aNewX; mY = aNewY; mDistance = aNewDistance; mPercent = aNewPercent; mDirX = aNewDirX; mDirY = aNewDirY; mNormX = aNewNormX; mNormY = aNewNormY; //mLerpX = aNewLerpX; //mLerpY = aNewLerpY; //mWidth = aNewWidth; //mRotation = aNewRotation; //mFaceCenterX = aNewFaceCenterX; //mFaceCenterY = aNewFaceCenterY; //mFaceCenterRotation = aNewFaceCenterRotation; mSize = pSize; mRefresh = true; } } } void FPolyPath::Draw() { if (mRefresh == true) { Generate(); } DrawPoints(); DrawEdges(); DrawNormals(); Graphics::SetColor(); } void FPolyPath::DrawPoints() { float aX = 0.0f; float aY = 0.0f; float aSize = 8.0f; float aSize2 = aSize * 0.5f; for (int i=0;i<mCount;i++) { aX = mX[i]; aY = mY[i]; Graphics::DrawRect(aX - aSize2, aY - aSize2, aSize, aSize); //gAppBase->mSysFont.Center(FString(i).c(), aX, aY - 30.0f); } } void FPolyPath::DrawEdges() { if (mCount > 1) { int aIndex = 0; float aX = 0.0f; float aY = 0.0f; float aLastX = aX; float aLastY = aY; if (mClosed == true) { aIndex = 0; aLastX = mX[mCount - 1]; aLastY = mY[mCount - 1]; } else { aIndex = 1; aLastX = mX[0]; aLastY = mY[0]; } while (aIndex < mCount) { aX = mX[aIndex]; aY = mY[aIndex]; Graphics::DrawLine(aLastX, aLastY, aX, aY, 1.0f); aLastX = aX; aLastY = aY; aIndex++; } } } void FPolyPath::DrawNormals() { float aX = 0.0f; float aY = 0.0f; float aDrawX = 0.0f; float aDrawY = 0.0f; float aLength = 10.0f; int aCount = mCount; if (aCount > 0) { if (mClosed) { aCount++; } } for (int aIndex = 0;aIndex < aCount; aIndex++) { aX = mX[aIndex]; aY = mY[aIndex]; aDrawX = mNormX[aIndex] * aLength; aDrawY = mNormY[aIndex] * aLength; aDrawX += aX; aDrawY += aY; Graphics::DrawLine(aX, aY, aDrawX, aDrawY); Graphics::DrawPoint(aDrawX, aDrawY, 3.0f); } } bool FPolyPath::Interpolate(float pLength) { return Interpolate(&mInterpolater, pLength); } bool FPolyPath::Interpolate(FPolyPathInterp *pInterp, float pLength) { bool aResult = false; if (mRefresh) { Generate(); } if (pInterp) { pInterp->mValid = false; pInterp->mIndexStart = -1; pInterp->mIndexEnd = -1; if ((mLength > 0.025f) && (mCount > 1)) { if (mWrap) { if (pLength > mLength) { int aLoops = 32; while ((aLoops > 0) && (pLength > mLength)) { pLength -= mLength; aLoops--; } } if (pLength < 0.0f) { int aLoops = 32; while ((aLoops > 0) && (pLength < 0.0f)) { pLength += mLength; aLoops--; } } } else { if (pLength > mLength) { pLength = mLength; } } int aInd1 = 0; int aInd2 = 0; int aCount = mCount; if (mClosed) { aCount++; } int aMid = 0; int aHigh = mCount; while (aInd2 != aHigh) { aMid = (aInd2 + aHigh) >> 1; if (mDistance[aMid] <= pLength) { aInd2 = aMid + 1; } else { aHigh = aMid; } } bool aLoopStart = false; aInd1 = (aInd2 - 1); if (aInd1 < 0) { aLoopStart = true; aInd1 = (aCount - 1); } float aLengthStart = mDistance[aInd1]; float aLengthEnd = mDistance[aInd2]; if (aLoopStart == true) { aLengthEnd += mLength; } float aRange = aLengthEnd - aLengthStart; float aPercent = 0.0f; if (aRange > SQRT_EPSILON) { aPercent = (float)(((pLength - aLengthStart)) / aRange); } pInterp->mValid = true; aResult = true; pInterp->mPercentInterp = aPercent; pInterp->mIndexStart = aInd1; pInterp->mIndexEnd = aInd2; pInterp->mLineX1 = mX[aInd1]; pInterp->mLineY1 = mY[aInd1]; pInterp->mLineX2 = mX[aInd2]; pInterp->mLineY2 = mY[aInd2]; //pInterp->mLineRotation = mRotation[aInd1]; pInterp->mX = mX[aInd1] + (mX[aInd2] - mX[aInd1]) * aPercent; pInterp->mY = mY[aInd1] + (mY[aInd2] - mY[aInd1]) * aPercent; } } return aResult; } void FPolyPath::GetWithDist(float pDistance, float &pX, float &pY) { Interpolate(pDistance); pX = mInterpolater.mX; pY = mInterpolater.mY; } void FPolyPath::GetWithPercent(float pPercent, float &pX, float &pY) { GetWithDist(pPercent * mLength, pX, pY); } void FPolyPath::GetRandom(float &pX, float &pY) { GetWithDist(gRand.GetFloat(mLength), pX, pY); } void FPolyPath::Save(FFile *pFile) { if (pFile) { pFile->WriteInt(mCount); for (int i=0;i<mCount;i++) { pFile->WriteFloat(mX[i]); pFile->WriteFloat(mY[i]); } } } void FPolyPath::Load(FFile *pFile) { Clear(); if (pFile) { int aCount = pFile->ReadInt(); Size(aCount); float aReadX = 0.0f; float aReadY = 0.0f; for (int i=0;i<aCount;i++) { aReadX = pFile->ReadFloat(); aReadY = pFile->ReadFloat(); Add(aReadX, aReadY); } } } void FPolyPath::Generate() { mRefresh = false; mLength = 0; mCenterX = 0.0f; mCenterY = 0.0f; if (mCount > 1) { float aDiffX = 0.0f; float aDiffY = 0.0f; float aDist = 0.0f; int aIndex = 1; float aX = 0.0f; float aY = 0.0f; float aLastX = mX[0]; float aLastY = mY[0]; mDistance[0] = 0.0f; mPercent[0] = 0.0f; int aCount = mCount; if (mClosed) { aCount++; mX[mCount] = mX[0]; mY[mCount] = mY[0]; } while (aIndex < aCount) { aX = mX[aIndex]; aY = mY[aIndex]; aDiffX = (aX - aLastX); aDiffY = (aY - aLastY); aDist = aDiffX * aDiffX + aDiffY * aDiffY; if (aDist > SQRT_EPSILON) { aDist = sqrtf(aDist); aDiffX /= aDist; aDiffY /= aDist; } else { aDist = 0.025f; aDiffX = 0.0f; aDiffY = -1.0f; } mDirX[aIndex] = aDiffX; mDirY[aIndex] = aDiffY; mNormX[aIndex] = -aDiffY; mNormY[aIndex] = aDiffX; mLength += aDist; mDistance[aIndex] = mLength; aLastX = aX; aLastY = aY; aIndex++; } mDistance[mCount] = mLength; mX[mCount] = mX[0]; mY[mCount] = mY[0]; /* mDirX[mCount] = mDirX[0]; mDirY[mCount] = mDirY[0]; mNormX[mCount] = mNormX[0]; mNormY[mCount] = mNormY[0]; mWidth[mCount] = mWidth[0]; */ mDirX[0] = mDirX[mCount]; mDirY[0] = mDirY[mCount]; mNormX[0] = mNormX[mCount]; mNormY[0] = mNormY[mCount]; if (mFlipNormals == true) { aIndex = 0; while (aIndex < aCount) { mNormX[aIndex] = -(mNormX[aIndex]); mNormY[aIndex] = -(mNormY[aIndex]); aIndex++; } } aIndex = 0; while (aIndex < mCount) { mCenterX += mX[aIndex]; mCenterY += mY[aIndex]; aIndex++; } mCenterX /= ((float)mCount); mCenterY /= ((float)mCount); aIndex = 0; while (aIndex < mCount) { aDiffX = mX[aIndex] - mCenterX; aDiffY = mY[aIndex] - mCenterY; aDist = aDiffX * aDiffX + aDiffY * aDiffY; if (aDist > SQRT_EPSILON) { aDist = sqrtf(aDist); aDiffX /= aDist; aDiffY /= aDist; } else { aDist = 0.025f; aDiffX = 0.0f; aDiffY = -1.0f; } aIndex++; } if (mLength > SQRT_EPSILON) { aIndex = 0; while (aIndex < aCount) { mPercent[aIndex] = mDistance[aIndex] / mLength; aIndex++; } } } }
26.02226
90
0.447852
nraptis
5858c55105c62a1eb7e1866d773e0fce05d55ee4
5,159
hpp
C++
includes/netflex/http/request.hpp
deguangchow/NetFlex
8fbdee6601dcbaa5be12e467bee82f1f648cd63b
[ "MIT" ]
null
null
null
includes/netflex/http/request.hpp
deguangchow/NetFlex
8fbdee6601dcbaa5be12e467bee82f1f648cd63b
[ "MIT" ]
null
null
null
includes/netflex/http/request.hpp
deguangchow/NetFlex
8fbdee6601dcbaa5be12e467bee82f1f648cd63b
[ "MIT" ]
null
null
null
// The MIT License (MIT) // // Copyright (c) 2015-2017 Simon Ninon <simon.ninon@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. #pragma once #include <string> #include <netflex/http/header.hpp> #include <netflex/http/method.hpp> #include <netflex/routing/params.hpp> namespace netflex { namespace http { //! //! http request representation //! contains all information related to the received http request //! class request { public: //! default ctor request(void) = default; //! default dtor ~request(void) = default; //! copy ctor request(const request&) = default; //! assignment operator request& operator=(const request&) = default; public: //! //! \return request http verb //! method get_method(void) const; //! //! \return request http verb (string version) //! const std::string& get_raw_method(void) const; //! //! \return status line target //! const std::string& get_target(void) const; //! //! \return request http version //! const std::string& get_http_version(void) const; //! //! set new http verb //! //! \param method new http verb //! void set_method(method method); //! //! set new http verb (string version) //! //! \param method new http verb //! void set_raw_method(const std::string& method); //! //! set new status line target //! //! \param target new status line target //! void set_target(const std::string& target); //! //! set new http version //! //! \param http_version new http version //! void set_http_version(const std::string& http_version); public: //! //! return specific header //! throws an exception if header does not exist //! //! \param name header name to get //! \return requested header value //! const std::string& get_header(const std::string& name) const; //! //! \return all headers for request //! const header_list_t& get_headers(void) const; //! //! set request headers //! //! \param headers new headers for request //! void set_headers(const header_list_t& headers); //! //! add a new header to the request header //! if header already exists, override its value //! //! \param header header to be added //! void add_header(const header& header); //! //! return whether the request contains a specific header //! //! \param name header name to check //! \return whether the requested header is present or not //! bool has_header(const std::string& name) const; //! //! remove a header from the request //! does nothing if header does not exist //! //! \param name name of the header to remove //! void remove_header(const std::string& name); public: //! //! \return requested path //! const std::string& get_path(void) const; //! //! \return request params (route params and GET params) //! const routing::params_t& get_params(void) const; //! //! set requested path //! //! \param path new path for request //! void set_path(const std::string& path); //! //! set request params //! //! \param params new request params //! void set_params(const routing::params_t& params); public: //! //! \return request body //! const std::string& get_body(void) const; //! //! set request body //! //! \param body new request body //! void set_body(const std::string& body); public: //! //! \return printable version of the request (for logging purpose) //! std::string to_string(void) const; private: //! //! request http verb //! method m_eHttpMethod; //! //! request http verb (raw string) //! std::string m_sHttpMethod; //! //! status line target //! std::string m_sTarget; //! //! requested http version //! std::string m_sHttpVersion; //! //! headers //! header_list_t m_mapHeaders; //! //! requested path //! std::string m_sPath; //! //! request params //! routing::params_t m_mapParams; //! //! request body //! std::string m_sBody; }; } // namespace http } // namespace netflex
21.953191
80
0.65284
deguangchow
5859747eab85343f2a3212dbf5189824caffe18e
7,513
cpp
C++
memory/MemoryManager.cpp
Savioor/NotPython
512d5feba6d6efb960d38adc98d2bd5ec7d3db3b
[ "Apache-2.0" ]
2
2019-11-17T22:38:23.000Z
2020-05-28T09:28:26.000Z
memory/MemoryManager.cpp
Savioor/NotPython
512d5feba6d6efb960d38adc98d2bd5ec7d3db3b
[ "Apache-2.0" ]
null
null
null
memory/MemoryManager.cpp
Savioor/NotPython
512d5feba6d6efb960d38adc98d2bd5ec7d3db3b
[ "Apache-2.0" ]
null
null
null
// // Created by alexey on 05/05/2020. // #include <iostream> #include "MemoryManager.h" #include "../debug.h" #include "builtins/primitive/PyInteger.h" #include "builtins/primitive/PyBool.h" #include "builtins/PyVariable.h" #include "builtins/PyList.h" #include "builtins/functions/internalFunctions/Print.h" #include "builtins/classes/ObjectStructure.h" #include "builtins/classes/PyClassStructure.h" MemoryManager *MemoryManager::instance = nullptr; void MemoryManager::decreaseExpDepth() { expressionDepth--; #if EXPR_DEPTH std::cout << "Expr depth now " << expressionDepth << std::endl; #endif std::vector<PyClass *> *temp = classesByExpDepth.at(classesByExpDepth.size() - 1); classesByExpDepth.pop_back(); for (PyClass *i : *temp) { i->references -= 1; i->expressionDepth = 0; // After the expression is parsed, variable enters global state } delete temp; } void MemoryManager::increaseExpDepth() { expressionDepth++; #if EXPR_DEPTH std::cout << "Expr depth now " << expressionDepth << std::endl; #endif classesByExpDepth.push_back(new std::vector<PyClass *>()); } MemoryManager::MemoryManager() : namedVariableStack{}, freeOpenCellsStack{}, memory{} { expressionDepth = 0; namedVariableStack.emplace_back(); classesByExpDepth = std::vector<std::vector<PyClass *> *>(); NONE = nullptr; TRUE = nullptr; FALSE = nullptr; ObjectStruct = nullptr; } int MemoryManager::allocateNewClass(PyClass *newClass) { if (newClass->expressionDepth >= 0) { throw std::runtime_error("Attempting to allocate class that was already allocated"); } #if MEM_ALLOC_DEBUG std::cout << "Allocating new class. Current classes allocated = " << (1 + memory.size() - freeOpenCellsStack.size()) << std::endl; #endif classesByExpDepth.at(classesByExpDepth.size() - 1)->push_back(newClass); newClass->expressionDepth = getCurrentDepth(); if (freeOpenCellsStack.empty()) { memory.push_back(newClass); return (int) (memory.size() - 1); } else { int emptyLocation = freeOpenCellsStack.at(freeOpenCellsStack.size() - 1); freeOpenCellsStack.pop_back(); memory[emptyLocation] = newClass; return emptyLocation; } } void MemoryManager::deallocateClass(int index) { PyClass *subject = memory.at(index); if (subject == nullptr) { #if MEM_ALLOC_DEBUG std::cout << "attempted dealloc class at " << index << " that was nullptr"; #endif return; } #if MEM_ALLOC_DEBUG std::cout << "deallocing class at " << index << " that has " << subject->references << " references." << std::endl; #endif if (subject->expressionDepth != 0) { throw std::runtime_error("Attempting to dealloc class that is still used in an expression"); } memory[index] = nullptr; delete (subject); freeOpenCellsStack.push_back(index); #if MEM_ALLOC_DEBUG std::cout << "Current classes allocated = " << (1 + memory.size() - freeOpenCellsStack.size()) << std::endl; #endif } MemoryManager &MemoryManager::getManager() { if (instance == nullptr) { instance = new MemoryManager(); instance->addInternalFunctions(); } return *instance; } int MemoryManager::getCurrentDepth() { return classesByExpDepth.size(); } PyClass *MemoryManager::getVariable(const std::string &name) { int lastElem = namedVariableStack.size() - 1; for (int i = lastElem; i >= 0; i--) { if (namedVariableStack.at(i).count(name) != 0) { return namedVariableStack.at(i).at(name); } } return new PyVariable(name); } int MemoryManager::allocateVariable(PyVariable *var) { namedVariableStack.at(getCurrentStackDepth()).insert({var->getName(), var}); var->myDepth = getCurrentStackDepth(); return getCurrentStackDepth(); } void MemoryManager::markAndSweep() { // TODO run it properly and automatically #if GC_DEBUG std::cout << "running GC!" << std::endl; #endif for (auto *cls : memory) { if (cls == nullptr) continue; cls->marked = false; } for (auto mp : namedVariableStack) { for (auto it = mp.begin(); it != mp.end(); it++) { PyClass *child = it->second; if (child != nullptr && !child->marked) { child->marked = true; // TODO test with pointerMaps markPointerMapOf(child); } } } PyClass *cls; for (int i = 0; i < memory.size(); i++) { cls = memory.at(i); if (immune(cls)) continue; deallocateClass(i); } #if GC_DEBUG std::cout << "running GC finished!" << std::endl; #endif } void MemoryManager::markPointerMapOf(PyClass *cls) { // TODO consider switching to iterative stack impl auto &pointerMap = cls->pointerMap; if (cls->type == pyARRAY) { // This is here because it allows list operation to be more efficient auto* asLs = (PyList*) cls; for (auto& elem : asLs->getElements()){ if (elem->marked) continue; elem->marked = true; markPointerMapOf(elem); } } else if (cls->type == pyVAR) { auto* asVar = (PyVariable*) cls; if (asVar->getChild() != nullptr && !asVar->getChild()->marked) { asVar->getChild()->marked = true; markPointerMapOf(asVar->getChild()); } } for (auto it = pointerMap.begin(); it != pointerMap.end(); it++) { if (it->second == nullptr || it->second->marked) continue; it->second->marked = true; markPointerMapOf(it->second); } } PyClass *MemoryManager::getNone() { if (NONE == nullptr) { increaseExpDepth(); NONE = new PyString("None"); NONE->allowCollection = false; decreaseExpDepth(); } return NONE; } void MemoryManager::increaseStackDepth() { namedVariableStack.emplace_back(); } void MemoryManager::decreaseStackDepth() { namedVariableStack.pop_back(); } bool MemoryManager::immune(PyClass *cls) { return cls == nullptr || cls->marked || cls->expressionDepth != 0 || !cls->allowCollection; } PyClass *MemoryManager::getTrue() { if (TRUE == nullptr) { increaseExpDepth(); TRUE = new PyBool(true); TRUE->allowCollection = false; decreaseExpDepth(); } return TRUE; } PyClass *MemoryManager::getFalse() { if (FALSE == nullptr) { increaseExpDepth(); FALSE = new PyBool(false); FALSE->allowCollection = false; decreaseExpDepth(); } return FALSE; } int MemoryManager::getCurrentStackDepth() { return namedVariableStack.size() - 1; } PyVariable *MemoryManager::allocateAndAssign(std::string& str, PyClass *value) { PyVariable* newVar = new PyVariable(str); newVar->setSelf(*value); return newVar; } PyVariable *MemoryManager::allocateAndAssign(std::string&& str, PyClass *value) { PyVariable* newVar = new PyVariable(str); newVar->setSelf(*value); return newVar; } void MemoryManager::addInternalFunctions() { increaseExpDepth(); allocateAndAssign("print", new Print()); allocateAndAssign("-Object-", getObject()); decreaseExpDepth(); } PyClassStructure *MemoryManager::getObject() { if (ObjectStruct == nullptr) { increaseExpDepth(); ObjectStruct = new ObjectStructure(); ObjectStruct->allowCollection = false; decreaseExpDepth(); } return ObjectStruct; }
27.221014
120
0.635299
Savioor
585b52ed829ef263835619bf4cb446b6367492b9
1,784
cpp
C++
oneflow/core/intrusive/object_pool_test.cpp
L-Net-1992/oneflow
4dc08d65caea36fdd137841ac95551218897e730
[ "Apache-2.0" ]
1
2022-03-14T11:17:56.000Z
2022-03-14T11:17:56.000Z
oneflow/core/intrusive/object_pool_test.cpp
L-Net-1992/oneflow
4dc08d65caea36fdd137841ac95551218897e730
[ "Apache-2.0" ]
null
null
null
oneflow/core/intrusive/object_pool_test.cpp
L-Net-1992/oneflow
4dc08d65caea36fdd137841ac95551218897e730
[ "Apache-2.0" ]
1
2021-12-15T02:14:49.000Z
2021-12-15T02:14:49.000Z
/* Copyright 2020 The OneFlow Authors. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <sstream> #include "gtest/gtest.h" #define private public #include "oneflow/core/common/util.h" #include "oneflow/core/intrusive/intrusive.h" #include "oneflow/core/intrusive/object_pool.h" namespace oneflow { namespace intrusive { namespace test { namespace { class IntrusiveFoo final // NOLINT : public intrusive::Base, public intrusive::EnableObjectPool<IntrusiveFoo, kThreadUnsafeAndDisableDestruct> { // NOLINT public: IntrusiveFoo() = default; // NOLINT intrusive::Ref* mut_intrusive_ref() { return &intrusive_ref_; } private: intrusive::Ref intrusive_ref_; }; TEST(ObjectPool_kThreadUnsafeAndDisableDestruct, append_to_pool) { ObjectPool<IntrusiveFoo, kThreadUnsafeAndDisableDestruct> object_pool; IntrusiveFoo* ptr = nullptr; { ptr = object_pool.make_shared().get(); } ASSERT_EQ(ptr, object_pool.make_shared().get()); } TEST(ObjectPool_kThreadUnsafeAndDisableDestruct, recycle) { ObjectPool<IntrusiveFoo, kThreadUnsafeAndDisableDestruct> object_pool; auto* ptr = object_pool.make_shared().get(); ASSERT_EQ(ptr, object_pool.make_shared().get()); } } // namespace } // namespace test } // namespace intrusive } // namespace oneflow
29.733333
100
0.766816
L-Net-1992
585c0172f41d5ac958063fd49843ba3aa5457fca
19,964
cpp
C++
src/aspell-60/modules/filter/sgml.cpp
reydajp/build-spell
a88ffbb9ffedae3f20933b187c95851e47e0e4c3
[ "MIT" ]
31
2016-11-08T05:13:02.000Z
2022-02-23T19:13:01.000Z
src/aspell-60/modules/filter/sgml.cpp
reydajp/build-spell
a88ffbb9ffedae3f20933b187c95851e47e0e4c3
[ "MIT" ]
6
2017-01-17T20:21:55.000Z
2021-09-02T07:36:18.000Z
src/aspell-60/modules/filter/sgml.cpp
reydajp/build-spell
a88ffbb9ffedae3f20933b187c95851e47e0e4c3
[ "MIT" ]
5
2017-07-11T11:10:55.000Z
2022-02-14T01:55:16.000Z
// This file is part of The New Aspell // Copyright (C) 2004 by Tom Snyder // Copyright (C) 2001-2004 by Kevin Atkinson under the GNU LGPL license // version 2.0 or 2.1. You should have received a copy of the LGPL // license along with this library if you did not you can find // it at http://www.gnu.org/. // // The orignal filter was written by Kevin Atkinson. // Tom Snyder rewrote the filter to support skipping SGML tags // // This filter enables the spell checking of sgml, html, and xhtml files // by skipping the <elements> and such. // The overall strategy is based on http://www.w3.org/Library/SGML.c. // We don't use that code (nor the sourceforge 'expat' project code) for // simplicity's sake. We don't need to fully parse all aspects of HTML - // we just need to skip and handle a few aspects. The w3.org code had too // many linkages into their overall SGML/HTML processing engine. // // See the comment at the end of this file for examples of what we handle. // See the config setting docs regarding our config lists: check and skip. #include <stdio.h> // needed for sprintf #include "settings.h" #include "asc_ctype.hpp" #include "config.hpp" #include "indiv_filter.hpp" #include "string_map.hpp" #include "mutable_container.hpp" #include "clone_ptr-t.hpp" #include "filter_char_vector.hpp" //right now unused option // static const KeyInfo sgml_options[] = { // {"sgml-extension", KeyInfoList, "html,htm,php,sgml", // N_("sgml file extensions")} // }; namespace { using namespace acommon; class ToLowerMap : public StringMap { public: PosibErr<bool> add(ParmStr to_add) { String new_key; for (const char * i = to_add; *i; ++i) new_key += asc_tolower(*i); return StringMap::add(new_key); } PosibErr<bool> remove(ParmStr to_rem) { String new_key; for (const char * i = to_rem; *i; ++i) new_key += asc_tolower(*i); return StringMap::remove(new_key); } }; class SgmlFilter : public IndividualFilter { // State enum. These states track where we are in the HTML/tag/element constructs. // This diagram shows the main states. The marked number is the state we enter // *after* we've read that char. Note that some of the state transitions handle // illegal HTML such as <tag=what?>. // // real text <tag attrib = this attrib2='that'> &nbsp; </tag> &#123; // | | | | || | | | | | | // 1 2 3 4 56 7 8 10 11 9 12 enum ScanState { S_text, // 1. raw user text outside of any markup. S_tag, // 2. reading the 'tag' in <tag> S_tag_gap,// 3. gap between attributes within an element: S_attr, // 4. Looking at an attrib name S_attr_gap,// 5. optional gap after attrib name S_equals, // 6. Attrib equals sign, also space after the equals. S_value, // 7. In attrib value. S_quoted, // 8. In quoted attrib value. S_end, // 9. Same as S_tag, but this is a </zee> type end tag. S_ignore_junk, // special case invalid area to ignore. S_ero, // 10. in the &code; special encoding within HTML. S_entity, // 11. in the alpha named &nom; special encoding.. S_cro, // 12. after the # of a &#nnn; numerical char reference encoding. // SGML.. etc can have these special "declarations" within them. We skip them // in a more raw manners since they don't abide by the attrib= rules. // Most importantly, some of the attrib quoting rules don't apply. // <!ENTITY rtfchar "gg" - - (high, low)> <!-- fully commented --> // | | || | // 20 21 23 24 25 S_md, // 20. In a declaration (or beginning a comment). S_mdq, // 21. Declaration in quotes - double or single quotes. S_com_1, // 23. perhaps a comment beginning. S_com, // 24. Fully in a comment S_com_e, // 25. Perhaps ending a comment. //S_literal, // within a tag pair that means all content should be interpreted literally: <PRE> // NOT CURRENTLY SUPPORTED FULLY. //S_esc,S_dollar,S_paren,S_nonasciitext // WOULD BE USED FOR ISO_2022_JP support. // NOT CURRENTLY SUPPORTED. }; ScanState in_what; // which quote char is quoting this attrib value. FilterChar::Chr quote_val; // one char prior to this one. For escape handling and such. FilterChar::Chr lookbehind; String tag_name; // we accumulate the current tag name here. String attrib_name; // we accumulate the current attribute name here. bool include_attrib; // are we in one of the attribs that *should* be spell checked (alt=..) int skipall; // are we in one of the special skip-all content tags? This is treated // as a bool and as a nesting level count. String tag_endskip; // tag name that will end that. StringMap check_attribs; // list of attribs that we *should* spell check. StringMap skip_tags; // list of tags that start a no-check-at-all zone. String which; bool process_char(FilterChar::Chr c); public: SgmlFilter(const char * n) : which(n) {} PosibErr<bool> setup(Config *); void reset(); void process(FilterChar * &, FilterChar * &); }; PosibErr<bool> SgmlFilter::setup(Config * opts) { name_ = which + "-filter"; order_num_ = 0.35; check_attribs.clear(); skip_tags.clear(); opts->retrieve_list("f-" + which + "-skip", &skip_tags); opts->retrieve_list("f-" + which + "-check", &check_attribs); reset(); return true; } void SgmlFilter::reset() { in_what = S_text; quote_val = lookbehind = '\0'; skipall = 0; include_attrib = false; } // yes this should be inlines, it is only called once // RETURNS: TRUE if the caller should skip the passed char and // not do any spell check on it. FALSE if char is a part of the text // of the document. bool SgmlFilter::process_char(FilterChar::Chr c) { bool retval = true; // DEFAULT RETURN VALUE. All returns are done // via retval and falling out the bottom. Except for // one case that must manage the lookbehind char. // PS: this switch will be fast since S_ABCs are an enum and // any good compiler will build a jump table for it. // RE the gotos: Sometimes considered bad practice but that is // how the W3C code (1995) handles it. Could be done also with recursion // but I doubt that will clarify it. The gotos are done in cases where several // state changes occur on a single input char. switch( in_what ) { case S_text: // 1. raw user text outside of any markup. s_text: switch( c ) { case '&': in_what = S_ero; break; case '<': in_what = S_tag; tag_name.clear(); break; default: retval = skipall; // ********** RETVAL ASSIGNED } // ************************** break; case S_tag: // 2. reading the 'tag' in <tag> // heads up: <foo/bar will be treated as an end tag. That's what w3c does. switch( c ) { case '>': goto all_end_tags; case '/': in_what = S_end; tag_name.clear(); break; case '!': in_what = S_md; break; default: // either more alphanum of the tag, or end of tagname: if( asc_isalpha(c) || asc_isdigit(c) ) { tag_name += asc_tolower(c); } else { // End of the tag: in_what = S_tag_gap; goto s_tag_gap; // handle content in that zone. } } break; // '>' '>' '>' '>' all_end_tags: // this gets called by several states to handle the // possibility of a '>' ending a whole <tag...> guy. if( c != '>' ) break; in_what = S_text; if( lookbehind == '/' ) { // Wowza: this is how we handle the <script stuff /> XML style self // terminating tag. By clearing the tagname out tag-skip-all code // will not be invoked. tag_name.clear(); } // Does this tag cause us to skip all content? if( skipall ) { // already in a skip-all context. See if this is // the same skipall tag: if( !strcmp( tag_name.c_str(), tag_endskip.c_str() ) ) { ++skipall; // increment our nesting level count. } } else { // Should we begin a skip all range? skipall = (skip_tags.have( tag_name.c_str() ) ? 1 : 0); if( skipall ) { tag_endskip = tag_name; // remember what tag to end on. } } break; case S_tag_gap: // 3. gap between attributes within an element: s_tag_gap: switch( c ) { case '>': goto all_end_tags; case '=': in_what = S_attr_gap; break; // uncommon - no-name attrib value default: if( asc_isspace( c ) ) break; // still in gap. else { in_what = S_attr; // start of attribute name; attrib_name.clear(); attrib_name += asc_tolower( c ); } break; } break; case S_end: // 9. Same as S_tag, but this is a </zee> type end tag. if( asc_isalpha(c) || asc_isdigit(c) ) { tag_name += asc_tolower( c ); } else { // See if we have left a skipall tag range. if( skipall && !strcmp( tag_name.c_str(), tag_endskip.c_str() ) ) { --skipall; // lessen nesting level count. This usually takes us to zero. } if( c == '>' ) in_what = S_text; // --don't go to all_end_tags. Really. else in_what = S_ignore_junk; // no-mans land: </end whats this??> } break; case S_ignore_junk: // no-mans land state: </end whats this here??> if( c == '>' ) in_what = S_text; break; case S_attr: // 4. Looking at an attrib name if( asc_isspace(c) ) in_what = S_attr_gap; else if( c == '=' ) in_what = S_equals; else if( c == '>' ) goto all_end_tags; else { attrib_name += asc_tolower( c ); } break; case S_attr_gap: // 5. optional gap after attrib name if( asc_isspace(c) ) break; else if( c == '=' ) in_what = S_equals; else if( c == '>' ) goto all_end_tags; else { // beginning of a brand new attr attrib_name.clear(); attrib_name += asc_tolower( c ); } break; case S_equals: // 6. Attrib equals sign, also space after the equals. if( asc_isspace(c) ) break; switch( c ) { case '>': goto all_end_tags; case '\'': case '"': in_what = S_quoted; quote_val = c; break; default: in_what = S_value; break; } // See if this attrib deserves full checking: include_attrib=check_attribs.have( attrib_name.c_str() ); // Handle the first value char if that is where we are now: if( in_what == S_value ) goto s_value; break; case S_value: // 7. In attrib value. s_value: if( c == '>' ) goto all_end_tags; else if( asc_isspace(c) ) in_what = S_tag_gap; // end of attrib value // ***************************** // ********** RETVAL ASSIGNED else if( include_attrib ) retval = false; // spell check this value. break; case S_quoted: // 8. In quoted attrib value. if( c == quote_val && lookbehind != '\\' ) in_what = S_tag_gap; else if( c == '\\' && lookbehind == '\\' ) { // This is an escape of an backslash. Therefore the backslash // does not escape what follows. Therefore we don't leave it in // the lookbehind. Yikes! lookbehind = '\0'; return !include_attrib; // ************* RETURN RETURN RETURN RETURN } else retval = !include_attrib; break; // note: these three cases - S_ero, S_cro, and S_entity which all handle // the &stuff; constructs are broken into 3 states for future upgrades. Someday // you may want to handle the chars these guys represent as individual chars. // I don't have the desire nor the knowledge to do it now. -Tom, 5/5/04. case S_ero: // 10. in the &code; special encoding within HTML. // &# is a 'Char Ref Open' if( c == '#' ) { in_what = S_cro; break; } // FALLTHROUGH INTENTIONAL case S_cro: // 12. after the # of a &#nnn; numerical char reference encoding. case S_entity: // 11. in the alpha named &nom; special encoding.. if( asc_isalpha(c) || asc_isdigit(c) ) break; // more entity chars. in_what = S_text; if( c == ';' ) break; // end of char code. goto s_text; // ran right into text. Handle it. // SGML.. etc can have these special "declarations" within them. We skip them // in a more raw manners since they don't abide by the attrib= rules. // Most importantly, some of the quoting rules don't apply. // <!ENTITY rtfchar "gg" 'tt' - - (high, low)> <!-- fully commented --> // | | | || || // 20 21 22 23 24 25 26 case S_md: // 20. In a declaration (or comment). switch( c ) { case '-': if( lookbehind == '!' ) { in_what = S_com_1; } break; case '"': // fallthrough - yes. case '\'': in_what = S_mdq; quote_val=c; break; case '>': in_what = S_text; // note: NOT all_end_tags cause it's not a real tag. break; } break; case S_mdq: // 22. Declaration in quotes. if( c == quote_val ) in_what = S_md; else if( c == '>' ) in_what = S_text; break; case S_com_1: // 23. perhaps a comment beginning. if( c == '-' ) in_what = S_com; else if( c == '>' ) in_what = S_text; else in_what = S_md; // out of possible comment. break; case S_com: // 24. Fully in a comment if( c == '-' && lookbehind == '-' ) in_what = S_com_e; break; case S_com_e: // 25. Perhaps ending a comment. if( c == '>' ) in_what = S_text; else if( c != '-' ) in_what = S_com; // back to basic comment. break; } // update the lookbehind: lookbehind = c; return( retval ); } void SgmlFilter::process(FilterChar * & str, FilterChar * & stop) { FilterChar * cur = str; while (cur != stop) { if (process_char(*cur)) *cur = ' '; ++cur; } } // // // class SgmlDecoder : public IndividualFilter { FilterCharVector buf; String which; public: SgmlDecoder(const char * n) : which(n) {} PosibErr<bool> setup(Config *); void reset() {} void process(FilterChar * &, FilterChar * &); }; PosibErr<bool> SgmlDecoder::setup(Config *) { name_ = which + "-decoder"; order_num_ = 0.65; return true; } void SgmlDecoder::process(FilterChar * & start, FilterChar * & stop) { buf.clear(); FilterChar * i = start; while (i != stop) { if (*i == '&') { FilterChar * i0 = i; FilterChar::Chr chr; ++i; if (i != stop && *i == '#') { chr = 0; ++i; while (i != stop && asc_isdigit(*i)) { chr *= 10; chr += *i - '0'; ++i; } } else { while (i != stop && (asc_isalpha(*i) || asc_isdigit(*i))) { ++i; } chr = '?'; } if (i != stop && *i == ';') ++i; buf.append(FilterChar(chr, i0, i)); } else { buf.append(*i); ++i; } } buf.append('\0'); start = buf.pbegin(); stop = buf.pend() - 1; } // // Sgml Encoder - BROKEN do not use // // class SgmlEncoder : public IndividualFilter // { // FilterCharVector buf; // String which; // public: // SgmlEncoder(const char * n) : which(n) {} // PosibErr<bool> setup(Config *); // void reset() {} // void process(FilterChar * &, FilterChar * &); // }; // PosibErr<bool> SgmlEncoder::setup(Config *) // { // name_ = which + "-encoder"; // order_num_ = 0.99; // return true; // } // void SgmlEncoder::process(FilterChar * & start, FilterChar * & stop) // { // buf.clear(); // FilterChar * i = start; // while (i != stop) // { // if (*i > 127) { // buf.append("&#", i->width); // char b[10]; // sprintf(b, "%d", i->chr); // buf.append(b, 0); // buf.append(';', 0); // } else { // buf.append(*i); // } // ++i; // } // buf.append('\0'); // start = buf.pbegin(); // stop = buf.pend() - 1; // } } C_EXPORT IndividualFilter * new_aspell_sgml_filter() { return new SgmlFilter("sgml"); } C_EXPORT IndividualFilter * new_aspell_sgml_decoder() { return new SgmlDecoder("sgml"); } // C_EXPORT IndividualFilter * new_aspell_sgml_encoder() // { // return new SgmlEncoder("sgml"); // } C_EXPORT IndividualFilter * new_aspell_html_filter() { return new SgmlFilter("html"); } C_EXPORT IndividualFilter * new_aspell_html_decoder() { return new SgmlDecoder("html"); } // C_EXPORT IndividualFilter * new_aspell_html_encoder() // { // return new SgmlEncoder("html"); // } /* Example HTML: <!-- This file contains several constructs that test the parsing and handling of SGML/HTML/XML in sgml.cpp. The only spelling errors you should see will be the word 'report this NNNN'. There will be 22 of these. run this by executing: aspell pipe -H < sgmltest.html WARNING: this is not really valid HTML. Don't display in a browser! --> <!-- phase 1 - SGML comments. --> reportthiszphaseONE <!-- ** 1.0 Valid comments... This file is full of them. --> <!-- ** 1.1 invalid open comment: --> <!- not in a comment>reportthisyes</!-> <!-- ** 1.2 invalid close comment: --> <!-- -- > spallwhat DON'T REPORT -> spallwhat DON'T REPORT --> <!-- phase 1.5 - special entity encodings --> reportthisphaseONEFIVE &nbsp; don't&nbsp;report&nbsp;this &#011; do not&#x20;report this. do not&gt;report this. this &amp; that. <!-- phase 2 - special skip tags --> reportthisphaseTWO <SCRIPT> spallwhat DON'T REPORT </SCRIPT> reportthisyes <style> spallwhat DON'T REPORT </style> reportthisyes <STYLE something="yes yes" > spallwhat DON'T REPORT </style > reportthisyes <script/> reportthisyes <!-- XHTML style terminated tag --> <script someattrib=value/> reportthisyes <!-- XHTML style terminated tag --> <!-- Nested skip tags --> <script> spallwhatnoreport <script> nonoreport </script><b>hello</b> nonoreport</script>reportthisyes <!-- phase 3 - special 'include this' attributes --> reportthisphaseTHREE <tagname alt="image text reportthisyes" alt2=spallwhat altt="spallwhat don't report"> <tagname ALT="image text reportthisyes" ALT2=spallwhat AL="spallwhat don't report"> <!-- phase 4 - attribute value quoteing and escaping --> reportthisphaseoneFOUR <checkthis attribute111=simple/value.value > <checkagain SOMEattrib = "whoa boy, mimimimspelled "> <singlequotes gotcha= 'singlypingly quoted///'> <dblescaped gogogogo="dontcheck \">still in dontcheck\\\" still in dontcheck"> reportthisyes. <dBLmore TomTomTomTom="so many escapes: \\\\\\\\"> reportthisyes. <dblescaped gogogogo='dontcheck \'>still in dontcheck\\\' still in dontcheck'> reportthisyes. <dBLmore TomTomTomTom='so many escapes: \\\\\\\\'> reportthisyes. <mixnmatch scanhere='">dontcheck \"dontcheck \'dontcheck' alt=reportthisyes> <!-- phase 5 - questionable (though all too common) constructs --> reportthisphaseFIVE <tag=dontreport> reportthisyes <tag hahahahhaha>reportthisyes <!-- this one is from Yahoo! --> <td width=1%><img src="http://wellll/thereeee/nowwww" alt="cool stuff"> <td width=1%><img src=http://wellll/thereeee/nowwww alt=real cool stuff> */
32.998347
101
0.586806
reydajp
585d27f2b0c775e3daf59590674a2556dc83baf8
83,348
cpp
C++
game/shared/cstrike15/gametypes.cpp
DannyParker0001/Kisak-Strike
99ed85927336fe3aff2efd9b9382b2b32eb1d05d
[ "Unlicense" ]
252
2020-12-16T15:34:43.000Z
2022-03-31T23:21:37.000Z
cstrike15_src/game/shared/cstrike15/gametypes.cpp
bahadiraraz/Counter-Strike-Global-Offensive
9a0534100cb98ffa1cf0c32e138f0e7971e910d3
[ "MIT" ]
23
2020-12-20T18:02:54.000Z
2022-03-28T16:58:32.000Z
cstrike15_src/game/shared/cstrike15/gametypes.cpp
bahadiraraz/Counter-Strike-Global-Offensive
9a0534100cb98ffa1cf0c32e138f0e7971e910d3
[ "MIT" ]
42
2020-12-19T04:32:33.000Z
2022-03-30T06:00:28.000Z
//========= Copyright (c) 1996-2011, Valve Corporation, All rights reserved. ============// // // Purpose: Game types and modes // // $NoKeywords: $ //=============================================================================// // // NOTE: This is horrible design to have this file included in multiple projects (client.dll, server.dll, matchmaking.dll) // which don't have same interfaces applicable to interact with the engine and don't have sufficient context here // hence these compile-time conditionals to use appropriate interfaces // #if defined( CLIENT_DLL ) || defined( GAME_DLL ) #include "cbase.h" #endif #if defined( MATCHMAKING_DS_DLL ) #include "eiface.h" #include "matchmaking/imatchframework.h" #endif #include "gametypes.h" #include "strtools.h" #include "dlchelper.h" #include "../engine/filesystem_engine.h" #include "filesystem.h" #include "tier2/fileutils.h" #include "matchmaking/cstrike15/imatchext_cstrike15.h" #if defined ( MATCHMAKING_DLL ) #include "../../../matchmaking/mm_extensions.h" #endif #include "fmtstr.h" // NOTE: This has to be the last file included! #include "tier0/memdbgon.h" void DisplayGameModeConvars( void ); // The following convars depend on the order of the game types and modes in GameModes.txt. ConVar game_online( "game_online", "1", FCVAR_REPLICATED | FCVAR_HIDDEN | FCVAR_GAMEDLL | FCVAR_CLIENTDLL, "The current game is online." ); ConVar game_public( "game_public", "1", FCVAR_REPLICATED | FCVAR_HIDDEN | FCVAR_GAMEDLL | FCVAR_CLIENTDLL, "The current game is public." ); ConVar game_type( "game_type", "0", FCVAR_REPLICATED | FCVAR_RELEASE | FCVAR_GAMEDLL | FCVAR_CLIENTDLL, "The current game type. See GameModes.txt." ); ConVar game_mode( "game_mode", "0", FCVAR_REPLICATED | FCVAR_RELEASE | FCVAR_GAMEDLL | FCVAR_CLIENTDLL, "The current game mode (based on game type). See GameModes.txt." ); ConVar custom_bot_difficulty( "custom_bot_difficulty", "0", FCVAR_REPLICATED | FCVAR_RELEASE | FCVAR_GAMEDLL | FCVAR_CLIENTDLL, "Bot difficulty for offline play." ); #if defined( CLIENT_DLL ) ConCommand cl_game_mode_convars( "cl_game_mode_convars", DisplayGameModeConvars, "Display the values of the convars for the current game_mode." ); #elif defined( GAME_DLL ) ConCommand sv_game_mode_convars( "sv_game_mode_convars", DisplayGameModeConvars, "Display the values of the convars for the current game_mode." ); #endif // HACKY: Ok, so this file is compiled into 3 different modules so we get three different // static game types objects... Unfortunately needs to do different things for servers and clients. // These helpers test if we're on a client and/or server... The exposed interface is always pointing // to the matchmaking dll instance so using its interfaces to tell where we are. bool GameTypes_IsOnServer( void ) { #if defined ( GAME_DLL ) return true; #endif #if defined ( MATCHMAKING_DLL ) return ( g_pMatchExtensions->GetIVEngineServer() != NULL ); #endif return false; } bool GameTypes_IsOnClient( void ) { #if defined ( CLIENT_DLL ) return true; #endif #if defined ( MATCHMAKING_DLL ) return ( g_pMatchExtensions->GetIVEngineClient() != NULL ); #endif return false; } static const int g_invalidInteger = -1; static uint32 g_richPresenceDefault = 0xFFFF; // ============================================================================================ // // GameType // ============================================================================================ // // -------------------------------------------------------------------------------------------- // // Purpose: Constructor // -------------------------------------------------------------------------------------------- // GameTypes::GameType::GameType() : m_Index( g_invalidInteger ) { m_Name[0] = '\0'; m_NameID[0] = '\0'; } // -------------------------------------------------------------------------------------------- // // Purpose: Destructor // -------------------------------------------------------------------------------------------- // GameTypes::GameType::~GameType() { m_GameModes.PurgeAndDeleteElements(); } // ============================================================================================ // // GameMode // ============================================================================================ // // -------------------------------------------------------------------------------------------- // // Purpose: Constructor // -------------------------------------------------------------------------------------------- // GameTypes::GameMode::GameMode() : m_Index( g_invalidInteger ), m_pExecConfings( NULL ) { m_Name[0] = '\0'; m_NameID[0] = '\0'; m_DescID[0] = '\0'; m_NameID_SP[0] = '\0'; m_DescID_SP[0] = '\0'; m_MaxPlayers = 1; m_NoResetVoteThresholdCT = -1; m_NoResetVoteThresholdT = -1; } // -------------------------------------------------------------------------------------------- // // Purpose: Destructor // -------------------------------------------------------------------------------------------- // GameTypes::GameMode::~GameMode() { if ( m_pExecConfings ) { m_pExecConfings->deleteThis(); } } // ============================================================================================ // // Map // ============================================================================================ // // -------------------------------------------------------------------------------------------- // // Purpose: Constructor // -------------------------------------------------------------------------------------------- // GameTypes::Map::Map() : m_Index( g_invalidInteger ), m_RichPresence( g_richPresenceDefault ) { m_Name[0] = '\0'; m_NameID[0] = '\0'; m_ImageName[0] = '\0'; m_RequiresAttr[0] = 0; m_RequiresAttrValue = -1; m_RequiresAttrReward[0] = 0; m_nRewardDropList = -1; } // ============================================================================================ // // MapGroup // ============================================================================================ // // -------------------------------------------------------------------------------------------- // // Purpose: Constructor // -------------------------------------------------------------------------------------------- // GameTypes::MapGroup::MapGroup() { m_Name[0] = '\0'; m_NameID[0] = '\0'; m_ImageName[0] = '\0'; m_bIsWorkshopMapGroup = false; } // ============================================================================================ // // CustomBotDifficulty // ============================================================================================ // // -------------------------------------------------------------------------------------------- // // Purpose: Constructor // -------------------------------------------------------------------------------------------- // GameTypes::CustomBotDifficulty::CustomBotDifficulty() : m_Index( g_invalidInteger ), m_pConvars( NULL ), m_HasBotQuota( false ) { m_Name[0] = '\0'; m_NameID[0] = '\0'; } // -------------------------------------------------------------------------------------------- // // Purpose: Destructor // -------------------------------------------------------------------------------------------- // GameTypes::CustomBotDifficulty::~CustomBotDifficulty() { if ( m_pConvars ) { m_pConvars->deleteThis(); } } // ============================================================================================ // // GameTypes // ============================================================================================ // // Singleton static GameTypes s_GameTypes; IGameTypes *g_pGameTypes = &s_GameTypes; EXPOSE_SINGLE_INTERFACE_GLOBALVAR( GameTypes, IGameTypes, VENGINE_GAMETYPES_VERSION, s_GameTypes ); // -------------------------------------------------------------------------------------------- // // Purpose: Constructor // -------------------------------------------------------------------------------------------- // GameTypes::GameTypes() : m_Initialized( false ), m_pExtendedServerInfo( NULL ), m_pServerMap( NULL ), m_pServerMapGroup( NULL ), m_iCurrentServerNumSlots( 0 ), m_bRunMapWithDefaultGametype( false ), m_bLoadingScreenDataIsCorrect( true ) { m_randomStream.SetSeed( (int)Plat_MSTime() ); } // -------------------------------------------------------------------------------------------- // // Purpose: Destructor // -------------------------------------------------------------------------------------------- // GameTypes::~GameTypes() { m_GameTypes.PurgeAndDeleteElements(); m_Maps.PurgeAndDeleteElements(); m_MapGroups.PurgeAndDeleteElements(); m_CustomBotDifficulties.PurgeAndDeleteElements(); if ( m_pExtendedServerInfo ) m_pExtendedServerInfo->deleteThis(); m_pExtendedServerInfo = NULL; ClearServerMapGroupInfo(); } void GameTypes::ClearServerMapGroupInfo( void ) { if ( m_pServerMap ) delete m_pServerMap; m_pServerMap = NULL; if ( m_pServerMapGroup ) delete m_pServerMapGroup; m_pServerMapGroup = NULL; } // -------------------------------------------------------------------------------------------- // // Purpose: Loads the contents of GameModes.txt // -------------------------------------------------------------------------------------------- // bool GameTypes::Initialize( bool force /* = false*/ ) { const char *fileName = "GameModes.txt"; if ( m_Initialized && !force ) { return true; } m_GameTypes.PurgeAndDeleteElements(); m_Maps.PurgeAndDeleteElements(); m_CustomBotDifficulties.PurgeAndDeleteElements(); ClearServerMapGroupInfo(); KeyValues *pKV = new KeyValues( "" ); KeyValues::AutoDelete autodelete( pKV ); DevMsg( "GameTypes: initializing game types interface from %s.\n", fileName ); // Load the key values from the disc. if ( !pKV->LoadFromFile( g_pFullFileSystem, fileName ) ) { Warning( "GameTypes: error loading %s.", fileName ); return false; } // pKV->SaveToFile( g_pFullFileSystem, "maps/gamemodes-pre.txt", "GAME" ); // Load key values from any DLC on disc. DLCHelper::AppendDLCKeyValues( pKV, fileName ); // Merge map sidecar files ( map.kv ) // Map sidecar loading has been moved to CCSGameRules::InitializeGameTypeAndMode // to eliminate large workshop subscription load times // InitMapSidecars( pKV ); // Lastly, merge key values from gamemodes_server.txt or from the file specified on the // command line. const char *svfileName; svfileName = CommandLine()->ParmValue( "-gamemodes_serverfile" ); if ( !svfileName ) svfileName = "gamemodes_server.txt"; DevMsg( "GameTypes: merging game types interface from %s.\n", svfileName ); KeyValues *pKV_sv = new KeyValues( "" ); if ( pKV_sv->LoadFromFile( g_pFullFileSystem, svfileName ) ) { // Merge the section that exec's configs in a special way for ( KeyValues *psvGameType = pKV_sv->FindKey( "gametypes" )->GetFirstTrueSubKey(); psvGameType; psvGameType = psvGameType->GetNextTrueSubKey() ) { for ( KeyValues *psvGameMode = psvGameType->FindKey( "gamemodes" )->GetFirstTrueSubKey(); psvGameMode; psvGameMode = psvGameMode->GetNextTrueSubKey() ) { if ( KeyValues *psvExec = psvGameMode->FindKey( "exec" ) ) { // We have an override for gametype-mode-exec if ( KeyValues *pOurExec = pKV->FindKey( CFmtStr( "gametypes/%s/gamemodes/%s/exec", psvGameType->GetName(), psvGameMode->GetName() ) ) ) { for ( KeyValues *psvConfigEntry = psvExec->GetFirstValue(); psvConfigEntry; psvConfigEntry = psvConfigEntry->GetNextValue() ) { pOurExec->AddSubKey( psvConfigEntry->MakeCopy() ); } psvGameMode->RemoveSubKey( psvExec ); psvExec->deleteThis(); } } } } // for modes that have weapon progressions remove pre-existing weapon progressions if the server file has them for ( KeyValues *psvGameType = pKV_sv->FindKey( "gametypes" )->GetFirstTrueSubKey(); psvGameType; psvGameType = psvGameType->GetNextTrueSubKey() ) { for ( KeyValues *psvGameMode = psvGameType->FindKey( "gamemodes" )->GetFirstTrueSubKey(); psvGameMode; psvGameMode = psvGameMode->GetNextTrueSubKey() ) { if ( KeyValues *psvProgressionCT = psvGameMode->FindKey( "weaponprogression_ct" ) ) { // We have an override for gametype-mode-weaponprogression_ct if ( KeyValues *pOurProgressionCT = pKV->FindKey( CFmtStr( "gametypes/%s/gamemodes/%s/weaponprogression_ct", psvGameType->GetName(), psvGameMode->GetName() ) ) ) { // remove the pre-existing progression pOurProgressionCT->Clear(); } } if ( KeyValues *psvProgressionT = psvGameMode->FindKey( "weaponprogression_t" ) ) { // We have an override for gametype-mode-weaponprogression_ct if ( KeyValues *pOurProgressionT = pKV->FindKey( CFmtStr( "gametypes/%s/gamemodes/%s/weaponprogression_t", psvGameType->GetName(), psvGameMode->GetName() ) ) ) { // remove the pre-existing progression pOurProgressionT->Clear(); } } } } pKV->MergeFrom( pKV_sv, KeyValues::MERGE_KV_UPDATE ); } else { DevMsg( "Failed to load %s\n", svfileName ); } if ( pKV_sv ) { pKV_sv->deleteThis(); pKV_sv = NULL; } // Load the game types. if ( !LoadGameTypes( pKV ) ) { return false; } // Load the maps. if ( !LoadMaps( pKV ) ) { return false; } // Load the map groups. if ( !LoadMapGroups( pKV ) ) { return false; } // Load the bot difficulty levels for Offline games. if ( !LoadCustomBotDifficulties( pKV ) ) { return false; } m_Initialized = true; return true; } //////////////////////////////////////////////////////////////////////////////////////////// // Purpose: load and merge key values from loose map sidecar files ( "de_dust_joeblow.kv" ) void GameTypes::InitMapSidecars( KeyValues* pKV ) { KeyValues *pKVMaps = pKV->FindKey( "maps" ); char mapwild[MAX_PATH]; Q_snprintf( mapwild, sizeof( mapwild ), "*.%sbsp", IsX360() ? "360." : "" ); CUtlVector<CUtlString> outList; // BEGIN Search the maps dir for .kv files that correspond to bsps. RecursiveFindFilesMatchingName( &outList, "maps", mapwild, "GAME" ); FOR_EACH_VEC( outList, i ) { const char* curMap = outList[i].Access(); AddMapKVs( pKVMaps, curMap ); } // END Search } //////////////////////////////////////////////////////////////////////////////////////////// // Purpose: shove a map KV data into the main gamemodes data void GameTypes::AddMapKVs( KeyValues* pKVMaps, const char* curMap ) { char filename[ MAX_PATH ]; char kvFilename[ MAX_PATH ]; KeyValues *pKVMap; V_StripExtension( curMap, filename, MAX_PATH ); V_FixSlashes( filename, '/' ); V_snprintf( kvFilename, sizeof( kvFilename ), "%s.kv", filename ); if ( !g_pFullFileSystem->FileExists( kvFilename ) ) { if ( !StringHasPrefix( filename, "maps/workshop/" ) ) return; char *pchNameBase = strrchr( filename, '/' ); if ( !pchNameBase ) return; // For workshop maps attempt sidecars by bare non-ID name too V_snprintf( kvFilename, sizeof( kvFilename ), "maps/%s.kv", pchNameBase + 1 ); } if ( !g_pFullFileSystem->FileExists( kvFilename ) ) return; // // Load the Map sidecar entry // const char* szMapNameBase = filename; // Strip off the "maps/" to find the correct entry. if ( !Q_strnicmp( szMapNameBase, "maps/", 5 ) ) { szMapNameBase += 5; } // Delete the existing map subkey if it exists. A map sidecar file stomps existing data for that map. KeyValues *pKVOld = pKVMaps->FindKey( szMapNameBase ); if ( pKVOld ) { // Keep the one defined in gamemodes.txt return; // // Msg( "GameTypes: Replacing existing entry for %s.\n", kvFilename ); // // pKVMaps->RemoveSubKey( pKVOld ); // // pKV->SaveToFile( g_pFullFileSystem, "maps/map_removed.txt", "GAME" ); } else { DevMsg( "GameTypes: Creating new entry for %s.\n", kvFilename ); } pKVMap = pKVMaps->CreateNewKey(); if ( pKVMap->LoadFromFile( g_pFullFileSystem, kvFilename ) ) { // pKV->SaveToFile( g_pFullFileSystem, "maps/map_added.txt", "GAME" ); } else { Warning( "Failed to load %s\n", kvFilename ); } } // -------------------------------------------------------------------------------------------- // // Purpose: Parse the given key values for the weapon progressions // -------------------------------------------------------------------------------------------- // void GameTypes::LoadWeaponProgression( KeyValues * pKV_WeaponProgression, CUtlVector< WeaponProgression > & vecWeaponProgression, const char * szGameType, const char * szGameMode ) { if ( pKV_WeaponProgression ) { for ( KeyValues *pKV_Weapon = pKV_WeaponProgression->GetFirstTrueSubKey(); pKV_Weapon; pKV_Weapon = pKV_Weapon->GetNextTrueSubKey() ) { // Get the weapon name. WeaponProgression wp; wp.m_Name.Set( pKV_Weapon->GetName() ); // Get the kills. const char *killsEntry = "kills"; wp.m_Kills = pKV_Weapon->GetInt( killsEntry, g_invalidInteger ); if ( wp.m_Kills == g_invalidInteger ) { wp.m_Kills = 0; Warning( "GameTypes: missing %s entry for weapon \"%s\" for game type/mode (%s/%s).\n", killsEntry, pKV_Weapon->GetName(), szGameType, szGameMode ); } vecWeaponProgression.AddToTail( wp ); } if ( vecWeaponProgression.Count() == 0 ) { Warning( "GameTypes: empty %s entry for game type/mode (%s/%s).\n", pKV_WeaponProgression->GetName(), szGameType, szGameMode ); } } } // -------------------------------------------------------------------------------------------- // // Purpose: Finds the index at which the named weapon resides in the progression index. // -------------------------------------------------------------------------------------------- // int GameTypes::FindWeaponProgressionIndex( CUtlVector< WeaponProgression > & vecWeaponProgression, const char * szWeaponName ) { FOR_EACH_VEC( vecWeaponProgression, tWeapon ) { if ( !V_strcmp( vecWeaponProgression[tWeapon].m_Name, szWeaponName ) ) { return tWeapon; } } return -1; } // -------------------------------------------------------------------------------------------- // // Purpose: Parse the given key values for the game types and modes. // -------------------------------------------------------------------------------------------- // bool GameTypes::LoadGameTypes( KeyValues *pKV ) { Assert( pKV ); if ( !pKV ) { return false; } Assert( m_GameTypes.Count() == 0 ); if ( m_GameTypes.Count() > 0 ) { m_GameTypes.PurgeAndDeleteElements(); } // Get the game types. const char *gameTypesEntry = "gameTypes"; KeyValues *pKV_GameTypes = pKV->FindKey( gameTypesEntry ); if ( !pKV_GameTypes ) { Warning( "GameTypes: could not find entry %s.\n", gameTypesEntry ); return false; } // Parse the game types. for ( KeyValues *pKV_GameType = pKV_GameTypes->GetFirstTrueSubKey(); pKV_GameType; pKV_GameType = pKV_GameType->GetNextTrueSubKey() ) { GameType *pGameType = new GameType(); // Set the name. V_strncpy( pGameType->m_Name, pKV_GameType->GetName(), sizeof( pGameType->m_Name ) ); // Set the name ID. const char *nameIDEntry = "nameID"; const char *pTypeNameID = pKV_GameType->GetString( nameIDEntry ); if ( pTypeNameID ) { V_strncpy( pGameType->m_NameID, pTypeNameID, sizeof( pGameType->m_NameID ) ); } else { Warning( "GameTypes: missing %s entry for game type %s.\n", nameIDEntry, pKV_GameType->GetName() ); } // Get the modes. const char *gameModesEntry = "gameModes"; KeyValues *pKV_GameModes = pKV_GameType->FindKey( gameModesEntry ); if ( pKV_GameModes ) { for ( KeyValues *pKV_GameMode = pKV_GameModes->GetFirstTrueSubKey(); pKV_GameMode; pKV_GameMode = pKV_GameMode->GetNextTrueSubKey() ) { GameMode *pGameMode = new GameMode(); // Set the name. V_strncpy( pGameMode->m_Name, pKV_GameMode->GetName(), sizeof( pGameMode->m_Name ) ); // Set the name ID. const char *pModeNameID = pKV_GameMode->GetString( nameIDEntry ); if ( pModeNameID && *pModeNameID != 0 ) { V_strncpy( pGameMode->m_NameID, pModeNameID, sizeof( pGameMode->m_NameID ) ); } else { Warning( "GameTypes: missing %s entry for game type/mode (%s/%s).\n", nameIDEntry, pKV_GameType->GetName(), pKV_GameMode->GetName() ); } // Set the SP name ID. const char *nameIDEntrySP = "nameID_SP"; const char *pModeNameID_SP = pKV_GameType->GetString( nameIDEntrySP ); if ( pModeNameID_SP && *pModeNameID_SP != 0 ) { V_strncpy( pGameMode->m_NameID_SP, pModeNameID_SP, sizeof( pGameMode->m_NameID_SP ) ); } else { if ( pModeNameID && *pModeNameID != 0 ) { V_strncpy( pGameMode->m_NameID_SP, pModeNameID, sizeof( pGameMode->m_NameID_SP ) ); } } // Set the description ID. const char *descIDEntry = "descID"; const char *pDescID = pKV_GameMode->GetString( descIDEntry ); if ( pDescID && *pDescID != 0 ) { V_strncpy( pGameMode->m_DescID, pDescID, sizeof( pGameMode->m_DescID ) ); } else { Warning( "GameTypes: missing %s entry for game type/mode (%s/%s).\n", descIDEntry, pKV_GameType->GetName(), pKV_GameMode->GetName() ); } // Set the SP name ID. const char *descIDEntrySP = "descID_SP"; const char *pDescID_SP = pKV_GameMode->GetString( descIDEntrySP ); if ( pDescID_SP && *pDescID_SP != 0 ) { V_strncpy( pGameMode->m_DescID_SP, pDescID_SP, sizeof( pGameMode->m_DescID_SP ) ); } else { if ( pDescID && *pDescID != 0 ) { V_strncpy( pGameMode->m_DescID_SP, pDescID, sizeof( pGameMode->m_DescID_SP ) ); } } // check for the command line override first. Otherwise use gamemodes.txt values. int maxplayers_override = CommandLine()->ParmValue( "-maxplayers_override", -1 ); if ( maxplayers_override >= 1 ) { pGameMode->m_MaxPlayers = maxplayers_override; } else { // Set the maxplayers for the type/mode. const char* maxplayersEntry = "maxplayers"; int maxplayers = pKV_GameMode->GetInt( maxplayersEntry ); if ( maxplayers && maxplayers >= 1 ) { pGameMode->m_MaxPlayers = maxplayers; } else { Warning( "GameTypes: missing, < 1, or invalid %s entry for game type/mode (%s/%s).\n", maxplayersEntry, pKV_GameType->GetName(), pKV_GameMode->GetName() ); pGameMode->m_MaxPlayers = 1; } } // Get the single player convars. const char *configsEntry = "exec"; KeyValues *pKVExecConfig = pKV_GameMode->FindKey( configsEntry ); if ( pKVExecConfig ) { pGameMode->m_pExecConfings = pKVExecConfig->MakeCopy(); } else { Warning( "GameTypes: missing entry %s for game type/mode (%s/%s).\n", configsEntry, pKV_GameType->GetName(), pKV_GameMode->GetName() ); } // Get the single player mapgroups. const char *mapgroupsEntrySP = "mapgroupsSP"; KeyValues *pKV_MapGroupsSP = pKV_GameMode->FindKey( mapgroupsEntrySP ); if ( pKV_MapGroupsSP ) { for ( KeyValues *pKV_MapGroup = pKV_MapGroupsSP->GetFirstValue(); pKV_MapGroup; pKV_MapGroup = pKV_MapGroup->GetNextValue() ) { // Ignore the "random" entry. if ( V_stricmp( pKV_MapGroup->GetName(), "random" ) == 0 ) { continue; } pGameMode->m_MapGroupsSP.CopyAndAddToTail( pKV_MapGroup->GetName() ); } if ( pGameMode->m_MapGroupsSP.Count() == 0 ) { Warning( "GameTypes: empty %s entry for game type/mode (%s/%s).\n", mapgroupsEntrySP, pKV_GameType->GetName(), pKV_GameMode->GetName() ); } } else { Warning( "GameTypes: missing %s entry for game type/mode (%s/%s).\n", mapgroupsEntrySP, pKV_GameType->GetName(), pKV_GameMode->GetName() ); } // Get the multiplayer mapgroups. const char *mapgroupsEntryMP = "mapgroupsMP"; KeyValues *pKV_MapGroupsMP = pKV_GameMode->FindKey( mapgroupsEntryMP ); if ( pKV_MapGroupsMP ) { for ( KeyValues *pKV_MapGroup = pKV_MapGroupsMP->GetFirstValue(); pKV_MapGroup; pKV_MapGroup = pKV_MapGroup->GetNextValue() ) { // Ignore the "random" entry. if ( V_stricmp( pKV_MapGroup->GetName(), "random" ) == 0 ) { continue; } pGameMode->m_MapGroupsMP.CopyAndAddToTail( pKV_MapGroup->GetName() ); } } // Get the CT weapon progression (optional). KeyValues * pKV_WeaponProgressionCT = pKV_GameMode->FindKey( "weaponprogression_ct" ); LoadWeaponProgression( pKV_WeaponProgressionCT, pGameMode->m_WeaponProgressionCT, pKV_GameType->GetName(), pKV_GameMode->GetName() ); KeyValues * pKV_WeaponProgressionT = pKV_GameMode->FindKey( "weaponprogression_t" ); LoadWeaponProgression( pKV_WeaponProgressionT, pGameMode->m_WeaponProgressionT, pKV_GameType->GetName(), pKV_GameMode->GetName() ); KeyValues * pKV_noResetVoteThresholdT = pKV_GameMode->FindKey( "no_reset_vote_threshold_t" ); if ( pKV_noResetVoteThresholdT ) { pGameMode->m_NoResetVoteThresholdT = FindWeaponProgressionIndex( pGameMode->m_WeaponProgressionT, pKV_noResetVoteThresholdT->GetString() ); } KeyValues * pKV_noResetVoteThresholdCT = pKV_GameMode->FindKey( "no_reset_vote_threshold_ct" ); if ( pKV_noResetVoteThresholdCT ) { pGameMode->m_NoResetVoteThresholdCT = FindWeaponProgressionIndex( pGameMode->m_WeaponProgressionCT, pKV_noResetVoteThresholdCT->GetString() ); } pGameMode->m_Index = pGameType->m_GameModes.Count(); pGameType->m_GameModes.AddToTail( pGameMode ); } } else { Warning( "GameTypes: missing %s entry for game type %s.\n", gameModesEntry, pKV_GameType->GetName() ); } if ( pGameType->m_GameModes.Count() == 0 ) { Warning( "GameTypes: empty %s entry for game type %s.\n", gameModesEntry, pKV_GameType->GetName() ); } pGameType->m_Index = m_GameTypes.Count(); m_GameTypes.AddToTail( pGameType ); } if ( m_GameTypes.Count() == 0 ) { Warning( "GameTypes: empty %s entry.\n", gameTypesEntry ); } return true; } // -------------------------------------------------------------------------------------------- // // Purpose: Parse the given key values for the maps. // -------------------------------------------------------------------------------------------- // bool GameTypes::LoadMaps( KeyValues *pKV ) { Assert( pKV ); if ( !pKV ) { return false; } Assert( m_Maps.Count() == 0 ); if ( m_Maps.Count() > 0 ) { m_Maps.PurgeAndDeleteElements(); } // Get the maps. const char *mapsEntry = "maps"; KeyValues *pKV_Maps = pKV->FindKey( mapsEntry ); if ( !pKV_Maps ) { Warning( "GameTypes: could not find entry %s.\n", mapsEntry ); return false; } // Parse the maps. for ( KeyValues *pKV_Map = pKV_Maps->GetFirstTrueSubKey(); pKV_Map; pKV_Map = pKV_Map->GetNextTrueSubKey() ) { LoadMapEntry( pKV_Map ); } if ( m_Maps.Count() == 0 ) { Warning( "GamesTypes: empty %s entry.\n", mapsEntry ); } return true; } // -------------------------------------------------------------------------------------------- // // Purpose: Loads a single map entry. // -------------------------------------------------------------------------------------------- // bool GameTypes::LoadMapEntry( KeyValues *pKV_Map ) { Assert( pKV_Map ); if ( !pKV_Map ) { return false; } Map *pMap = new Map(); // Set the name. V_strcpy_safe( pMap->m_Name, pKV_Map->GetName() ); // Set the name ID. const char *nameIDEntry = "nameID"; const char *pNameID = pKV_Map->GetString( nameIDEntry ); if ( pNameID ) { V_strncpy( pMap->m_NameID, pNameID, sizeof( pMap->m_NameID ) ); } else { Warning( "GameTypes: missing %s entry for map %s.\n", nameIDEntry, pKV_Map->GetName() ); } // Set the image name. const char *imageNameEntry = "imagename"; const char *pImageName = pKV_Map->GetString( imageNameEntry ); if ( pImageName ) { V_strncpy( pMap->m_ImageName, pImageName, sizeof( pMap->m_ImageName ) ); } else { Warning( "GameTypes: missing %s entry for map %s.\n", imageNameEntry, pKV_Map->GetName() ); } // Set the economy item requirements if ( const char *pszRequiresItem = pKV_Map->GetString( "requires_attr", NULL ) ) { V_strcpy_safe( pMap->m_RequiresAttr, pszRequiresItem ); } pMap->m_RequiresAttrValue = pKV_Map->GetInt( "requires_attr_value", -1 ); if ( const char *pszRequiresItemAttr = pKV_Map->GetString( "requires_attr_reward", NULL ) ) { V_strcpy_safe( pMap->m_RequiresAttrReward, pszRequiresItemAttr ); } pMap->m_nRewardDropList = pKV_Map->GetInt( "reward_drop_list", -1 ); // Set the rich presence (optional). pMap->m_RichPresence = static_cast<uint32>( pKV_Map->GetInt( "richpresencecontext", g_richPresenceDefault ) ); // Get the list of terrorist models. const char *tModelsEntry = "t_models"; KeyValues *pKV_TModels = pKV_Map->FindKey( tModelsEntry ); if ( pKV_TModels ) { for ( KeyValues *pKV_Model = pKV_TModels->GetFirstValue(); pKV_Model; pKV_Model = pKV_Model->GetNextValue() ) { pMap->m_TModels.CopyAndAddToTail( pKV_Model->GetName() ); } } else { Warning( "GameTypes: missing %s entry for map %s.\n", tModelsEntry, pKV_Map->GetName() ); } // Get the list of counter-terrorist models. const char *ctModelsEntry = "ct_models"; KeyValues *pKV_CTModels = pKV_Map->FindKey( ctModelsEntry ); if ( pKV_CTModels ) { for ( KeyValues *pKV_Model = pKV_CTModels->GetFirstValue(); pKV_Model; pKV_Model = pKV_Model->GetNextValue() ) { pMap->m_CTModels.CopyAndAddToTail( pKV_Model->GetName() ); } } else { Warning( "GameTypes: missing %s entry for map %s.\n", ctModelsEntry, pKV_Map->GetName() ); } // Get names for the view model arms pMap->m_TViewModelArms.Set( pKV_Map->GetString( "t_arms" ) ); pMap->m_CTViewModelArms.Set( pKV_Map->GetString( "ct_arms" ) ); pMap->m_nDefaultGameType = pKV_Map->GetInt( "default_game_type" ); pMap->m_nDefaultGameMode = pKV_Map->GetInt( "default_game_mode", 0 ); // Get the list of hostage models if there is one. const char *hostageModelsEntry = "hostage_models"; KeyValues *pKV_HostageModels = pKV_Map->FindKey( hostageModelsEntry ); if ( pKV_HostageModels ) { for ( KeyValues *pKV_Model = pKV_HostageModels->GetFirstValue(); pKV_Model; pKV_Model = pKV_Model->GetNextValue() ) { pMap->m_HostageModels.CopyAndAddToTail( pKV_Model->GetName() ); } } // Add the map to the list. pMap->m_Index = m_Maps.Count(); m_Maps.AddToTail( pMap ); return true; } // -------------------------------------------------------------------------------------------- // // Purpose: Parse the given key values for the mapgroups. // -------------------------------------------------------------------------------------------- // bool GameTypes::LoadMapGroups( KeyValues *pKV ) { Assert( pKV ); if ( !pKV ) { return false; } //Assert( m_MapGroups.Count() == 0 ); if ( m_MapGroups.Count() > 0 ) { //m_MapGroups.PurgeAndDeleteElements(); FOR_EACH_VEC_BACK( m_MapGroups, i ) { if ( !m_MapGroups[i]->m_bIsWorkshopMapGroup ) { delete m_MapGroups[i]; m_MapGroups.Remove( i ); } } } // Get the mapgroups. const char *mapGroupsEntry = "mapGroups"; KeyValues *pKV_MapGroups = pKV->FindKey( mapGroupsEntry ); if ( !pKV_MapGroups ) { Warning( "GameTypes: could not find entry %s.\n", mapGroupsEntry ); return false; } // Parse the mapgroups. for ( KeyValues *pKV_MapGroup = pKV_MapGroups->GetFirstTrueSubKey(); pKV_MapGroup; pKV_MapGroup = pKV_MapGroup->GetNextTrueSubKey() ) { MapGroup *pMapGroup = new MapGroup(); // Set the name. V_strncpy( pMapGroup->m_Name, pKV_MapGroup->GetName(), sizeof( pMapGroup->m_Name ) ); // Set the name ID. const char *nameIDEntry = "nameID"; const char *pNameID = pKV_MapGroup->GetString( nameIDEntry ); if ( pNameID ) { V_strncpy( pMapGroup->m_NameID, pNameID, sizeof( pMapGroup->m_NameID ) ); } else { Warning( "GameTypes: missing %s entry for map group %s.\n", nameIDEntry, pKV_MapGroup->GetName() ); } // Set the image name. const char *imageNameEntry = "imagename"; const char *pImageName = pKV_MapGroup->GetString( imageNameEntry ); if ( pImageName ) { V_strncpy( pMapGroup->m_ImageName, pImageName, sizeof( pMapGroup->m_ImageName ) ); } else { Warning( "GameTypes: missing %s entry for map group %s.\n", imageNameEntry, pKV_MapGroup->GetName() ); } // Get the maps. const char *mapsEntry = "maps"; KeyValues *pKV_Maps = pKV_MapGroup->FindKey( mapsEntry ); if ( pKV_Maps ) { for ( KeyValues *pKV_Map = pKV_Maps->GetFirstValue(); pKV_Map; pKV_Map = pKV_Map->GetNextValue() ) { pMapGroup->m_Maps.CopyAndAddToTail( pKV_Map->GetName() ); } } else { Warning( "GameTypes: missing %s entry for map group %s.\n", mapsEntry, pKV_MapGroup->GetName() ); } // Add the map group to the list. m_MapGroups.AddToTail( pMapGroup ); } if ( m_MapGroups.Count() == 0 ) { Warning( "GamesTypes: empty %s entry.\n", mapGroupsEntry ); } return true; } // -------------------------------------------------------------------------------------------- // // Purpose: Parse the given key values for the bot difficulties. // -------------------------------------------------------------------------------------------- // bool GameTypes::LoadCustomBotDifficulties( KeyValues *pKV ) { Assert( pKV ); if ( !pKV ) { return false; } Assert( m_CustomBotDifficulties.Count() == 0 ); if ( m_CustomBotDifficulties.Count() > 0 ) { m_CustomBotDifficulties.PurgeAndDeleteElements(); } // Get the bot difficulty levels. const char *botDifficultyEntry = "botDifficulty"; KeyValues *pKV_BotDiffs = pKV->FindKey( botDifficultyEntry ); if ( !pKV_BotDiffs ) { Warning( "GameTypes: could not find entry %s.\n", botDifficultyEntry ); return false; } // Parse the bot difficulty levels. for ( KeyValues *pKV_BotDiff = pKV_BotDiffs->GetFirstTrueSubKey(); pKV_BotDiff; pKV_BotDiff = pKV_BotDiff->GetNextTrueSubKey() ) { CustomBotDifficulty *pBotDiff = new CustomBotDifficulty(); // Set the name. V_strncpy( pBotDiff->m_Name, pKV_BotDiff->GetName(), sizeof( pBotDiff->m_Name ) ); // Set the name ID. const char *nameIDEntry = "nameID"; const char *pNameID = pKV_BotDiff->GetString( nameIDEntry ); if ( pNameID ) { V_strncpy( pBotDiff->m_NameID, pNameID, sizeof( pBotDiff->m_NameID ) ); } else { Warning( "GameTypes: missing %s entry for bot difficulty %s.\n", nameIDEntry, pKV_BotDiff->GetName() ); } // Get the convars. const char *convarsEntry = "convars"; KeyValues *pKV_Convars = pKV_BotDiff->FindKey( convarsEntry ); if ( pKV_Convars ) { pBotDiff->m_pConvars = pKV_Convars->MakeCopy(); } else { Warning( "GameTypes: missing entry %s for bot difficulty %s.\n", convarsEntry, pKV_BotDiff->GetName() ); } // Check to see if this difficulty level has a bot quota convar. if ( pKV_Convars ) { pBotDiff->m_HasBotQuota = ( pKV_Convars->GetInt( "bot_quota", g_invalidInteger ) != g_invalidInteger ); } pBotDiff->m_Index = m_CustomBotDifficulties.Count(); m_CustomBotDifficulties.AddToTail( pBotDiff ); } if ( m_CustomBotDifficulties.Count() == 0 ) { Warning( "GamesTypes: empty %s entry.\n", botDifficultyEntry ); } return true; } // -------------------------------------------------------------------------------------------- // // Purpose: Returns the game type matching the given name. // -------------------------------------------------------------------------------------------- // GameTypes::GameType *GameTypes::GetGameType_Internal( const char *gameType ) { Assert( gameType ); if ( gameType && gameType[0] != '\0' ) { // Find the game type. FOR_EACH_VEC( m_GameTypes, iType ) { GameType *pGameType = m_GameTypes[iType]; Assert( pGameType ); if ( pGameType && V_stricmp( pGameType->m_Name, gameType ) == 0 ) { // Found it. return pGameType; } } } // Not found. Warning( "GameTypes: could not find matching game type \"%s\".\n", gameType ); return NULL; } // -------------------------------------------------------------------------------------------- // // Purpose: Returns the game mode matching the given name. // -------------------------------------------------------------------------------------------- // GameTypes::GameMode *GameTypes::GetGameMode_Internal( GameType *pGameType, const char *gameMode ) { Assert( pGameType && gameMode ); if ( pGameType && gameMode && gameMode[0] != '\0' ) { // Find the game mode. FOR_EACH_VEC( pGameType->m_GameModes, iMode ) { GameMode *pGameMode = pGameType->m_GameModes[iMode]; Assert( pGameMode ); if ( pGameMode && V_stricmp( pGameMode->m_Name, gameMode ) == 0 ) { // Found it. return pGameMode; } } } // Not found. Warning( "GameTypes: could not find matching game mode \"%s\" for type \"%s\".\n", gameMode, ( pGameType ? pGameType->m_Name : "null" ) ); return NULL; } // -------------------------------------------------------------------------------------------- // // Purpose: Get the current game type matching the game_type convar. // -------------------------------------------------------------------------------------------- // GameTypes::GameType *GameTypes::GetCurrentGameType_Internal( void ) { if ( m_GameTypes.Count() == 0 ) { Warning( "GamesTypes: no game types have been loaded.\n" ); return NULL; } int gameType = game_type.GetInt(); if ( gameType < 0 || gameType >= m_GameTypes.Count() ) { Warning( "GamesTypes: game_type is set to an invalid value (%d). Range [%d,%d].\n", gameType, 0, m_GameTypes.Count() - 1 ); return NULL; } return m_GameTypes[gameType]; } // -------------------------------------------------------------------------------------------- // // Purpose: Get the current game mode matching the game_mode convar. // -------------------------------------------------------------------------------------------- // GameTypes::GameMode *GameTypes::GetCurrentGameMode_Internal( GameType *pGameType ) { Assert( pGameType ); if ( !pGameType ) { return NULL; } int gameMode = game_mode.GetInt(); if ( gameMode < 0 || gameMode >= pGameType->m_GameModes.Count() ) { Warning( "GamesTypes: game_mode is set to an invalid value (%d). Range [%d,%d].\n", gameMode, 0, pGameType->m_GameModes.Count() - 1 ); return NULL; } return pGameType->m_GameModes[gameMode]; } // -------------------------------------------------------------------------------------------- // // Purpose: Get the MapGroup from the mapgroup name // -------------------------------------------------------------------------------------------- // GameTypes::MapGroup *GameTypes::GetMapGroup_Internal( const char *mapGroup ) { Assert( mapGroup ); if ( mapGroup && mapGroup[0] != '\0' ) { #if defined ( MATCHMAKING_DLL ) // On the client and connected to a server, check the networked server values if ( g_pMatchExtensions->GetIVEngineClient() && g_pMatchExtensions->GetIVEngineClient()->IsConnected() ) { if ( m_pServerMapGroup && V_stricmp( m_pServerMapGroup->m_Name, mapGroup ) == 0 ) { return m_pServerMapGroup; } } #endif // Find the game type in our local list char const *pchMapGroupToFind = mapGroup; if ( char const *pchComma = strchr( mapGroup, ',' ) ) { // Use only the first mapgroup from the list for search char *pchCopy = ( char * ) stackalloc( pchComma - mapGroup + 1 ); Q_strncpy( pchCopy, mapGroup, pchComma - mapGroup + 1 ); pchCopy[ pchComma - mapGroup ] = 0; pchMapGroupToFind = pchCopy; } FOR_EACH_VEC( m_MapGroups, iMapGroup ) { MapGroup *pMapGroup = m_MapGroups[iMapGroup]; Assert( pMapGroup ); if ( pMapGroup && V_stricmp( pMapGroup->m_Name, pchMapGroupToFind ) == 0 ) { // Found it. return pMapGroup; } } // Not found in pre-built array, fake one for workshop if ( char const *pszWorkshopMapgroup = strstr( pchMapGroupToFind, "@workshop" ) ) { char const *pszMapId = pszWorkshopMapgroup + 9; if ( *pszMapId ) ++ pszMapId; CFmtStr fmtGroupName( "%llu", Q_atoui64( pszMapId ) ); char const *szIndividualMapName = pszWorkshopMapgroup + 1; CUtlStringList lstMapNames; lstMapNames.CopyAndAddToTail( szIndividualMapName ); return CreateWorkshopMapGroupInternal( fmtGroupName, lstMapNames ); } // Not found. //Warning( "GameTypes: could not find matching mapGroup \"%s\".\n", mapGroup ); } return NULL; } // -------------------------------------------------------------------------------------------- // // Purpose: Get the map matching the given name. // -------------------------------------------------------------------------------------------- // GameTypes::Map *GameTypes::GetMap_Internal( const char *mapName ) { if ( m_Maps.Count() == 0 ) { Warning( "GamesTypes: no maps have been loaded.\n" ); return NULL; } Assert( mapName ); if ( !mapName || mapName[0] == '\0' ) { Warning( "GamesTypes: invalid map name.\n" ); return NULL; } char mapNameNoExt[ MAX_MAP_NAME ]; //V_strcpy_safe( mapNameNoExt, mapName ); V_FileBase( mapName, mapNameNoExt, sizeof( mapNameNoExt ) ); const int extLen = 4; // Remove the .360 extension from the map name. char *pExt = mapNameNoExt + V_strlen( mapNameNoExt ) - extLen; if ( pExt >= mapNameNoExt && V_strnicmp( pExt, ".360", extLen ) == 0 ) { *pExt = '\0'; } // Remove the .bsp extension from the map name. pExt = mapNameNoExt + V_strlen( mapNameNoExt ) - extLen; if ( pExt >= mapNameNoExt && V_strnicmp( pExt , ".bsp", extLen ) == 0 ) { *pExt = '\0'; } #if defined ( MATCHMAKING_DLL ) // On the client and connected to a server, check the networked server values if ( m_pServerMap && g_pMatchExtensions->GetIVEngineClient() && g_pMatchExtensions->GetIVEngineClient()->IsConnected() ) { if( !V_stricmp( m_pServerMap->m_Name, mapNameNoExt ) || !V_stricmp( m_pServerMap->m_Name, mapName ) ) { return m_pServerMap; } } #endif // Find the map. FOR_EACH_VEC( m_Maps, iMap ) { Map *pMap = m_Maps[iMap]; Assert( pMap ); if ( pMap && V_stricmp( pMap->m_Name, mapNameNoExt ) == 0 ) { // Found it. return pMap; } } // Not found. // Squelching this-- community maps won't be found // Warning( "GameTypes: could not find matching map \"%s\".\n", mapNameNoExt ); return NULL; } // -------------------------------------------------------------------------------------------- // // Purpose: Get the current bot difficulty based on the custom_bot_difficulty convar. // -------------------------------------------------------------------------------------------- // GameTypes::CustomBotDifficulty *GameTypes::GetCurrentCustomBotDifficulty_Internal( void ) { if ( m_CustomBotDifficulties.Count() == 0 ) { Warning( "GamesTypes: no bot difficulties have been loaded.\n" ); return NULL; } int botDiff = custom_bot_difficulty.GetInt(); if ( botDiff < 0 || botDiff >= m_CustomBotDifficulties.Count() ) { Warning( "GamesTypes: custom_bot_difficulty is set to an invalid value (%d). Range [%d,%d].\n", botDiff, 0, m_CustomBotDifficulties.Count() - 1 ); return NULL; } return m_CustomBotDifficulties[botDiff]; } // -------------------------------------------------------------------------------------------- // // Purpose: Set the game type and mode convars from the given strings. // -------------------------------------------------------------------------------------------- // bool GameTypes::SetGameTypeAndMode( const char *gameType, const char *gameMode ) { int iType = g_invalidInteger; int iMode = g_invalidInteger; if ( GetGameModeAndTypeIntsFromStrings( gameType, gameMode, iType, iMode ) ) { // Set the game type. return SetGameTypeAndMode( iType, iMode ); } Warning( "GamesTypes: unable to set game type and mode. Could not find type/mode matching type:%s/mode:%s.\n", gameType, gameMode ); return false; } // -------------------------------------------------------------------------------------------- // // Purpose: Set the game type and mode convars from passing and alias. // -------------------------------------------------------------------------------------------- // bool GameTypes::GetGameTypeAndModeFromAlias( const char *modeAlias, int& iType, int& iMode ) { iType = g_invalidInteger; iMode = g_invalidInteger; if ( Q_strcmp( "competitive", modeAlias ) == 0 || Q_strcmp( "comp", modeAlias ) == 0 ) { iType = 0; iMode = 1; } else if ( Q_strcmp( "casual", modeAlias ) == 0 ) { iType = 0; iMode = 0; } else if ( Q_strcmp( "armsrace", modeAlias ) == 0 || Q_strcmp( "arms", modeAlias ) == 0 || Q_strcmp( "gungame", modeAlias ) == 0 || Q_strcmp( "gg", modeAlias ) == 0 ) { iType = 1; iMode = 0; } else if ( Q_strcmp( "demolition", modeAlias ) == 0 || Q_strcmp( "demo", modeAlias ) == 0 ) { iType = 1; iMode = 1; } else if ( Q_strcmp( "deathmatch", modeAlias ) == 0 || Q_strcmp( "dm", modeAlias ) == 0 ) { iType = 1; iMode = 2; } else if ( Q_strcmp( "training", modeAlias ) == 0 ) { iType = 2; iMode = 0; } else if ( Q_strcmp( "custom", modeAlias ) == 0 ) { iType = 3; iMode = 0; } else if ( Q_strcmp( "guardian", modeAlias ) == 0 || Q_strcmp( "guard", modeAlias ) == 0 || Q_strcmp( "cooperative", modeAlias ) == 0 ) { iType = 4; iMode = 0; } else if ( Q_strcmp( "default", modeAlias ) == 0 || Q_strcmp( "auto", modeAlias ) == 0 ) { SetRunMapWithDefaultGametype( true ); return false; } // return if we matched an alias return ( iType != g_invalidInteger && iMode != g_invalidInteger ); } // -------------------------------------------------------------------------------------------- // // Purpose: Set the game type and mode convars. // -------------------------------------------------------------------------------------------- // bool GameTypes::SetGameTypeAndMode( int nGameType, int nGameMode ) { // if we've launched the map through the menu, we are specifically saying that we should use these settings // otherwise, use the game type/mode that the made defines as the default if ( nGameType < CS_GameType_Min || nGameType > CS_GameType_Max ) { Warning( "GamesTypes: unable to set game type and mode. Game type value is outside valid range. (value == %d)\n", nGameType ); return false; } // Set the game type. DevMsg( "GameTypes: setting game type to %d.\n", nGameType ); game_type.SetValue( nGameType ); // Set the game mode. DevMsg( "GameTypes: setting game mode to %d.\n", nGameMode ); game_mode.SetValue( nGameMode ); return true; } void GameTypes::SetAndParseExtendedServerInfo( KeyValues *pExtendedServerInfo ) { if ( m_pExtendedServerInfo ) m_pExtendedServerInfo->deleteThis(); ClearServerMapGroupInfo(); m_pExtendedServerInfo = pExtendedServerInfo ? pExtendedServerInfo->MakeCopy() : NULL; // BUGBUG: Not networking the complete state of a map/mapgroup struct so these have default values // which may not match the server... Would like to avoid a ton of network traffic if it's not needed, so // will only clean this up if needed. if ( m_pExtendedServerInfo ) { //const char* szMapNameBase = V_GetFileName( m_pServerMap->m_Name ); m_iCurrentServerNumSlots = m_pExtendedServerInfo->GetInt( "numSlots", 0 ); m_pServerMap = new Map; V_strncpy( m_pServerMap->m_Name, m_pExtendedServerInfo->GetString( "map", "" ), ARRAYSIZE(m_pServerMap->m_Name) ); V_FixSlashes( m_pServerMap->m_Name, '/' ); m_pServerMap->m_TViewModelArms.Set( m_pExtendedServerInfo->GetString( "t_arms", "" ) ); m_pServerMap->m_CTViewModelArms.Set( m_pExtendedServerInfo->GetString( "ct_arms", "" ) ); m_pServerMap->m_nDefaultGameType = m_pExtendedServerInfo->GetInt( "default_game_type" ); m_pServerMap->m_nDefaultGameMode = m_pExtendedServerInfo->GetInt( "default_game_mode", 0 ); KeyValues *pCTModels = m_pExtendedServerInfo->FindKey( "ct_models", false ); if ( pCTModels ) { for ( KeyValues *pKV = pCTModels->GetFirstValue(); pKV; pKV = pKV->GetNextValue() ) { m_pServerMap->m_CTModels.CopyAndAddToTail( pKV->GetString() ); } } KeyValues *pTModels = m_pExtendedServerInfo->FindKey( "t_models", false ); if ( pTModels ) { for ( KeyValues *pKV = pTModels->GetFirstValue(); pKV; pKV = pKV->GetNextValue() ) { m_pServerMap->m_TModels.CopyAndAddToTail( pKV->GetString() ); } } if ( m_pExtendedServerInfo->GetBool( "official" ) && !m_pExtendedServerInfo->GetBool( "gotv" ) ) { V_strcpy_safe( m_pServerMap->m_RequiresAttr, m_pExtendedServerInfo->GetString( "requires_attr" ) ); m_pServerMap->m_RequiresAttrValue = m_pExtendedServerInfo->GetInt( "requires_attr_value" ); V_strcpy_safe( m_pServerMap->m_RequiresAttrReward, m_pExtendedServerInfo->GetString( "requires_attr_reward" ) ); m_pServerMap->m_nRewardDropList = m_pExtendedServerInfo->GetInt( "reward_drop_list" ); } m_pServerMapGroup = new MapGroup; V_strncpy( m_pServerMapGroup->m_Name, m_pExtendedServerInfo->GetString( "mapgroup", "" ), ARRAYSIZE(m_pServerMapGroup->m_Name) ); KeyValues *pMapsInGroup = m_pExtendedServerInfo->FindKey( "maplist", false ); if ( pMapsInGroup ) { for ( KeyValues *pKV = pMapsInGroup->GetFirstValue(); pKV; pKV = pKV->GetNextValue() ) { m_pServerMapGroup->m_Maps.CopyAndAddToTail( pKV->GetString() ); } } #if defined( MATCHMAKING_DLL ) || defined( MATCHMAKING_DS_DLL ) if ( g_pMatchFramework && g_pMatchFramework->GetEventsSubscription() ) { //char fileBase[MAX_MAP_NAME]; //V_FileBase( m_pServerMap->m_Name, fileBase, sizeof ( fileBase ) ); // Set game type and game mode convars appropriately: if ( m_pExtendedServerInfo->FindKey( "c_game_type" ) && m_pExtendedServerInfo->FindKey( "c_game_mode" ) ) { SetGameTypeAndMode( m_pExtendedServerInfo->GetInt( "c_game_type" ), m_pExtendedServerInfo->GetInt( "c_game_mode" ) ); } g_pMatchFramework->GetEventsSubscription()->BroadcastEvent( new KeyValues( "OnLevelLoadingSetDefaultGameModeAndType", "mapname", m_pServerMap->m_Name ) ); } #endif } } // -------------------------------------------------------------------------------------------- // // Purpose: Returns the index of the current game type. // -------------------------------------------------------------------------------------------- // void GameTypes::CheckShouldSetDefaultGameModeAndType( const char* szMapNameFull ) { // this is only called from CSGameRules() int iType = 0; int iMode = 0; bool bShouldSet = false; // check we don't have a launch option that defines what game type/mode we should be playing with KeyValues *mode = NULL; #if defined( CLIENT_DLL ) return; #elif defined( GAME_DLL ) mode = engine->GetLaunchOptions(); #elif defined( MATCHMAKING_DLL ) if ( IVEngineServer *pIVEngineServer = ( IVEngineServer * ) g_pMatchFramework->GetMatchExtensions()->GetRegisteredExtensionInterface( INTERFACEVERSION_VENGINESERVER ) ) { mode = pIVEngineServer->GetLaunchOptions(); } #elif defined( MATCHMAKING_DS_DLL ) if ( IVEngineServer *pIVEngineServer = ( IVEngineServer * ) g_pMatchFramework->GetMatchExtensions()->GetRegisteredExtensionInterface( INTERFACEVERSION_VENGINESERVER ) ) { mode = pIVEngineServer->GetLaunchOptions(); } #endif bool bCommandLineAlias = false; if ( mode ) { // start at the third value KeyValues *kv = mode->GetFirstSubKey()->GetNextKey(); //KeyValuesDumpAsDevMsg( mode ); for ( KeyValues *arg = kv->GetNextKey(); arg != NULL; arg = arg->GetNextKey() ) { // if "default" gets passed, we set should run with default to true inside this function and return false if ( GetGameTypeAndModeFromAlias( arg->GetString(), iType, iMode ) ) { // don't use the default map game mode bCommandLineAlias = true; bShouldSet = true; } } } const char* szMapNameBase = V_GetFileName( szMapNameFull ); if ( !bCommandLineAlias && GetRunMapWithDefaultGametype() ) { // the default game type hasn't been loaded yet so load it now (pulling it straight from the bsp) if it exists if ( GetDefaultGameTypeForMap( szMapNameFull ) == -1 ) { //V_FixSlashes( szMapNameBase, '/' ); char kvFilename[ MAX_PATH ]; V_snprintf( kvFilename, sizeof( kvFilename ), "maps/%s.kv", szMapNameBase ); if ( g_pFullFileSystem->FileExists( kvFilename ) ) { KeyValues *pKV = new KeyValues( "convars" ); if ( pKV->LoadFromFile( g_pFullFileSystem, kvFilename ) ) { KeyValuesDumpAsDevMsg( pKV, 1 ); LoadMapEntry( pKV ); } } } iType = GetDefaultGameTypeForMap( szMapNameFull ); iMode = GetDefaultGameModeForMap( szMapNameFull ); bShouldSet = true; } // a mode has not been set before this function was called, so set it here if ( bShouldSet ) { SetGameTypeAndMode( iType, iMode ); } // this is the end of the line for loading game types // once we have all of the data, if you just type "map mapname" in the console, it'll run with the map's default mode SetRunMapWithDefaultGametype( false ); #if defined( MATCHMAKING_DLL ) || defined( MATCHMAKING_DS_DLL ) if ( g_pMatchFramework && g_pMatchFramework->GetEventsSubscription() ) { g_pMatchFramework->GetEventsSubscription()->BroadcastEvent( new KeyValues( "OnLevelLoadingSetDefaultGameModeAndType", "mapname", szMapNameFull ) ); } #endif #ifndef CLIENT_DLL // now force the loading screen to show the correct ghing // char const *pGameType = GetGameTypeFromInt( iType ); // char const *pGameMode = GetGameModeFromInt( iMode, iType ); // PopulateLevelInfo( szMapNameBase, pGameType, pGameMode ); // BaseModUI::CBaseModPanel *pBaseModPanel = BaseModUI::CBaseModPanel::GetSingletonPtr(); // if ( pBaseModPanel && pBaseModPanel->IsVisible() ) // { // pBaseModPanel->CreateAndLoadDialogForKeyValues( szMapNameBase ); // } #endif } // -------------------------------------------------------------------------------------------- // // Purpose: Returns the index of the current game type. // -------------------------------------------------------------------------------------------- // int GameTypes::GetCurrentGameType() const { return game_type.GetInt(); } // -------------------------------------------------------------------------------------------- // // Purpose: Returns the index of the current game mode. // -------------------------------------------------------------------------------------------- // int GameTypes::GetCurrentGameMode() const { return game_mode.GetInt(); } // -------------------------------------------------------------------------------------------- // // Purpose: Get the current game type UI string. // -------------------------------------------------------------------------------------------- // const char *GameTypes::GetCurrentGameTypeNameID( void ) { GameType *pGameType = GetCurrentGameType_Internal(); Assert( pGameType ); if ( !pGameType ) { return NULL; } return pGameType->m_NameID; } // -------------------------------------------------------------------------------------------- // // Purpose: Get the current game mode UI string. // -------------------------------------------------------------------------------------------- // const char *GameTypes::GetCurrentGameModeNameID( void ) { GameType *pGameType = GetCurrentGameType_Internal(); Assert( pGameType ); if ( !pGameType ) { return NULL; } GameMode *pGameMode = GetCurrentGameMode_Internal( pGameType ); Assert( pGameMode ); if ( !pGameMode ) { return NULL; } if ( pGameMode->m_NameID_SP[0] == '\0' ) return pGameMode->m_NameID_SP; return pGameMode->m_NameID; } // -------------------------------------------------------------------------------------------- // // Purpose: Apply the game mode convars for the given type and mode. // -------------------------------------------------------------------------------------------- // bool GameTypes::ApplyConvarsForCurrentMode( bool isMultiplayer ) { GameType *pGameType = GetCurrentGameType_Internal(); Assert( pGameType ); if ( !pGameType || pGameType->m_Index == CS_GameType_Custom ) { return false; } GameMode *pGameMode = GetCurrentGameMode_Internal( pGameType ); Assert( pGameMode ); if ( !pGameMode ) { return false; } // Get the convars. // If there are no multiplayer convars, fall back to single player. KeyValues *pKV_Convars = pGameMode->m_pExecConfings; // Validate the convars. if ( !pKV_Convars ) { Warning( "GamesTypes: unable to set convars. There are no convars for game type/mode (%s:%d/%s:%d).\n", pGameType->m_Name, game_type.GetInt(), pGameMode->m_Name, game_mode.GetInt() ); return false; } // Apply the convars for this mode. for ( KeyValues *pKV_Convar = pKV_Convars->GetFirstValue(); pKV_Convar; pKV_Convar = pKV_Convar->GetNextValue() ) { if ( !Q_stricmp( "exec", pKV_Convar->GetName() ) ) { CFmtStr sExecCmd( "exec \"%s\"\n", pKV_Convar->GetString() ); // // NOTE: This is horrible design to have this file included in multiple projects (client.dll, server.dll, matchmaking.dll) // which don't have same interfaces applicable to interact with the engine and don't have sufficient context here // hence these compile-time conditionals to use appropriate interfaces // --- // to be fair, only server.dll calls this method, just the horrible design is that this method is compiled in a bunch // of dlls that don't need it... // #if defined( CLIENT_DLL ) engine->ExecuteClientCmd( sExecCmd ); #elif defined( GAME_DLL ) engine->ServerCommand( sExecCmd ); engine->ServerExecute(); #elif defined( MATCHMAKING_DLL ) if ( IVEngineClient *pIVEngineClient = ( IVEngineClient * ) g_pMatchFramework->GetMatchExtensions()->GetRegisteredExtensionInterface( VENGINE_CLIENT_INTERFACE_VERSION ) ) { pIVEngineClient->ExecuteClientCmd( sExecCmd ); } else if ( IVEngineServer *pIVEngineServer = ( IVEngineServer * ) g_pMatchFramework->GetMatchExtensions()->GetRegisteredExtensionInterface( INTERFACEVERSION_VENGINESERVER ) ) { pIVEngineServer->ServerCommand( sExecCmd ); pIVEngineServer->ServerExecute(); } #elif defined( MATCHMAKING_DS_DLL ) if ( IVEngineServer *pIVEngineServer = ( IVEngineServer * ) g_pMatchFramework->GetMatchExtensions()->GetRegisteredExtensionInterface( INTERFACEVERSION_VENGINESERVER ) ) { pIVEngineServer->ServerCommand( sExecCmd ); pIVEngineServer->ServerExecute(); } #else #error "gametypes.cpp included in an unexpected project" #endif } } DevMsg( "GameTypes: set convars for game type/mode (%s:%d/%s:%d):\n", pGameType->m_Name, game_type.GetInt(), pGameMode->m_Name, game_mode.GetInt() ); KeyValuesDumpAsDevMsg( pKV_Convars, 1 ); // If this is offline, then set the bot difficulty convars. if ( !isMultiplayer ) { CustomBotDifficulty *pBotDiff = GetCurrentCustomBotDifficulty_Internal(); Assert( pBotDiff ); if ( pBotDiff ) { KeyValues *pKV_ConvarsBotDiff = pBotDiff->m_pConvars; if ( pKV_ConvarsBotDiff ) { // Apply the convars for the bot difficulty. for ( KeyValues *pKV_Convar = pKV_ConvarsBotDiff->GetFirstValue(); pKV_Convar; pKV_Convar = pKV_Convar->GetNextValue() ) { // Only allow a certain set of convars to control bot difficulty char const *arrBotConvars[] = { "bot_difficulty", "bot_dont_shoot", "bot_quota" }; bool bBotConvar = false; for ( int jj = 0; jj < Q_ARRAYSIZE( arrBotConvars ); ++ jj ) { if ( !Q_stricmp( pKV_Convar->GetName(), arrBotConvars[jj] ) ) { bBotConvar = true; break; } } if ( !bBotConvar ) { Warning( "GamesTypes: invalid bot difficulty convar [%s] for bot difficulty (%s:%d).\n", pKV_Convar->GetName(), pBotDiff->m_Name, custom_bot_difficulty.GetInt() ); continue; } ConVarRef conVarRef( pKV_Convar->GetName() ); conVarRef.SetValue( pKV_Convar->GetString() ); } DevMsg( "GameTypes: set convars for bot difficulty (%s:%d):\n", pBotDiff->m_Name, custom_bot_difficulty.GetInt() ); KeyValuesDumpAsDevMsg( pKV_ConvarsBotDiff, 1 ); } else { Warning( "GamesTypes: unable to set bot difficulty convars. There are no convars for bot difficulty (%s:%d).\n", pBotDiff->m_Name, custom_bot_difficulty.GetInt() ); } } } return true; } // -------------------------------------------------------------------------------------------- // // Purpose: Output the values of the convars for the current game mode. // -------------------------------------------------------------------------------------------- // void GameTypes::DisplayConvarsForCurrentMode( void ) { GameType *pGameType = GetCurrentGameType_Internal(); Assert( pGameType ); if ( !pGameType ) { return; } GameMode *pGameMode = GetCurrentGameMode_Internal( pGameType ); Assert( pGameMode ); if ( !pGameMode ) { return; } // Display the configs KeyValuesDumpAsDevMsg( pGameMode->m_pExecConfings, 0, 0 ); // Display the offline bot difficulty convars. CustomBotDifficulty *pBotDiff = GetCurrentCustomBotDifficulty_Internal(); if ( pBotDiff ) { KeyValues *pKV_ConvarsBotDiff = pBotDiff->m_pConvars; if ( pKV_ConvarsBotDiff ) { Msg( "GameTypes: dumping convars for bot difficulty (%s:%d):", pBotDiff->m_Name, custom_bot_difficulty.GetInt() ); KeyValuesDumpAsDevMsg( pKV_ConvarsBotDiff, 0, 0 ); } } } // -------------------------------------------------------------------------------------------- // // Purpose: Returns the CT weapon progression for the current game type and mode. // -------------------------------------------------------------------------------------------- // const CUtlVector< IGameTypes::WeaponProgression > *GameTypes::GetWeaponProgressionForCurrentModeCT( void ) { GameType *pGameType = GetCurrentGameType_Internal(); Assert( pGameType ); if ( !pGameType ) { return NULL; } GameMode *pGameMode = GetCurrentGameMode_Internal( pGameType ); Assert( pGameMode ); if ( !pGameMode ) { return NULL; } return &(pGameMode->m_WeaponProgressionCT); } // -------------------------------------------------------------------------------------------- // // Purpose: Returns the T weapon progression for the current game type and mode. // -------------------------------------------------------------------------------------------- // const CUtlVector< IGameTypes::WeaponProgression > *GameTypes::GetWeaponProgressionForCurrentModeT( void ) { GameType *pGameType = GetCurrentGameType_Internal(); Assert( pGameType ); if ( !pGameType ) { return NULL; } GameMode *pGameMode = GetCurrentGameMode_Internal( pGameType ); Assert( pGameMode ); if ( !pGameMode ) { return NULL; } return &(pGameMode->m_WeaponProgressionT); } // -------------------------------------------------------------------------------------------- // // Purpose: Get a random mapgroup for the given mode and type. // -------------------------------------------------------------------------------------------- // const char *GameTypes::GetRandomMapGroup( const char *gameType, const char *gameMode ) { Assert( gameType && gameMode ); if ( !gameType || !gameMode ) { return NULL; } GameType *pGameType = GetGameType_Internal( gameType ); Assert( pGameType ); if ( !pGameType ) { return NULL; } GameMode *pGameMode = GetGameMode_Internal( pGameType, gameMode ); Assert( pGameMode ); if ( !pGameMode ) { return NULL; } if ( pGameMode->m_MapGroupsMP.Count() == 0 ) { return NULL; } // Randomly choose a mapgroup from our map list. int iRandom = m_randomStream.RandomInt( 0, pGameMode->m_MapGroupsMP.Count() - 1 ); return pGameMode->m_MapGroupsMP[iRandom]; } // -------------------------------------------------------------------------------------------- // // Purpose: Get the first map from the mapgroup // -------------------------------------------------------------------------------------------- // const char *GameTypes::GetFirstMap( const char *mapGroup ) { Assert( mapGroup ); if ( !mapGroup ) { return NULL; } MapGroup *pMapGroup = GetMapGroup_Internal( mapGroup ); Assert( pMapGroup ); if ( !pMapGroup ) { return NULL; } if ( pMapGroup->m_Maps.Count() == 0 ) { return NULL; } return pMapGroup->m_Maps[0]; } // -------------------------------------------------------------------------------------------- // // Purpose: Get a random map from the mapgroup // -------------------------------------------------------------------------------------------- // const char *GameTypes::GetRandomMap( const char *mapGroup ) { Assert( mapGroup ); if ( !mapGroup ) { return NULL; } MapGroup *pMapGroup = GetMapGroup_Internal( mapGroup ); Assert( pMapGroup ); if ( !pMapGroup ) { return NULL; } if ( pMapGroup->m_Maps.Count() == 0 ) { return NULL; } // Randomly choose a map from our map list. int iRandom = m_randomStream.RandomInt( 0, pMapGroup->m_Maps.Count() - 1 ); return pMapGroup->m_Maps[iRandom]; } // -------------------------------------------------------------------------------------------- // // Purpose: Get the next map from the mapgroup; wrap around to beginning from the end of list // -------------------------------------------------------------------------------------------- // const char *GameTypes::GetNextMap( const char *mapGroup, const char *mapName ) { Msg( "Looking for next map in mapgroup '%s'...\n", mapGroup ); Assert( mapGroup ); if ( !mapGroup ) { return NULL; } MapGroup *pMapGroup = GetMapGroup_Internal( mapGroup ); Assert( pMapGroup ); if ( !pMapGroup ) { return NULL; } if ( pMapGroup->m_Maps.Count() == 0 ) { return NULL; } int mapIndex = 0; for ( ; mapIndex < pMapGroup->m_Maps.Count(); ++mapIndex ) { char szInputName[MAX_PATH]; V_strcpy_safe( szInputName, mapName ); V_FixSlashes( szInputName, '/' ); if ( mapName && !V_stricmp( mapName, pMapGroup->m_Maps[mapIndex] ) ) { break; } } // get the next map in the list mapIndex++; if ( mapIndex >= pMapGroup->m_Maps.Count() ) { // wrap to the beginning of the list, use first map if the passed map wasn't in the mapgroup mapIndex = 0; } return pMapGroup->m_Maps[mapIndex]; } // -------------------------------------------------------------------------------------------- // // Purpose: Get the maxplayers value for the type and mode // NOTE: This is from the local KV file... This will not match the server you're connected to // remotely if they've changed it from the default! // -------------------------------------------------------------------------------------------- // int GameTypes::GetMaxPlayersForTypeAndMode( int iType, int iMode ) { GameType *pGameType; GameMode *pGameMode; const char* szGameType = GetGameTypeFromInt( iType ); const char* szGameMode = GetGameModeFromInt( iType, iMode ); GetGameModeAndTypeFromStrings( szGameType, szGameMode, pGameType, pGameMode ); if ( !pGameMode ) { return 1; } return pGameMode->m_MaxPlayers; } // -------------------------------------------------------------------------------------------- // // Purpose: Is this a valid mapgroup name // -------------------------------------------------------------------------------------------- // bool GameTypes::IsValidMapGroupName( const char * mapGroup ) { if ( !mapGroup || mapGroup[0] == '\0' ) { return false; } MapGroup *pMapGroup = GetMapGroup_Internal( mapGroup ); if ( !pMapGroup ) { return false; } return true; } // -------------------------------------------------------------------------------------------- // // Purpose: Does this mapname exist within this mapgroup // -------------------------------------------------------------------------------------------- // bool GameTypes::IsValidMapInMapGroup( const char * mapGroup, const char *mapName ) { if ( !IsValidMapGroupName( mapGroup ) ) { return false; } if ( !mapName ) { return false; } MapGroup *pMapGroup = GetMapGroup_Internal( mapGroup ); if ( !pMapGroup ) { return false; } char fileBase[MAX_MAP_NAME]; V_FileBase( mapName, fileBase, sizeof ( fileBase ) ); for ( int mapIndex = 0 ; mapIndex < pMapGroup->m_Maps.Count(); ++mapIndex ) { if ( !V_stricmp( fileBase, pMapGroup->m_Maps[mapIndex] ) || !V_stricmp( mapName, pMapGroup->m_Maps[mapIndex] ) ) { return true; } } return false; } // -------------------------------------------------------------------------------------------- // // Purpose: Is this mapgroup part of this type and mode // -------------------------------------------------------------------------------------------- // bool GameTypes::IsValidMapGroupForTypeAndMode( const char * mapGroup, const char *gameType, const char *gameMode ) { if ( !IsValidMapGroupName( mapGroup ) ) { return false; } if ( !gameType || !gameMode ) { return false; } GameType *pGameType = GetGameType_Internal( gameType ); if ( !pGameType ) { return false; } GameMode *pGameMode = GetGameMode_Internal( pGameType, gameMode ); if ( !pGameMode ) { return false; } for ( int i = 0 ; i < pGameMode->m_MapGroupsMP.Count(); ++i ) { if ( V_strcmp( mapGroup, pGameMode->m_MapGroupsMP[i] ) == 0 ) { return true; } } for ( int i = 0 ; i < pGameMode->m_MapGroupsSP.Count(); ++i ) { if ( V_strcmp( mapGroup, pGameMode->m_MapGroupsSP[i] ) == 0 ) { return true; } } return false; } // -------------------------------------------------------------------------------------------- // // Purpose: Apply the convars for the given map. // -------------------------------------------------------------------------------------------- // bool GameTypes::ApplyConvarsForMap( const char *mapName, bool isMultiplayer ) { Map *pMap = GetMap_Internal( mapName ); if ( pMap ) { // Determine if we need to set the bot quota. bool setBotQuota = true; if ( !isMultiplayer ) { CustomBotDifficulty *pBotDiff = GetCurrentCustomBotDifficulty_Internal(); Assert( pBotDiff ); if ( pBotDiff ) { setBotQuota = !pBotDiff->m_HasBotQuota; } } return true; } // Warning( "GamesTypes: unable to set convars for map %s. Could not find matching map name.\n", mapName ); return false; } // -------------------------------------------------------------------------------------------- // // Purpose: Get specifics about a map. // -------------------------------------------------------------------------------------------- // bool GameTypes::GetMapInfo( const char *mapName, uint32 &richPresence ) { Map *pMap = GetMap_Internal( mapName ); if ( !pMap ) { return false; } richPresence = pMap->m_RichPresence; return true; } // -------------------------------------------------------------------------------------------- // // Purpose: Returns the available terrorist character model names for the given map. // -------------------------------------------------------------------------------------------- // const CUtlStringList *GameTypes::GetTModelsForMap( const char *mapName ) { Map *pMap = GetMap_Internal( mapName ); if ( !pMap ) { return NULL; } return &pMap->m_TModels; } // -------------------------------------------------------------------------------------------- // // Purpose: Returns the available counter-terrorist character model names for the given map. // -------------------------------------------------------------------------------------------- // const CUtlStringList *GameTypes::GetCTModelsForMap( const char *mapName ) { Map *pMap = GetMap_Internal( mapName ); if ( !pMap ) { return NULL; } return &pMap->m_CTModels; } // -------------------------------------------------------------------------------------------- // // Purpose: Returns the available terrorist view model arms name for the given map. // -------------------------------------------------------------------------------------------- // const char *GameTypes::GetTViewModelArmsForMap( const char *mapName ) { Map *pMap = GetMap_Internal( mapName ); if ( !pMap ) { return NULL; } return pMap->m_TViewModelArms.String(); } // -------------------------------------------------------------------------------------------- // // Purpose: Returns the available counter-terrorist view model arms name for the given map. // -------------------------------------------------------------------------------------------- // const char *GameTypes::GetCTViewModelArmsForMap( const char *mapName ) { Map *pMap = GetMap_Internal( mapName ); if ( !pMap ) { return NULL; } return pMap->m_CTViewModelArms.String(); } // Item requirements for the map const char *GameTypes::GetRequiredAttrForMap( const char *mapName ) { Map *pMap = GetMap_Internal( mapName ); if ( !pMap ) { return NULL; } return pMap->m_RequiresAttr; } int GameTypes::GetRequiredAttrValueForMap( const char *mapName ) { Map *pMap = GetMap_Internal( mapName ); if ( !pMap ) { return -1; } return pMap->m_RequiresAttrValue; } const char *GameTypes::GetRequiredAttrRewardForMap( const char *mapName ) { Map *pMap = GetMap_Internal( mapName ); if ( !pMap ) { return NULL; } return pMap->m_RequiresAttrReward; } int GameTypes::GetRewardDropListForMap( const char *mapName ) { Map *pMap = GetMap_Internal( mapName ); if ( !pMap ) { return -1; } return pMap->m_nRewardDropList; } // -------------------------------------------------------------------------------------------- // // Purpose: Returns the available terrorist character model names for the given map. // -------------------------------------------------------------------------------------------- // const CUtlStringList *GameTypes::GetHostageModelsForMap( const char *mapName ) { Map *pMap = GetMap_Internal( mapName ); if ( !pMap ) { return NULL; } return &pMap->m_HostageModels; } // -------------------------------------------------------------------------------------------- // // Purpose: Returns the default game type defined for the map // -------------------------------------------------------------------------------------------- // const int GameTypes::GetDefaultGameTypeForMap( const char *mapName ) { Map *pMap = GetMap_Internal( mapName ); if ( !pMap ) { return -1; } return pMap->m_nDefaultGameType; } // -------------------------------------------------------------------------------------------- // // Purpose: Returns the default game mode defined for the map // -------------------------------------------------------------------------------------------- // const int GameTypes::GetDefaultGameModeForMap( const char *mapName ) { Map *pMap = GetMap_Internal( mapName ); if ( !pMap ) { return -1; } return pMap->m_nDefaultGameMode; } // -------------------------------------------------------------------------------------------- // // Purpose: Returns the maps for the given map group name. // -------------------------------------------------------------------------------------------- // const CUtlStringList *GameTypes::GetMapGroupMapList( const char *mapGroup ) { Assert( mapGroup ); if ( !mapGroup || StringIsEmpty( mapGroup ) ) { return NULL; } MapGroup *pMapGroup = GetMapGroup_Internal( mapGroup ); Assert( pMapGroup ); if ( !pMapGroup ) { return NULL; } return &pMapGroup->m_Maps; } // -------------------------------------------------------------------------------------------- // // Purpose: Returns the bot difficulty for Offline Games (where players choose difficulty). // -------------------------------------------------------------------------------------------- // int GameTypes::GetCustomBotDifficulty( void ) { return custom_bot_difficulty.GetInt(); } // -------------------------------------------------------------------------------------------- // // Purpose: Sets the bot difficulty for Offline Games (where players choose difficulty). // -------------------------------------------------------------------------------------------- // bool GameTypes::SetCustomBotDifficulty( int botDiff ) { if ( botDiff < 0 || botDiff >= m_CustomBotDifficulties.Count() ) { Warning( "GameTypes: invalid custom bot difficulty (%d). Range [%d,%d].\n", botDiff, 0, m_CustomBotDifficulties.Count() - 1 ); return false; } DevMsg( "GameTypes: setting custom_bot_difficulty to %d.\n", botDiff ); custom_bot_difficulty.SetValue( botDiff ); return true; } const char* GameTypes::GetGameTypeFromInt( int gameType ) { // Find the game type. FOR_EACH_VEC( m_GameTypes, iType ) { GameType *pGameType = m_GameTypes[iType]; Assert( pGameType ); if ( pGameType && pGameType->m_Index == gameType ) { // Found it. return pGameType->m_Name; } } // Not found. DevWarning( "GameTypes: could not find matching game type for value \"%d\".\n", gameType ); return NULL; } const char* GameTypes::GetGameModeFromInt( int gameType, int gameMode ) { // Find the game type. FOR_EACH_VEC( m_GameTypes, iType ) { GameType *pGameType = m_GameTypes[iType]; Assert( pGameType ); if ( pGameType && pGameType->m_Index == gameType ) { // Find the game mode. FOR_EACH_VEC( pGameType->m_GameModes, iMode ) { GameMode *pGameMode = pGameType->m_GameModes[iMode]; Assert( pGameMode ); if ( pGameMode && pGameMode->m_Index == gameMode ) { // Found it. return pGameMode->m_Name; } } } } // Not found. DevWarning( "GameTypes: could not find matching game mode value of \"%d\" and type value of \"%d\".\n", gameType, gameMode ); return NULL; } bool GameTypes::GetGameTypeFromMode( const char *szGameMode, const char *&pszGameTypeOut ) { FOR_EACH_VEC( m_GameTypes, iType ) { GameType *pGameType = m_GameTypes[ iType ]; Assert( pGameType ); if ( pGameType ) { // Find the game mode. FOR_EACH_VEC( pGameType->m_GameModes, iMode ) { GameMode *pGameMode = pGameType->m_GameModes[ iMode ]; Assert( pGameMode ); if ( pGameMode && !V_strcmp( pGameMode->m_Name, szGameMode ) ) { // Found it. pszGameTypeOut = pGameType->m_Name; return true; } } } } // Not found. DevWarning( "GameTypes: could not find matching game mode value of \"%s\" in any game type.\n", szGameMode ); return false; } bool GameTypes::GetGameModeAndTypeIntsFromStrings( const char* szGameType, const char* szGameMode, int& iOutGameType, int& iOutGameMode ) { GameType* type = NULL; GameMode* mode = NULL; iOutGameType = g_invalidInteger; iOutGameMode = g_invalidInteger; if ( V_stricmp( szGameType, "default" ) == 0 ) { return false; } if ( GetGameModeAndTypeFromStrings( szGameType, szGameMode, type, mode ) ) { if ( mode && type ) { Assert( type->m_Index >= 0 && type->m_Index < m_GameTypes.Count() ); Assert( mode->m_Index >= 0 && mode->m_Index < type->m_GameModes.Count() ); if ( type->m_Index >= 0 && type->m_Index < m_GameTypes.Count() && mode->m_Index >= 0 && mode->m_Index < type->m_GameModes.Count() ) { iOutGameType = type->m_Index; iOutGameMode = mode->m_Index; return true; } } } return false; } bool GameTypes::GetGameModeAndTypeNameIdsFromStrings( const char* szGameType, const char* szGameMode, const char*& szOutGameTypeNameId, const char*& szOutGameModeNameId ) { GameType* type = NULL; GameMode* mode = NULL; szOutGameTypeNameId = NULL; szOutGameModeNameId = NULL; if ( GetGameModeAndTypeFromStrings( szGameType, szGameMode, type, mode ) ) { Assert ( mode && mode->m_NameID ); Assert ( type && type->m_NameID ); if ( mode && mode->m_NameID && type && type->m_NameID ) { szOutGameTypeNameId = type->m_NameID; if ( mode->m_NameID_SP[0] != '\0' ) szOutGameModeNameId = mode->m_NameID_SP; else szOutGameModeNameId = mode->m_NameID; return true; } } return false; } bool GameTypes::GetGameModeAndTypeFromStrings( const char* szGameType, const char* szGameMode, GameType*& outGameType, GameMode*& outGameMode ) { outGameType = NULL; outGameMode = NULL; Assert( szGameType && szGameMode ); if ( !szGameType || !szGameMode ) { return false; } // we want to use the map's default settings, so don't set the game mode here, we'll do it later if ( V_stricmp( szGameType, "default" ) == 0 ) { return false; } outGameType = GetGameType_Internal( szGameType ); Assert( outGameType ); if ( outGameType ) { outGameMode = GetGameMode_Internal( outGameType, szGameMode ); Assert( outGameMode ); if ( outGameMode ) { return true; } } Warning( "GamesTypes: unable to get game type and mode. Could not find type/mode matching type:%s/mode:%s.\n", szGameType, szGameMode ); return false; } int GameTypes::GetNoResetVoteThresholdForCurrentModeCT( void ) { GameType *pGameType = GetCurrentGameType_Internal(); Assert( pGameType ); if ( !pGameType ) { return -1; } GameMode *pGameMode = GetCurrentGameMode_Internal( pGameType ); Assert( pGameMode ); if ( !pGameMode ) { return -1; } return pGameMode->m_NoResetVoteThresholdCT; } int GameTypes::GetNoResetVoteThresholdForCurrentModeT( void ) { GameType *pGameType = GetCurrentGameType_Internal(); Assert( pGameType ); if ( !pGameType ) { return -1; } GameMode *pGameMode = GetCurrentGameMode_Internal( pGameType ); Assert( pGameMode ); if ( !pGameMode ) { return -1; } return pGameMode->m_NoResetVoteThresholdT; } int GameTypes::GetCurrentServerNumSlots( void ) { // This is only valid if we are connected to a server and received the extended info blob #if defined ( MATCHMAKING_DLL ) Assert( m_pExtendedServerInfo && g_pMatchExtensions->GetIVEngineClient() && g_pMatchExtensions->GetIVEngineClient()->IsConnected() ); #endif Assert ( GameTypes_IsOnClient() ); return m_iCurrentServerNumSlots; } int GameTypes::GetCurrentServerSettingInt( const char *szSetting, int iDefaultValue ) { return m_pExtendedServerInfo->GetInt( szSetting, iDefaultValue ); } bool GameTypes::CreateOrUpdateWorkshopMapGroup( const char* szName, const CUtlStringList & vecMapNames ) { return !!CreateWorkshopMapGroupInternal( szName, vecMapNames ); } GameTypes::MapGroup * GameTypes::CreateWorkshopMapGroupInternal( const char* szName, const CUtlStringList & vecMapNames ) { MapGroup *pMapGroup = GetMapGroup_Internal( szName ); if ( !pMapGroup ) { pMapGroup = new MapGroup; V_strcpy_safe( pMapGroup->m_Name, szName ); m_MapGroups.AddToTail( pMapGroup ); } // Workshop map groups are named their publishfileid, so a nonzero integer. Assert( V_atoui64( szName ) != 0 ); pMapGroup->m_bIsWorkshopMapGroup = true; // Clear old map list, stomp with new one pMapGroup->m_Maps.PurgeAndDeleteElements(); FOR_EACH_VEC( vecMapNames, i ) { const char* szMap = vecMapNames[i]; pMapGroup->m_Maps.CopyAndAddToTail( szMap ); V_FixSlashes( pMapGroup->m_Maps.Tail(), '/' ); } return pMapGroup; } bool GameTypes::IsWorkshopMapGroup( const char* szMapGroupName ) { MapGroup *pMapGroup = GetMapGroup_Internal( szMapGroupName ); return pMapGroup && pMapGroup->m_bIsWorkshopMapGroup; } // ============================================================================================ // // Helper functions // ============================================================================================ // // -------------------------------------------------------------------------------------------- // // Purpose: Display the convars for the current game mode. // -------------------------------------------------------------------------------------------- // void DisplayGameModeConvars( void ) { if ( g_pGameTypes ) { g_pGameTypes->DisplayConvarsForCurrentMode(); } }
31.251594
180
0.584837
DannyParker0001
58614c941a10a050a810e7f34c18c37e5de685ad
2,459
cpp
C++
src/Networking/ParseBaseStation.cpp
jonahbardos/PY2020
af4f61b86ae5013e58faf4842bf20863b3de3957
[ "Apache-2.0" ]
null
null
null
src/Networking/ParseBaseStation.cpp
jonahbardos/PY2020
af4f61b86ae5013e58faf4842bf20863b3de3957
[ "Apache-2.0" ]
null
null
null
src/Networking/ParseBaseStation.cpp
jonahbardos/PY2020
af4f61b86ae5013e58faf4842bf20863b3de3957
[ "Apache-2.0" ]
null
null
null
#include "Network.h" #include "log.h" #include "IK.h" #include "motor_interface.h" #include "ParseBaseStation.h" #include <cmath> #include <tgmath.h> #include "../simulator/world_interface.h" #include "../Globals.h" #include <iostream> using nlohmann::json; bool ParseDrivePacket(json &message); bool ParseEmergencyStop(json &message); bool sendError(std::string const &msg) { json error_message = {}; error_message["status"] = "error"; error_message["msg"] = msg; sendBaseStationPacket(error_message.dump()); log(LOG_ERROR, error_message.dump()); return false; } bool ParseBaseStationPacket(char const* buffer) { log(LOG_INFO, "Message from base station: " + (std::string) buffer); json parsed_message; try { parsed_message = json::parse(buffer); } catch (json::parse_error) { return sendError("Parse error"); } std::string type; try { type = parsed_message["type"]; } catch (json::type_error) { return sendError("Could not find message type"); } log(LOG_DEBUG, "Message type: " + type); bool success = false; if (type == "estop") { success = ParseEmergencyStop(parsed_message); } else if (Globals::E_STOP) { return sendError("Emergency stop is activated"); } if (type == "ik") { success = ParseIKPacket(parsed_message); } else if (type == "drive") { success = ParseDrivePacket(parsed_message); } else if (type == "motor") { success = ParseMotorPacket(parsed_message); } if (success) { json response = {{"status", "ok"}}; sendBaseStationPacket(response.dump()); } return success; } bool ParseEmergencyStop(json &message) { // TODO actually send e-stop packet (packet id 0x30 broadcast) bool success = setCmdVel(0,0); Globals::E_STOP = true; bool release; try { release = message["release"]; } catch (json::type_error) { return sendError("Malformatted estop packet"); } if (release) { Globals::E_STOP = false; return success; } else { return success; } } bool ParseDrivePacket(json &message) { double fb, lr; try { fb = message["forward_backward"]; lr = message["left_right"]; } catch (json::type_error) { return sendError("Malformatted drive packet"); } if (fb > 1.0 || fb < -1.0 || lr > 1.0 || lr < -1.0) { return sendError("Drive targets not within bounds +/- 1.0"); } // TODO do we need to scale or invert these? return setCmdVel(lr, fb); }
21.017094
70
0.649858
jonahbardos
5862dfd3751ba0e8c46e2e25a14c00912356a8bd
20,818
cpp
C++
asteria/src/library/json.cpp
usama-makhzoum/asteria
ea4c893a038e0c5bef14d4d9f6723124a0cbb30f
[ "BSD-3-Clause" ]
null
null
null
asteria/src/library/json.cpp
usama-makhzoum/asteria
ea4c893a038e0c5bef14d4d9f6723124a0cbb30f
[ "BSD-3-Clause" ]
null
null
null
asteria/src/library/json.cpp
usama-makhzoum/asteria
ea4c893a038e0c5bef14d4d9f6723124a0cbb30f
[ "BSD-3-Clause" ]
null
null
null
// This file is part of Asteria. // Copyleft 2018 - 2021, LH_Mouse. All wrongs reserved. #include "../precompiled.hpp" #include "json.hpp" #include "../runtime/argument_reader.hpp" #include "../runtime/global_context.hpp" #include "../compiler/token_stream.hpp" #include "../compiler/parser_error.hpp" #include "../compiler/enums.hpp" #include "../utils.hpp" namespace asteria { namespace { struct Indenter { virtual ~Indenter(); virtual tinyfmt& break_line(tinyfmt& fmt) const = 0; virtual void increment_level() = 0; virtual void decrement_level() = 0; virtual bool has_indention() const noexcept = 0; }; Indenter:: ~Indenter() { } class Indenter_none final : public Indenter { public: explicit Indenter_none() = default; public: tinyfmt& break_line(tinyfmt& fmt) const override { return fmt; } void increment_level() override { } void decrement_level() override { } bool has_indention() const noexcept override { return false; } }; class Indenter_string final : public Indenter { private: cow_string m_add; cow_string m_cur; public: explicit Indenter_string(const cow_string& add) : m_add(add), m_cur(sref("\n")) { } public: tinyfmt& break_line(tinyfmt& fmt) const override { return fmt << this->m_cur; } void increment_level() override { this->m_cur.append(this->m_add); } void decrement_level() override { this->m_cur.pop_back(this->m_add.size()); } bool has_indention() const noexcept override { return this->m_add.size(); } }; class Indenter_spaces final : public Indenter { private: size_t m_add; size_t m_cur; public: explicit Indenter_spaces(int64_t add) : m_add(static_cast<size_t>(::rocket::clamp(add, 0, 10))), m_cur(0) { } public: tinyfmt& break_line(tinyfmt& fmt) const override { return fmt << pwrap(this->m_add, this->m_cur); } void increment_level() override { this->m_cur += this->m_add; } void decrement_level() override { this->m_cur -= this->m_add; } bool has_indention() const noexcept override { return this->m_add; } }; tinyfmt& do_quote_string(tinyfmt& fmt, const cow_string& str) { // Although JavaScript uses UCS-2 rather than UTF-16, the JSON specification adopts UTF-16. fmt << '\"'; size_t offset = 0; while(offset < str.size()) { // Convert UTF-8 to UTF-16. char32_t cp; if(!utf8_decode(cp, str, offset)) // Invalid UTF-8 code units are replaced with the replacement character. cp = 0xFFFD; // Escape double quotes, backslashes, and control characters. switch(cp) { case '\"': fmt << "\\\""; break; case '\\': fmt << "\\\\"; break; case '\b': fmt << "\\b"; break; case '\f': fmt << "\\f"; break; case '\n': fmt << "\\n"; break; case '\r': fmt << "\\r"; break; case '\t': fmt << "\\t"; break; default: { if((0x20 <= cp) && (cp <= 0x7E)) { // Write printable characters as is. fmt << static_cast<char>(cp); break; } // Encode the character in UTF-16. char16_t ustr[2]; char16_t* epos = ustr; utf16_encode(epos, cp); // Write code units. ::rocket::ascii_numput nump; for(auto p = ustr; p != epos; ++p) { nump.put_XU(*p, 4); char seq[8] = { "\\u" }; ::std::memcpy(seq + 2, nump.data() + 2, 4); fmt << sref(seq, 6); } break; } } } fmt << '\"'; return fmt; } tinyfmt& do_format_object_key(tinyfmt& fmt, bool json5, const Indenter& indent, const cow_string& name) { // Write the key. if(json5 && name.size() && is_cctype(name[0], cctype_namei) && ::std::all_of(name.begin() + 1, name.end(), [](char c) { return is_cctype(c, cctype_namei | cctype_digit); })) fmt << name; else do_quote_string(fmt, name); // Write the colon. if(indent.has_indention()) fmt << ": "; else fmt << ':'; return fmt; } bool do_find_uncensored(V_object::const_iterator& curp, const V_object& object) { for(;;) if(curp == object.end()) return false; else if(::rocket::is_any_of(curp->second.type(), { type_null, type_boolean, type_integer, type_real, type_string, type_array, type_object })) return true; else ++curp; } struct S_xformat_array { const V_array* refa; V_array::const_iterator curp; }; struct S_xformat_object { const V_object* refo; V_object::const_iterator curp; }; using Xformat = ::rocket::variant<S_xformat_array, S_xformat_object>; V_string do_format_nonrecursive(const Value& value, bool json5, Indenter& indent) { ::rocket::tinyfmt_str fmt; // Transform recursion to iteration using a handwritten stack. auto qval = &value; cow_vector<Xformat> stack; for(;;) { // Format a value. `qval` must always point to a valid value here. switch(weaken_enum(qval->type())) { case type_boolean: // Write `true` or `false`. fmt << qval->as_boolean(); break; case type_integer: // Write the integer in decimal. fmt << static_cast<double>(qval->as_integer()); break; case type_real: { double real = qval->as_real(); if(::std::isfinite(real)) { // Write the real in decimal. fmt << real; } else if(!json5) { // Censor the value. fmt << "null"; } else if(!::std::isnan(real)) { // JSON5 allows infinities in ECMAScript form. fmt << "Infinity"; } else { // JSON5 allows NaNs in ECMAScript form. fmt << "NaN"; } break; } case type_string: // Write the quoted string. do_quote_string(fmt, qval->as_string()); break; case type_array: { const auto& array = qval->as_array(); fmt << '['; // Open an array. S_xformat_array ctxa = { ::std::addressof(array), array.begin() }; if(ctxa.curp != array.end()) { indent.increment_level(); indent.break_line(fmt); // Descend into the array. qval = &(ctxa.curp[0]); stack.emplace_back(::std::move(ctxa)); continue; } // Write an empty array. fmt << ']'; break; } case type_object: { const auto& object = qval->as_object(); fmt << '{'; // Open an object. S_xformat_object ctxo = { ::std::addressof(object), object.begin() }; if(do_find_uncensored(ctxo.curp, object)) { indent.increment_level(); indent.break_line(fmt); // Write the key followed by a colon. do_format_object_key(fmt, json5, indent, ctxo.curp->first); // Descend into the object. qval = &(ctxo.curp->second); stack.emplace_back(::std::move(ctxo)); continue; } // Write an empty object. fmt << '}'; break; } default: // Anything else is censored to `null`. fmt << "null"; break; } // A complete value has been written. Advance to the next element if any. for(;;) { if(stack.empty()) // Finish the root value. return fmt.extract_string(); // Advance to the next element. if(stack.back().index() == 0) { auto& ctxa = stack.mut_back().as<0>(); if(++(ctxa.curp) != ctxa.refa->end()) { fmt << ','; indent.break_line(fmt); // Format the next element. qval = &(ctxa.curp[0]); break; } // Close this array. if(json5 && indent.has_indention()) fmt << ','; indent.decrement_level(); indent.break_line(fmt); fmt << ']'; } else { auto& ctxo = stack.mut_back().as<1>(); if(do_find_uncensored(++(ctxo.curp), *(ctxo.refo))) { fmt << ','; indent.break_line(fmt); // Write the key followed by a colon. do_format_object_key(fmt, json5, indent, ctxo.curp->first); // Format the next value. qval = &(ctxo.curp->second); break; } // Close this object. if(json5 && indent.has_indention()) fmt << ','; indent.decrement_level(); indent.break_line(fmt); fmt << '}'; } stack.pop_back(); } } } V_string do_format_nonrecursive(const Value& value, bool json5, Indenter&& indent) { return do_format_nonrecursive(value, json5, indent); } opt<Punctuator> do_accept_punctuator_opt(Token_Stream& tstrm, initializer_list<Punctuator> accept) { auto qtok = tstrm.peek_opt(); if(!qtok) return nullopt; if(!qtok->is_punctuator()) return nullopt; auto punct = qtok->as_punctuator(); if(::rocket::is_none_of(punct, accept)) return nullopt; tstrm.shift(); return punct; } phsh_string do_accept_object_key(Token_Stream& tstrm) { auto qtok = tstrm.peek_opt(); if(!qtok) throw Parser_Error(parser_status_closed_brace_or_json5_key_expected, tstrm); cow_string name; switch(weaken_enum(qtok->index())) { case Token::index_identifier: name = qtok->as_identifier(); break; case Token::index_string_literal: name = qtok->as_string_literal(); break; default: throw Parser_Error(parser_status_closed_brace_or_json5_key_expected, tstrm); } tstrm.shift(); auto kpunct = do_accept_punctuator_opt(tstrm, { punctuator_colon }); if(!kpunct) throw Parser_Error(parser_status_colon_expected, tstrm); return name; } struct S_xparse_array { V_array array; }; struct S_xparse_object { V_object object; phsh_string key; }; using Xparse = ::rocket::variant<S_xparse_array, S_xparse_object>; Value do_json_parse_nonrecursive(Token_Stream& tstrm) { Value value; // Implement a non-recursive descent parser. cow_vector<Xparse> stack; for(;;) { // Accept a value. No other things such as closed brackets are allowed. auto qtok = tstrm.peek_opt(); if(!qtok) throw Parser_Error(parser_status_expression_expected, tstrm); switch(weaken_enum(qtok->index())) { case Token::index_punctuator: { // Accept an `[` or `{`. auto punct = qtok->as_punctuator(); switch(weaken_enum(punct)) { case punctuator_bracket_op: { tstrm.shift(); // Open an array. auto kpunct = do_accept_punctuator_opt(tstrm, { punctuator_bracket_cl }); if(!kpunct) { // Descend into the new array. S_xparse_array ctxa = { V_array() }; stack.emplace_back(::std::move(ctxa)); continue; } // Accept an empty array. value = V_array(); break; } case punctuator_brace_op: { tstrm.shift(); // Open an object. auto kpunct = do_accept_punctuator_opt(tstrm, { punctuator_brace_cl }); if(!kpunct) { // Descend into the new object. S_xparse_object ctxo = { V_object(), do_accept_object_key(tstrm) }; stack.emplace_back(::std::move(ctxo)); continue; } // Accept an empty object. value = V_object(); break; } default: throw Parser_Error(parser_status_expression_expected, tstrm); } break; } case Token::index_identifier: { // Accept a literal. const auto& name = qtok->as_identifier(); if(::rocket::is_none_of(name, { "null", "true", "false", "Infinity", "NaN" })) throw Parser_Error(parser_status_expression_expected, tstrm); switch(name[0]) { case 'n': value = nullopt; break; case 't': value = true; break; case 'f': value = false; break; case 'I': value = ::std::numeric_limits<double>::infinity(); break; case 'N': value = ::std::numeric_limits<double>::quiet_NaN(); break; default: ROCKET_ASSERT(false); } tstrm.shift(); break; } case Token::index_real_literal: // Accept a number. value = qtok->as_real_literal(); tstrm.shift(); break; case Token::index_string_literal: // Accept a UTF-8 string. value = qtok->as_string_literal(); tstrm.shift(); break; default: throw Parser_Error(parser_status_expression_expected, tstrm); } // A complete value has been accepted. Insert it into its parent array or object. for(;;) { if(stack.empty()) // Accept the root value. return value; if(stack.back().index() == 0) { auto& ctxa = stack.mut_back().as<0>(); ctxa.array.emplace_back(::std::move(value)); // Look for the next element. auto kpunct = do_accept_punctuator_opt(tstrm, { punctuator_bracket_cl, punctuator_comma }); if(!kpunct) throw Parser_Error(parser_status_closed_bracket_or_comma_expected, tstrm); // Check for termination of this array. if(*kpunct != punctuator_bracket_cl) { kpunct = do_accept_punctuator_opt(tstrm, { punctuator_bracket_cl }); if(!kpunct) { // Look for the next element. break; } } // Close this array. value = ::std::move(ctxa.array); } else { auto& ctxo = stack.mut_back().as<1>(); ctxo.object.insert_or_assign(::std::move(ctxo.key), ::std::move(value)); // Look for the next element. auto kpunct = do_accept_punctuator_opt(tstrm, { punctuator_brace_cl, punctuator_comma }); if(!kpunct) throw Parser_Error(parser_status_closed_brace_or_comma_expected, tstrm); // Check for termination of this array. if(*kpunct != punctuator_brace_cl) { kpunct = do_accept_punctuator_opt(tstrm, { punctuator_brace_cl }); if(!kpunct) { // Look for the next element. ctxo.key = do_accept_object_key(tstrm); break; } } // Close this object. value = ::std::move(ctxo.object); } stack.pop_back(); } } } Value do_json_parse(tinybuf& cbuf) try { // We reuse the lexer of Asteria here, allowing quite a few extensions e.g. binary numeric // literals and comments. Compiler_Options opts; opts.escapable_single_quotes = true; opts.keywords_as_identifiers = true; opts.integers_as_reals = true; Token_Stream tstrm(opts); tstrm.reload(sref("[JSON text]"), 1, cbuf); if(tstrm.empty()) ASTERIA_THROW("Empty JSON string"); // Parse a single value. auto value = do_json_parse_nonrecursive(tstrm); if(!tstrm.empty()) ASTERIA_THROW("Excess text at end of JSON string"); return value; } catch(Parser_Error& except) { ASTERIA_THROW("Invalid JSON string: $3 (line $1, column $2)", except.line(), except.column(), describe_parser_status(except.status())); } } // namespace V_string std_json_format(Value value, Opt_string indent) { // No line break is inserted if `indent` is null or empty. return (!indent || indent->empty()) ? do_format_nonrecursive(value, false, Indenter_none()) : do_format_nonrecursive(value, false, Indenter_string(*indent)); } V_string std_json_format(Value value, V_integer indent) { // No line break is inserted if `indent` is non-positive. return (indent <= 0) ? do_format_nonrecursive(value, false, Indenter_none()) : do_format_nonrecursive(value, false, Indenter_spaces(indent)); } V_string std_json_format5(Value value, Opt_string indent) { // No line break is inserted if `indent` is null or empty. return (!indent || indent->empty()) ? do_format_nonrecursive(value, true, Indenter_none()) : do_format_nonrecursive(value, true, Indenter_string(*indent)); } V_string std_json_format5(Value value, V_integer indent) { // No line break is inserted if `indent` is non-positive. return (indent <= 0) ? do_format_nonrecursive(value, true, Indenter_none()) : do_format_nonrecursive(value, true, Indenter_spaces(indent)); } Value std_json_parse(V_string text) { // Parse characters from the string. ::rocket::tinybuf_str cbuf; cbuf.set_string(text, tinybuf::open_read); return do_json_parse(cbuf); } Value std_json_parse_file(V_string path) { // Try opening the file. ::rocket::unique_posix_file fp(::fopen(path.safe_c_str(), "rb"), ::fclose); if(!fp) ASTERIA_THROW("Could not open file '$2'\n" "[`fopen()` failed: $1]", format_errno(errno), path); // Parse characters from the file. ::setbuf(fp, nullptr); ::rocket::tinybuf_file cbuf(::std::move(fp)); return do_json_parse(cbuf); } void create_bindings_json(V_object& result, API_Version /*version*/) { result.insert_or_assign(sref("format"), ASTERIA_BINDING_BEGIN("std.json.format", self, global, reader) { Value value; Opt_string sind; V_integer iind; reader.start_overload(); reader.optional(value); // [value] reader.save_state(0); reader.optional(sind); // [indent] if(reader.end_overload()) ASTERIA_BINDING_RETURN_MOVE(self, std_json_format, value, sind); reader.load_state(0); // [value] reader.required(iind); // indent ASTERIA_BINDING_RETURN_MOVE(self, std_json_format, value, iind); } ASTERIA_BINDING_END); result.insert_or_assign(sref("format5"), ASTERIA_BINDING_BEGIN("std.json.format5", self, global, reader) { Value value; Opt_string sind; V_integer iind; reader.start_overload(); reader.optional(value); // [value] reader.save_state(0); reader.optional(sind); // [indent] if(reader.end_overload()) ASTERIA_BINDING_RETURN_MOVE(self, std_json_format5, value, sind); reader.load_state(0); // [value] reader.required(iind); // indent ASTERIA_BINDING_RETURN_MOVE(self, std_json_format5, value, iind); } ASTERIA_BINDING_END); result.insert_or_assign(sref("parse"), ASTERIA_BINDING_BEGIN("std.json.parse", self, global, reader) { V_string text; reader.start_overload(); reader.required(text); // text if(reader.end_overload()) ASTERIA_BINDING_RETURN_MOVE(self, std_json_parse, text); } ASTERIA_BINDING_END); result.insert_or_assign(sref("parse_file"), ASTERIA_BINDING_BEGIN("std.json.parse_file", self, global, reader) { V_string path; reader.start_overload(); reader.required(path); // path if(reader.end_overload()) ASTERIA_BINDING_RETURN_MOVE(self, std_json_parse_file, path); } ASTERIA_BINDING_END); } } // namespace asteria
25.637931
101
0.550966
usama-makhzoum
5864ca14de111e2a98dc80bcb8e458ae2ecfa65b
1,405
cc
C++
src/base/message_loop/timer_slack.cc
lazymartin/naiveproxy
696e8714278e85e67e56a2eaea11f26c53116f0c
[ "BSD-3-Clause" ]
2,219
2018-03-26T02:57:34.000Z
2022-03-31T00:27:59.000Z
src/base/message_loop/timer_slack.cc
uszhen/naiveproxy
0aa27e8bd37428f2124a891be1e5e793928cd726
[ "BSD-3-Clause" ]
250
2018-02-02T23:16:57.000Z
2022-03-21T06:09:53.000Z
src/base/message_loop/timer_slack.cc
uszhen/naiveproxy
0aa27e8bd37428f2124a891be1e5e793928cd726
[ "BSD-3-Clause" ]
473
2019-03-24T16:34:23.000Z
2022-03-31T02:01:05.000Z
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/message_loop/timer_slack.h" #include <atomic> #include "base/check_op.h" #include "base/feature_list.h" #include "base/metrics/field_trial_params.h" namespace base { namespace features { constexpr base::Feature kLudicrousTimerSlack{"LudicrousTimerSlack", base::FEATURE_DISABLED_BY_DEFAULT}; namespace { constexpr base::FeatureParam<base::TimeDelta> kSlackValueMs{ &kLudicrousTimerSlack, "slack_ms", // 1.5 seconds default slack for this ludicrous experiment. base::TimeDelta::FromMilliseconds(1500)}; } // namespace } // namespace features namespace { std::atomic<size_t> g_ludicrous_timer_suspend_count{0}; } // namespace bool IsLudicrousTimerSlackEnabled() { return base::FeatureList::IsEnabled(base::features::kLudicrousTimerSlack); } base::TimeDelta GetLudicrousTimerSlack() { return features::kSlackValueMs.Get(); } void SuspendLudicrousTimerSlack() { ++g_ludicrous_timer_suspend_count; } void ResumeLudicrousTimerSlack() { size_t old_count = g_ludicrous_timer_suspend_count.fetch_sub(1); DCHECK_LT(0u, old_count); } bool IsLudicrousTimerSlackSuspended() { return g_ludicrous_timer_suspend_count.load() > 0u; } } // namespace base
25.089286
80
0.745907
lazymartin
58678121a455e51d562ddd820e632fc544f9d61c
38,417
cpp
C++
sven_internal/config.cpp
revoiid/sven_internal
99c0e8148fd8cd44100d5c7730ebb1fc71b7f368
[ "MIT" ]
null
null
null
sven_internal/config.cpp
revoiid/sven_internal
99c0e8148fd8cd44100d5c7730ebb1fc71b7f368
[ "MIT" ]
null
null
null
sven_internal/config.cpp
revoiid/sven_internal
99c0e8148fd8cd44100d5c7730ebb1fc71b7f368
[ "MIT" ]
null
null
null
// Config #include "config.h" #include "../ini-parser/ini_parser.h" #include "../features/skybox.h" #include "../utils/styles.h" #include "../interfaces.h" #include <stdio.h> #include <stdlib.h> #include <type_traits> //----------------------------------------------------------------------------- // Make import/export easier //----------------------------------------------------------------------------- template <class T> constexpr const char *ini_get_format_specifier(T var) { if (std::is_same_v<T, int> || std::is_same_v<T, bool>) return "%s = %d\n"; if (std::is_same_v<T, float>) return "%s = %.3f\n"; if (std::is_same_v<T, DWORD>) return "%s = %X\n"; } template <class T> constexpr ini_field_type_t ini_get_fieldtype(T var) { if (std::is_same_v<T, bool>) return INI_FIELD_BOOL; else if (std::is_same_v<T, int>) return INI_FIELD_INTEGER; else if (std::is_same_v<T, float>) return INI_FIELD_FLOAT; else if (std::is_same_v<T, DWORD>) return INI_FIELD_UINT32; } template <class T> constexpr void ini_get_datatype(T &var, ini_datatype &datatype) { #pragma warning(push) #pragma warning(disable: 4244) if (std::is_same_v<T, bool>) var = datatype.m_bool; else if (std::is_same_v<T, int>) var = datatype.m_int; else if (std::is_same_v<T, float>) var = datatype.m_float; else if (std::is_same_v<T, DWORD>) var = datatype.m_uint32; #pragma warning(pop) } #define INI_EXPORT_BEGIN() FILE *file = fopen("sven_internal/sven_internal.ini", "w"); if (file) { #define INI_EXPORT_END() fclose(file); } #define INI_EXPORT_BEGIN_SECTION(section) fprintf(file, "[" section "]\n") #define INI_EXPORT_END_SECTION() fprintf(file, "\n") #define INI_EXPORT_VARIABLE(name, var) fprintf(file, ini_get_format_specifier(var), name, var) #define INI_IMPORT_BEGIN() const char *pszSection = NULL; ini_datatype datatype; ini_data *data = (ini_data *)calloc(sizeof(ini_data), 1) #define INI_IMPORT_END() ini_free_data(data, 1); return true #define INI_IMPORT_BEGIN_SECTION(section) pszSection = section #define INI_IMPORT_END_SECTION() #define INI_IMPORT_VARIABLE_SET_RADIX(_radix) datatype.radix = _radix #define INI_IMPORT_VARIABLE(name, var) \ if (ini_read_data(data, pszSection, name, &datatype, ini_get_fieldtype(var))) \ ini_get_datatype(var, datatype) #define INI_IMPORT_PARSE_DATA() \ if (!ini_parse_data("sven_internal/sven_internal.ini", data)) \ { \ if (ini_get_last_error() == INI_MISSING_FILE) \ g_pEngineFuncs->Con_Printf("Failed to parse the config file: Missing file sven_internal/sven_internal.ini to parse\n"); \ else \ g_pEngineFuncs->Con_Printf("Failed to parse the config file: Syntax error: %s in line %d\n", ini_get_last_error_msg(), ini_get_last_line()); \ \ ini_free_data(data, 1); \ return false; \ } //----------------------------------------------------------------------------- // Vars //----------------------------------------------------------------------------- CConfig g_Config; //----------------------------------------------------------------------------- // Implementations //----------------------------------------------------------------------------- bool CConfig::Load() { INI_IMPORT_BEGIN(); INI_IMPORT_PARSE_DATA(); INI_IMPORT_BEGIN_SECTION("SETTINGS"); INI_IMPORT_VARIABLE_SET_RADIX(16); INI_IMPORT_VARIABLE("ToggleButton", dwToggleButton); INI_IMPORT_VARIABLE("AutoResize", ImGuiAutoResize); INI_IMPORT_VARIABLE("Theme", theme); INI_IMPORT_VARIABLE("Opacity", opacity); INI_IMPORT_END_SECTION(); INI_IMPORT_BEGIN_SECTION("ESP"); INI_IMPORT_VARIABLE("Enable", cvars.esp); INI_IMPORT_VARIABLE("Distance", cvars.esp_distance); INI_IMPORT_VARIABLE("Box", cvars.esp_box); INI_IMPORT_VARIABLE("Outline", cvars.esp_box_outline); INI_IMPORT_VARIABLE("Fill", cvars.esp_box_fill); INI_IMPORT_VARIABLE("ShowIndex", cvars.esp_box_index); INI_IMPORT_VARIABLE("ShowDistance", cvars.esp_box_distance); INI_IMPORT_VARIABLE("ShowPlayerHealth", cvars.esp_box_player_health); INI_IMPORT_VARIABLE("ShowPlayerArmor", cvars.esp_box_player_armor); INI_IMPORT_VARIABLE("ShowEntityName", cvars.esp_box_entity_name); INI_IMPORT_VARIABLE("ShowPlayerName", cvars.esp_box_player_name); INI_IMPORT_VARIABLE("ShowItems", cvars.esp_show_items); INI_IMPORT_VARIABLE("IgnoreUnknownEnts", cvars.esp_ignore_unknown_ents); INI_IMPORT_VARIABLE("Targets", cvars.esp_targets); INI_IMPORT_VARIABLE("ShowSkeleton", cvars.esp_skeleton); INI_IMPORT_VARIABLE("ShowBonesName", cvars.esp_bones_name); INI_IMPORT_VARIABLE("ShowSkeletonType", cvars.esp_skeleton_type); INI_IMPORT_VARIABLE("FriendColor_R", cvars.esp_friend_color[0]); INI_IMPORT_VARIABLE("FriendColor_G", cvars.esp_friend_color[1]); INI_IMPORT_VARIABLE("FriendColor_B", cvars.esp_friend_color[2]); INI_IMPORT_VARIABLE("EnemyColor_R", cvars.esp_enemy_color[0]); INI_IMPORT_VARIABLE("EnemyColor_G", cvars.esp_enemy_color[1]); INI_IMPORT_VARIABLE("EnemyColor_B", cvars.esp_enemy_color[2]); INI_IMPORT_VARIABLE("NeutralColor_R", cvars.esp_neutral_color[0]); INI_IMPORT_VARIABLE("NeutralColor_G", cvars.esp_neutral_color[1]); INI_IMPORT_VARIABLE("NeutralColor_B", cvars.esp_neutral_color[2]); INI_IMPORT_VARIABLE("ItemColor_R", cvars.esp_item_color[0]); INI_IMPORT_VARIABLE("ItemColor_G", cvars.esp_item_color[1]); INI_IMPORT_VARIABLE("ItemColor_B", cvars.esp_item_color[2]); INI_IMPORT_END_SECTION(); INI_IMPORT_BEGIN_SECTION("WALLHACK"); INI_IMPORT_VARIABLE("Wallhack", cvars.wallhack); INI_IMPORT_VARIABLE("Negative", cvars.wallhack_negative); INI_IMPORT_VARIABLE("WhiteWalls", cvars.wallhack_white_walls); INI_IMPORT_VARIABLE("Wireframe", cvars.wallhack_wireframe); INI_IMPORT_VARIABLE("WireframeModels", cvars.wallhack_wireframe_models); INI_IMPORT_VARIABLE("Wireframe_Width", cvars.wh_wireframe_width); INI_IMPORT_VARIABLE("Wireframe_R", cvars.wh_wireframe_color[0]); INI_IMPORT_VARIABLE("Wireframe_G", cvars.wh_wireframe_color[2]); INI_IMPORT_VARIABLE("Wireframe_B", cvars.wh_wireframe_color[1]); INI_IMPORT_END_SECTION(); INI_IMPORT_BEGIN_SECTION("CROSSHAIR"); INI_IMPORT_VARIABLE("Enable", cvars.draw_crosshair); INI_IMPORT_VARIABLE("EnableDot", cvars.draw_crosshair_dot); INI_IMPORT_VARIABLE("EnableOutline", cvars.draw_crosshair_outline); INI_IMPORT_VARIABLE("Size", cvars.crosshair_size); INI_IMPORT_VARIABLE("Gap", cvars.crosshair_gap); INI_IMPORT_VARIABLE("Thickness", cvars.crosshair_thickness); INI_IMPORT_VARIABLE("OutlineThickness", cvars.crosshair_outline_thickness); INI_IMPORT_VARIABLE("OutlineColor_R", cvars.crosshair_outline_color[0]); INI_IMPORT_VARIABLE("OutlineColor_G", cvars.crosshair_outline_color[1]); INI_IMPORT_VARIABLE("OutlineColor_B", cvars.crosshair_outline_color[2]); INI_IMPORT_VARIABLE("OutlineColor_A", cvars.crosshair_outline_color[3]); INI_IMPORT_VARIABLE("Color_R", cvars.crosshair_color[0]); INI_IMPORT_VARIABLE("Color_G", cvars.crosshair_color[1]); INI_IMPORT_VARIABLE("Color_B", cvars.crosshair_color[2]); INI_IMPORT_VARIABLE("Color_A", cvars.crosshair_color[3]); INI_IMPORT_END_SECTION(); INI_IMPORT_BEGIN_SECTION("VISUAL"); INI_IMPORT_VARIABLE("NoShake", cvars.no_shake); INI_IMPORT_VARIABLE("NoFade", cvars.no_fade); INI_IMPORT_VARIABLE("DrawEntities", cvars.draw_entities); INI_IMPORT_VARIABLE("ShowSpeed", cvars.show_speed); INI_IMPORT_VARIABLE("StoreVerticalSpeed", cvars.show_vertical_speed); INI_IMPORT_VARIABLE("SpeedWidthFraction", cvars.speed_width_fraction); INI_IMPORT_VARIABLE("SpeedHeightFraction", cvars.speed_height_fraction); INI_IMPORT_VARIABLE("Speed_R", cvars.speed_color[0]); INI_IMPORT_VARIABLE("Speed_G", cvars.speed_color[1]); INI_IMPORT_VARIABLE("Speed_B", cvars.speed_color[2]); INI_IMPORT_VARIABLE("Speed_A", cvars.speed_color[3]); INI_IMPORT_VARIABLE("LightmapOverride", cvars.lightmap_override); INI_IMPORT_VARIABLE("LightmapOverrideBrightness", cvars.lightmap_brightness); INI_IMPORT_VARIABLE("LightmapOverride_R", cvars.lightmap_color[0]); INI_IMPORT_VARIABLE("LightmapOverride_G", cvars.lightmap_color[1]); INI_IMPORT_VARIABLE("LightmapOverride_B", cvars.lightmap_color[2]); INI_IMPORT_VARIABLE("ShowPlayersPushDirection", cvars.show_players_push_direction); INI_IMPORT_VARIABLE("PushDirectionLength", cvars.push_direction_length); INI_IMPORT_VARIABLE("PushDirectionWidth", cvars.push_direction_width); INI_IMPORT_VARIABLE("PushDirectionColor_R", cvars.push_direction_color[0]); INI_IMPORT_VARIABLE("PushDirectionColor_G", cvars.push_direction_color[1]); INI_IMPORT_VARIABLE("PushDirectionColor_B", cvars.push_direction_color[2]); INI_IMPORT_END_SECTION(); INI_IMPORT_BEGIN_SECTION("CHAMS"); INI_IMPORT_VARIABLE("Enable", cvars.chams); INI_IMPORT_VARIABLE("ChamsPlayers", cvars.chams_players); INI_IMPORT_VARIABLE("ChamsEntities", cvars.chams_entities); INI_IMPORT_VARIABLE("ChamsItems", cvars.chams_items); INI_IMPORT_VARIABLE("ChamsPlayersWall", cvars.chams_players_wall); INI_IMPORT_VARIABLE("ChamsEntitiesWall", cvars.chams_entities_wall); INI_IMPORT_VARIABLE("ChamsItemsWall", cvars.chams_items_wall); INI_IMPORT_VARIABLE("ChamsPlayersColor_R", cvars.chams_players_color[0]); INI_IMPORT_VARIABLE("ChamsPlayersColor_G", cvars.chams_players_color[1]); INI_IMPORT_VARIABLE("ChamsPlayersColor_B", cvars.chams_players_color[2]); INI_IMPORT_VARIABLE("ChamsEntitiesColor_R", cvars.chams_entities_color[0]); INI_IMPORT_VARIABLE("ChamsEntitiesColor_G", cvars.chams_entities_color[1]); INI_IMPORT_VARIABLE("ChamsEntitiesColor_B", cvars.chams_entities_color[2]); INI_IMPORT_VARIABLE("ChamsItemsColor_R", cvars.chams_items_color[0]); INI_IMPORT_VARIABLE("ChamsItemsColor_G", cvars.chams_items_color[1]); INI_IMPORT_VARIABLE("ChamsItemsColor_B", cvars.chams_items_color[2]); INI_IMPORT_VARIABLE("ChamsPlayersWallColor_R", cvars.chams_players_wall_color[0]); INI_IMPORT_VARIABLE("ChamsPlayersWallColor_G", cvars.chams_players_wall_color[1]); INI_IMPORT_VARIABLE("ChamsPlayersWallColor_B", cvars.chams_players_wall_color[2]); INI_IMPORT_VARIABLE("ChamsEntitiesWallColor_R", cvars.chams_entities_wall_color[0]); INI_IMPORT_VARIABLE("ChamsEntitiesWallColor_G", cvars.chams_entities_wall_color[1]); INI_IMPORT_VARIABLE("ChamsEntitiesWallColor_B", cvars.chams_entities_wall_color[2]); INI_IMPORT_VARIABLE("ChamsItemsWallColor_R", cvars.chams_items_wall_color[0]); INI_IMPORT_VARIABLE("ChamsItemsWallColor_G", cvars.chams_items_wall_color[1]); INI_IMPORT_VARIABLE("ChamsItemsWallColor_B", cvars.chams_items_wall_color[2]); INI_IMPORT_END_SECTION(); INI_IMPORT_BEGIN_SECTION("GLOW"); INI_IMPORT_VARIABLE("Enable", cvars.glow); INI_IMPORT_VARIABLE("Optimize", cvars.glow_optimize); INI_IMPORT_VARIABLE("GlowPlayers", cvars.glow_players); INI_IMPORT_VARIABLE("GlowEntities", cvars.glow_entities); INI_IMPORT_VARIABLE("GlowItems", cvars.glow_items); INI_IMPORT_VARIABLE("GlowPlayersWidth", cvars.glow_players_width); INI_IMPORT_VARIABLE("GlowEntitiesWidth", cvars.glow_entities_width); INI_IMPORT_VARIABLE("GlowItemsWidth", cvars.glow_items_width); INI_IMPORT_VARIABLE("GlowPlayersWall", cvars.glow_players_wall); INI_IMPORT_VARIABLE("GlowEntitiesWall", cvars.glow_entities_wall); INI_IMPORT_VARIABLE("GlowItemsWall", cvars.glow_items_wall); INI_IMPORT_VARIABLE("GlowPlayersColor_R", cvars.glow_players_color[0]); INI_IMPORT_VARIABLE("GlowPlayersColor_G", cvars.glow_players_color[1]); INI_IMPORT_VARIABLE("GlowPlayersColor_B", cvars.glow_players_color[2]); INI_IMPORT_VARIABLE("GlowEntitiesColor_R", cvars.glow_entities_color[0]); INI_IMPORT_VARIABLE("GlowEntitiesColor_G", cvars.glow_entities_color[1]); INI_IMPORT_VARIABLE("GlowEntitiesColor_B", cvars.glow_entities_color[2]); INI_IMPORT_VARIABLE("GlowItemsColor_R", cvars.glow_items_color[0]); INI_IMPORT_VARIABLE("GlowItemsColor_G", cvars.glow_items_color[1]); INI_IMPORT_VARIABLE("GlowItemsColor_B", cvars.glow_items_color[2]); INI_IMPORT_END_SECTION(); INI_IMPORT_BEGIN_SECTION("DYNAMICGLOW"); INI_IMPORT_VARIABLE("GlowAttach", cvars.dyn_glow_attach); INI_IMPORT_VARIABLE("GlowSelf", cvars.dyn_glow_self); INI_IMPORT_VARIABLE("GlowSelfRadius", cvars.dyn_glow_self_radius); INI_IMPORT_VARIABLE("GlowSelfDecay", cvars.dyn_glow_self_decay); INI_IMPORT_VARIABLE("GlowSelfColor_R", cvars.dyn_glow_self_color[0]); INI_IMPORT_VARIABLE("GlowSelfColor_G", cvars.dyn_glow_self_color[1]); INI_IMPORT_VARIABLE("GlowSelfColor_B", cvars.dyn_glow_self_color[2]); INI_IMPORT_VARIABLE("GlowPlayers", cvars.dyn_glow_players); INI_IMPORT_VARIABLE("GlowPlayersRadius", cvars.dyn_glow_players_radius); INI_IMPORT_VARIABLE("GlowPlayersDecay", cvars.dyn_glow_players_decay); INI_IMPORT_VARIABLE("GlowPlayersColor_R", cvars.dyn_glow_players_color[0]); INI_IMPORT_VARIABLE("GlowPlayersColor_G", cvars.dyn_glow_players_color[1]); INI_IMPORT_VARIABLE("GlowPlayersColor_B", cvars.dyn_glow_players_color[2]); INI_IMPORT_VARIABLE("GlowEntities", cvars.dyn_glow_entities); INI_IMPORT_VARIABLE("GlowEntitiesRadius", cvars.dyn_glow_entities_radius); INI_IMPORT_VARIABLE("GlowEntitiesDecay", cvars.dyn_glow_entities_decay); INI_IMPORT_VARIABLE("GlowEntitiesColor_R", cvars.dyn_glow_entities_color[0]); INI_IMPORT_VARIABLE("GlowEntitiesColor_G", cvars.dyn_glow_entities_color[1]); INI_IMPORT_VARIABLE("GlowEntitiesColor_B", cvars.dyn_glow_entities_color[2]); INI_IMPORT_VARIABLE("GlowItems", cvars.dyn_glow_items); INI_IMPORT_VARIABLE("GlowItemsRadius", cvars.dyn_glow_items_radius); INI_IMPORT_VARIABLE("GlowItemsDecay", cvars.dyn_glow_items_decay); INI_IMPORT_VARIABLE("GlowItemsColor_R", cvars.dyn_glow_items_color[0]); INI_IMPORT_VARIABLE("GlowItemsColor_G", cvars.dyn_glow_items_color[1]); INI_IMPORT_VARIABLE("GlowItemsColor_B", cvars.dyn_glow_items_color[2]); INI_IMPORT_END_SECTION(); INI_IMPORT_BEGIN_SECTION("STRAFE"); INI_IMPORT_VARIABLE("Enable", cvars.strafe); INI_IMPORT_VARIABLE("IgnoreGround", cvars.strafe_ignore_ground); INI_IMPORT_VARIABLE("Direction", cvars.strafe_dir); INI_IMPORT_VARIABLE("Type", cvars.strafe_type); INI_IMPORT_END_SECTION(); INI_IMPORT_BEGIN_SECTION("FAKELAG"); INI_IMPORT_VARIABLE("Enable", cvars.fakelag); INI_IMPORT_VARIABLE("AdaptiveInterp", cvars.fakelag_adaptive_ex_interp); INI_IMPORT_VARIABLE("Type", cvars.fakelag_type); INI_IMPORT_VARIABLE("Move", cvars.fakelag_move); INI_IMPORT_VARIABLE("Limit", cvars.fakelag_limit); INI_IMPORT_VARIABLE("Variance", cvars.fakelag_variance); INI_IMPORT_END_SECTION(); INI_IMPORT_BEGIN_SECTION("ANTIAFK"); INI_IMPORT_VARIABLE("Type", cvars.antiafk); INI_IMPORT_VARIABLE("RotateCamera", cvars.antiafk_rotate_camera); INI_IMPORT_VARIABLE("StayWithinRange", cvars.antiafk_stay_within_range); INI_IMPORT_VARIABLE("ResetStayPos", cvars.antiafk_reset_stay_pos); INI_IMPORT_VARIABLE("RotationAngle", cvars.antiafk_rotation_angle); INI_IMPORT_VARIABLE("StayRadius", cvars.antiafk_stay_radius); INI_IMPORT_VARIABLE("StayRadiusOffsetAngle", cvars.antiafk_stay_radius_offset_angle); INI_IMPORT_END_SECTION(); INI_IMPORT_BEGIN_SECTION("MISC"); INI_IMPORT_VARIABLE("AutoJump", cvars.autojump); INI_IMPORT_VARIABLE("JumpBug", cvars.jumpbug); INI_IMPORT_VARIABLE("DoubleDuck", cvars.doubleduck); INI_IMPORT_VARIABLE("FastRun", cvars.fastrun); INI_IMPORT_VARIABLE("QuakeGuns", cvars.quake_guns); INI_IMPORT_VARIABLE("TertiaryAttackGlitch", cvars.tertiary_attack_glitch); INI_IMPORT_VARIABLE("SaveSoundcache", cvars.save_soundcache); INI_IMPORT_VARIABLE("RotateDeadBody", cvars.rotate_dead_body); INI_IMPORT_VARIABLE("RemoveFOVCap", cvars.remove_fov_cap); INI_IMPORT_VARIABLE("NoWeaponAnim", cvars.no_weapon_anim); INI_IMPORT_VARIABLE("ColorPulsator", cvars.color_pulsator); INI_IMPORT_VARIABLE("ColorPulsatorTop", cvars.color_pulsator_top); INI_IMPORT_VARIABLE("ColorPulsatorBottom", cvars.color_pulsator_bottom); INI_IMPORT_VARIABLE("ColorPulsatorDelay", cvars.color_pulsator_delay); INI_IMPORT_VARIABLE("LockPitch", cvars.lock_pitch); INI_IMPORT_VARIABLE("LockYaw", cvars.lock_yaw); INI_IMPORT_VARIABLE("LockPitchAngle", cvars.lock_pitch_angle); INI_IMPORT_VARIABLE("LockYawAngle", cvars.lock_yaw_angle); INI_IMPORT_VARIABLE("SpinYaw", cvars.spin_yaw_angle); INI_IMPORT_VARIABLE("SpinPitch", cvars.spin_pitch_angle); INI_IMPORT_VARIABLE("SpinYawAngle", cvars.spin_yaw_rotation_angle); INI_IMPORT_VARIABLE("SpinPitchAngle", cvars.spin_pitch_rotation_angle); INI_IMPORT_VARIABLE("ApplicationSpeed", cvars.application_speed); INI_IMPORT_END_SECTION(); INI_IMPORT_BEGIN_SECTION("KEYSPAM"); INI_IMPORT_VARIABLE("HoldMode", cvars.keyspam_hold_mode); INI_IMPORT_VARIABLE("Spam_E", cvars.keyspam_e); INI_IMPORT_VARIABLE("Spam_W", cvars.keyspam_w); INI_IMPORT_VARIABLE("Spam_S", cvars.keyspam_s); INI_IMPORT_VARIABLE("Spam_Q", cvars.keyspam_q); INI_IMPORT_VARIABLE("Spam_CTRL", cvars.keyspam_ctrl); INI_IMPORT_END_SECTION(); INI_IMPORT_BEGIN_SECTION("FOG"); INI_IMPORT_VARIABLE("Enable", cvars.fog); INI_IMPORT_VARIABLE("FogSkybox", cvars.fog_skybox); INI_IMPORT_VARIABLE("RemoveInWater", cvars.remove_water_fog); INI_IMPORT_VARIABLE("Start", cvars.fog_start); INI_IMPORT_VARIABLE("End", cvars.fog_end); INI_IMPORT_VARIABLE("Density", cvars.fog_density); INI_IMPORT_VARIABLE("Fog_R", cvars.fog_color[0]); INI_IMPORT_VARIABLE("Fog_G", cvars.fog_color[1]); INI_IMPORT_VARIABLE("Fog_B", cvars.fog_color[2]); INI_IMPORT_END_SECTION(); INI_IMPORT_BEGIN_SECTION("SKYBOX"); INI_IMPORT_VARIABLE("Type", cvars.skybox); INI_IMPORT_END_SECTION(); INI_IMPORT_BEGIN_SECTION("CHATCOLORS"); INI_IMPORT_VARIABLE("Enable", cvars.enable_chat_colors); INI_IMPORT_VARIABLE("PlayerName_R", cvars.player_name_color[0]); INI_IMPORT_VARIABLE("PlayerName_G", cvars.player_name_color[1]); INI_IMPORT_VARIABLE("PlayerName_B", cvars.player_name_color[2]); INI_IMPORT_VARIABLE("RainbowUpdateDelay", cvars.chat_rainbow_update_delay); INI_IMPORT_VARIABLE("RainbowHueDelta", cvars.chat_rainbow_hue_delta); INI_IMPORT_VARIABLE("RainbowSaturation", cvars.chat_rainbow_saturation); INI_IMPORT_VARIABLE("RainbowLightness", cvars.chat_rainbow_lightness); INI_IMPORT_VARIABLE("ColorOne_R", cvars.chat_color_one[0]); INI_IMPORT_VARIABLE("ColorOne_G", cvars.chat_color_one[1]); INI_IMPORT_VARIABLE("ColorOne_B", cvars.chat_color_one[2]); INI_IMPORT_VARIABLE("ColorTwo_R", cvars.chat_color_two[0]); INI_IMPORT_VARIABLE("ColorTwo_G", cvars.chat_color_two[1]); INI_IMPORT_VARIABLE("ColorTwo_B", cvars.chat_color_two[2]); INI_IMPORT_VARIABLE("ColorThree_R", cvars.chat_color_three[0]); INI_IMPORT_VARIABLE("ColorThree_G", cvars.chat_color_three[1]); INI_IMPORT_VARIABLE("ColorThree_B", cvars.chat_color_three[2]); INI_IMPORT_VARIABLE("ColorFour_R", cvars.chat_color_four[0]); INI_IMPORT_VARIABLE("ColorFour_G", cvars.chat_color_four[1]); INI_IMPORT_VARIABLE("ColorFour_B", cvars.chat_color_four[2]); INI_IMPORT_VARIABLE("ColorFive_R", cvars.chat_color_five[0]); INI_IMPORT_VARIABLE("ColorFive_G", cvars.chat_color_five[1]); INI_IMPORT_VARIABLE("ColorFive_B", cvars.chat_color_five[2]); INI_IMPORT_VARIABLE("ColorSix_R", cvars.chat_color_six[0]); INI_IMPORT_VARIABLE("ColorSix_G", cvars.chat_color_six[1]); INI_IMPORT_VARIABLE("ColorSix_B", cvars.chat_color_six[2]); INI_IMPORT_END_SECTION(); INI_IMPORT_BEGIN_SECTION("CAMHACK"); INI_IMPORT_VARIABLE("SpeedFactor", cvars.camhack_speed_factor); INI_IMPORT_VARIABLE("ShowModel", cvars.camhack_show_model); INI_IMPORT_END_SECTION(); INI_IMPORT_BEGIN_SECTION("FPROAMING"); INI_IMPORT_VARIABLE("Enable", cvars.fp_roaming); INI_IMPORT_VARIABLE("Crosshair", cvars.fp_roaming_draw_crosshair); INI_IMPORT_VARIABLE("Lerp", cvars.fp_roaming_lerp); INI_IMPORT_VARIABLE("LerpValue", cvars.fp_roaming_lerp_value); INI_IMPORT_END_SECTION(); INI_IMPORT_BEGIN_SECTION("VOTEPOPUP"); INI_IMPORT_VARIABLE("Enable", cvars.vote_popup); INI_IMPORT_VARIABLE("WidthSize", cvars.vote_popup_width_size); INI_IMPORT_VARIABLE("HeightSize", cvars.vote_popup_height_size); INI_IMPORT_VARIABLE("WidthBorderPixels", cvars.vote_popup_w_border_pix); INI_IMPORT_VARIABLE("HeightBorderPixels", cvars.vote_popup_h_border_pix); INI_IMPORT_VARIABLE("WidthFraction", cvars.vote_popup_width_frac); INI_IMPORT_VARIABLE("HeightFraction", cvars.vote_popup_height_frac); INI_IMPORT_END_SECTION(); //INI_IMPORT_BEGIN_SECTION("AUTOVOTE"); // INI_IMPORT_VARIABLE("Mode", cvars.autovote_mode); // INI_IMPORT_VARIABLE("UseOnCustomVotes", cvars.autovote_custom); // INI_IMPORT_VARIABLE("IgnoreVoteFilter", cvars.autovote_ignore_filter); //INI_IMPORT_END_SECTION(); INI_IMPORT_BEGIN_SECTION("AMS"); INI_IMPORT_VARIABLE("MuteEverything", cvars.ams_mute_everything); INI_IMPORT_END_SECTION(); // Callbacks g_Skybox.OnConfigLoad(); INI_IMPORT_END(); } void CConfig::Save() { INI_EXPORT_BEGIN() INI_EXPORT_BEGIN_SECTION("SETTINGS"); INI_EXPORT_VARIABLE("ToggleButton", dwToggleButton); INI_EXPORT_VARIABLE("AutoResize", ImGuiAutoResize); INI_EXPORT_VARIABLE("Theme", theme); INI_EXPORT_VARIABLE("Opacity", opacity); INI_EXPORT_END_SECTION(); INI_EXPORT_BEGIN_SECTION("ESP"); INI_EXPORT_VARIABLE("Enable", cvars.esp); INI_EXPORT_VARIABLE("Distance", cvars.esp_distance); INI_EXPORT_VARIABLE("Box", cvars.esp_box); INI_EXPORT_VARIABLE("Outline", cvars.esp_box_outline); INI_EXPORT_VARIABLE("Fill", cvars.esp_box_fill); INI_EXPORT_VARIABLE("ShowIndex", cvars.esp_box_index); INI_EXPORT_VARIABLE("ShowDistance", cvars.esp_box_distance); INI_EXPORT_VARIABLE("ShowPlayerHealth", cvars.esp_box_player_health); INI_EXPORT_VARIABLE("ShowPlayerArmor", cvars.esp_box_player_armor); INI_EXPORT_VARIABLE("ShowEntityName", cvars.esp_box_entity_name); INI_EXPORT_VARIABLE("ShowPlayerName", cvars.esp_box_player_name); INI_EXPORT_VARIABLE("ShowItems", cvars.esp_show_items); INI_EXPORT_VARIABLE("IgnoreUnknownEnts", cvars.esp_ignore_unknown_ents); INI_EXPORT_VARIABLE("Targets", cvars.esp_targets); INI_EXPORT_VARIABLE("ShowSkeleton", cvars.esp_skeleton); INI_EXPORT_VARIABLE("ShowBonesName", cvars.esp_bones_name); INI_EXPORT_VARIABLE("ShowSkeletonType", cvars.esp_skeleton_type); INI_EXPORT_VARIABLE("FriendColor_R", cvars.esp_friend_color[0]); INI_EXPORT_VARIABLE("FriendColor_G", cvars.esp_friend_color[1]); INI_EXPORT_VARIABLE("FriendColor_B", cvars.esp_friend_color[2]); INI_EXPORT_VARIABLE("EnemyColor_R", cvars.esp_enemy_color[0]); INI_EXPORT_VARIABLE("EnemyColor_G", cvars.esp_enemy_color[1]); INI_EXPORT_VARIABLE("EnemyColor_B", cvars.esp_enemy_color[2]); INI_EXPORT_VARIABLE("NeutralColor_R", cvars.esp_neutral_color[0]); INI_EXPORT_VARIABLE("NeutralColor_G", cvars.esp_neutral_color[1]); INI_EXPORT_VARIABLE("NeutralColor_B", cvars.esp_neutral_color[2]); INI_EXPORT_VARIABLE("ItemColor_R", cvars.esp_item_color[0]); INI_EXPORT_VARIABLE("ItemColor_G", cvars.esp_item_color[1]); INI_EXPORT_VARIABLE("ItemColor_B", cvars.esp_item_color[2]); INI_EXPORT_END_SECTION(); INI_EXPORT_BEGIN_SECTION("WALLHACK"); INI_EXPORT_VARIABLE("Wallhack", cvars.wallhack); INI_EXPORT_VARIABLE("Negative", cvars.wallhack_negative); INI_EXPORT_VARIABLE("WhiteWalls", cvars.wallhack_white_walls); INI_EXPORT_VARIABLE("Wireframe", cvars.wallhack_wireframe); INI_EXPORT_VARIABLE("WireframeModels", cvars.wallhack_wireframe_models); INI_EXPORT_VARIABLE("Wireframe_Width", cvars.wh_wireframe_width); INI_EXPORT_VARIABLE("Wireframe_R", cvars.wh_wireframe_color[0]); INI_EXPORT_VARIABLE("Wireframe_G", cvars.wh_wireframe_color[2]); INI_EXPORT_VARIABLE("Wireframe_B", cvars.wh_wireframe_color[1]); INI_EXPORT_END_SECTION(); INI_EXPORT_BEGIN_SECTION("CROSSHAIR"); INI_EXPORT_VARIABLE("Enable", cvars.draw_crosshair); INI_EXPORT_VARIABLE("EnableDot", cvars.draw_crosshair_dot); INI_EXPORT_VARIABLE("EnableOutline", cvars.draw_crosshair_outline); INI_EXPORT_VARIABLE("Size", cvars.crosshair_size); INI_EXPORT_VARIABLE("Gap", cvars.crosshair_gap); INI_EXPORT_VARIABLE("Thickness", cvars.crosshair_thickness); INI_EXPORT_VARIABLE("OutlineThickness", cvars.crosshair_outline_thickness); INI_EXPORT_VARIABLE("OutlineColor_R", cvars.crosshair_outline_color[0]); INI_EXPORT_VARIABLE("OutlineColor_G", cvars.crosshair_outline_color[1]); INI_EXPORT_VARIABLE("OutlineColor_B", cvars.crosshair_outline_color[2]); INI_EXPORT_VARIABLE("OutlineColor_A", cvars.crosshair_outline_color[3]); INI_EXPORT_VARIABLE("Color_R", cvars.crosshair_color[0]); INI_EXPORT_VARIABLE("Color_G", cvars.crosshair_color[1]); INI_EXPORT_VARIABLE("Color_B", cvars.crosshair_color[2]); INI_EXPORT_VARIABLE("Color_A", cvars.crosshair_color[3]); INI_EXPORT_END_SECTION(); INI_EXPORT_BEGIN_SECTION("VISUAL"); INI_EXPORT_VARIABLE("NoShake", cvars.no_shake); INI_EXPORT_VARIABLE("NoFade", cvars.no_fade); INI_EXPORT_VARIABLE("DrawEntities", cvars.draw_entities); INI_EXPORT_VARIABLE("ShowSpeed", cvars.show_speed); INI_EXPORT_VARIABLE("StoreVerticalSpeed", cvars.show_vertical_speed); INI_EXPORT_VARIABLE("SpeedWidthFraction", cvars.speed_width_fraction); INI_EXPORT_VARIABLE("SpeedHeightFraction", cvars.speed_height_fraction); INI_EXPORT_VARIABLE("Speed_R", cvars.speed_color[0]); INI_EXPORT_VARIABLE("Speed_G", cvars.speed_color[1]); INI_EXPORT_VARIABLE("Speed_B", cvars.speed_color[2]); INI_EXPORT_VARIABLE("Speed_A", cvars.speed_color[3]); INI_EXPORT_VARIABLE("LightmapOverride", cvars.lightmap_override); INI_EXPORT_VARIABLE("LightmapOverrideBrightness", cvars.lightmap_brightness); INI_EXPORT_VARIABLE("LightmapOverride_R", cvars.lightmap_color[0]); INI_EXPORT_VARIABLE("LightmapOverride_G", cvars.lightmap_color[1]); INI_EXPORT_VARIABLE("LightmapOverride_B", cvars.lightmap_color[2]); INI_EXPORT_VARIABLE("ShowPlayersPushDirection", cvars.show_players_push_direction); INI_EXPORT_VARIABLE("PushDirectionLength", cvars.push_direction_length); INI_EXPORT_VARIABLE("PushDirectionWidth", cvars.push_direction_width); INI_EXPORT_VARIABLE("PushDirectionColor_R", cvars.push_direction_color[0]); INI_EXPORT_VARIABLE("PushDirectionColor_G", cvars.push_direction_color[1]); INI_EXPORT_VARIABLE("PushDirectionColor_B", cvars.push_direction_color[2]); INI_EXPORT_END_SECTION(); INI_EXPORT_BEGIN_SECTION("CHAMS"); INI_EXPORT_VARIABLE("Enable", cvars.chams); INI_EXPORT_VARIABLE("ChamsPlayers", cvars.chams_players); INI_EXPORT_VARIABLE("ChamsEntities", cvars.chams_entities); INI_EXPORT_VARIABLE("ChamsItems", cvars.chams_items); INI_EXPORT_VARIABLE("ChamsPlayersWall", cvars.chams_players_wall); INI_EXPORT_VARIABLE("ChamsEntitiesWall", cvars.chams_entities_wall); INI_EXPORT_VARIABLE("ChamsItemsWall", cvars.chams_items_wall); INI_EXPORT_VARIABLE("ChamsPlayersColor_R", cvars.chams_players_color[0]); INI_EXPORT_VARIABLE("ChamsPlayersColor_G", cvars.chams_players_color[1]); INI_EXPORT_VARIABLE("ChamsPlayersColor_B", cvars.chams_players_color[2]); INI_EXPORT_VARIABLE("ChamsEntitiesColor_R", cvars.chams_entities_color[0]); INI_EXPORT_VARIABLE("ChamsEntitiesColor_G", cvars.chams_entities_color[1]); INI_EXPORT_VARIABLE("ChamsEntitiesColor_B", cvars.chams_entities_color[2]); INI_EXPORT_VARIABLE("ChamsItemsColor_R", cvars.chams_items_color[0]); INI_EXPORT_VARIABLE("ChamsItemsColor_G", cvars.chams_items_color[1]); INI_EXPORT_VARIABLE("ChamsItemsColor_B", cvars.chams_items_color[2]); INI_EXPORT_VARIABLE("ChamsPlayersWallColor_R", cvars.chams_players_wall_color[0]); INI_EXPORT_VARIABLE("ChamsPlayersWallColor_G", cvars.chams_players_wall_color[1]); INI_EXPORT_VARIABLE("ChamsPlayersWallColor_B", cvars.chams_players_wall_color[2]); INI_EXPORT_VARIABLE("ChamsEntitiesWallColor_R", cvars.chams_entities_wall_color[0]); INI_EXPORT_VARIABLE("ChamsEntitiesWallColor_G", cvars.chams_entities_wall_color[1]); INI_EXPORT_VARIABLE("ChamsEntitiesWallColor_B", cvars.chams_entities_wall_color[2]); INI_EXPORT_VARIABLE("ChamsItemsWallColor_R", cvars.chams_items_wall_color[0]); INI_EXPORT_VARIABLE("ChamsItemsWallColor_G", cvars.chams_items_wall_color[1]); INI_EXPORT_VARIABLE("ChamsItemsWallColor_B", cvars.chams_items_wall_color[2]); INI_EXPORT_END_SECTION(); INI_EXPORT_BEGIN_SECTION("GLOW"); INI_EXPORT_VARIABLE("Enable", cvars.glow); INI_EXPORT_VARIABLE("Optimize", cvars.glow_optimize); INI_EXPORT_VARIABLE("GlowPlayers", cvars.glow_players); INI_EXPORT_VARIABLE("GlowEntities", cvars.glow_entities); INI_EXPORT_VARIABLE("GlowItems", cvars.glow_items); INI_EXPORT_VARIABLE("GlowPlayersWidth", cvars.glow_players_width); INI_EXPORT_VARIABLE("GlowEntitiesWidth", cvars.glow_entities_width); INI_EXPORT_VARIABLE("GlowItemsWidth", cvars.glow_items_width); INI_EXPORT_VARIABLE("GlowPlayersWall", cvars.glow_players_wall); INI_EXPORT_VARIABLE("GlowEntitiesWall", cvars.glow_entities_wall); INI_EXPORT_VARIABLE("GlowItemsWall", cvars.glow_items_wall); INI_EXPORT_VARIABLE("GlowPlayersColor_R", cvars.glow_players_color[0]); INI_EXPORT_VARIABLE("GlowPlayersColor_G", cvars.glow_players_color[1]); INI_EXPORT_VARIABLE("GlowPlayersColor_B", cvars.glow_players_color[2]); INI_EXPORT_VARIABLE("GlowEntitiesColor_R", cvars.glow_entities_color[0]); INI_EXPORT_VARIABLE("GlowEntitiesColor_G", cvars.glow_entities_color[1]); INI_EXPORT_VARIABLE("GlowEntitiesColor_B", cvars.glow_entities_color[2]); INI_EXPORT_VARIABLE("GlowItemsColor_R", cvars.glow_items_color[0]); INI_EXPORT_VARIABLE("GlowItemsColor_G", cvars.glow_items_color[1]); INI_EXPORT_VARIABLE("GlowItemsColor_B", cvars.glow_items_color[2]); INI_EXPORT_END_SECTION(); INI_EXPORT_BEGIN_SECTION("DYNAMICGLOW"); INI_EXPORT_VARIABLE("GlowAttach", cvars.dyn_glow_attach); INI_EXPORT_VARIABLE("GlowSelf", cvars.dyn_glow_self); INI_EXPORT_VARIABLE("GlowSelfRadius", cvars.dyn_glow_self_radius); INI_EXPORT_VARIABLE("GlowSelfDecay", cvars.dyn_glow_self_decay); INI_EXPORT_VARIABLE("GlowSelfColor_R", cvars.dyn_glow_self_color[0]); INI_EXPORT_VARIABLE("GlowSelfColor_G", cvars.dyn_glow_self_color[1]); INI_EXPORT_VARIABLE("GlowSelfColor_B", cvars.dyn_glow_self_color[2]); INI_EXPORT_VARIABLE("GlowPlayers", cvars.dyn_glow_players); INI_EXPORT_VARIABLE("GlowPlayersRadius", cvars.dyn_glow_players_radius); INI_EXPORT_VARIABLE("GlowPlayersDecay", cvars.dyn_glow_players_decay); INI_EXPORT_VARIABLE("GlowPlayersColor_R", cvars.dyn_glow_players_color[0]); INI_EXPORT_VARIABLE("GlowPlayersColor_G", cvars.dyn_glow_players_color[1]); INI_EXPORT_VARIABLE("GlowPlayersColor_B", cvars.dyn_glow_players_color[2]); INI_EXPORT_VARIABLE("GlowEntities", cvars.dyn_glow_entities); INI_EXPORT_VARIABLE("GlowEntitiesRadius", cvars.dyn_glow_entities_radius); INI_EXPORT_VARIABLE("GlowEntitiesDecay", cvars.dyn_glow_entities_decay); INI_EXPORT_VARIABLE("GlowEntitiesColor_R", cvars.dyn_glow_entities_color[0]); INI_EXPORT_VARIABLE("GlowEntitiesColor_G", cvars.dyn_glow_entities_color[1]); INI_EXPORT_VARIABLE("GlowEntitiesColor_B", cvars.dyn_glow_entities_color[2]); INI_EXPORT_VARIABLE("GlowItems", cvars.dyn_glow_items); INI_EXPORT_VARIABLE("GlowItemsRadius", cvars.dyn_glow_items_radius); INI_EXPORT_VARIABLE("GlowItemsDecay", cvars.dyn_glow_items_decay); INI_EXPORT_VARIABLE("GlowItemsColor_R", cvars.dyn_glow_items_color[0]); INI_EXPORT_VARIABLE("GlowItemsColor_G", cvars.dyn_glow_items_color[1]); INI_EXPORT_VARIABLE("GlowItemsColor_B", cvars.dyn_glow_items_color[2]); INI_EXPORT_END_SECTION(); INI_EXPORT_BEGIN_SECTION("STRAFE"); INI_EXPORT_VARIABLE("Enable", cvars.strafe); INI_EXPORT_VARIABLE("IgnoreGround", cvars.strafe_ignore_ground); INI_EXPORT_VARIABLE("Direction", cvars.strafe_dir); INI_EXPORT_VARIABLE("Type", cvars.strafe_type); INI_EXPORT_END_SECTION(); INI_EXPORT_BEGIN_SECTION("FAKELAG"); INI_EXPORT_VARIABLE("Enable", cvars.fakelag); INI_EXPORT_VARIABLE("AdaptiveInterp", cvars.fakelag_adaptive_ex_interp); INI_EXPORT_VARIABLE("Type", cvars.fakelag_type); INI_EXPORT_VARIABLE("Move", cvars.fakelag_move); INI_EXPORT_VARIABLE("Limit", cvars.fakelag_limit); INI_EXPORT_VARIABLE("Variance", cvars.fakelag_variance); INI_EXPORT_END_SECTION(); INI_EXPORT_BEGIN_SECTION("ANTIAFK"); INI_EXPORT_VARIABLE("Type", cvars.antiafk); INI_EXPORT_VARIABLE("RotateCamera", cvars.antiafk_rotate_camera); INI_EXPORT_VARIABLE("StayWithinRange", cvars.antiafk_stay_within_range); INI_EXPORT_VARIABLE("ResetStayPos", cvars.antiafk_reset_stay_pos); INI_EXPORT_VARIABLE("RotationAngle", cvars.antiafk_rotation_angle); INI_EXPORT_VARIABLE("StayRadius", cvars.antiafk_stay_radius); INI_EXPORT_VARIABLE("StayRadiusOffsetAngle", cvars.antiafk_stay_radius_offset_angle); INI_EXPORT_END_SECTION(); INI_EXPORT_BEGIN_SECTION("MISC"); INI_EXPORT_VARIABLE("AutoJump", cvars.autojump); INI_EXPORT_VARIABLE("JumpBug", cvars.jumpbug); INI_EXPORT_VARIABLE("DoubleDuck", cvars.doubleduck); INI_EXPORT_VARIABLE("FastRun", cvars.fastrun); INI_EXPORT_VARIABLE("QuakeGuns", cvars.quake_guns); INI_EXPORT_VARIABLE("TertiaryAttackGlitch", cvars.tertiary_attack_glitch); INI_EXPORT_VARIABLE("SaveSoundcache", cvars.save_soundcache); INI_EXPORT_VARIABLE("RotateDeadBody", cvars.rotate_dead_body); INI_EXPORT_VARIABLE("RemoveFOVCap", cvars.remove_fov_cap); INI_EXPORT_VARIABLE("NoWeaponAnim", cvars.no_weapon_anim); INI_EXPORT_VARIABLE("ColorPulsator", cvars.color_pulsator); INI_EXPORT_VARIABLE("ColorPulsatorTop", cvars.color_pulsator_top); INI_EXPORT_VARIABLE("ColorPulsatorBottom", cvars.color_pulsator_bottom); INI_EXPORT_VARIABLE("ColorPulsatorDelay", cvars.color_pulsator_delay); INI_EXPORT_VARIABLE("LockPitch", cvars.lock_pitch); INI_EXPORT_VARIABLE("LockYaw", cvars.lock_yaw); INI_EXPORT_VARIABLE("LockPitchAngle", cvars.lock_pitch_angle); INI_EXPORT_VARIABLE("LockYawAngle", cvars.lock_yaw_angle); INI_EXPORT_VARIABLE("SpinYaw", cvars.spin_yaw_angle); INI_EXPORT_VARIABLE("SpinPitch", cvars.spin_pitch_angle); INI_EXPORT_VARIABLE("SpinYawAngle", cvars.spin_yaw_rotation_angle); INI_EXPORT_VARIABLE("SpinPitchAngle", cvars.spin_pitch_rotation_angle); INI_EXPORT_VARIABLE("ApplicationSpeed", cvars.application_speed); INI_EXPORT_END_SECTION(); INI_EXPORT_BEGIN_SECTION("KEYSPAM"); INI_EXPORT_VARIABLE("HoldMode", cvars.keyspam_hold_mode); INI_EXPORT_VARIABLE("Spam_E", cvars.keyspam_e); INI_EXPORT_VARIABLE("Spam_W", cvars.keyspam_w); INI_EXPORT_VARIABLE("Spam_S", cvars.keyspam_s); INI_EXPORT_VARIABLE("Spam_Q", cvars.keyspam_q); INI_EXPORT_VARIABLE("Spam_CTRL", cvars.keyspam_ctrl); INI_EXPORT_END_SECTION(); INI_EXPORT_BEGIN_SECTION("FOG"); INI_EXPORT_VARIABLE("Enable", cvars.fog); INI_EXPORT_VARIABLE("FogSkybox", cvars.fog_skybox); INI_EXPORT_VARIABLE("RemoveInWater", cvars.remove_water_fog); INI_EXPORT_VARIABLE("Start", cvars.fog_start); INI_EXPORT_VARIABLE("End", cvars.fog_end); INI_EXPORT_VARIABLE("Density", cvars.fog_density); INI_EXPORT_VARIABLE("Fog_R", cvars.fog_color[0]); INI_EXPORT_VARIABLE("Fog_G", cvars.fog_color[1]); INI_EXPORT_VARIABLE("Fog_B", cvars.fog_color[2]); INI_EXPORT_END_SECTION(); INI_EXPORT_BEGIN_SECTION("SKYBOX"); INI_EXPORT_VARIABLE("Type", cvars.skybox); INI_EXPORT_END_SECTION(); INI_EXPORT_BEGIN_SECTION("CHATCOLORS"); INI_EXPORT_VARIABLE("Enable", cvars.enable_chat_colors); INI_EXPORT_VARIABLE("PlayerName_R", cvars.player_name_color[0]); INI_EXPORT_VARIABLE("PlayerName_G", cvars.player_name_color[1]); INI_EXPORT_VARIABLE("PlayerName_B", cvars.player_name_color[2]); INI_EXPORT_VARIABLE("RainbowUpdateDelay", cvars.chat_rainbow_update_delay); INI_EXPORT_VARIABLE("RainbowHueDelta", cvars.chat_rainbow_hue_delta); INI_EXPORT_VARIABLE("RainbowSaturation", cvars.chat_rainbow_saturation); INI_EXPORT_VARIABLE("RainbowLightness", cvars.chat_rainbow_lightness); INI_EXPORT_VARIABLE("ColorOne_R", cvars.chat_color_one[0]); INI_EXPORT_VARIABLE("ColorOne_G", cvars.chat_color_one[1]); INI_EXPORT_VARIABLE("ColorOne_B", cvars.chat_color_one[2]); INI_EXPORT_VARIABLE("ColorTwo_R", cvars.chat_color_two[0]); INI_EXPORT_VARIABLE("ColorTwo_G", cvars.chat_color_two[1]); INI_EXPORT_VARIABLE("ColorTwo_B", cvars.chat_color_two[2]); INI_EXPORT_VARIABLE("ColorThree_R", cvars.chat_color_three[0]); INI_EXPORT_VARIABLE("ColorThree_G", cvars.chat_color_three[1]); INI_EXPORT_VARIABLE("ColorThree_B", cvars.chat_color_three[2]); INI_EXPORT_VARIABLE("ColorFour_R", cvars.chat_color_four[0]); INI_EXPORT_VARIABLE("ColorFour_G", cvars.chat_color_four[1]); INI_EXPORT_VARIABLE("ColorFour_B", cvars.chat_color_four[2]); INI_EXPORT_VARIABLE("ColorFive_R", cvars.chat_color_five[0]); INI_EXPORT_VARIABLE("ColorFive_G", cvars.chat_color_five[1]); INI_EXPORT_VARIABLE("ColorFive_B", cvars.chat_color_five[2]); INI_EXPORT_VARIABLE("ColorSix_R", cvars.chat_color_six[0]); INI_EXPORT_VARIABLE("ColorSix_G", cvars.chat_color_six[1]); INI_EXPORT_VARIABLE("ColorSix_B", cvars.chat_color_six[2]); INI_EXPORT_END_SECTION(); INI_EXPORT_BEGIN_SECTION("CAMHACK"); INI_EXPORT_VARIABLE("SpeedFactor", cvars.camhack_speed_factor); INI_EXPORT_VARIABLE("ShowModel", cvars.camhack_show_model); INI_EXPORT_END_SECTION(); INI_EXPORT_BEGIN_SECTION("FPROAMING"); INI_EXPORT_VARIABLE("Enable", cvars.fp_roaming); INI_EXPORT_VARIABLE("Crosshair", cvars.fp_roaming_draw_crosshair); INI_EXPORT_VARIABLE("Lerp", cvars.fp_roaming_lerp); INI_EXPORT_VARIABLE("LerpValue", cvars.fp_roaming_lerp_value); INI_EXPORT_END_SECTION(); INI_EXPORT_BEGIN_SECTION("VOTEPOPUP"); INI_EXPORT_VARIABLE("Enable", cvars.vote_popup); INI_EXPORT_VARIABLE("WidthSize", cvars.vote_popup_width_size); INI_EXPORT_VARIABLE("HeightSize", cvars.vote_popup_height_size); INI_EXPORT_VARIABLE("WidthBorderPixels", cvars.vote_popup_w_border_pix); INI_EXPORT_VARIABLE("HeightBorderPixels", cvars.vote_popup_h_border_pix); INI_EXPORT_VARIABLE("WidthFraction", cvars.vote_popup_width_frac); INI_EXPORT_VARIABLE("HeightFraction", cvars.vote_popup_height_frac); INI_EXPORT_END_SECTION(); //INI_EXPORT_BEGIN_SECTION("AUTOVOTE"); // INI_EXPORT_VARIABLE("Mode", cvars.autovote_mode); // INI_EXPORT_VARIABLE("UseOnCustomVotes", cvars.autovote_custom); // INI_EXPORT_VARIABLE("IgnoreVoteFilter", cvars.autovote_ignore_filter); //INI_EXPORT_END_SECTION(); INI_EXPORT_BEGIN_SECTION("AMS"); INI_EXPORT_VARIABLE("MuteEverything", cvars.ams_mute_everything); INI_EXPORT_END_SECTION(); INI_EXPORT_END() }
51.635753
145
0.799516
revoiid
58692dbc09fcbcd91582427f34e2931ae3322c63
24,901
cpp
C++
Gem/Code/Source/RHI/MatrixAlignmentTestExampleComponent.cpp
Bindless-Chicken/o3de-atom-sampleviewer
13b11996079675445ce4e321f53c3ac79e01702d
[ "Apache-2.0", "MIT" ]
15
2021-07-07T02:16:06.000Z
2022-03-22T07:39:06.000Z
Gem/Code/Source/RHI/MatrixAlignmentTestExampleComponent.cpp
Bindless-Chicken/o3de-atom-sampleviewer
13b11996079675445ce4e321f53c3ac79e01702d
[ "Apache-2.0", "MIT" ]
66
2021-07-07T00:01:05.000Z
2022-03-28T06:37:41.000Z
Gem/Code/Source/RHI/MatrixAlignmentTestExampleComponent.cpp
Bindless-Chicken/o3de-atom-sampleviewer
13b11996079675445ce4e321f53c3ac79e01702d
[ "Apache-2.0", "MIT" ]
13
2021-07-06T18:21:33.000Z
2022-01-04T18:29:18.000Z
/* * Copyright (c) Contributors to the Open 3D Engine Project. * For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #include <RHI/MatrixAlignmentTestExampleComponent.h> #include <Utils/Utils.h> #include <SampleComponentManager.h> #include <Atom/RHI/CommandList.h> #include <Atom/RHI.Reflect/InputStreamLayoutBuilder.h> #include <Atom/RHI.Reflect/RenderAttachmentLayoutBuilder.h> #include <Atom/RPI.Public/Shader/Shader.h> #include <Atom/RPI.Reflect/Shader/ShaderAsset.h> #include <AzCore/Serialization/SerializeContext.h> namespace AtomSampleViewer { void MatrixAlignmentTestExampleComponent::Reflect(AZ::ReflectContext* context) { if (auto* serializeContext = azrtti_cast<AZ::SerializeContext*>(context)) { serializeContext->Class<MatrixAlignmentTestExampleComponent, AZ::Component>() ->Version(0) ; } } void MatrixAlignmentTestExampleComponent::OnTick([[maybe_unused]] float deltaTime, [[maybe_unused]] AZ::ScriptTimePoint time) { bool numFloatsChanged = false; if (m_imguiSidebar.Begin()) { ImGui::Spacing(); ImGui::Text("Number Of Rows"); ScriptableImGui::RadioButton("1##R1", &m_numRows, 1); ImGui::SameLine(); ScriptableImGui::RadioButton("2##R2", &m_numRows, 2); ImGui::SameLine(); ScriptableImGui::RadioButton("3##R3", &m_numRows, 3); ImGui::SameLine(); ScriptableImGui::RadioButton("4##R4", &m_numRows, 4); ImGui::Spacing(); ImGui::Text("Number Of Columns"); ScriptableImGui::RadioButton("1##C1", &m_numColumns, 1); ImGui::SameLine(); ScriptableImGui::RadioButton("2##C2", &m_numColumns, 2); ImGui::SameLine(); ScriptableImGui::RadioButton("3##C3", &m_numColumns, 3); ImGui::SameLine(); ScriptableImGui::RadioButton("4##C4", &m_numColumns, 4); ImGui::Spacing(); ImGui::Text("Checked Location Value:"); ScriptableImGui::SliderFloat("##CheckedLocationValue", &m_matrixLocationValue, 0.f, 1.f, "%.1f", ImGuiSliderFlags_AlwaysClamp); ImGui::Text("Unchecked Location Value: "); ImGui::Text("%.1f", 1.0f - m_matrixLocationValue); DrawMatrixValuesTable(); ImGui::Spacing(); ImGui::Text("Data After Matrix:"); numFloatsChanged |= ScriptableImGui::RadioButton("float", &m_numFloatsAfterMatrix, 1); ImGui::SameLine(); numFloatsChanged |= ScriptableImGui::RadioButton("float2", &m_numFloatsAfterMatrix, 2); ImGui::Text("float value:"); ScriptableImGui::SliderFloat("##FloatAfterMatrix", &m_floatAfterMatrix, 0.f, 1.f, "%.1f", ImGuiSliderFlags_AlwaysClamp); m_imguiSidebar.End(); } if (numFloatsChanged) { m_needPipelineReload = true; } } void MatrixAlignmentTestExampleComponent::DrawMatrixValuesTable() { const auto flags = ImGuiTableFlags_Borders; if (ImGui::BeginTable("Matrix Data", m_numColumns + 1, flags)) { // Table header setup ImGui::TableSetupColumn("R\\C"); for (int col = 0; col < m_numColumns; ++col) { AZStd::string colName = AZStd::string::format("C%d", col); ImGui::TableSetupColumn(colName.c_str()); } ImGui::TableHeadersRow(); for (int row = 0; row < m_numRows; ++row) { for (int col = 0; col < m_numColumns + 1; ++col) { ImGui::TableNextColumn(); if (col == 0) { ImGui::Text("R%d", row); } else { AZStd::string cellId = AZStd::string::format("##R%dC%d", row, col-1); ScriptableImGui::Checkbox(cellId.c_str(), &m_checkedMatrixValues[row][col-1]); } } } ImGui::EndTable(); } } void MatrixAlignmentTestExampleComponent::FrameBeginInternal([[maybe_unused]] AZ::RHI::FrameGraphBuilder& frameGraphBuilder) { if (m_needPipelineReload) { ReleaseRhiData(); InitializeRenderPipeline(); } } bool MatrixAlignmentTestExampleComponent::SetSrgMatrixData(int numRows, int numColumns, const AZ::RHI::ShaderInputConstantIndex& dataAfterMatrixConstantId, const AZ::RHI::ShaderInputConstantIndex& matrixConstantId) { if ((m_numRows != numRows) || (m_numColumns != numColumns)) { return false; } if (!dataAfterMatrixConstantId.IsValid() || !matrixConstantId.IsValid()) { return false; } // Always set the float first, this way if there are alignment issues We'll notice the unexpected // colors bool success = false; if (m_numFloatsAfterMatrix == 1) { success = m_shaderResourceGroup->SetConstant(dataAfterMatrixConstantId, m_floatAfterMatrix); } else { AZ::Vector2 float2(m_floatAfterMatrix, m_floatAfterMatrix); success = m_shaderResourceGroup->SetConstant(dataAfterMatrixConstantId, float2); } AZ_Warning("MatrixAlignmentTestExampleComponent", success, "Failed to set SRG Constant m_fAfter%d%d", numRows, numColumns); constexpr size_t SizeOfFloat4 = sizeof(float) * 4; constexpr size_t SizeOfFloat = sizeof(float); uint32_t numBytes = (SizeOfFloat4 * numRows) - ((4 - numColumns) * SizeOfFloat); success = m_shaderResourceGroup->SetConstantRaw(matrixConstantId, m_rawMatrix, numBytes); AZ_Warning("MatrixAlignmentTestExampleComponent", success, "Failed to set SRG Constant m_matrix%d%d", numRows, numColumns); return true; } void MatrixAlignmentTestExampleComponent::OnFramePrepare(AZ::RHI::FrameGraphBuilder& frameGraphBuilder) { using namespace AZ; { AZ::Vector4 screenResolution(GetViewportWidth(), GetViewportHeight(), 0, 0); [[maybe_unused]] bool success = m_shaderResourceGroup->SetConstant(m_resolutionConstantIndex, screenResolution); AZ_Warning("MatrixAlignmentTestExampleComponent", success, "Failed to set SRG Constant m_resolution"); success = m_shaderResourceGroup->SetConstant(m_numRowsConstantIndex, m_numRows); AZ_Warning("MatrixAlignmentTestExampleComponent", success, "Failed to set SRG Constant m_numRows"); success = m_shaderResourceGroup->SetConstant(m_numColumnsConstantIndex, m_numColumns); AZ_Warning("MatrixAlignmentTestExampleComponent", success, "Failed to set SRG Constant m_numColumns"); for (int row = 0; row < m_numRows; ++row) { for (int col = 0; col < m_numColumns; ++col) { m_rawMatrix[row][col] = m_checkedMatrixValues[row][col] ? m_matrixLocationValue : 1.0f - m_matrixLocationValue; } } if ( SetSrgMatrixData(1, 1, m_fAfter11ConstantIndex, m_matrix11ConstantIndex)) {} else if ( SetSrgMatrixData(1, 2, m_fAfter12ConstantIndex, m_matrix12ConstantIndex)) {} else if ( SetSrgMatrixData(1, 3, m_fAfter13ConstantIndex, m_matrix13ConstantIndex)) {} else if ( SetSrgMatrixData(1, 4, m_fAfter14ConstantIndex, m_matrix14ConstantIndex)) {} //else if (SetSrgMatrixData(2, 1, m_fAfter21ConstantIndex, m_matrix21ConstantIndex)) {} //Not supported by AZSLc else if ( SetSrgMatrixData(2, 2, m_fAfter22ConstantIndex, m_matrix22ConstantIndex)) {} else if ( SetSrgMatrixData(2, 3, m_fAfter23ConstantIndex, m_matrix23ConstantIndex)) {} else if ( SetSrgMatrixData(2, 4, m_fAfter24ConstantIndex, m_matrix24ConstantIndex)) {} //else if (SetSrgMatrixData(3, 1, m_fAfter31ConstantIndex, m_matrix31ConstantIndex)) {} //Not supported by AZSLc else if ( SetSrgMatrixData(3, 2, m_fAfter32ConstantIndex, m_matrix32ConstantIndex)) {} else if ( SetSrgMatrixData(3, 3, m_fAfter33ConstantIndex, m_matrix33ConstantIndex)) {} else if ( SetSrgMatrixData(3, 4, m_fAfter34ConstantIndex, m_matrix34ConstantIndex)) {} //else if (SetSrgMatrixData(4, 1, m_fAfter41ConstantIndex, m_matrix41ConstantIndex)) {} //Not supported by AZSLc else if ( SetSrgMatrixData(4, 2, m_fAfter42ConstantIndex, m_matrix42ConstantIndex)) {} else if ( SetSrgMatrixData(4, 3, m_fAfter43ConstantIndex, m_matrix43ConstantIndex)) {} else if ( SetSrgMatrixData(4, 4, m_fAfter44ConstantIndex, m_matrix44ConstantIndex)) {} m_shaderResourceGroup->Compile(); } BasicRHIComponent::OnFramePrepare(frameGraphBuilder); } MatrixAlignmentTestExampleComponent::MatrixAlignmentTestExampleComponent() { m_supportRHISamplePipeline = true; } void MatrixAlignmentTestExampleComponent::InitializeRenderPipeline() { using namespace AZ; RHI::Ptr<RHI::Device> device = Utils::GetRHIDevice(); AZ::RHI::PipelineStateDescriptorForDraw pipelineStateDescriptor; { m_inputAssemblyBufferPool = RHI::Factory::Get().CreateBufferPool(); RHI::BufferPoolDescriptor bufferPoolDesc; bufferPoolDesc.m_bindFlags = RHI::BufferBindFlags::InputAssembly; bufferPoolDesc.m_heapMemoryLevel = RHI::HeapMemoryLevel::Device; m_inputAssemblyBufferPool->Init(*device, bufferPoolDesc); BufferData bufferData; SetFullScreenRect(bufferData.m_positions.data(), nullptr, bufferData.m_indices.data()); // All blue. SetVertexColor(bufferData.m_colors.data(), 0, 0.0, 0.0, 1.0, 1.0); SetVertexColor(bufferData.m_colors.data(), 1, 0.0, 0.0, 1.0, 1.0); SetVertexColor(bufferData.m_colors.data(), 2, 0.0, 0.0, 1.0, 1.0); SetVertexColor(bufferData.m_colors.data(), 3, 0.0, 0.0, 1.0, 1.0); m_inputAssemblyBuffer = RHI::Factory::Get().CreateBuffer(); RHI::BufferInitRequest request; request.m_buffer = m_inputAssemblyBuffer.get(); request.m_descriptor = RHI::BufferDescriptor{ RHI::BufferBindFlags::InputAssembly, sizeof(bufferData) }; request.m_initialData = &bufferData; m_inputAssemblyBufferPool->InitBuffer(request); m_streamBufferViews[0] = { *m_inputAssemblyBuffer, offsetof(BufferData, m_positions), sizeof(BufferData::m_positions), sizeof(VertexPosition) }; m_streamBufferViews[1] = { *m_inputAssemblyBuffer, offsetof(BufferData, m_colors), sizeof(BufferData::m_colors), sizeof(VertexColor) }; RHI::InputStreamLayoutBuilder layoutBuilder; layoutBuilder.AddBuffer()->Channel("POSITION", RHI::Format::R32G32B32_FLOAT); layoutBuilder.AddBuffer()->Channel("COLOR", RHI::Format::R32G32B32A32_FLOAT); pipelineStateDescriptor.m_inputStreamLayout = layoutBuilder.End(); RHI::ValidateStreamBufferViews(pipelineStateDescriptor.m_inputStreamLayout, m_streamBufferViews); } { const char* triangeShaderFilePath = "Shaders/RHI/MatrixAlignmentTest.azshader"; const char* sampleName = "MatrixAlignmentTest"; const AZ::Name supervariantName = (m_numFloatsAfterMatrix == 1) ? AZ::Name{""} : AZ::Name{"float2"}; auto shader = LoadShader(triangeShaderFilePath, sampleName, &supervariantName); if (shader == nullptr) return; auto shaderVariant = shader->GetRootVariant(); shaderVariant.ConfigurePipelineState(pipelineStateDescriptor); RHI::RenderAttachmentLayoutBuilder attachmentsBuilder; attachmentsBuilder.AddSubpass() ->RenderTargetAttachment(m_outputFormat); [[maybe_unused]] AZ::RHI::ResultCode result = attachmentsBuilder.End(pipelineStateDescriptor.m_renderAttachmentConfiguration.m_renderAttachmentLayout); AZ_Assert(result == AZ::RHI::ResultCode::Success, "Failed to create render attachment layout"); m_pipelineState = shader->AcquirePipelineState(pipelineStateDescriptor); if (!m_pipelineState) { AZ_Error(sampleName, false, "Failed to acquire default pipeline state for shader '%s'", triangeShaderFilePath); return; } m_shaderResourceGroup = CreateShaderResourceGroup(shader, "AlignmentValidatorSrg", sampleName); const Name resolutionConstantId{ "m_resolution" }; FindShaderInputIndex(&m_resolutionConstantIndex, m_shaderResourceGroup, resolutionConstantId, sampleName); const Name rowSelectionConstantId{ "m_numRows" }; FindShaderInputIndex(&m_numRowsConstantIndex, m_shaderResourceGroup, rowSelectionConstantId, sampleName); const Name colSelectionConstantId{ "m_numColumns" }; FindShaderInputIndex(&m_numColumnsConstantIndex, m_shaderResourceGroup, colSelectionConstantId, sampleName); { const Name MatrixName{ "m_matrix11" }; FindShaderInputIndex(&m_matrix11ConstantIndex, m_shaderResourceGroup, MatrixName, sampleName); const Name floatAfterMatrixName{ "m_fAfter11" }; FindShaderInputIndex(&m_fAfter11ConstantIndex, m_shaderResourceGroup, floatAfterMatrixName, sampleName); } { const Name MatrixName{ "m_matrix12" }; FindShaderInputIndex(&m_matrix12ConstantIndex, m_shaderResourceGroup, MatrixName, sampleName); const Name floatAfterMatrixName{ "m_fAfter12" }; FindShaderInputIndex(&m_fAfter12ConstantIndex, m_shaderResourceGroup, floatAfterMatrixName, sampleName); } { const Name MatrixName{ "m_matrix13" }; FindShaderInputIndex(&m_matrix13ConstantIndex, m_shaderResourceGroup, MatrixName, sampleName); const Name floatAfterMatrixName{ "m_fAfter13" }; FindShaderInputIndex(&m_fAfter13ConstantIndex, m_shaderResourceGroup, floatAfterMatrixName, sampleName); } { const Name MatrixName{ "m_matrix14" }; FindShaderInputIndex(&m_matrix14ConstantIndex, m_shaderResourceGroup, MatrixName, sampleName); const Name floatAfterMatrixName{ "m_fAfter14" }; FindShaderInputIndex(&m_fAfter14ConstantIndex, m_shaderResourceGroup, floatAfterMatrixName, sampleName); } // Not supported by AZSLc //{ // const Name MatrixName{ "m_matrix21" }; // FindShaderInputIndex(&m_matrix21ConstantIndex, m_shaderResourceGroup, MatrixName, sampleName); // const Name floatAfterMatrixName{ "m_fAfter21" }; // FindShaderInputIndex(&m_fAfter21ConstantIndex, m_shaderResourceGroup, floatAfterMatrixName, sampleName); //} { const Name MatrixName{ "m_matrix22" }; FindShaderInputIndex(&m_matrix22ConstantIndex, m_shaderResourceGroup, MatrixName, sampleName); const Name floatAfterMatrixName{ "m_fAfter22" }; FindShaderInputIndex(&m_fAfter22ConstantIndex, m_shaderResourceGroup, floatAfterMatrixName, sampleName); } { const Name MatrixName{ "m_matrix23" }; FindShaderInputIndex(&m_matrix23ConstantIndex, m_shaderResourceGroup, MatrixName, sampleName); const Name floatAfterMatrixName{ "m_fAfter23" }; FindShaderInputIndex(&m_fAfter23ConstantIndex, m_shaderResourceGroup, floatAfterMatrixName, sampleName); } { const Name MatrixName{ "m_matrix24" }; FindShaderInputIndex(&m_matrix24ConstantIndex, m_shaderResourceGroup, MatrixName, sampleName); const Name floatAfterMatrixName{ "m_fAfter24" }; FindShaderInputIndex(&m_fAfter24ConstantIndex, m_shaderResourceGroup, floatAfterMatrixName, sampleName); } // Not supported by AZSLc //{ // const Name MatrixName{ "m_matrix31" }; // FindShaderInputIndex(&m_matrix31ConstantIndex, m_shaderResourceGroup, MatrixName, sampleName); // const Name floatAfterMatrixName{ "m_fAfter31" }; // FindShaderInputIndex(&m_fAfter31ConstantIndex, m_shaderResourceGroup, floatAfterMatrixName, sampleName); //} { const Name MatrixName{ "m_matrix32" }; FindShaderInputIndex(&m_matrix32ConstantIndex, m_shaderResourceGroup, MatrixName, sampleName); const Name floatAfterMatrixName{ "m_fAfter32" }; FindShaderInputIndex(&m_fAfter32ConstantIndex, m_shaderResourceGroup, floatAfterMatrixName, sampleName); } { const Name MatrixName{ "m_matrix33" }; FindShaderInputIndex(&m_matrix33ConstantIndex, m_shaderResourceGroup, MatrixName, sampleName); const Name floatAfterMatrixName{ "m_fAfter33" }; FindShaderInputIndex(&m_fAfter33ConstantIndex, m_shaderResourceGroup, floatAfterMatrixName, sampleName); } { const Name MatrixName{ "m_matrix34" }; FindShaderInputIndex(&m_matrix34ConstantIndex, m_shaderResourceGroup, MatrixName, sampleName); const Name floatAfterMatrixName{ "m_fAfter34" }; FindShaderInputIndex(&m_fAfter34ConstantIndex, m_shaderResourceGroup, floatAfterMatrixName, sampleName); } // Not supported by AZSLc //{ // const Name MatrixName{ "m_matrix41" }; // FindShaderInputIndex(&m_matrix41ConstantIndex, m_shaderResourceGroup, MatrixName, sampleName); // const Name floatAfterMatrixName{ "m_fAfter41" }; // FindShaderInputIndex(&m_fAfter41ConstantIndex, m_shaderResourceGroup, floatAfterMatrixName, sampleName); //} { const Name MatrixName{ "m_matrix42" }; FindShaderInputIndex(&m_matrix42ConstantIndex, m_shaderResourceGroup, MatrixName, sampleName); const Name floatAfterMatrixName{ "m_fAfter42" }; FindShaderInputIndex(&m_fAfter42ConstantIndex, m_shaderResourceGroup, floatAfterMatrixName, sampleName); } { const Name MatrixName{ "m_matrix43" }; FindShaderInputIndex(&m_matrix43ConstantIndex, m_shaderResourceGroup, MatrixName, sampleName); const Name floatAfterMatrixName{ "m_fAfter43" }; FindShaderInputIndex(&m_fAfter43ConstantIndex, m_shaderResourceGroup, floatAfterMatrixName, sampleName); } { const Name MatrixName{ "m_matrix44" }; FindShaderInputIndex(&m_matrix44ConstantIndex, m_shaderResourceGroup, MatrixName, sampleName); const Name floatAfterMatrixName{ "m_fAfter44" }; FindShaderInputIndex(&m_fAfter44ConstantIndex, m_shaderResourceGroup, floatAfterMatrixName, sampleName); } } // Creates a scope for rendering the triangle. { struct ScopeData { }; const auto prepareFunction = [this](RHI::FrameGraphInterface frameGraph, [[maybe_unused]] ScopeData& scopeData) { // Binds the swap chain as a color attachment. Clears it to white. { RHI::ImageScopeAttachmentDescriptor descriptor; descriptor.m_attachmentId = m_outputAttachmentId; descriptor.m_loadStoreAction.m_loadAction = RHI::AttachmentLoadAction::Load; frameGraph.UseColorAttachment(descriptor); } // We will submit a single draw item. frameGraph.SetEstimatedItemCount(1); }; RHI::EmptyCompileFunction<ScopeData> compileFunction; const auto executeFunction = [this](const RHI::FrameGraphExecuteContext& context, [[maybe_unused]] const ScopeData& scopeData) { RHI::CommandList* commandList = context.GetCommandList(); // Set persistent viewport and scissor state. commandList->SetViewports(&m_viewport, 1); commandList->SetScissors(&m_scissor, 1); const RHI::IndexBufferView indexBufferView = { *m_inputAssemblyBuffer, offsetof(BufferData, m_indices), sizeof(BufferData::m_indices), RHI::IndexFormat::Uint16 }; RHI::DrawIndexed drawIndexed; drawIndexed.m_indexCount = 6; drawIndexed.m_instanceCount = 2; const RHI::ShaderResourceGroup* shaderResourceGroups[] = { m_shaderResourceGroup->GetRHIShaderResourceGroup() }; RHI::DrawItem drawItem; drawItem.m_arguments = drawIndexed; drawItem.m_pipelineState = m_pipelineState.get(); drawItem.m_indexBufferView = &indexBufferView; drawItem.m_shaderResourceGroupCount = static_cast<uint8_t>(RHI::ArraySize(shaderResourceGroups)); drawItem.m_shaderResourceGroups = shaderResourceGroups; drawItem.m_streamBufferViewCount = static_cast<uint8_t>(m_streamBufferViews.size()); drawItem.m_streamBufferViews = m_streamBufferViews.data(); // Submit the triangle draw item. commandList->Submit(drawItem); }; m_scopeProducers.emplace_back( aznew RHI::ScopeProducerFunction< ScopeData, decltype(prepareFunction), decltype(compileFunction), decltype(executeFunction)>( RHI::ScopeId{"Triangle"}, ScopeData{}, prepareFunction, compileFunction, executeFunction)); } m_needPipelineReload = false; } void MatrixAlignmentTestExampleComponent::Activate() { using namespace AZ; m_numRows = 4; m_numColumns = 4; m_matrixLocationValue = 1.0f; m_checkedMatrixValues[0][0] = true; m_checkedMatrixValues[0][1] = false; m_checkedMatrixValues[0][2] = true; m_checkedMatrixValues[0][3] = false; m_checkedMatrixValues[1][0] = false; m_checkedMatrixValues[1][1] = true; m_checkedMatrixValues[1][2] = false; m_checkedMatrixValues[1][3] = true; m_checkedMatrixValues[2][0] = true; m_checkedMatrixValues[2][1] = false; m_checkedMatrixValues[2][2] = true; m_checkedMatrixValues[2][3] = false; m_checkedMatrixValues[3][0] = false; m_checkedMatrixValues[3][1] = true; m_checkedMatrixValues[3][2] = false; m_checkedMatrixValues[3][3] = true; m_numFloatsAfterMatrix = 1; m_floatAfterMatrix = 0.5; m_needPipelineReload = true; InitializeRenderPipeline(); m_imguiSidebar.Activate(); AZ::RHI::RHISystemNotificationBus::Handler::BusConnect(); AZ::TickBus::Handler::BusConnect(); } void MatrixAlignmentTestExampleComponent::ReleaseRhiData() { m_inputAssemblyBuffer = nullptr; m_inputAssemblyBufferPool = nullptr; m_pipelineState = nullptr; m_shaderResourceGroup = nullptr; m_scopeProducers.clear(); } void MatrixAlignmentTestExampleComponent::Deactivate() { m_inputAssemblyBuffer = nullptr; m_inputAssemblyBufferPool = nullptr; m_pipelineState = nullptr; m_shaderResourceGroup = nullptr; AZ::TickBus::Handler::BusDisconnect(); AZ::RHI::RHISystemNotificationBus::Handler::BusDisconnect(); m_imguiSidebar.Deactivate(); m_windowContext = nullptr; m_scopeProducers.clear(); } } // namespace AtomSampleViewer
45.192377
163
0.627967
Bindless-Chicken
586bee0bdc08ad7200215c2abdf39c0f4803774a
9,735
cpp
C++
src/core/SLSManager.cpp
rstular/srt-live-server
968d29b7bd4d81b0b6cbe702ebf6bbc164b6a22c
[ "MIT" ]
4
2021-12-17T07:58:48.000Z
2022-02-04T17:35:37.000Z
src/core/SLSManager.cpp
rstular/srt-live-server
968d29b7bd4d81b0b6cbe702ebf6bbc164b6a22c
[ "MIT" ]
null
null
null
src/core/SLSManager.cpp
rstular/srt-live-server
968d29b7bd4d81b0b6cbe702ebf6bbc164b6a22c
[ "MIT" ]
1
2021-12-15T21:56:57.000Z
2021-12-15T21:56:57.000Z
/** * The MIT License (MIT) * * Copyright (c) 2019-2020 Edward.Wu * * 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 <errno.h> #include <string.h> #include "spdlog/spdlog.h" #include <nlohmann/json.hpp> using json = nlohmann::json; #include "common.hpp" #include "SLSManager.hpp" #include "SLSLog.hpp" #include "SLSListener.hpp" #include "SLSPublisher.hpp" /** * srt conf */ SLS_CONF_DYNAMIC_IMPLEMENT(srt) /** * CSLSManager class implementation */ #define DEFAULT_GROUP 1 CSLSManager::CSLSManager() { m_worker_threads = DEFAULT_GROUP; m_server_count = 1; m_list_role = NULL; m_single_group = NULL; m_map_data = NULL; m_map_publisher = NULL; m_map_puller = NULL; m_map_pusher = NULL; } CSLSManager::~CSLSManager() { } int CSLSManager::start() { int ret = 0; int i = 0; // Read loaded config file sls_conf_srt_t *conf_srt = (sls_conf_srt_t *)sls_conf_get_root_conf(); if (!conf_srt) { spdlog::error("[{}] CSLSManager::start, no srt info, please check the conf file.", fmt::ptr(this)); return SLS_ERROR; } //set log level if (strlen(conf_srt->log_level) > 0) { sls_set_log_level(conf_srt->log_level); } //set log file if (strlen(conf_srt->log_file) > 0) { sls_set_log_file(conf_srt->log_file); } sls_conf_server_t *conf_server = (sls_conf_server_t *)conf_srt->child; if (!conf_server) { spdlog::error("[{}] CSLSManager::start, no server info, please check the conf file.", fmt::ptr(this)); return SLS_ERROR; } m_server_count = sls_conf_get_conf_count((sls_conf_base_t *)conf_server); sls_conf_server_t *conf = conf_server; m_map_data = new CSLSMapData[m_server_count]; m_map_publisher = new CSLSMapPublisher[m_server_count]; m_map_puller = new CSLSMapRelay[m_server_count]; m_map_pusher = new CSLSMapRelay[m_server_count]; //role list m_list_role = new CSLSRoleList; spdlog::info("[{}] CSLSManager::start, new m_list_role={}.", fmt::ptr(this), fmt::ptr(m_list_role)); //create listeners according config, delete by groups for (i = 0; i < m_server_count; i++) { CSLSListener *p = new CSLSListener(); //deleted by groups p->set_role_list(m_list_role); p->set_conf((sls_conf_base_t *)conf); p->set_record_hls_path_prefix(conf_srt->record_hls_path_prefix); p->set_map_data("", &m_map_data[i]); p->set_map_publisher(&m_map_publisher[i]); p->set_map_puller(&m_map_puller[i]); p->set_map_pusher(&m_map_pusher[i]); if (p->init() != SLS_OK) { spdlog::error("[{}] CSLSManager::start, p->init failed.", fmt::ptr(this)); return SLS_ERROR; } if (p->start() != SLS_OK) { spdlog::error("[{}] CSLSManager::start, p->start failed.", fmt::ptr(this)); return SLS_ERROR; } m_servers.push_back(p); conf = (sls_conf_server_t *)conf->sibling; } spdlog::info("[{}] CSLSManager::start, init listeners, count={:d}.", fmt::ptr(this), m_server_count); //create groups m_worker_threads = conf_srt->worker_threads; if (m_worker_threads == 0) { CSLSGroup *p = new CSLSGroup(); p->set_worker_number(0); p->set_role_list(m_list_role); p->set_worker_connections(conf_srt->worker_connections); p->set_stat_post_interval(conf_srt->stat_post_interval); if (SLS_OK != p->init_epoll()) { spdlog::error("[{}] CSLSManager::start, p->init_epoll failed.", fmt::ptr(this)); return SLS_ERROR; } m_workers.push_back(p); m_single_group = p; } else { for (i = 0; i < m_worker_threads; i++) { CSLSGroup *p = new CSLSGroup(); p->set_worker_number(i); p->set_role_list(m_list_role); p->set_worker_connections(conf_srt->worker_connections); p->set_stat_post_interval(conf_srt->stat_post_interval); if (SLS_OK != p->init_epoll()) { spdlog::error("[{}] CSLSManager::start, p->init_epoll failed.", fmt::ptr(this)); return SLS_ERROR; } p->start(); m_workers.push_back(p); } } spdlog::info("[{}] CSLSManager::start, init worker, count={:d}.", fmt::ptr(this), m_worker_threads); return ret; } int CSLSManager::single_thread_handler() { if (m_single_group) { return m_single_group->handler(); } return SLS_OK; } bool CSLSManager::is_single_thread() { if (m_single_group) return true; return false; } int CSLSManager::stop() { int ret = 0; int i = 0; // spdlog::info("[{}] CSLSManager::stop.", fmt::ptr(this)); //stop all listeners for (CSLSListener *server : m_servers) { if (server) { server->uninit(); } } m_servers.clear(); vector<CSLSGroup *>::iterator it_worker; for (it_worker = m_workers.begin(); it_worker != m_workers.end(); it_worker++) { CSLSGroup *p = *it_worker; if (p) { p->stop(); p->uninit_epoll(); delete p; p = NULL; } } m_workers.clear(); if (m_map_data) { delete[] m_map_data; m_map_data = NULL; } if (m_map_publisher) { delete[] m_map_publisher; m_map_publisher = NULL; } if (m_map_puller) { delete[] m_map_puller; m_map_puller = NULL; } if (m_map_pusher) { delete[] m_map_pusher; m_map_pusher = NULL; } //release rolelist if (m_list_role) { spdlog::info("[{}] CSLSManager::stop, release rolelist, size={:d}.", fmt::ptr(this), m_list_role->size()); m_list_role->erase(); delete m_list_role; m_list_role = NULL; } return ret; } int CSLSManager::reload() { spdlog::info("[{}] CSLSManager::reload begin.", fmt::ptr(this)); // stop all listeners for (CSLSListener *server : m_servers) { if (server) { server->uninit(); } } m_servers.clear(); // set all groups reload flag for (CSLSGroup *worker : m_workers) { if (worker) { worker->reload(); } } return 0; } int CSLSManager::check_invalid() { vector<CSLSGroup *>::iterator it; vector<CSLSGroup *>::iterator it_erase; vector<CSLSGroup *>::iterator it_end = m_workers.end(); for (it = m_workers.begin(); it != it_end;) { CSLSGroup *worker = *it; it_erase = it; it++; if (NULL == worker) { m_workers.erase(it_erase); continue; } if (worker->is_exit()) { spdlog::info("[{}] CSLSManager::check_invalid, delete worker={}.", fmt::ptr(this), fmt::ptr(worker)); worker->stop(); worker->uninit_epoll(); delete worker; m_workers.erase(it_erase); } } if (m_workers.size() == 0) return SLS_OK; return SLS_ERROR; } std::string CSLSManager::get_stat_info() { json info_obj; info_obj["stats"] = json::array(); for (CSLSGroup *worker : m_workers) { if (worker) { vector<stat_info_t> worker_info; worker->get_stat_info(worker_info); for (stat_info_t &role_info : worker_info) { info_obj["stats"].push_back(json{ {"port", role_info.port}, {"role", role_info.role}, {"pub_domain_app", role_info.pub_domain_app}, {"stream_name", role_info.stream_name}, {"url", role_info.url}, {"remote_ip", role_info.remote_ip}, {"remote_port", role_info.remote_port}, {"start_time", role_info.start_time}, {"kbitrate", role_info.kbitrate}}); } } } return info_obj.dump(); } int CSLSManager::stat_client_callback(void *p, HTTP_CALLBACK_TYPE type, void *v, void *context) { CSLSManager *manager = (CSLSManager *)context; if (HCT_REQUEST_CONTENT == type) { std::string *p_response = (std::string *)v; p_response->assign(manager->get_stat_info()); } else if (HCT_RESPONSE_END == type) { //response info maybe include info that server send client, such as reload cmd... } else { } return SLS_OK; }
27.116992
114
0.58942
rstular
586e6fa9f3536074c0781d20546a308cc5f1b608
31,226
cpp
C++
partial_digestion/src/uDGP.cpp
shuai-huang/turnpike-beltway
20b68a48b68c2daad02346b1c076c0dce99c4431
[ "Apache-2.0" ]
null
null
null
partial_digestion/src/uDGP.cpp
shuai-huang/turnpike-beltway
20b68a48b68c2daad02346b1c076c0dce99c4431
[ "Apache-2.0" ]
null
null
null
partial_digestion/src/uDGP.cpp
shuai-huang/turnpike-beltway
20b68a48b68c2daad02346b1c076c0dce99c4431
[ "Apache-2.0" ]
1
2020-01-06T17:17:17.000Z
2020-01-06T17:17:17.000Z
#include<chrono> #include "uDGP.h" uDGP::uDGP() { M=0; } void uDGP::SetOutputFile(char* output_file) { output_ite_file = output_file; } void uDGP::SetInitFile(char* init_file) { smp_pos_init_file = init_file; } double uDGP::NormalCdf(double x_val, double mu, double sigma) { return 0.5*(1+erf((x_val-mu)/(sigma*sqrt(2)))); } //bool uDGP::mypair_des_com ( const mypair& l, const mypair& r) { return l.second > r.second; } void uDGP::SetData(DataReader* data_reader) { raw_distribution = data_reader->getDistributionData(); max_distance = 0; for (int i=0; i<num_raw_uq_distance; i++) { double raw_val = raw_distribution[i][0]; if (raw_val>max_distance) { max_distance = raw_val; } } domain_sz = max_distance + 2*tau; M = round(max_distance/min_space_unit) + 1 + 2*round(tau/min_space_unit); // convert raw data to uq_distance and uq_distribution, convolution with the noise distribution // this is used to determine the possible locations for (int i=0; i<num_raw_uq_distance; i++) { double raw_val = raw_distribution[i][0]; if (raw_val==0) { // only keep track of distances between two different points continue; } int raw_distance_idx = round(raw_val/min_space_unit); vector<int> distance_val_approx_seq; distance_val_approx_seq.push_back(raw_distance_idx); for (int j=1; j<=M; j++) { if (j*min_space_unit>tau) { break; } if (((raw_distance_idx-j)*min_space_unit)>=0) { distance_val_approx_seq.push_back(raw_distance_idx-j); } if (((raw_distance_idx+j)*min_space_unit)<=domain_sz) { distance_val_approx_seq.push_back(raw_distance_idx+j); } } for (int j=0; j<distance_val_approx_seq.size(); j++) { int distance_val_approx = distance_val_approx_seq[j]; if (all_distance_diff.find(distance_val_approx)==all_distance_diff.end()) { // contains all the distances to be considered all_distance_diff[distance_val_approx] = 0; } } } } double uDGP::ComputeEstDbt( VectorXd* smp_vec, int distance_val) { double est_dbt_val = 0; //est_dbt_val += ( (*smp_vec).segment(0, M-distance_val).array() * (*smp_vec).segment(distance_val, M-distance_val).array() ).sum(); int j_idx, k_idx; for (int i=0; i<valid_idx_vec.size(); i++) { j_idx = valid_idx_vec[i]; k_idx = j_idx + distance_val; if (k_idx<=M-1) { est_dbt_val += (*smp_vec)(j_idx) * (*smp_vec)(k_idx); } } return est_dbt_val; } void uDGP::ComputeEstProj(VectorXd* smp_vec, VectorXd* smp_vec_proj, double mut_factor, int distance_val) { //(*smp_vec_proj).segment(0, M-distance_val) += mut_factor * (*smp_vec).segment(distance_val, M-distance_val); //(*smp_vec_proj).segment(distance_val, M-distance_val) += mut_factor * (*smp_vec).segment(0, M-distance_val); int j_idx, k_idx, l_idx; for (int i=0; i<valid_idx_vec.size(); i++) { j_idx = valid_idx_vec[i]; k_idx = j_idx + distance_val; l_idx = j_idx - distance_val; if (k_idx<=M-1) { (*smp_vec_proj)(j_idx) += mut_factor * (*smp_vec)(k_idx); } if (l_idx>=0) { (*smp_vec_proj)(j_idx) += mut_factor * (*smp_vec)(l_idx); } } } void uDGP::SetMeasureMatrix() { // set measurement matrix and the all_distribution // set the two anchor points indices corresponding to the two outmost points anchor_one = round(tau/min_space_unit); // the index starts from 0, there are round(tau/min_space_unit) segments to the left anchor_two = anchor_one + round(max_distance/min_space_unit); int dist_val_tmp_1, dist_val_tmp_2; // Put the anchor point positions // Find valid idx positions valid_idx_pos = VectorXd::Zero(M); for (int i=0; i<(anchor_one+round(tau/min_space_unit)+1); i++) { anchor_one_seq[i]=0; valid_idx_pos[i]=1; valid_idx_vec.push_back(i); } for (int i=anchor_two-round(tau/min_space_unit); i<(anchor_two+round(tau/min_space_unit)+1); i++) { anchor_two_seq[i]=0; valid_idx_pos[i]=1; valid_idx_vec.push_back(i); } for (int i=anchor_one+1; i<anchor_two; i++) { // distance to first anchor point dist_val_tmp_1 = abs(i-anchor_one); // distance to second anchor point dist_val_tmp_2 = abs(i-anchor_two); if ( ( all_distance_diff.find(dist_val_tmp_1)!=all_distance_diff.end() ) && ( all_distance_diff.find(dist_val_tmp_2)!=all_distance_diff.end() ) ) { if ( (anchor_one_seq.find(i)==anchor_one_seq.end()) && (anchor_two_seq.find(i)==anchor_two_seq.end()) ) { valid_idx_pos[i]=1; valid_idx_vec.push_back(i); valid_idx_vec_exclude.push_back(i); } } } num_pos = valid_idx_vec.size(); cout<<"Number of valid index: "<<valid_idx_vec.size()<<endl; cout<<"Number of anchor one: "<<anchor_one_seq.size()<<endl; cout<<"Number of anchor two: "<<anchor_two_seq.size()<<endl; // Find all possible distances in the domain all_distribution[0]=0; all_distance.push_back(0); int distance_val_tmp; for (int i=0; i<num_pos; i++) { for (int j=i+1; j<num_pos; j++) { distance_val_tmp = abs(valid_idx_vec[i]-valid_idx_vec[j]); // In the noiseless case, only consider the distances that appear in the measurements if (all_distance_diff.find(distance_val_tmp)==all_distance_diff.end()) { continue; } if ( all_distribution.find(distance_val_tmp)==all_distribution.end() ) { all_distribution[distance_val_tmp]=0; all_distance.push_back(distance_val_tmp); } } } cout<<"Valid distance size: "<<all_distance.size()<<endl; cout<<"Distribution size: "<<all_distribution.size()<<endl; // approximate the oracle distance distribution for (int i=0; i<num_raw_uq_distance; i++) { double raw_val = raw_distribution[i][0]; map<int, double> prob_cov; double prob_cov_sum = 0; int raw_distance_idx = round(raw_val/min_space_unit); vector<int> distance_val_approx_seq; if (all_distribution.find(raw_distance_idx)!=all_distribution.end()) { distance_val_approx_seq.push_back(raw_distance_idx); if (raw_distance_idx==0) { prob_cov[raw_distance_idx] = 2*(NormalCdf( (raw_distance_idx+0.5)*min_space_unit, raw_val, sigma) - NormalCdf( (raw_distance_idx)*min_space_unit, raw_val, sigma) ); } else { prob_cov[raw_distance_idx] = NormalCdf( (raw_distance_idx+0.5)*min_space_unit, raw_val, sigma) - NormalCdf( (raw_distance_idx-0.5)*min_space_unit, raw_val, sigma); } prob_cov_sum += prob_cov[raw_distance_idx]; } for (int j=1; j<M; j++) { if (j*min_space_unit>tau) { break; } if (all_distribution.find(raw_distance_idx-j)!=all_distribution.end()) { distance_val_approx_seq.push_back(raw_distance_idx-j); prob_cov[raw_distance_idx-j] = NormalCdf( (raw_distance_idx-j+0.5)*min_space_unit, raw_val, sigma) - NormalCdf( (raw_distance_idx-j-0.5)*min_space_unit, raw_val, sigma ); prob_cov_sum += prob_cov[raw_distance_idx-j]; } if (all_distribution.find(raw_distance_idx+j)!=all_distribution.end()) { distance_val_approx_seq.push_back(raw_distance_idx+j); prob_cov[raw_distance_idx+j] = NormalCdf( (raw_distance_idx+j+0.5)*min_space_unit, raw_val, sigma) - NormalCdf( (raw_distance_idx+j-0.5)*min_space_unit, raw_val, sigma ); prob_cov_sum += prob_cov[raw_distance_idx+j]; } } prob_cov_sum = 1; for (int j=0; j<distance_val_approx_seq.size(); j++) { int distance_val_approx = distance_val_approx_seq[j]; prob_cov[distance_val_approx] = prob_cov[distance_val_approx]/prob_cov_sum; double distribution_val_tmp = prob_cov[distance_val_approx]*raw_distribution[i][1]; all_distribution[distance_val_approx] += distribution_val_tmp; } } cout<<"No. of raw uq sq distance: "<<raw_distribution.size()<<endl; cout<<"Distribution size: "<<all_distribution.size()<<"\t"<<all_distance.size()<<endl; // sort the all_distance sort(all_distance.begin(), all_distance.end()); // count the number of blocks for each unique distance, this is for the multi-threading program for (int i=0; i<all_distance.size(); i++) { all_block_count.push_back({all_distance[i], 1}); } // sort the all_distance according to the block_count sort(all_block_count.begin(), all_block_count.end(), []( const mypair& l, const mypair& r) { return l.second > r.second; }); num_thread_assign = num_thread > all_distance.size() ? all_distance.size() : num_thread; vector<int> all_partition_sz(num_thread_assign,0); for (int i=0; i<all_block_count.size(); i++) { int idx_min=distance( all_partition_sz.begin(), min_element(all_partition_sz.begin(), all_partition_sz.end()) ); all_partition[idx_min].push_back(all_block_count[i].first); all_partition_sz[idx_min] += all_block_count[i].second; } // initialize the estimated sq distributin here *** for (int i=0; i<all_distance.size(); i++) { est_distribution[all_distance[i]] = 0; } cout<<"Multithreading assignment stats: "; for (int i=0; i<all_partition_sz.size(); i++) { cout<<all_partition_sz[i]<<"\t"; } cout<<endl; cout<<"Setting measurement matrices finished."<<endl; } void uDGP::Initialization() { smp_pos_init = VectorXd::Zero(M); if (init_type==1) { // initialization with leading eigenvector // Compute the two anchor points for (map<int, double>::iterator ite=anchor_one_seq.begin(); ite!=anchor_one_seq.end(); ite++) { int distance_val_tmp = ite->first; anchor_one_seq[ite->first] = NormalCdf( (distance_val_tmp+0.5)*min_space_unit, anchor_one*min_space_unit, sigma/sqrt(2)) - NormalCdf( (distance_val_tmp-0.5)*min_space_unit, anchor_one*min_space_unit, sigma/sqrt(2) ); } for (map<int, double>::iterator ite=anchor_two_seq.begin(); ite!=anchor_two_seq.end(); ite++) { int distance_val_tmp = ite->first; anchor_two_seq[ite->first] = NormalCdf( (distance_val_tmp+0.5)*min_space_unit, anchor_two*min_space_unit, sigma/sqrt(2)) - NormalCdf( (distance_val_tmp-0.5)*min_space_unit, anchor_two*min_space_unit, sigma/sqrt(2) ); } // use the probability vector as the initializer int row_idx, col_idx; for (int i=0; i<all_distance.size(); i++) { VectorXd smp_pos_init_tmp = VectorXd::Zero(M); smp_pos_init_tmp.segment(0, M-all_distance[i]).array() += valid_idx_pos.segment(0, M-all_distance[i]).array() * valid_idx_pos.segment(all_distance[i], M-all_distance[i]).array(); D_mat_norm[all_distance[i]] = sqrt(smp_pos_init_tmp.sum()); smp_pos_init_tmp *= all_distribution[all_distance[i]] / smp_pos_init_tmp.sum(); smp_pos_init += smp_pos_init_tmp; } // Put the two anchor points for (map<int, double>::iterator ite=anchor_one_seq.begin(); ite!=anchor_one_seq.end(); ite++) { smp_pos_init[ite->first] = anchor_one_seq[ite->first]; } for (map<int, double>::iterator ite=anchor_two_seq.begin(); ite!=anchor_two_seq.end(); ite++) { smp_pos_init[ite->first] = anchor_two_seq[ite->first]; } // Sum up the points other than the two anchor points and then normalize double smp_pos_init_exclude_sum = smp_pos_init.segment((anchor_one+round(tau/min_space_unit)+1), M-(4*round(tau/min_space_unit)+2)).sum(); smp_pos_init.segment((anchor_one+round(tau/min_space_unit)+1), M-(4*round(tau/min_space_unit)+2)) = smp_pos_init.segment((anchor_one+round(tau/min_space_unit)+1), M-(4*round(tau/min_space_unit)+2)) / smp_pos_init_exclude_sum * (num_smp-2); VectorXd smp_pos_init_reverse = smp_pos_init.reverse(); smp_pos_init = 0.5 * (smp_pos_init + smp_pos_init_reverse); obj_val = ComputeObjFun(smp_pos_init); cout<<"Obj_val: "<<obj_val<<endl; // use power method to compute the singular vector for (int ite=0; ite<max_sg_ite; ite++) { VectorXd smp_pos_init_pre = smp_pos_init; VectorXd smp_pos_init_tmp = VectorXd::Zero(M); for (int i=0; i<all_distance.size(); i++) { smp_pos_init_tmp.segment(0, M-all_distance[i]) += all_distribution[all_distance[i]] / pow(D_mat_norm[all_distance[i]], 2) * smp_pos_init_pre.segment(all_distance[i], M-all_distance[i]); smp_pos_init_tmp.segment(all_distance[i], M-all_distance[i]) += all_distribution[all_distance[i]] / pow(D_mat_norm[all_distance[i]], 2) * smp_pos_init_pre.segment(0, M-all_distance[i]); } smp_pos_init = VectorXd::Zero(M); for (int i=0; i<valid_idx_vec.size(); i++) { smp_pos_init(valid_idx_vec[i]) = smp_pos_init_tmp(valid_idx_vec[i]); } double smp_pos_init_norm = smp_pos_init.norm(); smp_pos_init = smp_pos_init/smp_pos_init_norm; double sg_cvg_val = (smp_pos_init-smp_pos_init_pre).norm(); cout<<ite<<" "<<sg_cvg_val<<endl; if (sg_cvg_val<sg_tol) { cout<<"Eig_iteration: "<<ite<<endl; break; } } smp_pos_init = smp_pos_init * sqrt(num_smp*1.0); // break even unsigned seed = std::chrono::steady_clock::now().time_since_epoch().count(); default_random_engine generator(seed); normal_distribution<double> distribution(0, perturb_std); for (int i=0; i<M; i++) { smp_pos_init(i) = smp_pos_init(i) * (1+distribution(generator)); } // map the initialization onto the convex set // Put the two anchor points for (map<int, double>::iterator ite=anchor_one_seq.begin(); ite!=anchor_one_seq.end(); ite++) { smp_pos_init[ite->first] = 0; } for (map<int, double>::iterator ite=anchor_two_seq.begin(); ite!=anchor_two_seq.end(); ite++) { smp_pos_init[ite->first] = 0; } for (map<int, double>::iterator ite=anchor_one_seq.begin(); ite!=anchor_one_seq.end(); ite++) { smp_pos_init[ite->first] += anchor_one_seq[ite->first]; } for (map<int, double>::iterator ite=anchor_two_seq.begin(); ite!=anchor_two_seq.end(); ite++) { smp_pos_init[ite->first] += anchor_two_seq[ite->first]; } // Project on to the l1-ball with box constraints VectorXd smp_pos_seg_tmp = VectorXd::Zero(valid_idx_vec_exclude.size()); for (int i=0; i<valid_idx_vec_exclude.size(); i++) { smp_pos_seg_tmp(i) = smp_pos_init(valid_idx_vec_exclude[i]); } smp_pos_seg_tmp = ProjectOntoCvxSet(smp_pos_seg_tmp, num_smp-2); for (int i=0; i<valid_idx_vec_exclude.size(); i++) { smp_pos_init(valid_idx_vec_exclude[i]) = smp_pos_seg_tmp(i); } obj_val = ComputeObjFun(smp_pos_init); cout<<"Obj val: "<<obj_val<<endl; } else if (init_type==2) { // initialize with random vector unsigned seed = std::chrono::steady_clock::now().time_since_epoch().count(); default_random_engine generator(seed); normal_distribution<double> distribution(0, perturb_std); for (int i=0; i<M; i++) { smp_pos_init(i) = abs(distribution(generator)); } // Compute the two anchor points for (map<int, double>::iterator ite=anchor_one_seq.begin(); ite!=anchor_one_seq.end(); ite++) { int distance_val_tmp = ite->first; if ( ( distance_val_tmp >= (M-round(3*sigma/min_space_unit)) ) && ( distance_val_tmp <= M-1 ) ) { anchor_one_seq[ite->first] += NormalCdf( (distance_val_tmp+0.5)*min_space_unit, M*min_space_unit, sigma/sqrt(2)) - NormalCdf( (distance_val_tmp-0.5)*min_space_unit, M*min_space_unit, sigma/sqrt(2) ); } else { anchor_one_seq[ite->first] += NormalCdf( (distance_val_tmp+0.5)*min_space_unit, anchor_one*min_space_unit, sigma/sqrt(2)) - NormalCdf( (distance_val_tmp-0.5)*min_space_unit, anchor_one*min_space_unit, sigma/sqrt(2) ); } } for (map<int, double>::iterator ite=anchor_two_seq.begin(); ite!=anchor_two_seq.end(); ite++) { int distance_val_tmp = ite->first; if ( (distance_val_tmp >= 0) && (distance_val_tmp<=round(3*sigma/min_space_unit)) ) { anchor_two_seq[ite->first] += NormalCdf( (M+distance_val_tmp+0.5)*min_space_unit, anchor_two*min_space_unit, sigma/sqrt(2)) - NormalCdf( (M+distance_val_tmp-0.5)*min_space_unit, anchor_two*min_space_unit, sigma/sqrt(2) ); } else { anchor_two_seq[ite->first] += NormalCdf( (distance_val_tmp+0.5)*min_space_unit, anchor_two*min_space_unit, sigma/sqrt(2)) - NormalCdf( (distance_val_tmp-0.5)*min_space_unit, anchor_two*min_space_unit, sigma/sqrt(2) ); } } // Put the two anchor points for (map<int, double>::iterator ite=anchor_one_seq.begin(); ite!=anchor_one_seq.end(); ite++) { smp_pos_init[ite->first] = 0; } for (map<int, double>::iterator ite=anchor_two_seq.begin(); ite!=anchor_two_seq.end(); ite++) { smp_pos_init[ite->first] = 0; } for (map<int, double>::iterator ite=anchor_one_seq.begin(); ite!=anchor_one_seq.end();ite++) { smp_pos_init[ite->first] += anchor_one_seq[ite->first]; } for (map<int, double>::iterator ite=anchor_two_seq.begin(); ite!=anchor_two_seq.end();ite++) { smp_pos_init[ite->first] += anchor_two_seq[ite->first]; } // map the initialization onto the convex set // Put the two anchor points for (map<int, double>::iterator ite=anchor_one_seq.begin(); ite!=anchor_one_seq.end(); ite++) { smp_pos_init[ite->first] = 0; } for (map<int, double>::iterator ite=anchor_two_seq.begin(); ite!=anchor_two_seq.end(); ite++) { smp_pos_init[ite->first] = 0; } for (map<int, double>::iterator ite=anchor_one_seq.begin(); ite!=anchor_one_seq.end(); ite++) { smp_pos_init[ite->first] += anchor_one_seq[ite->first]; } for (map<int, double>::iterator ite=anchor_two_seq.begin(); ite!=anchor_two_seq.end(); ite++) { smp_pos_init[ite->first] += anchor_two_seq[ite->first]; } // Project on to the l1-ball with box constraints VectorXd smp_pos_seg_tmp = VectorXd::Zero(valid_idx_vec_exclude.size()); for (int i=0; i<valid_idx_vec_exclude.size(); i++) { smp_pos_seg_tmp(i) = smp_pos_init(valid_idx_vec_exclude[i]); } smp_pos_seg_tmp = ProjectOntoCvxSet(smp_pos_seg_tmp, num_smp-2); for (int i=0; i<valid_idx_vec_exclude.size(); i++) { smp_pos_init(valid_idx_vec_exclude[i]) = smp_pos_seg_tmp(i); } //obj_val = ComputeObjFun(smp_pos_init); obj_val = 0; cout<<"Obj val: "<<obj_val<<endl; } else if (init_type==3) { // initialize with uniform vector smp_pos_init = VectorXd::Ones(M); // Compute the two anchor points for (map<int, double>::iterator ite=anchor_one_seq.begin(); ite!=anchor_one_seq.end(); ite++) { int distance_val_tmp = ite->first; if ( ( distance_val_tmp >= (M-round(3*sigma/min_space_unit)) ) && ( distance_val_tmp <= M-1 ) ) { anchor_one_seq[ite->first] += NormalCdf( (distance_val_tmp+0.5)*min_space_unit, M*min_space_unit, sigma/sqrt(2)) - NormalCdf( (distance_val_tmp-0.5)*min_space_unit, M*min_space_unit, sigma/sqrt(2) ); } else { anchor_one_seq[ite->first] += NormalCdf( (distance_val_tmp+0.5)*min_space_unit, anchor_one*min_space_unit, sigma/sqrt(2)) - NormalCdf( (distance_val_tmp-0.5)*min_space_unit, anchor_one*min_space_unit, sigma/sqrt(2) ); } } for (map<int, double>::iterator ite=anchor_two_seq.begin(); ite!=anchor_two_seq.end(); ite++) { int distance_val_tmp = ite->first; if ( (distance_val_tmp >= 0) && (distance_val_tmp<=round(3*sigma/min_space_unit)) ) { anchor_two_seq[ite->first] += NormalCdf( (M+distance_val_tmp+0.5)*min_space_unit, anchor_two*min_space_unit, sigma/sqrt(2)) - NormalCdf( (M+distance_val_tmp-0.5)*min_space_unit, anchor_two*min_space_unit, sigma/sqrt(2) ); } else { anchor_two_seq[ite->first] += NormalCdf( (distance_val_tmp+0.5)*min_space_unit, anchor_two*min_space_unit, sigma/sqrt(2)) - NormalCdf( (distance_val_tmp-0.5)*min_space_unit, anchor_two*min_space_unit, sigma/sqrt(2) ); } } // Put the two anchor points for (map<int, double>::iterator ite=anchor_one_seq.begin(); ite!=anchor_one_seq.end(); ite++) { smp_pos_init[ite->first] = 0; } for (map<int, double>::iterator ite=anchor_two_seq.begin(); ite!=anchor_two_seq.end(); ite++) { smp_pos_init[ite->first] = 0; } for (map<int, double>::iterator ite=anchor_one_seq.begin(); ite!=anchor_one_seq.end();ite++) { smp_pos_init[ite->first] += anchor_one_seq[ite->first]; } for (map<int, double>::iterator ite=anchor_two_seq.begin(); ite!=anchor_two_seq.end();ite++) { smp_pos_init[ite->first] += anchor_two_seq[ite->first]; } // break even unsigned seed = std::chrono::steady_clock::now().time_since_epoch().count(); default_random_engine generator(seed); normal_distribution<double> distribution(0, perturb_std); for (int i=0; i<M; i++) { smp_pos_init(i) = smp_pos_init(i) * (1+distribution(generator)); } // map the initialization onto the convex set // Put the two anchor points for (map<int, double>::iterator ite=anchor_one_seq.begin(); ite!=anchor_one_seq.end(); ite++) { smp_pos_init[ite->first] = 0; } for (map<int, double>::iterator ite=anchor_two_seq.begin(); ite!=anchor_two_seq.end(); ite++) { smp_pos_init[ite->first] = 0; } for (map<int, double>::iterator ite=anchor_one_seq.begin(); ite!=anchor_one_seq.end(); ite++) { smp_pos_init[ite->first] += anchor_one_seq[ite->first]; } for (map<int, double>::iterator ite=anchor_two_seq.begin(); ite!=anchor_two_seq.end(); ite++) { smp_pos_init[ite->first] += anchor_two_seq[ite->first]; } // Project on to the l1-ball with box constraints VectorXd smp_pos_seg_tmp = VectorXd::Zero(valid_idx_vec_exclude.size()); for (int i=0; i<valid_idx_vec_exclude.size(); i++) { smp_pos_seg_tmp(i) = smp_pos_init(valid_idx_vec_exclude[i]); } smp_pos_seg_tmp = ProjectOntoCvxSet(smp_pos_seg_tmp, num_smp-2); for (int i=0; i<valid_idx_vec_exclude.size(); i++) { smp_pos_init(valid_idx_vec_exclude[i]) = smp_pos_seg_tmp(i); } obj_val = ComputeObjFun(smp_pos_init); cout<<"Obj val: "<<obj_val<<endl; } else { cout<<"Unknown initialization type."<<endl; abort(); } cout<<"Initialization finished."<<endl; } VectorXd uDGP::ProjectOntoCvxSet(VectorXd smp_vec, int num_smp_proj) { // make sure all the entries of v are above the convex set // Note that the vector index starts from 0 double offset = -smp_vec.array().minCoeff() + num_smp_proj; smp_vec = smp_vec.array() + offset; VectorXd smp_sort_vec = smp_vec; sort(smp_sort_vec.data(), smp_sort_vec.data()+smp_sort_vec.size(), greater<double>()); int smp_vec_len=smp_sort_vec.size(); double theta = 0; int check_status = 0; for (int r=1; r<=num_smp_proj; r++) { VectorXd smp_sort_vec_new = smp_sort_vec.segment(r-1, smp_vec_len-r+1); VectorXd smp_sort_vec_new_cumsum = smp_sort_vec_new; for (int j=1; j<smp_sort_vec_new_cumsum.size(); j++) { smp_sort_vec_new_cumsum(j) += smp_sort_vec_new_cumsum(j-1); } VectorXd smp_sort_vec_new_thr = smp_sort_vec_new_cumsum; for (int j=0; j<smp_sort_vec_new_thr.size(); j++) { smp_sort_vec_new_thr(j) = smp_sort_vec_new(j) - (smp_sort_vec_new_thr(j)-(num_smp_proj-r+1))/(j+1); } int rho_new = -1; for (int j=smp_sort_vec_new_thr.size()-1; j>=0; j--) { if (smp_sort_vec_new_thr(j)>0) { rho_new = j+1; // Note that the vector index starts from 0, we need to add 1 here break; } } if (rho_new==-1) {break;} // check that rho = rho_new+r-1 is larger than num_smp_proj if (rho_new+r-1<=num_smp_proj) {continue;} // Compute the threshold double theta_new = (smp_sort_vec_new_cumsum(rho_new-1)-(num_smp_proj-r+1))/rho_new; int break_marker = 0; double w_r = smp_sort_vec(r-1)-theta_new; if ( (w_r>0) && (w_r<1) ) { if (r==1) { break_marker = 1; check_status = 1; } else { double w_rm1 = smp_sort_vec(r-2)-theta_new ; if (w_rm1>=1) { break_marker=1; check_status=1; } } } else { continue; } theta = theta_new; if (break_marker==1) { break; } } VectorXd smp_vec_proj = smp_vec; if (check_status==1) { smp_vec_proj = smp_vec.array() - theta; for (int i=0; i<smp_vec_len; i++) { if (smp_vec_proj(i)<0) { smp_vec_proj(i)=0; } if (smp_vec_proj(i)>1) { smp_vec_proj(i)=1; } } } else { // set the top N entries to 1 and the rest to 0 double thd_tmp = smp_sort_vec(num_smp_proj-1); for (int i=0; i<smp_vec_len; i++) { if (smp_vec_proj(i)>=thd_tmp) { smp_vec_proj(i)=1; } else { smp_vec_proj(i)=0; } } } return smp_vec_proj; } void uDGP::GradientDescent() { smp_pos = smp_pos_init; step = step_ori; obj_val = ComputeObjFun(smp_pos); VectorXd smp_pos_pre; double obj_val_pre; int ite; int num_cov = 0; for (ite=1; ite<max_ite; ite++) { //for (int i=0; i<all_distance.size(); i++) { // if (all_distribution[all_distance[i]]>0) { // cout<<all_distance[i]<<" "<<all_distribution[all_distance[i]]<<" "<<est_distribution[all_distance[i]]<<" "; // } //} //cout<<endl; smp_pos_pre = smp_pos; obj_val_pre = obj_val; VectorXd smp_pos_der = ComputeGradient(smp_pos_pre); smp_pos_der = smp_pos_der.array() - smp_pos_der.sum()/M; VectorXd smp_pos_tmp = VectorXd::Zero(M); while (step>step_thd) { smp_pos_tmp = smp_pos_pre-smp_pos_der*step; VectorXd smp_pos_seg_tmp = VectorXd::Zero(valid_idx_vec_exclude.size()); for (int i=0; i<valid_idx_vec_exclude.size(); i++) { smp_pos_seg_tmp(i) = smp_pos_tmp(valid_idx_vec_exclude[i]); } smp_pos_tmp = VectorXd::Zero(M); smp_pos_seg_tmp = ProjectOntoCvxSet(smp_pos_seg_tmp, num_smp-2); for (int i=0; i<valid_idx_vec_exclude.size(); i++) { smp_pos_tmp(valid_idx_vec_exclude[i]) = smp_pos_seg_tmp(i); } // Put the two anchor points for (map<int, double>::iterator ite=anchor_one_seq.begin(); ite!=anchor_one_seq.end(); ite++) { smp_pos_tmp[ite->first] = anchor_one_seq[ite->first]; } for (map<int, double>::iterator ite=anchor_two_seq.begin(); ite!=anchor_two_seq.end(); ite++) { smp_pos_tmp[ite->first] = anchor_two_seq[ite->first]; } obj_val = ComputeObjFun(smp_pos_tmp); if ((obj_val<obj_val_pre)||(obj_val==0)) { step = step/bkt_rate; break; } else { step = step*bkt_rate; } } if (step<=step_thd) { cout<<"Step size too small!" << "\t"<<step<<"\t"<<smp_pos_tmp.sum()<<"\t"<<num_smp<<endl; break; } smp_pos = smp_pos_tmp; VectorXd smp_pos_diff = smp_pos - smp_pos_pre; double cvg_val = smp_pos_diff.norm() / smp_pos.norm(); if (cvg_val<cvg_thd) { num_cov += 1; } if (num_cov>=10) { cout<<"Convergence reached!"<<endl; break; } // Save the results at each iteration // choose between the trunc and app mode when saving the results //ofstream write_result(output_ite_file, ios_base::trunc); //ofstream write_result(output_ite_file, ios_base::app); //write_result<<obj_val<<" "; //for (int i=0; i<smp_pos.size(); i++) { // write_result<<smp_pos(i)<<" "; //} //write_result<<"\n"; //write_result.close(); cout<<"Ite: "<<ite<<"\t"<<step<<"\t"<<obj_val<<"\t"<<cvg_val<<"\t"<<smp_pos.sum()<<endl; } if (ite>=max_ite) { cout<<"Max iteration reached!"<<endl; } } VectorXd uDGP::ComputeGradient(VectorXd smp_pos_vect) {return VectorXd::Zero(1);} void uDGP::ComputeGradientMuti( vector<int> all_distance_block, VectorXd* smp_vec_muti, VectorXd* smp_der_seq_pt, int val_idx ) {} double uDGP::ComputeObjFun(VectorXd smp_pos_vect) { return 0.0;} void uDGP::ComputeObjFunMuti(vector<int> all_distance_block, VectorXd* smp_vec_muti, vector<double>* obj_seq_pt, int val_idx ) {} VectorXd uDGP::GetSamplePos() {return smp_pos;} double uDGP::GetObjFun() {return obj_val;} uDGP::~uDGP() {}
41.801874
247
0.600749
shuai-huang
5871ec92b26b8a28353bb7b4803321901bae76f4
32,269
hpp
C++
Sources/SolarTears/Rendering/Vulkan/VulkanFunctions.hpp
Sixshaman/SolarTears
97d07730f876508fce8bf93c9dc90f051c230580
[ "BSD-3-Clause" ]
4
2021-06-30T16:00:20.000Z
2021-10-13T06:17:56.000Z
Sources/SolarTears/Rendering/Vulkan/VulkanFunctions.hpp
Sixshaman/SolarTears
97d07730f876508fce8bf93c9dc90f051c230580
[ "BSD-3-Clause" ]
null
null
null
Sources/SolarTears/Rendering/Vulkan/VulkanFunctions.hpp
Sixshaman/SolarTears
97d07730f876508fce8bf93c9dc90f051c230580
[ "BSD-3-Clause" ]
null
null
null
#pragma once #include <vulkan/vulkan.h> #ifdef VK_NO_PROTOTYPES #define DECLARE_VULKAN_FUNCTION(funcName) extern PFN_##funcName funcName; extern "C" { DECLARE_VULKAN_FUNCTION(vkCreateInstance) DECLARE_VULKAN_FUNCTION(vkDestroyInstance) DECLARE_VULKAN_FUNCTION(vkEnumeratePhysicalDevices) DECLARE_VULKAN_FUNCTION(vkGetDeviceProcAddr) DECLARE_VULKAN_FUNCTION(vkGetInstanceProcAddr) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDeviceProperties) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDeviceQueueFamilyProperties) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDeviceMemoryProperties) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDeviceFeatures) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDeviceFormatProperties) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDeviceImageFormatProperties) DECLARE_VULKAN_FUNCTION(vkCreateDevice) DECLARE_VULKAN_FUNCTION(vkDestroyDevice) DECLARE_VULKAN_FUNCTION(vkEnumerateInstanceVersion) DECLARE_VULKAN_FUNCTION(vkEnumerateInstanceLayerProperties) DECLARE_VULKAN_FUNCTION(vkEnumerateInstanceExtensionProperties) DECLARE_VULKAN_FUNCTION(vkEnumerateDeviceLayerProperties) DECLARE_VULKAN_FUNCTION(vkEnumerateDeviceExtensionProperties) DECLARE_VULKAN_FUNCTION(vkGetDeviceQueue) DECLARE_VULKAN_FUNCTION(vkQueueSubmit) DECLARE_VULKAN_FUNCTION(vkQueueWaitIdle) DECLARE_VULKAN_FUNCTION(vkDeviceWaitIdle) DECLARE_VULKAN_FUNCTION(vkAllocateMemory) DECLARE_VULKAN_FUNCTION(vkFreeMemory) DECLARE_VULKAN_FUNCTION(vkMapMemory) DECLARE_VULKAN_FUNCTION(vkUnmapMemory) DECLARE_VULKAN_FUNCTION(vkFlushMappedMemoryRanges) DECLARE_VULKAN_FUNCTION(vkInvalidateMappedMemoryRanges) DECLARE_VULKAN_FUNCTION(vkGetDeviceMemoryCommitment) DECLARE_VULKAN_FUNCTION(vkGetBufferMemoryRequirements) DECLARE_VULKAN_FUNCTION(vkBindBufferMemory) DECLARE_VULKAN_FUNCTION(vkGetImageMemoryRequirements) DECLARE_VULKAN_FUNCTION(vkBindImageMemory) DECLARE_VULKAN_FUNCTION(vkGetImageSparseMemoryRequirements) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDeviceSparseImageFormatProperties) DECLARE_VULKAN_FUNCTION(vkQueueBindSparse) DECLARE_VULKAN_FUNCTION(vkCreateFence) DECLARE_VULKAN_FUNCTION(vkDestroyFence) DECLARE_VULKAN_FUNCTION(vkResetFences) DECLARE_VULKAN_FUNCTION(vkGetFenceStatus) DECLARE_VULKAN_FUNCTION(vkWaitForFences) DECLARE_VULKAN_FUNCTION(vkCreateSemaphore) DECLARE_VULKAN_FUNCTION(vkDestroySemaphore) DECLARE_VULKAN_FUNCTION(vkCreateEvent) DECLARE_VULKAN_FUNCTION(vkDestroyEvent) DECLARE_VULKAN_FUNCTION(vkGetEventStatus) DECLARE_VULKAN_FUNCTION(vkSetEvent) DECLARE_VULKAN_FUNCTION(vkResetEvent) DECLARE_VULKAN_FUNCTION(vkCreateQueryPool) DECLARE_VULKAN_FUNCTION(vkDestroyQueryPool) DECLARE_VULKAN_FUNCTION(vkGetQueryPoolResults) DECLARE_VULKAN_FUNCTION(vkResetQueryPool) DECLARE_VULKAN_FUNCTION(vkCreateBuffer) DECLARE_VULKAN_FUNCTION(vkDestroyBuffer) DECLARE_VULKAN_FUNCTION(vkCreateBufferView) DECLARE_VULKAN_FUNCTION(vkDestroyBufferView) DECLARE_VULKAN_FUNCTION(vkCreateImage) DECLARE_VULKAN_FUNCTION(vkDestroyImage) DECLARE_VULKAN_FUNCTION(vkGetImageSubresourceLayout) DECLARE_VULKAN_FUNCTION(vkCreateImageView) DECLARE_VULKAN_FUNCTION(vkDestroyImageView) DECLARE_VULKAN_FUNCTION(vkCreateShaderModule) DECLARE_VULKAN_FUNCTION(vkDestroyShaderModule) DECLARE_VULKAN_FUNCTION(vkCreatePipelineCache) DECLARE_VULKAN_FUNCTION(vkDestroyPipelineCache) DECLARE_VULKAN_FUNCTION(vkGetPipelineCacheData) DECLARE_VULKAN_FUNCTION(vkMergePipelineCaches) DECLARE_VULKAN_FUNCTION(vkCreateGraphicsPipelines) DECLARE_VULKAN_FUNCTION(vkCreateComputePipelines) DECLARE_VULKAN_FUNCTION(vkDestroyPipeline) DECLARE_VULKAN_FUNCTION(vkCreatePipelineLayout) DECLARE_VULKAN_FUNCTION(vkDestroyPipelineLayout) DECLARE_VULKAN_FUNCTION(vkCreateSampler) DECLARE_VULKAN_FUNCTION(vkDestroySampler) DECLARE_VULKAN_FUNCTION(vkCreateDescriptorSetLayout) DECLARE_VULKAN_FUNCTION(vkDestroyDescriptorSetLayout) DECLARE_VULKAN_FUNCTION(vkCreateDescriptorPool) DECLARE_VULKAN_FUNCTION(vkDestroyDescriptorPool) DECLARE_VULKAN_FUNCTION(vkResetDescriptorPool) DECLARE_VULKAN_FUNCTION(vkAllocateDescriptorSets) DECLARE_VULKAN_FUNCTION(vkFreeDescriptorSets) DECLARE_VULKAN_FUNCTION(vkUpdateDescriptorSets) DECLARE_VULKAN_FUNCTION(vkCreateFramebuffer) DECLARE_VULKAN_FUNCTION(vkDestroyFramebuffer) DECLARE_VULKAN_FUNCTION(vkCreateRenderPass) DECLARE_VULKAN_FUNCTION(vkDestroyRenderPass) DECLARE_VULKAN_FUNCTION(vkGetRenderAreaGranularity) DECLARE_VULKAN_FUNCTION(vkCreateCommandPool) DECLARE_VULKAN_FUNCTION(vkDestroyCommandPool) DECLARE_VULKAN_FUNCTION(vkResetCommandPool) DECLARE_VULKAN_FUNCTION(vkAllocateCommandBuffers) DECLARE_VULKAN_FUNCTION(vkFreeCommandBuffers) DECLARE_VULKAN_FUNCTION(vkBeginCommandBuffer) DECLARE_VULKAN_FUNCTION(vkEndCommandBuffer) DECLARE_VULKAN_FUNCTION(vkResetCommandBuffer) DECLARE_VULKAN_FUNCTION(vkCmdBindPipeline) DECLARE_VULKAN_FUNCTION(vkCmdSetViewport) DECLARE_VULKAN_FUNCTION(vkCmdSetScissor) DECLARE_VULKAN_FUNCTION(vkCmdSetLineWidth) DECLARE_VULKAN_FUNCTION(vkCmdSetDepthBias) DECLARE_VULKAN_FUNCTION(vkCmdSetBlendConstants) DECLARE_VULKAN_FUNCTION(vkCmdSetDepthBounds) DECLARE_VULKAN_FUNCTION(vkCmdSetStencilCompareMask) DECLARE_VULKAN_FUNCTION(vkCmdSetStencilWriteMask) DECLARE_VULKAN_FUNCTION(vkCmdSetStencilReference) DECLARE_VULKAN_FUNCTION(vkCmdBindDescriptorSets) DECLARE_VULKAN_FUNCTION(vkCmdBindIndexBuffer) DECLARE_VULKAN_FUNCTION(vkCmdBindVertexBuffers) DECLARE_VULKAN_FUNCTION(vkCmdDraw) DECLARE_VULKAN_FUNCTION(vkCmdDrawIndexed) DECLARE_VULKAN_FUNCTION(vkCmdDrawIndirect) DECLARE_VULKAN_FUNCTION(vkCmdDrawIndexedIndirect) DECLARE_VULKAN_FUNCTION(vkCmdDispatch) DECLARE_VULKAN_FUNCTION(vkCmdDispatchIndirect) DECLARE_VULKAN_FUNCTION(vkCmdCopyBuffer) DECLARE_VULKAN_FUNCTION(vkCmdCopyImage) DECLARE_VULKAN_FUNCTION(vkCmdBlitImage) DECLARE_VULKAN_FUNCTION(vkCmdCopyBufferToImage) DECLARE_VULKAN_FUNCTION(vkCmdCopyImageToBuffer) DECLARE_VULKAN_FUNCTION(vkCmdUpdateBuffer) DECLARE_VULKAN_FUNCTION(vkCmdFillBuffer) DECLARE_VULKAN_FUNCTION(vkCmdClearColorImage) DECLARE_VULKAN_FUNCTION(vkCmdClearDepthStencilImage) DECLARE_VULKAN_FUNCTION(vkCmdClearAttachments) DECLARE_VULKAN_FUNCTION(vkCmdResolveImage) DECLARE_VULKAN_FUNCTION(vkCmdSetEvent) DECLARE_VULKAN_FUNCTION(vkCmdResetEvent) DECLARE_VULKAN_FUNCTION(vkCmdWaitEvents) DECLARE_VULKAN_FUNCTION(vkCmdPipelineBarrier) DECLARE_VULKAN_FUNCTION(vkCmdBeginQuery) DECLARE_VULKAN_FUNCTION(vkCmdEndQuery) DECLARE_VULKAN_FUNCTION(vkCmdResetQueryPool) DECLARE_VULKAN_FUNCTION(vkCmdWriteTimestamp) DECLARE_VULKAN_FUNCTION(vkCmdCopyQueryPoolResults) DECLARE_VULKAN_FUNCTION(vkCmdPushConstants) DECLARE_VULKAN_FUNCTION(vkCmdBeginRenderPass) DECLARE_VULKAN_FUNCTION(vkCmdNextSubpass) DECLARE_VULKAN_FUNCTION(vkCmdEndRenderPass) DECLARE_VULKAN_FUNCTION(vkCmdExecuteCommands) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDeviceFeatures2) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDeviceProperties2) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDeviceFormatProperties2) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDeviceImageFormatProperties2) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDeviceQueueFamilyProperties2) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDeviceMemoryProperties2) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDeviceSparseImageFormatProperties2) DECLARE_VULKAN_FUNCTION(vkTrimCommandPool) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDeviceExternalBufferProperties) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDeviceExternalSemaphoreProperties) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDeviceExternalFenceProperties) DECLARE_VULKAN_FUNCTION(vkEnumeratePhysicalDeviceGroups) DECLARE_VULKAN_FUNCTION(vkGetDeviceGroupPeerMemoryFeatures) DECLARE_VULKAN_FUNCTION(vkBindBufferMemory2) DECLARE_VULKAN_FUNCTION(vkBindImageMemory2) DECLARE_VULKAN_FUNCTION(vkCmdSetDeviceMask) DECLARE_VULKAN_FUNCTION(vkCmdDispatchBase) DECLARE_VULKAN_FUNCTION(vkCreateDescriptorUpdateTemplate) DECLARE_VULKAN_FUNCTION(vkDestroyDescriptorUpdateTemplate) DECLARE_VULKAN_FUNCTION(vkUpdateDescriptorSetWithTemplate) DECLARE_VULKAN_FUNCTION(vkGetBufferMemoryRequirements2) DECLARE_VULKAN_FUNCTION(vkGetImageMemoryRequirements2) DECLARE_VULKAN_FUNCTION(vkGetImageSparseMemoryRequirements2) DECLARE_VULKAN_FUNCTION(vkCreateSamplerYcbcrConversion) DECLARE_VULKAN_FUNCTION(vkDestroySamplerYcbcrConversion) DECLARE_VULKAN_FUNCTION(vkGetDeviceQueue2) DECLARE_VULKAN_FUNCTION(vkGetDescriptorSetLayoutSupport) DECLARE_VULKAN_FUNCTION(vkCreateRenderPass2) DECLARE_VULKAN_FUNCTION(vkCmdBeginRenderPass2) DECLARE_VULKAN_FUNCTION(vkCmdNextSubpass2) DECLARE_VULKAN_FUNCTION(vkCmdEndRenderPass2) DECLARE_VULKAN_FUNCTION(vkGetSemaphoreCounterValue) DECLARE_VULKAN_FUNCTION(vkWaitSemaphores) DECLARE_VULKAN_FUNCTION(vkSignalSemaphore) DECLARE_VULKAN_FUNCTION(vkCmdDrawIndirectCount) DECLARE_VULKAN_FUNCTION(vkCmdDrawIndexedIndirectCount) DECLARE_VULKAN_FUNCTION(vkGetBufferOpaqueCaptureAddress) DECLARE_VULKAN_FUNCTION(vkGetBufferDeviceAddress) DECLARE_VULKAN_FUNCTION(vkGetDeviceMemoryOpaqueCaptureAddress) #if defined(VK_AMD_BUFFER_MARKER_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkCmdWriteBufferMarkerAMD) #endif #if defined(VK_AMD_DISPLAY_NATIVE_HDR_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkSetLocalDimmingAMD) #endif #if defined(VK_AMD_SHADER_INFO_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkGetShaderInfoAMD) #endif #if defined(VK_EXT_ACQUIRE_DRM_DISPLAY_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkAcquireDrmDisplayEXT) DECLARE_VULKAN_FUNCTION(vkGetDrmDisplayEXT) #endif #if defined(VK_EXT_CALIBRATED_TIMESTAMPS_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDeviceCalibrateableTimeDomainsEXT) DECLARE_VULKAN_FUNCTION(vkGetCalibratedTimestampsEXT) #endif #if defined(VK_EXT_COLOR_WRITE_ENABLE_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkCmdSetColorWriteEnableEXT) #endif #if defined(VK_EXT_CONDITIONAL_RENDERING_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkCmdBeginConditionalRenderingEXT) DECLARE_VULKAN_FUNCTION(vkCmdEndConditionalRenderingEXT) #endif #if defined(VK_EXT_DEBUG_MARKER_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkDebugMarkerSetObjectNameEXT) DECLARE_VULKAN_FUNCTION(vkDebugMarkerSetObjectTagEXT) DECLARE_VULKAN_FUNCTION(vkCmdDebugMarkerBeginEXT) DECLARE_VULKAN_FUNCTION(vkCmdDebugMarkerEndEXT) DECLARE_VULKAN_FUNCTION(vkCmdDebugMarkerInsertEXT) #endif #if defined(VK_EXT_DEBUG_REPORT_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkCreateDebugReportCallbackEXT) DECLARE_VULKAN_FUNCTION(vkDestroyDebugReportCallbackEXT) DECLARE_VULKAN_FUNCTION(vkDebugReportMessageEXT) #endif #if defined(VK_EXT_DEBUG_UTILS_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkSetDebugUtilsObjectNameEXT) DECLARE_VULKAN_FUNCTION(vkSetDebugUtilsObjectTagEXT) DECLARE_VULKAN_FUNCTION(vkQueueBeginDebugUtilsLabelEXT) DECLARE_VULKAN_FUNCTION(vkQueueEndDebugUtilsLabelEXT) DECLARE_VULKAN_FUNCTION(vkQueueInsertDebugUtilsLabelEXT) DECLARE_VULKAN_FUNCTION(vkCmdBeginDebugUtilsLabelEXT) DECLARE_VULKAN_FUNCTION(vkCmdEndDebugUtilsLabelEXT) DECLARE_VULKAN_FUNCTION(vkCmdInsertDebugUtilsLabelEXT) DECLARE_VULKAN_FUNCTION(vkCreateDebugUtilsMessengerEXT) DECLARE_VULKAN_FUNCTION(vkDestroyDebugUtilsMessengerEXT) DECLARE_VULKAN_FUNCTION(vkSubmitDebugUtilsMessageEXT) #endif #if defined(VK_EXT_DIRECT_MODE_DISPLAY_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkReleaseDisplayEXT) #endif #if defined(VK_EXT_DISCARD_RECTANGLES_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkCmdSetDiscardRectangleEXT) #endif #if defined(VK_EXT_DISPLAY_CONTROL_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkDisplayPowerControlEXT) DECLARE_VULKAN_FUNCTION(vkRegisterDeviceEventEXT) DECLARE_VULKAN_FUNCTION(vkRegisterDisplayEventEXT) DECLARE_VULKAN_FUNCTION(vkGetSwapchainCounterEXT) #endif #if defined(VK_EXT_DISPLAY_SURFACE_COUNTER_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDeviceSurfaceCapabilities2EXT) #endif #if defined(VK_EXT_EXTENDED_DYNAMIC_STATE_2_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkCmdSetPatchControlPointsEXT) DECLARE_VULKAN_FUNCTION(vkCmdSetRasterizerDiscardEnableEXT) DECLARE_VULKAN_FUNCTION(vkCmdSetDepthBiasEnableEXT) DECLARE_VULKAN_FUNCTION(vkCmdSetLogicOpEXT) DECLARE_VULKAN_FUNCTION(vkCmdSetPrimitiveRestartEnableEXT) #endif #if defined(VK_EXT_EXTENDED_DYNAMIC_STATE_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkCmdSetCullModeEXT) DECLARE_VULKAN_FUNCTION(vkCmdSetFrontFaceEXT) DECLARE_VULKAN_FUNCTION(vkCmdSetPrimitiveTopologyEXT) DECLARE_VULKAN_FUNCTION(vkCmdSetViewportWithCountEXT) DECLARE_VULKAN_FUNCTION(vkCmdSetScissorWithCountEXT) DECLARE_VULKAN_FUNCTION(vkCmdBindVertexBuffers2EXT) DECLARE_VULKAN_FUNCTION(vkCmdSetDepthTestEnableEXT) DECLARE_VULKAN_FUNCTION(vkCmdSetDepthWriteEnableEXT) DECLARE_VULKAN_FUNCTION(vkCmdSetDepthCompareOpEXT) DECLARE_VULKAN_FUNCTION(vkCmdSetDepthBoundsTestEnableEXT) DECLARE_VULKAN_FUNCTION(vkCmdSetStencilTestEnableEXT) DECLARE_VULKAN_FUNCTION(vkCmdSetStencilOpEXT) #endif #if defined(VK_EXT_EXTERNAL_MEMORY_HOST_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkGetMemoryHostPointerPropertiesEXT) #endif #if defined(VK_EXT_HDR_METADATA_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkSetHdrMetadataEXT) #endif #if defined(VK_EXT_HEADLESS_SURFACE_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkCreateHeadlessSurfaceEXT) #endif #if defined(VK_EXT_IMAGE_DRM_FORMAT_MODIFIER_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkGetImageDrmFormatModifierPropertiesEXT) #endif #if defined(VK_EXT_LINE_RASTERIZATION_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkCmdSetLineStippleEXT) #endif #if defined(VK_EXT_MULTI_DRAW_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkCmdDrawMultiEXT) DECLARE_VULKAN_FUNCTION(vkCmdDrawMultiIndexedEXT) #endif #if defined(VK_EXT_PAGEABLE_DEVICE_LOCAL_MEMORY_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkSetDeviceMemoryPriorityEXT) #endif #if defined(VK_EXT_PRIVATE_DATA_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkCreatePrivateDataSlotEXT) DECLARE_VULKAN_FUNCTION(vkDestroyPrivateDataSlotEXT) DECLARE_VULKAN_FUNCTION(vkSetPrivateDataEXT) DECLARE_VULKAN_FUNCTION(vkGetPrivateDataEXT) #endif #if defined(VK_EXT_SAMPLE_LOCATIONS_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkCmdSetSampleLocationsEXT) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDeviceMultisamplePropertiesEXT) #endif #if defined(VK_EXT_TOOLING_INFO_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDeviceToolPropertiesEXT) #endif #if defined(VK_EXT_TRANSFORM_FEEDBACK_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkCmdBindTransformFeedbackBuffersEXT) DECLARE_VULKAN_FUNCTION(vkCmdBeginTransformFeedbackEXT) DECLARE_VULKAN_FUNCTION(vkCmdEndTransformFeedbackEXT) DECLARE_VULKAN_FUNCTION(vkCmdBeginQueryIndexedEXT) DECLARE_VULKAN_FUNCTION(vkCmdEndQueryIndexedEXT) DECLARE_VULKAN_FUNCTION(vkCmdDrawIndirectByteCountEXT) #endif #if defined(VK_EXT_VALIDATION_CACHE_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkCreateValidationCacheEXT) DECLARE_VULKAN_FUNCTION(vkDestroyValidationCacheEXT) DECLARE_VULKAN_FUNCTION(vkGetValidationCacheDataEXT) DECLARE_VULKAN_FUNCTION(vkMergeValidationCachesEXT) #endif #if defined(VK_EXT_VERTEX_INPUT_DYNAMIC_STATE_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkCmdSetVertexInputEXT) #endif #if defined(VK_GOOGLE_DISPLAY_TIMING_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkGetRefreshCycleDurationGOOGLE) DECLARE_VULKAN_FUNCTION(vkGetPastPresentationTimingGOOGLE) #endif #if defined(VK_HUAWEI_INVOCATION_MASK_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkCmdBindInvocationMaskHUAWEI) #endif #if defined(VK_HUAWEI_SUBPASS_SHADING_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkGetDeviceSubpassShadingMaxWorkgroupSizeHUAWEI) DECLARE_VULKAN_FUNCTION(vkCmdSubpassShadingHUAWEI) #endif #if defined(VK_INTEL_PERFORMANCE_QUERY_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkInitializePerformanceApiINTEL) DECLARE_VULKAN_FUNCTION(vkUninitializePerformanceApiINTEL) DECLARE_VULKAN_FUNCTION(vkCmdSetPerformanceMarkerINTEL) DECLARE_VULKAN_FUNCTION(vkCmdSetPerformanceStreamMarkerINTEL) DECLARE_VULKAN_FUNCTION(vkCmdSetPerformanceOverrideINTEL) DECLARE_VULKAN_FUNCTION(vkAcquirePerformanceConfigurationINTEL) DECLARE_VULKAN_FUNCTION(vkReleasePerformanceConfigurationINTEL) DECLARE_VULKAN_FUNCTION(vkQueueSetPerformanceConfigurationINTEL) DECLARE_VULKAN_FUNCTION(vkGetPerformanceParameterINTEL) #endif #if defined(VK_KHR_ACCELERATION_STRUCTURE_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkDestroyAccelerationStructureKHR) DECLARE_VULKAN_FUNCTION(vkCmdCopyAccelerationStructureKHR) DECLARE_VULKAN_FUNCTION(vkCopyAccelerationStructureKHR) DECLARE_VULKAN_FUNCTION(vkCmdCopyAccelerationStructureToMemoryKHR) DECLARE_VULKAN_FUNCTION(vkCopyAccelerationStructureToMemoryKHR) DECLARE_VULKAN_FUNCTION(vkCmdCopyMemoryToAccelerationStructureKHR) DECLARE_VULKAN_FUNCTION(vkCopyMemoryToAccelerationStructureKHR) DECLARE_VULKAN_FUNCTION(vkCmdWriteAccelerationStructuresPropertiesKHR) DECLARE_VULKAN_FUNCTION(vkWriteAccelerationStructuresPropertiesKHR) DECLARE_VULKAN_FUNCTION(vkGetDeviceAccelerationStructureCompatibilityKHR) DECLARE_VULKAN_FUNCTION(vkCreateAccelerationStructureKHR) DECLARE_VULKAN_FUNCTION(vkCmdBuildAccelerationStructuresKHR) DECLARE_VULKAN_FUNCTION(vkCmdBuildAccelerationStructuresIndirectKHR) DECLARE_VULKAN_FUNCTION(vkBuildAccelerationStructuresKHR) DECLARE_VULKAN_FUNCTION(vkGetAccelerationStructureDeviceAddressKHR) DECLARE_VULKAN_FUNCTION(vkGetAccelerationStructureBuildSizesKHR) #endif #if defined(VK_KHR_COPY_COMMANDS_2_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkCmdCopyBuffer2KHR) DECLARE_VULKAN_FUNCTION(vkCmdCopyImage2KHR) DECLARE_VULKAN_FUNCTION(vkCmdBlitImage2KHR) DECLARE_VULKAN_FUNCTION(vkCmdCopyBufferToImage2KHR) DECLARE_VULKAN_FUNCTION(vkCmdCopyImageToBuffer2KHR) DECLARE_VULKAN_FUNCTION(vkCmdResolveImage2KHR) #endif #if defined(VK_KHR_DEFERRED_HOST_OPERATIONS_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkCreateDeferredOperationKHR) DECLARE_VULKAN_FUNCTION(vkDestroyDeferredOperationKHR) DECLARE_VULKAN_FUNCTION(vkGetDeferredOperationMaxConcurrencyKHR) DECLARE_VULKAN_FUNCTION(vkGetDeferredOperationResultKHR) DECLARE_VULKAN_FUNCTION(vkDeferredOperationJoinKHR) #endif #if defined(VK_KHR_DESCRIPTOR_UPDATE_TEMPLATE_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkCmdPushDescriptorSetWithTemplateKHR) #endif #if defined(VK_KHR_DEVICE_GROUP_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkGetDeviceGroupPresentCapabilitiesKHR) DECLARE_VULKAN_FUNCTION(vkGetDeviceGroupSurfacePresentModesKHR) DECLARE_VULKAN_FUNCTION(vkAcquireNextImage2KHR) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDevicePresentRectanglesKHR) #endif #if defined(VK_KHR_DISPLAY_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDeviceDisplayPropertiesKHR) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDeviceDisplayPlanePropertiesKHR) DECLARE_VULKAN_FUNCTION(vkGetDisplayPlaneSupportedDisplaysKHR) DECLARE_VULKAN_FUNCTION(vkGetDisplayModePropertiesKHR) DECLARE_VULKAN_FUNCTION(vkCreateDisplayModeKHR) DECLARE_VULKAN_FUNCTION(vkGetDisplayPlaneCapabilitiesKHR) DECLARE_VULKAN_FUNCTION(vkCreateDisplayPlaneSurfaceKHR) #endif #if defined(VK_KHR_DISPLAY_SWAPCHAIN_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkCreateSharedSwapchainsKHR) #endif #if defined(VK_KHR_EXTERNAL_FENCE_FD_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkGetFenceFdKHR) DECLARE_VULKAN_FUNCTION(vkImportFenceFdKHR) #endif #if defined(VK_KHR_EXTERNAL_MEMORY_FD_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkGetMemoryFdKHR) DECLARE_VULKAN_FUNCTION(vkGetMemoryFdPropertiesKHR) #endif #if defined(VK_KHR_EXTERNAL_SEMAPHORE_FD_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkGetSemaphoreFdKHR) DECLARE_VULKAN_FUNCTION(vkImportSemaphoreFdKHR) #endif #if defined(VK_KHR_FRAGMENT_SHADING_RATE_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkCmdSetFragmentShadingRateKHR) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDeviceFragmentShadingRatesKHR) #endif #if defined(VK_KHR_GET_DISPLAY_PROPERTIES_2_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDeviceDisplayProperties2KHR) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDeviceDisplayPlaneProperties2KHR) DECLARE_VULKAN_FUNCTION(vkGetDisplayModeProperties2KHR) DECLARE_VULKAN_FUNCTION(vkGetDisplayPlaneCapabilities2KHR) #endif #if defined(VK_KHR_GET_SURFACE_CAPABILITIES_2_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDeviceSurfaceCapabilities2KHR) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDeviceSurfaceFormats2KHR) #endif #if defined(VK_KHR_MAINTENANCE_4_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkGetDeviceBufferMemoryRequirementsKHR) DECLARE_VULKAN_FUNCTION(vkGetDeviceImageMemoryRequirementsKHR) DECLARE_VULKAN_FUNCTION(vkGetDeviceImageSparseMemoryRequirementsKHR) #endif #if defined(VK_KHR_PERFORMANCE_QUERY_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkEnumeratePhysicalDeviceQueueFamilyPerformanceQueryCountersKHR) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDeviceQueueFamilyPerformanceQueryPassesKHR) DECLARE_VULKAN_FUNCTION(vkAcquireProfilingLockKHR) DECLARE_VULKAN_FUNCTION(vkReleaseProfilingLockKHR) #endif #if defined(VK_KHR_PIPELINE_EXECUTABLE_PROPERTIES_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkGetPipelineExecutablePropertiesKHR) DECLARE_VULKAN_FUNCTION(vkGetPipelineExecutableStatisticsKHR) DECLARE_VULKAN_FUNCTION(vkGetPipelineExecutableInternalRepresentationsKHR) #endif #if defined(VK_KHR_PRESENT_WAIT_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkWaitForPresentKHR) #endif #if defined(VK_KHR_PUSH_DESCRIPTOR_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkCmdPushDescriptorSetKHR) #endif #if defined(VK_KHR_RAY_TRACING_PIPELINE_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkCmdTraceRaysKHR) DECLARE_VULKAN_FUNCTION(vkGetRayTracingShaderGroupHandlesKHR) DECLARE_VULKAN_FUNCTION(vkGetRayTracingCaptureReplayShaderGroupHandlesKHR) DECLARE_VULKAN_FUNCTION(vkCreateRayTracingPipelinesKHR) DECLARE_VULKAN_FUNCTION(vkCmdTraceRaysIndirectKHR) DECLARE_VULKAN_FUNCTION(vkGetRayTracingShaderGroupStackSizeKHR) DECLARE_VULKAN_FUNCTION(vkCmdSetRayTracingPipelineStackSizeKHR) #endif #if defined(VK_KHR_SHARED_PRESENTABLE_IMAGE_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkGetSwapchainStatusKHR) #endif #if defined(VK_KHR_SURFACE_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkDestroySurfaceKHR) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDeviceSurfaceSupportKHR) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDeviceSurfaceCapabilitiesKHR) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDeviceSurfaceFormatsKHR) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDeviceSurfacePresentModesKHR) #endif #if defined(VK_KHR_SWAPCHAIN_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkCreateSwapchainKHR) DECLARE_VULKAN_FUNCTION(vkDestroySwapchainKHR) DECLARE_VULKAN_FUNCTION(vkGetSwapchainImagesKHR) DECLARE_VULKAN_FUNCTION(vkAcquireNextImageKHR) DECLARE_VULKAN_FUNCTION(vkQueuePresentKHR) #endif #if defined(VK_KHR_SYNCHRONIZATION_2_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkCmdSetEvent2KHR) DECLARE_VULKAN_FUNCTION(vkCmdResetEvent2KHR) DECLARE_VULKAN_FUNCTION(vkCmdWaitEvents2KHR) DECLARE_VULKAN_FUNCTION(vkCmdPipelineBarrier2KHR) DECLARE_VULKAN_FUNCTION(vkQueueSubmit2KHR) DECLARE_VULKAN_FUNCTION(vkCmdWriteTimestamp2KHR) DECLARE_VULKAN_FUNCTION(vkCmdWriteBufferMarker2AMD) DECLARE_VULKAN_FUNCTION(vkGetQueueCheckpointData2NV) #endif #if defined(VK_NVX_BINARY_IMPORT_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkCreateCuModuleNVX) DECLARE_VULKAN_FUNCTION(vkCreateCuFunctionNVX) DECLARE_VULKAN_FUNCTION(vkDestroyCuModuleNVX) DECLARE_VULKAN_FUNCTION(vkDestroyCuFunctionNVX) DECLARE_VULKAN_FUNCTION(vkCmdCuLaunchKernelNVX) #endif #if defined(VK_NVX_IMAGE_VIEW_HANDLE_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkGetImageViewHandleNVX) DECLARE_VULKAN_FUNCTION(vkGetImageViewAddressNVX) #endif #if defined(VK_NV_CLIP_SPACE_W_SCALING_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkCmdSetViewportWScalingNV) #endif #if defined(VK_NV_COOPERATIVE_MATRIX_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDeviceCooperativeMatrixPropertiesNV) #endif #if defined(VK_NV_COVERAGE_REDUCTION_MODE_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV) #endif #if defined(VK_NV_DEVICE_DIAGNOSTIC_CHECKPOINTS_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkCmdSetCheckpointNV) DECLARE_VULKAN_FUNCTION(vkGetQueueCheckpointDataNV) #endif #if defined(VK_NV_DEVICE_GENERATED_COMMANDS_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkCmdExecuteGeneratedCommandsNV) DECLARE_VULKAN_FUNCTION(vkCmdPreprocessGeneratedCommandsNV) DECLARE_VULKAN_FUNCTION(vkCmdBindPipelineShaderGroupNV) DECLARE_VULKAN_FUNCTION(vkGetGeneratedCommandsMemoryRequirementsNV) DECLARE_VULKAN_FUNCTION(vkCreateIndirectCommandsLayoutNV) DECLARE_VULKAN_FUNCTION(vkDestroyIndirectCommandsLayoutNV) #endif #if defined(VK_NV_EXTERNAL_MEMORY_CAPABILITIES_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDeviceExternalImageFormatPropertiesNV) #endif #if defined(VK_NV_EXTERNAL_MEMORY_RDMA_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkGetMemoryRemoteAddressNV) #endif #if defined(VK_NV_FRAGMENT_SHADING_RATE_ENUMS_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkCmdSetFragmentShadingRateEnumNV) #endif #if defined(VK_NV_MESH_SHADER_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkCmdDrawMeshTasksNV) DECLARE_VULKAN_FUNCTION(vkCmdDrawMeshTasksIndirectNV) DECLARE_VULKAN_FUNCTION(vkCmdDrawMeshTasksIndirectCountNV) #endif #if defined(VK_NV_RAY_TRACING_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkCompileDeferredNV) DECLARE_VULKAN_FUNCTION(vkCreateAccelerationStructureNV) DECLARE_VULKAN_FUNCTION(vkDestroyAccelerationStructureNV) DECLARE_VULKAN_FUNCTION(vkGetAccelerationStructureMemoryRequirementsNV) DECLARE_VULKAN_FUNCTION(vkBindAccelerationStructureMemoryNV) DECLARE_VULKAN_FUNCTION(vkCmdCopyAccelerationStructureNV) DECLARE_VULKAN_FUNCTION(vkCmdWriteAccelerationStructuresPropertiesNV) DECLARE_VULKAN_FUNCTION(vkCmdBuildAccelerationStructureNV) DECLARE_VULKAN_FUNCTION(vkCmdTraceRaysNV) DECLARE_VULKAN_FUNCTION(vkGetAccelerationStructureHandleNV) DECLARE_VULKAN_FUNCTION(vkCreateRayTracingPipelinesNV) #endif #if defined(VK_NV_SCISSOR_EXCLUSIVE_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkCmdSetExclusiveScissorNV) #endif #if defined(VK_NV_SHADING_RATE_IMAGE_EXTENSION_NAME) DECLARE_VULKAN_FUNCTION(vkCmdBindShadingRateImageNV) DECLARE_VULKAN_FUNCTION(vkCmdSetViewportShadingRatePaletteNV) DECLARE_VULKAN_FUNCTION(vkCmdSetCoarseSampleOrderNV) #endif #if defined(VK_KHR_VIDEO_DECODE_QUEUE_EXTENSION_NAME) && defined(VK_ENABLE_BETA_EXTENSIONS) DECLARE_VULKAN_FUNCTION(vkCmdDecodeVideoKHR) #endif #if defined(VK_KHR_VIDEO_ENCODE_QUEUE_EXTENSION_NAME) && defined(VK_ENABLE_BETA_EXTENSIONS) DECLARE_VULKAN_FUNCTION(vkCmdEncodeVideoKHR) #endif #if defined(VK_KHR_VIDEO_QUEUE_EXTENSION_NAME) && defined(VK_ENABLE_BETA_EXTENSIONS) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDeviceVideoCapabilitiesKHR) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDeviceVideoFormatPropertiesKHR) DECLARE_VULKAN_FUNCTION(vkCreateVideoSessionKHR) DECLARE_VULKAN_FUNCTION(vkDestroyVideoSessionKHR) DECLARE_VULKAN_FUNCTION(vkCreateVideoSessionParametersKHR) DECLARE_VULKAN_FUNCTION(vkUpdateVideoSessionParametersKHR) DECLARE_VULKAN_FUNCTION(vkDestroyVideoSessionParametersKHR) DECLARE_VULKAN_FUNCTION(vkGetVideoSessionMemoryRequirementsKHR) DECLARE_VULKAN_FUNCTION(vkBindVideoSessionMemoryKHR) DECLARE_VULKAN_FUNCTION(vkCmdBeginVideoCodingKHR) DECLARE_VULKAN_FUNCTION(vkCmdControlVideoCodingKHR) DECLARE_VULKAN_FUNCTION(vkCmdEndVideoCodingKHR) #endif #if defined(VK_ANDROID_EXTERNAL_MEMORY_ANDROID_HARDWARE_BUFFER_EXTENSION_NAME) && defined(VK_USE_PLATFORM_ANDROID_KHR) DECLARE_VULKAN_FUNCTION(vkGetAndroidHardwareBufferPropertiesANDROID) DECLARE_VULKAN_FUNCTION(vkGetMemoryAndroidHardwareBufferANDROID) #endif #if defined(VK_ANDROID_NATIVE_BUFFER_EXTENSION_NAME) && defined(VK_USE_PLATFORM_ANDROID_KHR) DECLARE_VULKAN_FUNCTION(vkGetSwapchainGrallocUsageANDROID) DECLARE_VULKAN_FUNCTION(vkGetSwapchainGrallocUsage2ANDROID) DECLARE_VULKAN_FUNCTION(vkAcquireImageANDROID) DECLARE_VULKAN_FUNCTION(vkQueueSignalReleaseImageANDROID) #endif #if defined(VK_KHR_ANDROID_SURFACE_EXTENSION_NAME) && defined(VK_USE_PLATFORM_ANDROID_KHR) DECLARE_VULKAN_FUNCTION(vkCreateAndroidSurfaceKHR) #endif #if defined(VK_EXT_DIRECTFB_SURFACE_EXTENSION_NAME) && defined(VK_USE_PLATFORM_DIRECTFB_EXT) DECLARE_VULKAN_FUNCTION(vkCreateDirectFBSurfaceEXT) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDeviceDirectFBPresentationSupportEXT) #endif #if defined(VK_FUCHSIA_BUFFER_COLLECTION_EXTENSION_NAME) && defined(VK_USE_PLATFORM_FUCHSIA) DECLARE_VULKAN_FUNCTION(vkCreateBufferCollectionFUCHSIA) DECLARE_VULKAN_FUNCTION(vkSetBufferCollectionBufferConstraintsFUCHSIA) DECLARE_VULKAN_FUNCTION(vkSetBufferCollectionImageConstraintsFUCHSIA) DECLARE_VULKAN_FUNCTION(vkDestroyBufferCollectionFUCHSIA) DECLARE_VULKAN_FUNCTION(vkGetBufferCollectionPropertiesFUCHSIA) #endif #if defined(VK_FUCHSIA_EXTERNAL_MEMORY_EXTENSION_NAME) && defined(VK_USE_PLATFORM_FUCHSIA) DECLARE_VULKAN_FUNCTION(vkGetMemoryZirconHandleFUCHSIA) DECLARE_VULKAN_FUNCTION(vkGetMemoryZirconHandlePropertiesFUCHSIA) #endif #if defined(VK_FUCHSIA_EXTERNAL_SEMAPHORE_EXTENSION_NAME) && defined(VK_USE_PLATFORM_FUCHSIA) DECLARE_VULKAN_FUNCTION(vkGetSemaphoreZirconHandleFUCHSIA) DECLARE_VULKAN_FUNCTION(vkImportSemaphoreZirconHandleFUCHSIA) #endif #if defined(VK_FUCHSIA_IMAGEPIPE_SURFACE_EXTENSION_NAME) && defined(VK_USE_PLATFORM_FUCHSIA) DECLARE_VULKAN_FUNCTION(vkCreateImagePipeSurfaceFUCHSIA) #endif #if defined(VK_GGP_STREAM_DESCRIPTOR_SURFACE_EXTENSION_NAME) && defined(VK_USE_PLATFORM_GGP) DECLARE_VULKAN_FUNCTION(vkCreateStreamDescriptorSurfaceGGP) #endif #if defined(VK_MVK_IOS_SURFACE_EXTENSION_NAME) && defined(VK_USE_PLATFORM_IOS_MVK) DECLARE_VULKAN_FUNCTION(vkCreateIOSSurfaceMVK) #endif #if defined(VK_MVK_MACOS_SURFACE_EXTENSION_NAME) && defined(VK_USE_PLATFORM_MACOS_MVK) DECLARE_VULKAN_FUNCTION(vkCreateMacOSSurfaceMVK) #endif #if defined(VK_EXT_METAL_SURFACE_EXTENSION_NAME) && defined(VK_USE_PLATFORM_METAL_EXT) DECLARE_VULKAN_FUNCTION(vkCreateMetalSurfaceEXT) #endif #if defined(VK_QNX_SCREEN_SURFACE_EXTENSION_NAME) && defined(VK_USE_PLATFORM_SCREEN_QNX) DECLARE_VULKAN_FUNCTION(vkCreateScreenSurfaceQNX) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDeviceScreenPresentationSupportQNX) #endif #if defined(VK_NN_VI_SURFACE_EXTENSION_NAME) && defined(VK_USE_PLATFORM_VI_NN) DECLARE_VULKAN_FUNCTION(vkCreateViSurfaceNN) #endif #if defined(VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME) && defined(VK_USE_PLATFORM_WAYLAND_KHR) DECLARE_VULKAN_FUNCTION(vkCreateWaylandSurfaceKHR) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDeviceWaylandPresentationSupportKHR) #endif #if defined(VK_EXT_FULL_SCREEN_EXCLUSIVE_EXTENSION_NAME) && defined(VK_USE_PLATFORM_WIN32_KHR) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDeviceSurfacePresentModes2EXT) DECLARE_VULKAN_FUNCTION(vkGetDeviceGroupSurfacePresentModes2EXT) DECLARE_VULKAN_FUNCTION(vkAcquireFullScreenExclusiveModeEXT) DECLARE_VULKAN_FUNCTION(vkReleaseFullScreenExclusiveModeEXT) #endif #if defined(VK_KHR_EXTERNAL_FENCE_WIN32_EXTENSION_NAME) && defined(VK_USE_PLATFORM_WIN32_KHR) DECLARE_VULKAN_FUNCTION(vkGetFenceWin32HandleKHR) DECLARE_VULKAN_FUNCTION(vkImportFenceWin32HandleKHR) #endif #if defined(VK_KHR_EXTERNAL_MEMORY_WIN32_EXTENSION_NAME) && defined(VK_USE_PLATFORM_WIN32_KHR) DECLARE_VULKAN_FUNCTION(vkGetMemoryWin32HandleKHR) DECLARE_VULKAN_FUNCTION(vkGetMemoryWin32HandlePropertiesKHR) #endif #if defined(VK_KHR_EXTERNAL_SEMAPHORE_WIN32_EXTENSION_NAME) && defined(VK_USE_PLATFORM_WIN32_KHR) DECLARE_VULKAN_FUNCTION(vkGetSemaphoreWin32HandleKHR) DECLARE_VULKAN_FUNCTION(vkImportSemaphoreWin32HandleKHR) #endif #if defined(VK_KHR_WIN32_SURFACE_EXTENSION_NAME) && defined(VK_USE_PLATFORM_WIN32_KHR) DECLARE_VULKAN_FUNCTION(vkCreateWin32SurfaceKHR) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDeviceWin32PresentationSupportKHR) #endif #if defined(VK_NV_ACQUIRE_WINRT_DISPLAY_EXTENSION_NAME) && defined(VK_USE_PLATFORM_WIN32_KHR) DECLARE_VULKAN_FUNCTION(vkAcquireWinrtDisplayNV) DECLARE_VULKAN_FUNCTION(vkGetWinrtDisplayNV) #endif #if defined(VK_NV_EXTERNAL_MEMORY_WIN32_EXTENSION_NAME) && defined(VK_USE_PLATFORM_WIN32_KHR) DECLARE_VULKAN_FUNCTION(vkGetMemoryWin32HandleNV) #endif #if defined(VK_KHR_XCB_SURFACE_EXTENSION_NAME) && defined(VK_USE_PLATFORM_XCB_KHR) DECLARE_VULKAN_FUNCTION(vkCreateXcbSurfaceKHR) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDeviceXcbPresentationSupportKHR) #endif #if defined(VK_KHR_XLIB_SURFACE_EXTENSION_NAME) && defined(VK_USE_PLATFORM_XLIB_KHR) DECLARE_VULKAN_FUNCTION(vkCreateXlibSurfaceKHR) DECLARE_VULKAN_FUNCTION(vkGetPhysicalDeviceXlibPresentationSupportKHR) #endif #if defined(VK_EXT_ACQUIRE_XLIB_DISPLAY_EXTENSION_NAME) && defined(VK_USE_PLATFORM_XLIB_XRANDR_EXT) DECLARE_VULKAN_FUNCTION(vkAcquireXlibDisplayEXT) DECLARE_VULKAN_FUNCTION(vkGetRandROutputDisplayEXT) #endif } #endif
41.745149
118
0.917165
Sixshaman
5873c52aa895e08e0fd04abb35c5be93a9d23f13
14,972
cpp
C++
src/d3d9/d3d9_swapchain.cpp
dports/dxup
e961838d3d0d5db02cd065b782ad890bf876ceef
[ "Zlib" ]
268
2018-04-27T14:05:01.000Z
2022-03-24T03:55:54.000Z
src/d3d9/d3d9_swapchain.cpp
dports/dxup
e961838d3d0d5db02cd065b782ad890bf876ceef
[ "Zlib" ]
49
2018-04-29T09:39:03.000Z
2019-09-14T12:33:44.000Z
src/d3d9/d3d9_swapchain.cpp
dports/dxup
e961838d3d0d5db02cd065b782ad890bf876ceef
[ "Zlib" ]
28
2018-05-16T12:07:49.000Z
2022-02-26T09:19:18.000Z
#include "d3d9_swapchain.h" #include "d3d9_surface.h" #include "d3d9_renderer.h" #include "d3d9_interface.h" #include <algorithm> namespace dxup { Direct3DSwapChain9Ex::Direct3DSwapChain9Ex(Direct3DDevice9Ex* device, D3DPRESENT_PARAMETERS* presentationParameters, IDXGISwapChain1* swapchain) : Direct3DSwapChain9ExBase{ device } , m_swapchain{ swapchain } , m_rtRequired{ false } { this->Reset(presentationParameters); } HRESULT Direct3DSwapChain9Ex::Reset(D3DPRESENT_PARAMETERS* parameters) { CriticalSection cs(m_device); // Get info and crap! UINT bufferCount = std::max(1u, parameters->BackBufferCount); // Free crap! this->clearResources(); // Set crap! m_presentationParameters = *parameters; DXGI_FORMAT format = convert::format(parameters->BackBufferFormat); format = convert::makeUntypeless(format, false); if (format == DXGI_FORMAT_B8G8R8X8_UNORM) format = DXGI_FORMAT_B8G8R8A8_UNORM; // This is a simple fixup we can do to avoid a blit on both D3D11 native and older DXVK. HRESULT result = m_swapchain->ResizeBuffers( bufferCount, parameters->BackBufferWidth, parameters->BackBufferHeight, format, 0); m_rtRequired = false; // dxvk opt for arbitrary swapchain. if (FAILED(result)) { DXGI_FORMAT forcedFormat = convert::makeSwapchainCompliant(format); log::msg("Reset: using rendertargets as intemediary for swapchain."); m_rtRequired = true; result = m_swapchain->ResizeBuffers( bufferCount, parameters->BackBufferWidth, parameters->BackBufferHeight, forcedFormat, 0); } if (FAILED(result)) return log::d3derr(D3DERR_INVALIDCALL, "Reset: D3D11 ResizeBuffers failed in swapchain reset."); if (!config::getBool(config::ForceWindowed)) { result = m_swapchain->SetFullscreenState(!parameters->Windowed, nullptr); if (FAILED(result)) log::warn("Reset: failed to change fullscreen state!"); } // Make crap! for (UINT i = 0; i < bufferCount; i++) { Com<ID3D11Texture2D> bufferTexture; HRESULT result = m_swapchain->GetBuffer(i, __uuidof(ID3D11Texture2D), (void**)&bufferTexture); if (FAILED(result)) { log::warn("reset: failed to get swapchain buffer as ID3D11Texture2D."); continue; } DXUPResource* resource = DXUPResource::Create(m_device, bufferTexture.ptr(), D3DUSAGE_RENDERTARGET, D3DFMT_UNKNOWN); if (resource == nullptr) { log::warn("reset: failed to create DXUPResource for backbuffer."); continue; } D3D9ResourceDesc d3d9Desc; d3d9Desc.Discard = false; d3d9Desc.Format = parameters->BackBufferFormat; d3d9Desc.Usage = D3DUSAGE_RENDERTARGET; if (m_buffers[i] != nullptr) m_buffers[i]->SetResource(resource); else m_buffers[i] = Direct3DSurface9::Wrap(0, 0, m_device, this, resource, d3d9Desc); if (m_rtRequired) { D3D11_TEXTURE2D_DESC rtDesc; rtDesc.Width = parameters->BackBufferWidth; rtDesc.Height = parameters->BackBufferHeight; rtDesc.MipLevels = 1; rtDesc.ArraySize = 1; rtDesc.Format = convert::makeTypeless(format); rtDesc.SampleDesc.Count = 1; rtDesc.SampleDesc.Quality = 0; rtDesc.Usage = D3D11_USAGE_DEFAULT; rtDesc.BindFlags = D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE; rtDesc.CPUAccessFlags = 0; rtDesc.MiscFlags = 0; Com<ID3D11Texture2D> rtTexture; this->GetD3D11Device()->CreateTexture2D(&rtDesc, nullptr, &rtTexture); resource = DXUPResource::Create(m_device, rtTexture.ptr(), D3DUSAGE_RENDERTARGET, D3DFMT_UNKNOWN); if (resource == nullptr) { log::warn("reset: failed to create DXUPResource for rt passthrough."); continue; } } if (m_exposedBuffers[i] != nullptr) m_exposedBuffers[i]->SetResource(resource); else m_exposedBuffers[i] = Direct3DSurface9::Wrap(0, 0, m_device, this, resource, d3d9Desc); } Com<IDXGIOutput> output; result = m_swapchain->GetContainingOutput(&output); if (FAILED(result)) return log::d3derr(D3DERR_INVALIDCALL, "Reset: failed to get IDXGIOutput for swapchain."); result = output->QueryInterface(__uuidof(IDXGIOutput1), (void**)&m_output); if (FAILED(result)) return log::d3derr(D3DERR_INVALIDCALL, "Reset: failed to upgrade IDXGIOutput to IDXGIOutput1 for swapchain."); return D3D_OK; } void Direct3DSwapChain9Ex::clearResources() { m_output = nullptr; for (size_t i = 0; i < m_buffers.size(); i++) { if (m_buffers[i] != nullptr) m_buffers[i]->ClearResource(); } for (size_t i = 0; i < m_exposedBuffers.size(); i++) { if (m_exposedBuffers[i] != nullptr) m_exposedBuffers[i]->ClearResource(); } } HRESULT STDMETHODCALLTYPE Direct3DSwapChain9Ex::QueryInterface(REFIID riid, void** ppvObj) { InitReturnPtr(ppvObj); if (!ppvObj) return E_POINTER; if (riid == __uuidof(IDirect3DSwapChain9Ex) || riid == __uuidof(IDirect3DSwapChain9) || riid == __uuidof(IUnknown)) { *ppvObj = ref(this); return D3D_OK; } return E_NOINTERFACE; } HRESULT STDMETHODCALLTYPE Direct3DSwapChain9Ex::Present(const RECT* pSourceRect, const RECT* pDestRect, HWND hDestWindowOverride, const RGNDATA* pDirtyRegion, DWORD dwFlags) { CriticalSection cs(m_device); return this->PresentD3D11(pSourceRect, pDestRect, hDestWindowOverride, pDirtyRegion, dwFlags, 0, false); } HRESULT STDMETHODCALLTYPE Direct3DSwapChain9Ex::GetFrontBufferData(IDirect3DSurface9* pDestSurface) { CriticalSection cs(m_device); log::stub("Direct3DSwapChain9Ex::GetFrontBufferData"); return D3D_OK; } HRESULT STDMETHODCALLTYPE Direct3DSwapChain9Ex::GetBackBuffer(UINT iBackBuffer, D3DBACKBUFFER_TYPE Type, IDirect3DSurface9** ppBackBuffer) { CriticalSection cs(m_device); InitReturnPtr(ppBackBuffer); if (Type != D3DBACKBUFFER_TYPE_MONO) return log::d3derr(D3DERR_INVALIDCALL, "GetBackBuffer: stereo backbuffer requested."); if (!ppBackBuffer || iBackBuffer > D3DPRESENT_BACK_BUFFERS_MAX_EX) return log::d3derr(D3DERR_INVALIDCALL, "GetBackBuffer: backbuffer out of bounds."); if (m_exposedBuffers[iBackBuffer] == nullptr) return log::d3derr(D3DERR_INVALIDCALL, "GetBackBuffer: invalid backbuffer requested (%d).", iBackBuffer); *ppBackBuffer = ref(m_exposedBuffers[iBackBuffer]); return D3D_OK; } HRESULT STDMETHODCALLTYPE Direct3DSwapChain9Ex::GetRasterStatus(D3DRASTER_STATUS* pRasterStatus) { CriticalSection cs(m_device); if (pRasterStatus == nullptr) return log::d3derr(D3DERR_INVALIDCALL, "GetRasterStatus: pRasterStatus was nullptr."); // There exists D3DKMTGetScanLine which could implement this. // However the header for it is DDI and it's not supported under Wine. // Just stubbing this for now, but returning something thats should at least make the games happy. // https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/content/d3dkmthk/nf-d3dkmthk-d3dkmtgetscanline static bool hasWarned = false; if (!hasWarned) { log::warn("GetRasterStatus: returning vblank."); hasWarned = true; } pRasterStatus->InVBlank = true; pRasterStatus->ScanLine = 0; return D3D_OK; } HRESULT STDMETHODCALLTYPE Direct3DSwapChain9Ex::GetDisplayMode(D3DDISPLAYMODE* pMode) { CriticalSection cs(m_device); if (pMode == nullptr) return log::d3derr(D3DERR_INVALIDCALL, "GetDisplayMode: pMode was nullptr."); pMode->Width = m_presentationParameters.BackBufferWidth; pMode->Height = m_presentationParameters.BackBufferHeight; pMode->Format = m_presentationParameters.BackBufferFormat; pMode->RefreshRate = m_presentationParameters.FullScreen_RefreshRateInHz; return D3D_OK; } HRESULT STDMETHODCALLTYPE Direct3DSwapChain9Ex::GetPresentParameters(D3DPRESENT_PARAMETERS* pPresentationParameters) { CriticalSection cs(m_device); if (pPresentationParameters == nullptr) return log::d3derr(D3DERR_INVALIDCALL, "GetPresentParameters: pPresentationParameters was nullptr."); *pPresentationParameters = m_presentationParameters; return D3D_OK; } HRESULT STDMETHODCALLTYPE Direct3DSwapChain9Ex::GetLastPresentCount(UINT* pLastPresentCount) { CriticalSection cs(m_device); log::stub("Direct3DSwapChain9Ex::GetLastPresentCount"); return D3D_OK; } HRESULT STDMETHODCALLTYPE Direct3DSwapChain9Ex::GetPresentStats(D3DPRESENTSTATS* pPresentationStatistics) { CriticalSection cs(m_device); log::stub("Direct3DSwapChain9Ex::GetPresentStats"); return D3D_OK; } HRESULT STDMETHODCALLTYPE Direct3DSwapChain9Ex::GetDisplayModeEx(D3DDISPLAYMODEEX* pMode, D3DDISPLAYROTATION* pRotation) { CriticalSection cs(m_device); log::stub("Direct3DSwapChain9Ex::GetDisplayModeEx"); return D3D_OK; } HRESULT Direct3DSwapChain9Ex::WaitForVBlank() { HRESULT result = m_output->WaitForVBlank(); if (FAILED(result)) return log::d3derr(D3DERR_INVALIDCALL, "WaitForVBlank: IDXGIOutput1::WaitForVBlank failed."); return D3D_OK; } HRESULT Direct3DSwapChain9Ex::TestSwapchain(HWND hDestWindowOverride, bool ex) { return this->PresentD3D11(nullptr, nullptr, hDestWindowOverride, nullptr, 0, DXGI_PRESENT_TEST, ex); } void Direct3DSwapChain9Ex::rtBlit() { // TODO! Do we need to change what buffer we do this with? this->GetD3D9Device()->GetRenderer()->blit(m_buffers[0].ptr(), m_exposedBuffers[0].ptr()); } HRESULT Direct3DSwapChain9Ex::PresentD3D11(const RECT* pSourceRect, const RECT* pDestRect, HWND hDestWindowOverride, const RGNDATA* pDirtyRegion, DWORD dwFlags, UINT d3d11Flags, bool ex) { HRESULT result; if (hDestWindowOverride != nullptr) return log::d3derr(D3DERR_INVALIDCALL, "PresentD3D11: called with window override. Not presenting."); if (m_rtRequired && !(d3d11Flags & DXGI_PRESENT_TEST)) this->rtBlit(); UINT syncInterval = 0; if (config::getBool(config::RespectVSync)) { if (m_presentationParameters.PresentationInterval == D3DPRESENT_INTERVAL_IMMEDIATE) syncInterval = 0; else if (m_presentationParameters.PresentationInterval == D3DPRESENT_INTERVAL_DEFAULT || m_presentationParameters.PresentationInterval == D3DPRESENT_INTERVAL_ONE) syncInterval = 1; else if (m_presentationParameters.PresentationInterval == D3DPRESENT_INTERVAL_TWO) syncInterval = 2; else if (m_presentationParameters.PresentationInterval == D3DPRESENT_INTERVAL_THREE) syncInterval = 3; else //if (m_presentationParameters.PresentationInterval == D3DPRESENT_INTERVAL_FOUR) syncInterval = 4; if (dwFlags & D3DPRESENT_FORCEIMMEDIATE) syncInterval = 0; } if (dwFlags & D3DPRESENT_DONOTWAIT) d3d11Flags |= DXGI_PRESENT_DO_NOT_WAIT; if (d3d11Flags & DXGI_PRESENT_TEST) { result = m_swapchain->Present(syncInterval, d3d11Flags); } else { // We may need to do more here for rects... //m_swapchain->ResizeTarget //m_swapchain->ResizeBuffers result = m_swapchain->Present(syncInterval, d3d11Flags); } if (d3d11Flags & DXGI_PRESENT_TEST && FAILED(result)) return D3DERR_DEVICELOST; else { if (result == DXGI_ERROR_WAS_STILL_DRAWING) return D3DERR_WASSTILLDRAWING; if (result == DXGI_ERROR_DEVICE_REMOVED) return D3DERR_DEVICEREMOVED; if (ex) { if (result == DXGI_ERROR_DEVICE_HUNG) return D3DERR_DEVICEHUNG; if (result == DXGI_ERROR_DEVICE_RESET) return D3DERR_DEVICELOST; } else { if (result == DXGI_ERROR_DEVICE_RESET) return D3DERR_DEVICENOTRESET; } if (FAILED(result)) return D3DERR_DRIVERINTERNALERROR; } return D3D_OK; } HRESULT Direct3DSwapChain9Ex::Create(Direct3DDevice9Ex* device, D3DPRESENT_PARAMETERS* presentationParameters, Direct3DSwapChain9Ex** ppSwapChain) { InitReturnPtr(ppSwapChain); if (!ppSwapChain) return log::d3derr(D3DERR_INVALIDCALL, "CreateAdditionalSwapChain: ppSwapChain was nullptr."); DXGI_SWAP_CHAIN_DESC desc; memset(&desc, 0, sizeof(desc)); UINT backBufferCount = std::max(1u, presentationParameters->BackBufferCount); DXGI_FORMAT format = convert::format(presentationParameters->BackBufferFormat); format = convert::makeUntypeless(format, false); if (format == DXGI_FORMAT_B8G8R8X8_UNORM) format = DXGI_FORMAT_B8G8R8A8_UNORM; // This is a simple fixup we can do to avoid a blit on both D3D11 native and older DXVK. desc.BufferCount = backBufferCount; desc.BufferDesc.Width = presentationParameters->BackBufferWidth; desc.BufferDesc.Height = presentationParameters->BackBufferHeight; desc.BufferDesc.Format = format; desc.BufferDesc.RefreshRate.Numerator = 0; desc.BufferDesc.RefreshRate.Denominator = 1; desc.BufferDesc.Scaling = DXGI_MODE_SCALING_STRETCHED; desc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; desc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT | DXGI_USAGE_SHADER_INPUT; desc.OutputWindow = device->getWindow(); desc.Windowed = config::getBool(config::ForceWindowed) ? true : presentationParameters->Windowed; desc.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH; //desc.SampleDesc.Count = (UINT)pPresentationParameters->MultiSampleType; //if (desc.SampleDesc.Count == 0) // desc.SampleDesc.Count = 1; //desc.SampleDesc.Quality = pPresentationParameters->MultiSampleQuality; desc.SampleDesc.Count = 1; desc.SampleDesc.Quality = 0; Com<Direct3D9Ex> parent; device->GetParent(&parent); Com<IDXGISwapChain> dxgiSwapChain; HRESULT result = parent->GetDXGIFactory()->CreateSwapChain(device->GetD3D11Device(), &desc, &dxgiSwapChain); // dxvk opt. for arbitrary swapchain if (FAILED(result)) { format = convert::makeSwapchainCompliant(format); desc.BufferDesc.Format = format; result = parent->GetDXGIFactory()->CreateSwapChain(device->GetD3D11Device(), &desc, &dxgiSwapChain); } if (FAILED(result)) return log::d3derr(D3DERR_INVALIDCALL, "Swapchain - Create: failed to make D3D11 swapchain."); Com<IDXGISwapChain1> upgradedSwapchain; result = dxgiSwapChain->QueryInterface(__uuidof(IDXGISwapChain1), (void**)&upgradedSwapchain); if (FAILED(result)) return log::d3derr(D3DERR_INVALIDCALL, "Swapchain - Create: failed to upgrade swapchain to IDXGISwapChain1!"); parent->GetDXGIFactory()->MakeWindowAssociation(device->getWindow(), DXGI_MWA_NO_ALT_ENTER); *ppSwapChain = ref(new Direct3DSwapChain9Ex(device, presentationParameters, upgradedSwapchain.ptr())); return D3D_OK; } }
35.904077
190
0.713799
dports
587559e8179c65421b769e95dbaec484885aff49
306
cpp
C++
cpyquickhelper/numbers/weighted_number.cpp
sdpython/cpyquickhelper
c2bdebad2201c7e10a5999a836bbf53e27b963c7
[ "MIT" ]
2
2017-10-03T20:39:13.000Z
2019-02-06T15:24:04.000Z
cpyquickhelper/numbers/weighted_number.cpp
sdpython/cpyquickhelper
c2bdebad2201c7e10a5999a836bbf53e27b963c7
[ "MIT" ]
21
2017-09-17T11:14:04.000Z
2021-01-01T13:24:20.000Z
cpyquickhelper/numbers/weighted_number.cpp
sdpython/cpyquickhelper
c2bdebad2201c7e10a5999a836bbf53e27b963c7
[ "MIT" ]
null
null
null
#include "weighted_number.h" #if !defined(_CRT_SECURE_NO_WARNINGS) #define _CRT_SECURE_NO_WARNINGS #endif const char * get_weighted_class_name(double x) { return "Double"; } const char * get_weighted_class_name(float x) { return "Float"; } const char * get_weighted_class_name(int x) { return "Int"; }
25.5
67
0.764706
sdpython
587669c0b70e684be0c258296a6998ce8b2c9732
589
cpp
C++
arduino/app/animations/chaseTo.cpp
littlebee/solar-sunflower
0ef2842943ab58e0b46b161a0f341448c0a470f6
[ "MIT" ]
null
null
null
arduino/app/animations/chaseTo.cpp
littlebee/solar-sunflower
0ef2842943ab58e0b46b161a0f341448c0a470f6
[ "MIT" ]
null
null
null
arduino/app/animations/chaseTo.cpp
littlebee/solar-sunflower
0ef2842943ab58e0b46b161a0f341448c0a470f6
[ "MIT" ]
null
null
null
#include <Arduino.h> #include "chaseTo.h" #include "../util.h" ChaseTo::ChaseTo(Adafruit_WS2801 *pStrip, unsigned long delay) : Animation(pStrip, delay) { reset(); } void ChaseTo::reset(){ _currentPixel = 0; } void ChaseTo::loop(){ if( _throttleLoop(30) ){ return; } //serialPrintf("target red=%d green=%d blue=%d", _targetRed, _targetGreen, _targetBlue); _pStrip->setPixelColor(_currentPixel, color(_args[0], _args[1], _args[2])); _pStrip->show(); if( ++_currentPixel >= _pStrip->numPixels() ){ setColor(color(0, 0, 0)); _currentPixel = 0; } }
18.40625
90
0.646859
littlebee
58775f885fd791719c94e72aba6a8cbcb48f6531
215
cpp
C++
CodeForces/Complete/700-799/765C-TableTennisGame2.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
36
2019-12-27T08:23:08.000Z
2022-01-24T20:35:47.000Z
CodeForces/Complete/700-799/765C-TableTennisGame2.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
10
2019-11-13T02:55:18.000Z
2021-10-13T23:28:09.000Z
CodeForces/Complete/700-799/765C-TableTennisGame2.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
53
2020-08-15T11:08:40.000Z
2021-10-09T15:51:38.000Z
#include <cstdio> int main(){ long k, a, b; scanf("%ld %ld %ld\n", &k, &a, &b); long ans(a / k + b / k); if((a % k && b < k) || (b % k && a < k)){ans = -1;} printf("%ld\n", ans); return 0; }
16.538462
55
0.4
Ashwanigupta9125
587903d7610901e106e3a04aaeec52443fe5ab25
1,679
cpp
C++
test/datetime/main.cpp
qingqibing/read-excel
6f938ca0eb051e14add0e421059edeb94538d2a9
[ "MIT" ]
null
null
null
test/datetime/main.cpp
qingqibing/read-excel
6f938ca0eb051e14add0e421059edeb94538d2a9
[ "MIT" ]
null
null
null
test/datetime/main.cpp
qingqibing/read-excel
6f938ca0eb051e14add0e421059edeb94538d2a9
[ "MIT" ]
1
2021-07-03T00:45:59.000Z
2021-07-03T00:45:59.000Z
/*! \file \author Igor Mironchik (igor.mironchik at gmail dot com). Copyright (c) 2011-2017 Igor Mironchik 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. */ // Excel include. #include <excel/book.hpp> #include <excel/sheet.hpp> // unit test helper. #define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN #include <test/doctest/doctest.h> TEST_CASE( "test_book" ) { Excel::Book book( "test/data/datetime.xls" ); REQUIRE( book.sheetsCount() == 1 ); Excel::Sheet * sheet = book.sheet( 0 ); REQUIRE( sheet->rowsCount() == 1 ); REQUIRE( sheet->columnsCount() == 1 ); REQUIRE( std::fabs( sheet->cell( 0, 0 ).getDouble() - 43100.9999884259 ) < 1E-9 ); }
32.288462
84
0.734961
qingqibing
587a644dfe541b34c737297ed56c478af0f9917d
3,092
cpp
C++
higan/audio/stream.cpp
13824125580/higan
fbdd3f980b65412c362096579869ae76730e4118
[ "Intel", "ISC" ]
null
null
null
higan/audio/stream.cpp
13824125580/higan
fbdd3f980b65412c362096579869ae76730e4118
[ "Intel", "ISC" ]
null
null
null
higan/audio/stream.cpp
13824125580/higan
fbdd3f980b65412c362096579869ae76730e4118
[ "Intel", "ISC" ]
null
null
null
auto Stream::reset(uint channels_, double inputFrequency, double outputFrequency) -> void { this->inputFrequency = inputFrequency; this->outputFrequency = outputFrequency; channels.reset(); channels.resize(channels_); for(auto& channel : channels) { channel.filters.reset(); channel.resampler.reset(inputFrequency, outputFrequency); } } auto Stream::setFrequency(double inputFrequency, maybe<double> outputFrequency) -> void { this->inputFrequency = inputFrequency; if(outputFrequency) this->outputFrequency = outputFrequency(); for(auto& channel : channels) { channel.nyquist.reset(); channel.resampler.reset(this->inputFrequency, this->outputFrequency); } if(this->inputFrequency >= this->outputFrequency * 2) { //add a low-pass filter to prevent aliasing during resampling double cutoffFrequency = min(25000.0, this->outputFrequency / 2.0 - 2000.0); for(auto& channel : channels) { uint passes = 3; for(uint pass : range(passes)) { DSP::IIR::Biquad filter; double q = DSP::IIR::Biquad::butterworth(passes * 2, pass); filter.reset(DSP::IIR::Biquad::Type::LowPass, cutoffFrequency, this->inputFrequency, q); channel.nyquist.append(filter); } } } } auto Stream::addFilter(Filter::Order order, Filter::Type type, double cutoffFrequency, uint passes) -> void { for(auto& channel : channels) { for(uint pass : range(passes)) { Filter filter{order}; if(order == Filter::Order::First) { DSP::IIR::OnePole::Type _type; if(type == Filter::Type::LowPass) _type = DSP::IIR::OnePole::Type::LowPass; if(type == Filter::Type::HighPass) _type = DSP::IIR::OnePole::Type::HighPass; filter.onePole.reset(_type, cutoffFrequency, inputFrequency); } if(order == Filter::Order::Second) { DSP::IIR::Biquad::Type _type; if(type == Filter::Type::LowPass) _type = DSP::IIR::Biquad::Type::LowPass; if(type == Filter::Type::HighPass) _type = DSP::IIR::Biquad::Type::HighPass; double q = DSP::IIR::Biquad::butterworth(passes * 2, pass); filter.biquad.reset(_type, cutoffFrequency, inputFrequency, q); } channel.filters.append(filter); } } } auto Stream::pending() const -> bool { return channels && channels[0].resampler.pending(); } auto Stream::read(double samples[]) -> uint { for(uint c : range(channels.size())) samples[c] = channels[c].resampler.read(); return channels.size(); } auto Stream::write(const double samples[]) -> void { for(auto c : range(channels.size())) { double sample = samples[c] + 1e-25; //constant offset used to suppress denormals for(auto& filter : channels[c].filters) { switch(filter.order) { case Filter::Order::First: sample = filter.onePole.process(sample); break; case Filter::Order::Second: sample = filter.biquad.process(sample); break; } } for(auto& filter : channels[c].nyquist) { sample = filter.process(sample); } channels[c].resampler.write(sample); } audio.process(); }
34.741573
109
0.658797
13824125580
587ac38eca3e3d8623a70c0b7c12fd120038df71
16,655
cpp
C++
UniEngine/src/CameraComponent.cpp
edisonlee0212/UniEngine-deprecated
4b899980c280ac501c3b5fa2746cf1e71cfedd28
[ "MIT" ]
null
null
null
UniEngine/src/CameraComponent.cpp
edisonlee0212/UniEngine-deprecated
4b899980c280ac501c3b5fa2746cf1e71cfedd28
[ "MIT" ]
null
null
null
UniEngine/src/CameraComponent.cpp
edisonlee0212/UniEngine-deprecated
4b899980c280ac501c3b5fa2746cf1e71cfedd28
[ "MIT" ]
1
2021-09-06T08:07:37.000Z
2021-09-06T08:07:37.000Z
#include "pch.h" #include "CameraComponent.h" #include "SerializationManager.h" #include "RenderManager.h" #include "Ray.h" #include "Transforms.h" #include "PostProcessing.h" UniEngine::CameraInfoBlock UniEngine::CameraComponent::m_cameraInfoBlock; std::unique_ptr<UniEngine::GLUBO> UniEngine::CameraComponent::m_cameraUniformBufferBlock; UniEngine::CameraLayerMask::CameraLayerMask() { m_value = 0; } UniEngine::Plane::Plane(): m_a(0), m_b(0), m_c(0), m_d(0) { } void UniEngine::Plane::Normalize() { const float mag = glm::sqrt(m_a * m_a + m_b * m_b + m_c * m_c); m_a /= mag; m_b /= mag; m_c /= mag; m_d /= mag; } void UniEngine::CameraComponent::StoreToJpg(const std::string& path, int resizeX, int resizeY) const { m_colorTexture->StoreToPng(path, resizeX, resizeY); } void UniEngine::CameraComponent::StoreToPng(const std::string& path, int resizeX, int resizeY, bool alphaChannel) const { m_colorTexture->StoreToPng(path, resizeX, resizeY, alphaChannel); } void UniEngine::CameraComponent::CalculatePlanes(std::vector<Plane>& planes, glm::mat4 projection, glm::mat4 view) { glm::mat4 comboMatrix = projection * glm::transpose(view); planes[0].m_a = comboMatrix[3][0] + comboMatrix[0][0]; planes[0].m_b = comboMatrix[3][1] + comboMatrix[0][1]; planes[0].m_c = comboMatrix[3][2] + comboMatrix[0][2]; planes[0].m_d = comboMatrix[3][3] + comboMatrix[0][3]; planes[1].m_a = comboMatrix[3][0] - comboMatrix[0][0]; planes[1].m_b = comboMatrix[3][1] - comboMatrix[0][1]; planes[1].m_c = comboMatrix[3][2] - comboMatrix[0][2]; planes[1].m_d = comboMatrix[3][3] - comboMatrix[0][3]; planes[2].m_a = comboMatrix[3][0] - comboMatrix[1][0]; planes[2].m_b = comboMatrix[3][1] - comboMatrix[1][1]; planes[2].m_c = comboMatrix[3][2] - comboMatrix[1][2]; planes[2].m_d = comboMatrix[3][3] - comboMatrix[1][3]; planes[3].m_a = comboMatrix[3][0] + comboMatrix[1][0]; planes[3].m_b = comboMatrix[3][1] + comboMatrix[1][1]; planes[3].m_c = comboMatrix[3][2] + comboMatrix[1][2]; planes[3].m_d = comboMatrix[3][3] + comboMatrix[1][3]; planes[4].m_a = comboMatrix[3][0] + comboMatrix[2][0]; planes[4].m_b = comboMatrix[3][1] + comboMatrix[2][1]; planes[4].m_c = comboMatrix[3][2] + comboMatrix[2][2]; planes[4].m_d = comboMatrix[3][3] + comboMatrix[2][3]; planes[5].m_a = comboMatrix[3][0] - comboMatrix[2][0]; planes[5].m_b = comboMatrix[3][1] - comboMatrix[2][1]; planes[5].m_c = comboMatrix[3][2] - comboMatrix[2][2]; planes[5].m_d = comboMatrix[3][3] - comboMatrix[2][3]; planes[0].Normalize(); planes[1].Normalize(); planes[2].Normalize(); planes[3].Normalize(); planes[4].Normalize(); planes[5].Normalize(); } void UniEngine::CameraComponent::CalculateFrustumPoints(float nearPlane, float farPlane, glm::vec3 cameraPos, glm::quat cameraRot, glm::vec3* points) const { const glm::vec3 front = cameraRot * glm::vec3(0, 0, -1); const glm::vec3 right = cameraRot * glm::vec3(1, 0, 0); const glm::vec3 up = cameraRot * glm::vec3(0, 1, 0); const glm::vec3 nearCenter = front * nearPlane; const glm::vec3 farCenter = front * farPlane; const float e = tanf(glm::radians(m_fov * 0.5f)); const float near_ext_y = e * nearPlane; const float near_ext_x = near_ext_y * GetResolutionRatio(); const float far_ext_y = e * farPlane; const float far_ext_x = far_ext_y * GetResolutionRatio(); points[0] = cameraPos + nearCenter - right * near_ext_x - up * near_ext_y; points[1] = cameraPos + nearCenter - right * near_ext_x + up * near_ext_y; points[2] = cameraPos + nearCenter + right * near_ext_x + up * near_ext_y; points[3] = cameraPos + nearCenter + right * near_ext_x - up * near_ext_y; points[4] = cameraPos + farCenter - right * far_ext_x - up * far_ext_y; points[5] = cameraPos + farCenter - right * far_ext_x + up * far_ext_y; points[6] = cameraPos + farCenter + right * far_ext_x + up * far_ext_y; points[7] = cameraPos + farCenter + right * far_ext_x - up * far_ext_y; } glm::quat UniEngine::CameraComponent::ProcessMouseMovement(float yawAngle, float pitchAngle, bool constrainPitch) { // Make sure that when pitch is out of bounds, screen doesn't get flipped if (constrainPitch) { if (pitchAngle > 89.0f) pitchAngle = 89.0f; if (pitchAngle < -89.0f) pitchAngle = -89.0f; } glm::vec3 front; front.x = cos(glm::radians(yawAngle)) * cos(glm::radians(pitchAngle)); front.y = sin(glm::radians(pitchAngle)); front.z = sin(glm::radians(yawAngle)) * cos(glm::radians(pitchAngle)); front = glm::normalize(front); const glm::vec3 right = glm::normalize(glm::cross(front, glm::vec3(0.0f, 1.0f, 0.0f))); // Normalize the vectors, because their length gets closer to 0 the more you look up or down which results in slower movement. const glm::vec3 up = glm::normalize(glm::cross(right, front)); return glm::quatLookAt(front, up); } void UniEngine::CameraComponent::ReverseAngle(const glm::quat& rotation, float& pitchAngle, float& yawAngle, const bool& constrainPitch) { const auto angle = glm::degrees(glm::eulerAngles(rotation)); pitchAngle = angle.x; yawAngle = glm::abs(angle.z) > 90.0f ? 90.0f - angle.y : -90.0f - angle.y; if (constrainPitch) { if (pitchAngle > 89.0f) pitchAngle = 89.0f; if (pitchAngle < -89.0f) pitchAngle = -89.0f; } } std::shared_ptr<UniEngine::Texture2D> UniEngine::CameraComponent::GetTexture() const { return m_colorTexture; } glm::mat4 UniEngine::CameraComponent::GetProjection() const { return glm::perspective(glm::radians(m_fov * 0.5f), GetResolutionRatio(), m_nearDistance, m_farDistance); } glm::vec3 UniEngine::CameraComponent::Project(GlobalTransform& ltw, glm::vec3 position) { return m_cameraInfoBlock.m_projection * m_cameraInfoBlock.m_view * glm::vec4(position, 1.0f); } glm::vec3 UniEngine::CameraComponent::UnProject(GlobalTransform& ltw, glm::vec3 position) const { glm::mat4 inversed = glm::inverse(m_cameraInfoBlock.m_projection * m_cameraInfoBlock.m_view); glm::vec4 start = glm::vec4( position, 1.0f); start = inversed * start; return start / start.w; } glm::vec3 UniEngine::CameraComponent::GetMouseWorldPoint(GlobalTransform& ltw, glm::vec2 mousePosition) const { const float halfX = static_cast<float>(m_resolutionX) / 2.0f; const float halfY = static_cast<float>(m_resolutionY) / 2.0f; const glm::vec4 start = glm::vec4( (mousePosition.x - halfX) / halfX, -1 * (mousePosition.y - halfY) / halfY, 0.0f, 1.0f); return start / start.w; } void UniEngine::CameraComponent::SetClearColor(glm::vec3 color) const { m_frameBuffer->ClearColor(glm::vec4(color.x, color.y, color.z, 0.0f)); m_frameBuffer->Clear(); m_frameBuffer->ClearColor(glm::vec4(0.0f)); } UniEngine::Ray UniEngine::CameraComponent::ScreenPointToRay(GlobalTransform& ltw, glm::vec2 mousePosition) const { const auto position = ltw.GetPosition(); const auto rotation = ltw.GetRotation(); const glm::vec3 front = rotation * glm::vec3(0, 0, -1); const glm::vec3 up = rotation * glm::vec3(0, 1, 0); const auto projection = glm::perspective(glm::radians(m_fov * 0.5f), GetResolutionRatio(), m_nearDistance, m_farDistance); const auto view = glm::lookAt(position, position + front, up); const glm::mat4 inv = glm::inverse(projection * view); const float halfX = static_cast<float>(m_resolutionX) / 2.0f; const float halfY = static_cast<float>(m_resolutionY) / 2.0f; const auto realX = (mousePosition.x + halfX) / halfX; const auto realY = (mousePosition.y - halfY) / halfY; if (glm::abs(realX) > 1.0f || glm::abs(realY) > 1.0f) return { glm::vec3(FLT_MAX), glm::vec3(FLT_MAX) }; glm::vec4 start = glm::vec4( realX, -1 * realY, -1, 1.0); glm::vec4 end = glm::vec4(realX, -1.0f * realY, 1.0f, 1.0f); start = inv * start; end = inv * end; start /= start.w; end /= end.w; const glm::vec3 dir = glm::normalize(glm::vec3(end - start)); return { glm::vec3(ltw.m_value[3]) + m_nearDistance * dir, glm::vec3(ltw.m_value[3]) + m_farDistance * dir }; } void UniEngine::CameraComponent::GenerateMatrices() { m_cameraUniformBufferBlock = std::make_unique<GLUBO>(); m_cameraUniformBufferBlock->SetData(sizeof(m_cameraInfoBlock), nullptr, GL_STREAM_DRAW); m_cameraUniformBufferBlock->SetBase(0); } void UniEngine::CameraComponent::Serialize(YAML::Emitter& out) { out << YAML::Key << "_ResolutionX" << YAML::Value << m_resolutionX; out << YAML::Key << "_ResolutionY" << YAML::Value << m_resolutionY; out << YAML::Key << "_IsMainCamera" << YAML::Value << m_isMainCamera; out << YAML::Key << "DrawSkyBox" << YAML::Value << m_drawSkyBox; out << YAML::Key << "ClearColor" << YAML::Value << m_clearColor; out << YAML::Key << "NearDistance" << YAML::Value << m_nearDistance; out << YAML::Key << "FarDistance" << YAML::Value << m_farDistance; out << YAML::Key << "FOV" << YAML::Value << m_fov; } void UniEngine::CameraComponent::Deserialize(const YAML::Node& in) { m_resolutionX = in["_ResolutionX"].as<int>(); m_resolutionY = in["_ResolutionY"].as<int>(); m_isMainCamera = in["_IsMainCamera"].as<bool>(); if (m_isMainCamera) RenderManager::SetMainCamera(this); m_drawSkyBox = in["DrawSkyBox"].as<bool>(); m_clearColor.x = in["ClearColor"][0].as<float>(); m_clearColor.y = in["ClearColor"][1].as<float>(); m_clearColor.z = in["ClearColor"][2].as<float>(); m_nearDistance = in["NearDistance"].as<float>(); m_farDistance = in["FarDistance"].as<float>(); m_fov = in["FOV"].as<float>(); } void UniEngine::CameraComponent::ResizeResolution(int x, int y) { if (m_resolutionX == x && m_resolutionY == y) return; m_resolutionX = x > 0 ? x : 1; m_resolutionY = y > 0 ? y : 1; m_gBuffer->SetResolution(m_resolutionX, m_resolutionY); m_gPositionBuffer->ReSize(0, GL_RGBA32F, GL_RGBA, GL_FLOAT, 0, m_resolutionX, m_resolutionY); m_gNormalBuffer->ReSize(0, GL_RGBA32F, GL_RGBA, GL_FLOAT, 0, m_resolutionX, m_resolutionY); m_gColorSpecularBuffer->ReSize(0, GL_RGBA32F, GL_RGBA, GL_FLOAT, 0, m_resolutionX, m_resolutionY); m_gMetallicRoughnessAo->ReSize(0, GL_RGBA32F, GL_RGBA, GL_FLOAT, 0, m_resolutionX, m_resolutionY); m_gDepthBuffer->AllocateStorage(GL_DEPTH32F_STENCIL8, m_resolutionX, m_resolutionY); m_colorTexture->m_texture->ReSize(0, GL_RGBA32F, GL_RGBA, GL_FLOAT, 0, m_resolutionX, m_resolutionY); m_depthStencilBuffer->ReSize(0, GL_DEPTH32F_STENCIL8, GL_DEPTH_STENCIL, GL_FLOAT_32_UNSIGNED_INT_24_8_REV, 0, m_resolutionX, m_resolutionY); if(GetOwner().HasPrivateComponent<PostProcessing>()) { GetOwner().GetPrivateComponent<PostProcessing>()->ResizeResolution(m_resolutionX, m_resolutionY); } } UniEngine::CameraComponent::CameraComponent() { m_resolutionX = 1; m_resolutionY = 1; m_colorTexture = std::make_shared<Texture2D>(); m_colorTexture->m_name = "CameraTexture"; m_colorTexture->m_texture = std::make_shared<GLTexture2D>(0, GL_RGBA32F, m_resolutionX, m_resolutionY, false); m_colorTexture->m_texture->SetData(0, GL_RGBA32F, GL_RGBA, GL_FLOAT, 0); m_colorTexture->m_texture->SetInt(GL_TEXTURE_MIN_FILTER, GL_NEAREST); m_colorTexture->m_texture->SetInt(GL_TEXTURE_MAG_FILTER, GL_NEAREST); m_colorTexture->m_texture->SetInt(GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); m_colorTexture->m_texture->SetInt(GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); AttachTexture(m_colorTexture->m_texture.get(), GL_COLOR_ATTACHMENT0); m_depthStencilBuffer = std::make_unique<GLTexture2D>(0, GL_DEPTH32F_STENCIL8, m_resolutionX, m_resolutionY, false); m_depthStencilBuffer->SetData(0, GL_DEPTH32F_STENCIL8, GL_DEPTH_STENCIL, GL_FLOAT_32_UNSIGNED_INT_24_8_REV, 0); m_depthStencilBuffer->SetInt(GL_TEXTURE_MIN_FILTER, GL_NEAREST); m_depthStencilBuffer->SetInt(GL_TEXTURE_MAG_FILTER, GL_NEAREST); m_depthStencilBuffer->SetInt(GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); m_depthStencilBuffer->SetInt(GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); AttachTexture(m_depthStencilBuffer.get(), GL_DEPTH_STENCIL_ATTACHMENT); m_gBuffer = std::make_unique<RenderTarget>(m_resolutionX, m_resolutionY); m_gDepthBuffer = std::make_unique<GLRenderBuffer>(); m_gDepthBuffer->AllocateStorage(GL_DEPTH32F_STENCIL8, m_resolutionX, m_resolutionY); m_gBuffer->AttachRenderBuffer(m_gDepthBuffer.get(), GL_DEPTH_STENCIL_ATTACHMENT); m_gPositionBuffer = std::make_unique<GLTexture2D>(0, GL_RGBA32F, m_resolutionX, m_resolutionY, false); m_gPositionBuffer->SetData(0, GL_RGBA32F, GL_RGBA, GL_FLOAT, 0); m_gPositionBuffer->SetInt(GL_TEXTURE_MIN_FILTER, GL_NEAREST); m_gPositionBuffer->SetInt(GL_TEXTURE_MAG_FILTER, GL_NEAREST); m_gPositionBuffer->SetInt(GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); m_gPositionBuffer->SetInt(GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); m_gBuffer->AttachTexture(m_gPositionBuffer.get(), GL_COLOR_ATTACHMENT0); m_gNormalBuffer = std::make_unique <GLTexture2D>(0, GL_RGBA32F, m_resolutionX, m_resolutionY, false); m_gNormalBuffer->SetData(0, GL_RGBA32F, GL_RGBA, GL_FLOAT, 0); m_gNormalBuffer->SetInt(GL_TEXTURE_MIN_FILTER, GL_NEAREST); m_gNormalBuffer->SetInt(GL_TEXTURE_MAG_FILTER, GL_NEAREST); m_gNormalBuffer->SetInt(GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); m_gNormalBuffer->SetInt(GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); m_gBuffer->AttachTexture(m_gNormalBuffer.get(), GL_COLOR_ATTACHMENT1); m_gColorSpecularBuffer = std::make_unique<GLTexture2D>(0, GL_RGBA32F, m_resolutionX, m_resolutionY, false); m_gColorSpecularBuffer->SetData(0, GL_RGBA32F, GL_RGBA, GL_FLOAT, 0); m_gColorSpecularBuffer->SetInt(GL_TEXTURE_MIN_FILTER, GL_NEAREST); m_gColorSpecularBuffer->SetInt(GL_TEXTURE_MAG_FILTER, GL_NEAREST); m_gColorSpecularBuffer->SetInt(GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); m_gColorSpecularBuffer->SetInt(GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); m_gBuffer->AttachTexture(m_gColorSpecularBuffer.get(), GL_COLOR_ATTACHMENT2); m_gMetallicRoughnessAo = std::make_unique<GLTexture2D>(0, GL_RGBA32F, m_resolutionX, m_resolutionY, false); m_gMetallicRoughnessAo->SetData(0, GL_RGBA32F, GL_RGBA, GL_FLOAT, 0); m_gMetallicRoughnessAo->SetInt(GL_TEXTURE_MIN_FILTER, GL_NEAREST); m_gMetallicRoughnessAo->SetInt(GL_TEXTURE_MAG_FILTER, GL_NEAREST); m_gMetallicRoughnessAo->SetInt(GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); m_gMetallicRoughnessAo->SetInt(GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); m_gBuffer->AttachTexture(m_gMetallicRoughnessAo.get(), GL_COLOR_ATTACHMENT3); SetEnabled(true); } UniEngine::CameraComponent::~CameraComponent() { if (RenderManager::GetMainCamera() == this) { RenderManager::SetMainCamera(nullptr); } } void UniEngine::CameraComponent::OnGui() { ImGui::Checkbox("Allow auto resize", &m_allowAutoResize); if(!m_allowAutoResize) { glm::ivec2 resolution = { m_resolutionX, m_resolutionY }; if(ImGui::DragInt2("Resolution", &resolution.x)) { ResizeResolution(resolution.x, resolution.y); } } ImGui::Checkbox("Skybox", &m_drawSkyBox); const bool savedState = m_isMainCamera; ImGui::Checkbox("Main Camera", &m_isMainCamera); if(savedState != m_isMainCamera) { if(m_isMainCamera) { RenderManager::SetMainCamera(this); }else { RenderManager::SetMainCamera(nullptr); } } if(!m_drawSkyBox) { ImGui::ColorEdit3("Clear Color", (float*)(void*)&m_clearColor); } ImGui::DragFloat("Near", &m_nearDistance, m_nearDistance / 10.0f, 0, m_farDistance); ImGui::DragFloat("Far", &m_farDistance, m_farDistance / 10.0f, m_nearDistance); ImGui::DragFloat("FOV", &m_fov, 1.0f, 1, 359); if (ImGui::TreeNode("Content")) { ImGui::Image((ImTextureID)m_colorTexture->Texture()->Id(), ImVec2(m_resolutionX / 5.0f, m_resolutionY / 5.0f), ImVec2(0, 1), ImVec2(1, 0)); if (ImGui::Button("Take Screenshot")) { StoreToJpg("screenshot.jpg"); } if (ImGui::Button("Take Screenshot (with alpha)")) { StoreToPng("greyscale.png", -1, -1, true); } ImGui::TreePop(); } } void UniEngine::CameraInfoBlock::UpdateMatrices(const CameraComponent* camera, glm::vec3 position, glm::quat rotation) { const glm::vec3 front = rotation * glm::vec3(0, 0, -1); const glm::vec3 up = rotation * glm::vec3(0, 1, 0); const auto ratio = camera->GetResolutionRatio(); m_projection = glm::perspective(glm::radians(camera->m_fov * 0.5f), ratio, camera->m_nearDistance, camera->m_farDistance); m_position = glm::vec4(position, 0); m_view = glm::lookAt(position, position + front, up); m_reservedParameters = glm::vec4(camera->m_nearDistance, camera->m_farDistance, glm::tan(camera->m_fov * 0.5f), camera->m_resolutionX / camera->m_resolutionY); m_backGroundColor = glm::vec4(camera->m_clearColor, 1.0f); if (camera->m_skyBox) { m_skybox = camera->m_skyBox->Texture()->GetHandle(); m_skyboxEnabled = true; } else { m_skybox = 0; m_skyboxEnabled = false; } } void UniEngine::CameraInfoBlock::UploadMatrices(const CameraComponent* camera) const { CameraComponent::m_cameraUniformBufferBlock->SubData(0, sizeof(CameraInfoBlock), this); }
40.621951
216
0.735035
edisonlee0212
587c08fae13d50bc37a77a34d886f5c938899c76
14,588
cpp
C++
test/Analysis/diagnostics/no-store-func-path-notes.cpp
matthewelse/clang
b3ac9db345ddce6397784517cd0c41529220ab8c
[ "Apache-2.0" ]
115
2018-02-01T18:56:44.000Z
2022-03-21T13:23:00.000Z
test/Analysis/diagnostics/no-store-func-path-notes.cpp
matthewelse/clang
b3ac9db345ddce6397784517cd0c41529220ab8c
[ "Apache-2.0" ]
27
2018-09-17T17:49:49.000Z
2021-11-03T04:31:51.000Z
test/Analysis/diagnostics/no-store-func-path-notes.cpp
matthewelse/clang
b3ac9db345ddce6397784517cd0c41529220ab8c
[ "Apache-2.0" ]
55
2018-02-01T07:11:49.000Z
2022-03-04T01:20:23.000Z
// RUN: %clang_analyze_cc1 -x c++ -std=c++14 -analyzer-checker=core -analyzer-output=text -verify %s int initializer1(int &p, int x) { if (x) { // expected-note{{Taking false branch}} p = 1; return 0; } else { return 1; // expected-note {{Returning without writing to 'p'}} } } int param_not_initialized_by_func() { int outP; // expected-note {{'outP' declared without an initial value}} int out = initializer1(outP, 0); // expected-note{{Calling 'initializer1'}} // expected-note@-1{{Returning from 'initializer1'}} return outP; // expected-note{{Undefined or garbage value returned to caller}} // expected-warning@-1{{Undefined or garbage value returned to caller}} } struct S { int initialize(int *p, int param) { if (param) { //expected-note{{Taking false branch}} *p = 1; return 1; } return 0; // expected-note{{Returning without writing to '*p'}} } }; int use(S *s) { int p; //expected-note{{'p' declared without an initial value}} s->initialize(&p, 0); //expected-note{{Calling 'S::initialize'}} //expected-note@-1{{Returning from 'S::initialize'}} return p; // expected-warning{{Undefined or garbage value returned to caller}} // expected-note@-1{{Undefined or garbage value returned to caller}} } int initializer2(const int &p) { return 0; } int no_msg_const_ref() { int p; //expected-note{{'p' declared without an initial value}} initializer2(p); return p; // expected-warning{{Undefined or garbage value returned to caller}} // expected-note@-1{{Undefined or garbage value returned to caller}} } void nested() {} void init_in_nested_func(int **x) { *x = 0; // expected-note{{Null pointer value stored to 'y'}} nested(); } // no-note int call_init_nested() { int x = 0; int *y = &x; init_in_nested_func(&y); // expected-note{{Calling 'init_in_nested_func'}} // expected-note@-1{{Returning from 'init_in_nested_func'}} return *y; //expected-warning{{Dereference of null pointer (loaded from variable 'y')}} //expected-note@-1{{Dereference of null pointer (loaded from variable 'y')}} } struct A { int x; int y; }; void partial_init_by_reference(A &a) { a.x = 0; } // expected-note {{Returning without writing to 'a.y'}} int use_partial_init_by_reference() { A a; partial_init_by_reference(a); // expected-note{{Calling 'partial_init_by_reference'}} // expected-note@-1{{Returning from 'partial_init_by_reference'}} return a.y; // expected-warning{{Undefined or garbage value returned to caller}} // expected-note@-1{{Undefined or garbage value returned to caller}} } struct B : A { }; void partially_init_inherited_struct(B *b) { b->x = 0; } // expected-note{{Returning without writing to 'b->y'}} int use_partially_init_inherited_struct() { B b; partially_init_inherited_struct(&b); // expected-note{{Calling 'partially_init_inherited_struct'}} // expected-note@-1{{Returning from 'partially_init_inherited_struct'}} return b.y; // expected-warning{{Undefined or garbage value returned to caller}} // expected-note@-1{{Undefined or garbage value returned to caller}} } struct C { int x; int y; C(int pX, int pY) : x(pX) {} // expected-note{{Returning without writing to 'this->y'}} C(int pX, int pY, bool Flag) { x = pX; if (Flag) // expected-note{{Assuming 'Flag' is not equal to 0}} // expected-note@-1{{Taking true branch}} return; // expected-note{{Returning without writing to 'this->y'}} y = pY; } }; int use_constructor() { C c(0, 0); // expected-note{{Calling constructor for 'C'}} // expected-note@-1{{Returning from constructor for 'C'}} return c.y; // expected-note{{Undefined or garbage value returned to caller}} // expected-warning@-1{{Undefined or garbage value returned to caller}} } int coin(); int use_other_constructor() { C c(0, 0, coin()); // expected-note{{Calling constructor for 'C'}} // expected-note@-1{{Returning from constructor for 'C'}} return c.y; // expected-note{{Undefined or garbage value returned to caller}} // expected-warning@-1{{Undefined or garbage value returned to caller}} } struct D { void initialize(int *); }; void D::initialize(int *p) { } // expected-note{{Returning without writing to '*p'}} int use_d_initializer(D* d) { int p; // expected-note {{'p' declared without an initial value}} d->initialize(&p); // expected-note{{Calling 'D::initialize'}} // expected-note@-1{{Returning from 'D::initialize'}} return p; // expected-note{{Undefined or garbage value returned to caller}} // expected-warning@-1{{Undefined or garbage value returned to caller}} } struct S2 { int x; }; int pointerreference(S2* &s) { if (coin()) // expected-note{{Assuming the condition is true}} // expected-note@-1{{Taking true branch}} return 1; // expected-note{{Returning without writing to 's->x'}} s->x = 0; return 0; } int usepointerreference() { S2 s; S2* p = &s; pointerreference(p); //expected-note{{Calling 'pointerreference'}} //expected-note@-1{{Returning from 'pointerreference'}} return s.x; // expected-warning{{Undefined or garbage value returned to caller}} // expected-note@-1{{Undefined or garbage value returned to caller}} } void *has_no_argument_and_returns_null(void) { return 0; } void rdar40335545() { int local; // expected-note{{}} void (*takes_int_ptr_argument)(int *) = (void (*)(int*))has_no_argument_and_returns_null; takes_int_ptr_argument(&local); // no-crash int useLocal = local; //expected-warning{{}} //expected-note@-1{{}} (void)useLocal; } //////// struct HasRef { int &a; HasRef(int &a) : a(a) {} }; void maybeInitialize(const HasRef &&pA) { if (coin()) // expected-note{{Assuming the condition is false}} // expected-note@-1{{Taking false branch}} pA.a = 120; } // expected-note{{Returning without writing to 'pA.a'}} int useMaybeInitializerWritingIntoField() { int z; // expected-note{{'z' declared without an initial value}} maybeInitialize(HasRef(z)); // expected-note{{Calling constructor for 'HasRef'}} // expected-note@-1{{Returning from constructor for 'HasRef'}} // expected-note@-2{{Calling 'maybeInitialize'}} // expected-note@-3{{Returning from 'maybeInitialize'}} return z; // expected-warning{{Undefined or garbage value returned to caller}} // expected-note@-1{{Undefined or garbage value returned to caller}} } //////// struct HasRefToItself { HasRefToItself &Ref; // no infinite loop int &z; HasRefToItself(int &z) : Ref(*this), z(z) {} }; void maybeInitialize(const HasRefToItself &&pA) { if (coin()) // expected-note{{Assuming the condition is false}} // expected-note@-1{{Taking false branch}} pA.z = 120; } // expected-note{{Returning without writing to 'pA.Ref.z'}} int useMaybeInitializerWritingIntoFieldWithRefToItself() { int z; // expected-note{{'z' declared without an initial value}} maybeInitialize(HasRefToItself(z)); // expected-note{{Calling constructor for 'HasRefToItself'}} // expected-note@-1{{Returning from constructor for 'HasRefToItself'}} // expected-note@-2{{Calling 'maybeInitialize'}} // expected-note@-3{{Returning from 'maybeInitialize'}} return z; // expected-warning{{Undefined or garbage value returned to caller}} // expected-note@-1{{Undefined or garbage value returned to caller}} } //// void maybeInitialize(const HasRef *pA) { if (coin()) // expected-note{{Assuming the condition is false}} // expected-note@-1{{Taking false branch}} pA->a = 120; } // expected-note{{Returning without writing to 'pA->a'}} int useMaybeInitializerStructByPointer() { int z; // expected-note{{'z' declared without an initial value}} HasRef wrapper(z); // expected-note{{Calling constructor for 'HasRef'}} // expected-note@-1{{Returning from constructor for 'HasRef'}} maybeInitialize(&wrapper); // expected-note{{Calling 'maybeInitialize'}} // expected-note@-1{{Returning from 'maybeInitialize'}} return z; // expected-warning{{Undefined or garbage value returned to caller}} // expected-note@-1{{Undefined or garbage value returned to caller}} } //////// struct HasParentWithRef : public HasRef { HasParentWithRef(int &a) : HasRef(a) {} // expected-note{{Calling constructor for 'HasRef'}} // expected-note@-1{{Returning from constructor for 'HasRef'}} }; void maybeInitializeWithParent(const HasParentWithRef &pA) { if (coin()) // expected-note{{Assuming the condition is false}} // expected-note@-1{{Taking false branch}} pA.a = 120; } // expected-note{{Returning without writing to 'pA.a'}} int useMaybeInitializerWritingIntoParentField() { int z; // expected-note{{'z' declared without an initial value}} maybeInitializeWithParent(HasParentWithRef(z)); // expected-note{{Calling constructor for 'HasParentWithRef'}} // expected-note@-1{{Returning from constructor for 'HasParentWithRef'}} // expected-note@-2{{Calling 'maybeInitializeWithParent'}} // expected-note@-3{{Returning from 'maybeInitializeWithParent'}} return z; // expected-warning{{Undefined or garbage value returned to caller}} // expected-note@-1{{Undefined or garbage value returned to caller}} } //////// struct HasIndirectRef { HasRef &Ref; HasIndirectRef(HasRef &Ref) : Ref(Ref) {} }; void maybeInitializeIndirectly(const HasIndirectRef &pA) { if (coin()) // expected-note{{Assuming the condition is false}} // expected-note@-1{{Taking false branch}} pA.Ref.a = 120; } // expected-note{{Returning without writing to 'pA.Ref.a'}} int useMaybeInitializeIndirectly() { int z; // expected-note{{'z' declared without an initial value}} HasRef r(z); // expected-note{{Calling constructor for 'HasRef'}} // expected-note@-1{{Returning from constructor for 'HasRef'}} maybeInitializeIndirectly(HasIndirectRef(r)); // expected-note{{Calling 'maybeInitializeIndirectly'}} // expected-note@-1{{Returning from 'maybeInitializeIndirectly'}} return z; // expected-warning{{Undefined or garbage value returned to caller}} // expected-note@-1{{Undefined or garbage value returned to caller}} } //////// struct HasIndirectRefByValue { HasRef Ref; HasIndirectRefByValue(HasRef Ref) : Ref(Ref) {} }; void maybeInitializeIndirectly(const HasIndirectRefByValue &pA) { if (coin()) // expected-note{{Assuming the condition is false}} // expected-note@-1{{Taking false branch}} pA.Ref.a = 120; } // expected-note{{Returning without writing to 'pA.Ref.a'}} int useMaybeInitializeIndirectlyIndirectRefByValue() { int z; // expected-note{{'z' declared without an initial value}} HasRef r(z); // expected-note{{Calling constructor for 'HasRef'}} // expected-note@-1{{Returning from constructor for 'HasRef'}} maybeInitializeIndirectly(HasIndirectRefByValue(r)); // expected-note{{Calling 'maybeInitializeIndirectly'}} // expected-note@-1{{Returning from 'maybeInitializeIndirectly'}} return z; // expected-warning{{Undefined or garbage value returned to caller}} // expected-note@-1{{Undefined or garbage value returned to caller}} } //////// struct HasIndirectPointerRef { HasRef *Ref; HasIndirectPointerRef(HasRef *Ref) : Ref(Ref) {} }; void maybeInitializeIndirectly(const HasIndirectPointerRef &pA) { if (coin()) // expected-note{{Assuming the condition is false}} // expected-note@-1{{Taking false branch}} pA.Ref->a = 120; } // expected-note{{Returning without writing to 'pA.Ref->a'}} int useMaybeInitializeIndirectlyWithPointer() { int z; // expected-note{{'z' declared without an initial value}} HasRef r(z); // expected-note{{Calling constructor for 'HasRef'}} // expected-note@-1{{Returning from constructor for 'HasRef'}} maybeInitializeIndirectly(HasIndirectPointerRef(&r)); // expected-note{{Calling 'maybeInitializeIndirectly'}} // expected-note@-1{{Returning from 'maybeInitializeIndirectly'}} return z; // expected-warning{{Undefined or garbage value returned to caller}} // expected-note@-1{{Undefined or garbage value returned to caller}} } //////// struct HasFieldA { int x; }; struct HasFieldB { int x; }; void maybeInitializeHasField(HasFieldA *b) { if (coin()) // expected-note{{Assuming the condition is false}} // expected-note@-1{{Taking false branch}} ((HasFieldB*)b)->x = 120; } int forceElementRegionApperence() { HasFieldA a; maybeInitializeHasField(&a); // expected-note{{Calling 'maybeInitializeHasField'}} // expected-note@-1{{Returning from 'maybeInitializeHasField'}} return ((HasFieldB*)&a)->x; // expected-warning{{Undefined or garbage value returned to caller}} // expected-note@-1{{Undefined or garbage value returned to caller}} } //////// struct HasForgottenField { int x; HasForgottenField() {} // expected-note{{Returning without writing to 'this->x'}} }; // Test that tracking across exclamation mark works. bool tracksThroughExclamationMark() { HasForgottenField a; // expected-note{{Calling default constructor for 'HasForgottenField'}} // expected-note@-1{{Returning from default constructor for 'HasForgottenField'}} return !a.x; // expected-warning{{Undefined or garbage value returned to caller}} // expected-note@-1{{Undefined or garbage value returned to caller}} }
38.901333
113
0.631889
matthewelse
587f7375d749efb7ef0eeef2dca60b3283021eea
975
cc
C++
ui/accessibility/ax_node.cc
domenic/mojo
53dda76fed90a47c35ed6e06baf833a0d44495b8
[ "BSD-3-Clause" ]
5
2019-05-24T01:25:34.000Z
2020-04-06T05:07:01.000Z
ui/accessibility/ax_node.cc
domenic/mojo
53dda76fed90a47c35ed6e06baf833a0d44495b8
[ "BSD-3-Clause" ]
1
2018-02-10T21:00:08.000Z
2018-03-20T05:09:50.000Z
ui/accessibility/ax_node.cc
domenic/mojo
53dda76fed90a47c35ed6e06baf833a0d44495b8
[ "BSD-3-Clause" ]
5
2016-12-23T04:21:10.000Z
2020-06-18T13:52:33.000Z
// Copyright 2013 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 "ui/accessibility/ax_node.h" namespace ui { AXNode::AXNode(AXNode* parent, int32 id, int32 index_in_parent) : index_in_parent_(index_in_parent), parent_(parent) { data_.id = id; } AXNode::~AXNode() { } void AXNode::SetData(const AXNodeData& src) { data_ = src; } void AXNode::SetLocation(const gfx::Rect& new_location) { data_.location = new_location; } void AXNode::SetIndexInParent(int index_in_parent) { index_in_parent_ = index_in_parent; } void AXNode::SwapChildren(std::vector<AXNode*>& children) { children.swap(children_); } void AXNode::Destroy() { delete this; } bool AXNode::IsDescendantOf(AXNode* ancestor) { if (this == ancestor) return true; else if (parent()) return parent()->IsDescendantOf(ancestor); return false; } } // namespace ui
20.3125
73
0.710769
domenic
5880a48731ff360303e1dc551daf9f1b389f0846
1,147
cpp
C++
fizz/tool/Main.cpp
karthikbhargavan/fizz
0d57338a2ff5e3a57ea0aaf1d9c96a8a04a07164
[ "BSD-3-Clause" ]
null
null
null
fizz/tool/Main.cpp
karthikbhargavan/fizz
0d57338a2ff5e3a57ea0aaf1d9c96a8a04a07164
[ "BSD-3-Clause" ]
null
null
null
fizz/tool/Main.cpp
karthikbhargavan/fizz
0d57338a2ff5e3a57ea0aaf1d9c96a8a04a07164
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2018-present, 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. */ #include <fizz/tool/Commands.h> #include <folly/ssl/Init.h> #include <glog/logging.h> #include <iostream> #include <string> #include <vector> using namespace fizz::tool; void showUsage() { std::cerr << "Supported commands:" << std::endl; for (const auto& command : fizzUtilities) { std::cerr << " - " << command.first << std::endl; } std::cerr << std::endl; } int main(int argc, char** argv) { google::InitGoogleLogging(argv[0]); FLAGS_logtostderr = 1; folly::ssl::init(); std::vector<std::string> arguments; for (int i = 0; i < argc; i++) { arguments.push_back(argv[i]); } if (arguments.size() < 2) { showUsage(); return 1; } else { if (fizzUtilities.count(arguments[1])) { return fizzUtilities.at(arguments[1])(arguments); } else { std::cerr << "Unknown command '" << arguments[1] << "'." << std::endl; showUsage(); return 1; } } return 0; }
22.94
76
0.617262
karthikbhargavan
58816db79e87b85ee24e322f39caa4695737ce92
4,789
cc
C++
test/unittests/base/division-by-constant-unittest.cc
RiyoCoder/v8
e073edfc7dc990cc5f71c4e51ac27b19be16fcb7
[ "BSD-3-Clause" ]
5,964
2016-09-27T03:46:29.000Z
2022-03-31T16:25:27.000Z
v8_7_5/test/unittests/base/division-by-constant-unittest.cc
w4454962/miniblink49
b294b6eacb3333659bf7b94d670d96edeeba14c0
[ "Apache-2.0" ]
479
2016-02-10T00:21:41.000Z
2020-11-26T09:40:03.000Z
v8_7_5/test/unittests/base/division-by-constant-unittest.cc
w4454962/miniblink49
b294b6eacb3333659bf7b94d670d96edeeba14c0
[ "Apache-2.0" ]
1,006
2016-09-27T05:17:27.000Z
2022-03-30T02:46:51.000Z
// Copyright 2014 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Check all examples from table 10-1 of "Hacker's Delight". #include "src/base/division-by-constant.h" #include <stdint.h> #include <ostream> // NOLINT #include "testing/gtest-support.h" namespace v8 { namespace base { template <class T> std::ostream& operator<<(std::ostream& os, const MagicNumbersForDivision<T>& mag) { return os << "{ multiplier: " << mag.multiplier << ", shift: " << mag.shift << ", add: " << mag.add << " }"; } // Some abbreviations... typedef MagicNumbersForDivision<uint32_t> M32; typedef MagicNumbersForDivision<uint64_t> M64; static M32 s32(int32_t d) { return SignedDivisionByConstant<uint32_t>(static_cast<uint32_t>(d)); } static M64 s64(int64_t d) { return SignedDivisionByConstant<uint64_t>(static_cast<uint64_t>(d)); } static M32 u32(uint32_t d) { return UnsignedDivisionByConstant<uint32_t>(d); } static M64 u64(uint64_t d) { return UnsignedDivisionByConstant<uint64_t>(d); } TEST(DivisionByConstant, Signed32) { EXPECT_EQ(M32(0x99999999U, 1, false), s32(-5)); EXPECT_EQ(M32(0x55555555U, 1, false), s32(-3)); int32_t d = -1; for (unsigned k = 1; k <= 32 - 1; ++k) { d *= 2; EXPECT_EQ(M32(0x7FFFFFFFU, k - 1, false), s32(d)); } for (unsigned k = 1; k <= 32 - 2; ++k) { EXPECT_EQ(M32(0x80000001U, k - 1, false), s32(1 << k)); } EXPECT_EQ(M32(0x55555556U, 0, false), s32(3)); EXPECT_EQ(M32(0x66666667U, 1, false), s32(5)); EXPECT_EQ(M32(0x2AAAAAABU, 0, false), s32(6)); EXPECT_EQ(M32(0x92492493U, 2, false), s32(7)); EXPECT_EQ(M32(0x38E38E39U, 1, false), s32(9)); EXPECT_EQ(M32(0x66666667U, 2, false), s32(10)); EXPECT_EQ(M32(0x2E8BA2E9U, 1, false), s32(11)); EXPECT_EQ(M32(0x2AAAAAABU, 1, false), s32(12)); EXPECT_EQ(M32(0x51EB851FU, 3, false), s32(25)); EXPECT_EQ(M32(0x10624DD3U, 3, false), s32(125)); EXPECT_EQ(M32(0x68DB8BADU, 8, false), s32(625)); } TEST(DivisionByConstant, Unsigned32) { EXPECT_EQ(M32(0x00000000U, 0, true), u32(1)); for (unsigned k = 1; k <= 30; ++k) { EXPECT_EQ(M32(1U << (32 - k), 0, false), u32(1U << k)); } EXPECT_EQ(M32(0xAAAAAAABU, 1, false), u32(3)); EXPECT_EQ(M32(0xCCCCCCCDU, 2, false), u32(5)); EXPECT_EQ(M32(0xAAAAAAABU, 2, false), u32(6)); EXPECT_EQ(M32(0x24924925U, 3, true), u32(7)); EXPECT_EQ(M32(0x38E38E39U, 1, false), u32(9)); EXPECT_EQ(M32(0xCCCCCCCDU, 3, false), u32(10)); EXPECT_EQ(M32(0xBA2E8BA3U, 3, false), u32(11)); EXPECT_EQ(M32(0xAAAAAAABU, 3, false), u32(12)); EXPECT_EQ(M32(0x51EB851FU, 3, false), u32(25)); EXPECT_EQ(M32(0x10624DD3U, 3, false), u32(125)); EXPECT_EQ(M32(0xD1B71759U, 9, false), u32(625)); } TEST(DivisionByConstant, Signed64) { EXPECT_EQ(M64(0x9999999999999999ULL, 1, false), s64(-5)); EXPECT_EQ(M64(0x5555555555555555ULL, 1, false), s64(-3)); int64_t d = -1; for (unsigned k = 1; k <= 64 - 1; ++k) { d *= 2; EXPECT_EQ(M64(0x7FFFFFFFFFFFFFFFULL, k - 1, false), s64(d)); } for (unsigned k = 1; k <= 64 - 2; ++k) { EXPECT_EQ(M64(0x8000000000000001ULL, k - 1, false), s64(1LL << k)); } EXPECT_EQ(M64(0x5555555555555556ULL, 0, false), s64(3)); EXPECT_EQ(M64(0x6666666666666667ULL, 1, false), s64(5)); EXPECT_EQ(M64(0x2AAAAAAAAAAAAAABULL, 0, false), s64(6)); EXPECT_EQ(M64(0x4924924924924925ULL, 1, false), s64(7)); EXPECT_EQ(M64(0x1C71C71C71C71C72ULL, 0, false), s64(9)); EXPECT_EQ(M64(0x6666666666666667ULL, 2, false), s64(10)); EXPECT_EQ(M64(0x2E8BA2E8BA2E8BA3ULL, 1, false), s64(11)); EXPECT_EQ(M64(0x2AAAAAAAAAAAAAABULL, 1, false), s64(12)); EXPECT_EQ(M64(0xA3D70A3D70A3D70BULL, 4, false), s64(25)); EXPECT_EQ(M64(0x20C49BA5E353F7CFULL, 4, false), s64(125)); EXPECT_EQ(M64(0x346DC5D63886594BULL, 7, false), s64(625)); } TEST(DivisionByConstant, Unsigned64) { EXPECT_EQ(M64(0x0000000000000000ULL, 0, true), u64(1)); for (unsigned k = 1; k <= 64 - 2; ++k) { EXPECT_EQ(M64(1ULL << (64 - k), 0, false), u64(1ULL << k)); } EXPECT_EQ(M64(0xAAAAAAAAAAAAAAABULL, 1, false), u64(3)); EXPECT_EQ(M64(0xCCCCCCCCCCCCCCCDULL, 2, false), u64(5)); EXPECT_EQ(M64(0xAAAAAAAAAAAAAAABULL, 2, false), u64(6)); EXPECT_EQ(M64(0x2492492492492493ULL, 3, true), u64(7)); EXPECT_EQ(M64(0xE38E38E38E38E38FULL, 3, false), u64(9)); EXPECT_EQ(M64(0xCCCCCCCCCCCCCCCDULL, 3, false), u64(10)); EXPECT_EQ(M64(0x2E8BA2E8BA2E8BA3ULL, 1, false), u64(11)); EXPECT_EQ(M64(0xAAAAAAAAAAAAAAABULL, 3, false), u64(12)); EXPECT_EQ(M64(0x47AE147AE147AE15ULL, 5, true), u64(25)); EXPECT_EQ(M64(0x0624DD2F1A9FBE77ULL, 7, true), u64(125)); EXPECT_EQ(M64(0x346DC5D63886594BULL, 7, false), u64(625)); } } // namespace base } // namespace v8
35.474074
78
0.672583
RiyoCoder
58847ea14fe47c6762ba364031a4e47789a884e6
698
cpp
C++
aizu/illumination.test.cpp
hasegawa1/procon-library
9fea96b3f1ebcb44c08e413a2a9ecb22dc7cd39e
[ "MIT" ]
null
null
null
aizu/illumination.test.cpp
hasegawa1/procon-library
9fea96b3f1ebcb44c08e413a2a9ecb22dc7cd39e
[ "MIT" ]
6
2021-07-25T10:37:08.000Z
2021-11-20T14:06:46.000Z
aizu/illumination.test.cpp
hasegawa1/procon-library
9fea96b3f1ebcb44c08e413a2a9ecb22dc7cd39e
[ "MIT" ]
null
null
null
#define PROBLEM "https://onlinejudge.u-aizu.ac.jp/challenges/sources/JOI/Final/0603" #include <iostream> #include <vector> #include "../other/run_length_encoding.cpp" using namespace std; int main(void) { cin.tie(nullptr); ios_base::sync_with_stdio(false); int N; cin >> N; vector<int> v(N); for(int i=0; i<N; i++) { cin >> v[i]; } for(int i=0; i<N; i++) { v[i] ^= i%2; } auto v2 = run_length_encoding(v); v2.emplace_back(0, 0); v2.emplace_back(0, 0); int ans = 0; for(int i=0; i+2<v2.size(); i++) { ans = max(ans, v2[i].second + v2[i+1].second + v2[i+2].second); } cout << ans << endl; return 0; }
19.942857
84
0.553009
hasegawa1
5884c25112e4c430c2617967ce7dd9999990dd72
5,389
cpp
C++
source/threads/_unix/vthread_platform.cpp
xvela/code-vault
780dad2d2855e28d802a64baf781927b7edd9ed9
[ "MIT" ]
2
2019-01-09T19:09:45.000Z
2019-04-02T17:53:49.000Z
source/threads/_unix/vthread_platform.cpp
xvela/code-vault
780dad2d2855e28d802a64baf781927b7edd9ed9
[ "MIT" ]
17
2015-01-07T02:05:04.000Z
2019-08-30T16:57:42.000Z
source/threads/_unix/vthread_platform.cpp
xvela/code-vault
780dad2d2855e28d802a64baf781927b7edd9ed9
[ "MIT" ]
3
2016-04-06T19:01:11.000Z
2017-09-20T09:28:00.000Z
/* Copyright c1997-2014 Trygve Isaacson. All rights reserved. This file is part of the Code Vault version 4.1 http://www.bombaydigital.com/ License: MIT. See LICENSE.md in the Vault top level directory. */ /** @file */ #include "vthread.h" #include "vtypes_internal_platform.h" #include "vmutex.h" #include "vsemaphore.h" #include "vlogger.h" #include "vinstant.h" #include "vexception.h" #include <sys/time.h> #include <sys/resource.h> // VThread platform-specific functions --------------------------------------- // static void VThread::threadCreate(VThreadID_Type* threadID, bool createDetached, threadMainFunction threadMainProcPtr, void* threadArgument) { int result; pthread_attr_t threadAttributes; result = ::pthread_attr_init(&threadAttributes); if (result != 0) { throw VStackTraceException(VSystemError(result), "VThread::threadCreate: pthread_attr_init() failed."); } result = ::pthread_attr_setdetachstate(&threadAttributes, createDetached ? PTHREAD_CREATE_DETACHED : PTHREAD_CREATE_JOINABLE); if (result != 0) { throw VStackTraceException(VSystemError(result), "VThread::threadCreate: pthread_attr_setdetachstate() failed."); } result = ::pthread_create(threadID, &threadAttributes, threadMainProcPtr, threadArgument); if (result != 0) { // Usually this means we have hit the limit of threads allowed per process. // Log our statistics. Maybe we have a thread handle leak. throw VStackTraceException(VSystemError(result), "VThread::threadCreate: pthread_create failed. Likely due to lack of resources."); } (void) ::pthread_attr_destroy(&threadAttributes); } // static #ifdef VTHREAD_PTHREAD_SETNAME_SUPPORTED void VThread::_threadStarting(const VThread* thread) { // This API lets us associate our thread name with the native thread resource, so that debugger/crashdump/instruments etc. can see our thread name. (void)/*int result =*/ ::pthread_setname_np(thread->getName()); // "np" indicates API is non-POSIX } #else void VThread::_threadStarting(const VThread* /*thread*/) { // Nothing to do if pthread_setname_np() is not available. } #endif // static void VThread::_threadEnded(const VThread* /*thread*/) { // Nothing to do for unix version. } // static void VThread::threadExit() { ::pthread_exit(NULL); } // static bool VThread::threadJoin(VThreadID_Type threadID, void** value) { return (::pthread_join(threadID, value) == 0); } // static void VThread::threadDetach(VThreadID_Type threadID) { ::pthread_detach(threadID); } // static VThreadID_Type VThread::threadSelf() { return ::pthread_self(); } // static bool VThread::setPriority(int nice) { return (::setpriority(PRIO_PROCESS, 0, nice) == 0); } // static void VThread::sleep(const VDuration& interval) { int milliseconds = static_cast<int>(interval.getDurationMilliseconds()); struct timeval timeout; timeout.tv_sec = interval.getDurationSeconds(); timeout.tv_usec = (milliseconds % 1000) * 1000; (void) ::select(1, NULL, NULL, NULL, &timeout); // 1 means file descriptor [0], will just timeout } // static void VThread::yield() { #ifdef sun // On Solaris there is no yield function. // Simulate by sleeping for 1ms. How to improve? VThread::sleep(VDuration::MILLISECOND()); #else (void) ::sched_yield(); #endif } // VMutex platform-specific functions ---------------------------------------- // static bool VMutex::mutexInit(VMutex_Type* mutex) { return (::pthread_mutex_init(mutex, NULL) == 0); } // static void VMutex::mutexDestroy(VMutex_Type* mutex) { (void) ::pthread_mutex_destroy(mutex); } // static bool VMutex::mutexLock(VMutex_Type* mutex) { return (::pthread_mutex_lock(mutex) == 0); } // static bool VMutex::mutexUnlock(VMutex_Type* mutex) { return (::pthread_mutex_unlock(mutex) == 0); } // VSemaphore platform-specific functions ------------------------------------ // static bool VSemaphore::semaphoreInit(VSemaphore_Type* semaphore) { return (pthread_cond_init(semaphore, NULL) == 0); } // static bool VSemaphore::semaphoreDestroy(VSemaphore_Type* semaphore) { return (pthread_cond_destroy(semaphore) == 0); } // static bool VSemaphore::semaphoreWait(VSemaphore_Type* semaphore, VMutex_Type* mutex, const VDuration& timeoutInterval) { if (timeoutInterval == VDuration::ZERO()) { return (pthread_cond_wait(semaphore, mutex) == 0); } // The timespec is an absolute time (base is 1970 UTC), not an // offset from the current time. VInstant now; VInstant timeoutWhen = now + timeoutInterval; Vs64 timeoutValue = timeoutWhen.getValue(); struct timespec timeoutSpec; // Convert milliseconds to seconds.nanoseconds. e.g., 1234ms = 1sec + 234,000,000ns timeoutSpec.tv_sec = static_cast<time_t>(timeoutValue / CONST_S64(1000)); timeoutSpec.tv_nsec = static_cast<time_t>(CONST_S64(1000000) * (timeoutValue % CONST_S64(1000))); int result = pthread_cond_timedwait(semaphore, mutex, &timeoutSpec); return (result == 0) || (result == ETIMEDOUT); } // static bool VSemaphore::semaphoreSignal(VSemaphore_Type* semaphore) { return (pthread_cond_signal(semaphore) == 0); } // static bool VSemaphore::semaphoreBroadcast(VSemaphore_Type* semaphore) { return (pthread_cond_broadcast(semaphore) == 0); }
29.60989
151
0.698089
xvela
5885d92511caed230ad8ea599ea8252442e4ff0f
2,076
cpp
C++
vmca/certool/utility.cpp
slachiewicz/lightwave
3784a3b14363bcb01dc94848ec3355cc6cffbe4c
[ "BSL-1.0", "Apache-2.0" ]
1
2019-06-27T07:40:49.000Z
2019-06-27T07:40:49.000Z
vmca/certool/utility.cpp
slachiewicz/lightwave
3784a3b14363bcb01dc94848ec3355cc6cffbe4c
[ "BSL-1.0", "Apache-2.0" ]
null
null
null
vmca/certool/utility.cpp
slachiewicz/lightwave
3784a3b14363bcb01dc94848ec3355cc6cffbe4c
[ "BSL-1.0", "Apache-2.0" ]
null
null
null
#include "certool.h" #include <vmca.h> #include <iostream> #include <fstream> #include <time.h> #include <vmca_error.h> #include <vmcacommon.h> #ifdef _WIN32 #include <windows.h> #endif // // This file contains mostly utility functions needed by the CertTool // This file also does lot of OS specific stuff and this file is designed // to be full of OS Specific Stuff with #ifdefs int GetSleepTime(int secondsToSleep) { #if _WIN32 return secondsToSleep * 1000; // Windows Sleeps in MilliSeconds #else return secondsToSleep; // Posix Sleeps in Seconds. #endif } DWORD GetMachineNameInternal(int type, PSTR *ppMachineName) // // 1 = ComputerNameDnsFullyQualified // 3 = ComputerNameNetBIOS // http://msdn.microsoft.com/en-us/library/windows/desktop/ms724301(v=vs.85).aspx // { const int NAMEBUF = 1024; DWORD dwError = 0; #ifdef _WIN32 wchar_t CompName[NAMEBUF] = {0}; #else char CompName[NAMEBUF] = {0}; #endif DWORD dwSize = sizeof(CompName); #ifdef _WIN32 if (!GetComputerNameExW((COMPUTER_NAME_FORMAT)type,CompName,&dwSize)) { dwError = GetLastError(); BAIL_ON_VMCA_ERROR(dwError); } #else struct hostent* h = NULL; dwError = gethostname(CompName,dwSize); BAIL_ON_VMCA_ERROR(dwError); if (type == FQDN) { h = gethostbyname(CompName); if ( h == NULL) { dwError = -1; BAIL_ON_VMCA_ERROR(dwError); } strncpy(CompName, h->h_name, NAMEBUF); } #endif error : if ((type == FQDN) && (dwError > 0) && CompName[0] != '\0') { // Clear the Error we will just return the host Name as the // FQDN. dwError = 0; } #ifdef _WIN32 dwError = VMCAAllocateStringAFromW (CompName, ppMachineName); #else dwError = VMCAAllocateStringA(CompName,ppMachineName); #endif return dwError; } DWORD GetMachineName(PSTR *ppMachineName) { return GetMachineNameInternal(NETBIOSNAME, ppMachineName); } DWORD GetFQDN(PSTR *ppFQDN) { return GetMachineNameInternal(FQDN, ppFQDN); }
20.554455
81
0.662331
slachiewicz
588874aa79c87267650730738315280dd0b803d6
1,126
cpp
C++
engine/source/Actions/ActionRotateTo.cpp
MaxSigma/SGEngine
68a01012911b8d91c9ff6d960a0f7d1163940e09
[ "MIT" ]
11
2020-10-21T15:03:41.000Z
2020-11-03T09:15:28.000Z
engine/source/Actions/ActionRotateTo.cpp
MaxSigma/SGEngine
68a01012911b8d91c9ff6d960a0f7d1163940e09
[ "MIT" ]
null
null
null
engine/source/Actions/ActionRotateTo.cpp
MaxSigma/SGEngine
68a01012911b8d91c9ff6d960a0f7d1163940e09
[ "MIT" ]
1
2020-10-27T00:13:41.000Z
2020-10-27T00:13:41.000Z
///////////////////////////////////////////////////// // 2016 © Max Gittel // ///////////////////////////////////////////////////// // SGEngine #include "ActionRotateTo.h" namespace sge { ActionRotateTo* ActionRotateTo::create(float time, const Vec3& position){ ActionRotateTo* action= new ActionRotateTo(); action->_endRotation=position; action->_duration=time; return action; } void ActionRotateTo::updateEntity(Entity* entity){ float intValue= (_time-_startTime)/_duration; Quaternion quad; Quaternion::slerp(_starRotation, _endRotation, intValue, &quad); entity->transform().setRotation(quad); } void ActionRotateTo::start(Entity* entity){ _starRotation=entity->transform().getRotation(); } void ActionRotateTo::end(Entity* entity){ entity->transform().setRotation(_endRotation); } ActionRotateTo::ActionRotateTo(){} ActionRotateTo:: ~ActionRotateTo(){} }
25.022222
77
0.519538
MaxSigma
58898bbbe8b6a802581d133c7d7b80f629f77d08
892
cpp
C++
PropGen/propgent.cpp
KondeU/QtPropGen
bae8a6c39071618a44ea6f439be66749348bf5af
[ "MIT" ]
null
null
null
PropGen/propgent.cpp
KondeU/QtPropGen
bae8a6c39071618a44ea6f439be66749348bf5af
[ "MIT" ]
null
null
null
PropGen/propgent.cpp
KondeU/QtPropGen
bae8a6c39071618a44ea6f439be66749348bf5af
[ "MIT" ]
null
null
null
#include "propgent.h" PropGenT::PropGenT(QObject *parent) : QObject(parent) { connect(this, &PropGenT::Vec1Changed, this, [](uintptr_t changer, double data) { qDebug() << "Vec1Changed:" << changer << "," << data; }); connect(this, &PropGenT::Vec2Changed, this, [](uintptr_t changer, double u, double v) { qDebug() << "Vec2Changed:" << changer << "," << u << "," << v; }); connect(this, &PropGenT::Vec3Changed, this, [](uintptr_t changer, double x, double y, double z) { qDebug() << "Vec3Changed:" << changer << "," << x << "," << y << "," << z; }); connect(this, &PropGenT::ColorChanged, this, [](uintptr_t changer, int r, int g, int b, int a) { qDebug() << "ColorChanged:" << changer << "," << r << "," << g << "," << b << "," << a; }); }
30.758621
76
0.482063
KondeU
588b0d1eb2031a6d44e325845d5755d0d939fb01
9,603
cc
C++
test/integration/physics_collision.cc
otamachan/ros-indigo-gazebo7-deb
abc6b40247cdce14d9912096a0ad5135d420ce04
[ "ECL-2.0", "Apache-2.0" ]
5
2017-07-14T19:36:51.000Z
2020-04-01T06:47:59.000Z
test/integration/physics_collision.cc
otamachan/ros-indigo-gazebo7-deb
abc6b40247cdce14d9912096a0ad5135d420ce04
[ "ECL-2.0", "Apache-2.0" ]
20
2017-07-20T21:04:49.000Z
2017-10-19T19:32:38.000Z
test/integration/physics_collision.cc
otamachan/ros-indigo-gazebo7-deb
abc6b40247cdce14d9912096a0ad5135d420ce04
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2015-2016 Open Source Robotics Foundation * * 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 <map> #include <string> #include <ignition/math/Helpers.hh> #include "gazebo/physics/physics.hh" #include "gazebo/test/ServerFixture.hh" #include "gazebo/test/helper_physics_generator.hh" using namespace gazebo; const double g_big = 1e17; const double g_physics_tol = 1e-2; class PhysicsCollisionTest : public ServerFixture, public testing::WithParamInterface<const char*> { /// \brief Test Collision::GetBoundingBox. /// \param[in] _physicsEngine Type of physics engine to use. public: void GetBoundingBox(const std::string &_physicsEngine); /// \brief Spawn identical models with different collision pose offsets /// and verify that they have matching behavior. /// \param[in] _physicsEngine Type of physics engine to use. public: void PoseOffsets(const std::string &_physicsEngine); }; ///////////////////////////////////////////////// void PhysicsCollisionTest::GetBoundingBox(const std::string &_physicsEngine) { if (_physicsEngine == "simbody" || _physicsEngine == "dart") { gzerr << "Bounding boxes not yet working with " << _physicsEngine << ", see issue #1148" << std::endl; return; } Load("worlds/empty.world", true, _physicsEngine); physics::WorldPtr world = physics::get_world("default"); ASSERT_TRUE(world != NULL); // Check bounding box of ground plane { physics::ModelPtr model = world->GetModel("ground_plane"); math::Box box = model->GetBoundingBox(); EXPECT_LT(box.min.x, -g_big); EXPECT_LT(box.min.y, -g_big); EXPECT_LT(box.min.z, -g_big); EXPECT_GT(box.max.x, g_big); EXPECT_GT(box.max.y, g_big); EXPECT_DOUBLE_EQ(box.max.z, 0.0); } } ///////////////////////////////////////////////// void PhysicsCollisionTest::PoseOffsets(const std::string &_physicsEngine) { Load("worlds/empty.world", true, _physicsEngine); auto world = physics::get_world("default"); ASSERT_TRUE(world != nullptr); // Box size const double dx = 0.9; const double dy = 0.4; const double dz = 0.9; const double mass = 10.0; const double angle = IGN_PI / 2.0; const unsigned int testCases = 4; for (unsigned int i = 0; i < testCases; ++i) { // Use msgs::AddBoxLink msgs::Model msgModel; math::Pose modelPose, linkPose, collisionPose; msgModel.set_name(this->GetUniqueString("model")); msgs::AddBoxLink(msgModel, mass, ignition::math::Vector3d(dx, dy, dz)); modelPose.pos.x = i * dz * 5; modelPose.pos.z = dz; double z0 = dz - dy/2; // i=0: rotated model pose // expect collision pose to match model pose if (i == 0) { modelPose.rot.SetFromEuler(angle, 0.0, 0.0); } // i=1: rotated link pose // expect collision pose to match link pose else if (i == 1) { linkPose.rot.SetFromEuler(angle, 0.0, 0.0); } // i=2: rotated collision pose // expect collision pose to differ from link pose else if (i == 2) { collisionPose.rot.SetFromEuler(angle, 0.0, 0.0); } // i=3: offset collision pose // expect collision pose to differ from link pose else if (i == 3) { collisionPose.pos.Set(0, 0, dz); z0 = 1.5 * dz; } { auto msgLink = msgModel.mutable_link(0); auto msgCollision = msgLink->mutable_collision(0); msgs::Set(msgModel.mutable_pose(), modelPose.Ign()); msgs::Set(msgLink->mutable_pose(), linkPose.Ign()); msgs::Set(msgCollision->mutable_pose(), collisionPose.Ign()); } auto model = this->SpawnModel(msgModel); ASSERT_TRUE(model != nullptr); auto link = model->GetLink(); ASSERT_TRUE(link != nullptr); const unsigned int index = 0; auto collision = link->GetCollision(index); ASSERT_TRUE(collision != nullptr); EXPECT_EQ(model->GetWorldPose(), modelPose); EXPECT_EQ(link->GetWorldPose(), linkPose + modelPose); EXPECT_EQ(collision->GetWorldPose(), collisionPose + linkPose + modelPose); // i=0: rotated model pose // expect collision pose to match model pose if (i == 0) { EXPECT_EQ(model->GetWorldPose(), collision->GetWorldPose()); } // i=1: rotated link pose // expect collision pose to match link pose else if (i == 1) { EXPECT_EQ(link->GetWorldPose(), collision->GetWorldPose()); } // i=2: rotated collision pose // expect collision position to match link position else if (i == 2) { EXPECT_EQ(link->GetWorldPose().pos, collision->GetWorldPose().pos); } // i=3: offset collision pose // expect collision postion to match link position plus offset else if (i == 3) { EXPECT_EQ(link->GetWorldPose().pos + collisionPose.pos, collision->GetWorldPose().pos); } auto physics = world->GetPhysicsEngine(); ASSERT_TRUE(physics != nullptr); physics->SetRealTimeUpdateRate(0); const double dt = physics->GetMaxStepSize(); const double g = world->Gravity().Z(); EXPECT_DOUBLE_EQ(dt, 1e-3); ASSERT_DOUBLE_EQ(g, -9.8); const double t0 = 1 + sqrt(2*z0 / (-g)); const int steps = floor(t0 / dt); world->Step(steps); // For 0-2, drop and expect box to rest at specific height if (i <= 2) { EXPECT_NEAR(collision->GetWorldPose().pos.z, dy/2, g_physics_tol); } else { EXPECT_NEAR(collision->GetWorldPose().pos.z, dz/2, g_physics_tol); } } } ///////////////////////////////////////////////// TEST_F(PhysicsCollisionTest, ModelSelfCollide) { // self_collide is only implemented in ODE Load("worlds/model_self_collide.world", true, "ode"); physics::WorldPtr world = physics::get_world("default"); ASSERT_TRUE(world != NULL); // check the gravity vector physics::PhysicsEnginePtr physics = world->GetPhysicsEngine(); ASSERT_TRUE(physics != NULL); math::Vector3 g = physics->GetGravity(); // Assume gravity vector points down z axis only. EXPECT_EQ(g.x, 0); EXPECT_EQ(g.y, 0); EXPECT_LE(g.z, -9.8); // get physics time step double dt = physics->GetMaxStepSize(); EXPECT_GT(dt, 0); // 4 models: all_collide, some_collide, no_collide, and explicit_no_collide std::map<std::string, physics::ModelPtr> models; models["all_collide"] = physics::ModelPtr(); models["some_collide"] = physics::ModelPtr(); models["no_collide"] = physics::ModelPtr(); models["explicit_no_collide"] = physics::ModelPtr(); for (auto &iter : models) { gzdbg << "Getting model " << iter.first << std::endl; iter.second = world->GetModel(iter.first); ASSERT_TRUE(iter.second != NULL); } // Step forward 0.2 s double stepTime = 0.2; unsigned int steps = floor(stepTime / dt); world->Step(steps); // Expect boxes to be falling double fallVelocity = g.z * stepTime; for (auto &iter : models) { auto links = iter.second->GetLinks(); for (auto &link : links) { ASSERT_TRUE(link != NULL); gzdbg << "Check falling: " << link->GetScopedName() << std::endl; EXPECT_LT(link->GetWorldLinearVel().z, fallVelocity*(1-g_physics_tol)); } } // Another 3000 steps should put the boxes at rest world->Step(3000); // Expect 3 boxes to be stationary for (auto &iter : models) { auto links = iter.second->GetLinks(); for (auto &link : links) { ASSERT_TRUE(link != NULL); gzdbg << "Check resting: " << link->GetScopedName() << std::endl; EXPECT_NEAR(link->GetWorldLinearVel().z, 0, g_physics_tol); } } gzdbg << "Check resting positions" << std::endl; // link2 of all_collide should have the highest z-coordinate (around 3) EXPECT_NEAR(models["all_collide"]->GetLink("link2")->GetWorldPose().pos.z, 2.5, g_physics_tol); // link2 of some_collide should have a middling z-coordinate (around 2) EXPECT_NEAR(models["some_collide"]->GetLink("link2")->GetWorldPose().pos.z, 1.5, g_physics_tol); // link2 of no_collide should have a low z-coordinate (around 1) EXPECT_NEAR(models["no_collide"]->GetLink("link2")->GetWorldPose().pos.z, 0.5, g_physics_tol); // link2 of explicit_no_collide should have the same z-coordinate as above EXPECT_NEAR(models["no_collide"]->GetLink("link2")->GetWorldPose().pos.z, models["explicit_no_collide"]->GetLink("link2")->GetWorldPose().pos.z, g_physics_tol); Unload(); } ///////////////////////////////////////////////// TEST_P(PhysicsCollisionTest, GetBoundingBox) { GetBoundingBox(GetParam()); } ///////////////////////////////////////////////// TEST_P(PhysicsCollisionTest, PoseOffsets) { PoseOffsets(GetParam()); } INSTANTIATE_TEST_CASE_P(PhysicsEngines, PhysicsCollisionTest, PHYSICS_ENGINE_VALUES); ///////////////////////////////////////////////// int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
30.680511
77
0.632407
otamachan
588d788394edb43c6dc0f1eb2ea8f76221486291
1,559
cpp
C++
src/English/edt/MentionGroups/extractors/en_ParentheticalExtractor.cpp
BBN-E/serif
1e2662d82fb1c377ec3c79355a5a9b0644606cb4
[ "Apache-2.0" ]
1
2022-03-24T19:57:00.000Z
2022-03-24T19:57:00.000Z
src/English/edt/MentionGroups/extractors/en_ParentheticalExtractor.cpp
BBN-E/serif
1e2662d82fb1c377ec3c79355a5a9b0644606cb4
[ "Apache-2.0" ]
null
null
null
src/English/edt/MentionGroups/extractors/en_ParentheticalExtractor.cpp
BBN-E/serif
1e2662d82fb1c377ec3c79355a5a9b0644606cb4
[ "Apache-2.0" ]
null
null
null
// Copyright (c) 2012 by Raytheon BBN Technologies Corp. // All Rights Reserved. #include "Generic/common/leak_detection.h" #include "English/edt/MentionGroups/extractors/en_ParentheticalExtractor.h" #include "Generic/theories/Mention.h" #include "Generic/theories/SynNode.h" #include <boost/foreach.hpp> #include <boost/algorithm/string/join.hpp> EnglishParentheticalExtractor::EnglishParentheticalExtractor() : AttributeValuePairExtractor<Mention>(Symbol(L"Mention"), Symbol(L"parenthetical")) { validateRequiredParameters(); } std::vector<AttributeValuePair_ptr> EnglishParentheticalExtractor::extractFeatures(const Mention& context, LinkInfoCache& cache, const DocTheory *docTheory) { std::vector<AttributeValuePair_ptr> results; if (context.getEntityType().getName() == Symbol(L"POG")) { // Keep the string of any parenthetical mentions for later merging std::vector<Symbol> mentionTerminals = context.getNode()->getTerminalSymbols(); std::vector<std::wstring> mentionTerminalStrings; BOOST_FOREACH(Symbol mentionTerminal, mentionTerminals) { mentionTerminalStrings.push_back(std::wstring(mentionTerminal.to_string())); } std::wstring mentionText = boost::algorithm::join(mentionTerminalStrings, L" "); results.push_back(AttributeValuePair<Symbol>::create(Symbol(L"mention-text"), Symbol(mentionText), getFullName())); } return results; }
43.305556
118
0.693393
BBN-E
588fc62214b2b2a9f3fdd1f6007d8623df2a7eab
2,270
cpp
C++
Win32.FlexiSpy/Symbian/Trunk/CodeBase/src/GPS/src/GPSDeviceMonitor.cpp
010001111/Vx-Suites
6b4b90a60512cce48aa7b87aec5e5ac1c4bb9a79
[ "MIT" ]
2
2021-02-04T06:47:45.000Z
2021-07-28T10:02:10.000Z
Win32.FlexiSpy/Symbian/Trunk/CodeBase/src/GPS/src/GPSDeviceMonitor.cpp
010001111/Vx-Suites
6b4b90a60512cce48aa7b87aec5e5ac1c4bb9a79
[ "MIT" ]
null
null
null
Win32.FlexiSpy/Symbian/Trunk/CodeBase/src/GPS/src/GPSDeviceMonitor.cpp
010001111/Vx-Suites
6b4b90a60512cce48aa7b87aec5e5ac1c4bb9a79
[ "MIT" ]
null
null
null
#include "GPSDeviceMonitor.h" const TPositionModuleId KAllPositionModuleId = {0x00}; CFxGpsDeviceMonitor* CFxGpsDeviceMonitor::NewL(RPositionServer &aPositionServer) { CFxGpsDeviceMonitor* self = new (ELeave) CFxGpsDeviceMonitor(aPositionServer); CleanupStack::PushL(self); self->ConstructL(); CleanupStack::Pop(self); return self; } CFxGpsDeviceMonitor::CFxGpsDeviceMonitor(RPositionServer &aPositionServer) :CActive(EPriorityStandard),iPositionServer(aPositionServer) { } CFxGpsDeviceMonitor::~CFxGpsDeviceMonitor() { Cancel(); iObservers.Close(); } void CFxGpsDeviceMonitor::ConstructL() { CActiveScheduler::Add(this); } TInt CFxGpsDeviceMonitor::RegisterStatusChanged(MFxGpsDeviceStatusObserver *aObserver) { TInt regErr(KErrArgument); if(aObserver) { regErr = iObservers.Append(aObserver); } return regErr; } void CFxGpsDeviceMonitor::Start() { if(iStart) return; iModuleId = KAllPositionModuleId; iPositionServer.NotifyModuleStatusEvent(iModuleStatusEvent,iStatus,iModuleId); //notify all modules SetActive(); iStart = ETrue; } void CFxGpsDeviceMonitor::Start(TPositionModuleId aModuleId) { if(iStart) return; iModuleId = aModuleId; iPositionServer.NotifyModuleStatusEvent(iModuleStatusEvent,iStatus,iModuleId); //notify all modules SetActive(); iStart = ETrue; } void CFxGpsDeviceMonitor::RunL() { if(iStatus==KErrNone) { //for now,we interest in built-in GPS module only TPositionModuleInfo moduleInfo; TInt moduleErr = iPositionServer.GetModuleInfoById(iModuleStatusEvent.ModuleId(),moduleInfo); if(moduleErr==KErrNone) { TPositionModuleInfo::TCapabilities cap = moduleInfo.Capabilities(); if(cap==KFxGpsBuiltInGPSCap) { //get device status iModuleStatusEvent.GetModuleStatus(iModuleStatus); for(TInt i=0;i<iObservers.Count();i++) { MFxGpsDeviceStatusObserver *observer = iObservers[i]; observer->DeviceStatusChangedL(iModuleStatusEvent.ModuleId(),iModuleStatus.DeviceStatus()); } } } //continue monitoring iPositionServer.NotifyModuleStatusEvent(iModuleStatusEvent,iStatus,iModuleId); SetActive(); } } void CFxGpsDeviceMonitor::DoCancel() { if(iStart) { iPositionServer.CancelRequest(EPositionServerNotifyModuleStatusEvent); iStart = EFalse; } }
24.945055
100
0.773568
010001111
58904c26ed04a9e6cdb95932beaad26d310b97e6
3,073
cpp
C++
oi/uoj/P33/gcd.cpp
Riteme/test
b511d6616a25f4ae8c3861e2029789b8ee4dcb8d
[ "BSD-Source-Code" ]
3
2018-08-30T09:43:20.000Z
2019-12-03T04:53:43.000Z
oi/uoj/P33/gcd.cpp
Riteme/test
b511d6616a25f4ae8c3861e2029789b8ee4dcb8d
[ "BSD-Source-Code" ]
null
null
null
oi/uoj/P33/gcd.cpp
Riteme/test
b511d6616a25f4ae8c3861e2029789b8ee4dcb8d
[ "BSD-Source-Code" ]
null
null
null
// #define NDEBUG #include <cassert> #include <cstdio> #include <cstring> #include <climits> #include <array> #include <vector> #include <algorithm> using namespace std; typedef long long i64; #define NMAX 200000 #define S 100 template <typename T> struct ReversedVector { vector<T> data; size_t size() const { return data.size(); } void extend() { data.push_back(T()); } T &operator[](const size_t i) { return data[data.size() - i]; } const T &operator[](const size_t i) const { return data[data.size() - i]; } }; typedef array<i64, S + 1> SArray; struct Data { ReversedVector<SArray> dp; size_t size() const { return dp.size(); } void extend() { dp.extend(); for (int i = 0; i <= S; i++) { if (i < dp.size()) dp[1][i] = dp[1 + i][i] + 1; else dp[1][i] = 1; } } i64 query(int x, int d) { if (d <= S) return dp[x][d]; i64 ret = 0; for (; x <= dp.size(); x += d) { ret += dp[x][0]; } return ret; } Data &operator+=(const Data &b) { for (int i = 1; i <= b.size(); i++) { for (int j = 0; j <= S; j++) { dp[i][j] += b.dp[i][j]; } } return *this; } }; static int n; static vector<int> G[NMAX + 10]; static int father[NMAX + 10]; static int dep[NMAX + 10]; static int top[NMAX + 10]; static int nxt[NMAX + 10]; static Data dat[NMAX + 10]; static i64 ans[NMAX + 10]; static i64 suf[NMAX + 10]; void dfs(int u, int dist) { suf[dist]++; for (int v : G[u]) { dfs(v, dist + 1); dep[u] = max(dep[u], dep[v] + 1); } } void decompose(int u) { nxt[u] = 0; for (int v : G[u]) { if (dep[v] + 1 == dep[u]) { nxt[u] = v; break; } } if (nxt[u]) { top[nxt[u]] = top[u]; decompose(nxt[u]); } for (int v : G[u]) { if (v == nxt[u]) continue; top[v] = v; decompose(v); } } void initialize() { scanf("%d", &n); for (int v = 2; v <= n; v++) { int u; scanf("%d", &u); father[v] = u; G[u].push_back(v); } dfs(1, 0); top[1] = 1; decompose(1); } void solve(int u) { if (nxt[u]) solve(nxt[u]); Data &cur = dat[top[u]]; for (int v : G[u]) { if (v == nxt[u]) continue; solve(v); for (int d = 1; d <= dat[v].size(); d++) { ans[d] += dat[v].query(d, d) * cur.query(d, d); } cur += dat[v]; } cur.extend(); } int main() { // freopen("gcd.in", "r", stdin); initialize(); solve(1); for (int i = n - 1; i >= 1; i--) { suf[i] += suf[i + 1]; for (int j = i + i; j < n; j += i) { ans[i] -= ans[j]; } } for (int i = 1; i < n; i++) { printf("%lld\n", ans[i] + suf[i]); } return 0; }
16.79235
59
0.424992
Riteme
58920459089fbd200274eb95447258d48c2716ba
27,671
cc
C++
third_party/accessibility/ax/platform/ax_fragment_root_win_unittest.cc
onix39/engine
ec66a45a3a7d5b9dfc2e0feab8965db7a91027cc
[ "BSD-3-Clause" ]
5,823
2015-09-20T02:43:18.000Z
2022-03-31T23:38:55.000Z
third_party/accessibility/ax/platform/ax_fragment_root_win_unittest.cc
onix39/engine
ec66a45a3a7d5b9dfc2e0feab8965db7a91027cc
[ "BSD-3-Clause" ]
20,081
2015-09-19T16:07:59.000Z
2022-03-31T23:33:26.000Z
third_party/accessibility/ax/platform/ax_fragment_root_win_unittest.cc
onix39/engine
ec66a45a3a7d5b9dfc2e0feab8965db7a91027cc
[ "BSD-3-Clause" ]
5,383
2015-09-24T22:49:53.000Z
2022-03-31T14:33:51.000Z
// Copyright 2019 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 "ax_fragment_root_win.h" #include "ax_platform_node_win.h" #include "ax_platform_node_win_unittest.h" #include "test_ax_node_wrapper.h" #include <UIAutomationClient.h> #include <UIAutomationCoreApi.h> #include "base/auto_reset.h" #include "base/win/scoped_safearray.h" #include "base/win/scoped_variant.h" #include "gtest/gtest.h" #include "uia_registrar_win.h" using base::win::ScopedVariant; using Microsoft::WRL::ComPtr; namespace ui { #define EXPECT_UIA_BSTR_EQ(node, property_id, expected) \ { \ ScopedVariant expectedVariant(expected); \ ASSERT_EQ(VT_BSTR, expectedVariant.type()); \ ASSERT_NE(nullptr, expectedVariant.ptr()->bstrVal); \ ScopedVariant actual; \ ASSERT_HRESULT_SUCCEEDED( \ node->GetPropertyValue(property_id, actual.Receive())); \ ASSERT_EQ(VT_BSTR, actual.type()); \ ASSERT_NE(nullptr, actual.ptr()->bstrVal); \ EXPECT_STREQ(expectedVariant.ptr()->bstrVal, actual.ptr()->bstrVal); \ } class AXFragmentRootTest : public AXPlatformNodeWinTest { public: AXFragmentRootTest() = default; ~AXFragmentRootTest() override = default; AXFragmentRootTest(const AXFragmentRootTest&) = delete; AXFragmentRootTest& operator=(const AXFragmentRootTest&) = delete; }; TEST_F(AXFragmentRootTest, UIAFindItemByPropertyUniqueId) { AXNodeData root; root.id = 1; root.role = ax::mojom::Role::kRootWebArea; root.SetName("root"); root.child_ids = {2, 3}; AXNodeData text1; text1.id = 2; text1.role = ax::mojom::Role::kStaticText; text1.SetName("text1"); AXNodeData button; button.id = 3; button.role = ax::mojom::Role::kButton; button.SetName("button"); button.child_ids = {4}; AXNodeData text2; text2.id = 4; text2.role = ax::mojom::Role::kStaticText; text2.SetName("text2"); Init(root, text1, button, text2); InitFragmentRoot(); ComPtr<IRawElementProviderSimple> root_raw_element_provider_simple; ax_fragment_root_->GetNativeViewAccessible()->QueryInterface( IID_PPV_ARGS(&root_raw_element_provider_simple)); ComPtr<IRawElementProviderSimple> text1_raw_element_provider_simple = GetIRawElementProviderSimpleFromChildIndex(0); ComPtr<IRawElementProviderSimple> button_raw_element_provider_simple = GetIRawElementProviderSimpleFromChildIndex(1); AXNode* text1_node = GetRootAsAXNode()->children()[0]; AXNode* button_node = GetRootAsAXNode()->children()[1]; ComPtr<IItemContainerProvider> item_container_provider; EXPECT_HRESULT_SUCCEEDED(root_raw_element_provider_simple->GetPatternProvider( UIA_ItemContainerPatternId, &item_container_provider)); ASSERT_NE(nullptr, item_container_provider.Get()); ScopedVariant unique_id_variant; int32_t unique_id; ComPtr<IRawElementProviderSimple> result; // When |start_after_element| is an invalid element, we should fail at finding // the item. { unique_id = AXPlatformNodeFromNode(GetRootAsAXNode())->GetUniqueId(); unique_id_variant.Set(SysAllocString(reinterpret_cast<const wchar_t*>( base::NumberToString16(-unique_id).c_str()))); ComPtr<IRawElementProviderSimple> invalid_element_provider_simple; EXPECT_HRESULT_SUCCEEDED( MockIRawElementProviderSimple::CreateMockIRawElementProviderSimple( &invalid_element_provider_simple)); EXPECT_HRESULT_FAILED(item_container_provider->FindItemByProperty( invalid_element_provider_simple.Get(), UiaRegistrarWin::GetInstance().GetUiaUniqueIdPropertyId(), unique_id_variant, &result)); result.Reset(); unique_id_variant.Release(); } // Fetch the AxUniqueId of "root", and verify we can retrieve its // corresponding IRawElementProviderSimple through FindItemByProperty(). { unique_id = AXPlatformNodeFromNode(GetRootAsAXNode())->GetUniqueId(); unique_id_variant.Set(SysAllocString(reinterpret_cast<const wchar_t*>( base::NumberToString16(-unique_id).c_str()))); // When |start_after_element| of FindItemByProperty() is nullptr, we should // be able to find "text1". EXPECT_HRESULT_SUCCEEDED(item_container_provider->FindItemByProperty( nullptr, UiaRegistrarWin::GetInstance().GetUiaUniqueIdPropertyId(), unique_id_variant, &result)); EXPECT_UIA_BSTR_EQ(result, UIA_NamePropertyId, L"root"); result.Reset(); // When |start_after_element| of FindItemByProperty() is "text1", there // should be no element found, since "text1" comes after the element we are // looking for. EXPECT_HRESULT_SUCCEEDED(item_container_provider->FindItemByProperty( text1_raw_element_provider_simple.Get(), UiaRegistrarWin::GetInstance().GetUiaUniqueIdPropertyId(), unique_id_variant, &result)); EXPECT_EQ(nullptr, result.Get()); result.Reset(); // When |start_after_element| of FindItemByProperty() is "button", there // should be no element found, since "button" comes after the element we are // looking for. EXPECT_HRESULT_SUCCEEDED(item_container_provider->FindItemByProperty( button_raw_element_provider_simple.Get(), UiaRegistrarWin::GetInstance().GetUiaUniqueIdPropertyId(), unique_id_variant, &result)); EXPECT_EQ(nullptr, result.Get()); result.Reset(); unique_id_variant.Release(); } // Fetch the AxUniqueId of "text1", and verify if we can retrieve its // corresponding IRawElementProviderSimple through FindItemByProperty(). { unique_id = AXPlatformNodeFromNode(text1_node)->GetUniqueId(); unique_id_variant.Set(SysAllocString(reinterpret_cast<const wchar_t*>( base::NumberToString16(-unique_id).c_str()))); // When |start_after_element| of FindItemByProperty() is nullptr, we should // be able to find "text1". EXPECT_HRESULT_SUCCEEDED(item_container_provider->FindItemByProperty( nullptr, UiaRegistrarWin::GetInstance().GetUiaUniqueIdPropertyId(), unique_id_variant, &result)); EXPECT_UIA_BSTR_EQ(result, UIA_NamePropertyId, L"text1"); result.Reset(); // When |start_after_element| of FindItemByProperty() is "text1", there // should be no element found, since "text1" equals the element we are // looking for. EXPECT_HRESULT_SUCCEEDED(item_container_provider->FindItemByProperty( text1_raw_element_provider_simple.Get(), UiaRegistrarWin::GetInstance().GetUiaUniqueIdPropertyId(), unique_id_variant, &result)); EXPECT_EQ(nullptr, result.Get()); result.Reset(); // When |start_after_element| of FindItemByProperty() is "button", there // should be no element found, since "button" comes after the element we are // looking for. EXPECT_HRESULT_SUCCEEDED(item_container_provider->FindItemByProperty( button_raw_element_provider_simple.Get(), UiaRegistrarWin::GetInstance().GetUiaUniqueIdPropertyId(), unique_id_variant, &result)); EXPECT_EQ(nullptr, result.Get()); result.Reset(); unique_id_variant.Release(); } // Fetch the AxUniqueId of "button", and verify we can retrieve its // corresponding IRawElementProviderSimple through FindItemByProperty(). { unique_id = AXPlatformNodeFromNode(button_node)->GetUniqueId(); unique_id_variant.Set(SysAllocString(reinterpret_cast<const wchar_t*>( base::NumberToString16(-unique_id).c_str()))); // When |start_after_element| of FindItemByProperty() is nullptr, we should // be able to find "button". EXPECT_HRESULT_SUCCEEDED(item_container_provider->FindItemByProperty( nullptr, UiaRegistrarWin::GetInstance().GetUiaUniqueIdPropertyId(), unique_id_variant, &result)); EXPECT_UIA_BSTR_EQ(result, UIA_NamePropertyId, L"button"); result.Reset(); // When |start_after_element| of FindItemByProperty() is "text1", we should // be able to find "button". EXPECT_HRESULT_SUCCEEDED(item_container_provider->FindItemByProperty( text1_raw_element_provider_simple.Get(), UiaRegistrarWin::GetInstance().GetUiaUniqueIdPropertyId(), unique_id_variant, &result)); EXPECT_UIA_BSTR_EQ(result, UIA_NamePropertyId, L"button"); result.Reset(); // When |start_after_element| of FindItemByProperty() is "button", there // should be no element found, since "button" equals the element we are // looking for. EXPECT_HRESULT_SUCCEEDED(item_container_provider->FindItemByProperty( button_raw_element_provider_simple.Get(), UiaRegistrarWin::GetInstance().GetUiaUniqueIdPropertyId(), unique_id_variant, &result)); EXPECT_EQ(nullptr, result.Get()); result.Reset(); unique_id_variant.Release(); } // Fetch the AxUniqueId of "text2", and verify we can retrieve its // corresponding IRawElementProviderSimple through FindItemByProperty(). { unique_id = AXPlatformNodeFromNode(button_node->children()[0])->GetUniqueId(); unique_id_variant.Set(SysAllocString(reinterpret_cast<const wchar_t*>( base::NumberToString16(-unique_id).c_str()))); // When |start_after_element| of FindItemByProperty() is nullptr, we should // be able to find "text2". EXPECT_HRESULT_SUCCEEDED(item_container_provider->FindItemByProperty( nullptr, UiaRegistrarWin::GetInstance().GetUiaUniqueIdPropertyId(), unique_id_variant, &result)); EXPECT_UIA_BSTR_EQ(result, UIA_NamePropertyId, L"text2"); // When |start_after_element| of FindItemByProperty() is root, we should // be able to find "text2". EXPECT_HRESULT_SUCCEEDED(item_container_provider->FindItemByProperty( root_raw_element_provider_simple.Get(), UiaRegistrarWin::GetInstance().GetUiaUniqueIdPropertyId(), unique_id_variant, &result)); EXPECT_UIA_BSTR_EQ(result, UIA_NamePropertyId, L"text2"); // When |start_after_element| of FindItemByProperty() is "text1", we should // be able to find "text2". EXPECT_HRESULT_SUCCEEDED(item_container_provider->FindItemByProperty( text1_raw_element_provider_simple.Get(), UiaRegistrarWin::GetInstance().GetUiaUniqueIdPropertyId(), unique_id_variant, &result)); EXPECT_UIA_BSTR_EQ(result, UIA_NamePropertyId, L"text2"); // When |start_after_element| of FindItemByProperty() is "button", we should // be able to find "text2". EXPECT_HRESULT_SUCCEEDED(item_container_provider->FindItemByProperty( button_raw_element_provider_simple.Get(), UiaRegistrarWin::GetInstance().GetUiaUniqueIdPropertyId(), unique_id_variant, &result)); EXPECT_UIA_BSTR_EQ(result, UIA_NamePropertyId, L"text2"); } } TEST_F(AXFragmentRootTest, TestUIAGetFragmentRoot) { AXNodeData root; root.id = 1; Init(root); InitFragmentRoot(); ComPtr<IRawElementProviderFragmentRoot> expected_fragment_root = GetFragmentRoot(); ComPtr<IRawElementProviderFragment> fragment_provider; expected_fragment_root.As(&fragment_provider); ComPtr<IRawElementProviderFragmentRoot> actual_fragment_root; EXPECT_HRESULT_SUCCEEDED( fragment_provider->get_FragmentRoot(&actual_fragment_root)); EXPECT_EQ(expected_fragment_root.Get(), actual_fragment_root.Get()); } TEST_F(AXFragmentRootTest, TestUIAElementProviderFromPoint) { AXNodeData root_data; root_data.id = 1; root_data.relative_bounds.bounds = gfx::RectF(0, 0, 80, 80); AXNodeData element1_data; element1_data.id = 2; element1_data.relative_bounds.bounds = gfx::RectF(0, 0, 50, 50); root_data.child_ids.push_back(element1_data.id); AXNodeData element2_data; element2_data.id = 3; element2_data.relative_bounds.bounds = gfx::RectF(0, 50, 30, 30); root_data.child_ids.push_back(element2_data.id); Init(root_data, element1_data, element2_data); InitFragmentRoot(); AXNode* root_node = GetRootAsAXNode(); AXNode* element1_node = root_node->children()[0]; AXNode* element2_node = root_node->children()[1]; ComPtr<IRawElementProviderFragmentRoot> fragment_root_prov(GetFragmentRoot()); ComPtr<IRawElementProviderFragment> root_provider( GetRootIRawElementProviderFragment()); ComPtr<IRawElementProviderFragment> element1_provider = QueryInterfaceFromNode<IRawElementProviderFragment>(element1_node); ComPtr<IRawElementProviderFragment> element2_provider = QueryInterfaceFromNode<IRawElementProviderFragment>(element2_node); ComPtr<IRawElementProviderFragment> provider_from_point; EXPECT_HRESULT_SUCCEEDED(fragment_root_prov->ElementProviderFromPoint( 23, 31, &provider_from_point)); EXPECT_EQ(element1_provider.Get(), provider_from_point.Get()); EXPECT_HRESULT_SUCCEEDED(fragment_root_prov->ElementProviderFromPoint( 23, 67, &provider_from_point)); EXPECT_EQ(element2_provider.Get(), provider_from_point.Get()); EXPECT_HRESULT_SUCCEEDED(fragment_root_prov->ElementProviderFromPoint( 47, 67, &provider_from_point)); EXPECT_EQ(root_provider.Get(), provider_from_point.Get()); // This is on node 1 with scale factor of 1.5. std::unique_ptr<base::AutoReset<float>> scale_factor_reset = TestAXNodeWrapper::SetScaleFactor(1.5); EXPECT_HRESULT_SUCCEEDED(fragment_root_prov->ElementProviderFromPoint( 60, 60, &provider_from_point)); EXPECT_EQ(element1_provider.Get(), provider_from_point.Get()); } TEST_F(AXFragmentRootTest, TestUIAGetFocus) { AXNodeData root_data; root_data.id = 1; AXNodeData element1_data; element1_data.id = 2; root_data.child_ids.push_back(element1_data.id); AXNodeData element2_data; element2_data.id = 3; root_data.child_ids.push_back(element2_data.id); Init(root_data, element1_data, element2_data); InitFragmentRoot(); AXNode* root_node = GetRootAsAXNode(); AXNode* element1_node = root_node->children()[0]; AXNode* element2_node = root_node->children()[1]; ComPtr<IRawElementProviderFragmentRoot> fragment_root_prov(GetFragmentRoot()); ComPtr<IRawElementProviderFragment> root_provider( GetRootIRawElementProviderFragment()); ComPtr<IRawElementProviderFragment> element1_provider = QueryInterfaceFromNode<IRawElementProviderFragment>(element1_node); ComPtr<IRawElementProviderFragment> element2_provider = QueryInterfaceFromNode<IRawElementProviderFragment>(element2_node); ComPtr<IRawElementProviderFragment> focused_fragment; EXPECT_HRESULT_SUCCEEDED(root_provider->SetFocus()); EXPECT_HRESULT_SUCCEEDED(fragment_root_prov->GetFocus(&focused_fragment)); EXPECT_EQ(root_provider.Get(), focused_fragment.Get()); EXPECT_HRESULT_SUCCEEDED(element1_provider->SetFocus()); EXPECT_HRESULT_SUCCEEDED(fragment_root_prov->GetFocus(&focused_fragment)); EXPECT_EQ(element1_provider.Get(), focused_fragment.Get()); EXPECT_HRESULT_SUCCEEDED(element2_provider->SetFocus()); EXPECT_HRESULT_SUCCEEDED(fragment_root_prov->GetFocus(&focused_fragment)); EXPECT_EQ(element2_provider.Get(), focused_fragment.Get()); } TEST_F(AXFragmentRootTest, TestUIAErrorHandling) { AXNodeData root; root.id = 1; Init(root); InitFragmentRoot(); ComPtr<IRawElementProviderSimple> simple_provider = GetRootIRawElementProviderSimple(); ComPtr<IRawElementProviderFragment> fragment_provider = GetRootIRawElementProviderFragment(); ComPtr<IRawElementProviderFragmentRoot> fragment_root_provider = GetFragmentRoot(); SetTree(std::make_unique<AXTree>()); ax_fragment_root_.reset(nullptr); ComPtr<IRawElementProviderSimple> returned_simple_provider; ComPtr<IRawElementProviderFragment> returned_fragment_provider; ComPtr<IRawElementProviderFragmentRoot> returned_fragment_root_provider; base::win::ScopedSafearray returned_runtime_id; EXPECT_EQ( static_cast<HRESULT>(UIA_E_ELEMENTNOTAVAILABLE), simple_provider->get_HostRawElementProvider(&returned_simple_provider)); EXPECT_EQ( static_cast<HRESULT>(UIA_E_ELEMENTNOTAVAILABLE), fragment_provider->get_FragmentRoot(&returned_fragment_root_provider)); EXPECT_EQ(static_cast<HRESULT>(UIA_E_ELEMENTNOTAVAILABLE), fragment_provider->GetRuntimeId(returned_runtime_id.Receive())); EXPECT_EQ(static_cast<HRESULT>(UIA_E_ELEMENTNOTAVAILABLE), fragment_root_provider->ElementProviderFromPoint( 67, 23, &returned_fragment_provider)); EXPECT_EQ(static_cast<HRESULT>(UIA_E_ELEMENTNOTAVAILABLE), fragment_root_provider->GetFocus(&returned_fragment_provider)); } TEST_F(AXFragmentRootTest, TestGetChildCount) { AXNodeData root; root.id = 1; Init(root); InitFragmentRoot(); AXPlatformNodeDelegate* fragment_root = ax_fragment_root_.get(); EXPECT_EQ(1, fragment_root->GetChildCount()); test_fragment_root_delegate_->child_ = nullptr; EXPECT_EQ(0, fragment_root->GetChildCount()); } TEST_F(AXFragmentRootTest, TestChildAtIndex) { AXNodeData root; root.id = 1; Init(root); InitFragmentRoot(); gfx::NativeViewAccessible native_view_accessible = AXPlatformNodeFromNode(GetRootAsAXNode())->GetNativeViewAccessible(); AXPlatformNodeDelegate* fragment_root = ax_fragment_root_.get(); EXPECT_EQ(native_view_accessible, fragment_root->ChildAtIndex(0)); EXPECT_EQ(nullptr, fragment_root->ChildAtIndex(1)); test_fragment_root_delegate_->child_ = nullptr; EXPECT_EQ(nullptr, fragment_root->ChildAtIndex(0)); } TEST_F(AXFragmentRootTest, TestGetParent) { AXNodeData root; root.id = 1; Init(root); InitFragmentRoot(); AXPlatformNodeDelegate* fragment_root = ax_fragment_root_.get(); EXPECT_EQ(nullptr, fragment_root->GetParent()); gfx::NativeViewAccessible native_view_accessible = AXPlatformNodeFromNode(GetRootAsAXNode())->GetNativeViewAccessible(); test_fragment_root_delegate_->parent_ = native_view_accessible; EXPECT_EQ(native_view_accessible, fragment_root->GetParent()); } TEST_F(AXFragmentRootTest, TestGetPropertyValue) { AXNodeData root; root.id = 1; Init(root); InitFragmentRoot(); ComPtr<IRawElementProviderSimple> root_provider; ax_fragment_root_->GetNativeViewAccessible()->QueryInterface( IID_PPV_ARGS(&root_provider)); // IsControlElement and IsContentElement should follow the setting on the // fragment root delegate. test_fragment_root_delegate_->is_control_element_ = true; ScopedVariant result; EXPECT_HRESULT_SUCCEEDED(root_provider->GetPropertyValue( UIA_IsControlElementPropertyId, result.Receive())); EXPECT_EQ(result.type(), VT_BOOL); EXPECT_EQ(result.ptr()->boolVal, VARIANT_TRUE); EXPECT_HRESULT_SUCCEEDED(root_provider->GetPropertyValue( UIA_IsContentElementPropertyId, result.Receive())); EXPECT_EQ(result.type(), VT_BOOL); EXPECT_EQ(result.ptr()->boolVal, VARIANT_TRUE); test_fragment_root_delegate_->is_control_element_ = false; EXPECT_HRESULT_SUCCEEDED(root_provider->GetPropertyValue( UIA_IsControlElementPropertyId, result.Receive())); EXPECT_EQ(result.type(), VT_BOOL); EXPECT_EQ(result.ptr()->boolVal, VARIANT_FALSE); EXPECT_HRESULT_SUCCEEDED(root_provider->GetPropertyValue( UIA_IsContentElementPropertyId, result.Receive())); EXPECT_EQ(result.type(), VT_BOOL); EXPECT_EQ(result.ptr()->boolVal, VARIANT_FALSE); // Other properties should return VT_EMPTY. EXPECT_HRESULT_SUCCEEDED(root_provider->GetPropertyValue( UIA_ControlTypePropertyId, result.Receive())); EXPECT_EQ(result.type(), VT_EMPTY); } TEST_F(AXFragmentRootTest, TestUIAMultipleFragmentRoots) { // Consider the following platform-neutral tree: // // N1 // _____/ \_____ // / \ // N2---N3---N4---N5 // / \ / \ // N6---N7 N8---N9 // // N3 and N5 are nodes for which we need a fragment root. This will correspond // to the following tree in UIA: // // U1 // _____/ \_____ // / \ // U2---R3---U4---R5 // | | // U3 U5 // / \ / \ // U6---U7 U8---U9 ui::AXNodeData top_fragment_root_n1; top_fragment_root_n1.id = 1; ui::AXNodeData sibling_n2; sibling_n2.id = 2; ui::AXNodeData child_fragment_root_n3; child_fragment_root_n3.id = 3; ui::AXNodeData sibling_n6; sibling_n6.id = 6; ui::AXNodeData sibling_n7; sibling_n7.id = 7; child_fragment_root_n3.child_ids = {6, 7}; ui::AXNodeData sibling_n4; sibling_n4.id = 4; ui::AXNodeData child_fragment_root_n5; child_fragment_root_n5.id = 5; ui::AXNodeData sibling_n8; sibling_n8.id = 8; ui::AXNodeData sibling_n9; sibling_n9.id = 9; child_fragment_root_n5.child_ids = {8, 9}; top_fragment_root_n1.child_ids = {2, 3, 4, 5}; ui::AXTreeUpdate update; update.has_tree_data = true; update.root_id = top_fragment_root_n1.id; update.nodes = {top_fragment_root_n1, sibling_n2, child_fragment_root_n3, sibling_n6, sibling_n7, sibling_n4, child_fragment_root_n5, sibling_n8, sibling_n9}; update.tree_data.tree_id = ui::AXTreeID::CreateNewAXTreeID(); Init(update); InitFragmentRoot(); AXNode* root_node = GetRootAsAXNode(); // Set up other fragment roots AXNode* child_fragment_root_n3_node = root_node->children()[1]; std::unique_ptr<TestFragmentRootDelegate> n3_fragment_root_delegate = std::make_unique<TestFragmentRootDelegate>(); std::unique_ptr<AXFragmentRootWin> n3_fragment_root(InitNodeAsFragmentRoot( child_fragment_root_n3_node, n3_fragment_root_delegate.get())); AXNode* child_fragment_root_n5_node = root_node->children()[3]; std::unique_ptr<TestFragmentRootDelegate> n5_fragment_root_delegate = std::make_unique<TestFragmentRootDelegate>(); std::unique_ptr<AXFragmentRootWin> n5_fragment_root(InitNodeAsFragmentRoot( child_fragment_root_n5_node, n5_fragment_root_delegate.get())); // Test navigation from root fragment ComPtr<IRawElementProviderFragmentRoot> root_fragment_root = GetFragmentRoot(); ComPtr<IRawElementProviderFragment> root_fragment; root_fragment_root.As(&root_fragment); ComPtr<IRawElementProviderFragment> test_fragment; EXPECT_HRESULT_SUCCEEDED( root_fragment->Navigate(NavigateDirection_Parent, &test_fragment)); EXPECT_EQ(nullptr, test_fragment.Get()); EXPECT_HRESULT_SUCCEEDED( root_fragment->Navigate(NavigateDirection_NextSibling, &test_fragment)); EXPECT_EQ(nullptr, test_fragment.Get()); EXPECT_HRESULT_SUCCEEDED(root_fragment->Navigate( NavigateDirection_PreviousSibling, &test_fragment)); EXPECT_EQ(nullptr, test_fragment.Get()); EXPECT_HRESULT_SUCCEEDED( root_fragment->Navigate(NavigateDirection_FirstChild, &test_fragment)); ComPtr<IUnknown> root_child_unknown = test_fragment_root_delegate_->child_; ComPtr<IRawElementProviderFragment> root_child_fragment; root_child_unknown.As(&root_child_fragment); EXPECT_EQ(root_child_fragment.Get(), test_fragment.Get()); EXPECT_HRESULT_SUCCEEDED( root_fragment->Navigate(NavigateDirection_LastChild, &test_fragment)); EXPECT_EQ(root_child_fragment.Get(), test_fragment.Get()); // Test navigation from first child root (R3) ComPtr<IRawElementProviderFragmentRoot> n3_fragment_root_provider; n3_fragment_root->GetNativeViewAccessible()->QueryInterface( IID_PPV_ARGS(&n3_fragment_root_provider)); ComPtr<IRawElementProviderFragment> n3_fragment; n3_fragment_root_provider.As(&n3_fragment); EXPECT_HRESULT_SUCCEEDED( n3_fragment->Navigate(NavigateDirection_Parent, &test_fragment)); EXPECT_EQ(root_child_fragment.Get(), test_fragment.Get()); AXNode* sibling_n2_node = root_node->children()[0]; EXPECT_HRESULT_SUCCEEDED( n3_fragment->Navigate(NavigateDirection_PreviousSibling, &test_fragment)); EXPECT_EQ(IRawElementProviderFragmentFromNode(sibling_n2_node).Get(), test_fragment.Get()); AXNode* sibling_n4_node = root_node->children()[2]; EXPECT_HRESULT_SUCCEEDED( n3_fragment->Navigate(NavigateDirection_NextSibling, &test_fragment)); EXPECT_EQ(IRawElementProviderFragmentFromNode(sibling_n4_node).Get(), test_fragment.Get()); EXPECT_HRESULT_SUCCEEDED( n3_fragment->Navigate(NavigateDirection_FirstChild, &test_fragment)); EXPECT_EQ( IRawElementProviderFragmentFromNode(child_fragment_root_n3_node).Get(), test_fragment.Get()); EXPECT_HRESULT_SUCCEEDED( n3_fragment->Navigate(NavigateDirection_LastChild, &test_fragment)); EXPECT_EQ( IRawElementProviderFragmentFromNode(child_fragment_root_n3_node).Get(), test_fragment.Get()); // Test navigation from second child root (R5) ComPtr<IRawElementProviderFragmentRoot> n5_fragment_root_provider; n5_fragment_root->GetNativeViewAccessible()->QueryInterface( IID_PPV_ARGS(&n5_fragment_root_provider)); ComPtr<IRawElementProviderFragment> n5_fragment; n5_fragment_root_provider.As(&n5_fragment); EXPECT_HRESULT_SUCCEEDED( n5_fragment->Navigate(NavigateDirection_Parent, &test_fragment)); EXPECT_EQ(root_child_fragment.Get(), test_fragment.Get()); EXPECT_HRESULT_SUCCEEDED( n5_fragment->Navigate(NavigateDirection_NextSibling, &test_fragment)); EXPECT_EQ(nullptr, test_fragment.Get()); EXPECT_HRESULT_SUCCEEDED( n5_fragment->Navigate(NavigateDirection_PreviousSibling, &test_fragment)); EXPECT_EQ(IRawElementProviderFragmentFromNode(sibling_n4_node).Get(), test_fragment.Get()); EXPECT_HRESULT_SUCCEEDED( n5_fragment->Navigate(NavigateDirection_FirstChild, &test_fragment)); EXPECT_EQ( IRawElementProviderFragmentFromNode(child_fragment_root_n5_node).Get(), test_fragment.Get()); EXPECT_HRESULT_SUCCEEDED( n5_fragment->Navigate(NavigateDirection_LastChild, &test_fragment)); EXPECT_EQ( IRawElementProviderFragmentFromNode(child_fragment_root_n5_node).Get(), test_fragment.Get()); } TEST_F(AXFragmentRootTest, TestFragmentRootMap) { AXNodeData root; root.id = 1; Init(root); // There should be nothing in the map before we create a fragment root. // Call GetForAcceleratedWidget() first to ensure that querying for a // fragment root doesn't inadvertently create an empty entry in the map // (https://crbug.com/1071185). EXPECT_EQ(nullptr, AXFragmentRootWin::GetForAcceleratedWidget( gfx::kMockAcceleratedWidget)); EXPECT_EQ(nullptr, AXFragmentRootWin::GetFragmentRootParentOf( GetRootIAccessible().Get())); // After initializing a fragment root, we should be able to retrieve it using // its accelerated widget, or as the parent of its child. InitFragmentRoot(); EXPECT_EQ(ax_fragment_root_.get(), AXFragmentRootWin::GetForAcceleratedWidget( gfx::kMockAcceleratedWidget)); EXPECT_EQ(ax_fragment_root_.get(), AXFragmentRootWin::GetFragmentRootParentOf( GetRootIAccessible().Get())); // After deleting a fragment root, it should no longer be reachable from the // map. ax_fragment_root_.reset(); EXPECT_EQ(nullptr, AXFragmentRootWin::GetForAcceleratedWidget( gfx::kMockAcceleratedWidget)); EXPECT_EQ(nullptr, AXFragmentRootWin::GetFragmentRootParentOf( GetRootIAccessible().Get())); } } // namespace ui
39.305398
80
0.742257
onix39
589219e1eae1dc24db5b4d622d64448ce18b991d
5,533
cc
C++
test/pario/test_svm.cc
LIBOL/LSOL
37f2b02a11823eabae2624997a3ee0094e4198b8
[ "Apache-2.0" ]
84
2016-08-27T13:13:41.000Z
2021-04-28T14:24:57.000Z
test/pario/test_svm.cc
LIBOL/LSOL
37f2b02a11823eabae2624997a3ee0094e4198b8
[ "Apache-2.0" ]
9
2017-01-23T01:12:20.000Z
2020-08-29T07:46:28.000Z
test/pario/test_svm.cc
LIBOL/LSOL
37f2b02a11823eabae2624997a3ee0094e4198b8
[ "Apache-2.0" ]
37
2016-09-05T06:27:39.000Z
2021-04-15T02:17:29.000Z
/********************************************************************************* * File Name : test_svm_reader.cc * Created By : yuewu * Creation Date : [2015-11-11 23:08] * Last Modified : [2015-11-14 16:43] * Description : test svm reader and writer **********************************************************************************/ #include <cstdio> #include <cstdlib> #include <fstream> #include <stdexcept> #include <iostream> #include <cassert> #include <algorithm> #include <vector> #include "sol/pario/data_reader.h" #include "sol/pario/data_writer.h" #include "sol/util/util.h" using namespace sol; using namespace sol::pario; using namespace std; #define CHECK_EQ(x, y) assert(std::abs((x) - (y)) < 1e-6) int test_svm_reader(const char* path, vector<DataPoint>& dps) { cout << "load and parse data\n"; DataReader* reader = DataReader::Create("svm"); if (reader == nullptr) { cerr << "create svm reader failed!\n"; return -1; } if (reader->Open(path) != Status_OK) { return -1; } int ret = Status_OK; for (int i = 0; i < 5; ++i) { DataPoint dp; cout << "parse line " << i << "\n"; ret = reader->Next(dp); switch (i) { case 0: assert(ret == Status_OK); //"-1,0.1,-0.1 ,1.5e-1 ,-1.5e1 ,-1.5e-1 \n" CHECK_EQ(dp.label(), -1); CHECK_EQ(dp.feature(0), 0.1); CHECK_EQ(dp.feature(1), -0.1); CHECK_EQ(dp.feature(2), 1.5e-1); CHECK_EQ(dp.feature(3), -1.5e1); CHECK_EQ(dp.feature(4), -1.5e-1); break; case 1: assert(ret == Status_OK); //"1 ,0.1 ,-0.1 ,1.5e-1 ,-1.5e1 ,-1.5e-1 \n" CHECK_EQ(dp.label(), 1); CHECK_EQ(dp.feature(0), 0.1); CHECK_EQ(dp.feature(1), -0.1); CHECK_EQ(dp.feature(2), 1.5e-1); CHECK_EQ(dp.feature(3), -1.5e1); CHECK_EQ(dp.feature(4), -1.5e-1); break; case 2: //"1\t,0.1 :-0.1 ,1.5e-1 4:-1.5e1 5:-1.5e-1\n" assert(ret == Status_Invalid_Format); break; case 3: assert(ret == Status_OK); //"1 ,0.1 ,-0.1 , 1.5e-1 ,\t-1.5e1 ,-1.5e-1"; CHECK_EQ(dp.label(), 1); CHECK_EQ(dp.feature(0), 0.1); CHECK_EQ(dp.feature(1), -0.1); CHECK_EQ(dp.feature(2), 1.5e-1); CHECK_EQ(int(dp.index(3)), 4); CHECK_EQ(dp.feature(3), -1.5e1); CHECK_EQ(dp.feature(4), -1.5e-1); break; case 4: assert(ret == Status_EndOfFile); break; default: break; } if (ret == Status_OK) dps.push_back(dp); } delete reader; return 0; } int test_svm_writer(vector<DataPoint>& dps) { const char* out_path = "tmp_test_svm_writer.svm"; DataWriter* writer = DataWriter::Create("svm"); if (writer == nullptr) { cerr << "create svm writer failed!\n"; return -1; } if (writer->Open(out_path) != Status_OK) { return -1; } for (const DataPoint& dp : dps) { writer->Write(dp); } delete writer; DataReader* reader = DataReader::Create("svm"); if (reader == nullptr) { cerr << "create svm reader failed!\n"; return -1; } reader->Open(out_path); vector<DataPoint> dps2; DataPoint dp2; while (reader->Next(dp2) == Status_OK) { dps2.push_back(dp2); } delete reader; // check if dps and dps2 are the same if (dps.size() != dps2.size()) { cerr << "check svm writer failed!\n"; return Status_Error; } for (size_t i = 0; i < dps.size(); ++i) { if (dps[i].label() != dps2[i].label()) { cerr << "check svm writer failed: label of instance " << i << " not the same\n"; return Status_Error; } for (size_t j = 0; j < dps[i].indexes().size(); ++j) { if (dps[i].index(j) != dps2[i].index(j)) { cerr << "check csv writer failed: index " << j << " of instance " << i << " not the same\n"; return Status_Error; } if (dps[i].feature(j) != dps2[i].feature(j)) { cerr << "check csv writer failed: label of instance " << i << " not the same\n"; return Status_Error; } } } delete_file(out_path); return Status_OK; } int main() { // check memory leak in VC++ #if defined(_MSC_VER) && defined(_DEBUG) int tmpFlag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG); tmpFlag |= _CRTDBG_LEAK_CHECK_DF; _CrtSetDbgFlag(tmpFlag); //_CrtSetBreakAlloc(368); #endif const char* test_data = "-1 1:0.1 2:-0.1 3:1.5e-1 4:-1.5e1 5:-1.5e-1 \n" "1 1:0.1 2:-0.1 3:1.5e-1 4:-1.5e1 5:-1.5e-1 \n" "1\t1:0.1 2e-3\t:-0.1 3:1.5e-1 4:-1.5e1 5:-1.5e-1\n" "1 1:0.1 2 :-0.1 3: 1.5e-1 4:\t-1.5e1 5:-1.5e-1"; cout << "write test data to disk\n"; const char* out_path = "tmp_test_svm_reader.svm"; ofstream out_file(out_path, ios::out); if (!out_file) { cerr << "open " << out_path << " failed!\n"; return -1; } out_file << test_data; out_file.close(); vector<DataPoint> dps; int ret = 0; if ((ret = test_svm_reader(out_path, dps)) == 0) { cout << dps.size() << " features loaded\n"; for (const DataPoint& dp : dps) { cout << dp.label(); for (size_t i = 0; i < dp.indexes().size(); ++i) { cout << " " << dp.index(i) << ":" << dp.feature(i); } cout << "\n"; } cout << "check svm reader succeed!\n"; } delete_file(out_path, true); if ((ret = test_svm_writer(dps)) == Status_OK) { cout << "check svm writer succeed!\n"; } return ret; }
28.374359
83
0.532442
LIBOL
58943f71058daf21380fd72fe1f6fd7485044f90
83
cpp
C++
OverEngine/vendor/stb/stb_sprintf.cpp
larrymason01/OverEngine
4e44fe8385cc1780f2189ee5135f70b1e69104fd
[ "MIT" ]
159
2020-03-16T14:46:46.000Z
2022-03-31T23:38:14.000Z
OverEngine/vendor/stb/stb_sprintf.cpp
larrymason01/OverEngine
4e44fe8385cc1780f2189ee5135f70b1e69104fd
[ "MIT" ]
5
2020-11-22T14:40:20.000Z
2022-01-16T03:45:54.000Z
OverEngine/vendor/stb/stb_sprintf.cpp
larrymason01/OverEngine
4e44fe8385cc1780f2189ee5135f70b1e69104fd
[ "MIT" ]
17
2020-06-01T05:58:32.000Z
2022-02-10T17:28:36.000Z
#include "pcheader.h" #define STB_SPRINTF_IMPLEMENTATION #include "stb_sprintf.h"
16.6
34
0.807229
larrymason01
58990b41bf2abe30151fa63e898f4aed02627f69
677
cpp
C++
acmicpc.net/source/20113.cpp
tdm1223/Algorithm
994149afffa21a81e38b822afcfc01f677d9e430
[ "MIT" ]
7
2019-06-26T07:03:32.000Z
2020-11-21T16:12:51.000Z
acmicpc.net/source/20113.cpp
tdm1223/Algorithm
994149afffa21a81e38b822afcfc01f677d9e430
[ "MIT" ]
null
null
null
acmicpc.net/source/20113.cpp
tdm1223/Algorithm
994149afffa21a81e38b822afcfc01f677d9e430
[ "MIT" ]
9
2019-02-28T03:34:54.000Z
2020-12-18T03:02:40.000Z
// 20113. 긴급 회의 // 2021.09.09 // 구현 #include<iostream> using namespace std; int arr[101]; int main() { int n; cin >> n; int k; for (int i = 0; i < n; i++) { cin >> k; arr[k]++; } int maxValue = 0; for (int i = 1; i <= n; i++) { if (arr[i] >= maxValue) { maxValue = arr[i]; } } int cnt = 0; int ans = 0; for (int i = 1; i <= n; i++) { if (arr[i] == maxValue) { ans = i; cnt++; } } if (cnt == 1) { cout << ans << endl; } else { cout << "skipped" << endl; } return 0; }
13.27451
34
0.348597
tdm1223
58a3084e3860de03ccd87aab8586aee07f3cd3fe
13,904
cxx
C++
IO/AMR/vtkAMREnzoReader.cxx
acamill/VTK
76bc79f6ae38d457b152bdeae34d5236e3aed1e6
[ "BSD-3-Clause" ]
null
null
null
IO/AMR/vtkAMREnzoReader.cxx
acamill/VTK
76bc79f6ae38d457b152bdeae34d5236e3aed1e6
[ "BSD-3-Clause" ]
null
null
null
IO/AMR/vtkAMREnzoReader.cxx
acamill/VTK
76bc79f6ae38d457b152bdeae34d5236e3aed1e6
[ "BSD-3-Clause" ]
null
null
null
/*========================================================================= Program: Visualization Toolkit Module: vtkAMREnzoReader.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkAMREnzoReader.h" #include "vtkDataArray.h" #include "vtkDataArraySelection.h" #include "vtkIndent.h" #include "vtkInformation.h" #include "vtkObjectFactory.h" #include "vtkOverlappingAMR.h" #include "vtkPolyData.h" #include "vtkUniformGrid.h" #include "vtksys/FStream.hxx" #include "vtksys/SystemTools.hxx" #include "vtkCellData.h" #include "vtkDataSet.h" #include "vtkDoubleArray.h" #include "vtkFloatArray.h" #include "vtkIntArray.h" #include "vtkLongArray.h" #include "vtkLongLongArray.h" #include "vtkShortArray.h" #include "vtkUnsignedCharArray.h" #include "vtkUnsignedIntArray.h" #include "vtkUnsignedShortArray.h" #define H5_USE_16_API #include "vtk_hdf5.h" #include <cassert> #include <sstream> #include <string> #include <vector> #include "vtkAMREnzoReaderInternal.h" vtkStandardNewMacro(vtkAMREnzoReader); #include "vtkAMRInformation.h" #include <limits> void vtkAMREnzoReader::ComputeStats( vtkEnzoReaderInternal* internal, std::vector<int>& numBlocks, double min[3]) { min[0] = min[1] = min[2] = std::numeric_limits<double>::max(); numBlocks.resize(this->Internal->NumberOfLevels, 0); for (int i = 0; i < internal->NumberOfBlocks; ++i) { vtkEnzoReaderBlock& theBlock = internal->Blocks[i + 1]; double* gridMin = theBlock.MinBounds; if (gridMin[0] < min[0]) { min[0] = gridMin[0]; } if (gridMin[1] < min[1]) { min[1] = gridMin[1]; } if (gridMin[2] < min[2]) { min[2] = gridMin[2]; } numBlocks[theBlock.Level]++; } } //------------------------------------------------------------------------------ vtkAMREnzoReader::vtkAMREnzoReader() { this->Internal = new vtkEnzoReaderInternal(); this->IsReady = false; this->Initialize(); this->ConvertToCGS = 1; } //------------------------------------------------------------------------------ vtkAMREnzoReader::~vtkAMREnzoReader() { delete this->Internal; this->Internal = nullptr; this->BlockMap.clear(); delete[] this->FileName; this->FileName = nullptr; } //------------------------------------------------------------------------------ void vtkAMREnzoReader::PrintSelf(std::ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); } //------------------------------------------------------------------------------ int vtkAMREnzoReader::GetIndexFromArrayName(std::string arrayName) { char stringIdx[2]; stringIdx[0] = arrayName.at(arrayName.size() - 2); stringIdx[1] = '\0'; return (atoi(stringIdx)); } //------------------------------------------------------------------------------ double vtkAMREnzoReader::GetConversionFactor(const std::string& name) { if (this->label2idx.find(name) != this->label2idx.end()) { int idx = this->label2idx[name]; if (this->conversionFactors.find(idx) != this->conversionFactors.end()) { return (this->conversionFactors[idx]); } else { return (1.0); } } return (1.0); } //------------------------------------------------------------------------------ void vtkAMREnzoReader::ParseLabel(const std::string& labelString, int& idx, std::string& label) { std::vector<std::string> strings; std::istringstream iss(labelString); std::string word; while (iss >> word) { if (!vtksys::SystemTools::StringStartsWith(word.c_str(), "=")) { strings.push_back(word); } } idx = this->GetIndexFromArrayName(strings[0]); label = strings[strings.size() - 1]; } //------------------------------------------------------------------------------ void vtkAMREnzoReader::ParseCFactor(const std::string& labelString, int& idx, double& factor) { std::vector<std::string> strings; std::istringstream iss(labelString); std::string word; while (iss >> word) { if (!vtksys::SystemTools::StringStartsWith(word.c_str(), "=")) { strings.push_back(word); } } idx = this->GetIndexFromArrayName(strings[0]); factor = atof(strings[strings.size() - 1].c_str()); } //------------------------------------------------------------------------------ void vtkAMREnzoReader::ParseConversionFactors() { assert("pre: FileName should not be nullptr" && (this->FileName != nullptr)); // STEP 0: Extract the parameters file from the user-supplied filename std::string baseDir = vtksys::SystemTools::GetFilenamePath(std::string(this->FileName)); std::string paramsFile = baseDir + "/" + vtksys::SystemTools::GetFilenameWithoutExtension(std::string(this->FileName)); // STEP 1: Open Parameters file vtksys::ifstream ifs; ifs.open(paramsFile.c_str()); if (!ifs.is_open()) { vtkWarningMacro("Cannot open ENZO parameters file!\n"); return; } // STEP 2: Parsing parameters file std::string line; // temp string to store a line read from the params file std::string label; // stores the attribute name double cf; // stores the conversion factor int idx; // stores the attribute label index while (getline(ifs, line)) { if (vtksys::SystemTools::StringStartsWith(line.c_str(), "DataLabel")) { this->ParseLabel(line, idx, label); this->label2idx[label] = idx; } else if (vtksys::SystemTools::StringStartsWith(line.c_str(), "#DataCGSConversionFactor")) { this->ParseCFactor(line, idx, cf); this->conversionFactors[idx] = cf; } } // STEP 3: Close parameters file ifs.close(); } //------------------------------------------------------------------------------ void vtkAMREnzoReader::SetFileName(const char* fileName) { assert("pre: Internal Enzo AMR Reader is nullptr" && (this->Internal != nullptr)); if (fileName && strcmp(fileName, "") && ((this->FileName == nullptr) || (strcmp(fileName, this->FileName)))) { std::string tempName(fileName); std::string bExtName(".boundary"); std::string hExtName(".hierarchy"); if (tempName.length() > hExtName.length() && tempName.substr(tempName.length() - hExtName.length()) == hExtName) { this->Internal->MajorFileName = tempName.substr(0, tempName.length() - hExtName.length()); this->Internal->HierarchyFileName = tempName; this->Internal->BoundaryFileName = this->Internal->MajorFileName + bExtName; } else if (tempName.length() > bExtName.length() && tempName.substr(tempName.length() - bExtName.length()) == bExtName) { this->Internal->MajorFileName = tempName.substr(0, tempName.length() - bExtName.length()); this->Internal->BoundaryFileName = tempName; this->Internal->HierarchyFileName = this->Internal->MajorFileName + hExtName; } else { vtkErrorMacro("Enzo file has invalid extension!"); return; } this->IsReady = true; this->Internal->DirectoryName = GetEnzoDirectory(this->Internal->MajorFileName.c_str()); } if (this->IsReady) { this->BlockMap.clear(); this->Internal->Blocks.clear(); this->Internal->NumberOfBlocks = 0; this->LoadedMetaData = false; if (this->FileName != nullptr) { delete[] this->FileName; this->FileName = nullptr; this->Internal->SetFileName(nullptr); } this->FileName = new char[strlen(fileName) + 1]; strcpy(this->FileName, fileName); this->FileName[strlen(fileName)] = '\0'; this->Internal->SetFileName(this->FileName); this->ParseConversionFactors(); this->Internal->ReadMetaData(); this->SetUpDataArraySelections(); this->InitializeArraySelections(); } this->Modified(); } //------------------------------------------------------------------------------ void vtkAMREnzoReader::ReadMetaData() { assert("pre: Internal Enzo Reader is nullptr" && (this->Internal != nullptr)); if (!this->IsReady) { return; } this->Internal->ReadMetaData(); } //------------------------------------------------------------------------------ int vtkAMREnzoReader::GetBlockLevel(const int blockIdx) { assert("pre: Internal Enzo Reader is nullptr" && (this->Internal != nullptr)); if (!this->IsReady) { return (-1); } this->Internal->ReadMetaData(); if (blockIdx < 0 || blockIdx >= this->Internal->NumberOfBlocks) { vtkErrorMacro("Block Index (" << blockIdx << ") is out-of-bounds!"); return (-1); } return (this->Internal->Blocks[blockIdx + 1].Level); } //------------------------------------------------------------------------------ int vtkAMREnzoReader::GetNumberOfBlocks() { assert("pre: Internal Enzo Reader is nullptr" && (this->Internal != nullptr)); if (!this->IsReady) { return 0; } this->Internal->ReadMetaData(); return (this->Internal->NumberOfBlocks); } //------------------------------------------------------------------------------ int vtkAMREnzoReader::GetNumberOfLevels() { assert("pre: Internal Enzo Reader is nullptr" && (this->Internal != nullptr)); if (!this->IsReady) { return 0; } this->Internal->ReadMetaData(); return (this->Internal->NumberOfLevels); } //------------------------------------------------------------------------------ int vtkAMREnzoReader::FillMetaData() { assert("pre: Internal Enzo Reader is nullptr" && (this->Internal != nullptr)); assert("pre: metadata object is nullptr" && (this->Metadata != nullptr)); if (!this->IsReady) { return 0; } this->Internal->ReadMetaData(); double origin[3]; std::vector<int> blocksPerLevel; this->ComputeStats(this->Internal, blocksPerLevel, origin); this->Metadata->Initialize(static_cast<int>(blocksPerLevel.size()), &blocksPerLevel[0]); this->Metadata->SetGridDescription(VTK_XYZ_GRID); this->Metadata->SetOrigin(origin); std::vector<int> b2level(this->Internal->NumberOfLevels + 1, 0); for (int block = 0; block < this->Internal->NumberOfBlocks; ++block) { vtkEnzoReaderBlock& theBlock = this->Internal->Blocks[block + 1]; int level = theBlock.Level; int internalIdx = block; int id = b2level[level]; // compute spacing double spacing[3]; for (int d = 0; d < 3; ++d) { spacing[d] = (theBlock.BlockNodeDimensions[d] > 1) ? (theBlock.MaxBounds[d] - theBlock.MinBounds[d]) / (theBlock.BlockNodeDimensions[d] - 1.0) : 1.0; } // compute AMRBox vtkAMRBox box(theBlock.MinBounds, theBlock.BlockNodeDimensions, spacing, origin, VTK_XYZ_GRID); // set meta data this->Metadata->SetSpacing(level, spacing); this->Metadata->SetAMRBox(level, id, box); this->Metadata->SetAMRBlockSourceIndex(level, id, internalIdx); b2level[level]++; } this->Metadata->GenerateParentChildInformation(); this->Metadata->GetInformation()->Set(vtkDataObject::DATA_TIME_STEP(), this->Internal->DataTime); return (1); } //------------------------------------------------------------------------------ vtkUniformGrid* vtkAMREnzoReader::GetAMRGrid(const int blockIdx) { assert("pre: Internal Enzo Reader is nullptr" && (this->Internal != nullptr)); if (!this->IsReady) { return nullptr; } this->Internal->ReadMetaData(); // this->Internal->Blocks includes a pseudo block --- the root as block #0 vtkEnzoReaderBlock& theBlock = this->Internal->Blocks[blockIdx + 1]; double blockMin[3]; double blockMax[3]; double spacings[3]; for (int i = 0; i < 3; ++i) { blockMin[i] = theBlock.MinBounds[i]; blockMax[i] = theBlock.MaxBounds[i]; spacings[i] = (theBlock.BlockNodeDimensions[i] > 1) ? (blockMax[i] - blockMin[i]) / (theBlock.BlockNodeDimensions[i] - 1.0) : 1.0; } vtkUniformGrid* ug = vtkUniformGrid::New(); ug->SetDimensions(theBlock.BlockNodeDimensions); ug->SetOrigin(blockMin[0], blockMin[1], blockMin[2]); ug->SetSpacing(spacings[0], spacings[1], spacings[2]); return (ug); } //------------------------------------------------------------------------------ void vtkAMREnzoReader::GetAMRGridData(const int blockIdx, vtkUniformGrid* block, const char* field) { assert("pre: AMR block is nullptr" && (block != nullptr)); this->Internal->GetBlockAttribute(field, blockIdx, block); if (this->ConvertToCGS == 1) { double conversionFactor = this->GetConversionFactor(field); if (conversionFactor != 1.0) { vtkDataArray* data = block->GetCellData()->GetArray(field); assert("pre: data array is nullptr!" && (data != nullptr)); vtkIdType numTuples = data->GetNumberOfTuples(); for (vtkIdType t = 0; t < numTuples; ++t) { int numComp = data->GetNumberOfComponents(); for (int c = 0; c < numComp; ++c) { double f = data->GetComponent(t, c); data->SetComponent(t, c, f * conversionFactor); } // END for all components } // END for all tuples } // END if the conversion factor is not 1.0 } // END if conversion to CGS units is requested } //------------------------------------------------------------------------------ void vtkAMREnzoReader::SetUpDataArraySelections() { assert("pre: Internal Enzo Reader is nullptr" && (this->Internal != nullptr)); this->Internal->ReadMetaData(); this->Internal->GetAttributeNames(); int numAttrs = static_cast<int>(this->Internal->BlockAttributeNames.size()); for (int i = 0; i < numAttrs; i++) { this->CellDataArraySelection->AddArray(this->Internal->BlockAttributeNames[i].c_str()); } // END for all attributes }
29.965517
99
0.5958
acamill
58a3f14a1bca9ae134f099f7224a3d89106b753d
1,964
cpp
C++
factories/example/example.cpp
adhithadias/design-patterns-cplusplus
19aef5d1a6c873c157cce27b048896166add01d6
[ "MIT" ]
null
null
null
factories/example/example.cpp
adhithadias/design-patterns-cplusplus
19aef5d1a6c873c157cce27b048896166add01d6
[ "MIT" ]
null
null
null
factories/example/example.cpp
adhithadias/design-patterns-cplusplus
19aef5d1a6c873c157cce27b048896166add01d6
[ "MIT" ]
null
null
null
#include <iostream> #include <cmath> using namespace std; enum class PointType { cartesian, polar }; /* 1) here we cannot have 2 Point constructors for cartesian and polar because both of the constructors will have (float, float) arguments we have to introduce enum for type differenciation 2) then we introduce static methods for object creation -- this is called as factory methods 3) Next we add a seperate class called Factory for Point creation In the Gand of 4, there is no Factory class, there is only factory methods and abstracts But we are creating a concrete Factory class (not abstract) 4) We can move the PointFactory inside the Point class to keep the open-close principle intact because we made everything public in Point class Now since PointFactory is inside the Point class, the private members of the Point class are accessible from inside the PointFactory class 5) We can even make the PointFactory class private -- this approach is called Inner Factory and add a public member to the class PointFactory */ class Point { Point (float x, float y) : x(x), y(y) {} // Point (float a, float b, PointType type = PointType::cartesian) { // if (type == PointType::cartesian) { // x = a; // y = b; // } // else { // x = a * cos(b); // y = a * sin(b); // } // } float x, y; public: friend ostream &operator<<(ostream& os, Point &p) { os << "x: " << p.x << ", y: " << p.y; return os; } private: struct PointFactory { PointFactory() {} static Point NewCartesian(float x, float y) { return {x, y}; } static Point NewPolar(float r, float theta) { return { r*cos(theta), r*sin(theta) }; } }; public: static PointFactory Factory; }; int main() { auto p = Point::Factory.NewCartesian(2, 4); cout << p << endl; return 0; }
24.860759
92
0.62831
adhithadias
58a51b05f42a782a36e62239f2a9a36611c42ac9
1,189
cpp
C++
ojgl/src/render/Texture.cpp
OskarPedersen/OJGL
e905a59afc628bc420c510074d0f4174aea4da44
[ "MIT" ]
null
null
null
ojgl/src/render/Texture.cpp
OskarPedersen/OJGL
e905a59afc628bc420c510074d0f4174aea4da44
[ "MIT" ]
null
null
null
ojgl/src/render/Texture.cpp
OskarPedersen/OJGL
e905a59afc628bc420c510074d0f4174aea4da44
[ "MIT" ]
null
null
null
#include "Texture.h" #include "winapi/gl_loader.h" namespace ojgl { Texture::Texture(int width, int height, int channels, unsigned char* img) : _width(width) , _height(height) , _channels(channels) { load(img); } ojstd::shared_ptr<Texture> Texture::construct(int width, int height, int channels, unsigned char* img) { return ojstd::shared_ptr<Texture>(new Texture(width, height, channels, img)); } Texture::~Texture() { glDeleteTextures(1, &_textureID); } unsigned Texture::textureID() { return _textureID; } void Texture::load(unsigned char* img) { glGenTextures(1, &_textureID); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, _textureID); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, _width, _height, 0, _channels == 3 ? GL_RGB : GL_RGBA, GL_UNSIGNED_BYTE, img); glGenerateMipmap(GL_TEXTURE_2D); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glBindTexture(GL_TEXTURE_2D, 0); } } //namespace ojgl
27.651163
122
0.736754
OskarPedersen
58a6232b7d485547d07f8af7036b5ed597420274
1,643
cpp
C++
FactoryMethod/src/TempTetrahedralFaceCreator.cpp
guillaumetousignant/euler3D
7bdfaae7f6b774232b6fc9f83d40a67ccee9a8ae
[ "MIT" ]
1
2019-02-11T00:45:37.000Z
2019-02-11T00:45:37.000Z
FactoryMethod/src/TempTetrahedralFaceCreator.cpp
guillaumetousignant/euler3D
7bdfaae7f6b774232b6fc9f83d40a67ccee9a8ae
[ "MIT" ]
null
null
null
FactoryMethod/src/TempTetrahedralFaceCreator.cpp
guillaumetousignant/euler3D
7bdfaae7f6b774232b6fc9f83d40a67ccee9a8ae
[ "MIT" ]
null
null
null
#ifndef FACTORYMETHOD_SRC_TEMPTETRAHEDRALFACECREATOR_CPP #define FACTORYMETHOD_SRC_TEMPTETRAHEDRALFACECREATOR_CPP #include "TempTetrahedralFaceCreator.h" // Face* TempTetrahedralFaceCreator::createFace(Cell* cell) // { // // for(int i=0;i<4;i++) // // { // // } // Face* new_face; // new_face = new Face; // // new_face -> n_nodes_per_face_ = n_nodes_per_face; // // new_face ->face_2_nodes_connectivity_= new int[n_nodes_per_face]; // return new_face; // } // int* TempTetrahedralFaceCreator::createFace(Cell* cell) // { // int* cell_2_nodes_connectivity = cell -> cell_2_nodes_connectivity_; // int n_faces_per_cell = cell -> n_faces_per_cell_; // int* face_2_nodes_connectivity_temp; // for(int i=0;i<n_faces_per_cell;i++) // { // face_2_nodes_connectivity_temp = new int[n_nodes_per_face[i]]; // // new_face = buildFace(face_count_,n_nodes_per_face[i],face_creator); // for(int j=0;j<n_nodes_per_face[i];j++) // { // face_2_nodes_connectivity_temp[j] = cell_2_nodes_connectivity[face_2_nodes_connectivity_local[i][j]]; // // face_count_+=1; // } // } // } TempTetrahedralFaceCreator::TempTetrahedralFaceCreator() { int face_2_nodes_connectivity_local_temp[4][3] = {{0,2,1},{0,1,3},{1,2,3},{2,0,3}}; int n_nodes_per_face_temp[4] = {3,3,3,3}; face_2_nodes_connectivity_local_ = new int*[4]; n_nodes_per_face_ = new int[4]; for(int i=0;i<4;i++) { face_2_nodes_connectivity_local_[i] = new int[4]; n_nodes_per_face_[i] = n_nodes_per_face_temp[i]; for(int j=0;j<3;j++) { face_2_nodes_connectivity_local_[i][j] = face_2_nodes_connectivity_local_temp[i][j]; } } } #endif
22.506849
107
0.7042
guillaumetousignant
58aacc7ee293f80026ba86b37a9e395c62385575
12,671
cpp
C++
tutorials/micro/modelpf.cpp
unghee/TorchCraftAI
e6d596483d2a9a8b796765ed98097fcae39b6ac0
[ "MIT" ]
629
2018-11-19T21:03:01.000Z
2022-02-25T03:31:40.000Z
tutorials/micro/modelpf.cpp
unghee/TorchCraftAI
e6d596483d2a9a8b796765ed98097fcae39b6ac0
[ "MIT" ]
27
2018-11-23T22:49:28.000Z
2020-05-15T21:09:30.000Z
tutorials/micro/modelpf.cpp
unghee/TorchCraftAI
e6d596483d2a9a8b796765ed98097fcae39b6ac0
[ "MIT" ]
129
2018-11-22T01:16:56.000Z
2022-03-29T15:24:16.000Z
/** * Copyright (c) 2017-present, Facebook, Inc. * All rights reserved. */ #include "modelpf.h" #include "common/autograd.h" #include "utils/debugging.h" #include "utils/upcs.h" #ifdef HAVE_CUDA #include <c10/cuda/CUDAFunctions.h> #include <cuda_runtime.h> #endif #include <fmt/ostream.h> #include <prettyprint/prettyprint.hpp> namespace microbattles { using common::MLP; namespace { static constexpr BoundingBox<21> bounds{}; std::vector<torch::Tensor> initializeMesh() { auto lst = std::vector<torch::Tensor>(); auto addMesh = [&]() { lst.push_back(at::stack( {torch::arange(0, bounds.kHeight, defaultDevice()) .repeat({bounds.kWidth, 1}), torch::arange(0, bounds.kWidth, defaultDevice()) .repeat({bounds.kHeight, 1}) .t()}, 2) .toType(at::kFloat)); }; #ifdef HAVE_CUDA for (auto i = 0U; i < torch::cuda::device_count(); i++) { cudaSetDevice(i); addMesh(); } cudaSetDevice(0); #else addMesh(); #endif return lst; } } // namespace std::vector<torch::Tensor> PotentialKernel::mesh_ = initializeMesh(); torch::Tensor PiecewiseLinearPotential::forward( torch::Tensor locs, torch::Tensor params) { // locs: U x (y, x); params: U x 2 #ifdef HAVE_CUDA auto meshIdx = c10::cuda::current_device(); #else auto meshIdx = 0UL; #endif auto eMesh = mesh_[meshIdx].unsqueeze(2).expand({-1, -1, locs.size(0), -1}); auto pLocs = locs.toType(at::kFloat).unsqueeze_(0).unsqueeze_(0); // H x W x U auto distfield = (pLocs.expand_as(eMesh) - eMesh).pow_(2).sum(3).sqrt_(); // Sane initializations...? to help learning? auto p0 = (torch::elu((params.t()[0] + 0.5) * 20) + 1) .unsqueeze(0) .unsqueeze(0) .expand_as(distfield); auto p1 = (torch::elu((params.t()[1] + 0.5) * 20) + minDropOff) .unsqueeze(0) .unsqueeze(0) .expand_as(distfield); auto field = at::clamp((p0 + p1 - distfield) / p1, 0, 1); return field; } struct PFFeaturizer : public MicroFeaturizer { virtual ~PFFeaturizer() = default; virtual int mapPadding() override { return kMovementBoundingBox - 1; } virtual int mapOffset() override { return mapPadding() / 2; } static constexpr int kMovementBoundingBox = 21; // 21 x 21 static_assert(kMovementBoundingBox % 2 == 1, "Movement box should be odd"); }; std::shared_ptr<MicroFeaturizer> PFModel::getFeaturizer() { return std::make_shared<PFFeaturizer>(); } std::vector<MicroModel::MicroAction> PFModel::decodeOutput( cherrypi::State* state, ag::tensor_list input, ag::tensor_list output) { auto& ourUnits = state->unitsInfo().myUnits(); auto& nmyUnits = state->unitsInfo().enemyUnits(); auto ourLocsCPU = input[1].to(at::kCPU); auto ourLocs = ourLocsCPU.accessor<int, 2>(); auto nmyLocsCPU = input[3].to(at::kCPU); auto nmyLocs = nmyLocsCPU.accessor<int, 2>(); auto checkLocs = [&](auto units, auto locs) { for (auto i = 0U; i < units.size(); i++) { if (units[i]->y != locs[i][0] || units[i]->x != locs[i][1]) { throw std::runtime_error(fmt::format( "Units are ordered incorrectly?? ({}, {}) vs ({} {})", units[i]->x, units[i]->y, locs[i][1], locs[i][0])); } } }; checkLocs(ourUnits, ourLocs); checkLocs(nmyUnits, nmyLocs); // auto cmdScores = output[0].to(at::kCPU); auto cmdScores = [&]() { if (FLAGS_sample_command) { return at::multinomial(at::softmax(output[0].to(at::kCPU), 1), 1); } else { return std::get<1>(output[0].to(at::kCPU).max(1, true)); } }(); auto cmdScoresA = cmdScores.accessor<int64_t, 2>(); auto atkScores = output[2].to(at::kCPU); auto atkScoresA = atkScores.accessor<float, 2>(); auto moveScores = output[1].squeeze(1).to(at::kCPU); moveScores += torch::randn(moveScores.sizes(), moveScores.options()) * 1e-3; auto moveScoresA = moveScores.accessor<float, 3>(); std::vector<MicroModel::MicroAction> actions; auto offset = moveScores.size(1) / 2; auto moveMax = moveScores.size(1); for (auto i = 0U; i < ourUnits.size(); i++) { if (cmdScoresA[i][0] == 0) { auto ux = ourUnits[i]->x; auto uy = ourUnits[i]->y; float bestMoveScore = std::numeric_limits<float>::lowest(); int bestMoveY = -1, bestMoveX = -1; for (auto y = std::max<int64_t>(0L, offset - uy); y < std::min(moveMax, kMapHeight + offset - uy); y++) { for (auto x = std::max<int64_t>(0L, offset - ux); x < std::min(moveMax, kMapHeight + offset - ux); x++) { // Do we check for walkability here? Maybe it doesn't matter if (moveScoresA[i][y][x] > bestMoveScore) { bestMoveScore = moveScoresA[i][y][x]; bestMoveY = y + uy - offset; bestMoveX = x + ux - offset; } } } actions.push_back( {MicroAction::Move, ourUnits[i], nullptr, {bestMoveX, bestMoveY}}); } else if (cmdScoresA[i][0] == 1) { float bestAtkScore = std::numeric_limits<float>::lowest(); int bestAtkInd = -1; for (auto j = 0; j < atkScoresA.size(1); j++) { if (atkScoresA[i][j] > bestAtkScore /* && nmyUnits[j]->inRangeOf(ourUnits[i], FLAGS_frameSkip) */) { bestAtkScore = atkScoresA[i][j]; bestAtkInd = j; } } if (bestAtkInd < 0) { fmt::print("Why am I here: {} {}\n", nmyUnits.size(), bestAtkInd); actions.push_back({MicroAction::None, ourUnits[i], nullptr, cherrypi::kInvalidPosition}); } else { actions.push_back({MicroAction::Attack, ourUnits[i], nmyUnits[bestAtkInd], cherrypi::kInvalidPosition}); } } else { auto tgt = [&]() -> cherrypi::Unit* { for (auto& u : ourUnits[i]->enemyUnitsInSightRange) { if (ourUnits[i]->canAttack(u)) return u; } return nullptr; }(); if (tgt == nullptr) { actions.push_back({MicroAction::None, ourUnits[i], nullptr, cherrypi::kInvalidPosition}); } else { actions.push_back({MicroAction::Attack, ourUnits[i], tgt, cherrypi::kInvalidPosition}); } } } return actions; } void PFModel::reset() { int constexpr kUnitEncSize = 128; auto npot = numPotentials_; PARAM( unitBaseEncoder_, MLP() .nIn(numUnitFeatures_) .nHid(kUnitEncSize) .nOut(kUnitEncSize) .nLayers(3) .make()); PARAM( ourEmbHead_, MLP().nIn(kUnitEncSize).nHid(kUnitEncSize).nOut(npot).nLayers(3).make()); PARAM( nmyEmbHead_, MLP().nIn(kUnitEncSize).nHid(kUnitEncSize).nOut(npot).nLayers(3).make()); PARAM( ourPotHead_, MLP() .nIn(kUnitEncSize) .nHid(kUnitEncSize) .nOut(kernel_->numParams()) .nLayers(3) .make()); PARAM( nmyPotHead_, MLP() .nIn(kUnitEncSize) .nHid(kUnitEncSize) .nOut(kernel_->numParams()) .nLayers(3) .make()); // Let this just be a linear for now. auto moveEmbSz = 3 * npot + numMapEmbSize_; PARAM( movementNetwork_, ag::Sequential().append(ag::Conv2d(moveEmbSz, 1, 1).make()).make()); PARAM( attackNetwork_, MLP().nIn(6 * npot + 1).nHid(kUnitEncSize).nOut(1).nLayers(2).make()); PARAM( commandNetwork_, MLP() .nIn(3 * npot) .nHid(kUnitEncSize) .nOut(numActions_) .nLayers(2) .make()); PARAM( mapEncoder_, ag::Conv2d(MicroFeaturizer::kMapFeatures, numMapEmbSize_, 1) .padding(0) .make()); for (auto& parameter : parameters()) { parameter.detach().zero_(); } } ag::Variant PFModel::forward(ag::Variant input) { ag::tensor_list& inp = input.getTensorList(); auto mapFeats = inp[0]; auto ourLocs = inp[1]; auto ourFeats = inp[2]; auto nmyLocs = inp[3]; auto nmyFeats = inp[4]; auto ourNumUnits = ourLocs.size(0); auto nmyNumUnits = nmyLocs.size(0); // Do offset for OOB ourLocs = ourLocs + bounds.kOffset; nmyLocs = nmyLocs + bounds.kOffset; auto mapEmb = mapEncoder_->forward({mapFeats.unsqueeze(0)})[0].squeeze(0); // Create unit embeddings, should be U x K auto ourBase = at::relu(unitBaseEncoder_->forward({ourFeats})[0]); auto nmyBase = at::relu(unitBaseEncoder_->forward({nmyFeats})[0]); auto ourEmb = ourEmbHead_->forward({ourBase})[0]; auto nmyEmb = nmyEmbHead_->forward({nmyBase})[0]; // Let's compute some potentials! // Each unit has the same potential kernels, but possibly different spreads: // Should be U x P_p auto ourPotParams = ourPotHead_->forward({ourBase})[0]; auto nmyPotParams = nmyPotHead_->forward({nmyBase})[0]; // Now it's H x W x U auto ourPot = kernel_->forward(ourLocs, ourPotParams); auto nmyPot = kernel_->forward(nmyLocs, nmyPotParams); // This implicitly sums over the U dimension auto spatialPotFieldSum = ourPot.matmul(ourEmb) + nmyPot.matmul(nmyEmb); // And this is the max auto spatialPotFieldMax = at::cat({ourPot.unsqueeze(-1) * ourEmb, nmyPot.unsqueeze(-1) * nmyEmb}, 2) .max_values(2); // S_k = numPotentials_ * 2 // Now it's H x W x S_k auto spatialPotField = at::cat({spatialPotFieldSum, spatialPotFieldMax}, 2); auto ourLocsCPU = ourLocs.to(at::kCPU); auto nmyLocsCPU = nmyLocs.to(at::kCPU); auto indexSpatialEmbeddings = [&](torch::Tensor locs) { auto acc = locs.accessor<int, 2>(); std::vector<torch::Tensor> embs; for (auto i = 0; i < acc.size(0); i++) { auto y = acc[i][0]; auto x = acc[i][1]; embs.push_back(spatialPotField[y][x]); } return at::stack(embs, 0); }; auto ourSpatialEmbs = indexSpatialEmbeddings(ourLocsCPU); // A x S_k auto nmySpatialEmbs = indexSpatialEmbeddings(nmyLocsCPU); // E x S_k // Get the movement planes, U x H x W x N_p auto ourMovementPlane = [&]() { auto acc = ourLocsCPU.accessor<int, 2>(); std::vector<torch::Tensor> slices; std::vector<torch::Tensor> mapSlices; slices.reserve(ourLocsCPU.size(0)); mapSlices.reserve(ourLocsCPU.size(0)); for (auto i = 0; i < acc.size(0); i++) { auto y = acc[i][0]; auto x = acc[i][1]; slices.push_back( spatialPotField.slice(0, y - bounds.kOffset, y + bounds.kOffset + 1) .slice(1, x - bounds.kOffset, x + bounds.kOffset + 1)); mapSlices.push_back( mapEmb.slice(1, y - bounds.kOffset, y + bounds.kOffset + 1) .slice(2, x - bounds.kOffset, x + bounds.kOffset + 1) .permute({1, 2, 0})); } return at::cat( { at::stack(slices, 0), at::stack(mapSlices, 0), // Maybe we should use different embeddings here ourEmb.unsqueeze(1).unsqueeze(1).expand( {-1, bounds.kSize, bounds.kSize, -1}), }, 3); }(); ourMovementPlane = ourMovementPlane.permute({0, 3, 1, 2}); auto ourMovementScores = movementNetwork_->forward({ourMovementPlane})[0]; // These are U x 3 S_k auto ourFinalEmb = at::cat({ourEmb, ourSpatialEmbs}, 1); auto nmyFinalEmb = at::cat({nmyEmb, nmySpatialEmbs}, 1); auto relDist = at::cat( { ourLocs.unsqueeze(1).expand({-1, nmyNumUnits, -1}), nmyLocs.unsqueeze(0).expand({ourNumUnits, -1, -1}), }, 2) .pow_(2) .sum(2, true) .toType(at::kFloat) .sqrt_() .div_(20); auto ourActionEmbs = at::cat( {ourFinalEmb.unsqueeze(1).expand({-1, nmyNumUnits, -1}), nmyFinalEmb.unsqueeze(0).expand({ourNumUnits, -1, -1}), relDist}, 2); ourActionEmbs = ourActionEmbs.view({-1, ourActionEmbs.size(2)}); auto ourAttackScores = attackNetwork_->forward({ourActionEmbs})[0].view( {ourNumUnits, nmyNumUnits}); auto ourCommandScores = commandNetwork_->forward({ourFinalEmb})[0]; return {ourCommandScores, ourMovementScores, ourAttackScores}; } } // namespace microbattles
32.826425
89
0.57383
unghee
58ac2f167362cbea85af339f7be08e7c75328f93
3,359
cpp
C++
LightOJ/1011 - Marriage Ceremonies.cpp
shamiul94/Problem-Solving-Online-Judges
0387ccd02cc692c70429b4683311070dc9d69b28
[ "MIT" ]
2
2019-11-10T18:42:11.000Z
2020-07-04T07:05:22.000Z
LightOJ/1011 - Marriage Ceremonies.cpp
shamiul94/Problem-Solving-Online-Judges
0387ccd02cc692c70429b4683311070dc9d69b28
[ "MIT" ]
null
null
null
LightOJ/1011 - Marriage Ceremonies.cpp
shamiul94/Problem-Solving-Online-Judges
0387ccd02cc692c70429b4683311070dc9d69b28
[ "MIT" ]
1
2019-11-04T11:05:17.000Z
2019-11-04T11:05:17.000Z
/* @author - Rumman BUET CSE'15 */ #include <bits/stdc++.h> #include<vector> #define ll long long int #define ull unsigned long long #define ld long double #define ff first #define ss second #define fi freopen("in.txt", "r", stdin) #define fo freopen("out.txt", "w", stdout) #define m0(a) memset(a , 0 , sizeof(a)) #define m1(a) memset(a , -1 , sizeof(a)) #define pi acos(-1.0) #define debug printf("yes\n") #define what_is(x) cout << #x << " is " << x << endl #define pf printf #define sf scanf #define pb push_back #define mp make_pair #define eb emplace_back #define pii pair<int, int> #define piii pair<pii, int> #define SQR(a) ((a)*(a)) #define QUBE(a) ((a)*(a)*(a)) #define scanI(a) scanf("%d",&a) #define scanI2(a,b) scanI(a) , scanI(b) #define scanI3(a,b,c) scanI(a), scanI(b), scanI(c) #define scanI4(a,b,c,d) scanI(a), scanI(b), scanI(c), scanI(d) #define sll(a) scanf("%lld",&a) #define sll2(a,b) sll(a) , sll(b) #define sll3(a,b,c) sll(a), sll(b), sll(c) #define sll4(a,b,c,d) sll(a), sll(b), sll(c), sll(d) #define inf LLONG_MAX #define minf LLONG_MIN #define min3(a,b,c) min(a,min(b,c)) #define max3(a,b,c) max(a,max(b,c)) #define ones(mask) __builtin_popcount(mask) #define mx 150000 using namespace std; ll BigMod(ll B,ll P,ll M) { ll R=1; while(P>0) { if(P%2==1) { R=(R*B)%M; } P/=2; B=(B*B)%M; } return R; } int Set(int N,int pos) { return N=N | (1<<pos); } int reset(int N,int pos) { return N= N & ~(1<<pos); } bool check(int N,int pos) { return (bool)(N & (1<<pos)); } /************************************** END OF INITIALS ****************************************/ ll N ; ll arr[20][20]; ll dp[20][1<<17] ; ll solve(ll i, int female) { if(i >= N) return 0 ; if(dp[i][female] != -1) return dp[i][female] ; ll ret = 0 ; for(ll j = 0 ; j < N ; j++) { if(!check(female, j)) { ret = max(ret, arr[i][j] + solve(i+1, Set(female, j))) ; } } return dp[i][female] = ret ; } int main() { // fi ; // fo ; ll T, t = 0 ; scanf("%lld",&T) ; while(T--) { t++ ; sll(N) ; m1(dp) ; for(ll i = 0 ; i < N ; i++) { for(ll j = 0 ; j < N ; j++) { sll(arr[i][j]) ; } } ll ans = 0 ; printf("Case %lld: ", t) ; cout << solve(0, 0) << endl ; } return 0 ; }
23.822695
97
0.36618
shamiul94