hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
08b415ca0bdaea628232bd7f385b7d66d254e256
777
hpp
C++
lib/graph/floyd_warshall.hpp
atree-GitHub/competitive-library
606b444036530b698a6363b1a41cdaa90a7f9578
[ "CC0-1.0" ]
1
2022-01-25T23:03:10.000Z
2022-01-25T23:03:10.000Z
lib/graph/floyd_warshall.hpp
atree4728/competitive-library
1aaa4d2cf9283b9a1a3d4c7f114ff7b867ca2f8b
[ "CC0-1.0" ]
6
2021-10-06T01:17:04.000Z
2022-01-16T14:45:47.000Z
lib/graph/floyd_warshall.hpp
atree-GitHub/competitive-library
606b444036530b698a6363b1a41cdaa90a7f9578
[ "CC0-1.0" ]
null
null
null
#pragma once #include <utility> #include <vector> template<typename T> std::vector<std::vector<T>> floyd_warshall(std::vector<std::vector<std::pair<std::size_t, T>>> const& graph) { using namespace std; const size_t n = size(graph); constexpr T INF = numeric_limits<T>::max(); vector<vector<T>> dp(n, vector<T>(n, INF)); for (size_t i = 0; i < n; i++) { dp[i][i] = 0; for (const auto& [to, cost]: graph[i]) dp[i][to] = cost; } for (size_t k = 0; k < n; k++) for (size_t i = 0; i < n; i++) for (size_t j = 0; j < n; j++) if (dp[i][k] < INF and dp[k][j] < INF) dp[i][j] = min(dp[i][j], dp[i][k] + dp[k][j]); for (size_t i = 0; i < n; i++) if (dp[i][i] < 0) return {}; return dp; }
33.782609
131
0.508366
[ "vector" ]
08b99345572bd547ddd396445d67c78b7168b482
4,216
cpp
C++
problems/28-implement-strstr.cpp
ZhongRuoyu/LeetCode
7472ef8b868165b485e5ce0676226bbe95561b73
[ "MIT" ]
1
2022-01-11T06:32:41.000Z
2022-01-11T06:32:41.000Z
problems/28-implement-strstr.cpp
ZhongRuoyu/LeetCode
7472ef8b868165b485e5ce0676226bbe95561b73
[ "MIT" ]
null
null
null
problems/28-implement-strstr.cpp
ZhongRuoyu/LeetCode
7472ef8b868165b485e5ce0676226bbe95561b73
[ "MIT" ]
null
null
null
// Solved 2022-01-11 // Runtime: 9 ms (78.35%) // Memory Usage: 7.2 MB (63.24%) // The Boyer-Moore algorithm (simplified) class Solution { public: int strStr(string haystack, string needle) { int n = haystack.length(); int m = needle.length(); if (m == 0) { return 0; } if (n == 0) { return -1; } vector<int> char_jump = MakeCharJump(needle); int p_haystack = m - 1; int p_needle = m - 1; while (p_haystack < n) { if (p_needle < 0) { return p_haystack + 1; } if (haystack[p_haystack] == needle[p_needle]) { --p_haystack; --p_needle; } else { int char_jump_value = char_jump[haystack[p_haystack]]; int jump = max(char_jump_value, m - p_needle); p_haystack += jump; p_needle = m - 1; } } return -1; } private: vector<int> MakeCharJump(string needle) { size_t m = needle.length(); vector<int> char_jump(numeric_limits<char>::max(), m); for (size_t i = 0; i != m; ++i) { char_jump[needle[i]] = m - i - 1; } return char_jump; } }; /* A Boyer-Moore algorithm implementing matchJump as well. 'Tis a pity that the MakeMatchJump is actually O(n^2)... class Solution { public: int strStr(string haystack, string needle) { int n = haystack.length(); int m = needle.length(); if (m == 0) { return 0; } if (n == 0) { return -1; } vector<int> char_jump = MakeCharJump(needle); vector<int> match_jump = MakeMatchJump(needle); int p_haystack = m - 1; int p_needle = m - 1; while (p_haystack < n) { if (p_needle < 0) { return p_haystack + 1; } if (haystack[p_haystack] == needle[p_needle]) { --p_haystack; --p_needle; } else { int char_jump_value = char_jump[haystack[p_haystack]]; int match_jump_value = match_jump[p_needle]; int jump = max(char_jump_value, match_jump_value); p_haystack += jump; p_needle = m - 1; } } return -1; } private: vector<int> MakeCharJump(string needle) { size_t m = needle.length(); vector<int> char_jump(numeric_limits<char>::max(), m); for (size_t i = 0; i != m; ++i) { char_jump[needle[i]] = m - i - 1; } return char_jump; } vector<int> MakeMatchJump(string needle) { size_t m = needle.length(); vector<int> match_jump(m); for (size_t i = 0; i != m; ++i) { int matched = m - (i + 1); match_jump[i] = matched + m; } match_jump[m - 1] = 1; for (size_t i = 0; i != m; ++i) { for (size_t prefix_length = 1; (i + 1) + prefix_length <= m; ++prefix_length) { if (needle.substr(0, prefix_length) == needle.substr(m - prefix_length, prefix_length)) { int matched = m - (i + 1); int slide = m - prefix_length; match_jump[i] = matched + slide; } } } for (size_t i = 0; i + 1 < m; ++i) { for (size_t r = 0; r != i; ++r) { int matched = m - (i + 1); if (needle.substr(r + 1, matched) == needle.substr(i + 1, matched) && needle[r] != needle[i]) { int earlier_occurrence_end = r + matched + 1; int slide = m - earlier_occurrence_end; match_jump[i] = matched + slide; } } } return match_jump; } }; */ /* That's surprisingly fast, although this is cheating, obviously... class Solution { public: int strStr(string haystack, string needle) { return haystack.find(needle); } }; */
27.025641
72
0.466793
[ "vector" ]
08c5a26f80797e66ef2c53959bda7e08cd9840ac
7,699
cpp
C++
src/Class_CefBrowser.cpp
Sympho8dnm/aborg0c
227b0b6ba4d8506b9170eb59b2d36d58686e8d63
[ "MIT" ]
18
2021-04-06T09:19:50.000Z
2021-07-08T01:33:00.000Z
src/Class_CefBrowser.cpp
Sympho8dnm/aborg0c
227b0b6ba4d8506b9170eb59b2d36d58686e8d63
[ "MIT" ]
2
2021-01-20T16:00:43.000Z
2021-03-08T00:23:25.000Z
src/Class_CefBrowser.cpp
Sympho8dnm/aborg0c
227b0b6ba4d8506b9170eb59b2d36d58686e8d63
[ "MIT" ]
6
2020-10-19T14:43:03.000Z
2021-03-26T04:00:12.000Z
#include "Class_CefBrowser.h" static INT M_CefInitialize = 0; Ck_InitializeEx_ Ck_InitializeEx; Ck_Browser_Create_ Ck_Browser_Create; Ck_Browser_Close_ Ck_Browser_Close; Ck_Browser_LoadUrl_ Ck_Browser_LoadUrl; Ck_Browser_SendMouse_ Ck_Browser_SendMouse; Ck_Browser_SendKey_ Ck_Browser_SendKey; Ck_Browser_Focus_ Ck_Browser_Focus; Ck_Browser_Move_ Ck_Browser_Move; BOOL Ex_ObjCefBrowserInitialize(LPCWSTR libPath, BOOL singleProcess, LPCWSTR cachePath, LPCWSTR userAgent, INT debuggingPort, CefPROC lpBeforeCommandLine) { int ret = 1; if (M_CefInitialize == 0) { if (libPath != 0) { DWORD nSize = GetEnvironmentVariableW(L"Path", 0, 0); if (nSize > 0) { wchar_t* buffer = new wchar_t[nSize]; nSize = GetEnvironmentVariableW(L"Path", buffer, nSize); if (nSize > 0) { std::wstring path(buffer, nSize); path = path + L";" + libPath; SetEnvironmentVariableW(L"Path", path.c_str()); } delete[] buffer; } } HMODULE Moudule = LoadLibraryW(L"Ex_libcef.dll"); if (Moudule == 0) { return 0; } M_CefInitialize = 1; Ck_InitializeEx = (Ck_InitializeEx_)GetProcAddress(Moudule, "Ck_InitializeEx"); Ck_Browser_Create = (Ck_Browser_Create_)GetProcAddress(Moudule, "Ck_Browser_Create"); Ck_Browser_Close = (Ck_Browser_Close_)GetProcAddress(Moudule, "Ck_Browser_Close"); Ck_Browser_LoadUrl = (Ck_Browser_LoadUrl_)GetProcAddress(Moudule, "Ck_Browser_LoadUrl"); Ck_Browser_SendMouse = (Ck_Browser_SendMouse_)GetProcAddress(Moudule, "Ck_Browser_SendMouse"); Ck_Browser_SendKey = (Ck_Browser_SendKey_)GetProcAddress(Moudule, "Ck_Browser_SendKey"); Ck_Browser_Focus = (Ck_Browser_Focus_)GetProcAddress(Moudule, "Ck_Browser_Focus"); Ck_Browser_Move = (Ck_Browser_Move_)GetProcAddress(Moudule, "Ck_Browser_Move"); if (singleProcess) { ret = Ck_InitializeEx(1, 0, cachePath, userAgent, debuggingPort, lpBeforeCommandLine); } else { std::wstring subprocess_path; if (libPath != 0) { subprocess_path = std::wstring(libPath) + L"\\CefSubprocess.exe"; } else { subprocess_path = L"CefSubprocess.exe"; } ret = Ck_InitializeEx(0, subprocess_path.c_str(), cachePath, userAgent, debuggingPort, lpBeforeCommandLine); } return ret == 0; } return FALSE; } void _cefbrowser_setcursor(HEXOBJ hObj, DWORD dwCursorType) { if (dwCursorType < 0 || dwCursorType > 44) { return; } std::vector<INT> arrCurs = { 32512, 32515, 32649, 32513, 32514, 32651, 32644, 32645, 32643, 32642, 32645, 32642, 32643, 32644, 32645, 32644, 32643, 32642, 32644, 32645, 32640, 32644, 32644, 32643, 32642, 32645, 32642, 32643, 32644, 32646, 32513, 32512, 32512, 32512, 32650, 32648, 32512, -1, 32648, 32515, 32646, 32512, 32512, 32512 }; LPCWSTR CursorName = NULL; int i = 0; for (i = 0; i < arrCurs.size(); i++) { if (i == dwCursorType) { CursorName = MAKEINTRESOURCE(arrCurs[i]); break; } } HCURSOR hCursor = LoadCursorW(0, CursorName); Ex_ObjSetLong(hObj, EOL_CURSOR, (LONG_PTR)hCursor); } BOOL CALLBACK _cefbrowser_callback(int uMsg, HANDLE handler, int hObj, LONG_PTR attach1, LONG_PTR attach2, LONG_PTR attach3, LONG_PTR attach4, LONG_PTR attach5) { INT nError = 0; obj_s* pObj = nullptr; if (_handle_validate(hObj, HT_OBJECT, (LPVOID*)&pObj, &nError)) { if (uMsg == 1) { Ex_ObjSetLong(hObj, CEFL_INIT, 1); Ex_ObjDispatchNotify(hObj, CEFN_CREATE, 0, (LPARAM)handler); LPCWSTR nUrl = (LPCWSTR)Ex_ObjGetLong(hObj, CEFL_URL); if (nUrl != 0) { Ck_Browser_LoadUrl(handler, nUrl); Ex_MemFree((LPVOID)nUrl); Ex_ObjSetLong(hObj, CEFL_URL, 0); } } else if (uMsg == 2) { //绘制 Ex_ObjSendMessage(hObj, WM_PAINT, attach1, MAKELONG(attach2, attach3)); } else if (uMsg == 3) { _cefbrowser_setcursor(hObj, attach1); } else if (uMsg == 4) { Ex_ObjPostMessage(hObj, WM_NEXTDLGCTL, attach1, 99); } else if (uMsg == 5) { int model = attach1; int TypeFlags = attach2; LPCWSTR LinkUrl = L""; LPCWSTR SourceUrl = L""; LPCWSTR SelectionText = L""; if (attach3 != 0) { LinkUrl = (LPCWSTR)attach3; } if (attach4 != 0) { SourceUrl = (LPCWSTR)attach4; } if (attach5 != 0) { SelectionText = (LPCWSTR)attach5; } return 0; } else if (uMsg == 6) { int command_id = attach1; } } return 0; } void _cefbrowser_register() { Ex_ObjRegister(L"CefBrowser", EOS_VISIBLE, EOS_EX_TABSTOP | EOS_EX_FOCUSABLE, -1, 4 * sizeof(SIZE_T), 0, 0, _cefbrowser_proc); } LRESULT CALLBACK _cefbrowser_proc(HWND hWnd, HEXOBJ hObj, INT uMsg, WPARAM wParam, LPARAM lParam) { INT nError = 0; obj_s* pObj = nullptr; if (_handle_validate(hObj, HT_OBJECT, (LPVOID*)&pObj, &nError)) { HANDLE hWebView = (HANDLE)Ex_ObjGetLong(hObj, CEFL_VIEW); INT hInit = Ex_ObjGetLong(hObj, CEFL_INIT); if (uMsg == WM_CREATE) { Ex_ObjDisableTranslateSpaceAndEnterToClick(hObj, TRUE); RECT Rect = { pObj->left_, pObj->top_, pObj->right_ - pObj->left_, pObj->bottom_ - pObj->top_ }; hWebView = Ck_Browser_Create(hWnd, hObj, &Rect, Ex_ObjGetColor(hObj, COLOR_EX_BACKGROUND), L"", _cefbrowser_callback); if (hWebView) { Ex_ObjSetLong(hObj, CEFL_VIEW, (LONG_PTR)hWebView); } } else if (uMsg == WM_DESTROY) { Ex_ObjSetLong(hObj, CEFL_INIT, 0); Ex_ObjSetLong(hObj, CEFL_VIEW, 0); LPCWSTR nUrl = (LPCWSTR)Ex_ObjGetLong(hObj, CEFL_URL); if (nUrl != 0) { Ex_MemFree((LPVOID)nUrl); Ex_ObjSetLong(hObj, CEFL_URL, 0); } if (hWebView != 0) { Ck_Browser_Close(hWebView); } } else if (uMsg == WM_PAINT) { if (wParam != 0) { EX_PAINTSTRUCT ps{}; if (Ex_ObjBeginPaint(hObj, &ps)) { HEXIMAGE hImg = 0; INT nWidth = LOWORD(lParam); INT nHeight = HIWORD(lParam); _img_createfrompngbits2(nWidth, nHeight, (BYTE*)wParam, &hImg); if (hImg != 0) { _canvas_drawimage(ps.hCanvas, hImg, 0, 0, 255); _img_destroy(hImg); } Ex_ObjEndPaint(hObj, &ps); } } else { return 1; } } else if (uMsg == WM_MOVE) { if (hWebView != 0) { Ck_Browser_Move(hWebView, LOWORD(lParam), HIWORD(lParam), EOP_DEFAULT, EOP_DEFAULT); } } else if (uMsg == WM_SIZE) { if (hWebView != 0) { Ck_Browser_Move(hWebView, EOP_DEFAULT, EOP_DEFAULT, LOWORD(lParam), HIWORD(lParam)); } } else if (uMsg >= WM_MOUSEMOVE && uMsg <= WM_MBUTTONDBLCLK) { if (uMsg == WM_MOUSEMOVE) { Ex_ObjSetLong(hObj, CEFL_lParam, lParam); } if (hInit == 1) Ck_Browser_SendMouse(hWebView, uMsg, wParam, lParam); } else if (uMsg == WM_MOUSEWHEEL) { if (hInit == 1) Ck_Browser_SendMouse(hWebView, uMsg, wParam, lParam); } else if (uMsg == WM_KEYDOWN || uMsg == WM_SYSKEYDOWN) { if (hInit == 1) Ck_Browser_SendKey(hWebView, uMsg, wParam, lParam); } else if (uMsg == WM_KEYUP || uMsg == WM_SYSKEYUP) { if (hInit == 1) Ck_Browser_SendKey(hWebView, uMsg, wParam, lParam); } else if (uMsg == WM_CHAR || uMsg == WM_SYSCHAR) { if (hInit == 1) Ck_Browser_SendKey(hWebView, uMsg, wParam, lParam); } else if (uMsg == WM_SETFOCUS) { if (hInit == 1) Ck_Browser_Focus(hWebView, TRUE); } else if (uMsg == WM_KILLFOCUS) { if (hInit == 1) Ck_Browser_Focus(hWebView, FALSE); } else if (uMsg == CEFM_GETWEBVIEW) { return (LRESULT)hWebView; } else if (uMsg == WM_NEXTDLGCTL && lParam == 99) { Ex_ObjSetIMEState(hObj, wParam == 0); } else if (uMsg == CEFM_LOADURL) { if (hInit != 1) { LPVOID nUrl = (LPVOID)Ex_ObjGetLong(hObj, CEFL_URL); if (nUrl != 0) { Ex_MemFree(nUrl); } Ex_ObjSetLong(hObj, CEFL_URL, (LONG_PTR)StrDupW((LPCWSTR)lParam)); } else { Ck_Browser_LoadUrl(hWebView, (LPCWSTR)lParam); } } } return Ex_ObjDefProc(hWnd, hObj, uMsg, wParam, lParam); }
31.42449
336
0.678789
[ "vector", "model" ]
08c75c345f33985058ca8ad11fbf52f23d4d3005
1,507
cpp
C++
Template/BouncingBall.cpp
ferenc-schultesz/YokosAdventure
951a91e5881134f0fbdf9968cefc350c6bdc16fd
[ "Apache-2.0" ]
null
null
null
Template/BouncingBall.cpp
ferenc-schultesz/YokosAdventure
951a91e5881134f0fbdf9968cefc350c6bdc16fd
[ "Apache-2.0" ]
null
null
null
Template/BouncingBall.cpp
ferenc-schultesz/YokosAdventure
951a91e5881134f0fbdf9968cefc350c6bdc16fd
[ "Apache-2.0" ]
null
null
null
#include "BouncingBall.h" CBouncingBall::CBouncingBall() {} CBouncingBall::~CBouncingBall() {} bool CBouncingBall::Initialise(CVector3f position, CVector3f velocity, CVector3f acceleration, float coefficientOfResitution, float radius) { m_position = position; m_velocity = velocity; m_acceleration = acceleration; m_coefficientOfRestitution = coefficientOfResitution; m_radius = radius; m_isActive = true; return true; } bool CBouncingBall::CollisionDetection(float yPlane) { if (m_position.y - m_radius < yPlane && m_velocity.y < 0) { return true; } return false; } void CBouncingBall::CollisionResponse() { float convergenceThreshold = 0.5f; if (m_velocity.Length() > convergenceThreshold) m_velocity = CVector3f(m_velocity.x, -m_velocity.y * m_coefficientOfRestitution, m_velocity.z); else { m_velocity = CVector3f(0, 0, 0); m_acceleration = CVector3f(0, 0, 0); m_position = CVector3f(m_position.x, m_radius, m_position.z); m_isActive = false; } } bool CBouncingBall::UpdatePhysics(float dt) { if (m_isActive == false) return false; bool bounce = false; m_position += m_velocity * dt + (m_acceleration * dt * dt) * 0.5; m_velocity += m_acceleration * dt; float yPlane = 0.0f; if(CollisionDetection(yPlane)) { CollisionResponse(); bounce = true; } return bounce; } void CBouncingBall::Render() { glColor3f(1, 0, 0); glPushMatrix(); glTranslatef(m_position.x, m_position.y, m_position.z); glutSolidSphere(m_radius, 15, 15); glPopMatrix(); }
20.364865
139
0.729263
[ "render" ]
c092f445095d4a16b415d9ae6426b06fa182d8b6
2,711
hpp
C++
Pods/OpenVPNAdapter/Sources/OpenVPN3/openvpn/common/stop.hpp
TiagoPedroByterev/openvpnclient-ios
a9dafb2a481cc72a3e408535fb7f0aba9f5cfa76
[ "MIT" ]
10
2021-03-29T13:52:06.000Z
2022-03-10T02:24:25.000Z
Pods/OpenVPNAdapter/Sources/OpenVPN3/openvpn/common/stop.hpp
TiagoPedroByterev/openvpnclient-ios
a9dafb2a481cc72a3e408535fb7f0aba9f5cfa76
[ "MIT" ]
1
2019-07-19T02:40:32.000Z
2019-07-19T02:40:32.000Z
Pods/OpenVPNAdapter/Sources/OpenVPN3/openvpn/common/stop.hpp
TiagoPedroByterev/openvpnclient-ios
a9dafb2a481cc72a3e408535fb7f0aba9f5cfa76
[ "MIT" ]
7
2018-07-11T10:37:02.000Z
2019-08-03T10:34:08.000Z
// OpenVPN -- An application to securely tunnel IP networks // over a single port, with support for SSL/TLS-based // session authentication and key exchange, // packet encryption, packet authentication, and // packet compression. // // Copyright (C) 2012-2017 OpenVPN Inc. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License Version 3 // as published by the Free Software Foundation. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program in the COPYING file. // If not, see <http://www.gnu.org/licenses/>. #ifndef OPENVPN_COMMON_STOP_H #define OPENVPN_COMMON_STOP_H #include <vector> #include <functional> #include <utility> #include <mutex> namespace openvpn { class Stop { public: class Scope { friend Stop; public: Scope(Stop* stop_arg, std::function<void()>&& method_arg) : stop(stop_arg), method(std::move(method_arg)), index(-1) { if (stop) { std::lock_guard<std::recursive_mutex> lock(stop->mutex); if (stop->stop_called) { // stop already called, call method immediately method(); } else { index = stop->scopes.size(); stop->scopes.push_back(this); } } } ~Scope() { if (stop) { std::lock_guard<std::recursive_mutex> lock(stop->mutex); if (index >= 0 && index < stop->scopes.size() && stop->scopes[index] == this) { stop->scopes[index] = nullptr; stop->prune(); } } } private: Scope(const Scope&) = delete; Scope& operator=(const Scope&) = delete; Stop *const stop; const std::function<void()> method; int index; }; Stop() { } void stop() { std::lock_guard<std::recursive_mutex> lock(mutex); stop_called = true; while (scopes.size()) { Scope* scope = scopes.back(); scopes.pop_back(); if (scope) { scope->index = -1; scope->method(); } } } private: Stop(const Stop&) = delete; Stop& operator=(const Stop&) = delete; void prune() { while (scopes.size() && !scopes.back()) scopes.pop_back(); } std::recursive_mutex mutex; std::vector<Scope*> scopes; bool stop_called = false; }; } #endif
22.591667
82
0.603098
[ "vector" ]
c09963a7c1a4d7677359a62d7ac41c4de761679e
2,031
cpp
C++
isometric-deformation/ext/libigl/include/igl/topological_hole_fill.cpp
jiayaozhang/CS-370-Mesh-Processing
26646d29af8cbc0d461302afa137f12b508b8b1b
[ "MIT" ]
1
2021-02-25T09:35:14.000Z
2021-02-25T09:35:14.000Z
isometric-deformation/ext/libigl/include/igl/topological_hole_fill.cpp
jiayaozhang/CS-370-Mesh-Processing
26646d29af8cbc0d461302afa137f12b508b8b1b
[ "MIT" ]
null
null
null
isometric-deformation/ext/libigl/include/igl/topological_hole_fill.cpp
jiayaozhang/CS-370-Mesh-Processing
26646d29af8cbc0d461302afa137f12b508b8b1b
[ "MIT" ]
2
2020-09-22T13:02:45.000Z
2020-10-08T00:21:36.000Z
// This file is part of libigl, a simple c++ geometry processing library. // // Copyright (C) 2018 Zhongshi Jiang <jiangzs@nyu.edu> // // This Source Code Form is subject to the terms of the Mozilla Public License // v. 2.0. If a copy of the MPL was not distributed with this file, You can // obtain one at http://mozilla.org/MPL/2.0/. #include "topological_hole_fill.h" template < typename DerivedF, typename Derivedb, typename VectorIndex, typename DerivedF_filled> IGL_INLINE void igl::topological_hole_fill( const Eigen::MatrixBase<DerivedF> & F, const Eigen::MatrixBase<Derivedb> & b, const std::vector<VectorIndex> & holes, Eigen::PlainObjectBase<DerivedF_filled> &F_filled) { int n_filled_faces = 0; int num_holes = holes.size(); int real_F_num = F.rows(); const int V_rows = F.maxCoeff()+1; for (int i = 0; i < num_holes; i++) n_filled_faces += holes[i].size(); F_filled.resize(n_filled_faces + real_F_num, 3); F_filled.topRows(real_F_num) = F; int new_vert_id = V_rows; int new_face_id = real_F_num; for (int i = 0; i < num_holes; i++, new_vert_id++) { int cur_bnd_size = holes[i].size(); int it = 0; int back = holes[i].size() - 1; F_filled.row(new_face_id++) << holes[i][it], holes[i][back], new_vert_id; while (it != back) { F_filled.row(new_face_id++) << holes[i][(it + 1)], holes[i][(it)], new_vert_id; it++; } } assert(new_face_id == F_filled.rows()); assert(new_vert_id == V_rows + num_holes); } #ifdef IGL_STATIC_LIBRARY template void igl::topological_hole_fill<Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, 1, 0, -1, 1>, std::vector<int, std::allocator<int> > >(Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, 1,0, -1, 1> > const&, std::vector<std::vector<int, std::allocator<int> >, std::allocator<std::vector<int, std::allocator<int> > > > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> >&); #endif
36.927273
470
0.656327
[ "geometry", "vector" ]
c09dedcf397afd68c0d16d0ac504a6b4930d3ff7
656
cpp
C++
Fierce-Engine/src/unitTests/Test_Rendering_Vulkan.cpp
TB989/Fierce-Engine-V1
007d41dec19b461a66595a6c5d4dae5e3ce8880d
[ "Apache-2.0" ]
null
null
null
Fierce-Engine/src/unitTests/Test_Rendering_Vulkan.cpp
TB989/Fierce-Engine-V1
007d41dec19b461a66595a6c5d4dae5e3ce8880d
[ "Apache-2.0" ]
null
null
null
Fierce-Engine/src/unitTests/Test_Rendering_Vulkan.cpp
TB989/Fierce-Engine-V1
007d41dec19b461a66595a6c5d4dae5e3ce8880d
[ "Apache-2.0" ]
null
null
null
#include "UnitTests.h" #include "src/system/logging/Logger.h" Test_Rendering_Vulkan::Test_Rendering_Vulkan() { m_settings.api = VULKAN; m_settings.apiVersionMajor = 1; m_settings.apiVersionMinor = 0; eventSystem->addListener(this, &Test_Rendering_Vulkan::onKeyPressed); } void Test_Rendering_Vulkan::init(World* world) { } void Test_Rendering_Vulkan::update(World* world, float dt) {} void Test_Rendering_Vulkan::render(World* world) { } void Test_Rendering_Vulkan::cleanUp(World* world) {} void Test_Rendering_Vulkan::onKeyPressed(KeyDownEvent* event) { if (event->m_key == VK_ESCAPE) { eventSystem->postEvent(new WindowCloseEvent()); } }
23.428571
70
0.766768
[ "render" ]
c0a29b2c413c8d07f7a977117c70d1d87c537e48
2,694
cpp
C++
source/Insider/TaskProcess.cpp
fstudio/Phoenix
28a7c6a3932fd7d6fea12770d0aa1e20bc70db7d
[ "MIT" ]
8
2015-01-23T05:41:46.000Z
2019-11-20T05:10:27.000Z
source/Insider/TaskProcess.cpp
fstudio/Phoenix
28a7c6a3932fd7d6fea12770d0aa1e20bc70db7d
[ "MIT" ]
null
null
null
source/Insider/TaskProcess.cpp
fstudio/Phoenix
28a7c6a3932fd7d6fea12770d0aa1e20bc70db7d
[ "MIT" ]
4
2015-05-05T05:15:43.000Z
2020-03-07T11:10:56.000Z
/********************************************************************************************************* * TaskProcess.cpp * Note: Phoenix Task Process * Date: @2015.03 * E-mail:<forcemz@outlook.com> * Copyright (C) 2015 The ForceStudio All Rights Reserved. **********************************************************************************************************/ #include <Windows.h> #include <winternl.h> #include <Processthreadsapi.h> #include <wchar.h> #include "Header.hpp" #include "Arguments.hpp" #include "TaskProcess.hpp" /* Winternl.h: NTSTATUS WINAPI NtQueryInformationProcess( __in HANDLE ProcessHandle, __in PROCESSINFOCLASS ProcessInformationClass, __out PVOID ProcessInformation, __in ULONG ProcessInformationLength, __out_opt PULONG ReturnLength ); */ using namespace Task; typedef NTSTATUS (WINAPI * NTQUERYINFORMATIONPROCESS) ( HANDLE ProcessHandle, PROCESSINFOCLASS ProcessInformationClass, PVOID ProcessInformation, ULONG ProcessInformationLength, PULONG ReturnLength ); /* typedef struct _PROCESS_BASIC_INFORMATION { PVOID Reserved1; PPEB PebBaseAddress; PVOID Reserved2[2]; ULONG_PTR UniqueProcessId; PVOID Reserved3; } PROCESS_BASIC_INFORMATION; */ //Task Process start DWORD WINAPI FollowParentQuit(LPVOID lParam) { ForceHANDLE hAlp=static_cast<ForceHANDLE>(lParam); HANDLE hProcess=GetCurrentProcess(); DWORD dwParentPid; LONG status; PROCESS_BASIC_INFORMATION pbi; HMODULE hMod = GetModuleHandleW(L"NTDLL.DLL"); NTQUERYINFORMATIONPROCESS NtQueryInformationProcess = (NTQUERYINFORMATIONPROCESS)GetProcAddress(hMod,"NtQueryInformationProcess"); if(NtQueryInformationProcess==NULL) { CloseHandle(hProcess); return 1; } status = NtQueryInformationProcess(hProcess,ProcessBasicInformation,(PVOID)&pbi,sizeof(PROCESS_BASIC_INFORMATION),NULL); dwParentPid=(DWORD)pbi.Reserved3; ForceHANDLE hFParent=OpenProcess(SYNCHRONIZE,FALSE,dwParentPid); if(hFParent.Get()==nullptr) { //OpenProcess Failed return 2; } DWORD dwRet; if((dwRet=WaitForSingleObject(hFParent.Get(),INFINITE))==WAIT_TIMEOUT) { /// } if(dwRet==WAIT_FAILED) { return 2; } //NTDLL always be called . so .... CloseHandle(hProcess); return 0; } TaskProcess::TaskProcess(int Argc,wchar_t **Argv) { } TaskProcess::TaskProcess(std::vector<std::wstring> &Args) { } TaskProcess::TaskProcess() { } int TaskProcess::Execute() { DWORD dwThread; HANDLE hThread=CreateThread(NULL, 0, FollowParentQuit, nullptr, 0, &dwThread); if(!hThread) return 2; CloseHandle(hThread); return 0; }
23.840708
134
0.665182
[ "vector" ]
c0a6ca04ed013c54e665f642fe365e2c8d9a81b1
1,260
hpp
C++
search/cuisine_filter.hpp
smartyw/organicmaps
9b10eb9d3ed6833861cef294c2416cc98b15e10d
[ "Apache-2.0" ]
4,879
2015-09-30T10:56:36.000Z
2022-03-31T18:43:03.000Z
search/cuisine_filter.hpp
smartyw/organicmaps
9b10eb9d3ed6833861cef294c2416cc98b15e10d
[ "Apache-2.0" ]
7,549
2015-09-30T10:52:53.000Z
2022-03-31T22:04:22.000Z
search/cuisine_filter.hpp
smartyw/organicmaps
9b10eb9d3ed6833861cef294c2416cc98b15e10d
[ "Apache-2.0" ]
1,493
2015-09-30T10:43:06.000Z
2022-03-21T09:16:49.000Z
#pragma once #include "search/categories_cache.hpp" #include "search/mwm_context.hpp" #include "indexer/mwm_set.hpp" #include <map> #include <memory> #include <utility> #include <vector> class FeatureType; namespace search { namespace cuisine_filter { struct Description { Description() = default; Description(FeatureType & ft); std::vector<uint32_t> m_types; }; class CuisineFilter { public: using Descriptions = std::vector<std::pair<uint32_t, Description>>; class ScopedFilter { public: ScopedFilter(MwmSet::MwmId const & mwmId, Descriptions const & descriptions, std::vector<uint32_t> const & types); bool Matches(FeatureID const & fid) const; private: MwmSet::MwmId const m_mwmId; Descriptions const & m_descriptions; std::vector<uint32_t> m_types; }; CuisineFilter(FoodCache & food); std::unique_ptr<ScopedFilter> MakeScopedFilter(MwmContext const & context, std::vector<uint32_t> const & types); void ClearCaches(); private: Descriptions const & GetDescriptions(MwmContext const & context); FoodCache & m_food; std::map<MwmSet::MwmId, Descriptions> m_descriptions; }; } // namespace cuisine_filter } // namespace search
20.655738
86
0.693651
[ "vector" ]
c0ac4477fd7f8892013b4d2ff9db3531cb1c0cfa
2,905
cpp
C++
gse/src/v20191112/model/UpdateRuntimeConfigurationRequest.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
43
2019-08-14T08:14:12.000Z
2022-03-30T12:35:09.000Z
gse/src/v20191112/model/UpdateRuntimeConfigurationRequest.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
12
2019-07-15T10:44:59.000Z
2021-11-02T12:35:00.000Z
gse/src/v20191112/model/UpdateRuntimeConfigurationRequest.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
28
2019-07-12T09:06:22.000Z
2022-03-30T08:04:18.000Z
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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 <tencentcloud/gse/v20191112/model/UpdateRuntimeConfigurationRequest.h> #include <tencentcloud/core/utils/rapidjson/document.h> #include <tencentcloud/core/utils/rapidjson/writer.h> #include <tencentcloud/core/utils/rapidjson/stringbuffer.h> using namespace TencentCloud::Gse::V20191112::Model; using namespace std; UpdateRuntimeConfigurationRequest::UpdateRuntimeConfigurationRequest() : m_fleetIdHasBeenSet(false), m_runtimeConfigurationHasBeenSet(false) { } string UpdateRuntimeConfigurationRequest::ToJsonString() const { rapidjson::Document d; d.SetObject(); rapidjson::Document::AllocatorType& allocator = d.GetAllocator(); if (m_fleetIdHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "FleetId"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(m_fleetId.c_str(), allocator).Move(), allocator); } if (m_runtimeConfigurationHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "RuntimeConfiguration"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(rapidjson::kObjectType).Move(), allocator); m_runtimeConfiguration.ToJsonObject(d[key.c_str()], allocator); } rapidjson::StringBuffer buffer; rapidjson::Writer<rapidjson::StringBuffer> writer(buffer); d.Accept(writer); return buffer.GetString(); } string UpdateRuntimeConfigurationRequest::GetFleetId() const { return m_fleetId; } void UpdateRuntimeConfigurationRequest::SetFleetId(const string& _fleetId) { m_fleetId = _fleetId; m_fleetIdHasBeenSet = true; } bool UpdateRuntimeConfigurationRequest::FleetIdHasBeenSet() const { return m_fleetIdHasBeenSet; } RuntimeConfiguration UpdateRuntimeConfigurationRequest::GetRuntimeConfiguration() const { return m_runtimeConfiguration; } void UpdateRuntimeConfigurationRequest::SetRuntimeConfiguration(const RuntimeConfiguration& _runtimeConfiguration) { m_runtimeConfiguration = _runtimeConfiguration; m_runtimeConfigurationHasBeenSet = true; } bool UpdateRuntimeConfigurationRequest::RuntimeConfigurationHasBeenSet() const { return m_runtimeConfigurationHasBeenSet; }
30.260417
114
0.756282
[ "model" ]
c0afb5a52f99f4ffe1174c4c143e3552c5ea26d6
3,593
cpp
C++
Solar/src/entities/line.cpp
ThaiDuongVu/Solar
eb4c1b69a92cb2f1ba4a365cc4e64f4e09bd2609
[ "MIT" ]
5
2021-03-07T01:04:55.000Z
2021-08-17T04:35:49.000Z
Solar/src/entities/line.cpp
ThaiDuongVu/Solar
eb4c1b69a92cb2f1ba4a365cc4e64f4e09bd2609
[ "MIT" ]
null
null
null
Solar/src/entities/line.cpp
ThaiDuongVu/Solar
eb4c1b69a92cb2f1ba4a365cc4e64f4e09bd2609
[ "MIT" ]
null
null
null
#include "line.h" #include "../mathf.h" #include "../core.h" #include <glad.h> #include <glfw3.h> #include <glm.hpp> namespace Solar { Line::Line(Transform transform, Color color, bool is_visible, bool is_parallax, bool is_bounded) : GameObject(transform, is_visible, is_parallax) { this->color = color; this->is_bounded = is_bounded; } Line::~Line() { glDeleteVertexArrays(1, &vao); glDeleteBuffers(1, &vbo); shader.Delete(); } void Line::Init(App app) { // Initialize shader shader.Init(); // Generate buffer and vertex array glGenBuffers(1, &vbo); glGenVertexArrays(1, &vao); // Finish initialization done_init = true; } void Line::Update(App app) { // Line position double x = transform.position.x; double y = transform.position.y; // Viewport position double viewport_x = (is_parallax) ? 0.0f : -app.viewport.transform.position.x; double viewport_y = (is_parallax) ? 0.0f : -app.viewport.transform.position.y; // Down vertex vertex[0] = Vector2(x / (app.Width() / 2.0f) + viewport_x, y / (app.Height() / 2.0f) + viewport_y); // Up vertex vertex[1] = Vector2(x / (app.Width() / 2.0f) + viewport_x, y / (app.Height() / 2.0f) + length / (app.Height()) + viewport_y); for (int i = 0; i < 2; i++) vertex[i] = CalculateRotation(app, vertex[i]); if (is_bounded) CalculateBound(app); vertices[0] = (float)vertex[0].x; vertices[1] = (float)vertex[0].y; vertices[2] = 0.0f; vertices[3] = color.r; vertices[4] = color.g; vertices[5] = color.b; vertices[6] = (float)vertex[1].x; vertices[7] = (float)vertex[1].y; vertices[8] = 0.0f; vertices[9] = color.r; vertices[10] = color.g; vertices[11] = color.b; } void Line::CalculateBound(App app) { } Vector2 Line::CalculateRotation(App app, Vector2 vertex) { // Sine & Cosine of current rotation double sin = Mathf::Sin(Mathf::DegreeToRadian(transform.rotation)); double cos = Mathf::Cos(Mathf::DegreeToRadian(transform.rotation)); // Point of rotation double x_point = transform.position.x; double y_point = transform.position.y; // Current vertex point double vertex_x = vertex.x * (app.Width() / 2.0f); double vertex_y = vertex.y * (app.Height() / 2.0f); // Rotate vertex vector to match with current rotation return (Vector2(x_point, y_point) + Vector2(cos * (vertex_x - x_point) - sin * (vertex_y - y_point), sin * (vertex_x - x_point) + cos * (vertex_y - y_point))) / Vector2((app.Width() / 2.0f), (app.Height() / 2.0f)); } void Line::Draw(App app, DrawMode draw_mode) { // If object is not visible then don't render if (!this->is_visible) return; // Perform initialization if not already if (!done_init) this->Init(app); if (draw_mode == DrawMode::Fill) glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); else glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); Update(app); /* ----- Offload this part to initialization instead? ----- */ // Bind buffer and vertex array glBindVertexArray(vao); glBindBuffer(GL_ARRAY_BUFFER, vbo); // Buffer vertices glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_DYNAMIC_DRAW); // How to interpret the vertex data glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)0); glEnableVertexAttribArray(0); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)(3 * sizeof(float))); glEnableVertexAttribArray(1); // Ativate shader shader.Use(); /* -------------------------------------------------------- */ // Draw vertices glDrawArrays(GL_LINE_STRIP, 0, 2); } } // namespace Solar
28.070313
146
0.658781
[ "render", "object", "vector", "transform" ]
c0b00348367725c0d95cbfa1fa06b1a18fbc6dca
3,762
cpp
C++
src/model/x-model.cpp
8l/swm
dfa4ba130ff39aa0bf96b991bca34fba086b333b
[ "BSD-2-Clause" ]
null
null
null
src/model/x-model.cpp
8l/swm
dfa4ba130ff39aa0bf96b991bca34fba086b333b
[ "BSD-2-Clause" ]
null
null
null
src/model/x-model.cpp
8l/swm
dfa4ba130ff39aa0bf96b991bca34fba086b333b
[ "BSD-2-Clause" ]
null
null
null
/** @file */ #include "x-model.h" /** * Registers a new icon - note that, at this point, XModel takes * responsibility for the given icon, and it should not be deleted unless * explicitly unregistered. * * @param icon The new icon to register. */ void XModel::register_icon(Icon *icon) { m_clients_to_icons[icon->client] = icon; m_icon_windows_to_icons[icon->icon] = icon; } /** * Unregisters an icon. This also removes the responsibility of the pointer * from the XModel, and it should be deleted later to avoid a memory leak. * * @param icon The icon to unregister. */ void XModel::unregister_icon(Icon *icon) { m_clients_to_icons.erase(icon->client); m_icon_windows_to_icons.erase(icon->icon); } /** * Gets the icon from the client window the icon is hiding. */ Icon* XModel::find_icon_from_client(Window client) { return m_clients_to_icons[client]; } /** * Gets the icon from the icon window which is being shown. */ Icon* XModel::find_icon_from_icon_window(Window icon_win) { return m_icon_windows_to_icons[icon_win]; } /** * Gets a list of all of the icons. */ void XModel::get_icons(std::vector<Icon*> &icons) { for (std::map<Window,Icon*>::iterator iter = m_clients_to_icons.begin(); iter != m_clients_to_icons.end(); iter++) { if (iter->second != 0) icons.push_back(iter->second); } } /** * Registers that a client is being moved, recording the client and the * placeholder, and recording the current pointer location. * * @return true if the change is successful, false if the change cannot be * done due to an invalid state. */ void XModel::enter_move(Window client, Window placeholder, Dimension2D pointer) { if (m_moveresize) return; m_moveresize = new MoveResize(client, placeholder, MR_MOVE); m_pointer = pointer; } /** * Registers that a client is being resized, recording the client and the * placeholder, and recording the current pointer location. * * @return true if the change is successful, false if the change cannot be * done due to an invalid state. */ void XModel::enter_resize(Window client, Window placeholder, Dimension2D pointer) { if (m_moveresize) return; m_moveresize = new MoveResize(client, placeholder, MR_RESIZE); m_pointer = pointer; } /** * Updates the pointer to a new location, returning the difference between * the old position and the current position. * * Note that, if no movement or resizing is currently going on, then the * return value will be (0, 0). */ Dimension2D XModel::update_pointer(Dimension x, Dimension y) { if (!m_moveresize) return Dimension2D(0, 0); Dimension2D diff(x - DIM2D_X(m_pointer), y - DIM2D_Y(m_pointer)); DIM2D_X(m_pointer) = x; DIM2D_Y(m_pointer) = y; return diff; } /** * Gets the current placeholder which is being used to move/resize. * * @return The placeholder, or None if no window is being moved/resized. */ Window XModel::get_move_resize_placeholder() { if (!m_moveresize) return None; return m_moveresize->placeholder; } /** * Gets the current client which is being moved/resized. * * @return The client, or None if no window is being moved/resized. */ Window XModel::get_move_resize_client() { if (!m_moveresize) return None; return m_moveresize->client; } /** * Gets the current move/resize state. */ MoveResizeState XModel::get_move_resize_state() { if (!m_moveresize) return MR_INVALID; return m_moveresize->state; } /** * Stops moving/resizing. */ void XModel::exit_move_resize() { if (!m_moveresize) return; delete m_moveresize; m_moveresize = 0; }
23.36646
76
0.683147
[ "vector", "model" ]
c0b0fb3d9a4596c0fd7f96248389e77451116e6b
41,023
cpp
C++
src/RigidBody/Joints.cpp
vincentdelpech/biorbd
0d7968e75e182f067a4d4c24cc15fa9a331ca792
[ "MIT" ]
null
null
null
src/RigidBody/Joints.cpp
vincentdelpech/biorbd
0d7968e75e182f067a4d4c24cc15fa9a331ca792
[ "MIT" ]
null
null
null
src/RigidBody/Joints.cpp
vincentdelpech/biorbd
0d7968e75e182f067a4d4c24cc15fa9a331ca792
[ "MIT" ]
null
null
null
#define BIORBD_API_EXPORTS #include "RigidBody/Joints.h" #include <rbdl/rbdl_math.h> #include <rbdl/rbdl_utils.h> #include <rbdl/Kinematics.h> #include <rbdl/Dynamics.h> #include "Utils/String.h" #include "Utils/Quaternion.h" #include "Utils/Matrix.h" #include "Utils/Error.h" #include "Utils/RotoTrans.h" #include "RigidBody/GeneralizedCoordinates.h" #include "RigidBody/GeneralizedTorque.h" #include "RigidBody/Integrator.h" #include "RigidBody/Bone.h" #include "RigidBody/Markers.h" #include "RigidBody/NodeBone.h" #include "RigidBody/Patch.h" #include "RigidBody/BoneMesh.h" #include "RigidBody/BoneCaracteristics.h" biorbd::rigidbody::Joints::Joints() : RigidBodyDynamics::Model(), m_bones(std::make_shared<std::vector<biorbd::rigidbody::Bone>>()), m_integrator(std::make_shared<biorbd::rigidbody::Integrator>()), m_nbRoot(std::make_shared<unsigned int>(0)), m_nDof(std::make_shared<unsigned int>(0)), m_nbQ(std::make_shared<unsigned int>(0)), m_nbQdot(std::make_shared<unsigned int>(0)), m_nbQddot(std::make_shared<unsigned int>(0)), m_nRotAQuat(std::make_shared<unsigned int>(0)), m_isRootActuated(std::make_shared<bool>(true)), m_hasExternalForces(std::make_shared<bool>(false)), m_isKinematicsComputed(std::make_shared<bool>(false)), m_totalMass(std::make_shared<double>(0)) { this->gravity = RigidBodyDynamics::Math::Vector3d (0, 0, -9.81); // Redéfinition de la gravité pour qu'elle soit en z } biorbd::rigidbody::Joints::Joints(const biorbd::rigidbody::Joints &other) : RigidBodyDynamics::Model(other), m_bones(other.m_bones), m_integrator(other.m_integrator), m_nbRoot(other.m_nbRoot), m_nDof(other.m_nDof), m_nbQ(other.m_nbQ), m_nbQdot(other.m_nbQdot), m_nbQddot(other.m_nbQddot), m_nRotAQuat(other.m_nRotAQuat), m_isRootActuated(other.m_isRootActuated), m_hasExternalForces(other.m_hasExternalForces), m_isKinematicsComputed(other.m_isKinematicsComputed), m_totalMass(other.m_totalMass) { } biorbd::rigidbody::Joints::~Joints() { } biorbd::rigidbody::Joints biorbd::rigidbody::Joints::DeepCopy() const { biorbd::rigidbody::Joints copy; copy.DeepCopy(*this); return copy; } void biorbd::rigidbody::Joints::DeepCopy(const biorbd::rigidbody::Joints &other) { static_cast<RigidBodyDynamics::Model&>(*this) = other; m_bones->resize(other.m_bones->size()); for (unsigned int i=0; i<other.m_bones->size(); ++i) (*m_bones)[i] = (*other.m_bones)[i].DeepCopy(); *m_integrator = other.m_integrator->DeepCopy(); *m_nbRoot = *other.m_nbRoot; *m_nDof = *other.m_nDof; *m_nbQ = *other.m_nbQ; *m_nbQdot = *other.m_nbQdot; *m_nbQddot = *other.m_nbQddot; *m_nRotAQuat = *other.m_nRotAQuat; *m_isRootActuated = *other.m_isRootActuated; *m_hasExternalForces = *other.m_hasExternalForces; *m_isKinematicsComputed = *other.m_isKinematicsComputed; *m_totalMass = *other.m_totalMass; } unsigned int biorbd::rigidbody::Joints::nbGeneralizedTorque() const { return dof_count-nbRoot(); } unsigned int biorbd::rigidbody::Joints::nbDof() const { return *m_nDof; } std::vector<std::string> biorbd::rigidbody::Joints::nameDof() const { std::vector<std::string> names; for (unsigned int i=0; i<nbBone(); ++i){ for (unsigned int j=0; j<bone(i).nDof(); ++j){ names.push_back(bone(i).name() + "_" + bone(i).nameDof(j)); } } return names; } unsigned int biorbd::rigidbody::Joints::nbQ() const { return *m_nbQ; } unsigned int biorbd::rigidbody::Joints::nbQdot() const { return *m_nbQdot; } unsigned int biorbd::rigidbody::Joints::nbQddot() const { return *m_nbQddot; } unsigned int biorbd::rigidbody::Joints::nbRoot() const { if (m_isRootActuated) return 0; else return *m_nbRoot; } void biorbd::rigidbody::Joints::setIsRootActuated(bool a) { *m_isRootActuated = a; } bool biorbd::rigidbody::Joints::isRootActuated() const { return *m_isRootActuated; } void biorbd::rigidbody::Joints::setHasExternalForces(bool f) { *m_hasExternalForces = f; } bool biorbd::rigidbody::Joints::hasExternalForces() const { return *m_hasExternalForces; } double biorbd::rigidbody::Joints::mass() const { return *m_totalMass; } void biorbd::rigidbody::Joints::integrateKinematics( const biorbd::rigidbody::GeneralizedCoordinates& Q, const biorbd::rigidbody::GeneralizedCoordinates& QDot, const biorbd::rigidbody::GeneralizedTorque& GeneralizedTorque) { biorbd::utils::Vector v(static_cast<unsigned int>(Q.rows()+QDot.rows())); v << Q,QDot; m_integrator->integrate(*this, v, GeneralizedTorque, 0, 1, 0.1); // vecteur, t0, tend, pas, effecteurs *m_isKinematicsComputed = true; } void biorbd::rigidbody::Joints::getIntegratedKinematics( unsigned int step, biorbd::rigidbody::GeneralizedCoordinates &Q, biorbd::rigidbody::GeneralizedCoordinates &QDot) { // Si la cinématique n'a pas été mise à jour biorbd::utils::Error::check(*m_isKinematicsComputed, "ComputeKinematics must be call before calling updateKinematics"); const biorbd::utils::Vector& tp(m_integrator->getX(step)); for (unsigned int i=0; i< static_cast<unsigned int>(tp.rows()/2); i++){ Q(i) = tp(i); QDot(i) = tp(i+tp.rows()/2); } } unsigned int biorbd::rigidbody::Joints::nbInterationStep() const { return m_integrator->steps(); } unsigned int biorbd::rigidbody::Joints::AddBone( const biorbd::utils::String &segmentName, // Nom du segment const biorbd::utils::String &parentName, // Nom du segment const biorbd::utils::String &translationSequence, const biorbd::utils::String &rotationSequence, // Séquence de Cardan pour classer les dof en rotation const biorbd::rigidbody::BoneCaracteristics& caract, // Mase, Centre de masse du segment, Inertie du segment, etc. const RigidBodyDynamics::Math::SpatialTransform& centreOfRotation, // Transformation du parent vers l'enfant int forcePlates) { // Numéro de la plateforme de force attaché à cet os biorbd::rigidbody::Bone tp(*this, segmentName, parentName, translationSequence, rotationSequence, caract, centreOfRotation, forcePlates); if (this->GetBodyId(parentName.c_str()) == std::numeric_limits<unsigned int>::max()) *m_nbRoot += tp.nDof(); // Si le nom du segment est "Root" ajouter le nombre de dof de racine *m_nDof += tp.nDof(); *m_nbQ += tp.nQ(); *m_nbQdot += tp.nQdot(); *m_nbQddot += tp.nQddot(); if (tp.isRotationAQuaternion()) ++*m_nRotAQuat; *m_totalMass += caract.mMass; // Ajouter la masse segmentaire a la masse totale du corps m_bones->push_back(tp); return 0; } unsigned int biorbd::rigidbody::Joints::AddBone( const biorbd::utils::String &segmentName, // Nom du segment const biorbd::utils::String &parentName, // Nom du segment const biorbd::utils::String &seqR, // Séquence de Cardan pour classer les dof en rotation const biorbd::rigidbody::BoneCaracteristics& caract, // Mase, Centre de masse du segment, Inertie du segment, etc. const RigidBodyDynamics::Math::SpatialTransform& cor, // Transformation du parent vers l'enfant int forcePlates) { // Numéro de la plateforme de force attaché à cet os biorbd::rigidbody::Bone tp(*this, segmentName, parentName, seqR, caract, cor, forcePlates); if (this->GetBodyId(parentName.c_str()) == std::numeric_limits<unsigned int>::max()) *m_nbRoot += tp.nDof(); // Si le nom du segment est "Root" ajouter le nombre de dof de racine *m_nDof += tp.nDof(); *m_totalMass += caract.mMass; // Ajouter la masse segmentaire a la masse totale du corps m_bones->push_back(tp); return 0; } const biorbd::rigidbody::Bone& biorbd::rigidbody::Joints::bone(unsigned int idxSegment) const { biorbd::utils::Error::check(idxSegment < m_bones->size(), "Asked for a wrong segment (out of range)"); return (*m_bones)[idxSegment]; } const biorbd::rigidbody::Bone &biorbd::rigidbody::Joints::bone(const biorbd::utils::String & nameSegment) const { return bone(static_cast<unsigned int>(GetBodyBiorbdId(nameSegment.c_str()))); } unsigned int biorbd::rigidbody::Joints::nbBone() const { return static_cast<unsigned int>(m_bones->size()); } std::vector<RigidBodyDynamics::Math::SpatialVector> biorbd::rigidbody::Joints::dispatchedForce( std::vector<std::vector<RigidBodyDynamics::Math::SpatialVector>> &spatialVector, unsigned int frame) const { // Itérateur sur le tableau de force std::vector<RigidBodyDynamics::Math::SpatialVector> sv2; // Mettre dans un même tableau les valeurs d'un même instant de différentes plateformes for (auto vec : spatialVector) sv2.push_back(vec[frame]); // Appel de la fonction équivalente qui ne gere qu'a un instant return dispatchedForce(sv2); } std::vector<RigidBodyDynamics::Math::SpatialVector> biorbd::rigidbody::Joints::dispatchedForce( std::vector<RigidBodyDynamics::Math::SpatialVector> &sv) const{ // un SpatialVector par PF // Tableau de sortie std::vector<RigidBodyDynamics::Math::SpatialVector> sv_out; // Spatial vector nul pour remplir le tableau final RigidBodyDynamics::Math::SpatialVector sv_zero(0,0,0,0,0,0); sv_out.push_back(sv_zero); // Le premier est associé a l'univers // Dispatch des forces for (auto bone : *m_bones){ unsigned int nDof = bone.nDof(); if (nDof != 0){ // Ne rien ajouter si le nDof est à 0 // Pour chaque segment, for (unsigned int i=0; i<nDof-1; ++i) // mettre un sv_zero sur tous les dof sauf le dernier sv_out.push_back(sv_zero); if (bone.plateformeIdx() >= 0){ // Si le solide fait contact avec la plateforme (!= -1) sv_out.push_back(sv[static_cast<unsigned int>(bone.plateformeIdx())]); // Mettre la force de la plateforme correspondante } else sv_out.push_back(sv_zero); // Sinon, mettre 0 } } // Retour du STL vector de SpatialVector return sv_out; } int biorbd::rigidbody::Joints::GetBodyBiorbdId(const biorbd::utils::String &segmentName) const{ for (int i=0; i<static_cast<int>(m_bones->size()); ++i) if (!(*m_bones)[static_cast<unsigned int>(i)].name().compare(segmentName)) return i; return -1; } std::vector<biorbd::utils::RotoTrans> biorbd::rigidbody::Joints::allGlobalJCS( const biorbd::rigidbody::GeneralizedCoordinates &Q) { UpdateKinematicsCustom (&Q, nullptr, nullptr); return allGlobalJCS(); } std::vector<biorbd::utils::RotoTrans> biorbd::rigidbody::Joints::allGlobalJCS() const { std::vector<biorbd::utils::RotoTrans> out; for (unsigned int i=0; i<m_bones->size(); ++i) out.push_back(globalJCS(i)); return out; } biorbd::utils::RotoTrans biorbd::rigidbody::Joints::globalJCS( const biorbd::rigidbody::GeneralizedCoordinates &Q, const biorbd::utils::String &name) { UpdateKinematicsCustom (&Q, nullptr, nullptr); return globalJCS(name); } biorbd::utils::RotoTrans biorbd::rigidbody::Joints::globalJCS( const biorbd::rigidbody::GeneralizedCoordinates &Q, unsigned int idx) { // update the Kinematics if necessary UpdateKinematicsCustom (&Q, nullptr, nullptr); return globalJCS(idx); } biorbd::utils::RotoTrans biorbd::rigidbody::Joints::globalJCS(const biorbd::utils::String &parentName) const { return globalJCS(static_cast<unsigned int>(GetBodyBiorbdId(parentName))); } biorbd::utils::RotoTrans biorbd::rigidbody::Joints::globalJCS( unsigned int idx) const { return CalcBodyWorldTransformation((*m_bones)[idx].id()); } std::vector<biorbd::utils::RotoTrans> biorbd::rigidbody::Joints::localJCS() const{ std::vector<biorbd::utils::RotoTrans> out; for (unsigned int i=0; i<m_bones->size(); ++i) out.push_back(localJCS(i)); return out; } biorbd::utils::RotoTrans biorbd::rigidbody::Joints::localJCS(const biorbd::utils::String &segmentName) const{ return localJCS(static_cast<unsigned int>(GetBodyBiorbdId(segmentName.c_str()))); } biorbd::utils::RotoTrans biorbd::rigidbody::Joints::localJCS(const unsigned int i) const{ return (*m_bones)[i].localJCS(); } std::vector<biorbd::rigidbody::NodeBone> biorbd::rigidbody::Joints::projectPoint( const biorbd::rigidbody::GeneralizedCoordinates &Q, const std::vector<biorbd::rigidbody::NodeBone> &v, bool updateKin) { if (updateKin) UpdateKinematicsCustom (&Q, nullptr, nullptr); updateKin = false; // Assuming that this is also a marker type (via BiorbdModel) const biorbd::rigidbody::Markers &marks = dynamic_cast<biorbd::rigidbody::Markers &>(*this); // Sécurité biorbd::utils::Error::check(marks.nMarkers() == v.size(), "Number of marker must be equal to number of Vector3d"); std::vector<biorbd::rigidbody::NodeBone> out; for (unsigned int i=0;i<marks.nMarkers();++i){ biorbd::rigidbody::NodeBone tp(marks.marker(i)); if (tp.nAxesToRemove()!=0){ tp = v[i].applyRT(globalJCS(tp.parent()).transpose()); // Prendre la position du nouveau marker avec les infos de celui du modèle out.push_back(projectPoint(Q,tp,updateKin)); } else // S'il ne faut rien retirer (renvoyer tout de suite la même position) out.push_back( v[i] ); } return out; } biorbd::rigidbody::NodeBone biorbd::rigidbody::Joints::projectPoint( const biorbd::rigidbody::GeneralizedCoordinates &Q, const utils::Node3d &v, int boneIdx, const biorbd::utils::String& axesToRemove, bool updateKin) { if (updateKin) UpdateKinematicsCustom (&Q, nullptr, nullptr); // Créer un marqueur const biorbd::utils::String& boneName(bone(static_cast<unsigned int>(boneIdx)).name()); biorbd::rigidbody::NodeBone node( v.applyRT(globalJCS(static_cast<unsigned int>(boneIdx)).transpose()), "tp", boneName, true, true, axesToRemove, static_cast<int>(GetBodyId(boneName.c_str()))); // projeté puis remettre dans le global return projectPoint(Q, node, updateKin); } biorbd::rigidbody::NodeBone biorbd::rigidbody::Joints::projectPoint( const biorbd::rigidbody::GeneralizedCoordinates &Q, const biorbd::rigidbody::NodeBone &n, bool updateKin) { // Assuming that this is also a Marker type (via BiorbdModel) return dynamic_cast<biorbd::rigidbody::Markers &>(*this).marker(Q, n, true, updateKin); } biorbd::utils::Matrix biorbd::rigidbody::Joints::projectPointJacobian( const biorbd::rigidbody::GeneralizedCoordinates &Q, biorbd::rigidbody::NodeBone node, bool updateKin) { if (updateKin) UpdateKinematicsCustom (&Q, nullptr, nullptr); // Assuming that this is also a Marker type (via BiorbdModel) biorbd::rigidbody::Markers &marks = dynamic_cast<biorbd::rigidbody::Markers &>(*this); // Si le point n'a pas été projeté, il n'y a donc aucun effet if (node.nAxesToRemove() != 0){ // Jacobienne du marqueur node.applyRT(globalJCS(node.parent()).transpose()); biorbd::utils::Matrix G_tp(marks.markersJacobian(Q, node.parent(), biorbd::utils::Node3d(0,0,0), updateKin)); biorbd::utils::Matrix JCor(biorbd::utils::Matrix::Zero(9,nbQ())); CalcMatRotJacobian(Q, GetBodyId(node.parent().c_str()), Eigen::Matrix3d::Identity(3,3), JCor,false); for (unsigned int n=0; n<3; ++n) if (node.isAxisKept(n)) G_tp += JCor.block(n*3,0,3,nbQ()) * node(n); return G_tp; } else { // Retourner la valeur return biorbd::utils::Matrix::Zero(3,nbQ()); } } biorbd::utils::Matrix biorbd::rigidbody::Joints::projectPointJacobian( const biorbd::rigidbody::GeneralizedCoordinates &Q, const utils::Node3d &v, int boneIdx, const biorbd::utils::String& axesToRemove, bool updateKin) { // Trouver le point const biorbd::rigidbody::NodeBone& p(projectPoint(Q, v, boneIdx, axesToRemove, updateKin)); // Retourner la valeur return projectPointJacobian(Q, p, updateKin); } std::vector<biorbd::utils::Matrix> biorbd::rigidbody::Joints::projectPointJacobian( const biorbd::rigidbody::GeneralizedCoordinates &Q, const std::vector<biorbd::rigidbody::NodeBone> &v, bool updateKin) { // Receuillir les points const std::vector<biorbd::rigidbody::NodeBone>& tp(projectPoint(Q, v, updateKin)); // Calculer la jacobienne si le point doit être projeté std::vector<biorbd::utils::Matrix> G; for (unsigned int i=0; i<tp.size(); ++i){ // Marqueur actuel G.push_back(projectPointJacobian(Q, biorbd::rigidbody::NodeBone(v[i]), false)); } return G; } RigidBodyDynamics::Math::SpatialTransform biorbd::rigidbody::Joints::CalcBodyWorldTransformation ( const biorbd::rigidbody::GeneralizedCoordinates &Q, const unsigned int body_id, bool update_kinematics = true) { // update the Kinematics if necessary if (update_kinematics) UpdateKinematicsCustom (&Q, nullptr, nullptr); return CalcBodyWorldTransformation(body_id); } RigidBodyDynamics::Math::SpatialTransform biorbd::rigidbody::Joints::CalcBodyWorldTransformation( const unsigned int body_id) const { if (body_id >= this->fixed_body_discriminator) { unsigned int fbody_id = body_id - this->fixed_body_discriminator; unsigned int parent_id = this->mFixedBodies[fbody_id].mMovableParent; biorbd::utils::RotoTrans parentRT(this->X_base[parent_id].E.transpose(), this->X_base[parent_id].r); biorbd::utils::RotoTrans bodyRT(this->mFixedBodies[fbody_id].mParentTransform.E.transpose(), this->mFixedBodies[fbody_id].mParentTransform.r); const biorbd::utils::RotoTrans& transfo_tp = parentRT * bodyRT; return RigidBodyDynamics::Math::SpatialTransform (transfo_tp.rot(), transfo_tp.trans()); } return RigidBodyDynamics::Math::SpatialTransform (this->X_base[body_id].E.transpose(), this->X_base[body_id].r); } biorbd::utils::Node3d biorbd::rigidbody::Joints::CoM( const biorbd::rigidbody::GeneralizedCoordinates &Q, bool updateKin) { // Retour la position du centre de masse a partir des coordonnées généralisées // S'assurer que le modele est dans la bonne configuration if (updateKin) UpdateKinematicsCustom(&Q, nullptr, nullptr); // Pour chaque segment, trouver le CoM (CoM = somme(masse_segmentaire * pos_com_seg)/masse_totale) const std::vector<biorbd::rigidbody::NodeBone>& com_segment(CoMbySegment(Q,true)); biorbd::utils::Node3d com(0, 0, 0); for (unsigned int i=0; i<com_segment.size(); ++i) com += (*m_bones)[i].caract().mMass * com_segment[i]; // Diviser par la masse totale com = com/this->mass(); // Retourner le CoM return com; } RigidBodyDynamics::Math::Vector3d biorbd::rigidbody::Joints::angularMomentum( const biorbd::rigidbody::GeneralizedCoordinates &Q, const biorbd::rigidbody::GeneralizedCoordinates &Qdot, bool updateKin) { return CalcAngularMomentum(*this, Q, Qdot, updateKin); } RigidBodyDynamics::Math::Vector3d biorbd::rigidbody::Joints::CoMdot( const biorbd::rigidbody::GeneralizedCoordinates &Q, const biorbd::rigidbody::GeneralizedCoordinates &Qdot) { // Retour la vitesse du centre de masse a partir des coordonnées généralisées // S'assurer que le modele est dans la bonne configuration UpdateKinematicsCustom(&Q, &Qdot, nullptr); // Pour chaque segment, trouver le CoM RigidBodyDynamics::Math::Vector3d com_dot(0,0,0); // CoMdot = somme(masse_seg * Jacobienne * qdot)/masse totale biorbd::utils::Matrix Jac(biorbd::utils::Matrix(3,this->dof_count)); for (auto bone : *m_bones){ Jac.setZero(); RigidBodyDynamics::CalcPointJacobian(*this, Q, this->GetBodyId(bone.name().c_str()), bone.caract().mCenterOfMass, Jac, false); // False for speed com_dot += ((Jac*Qdot) * bone.caract().mMass); } // Diviser par la masse totale com_dot = com_dot/this->mass(); // Retourner la vitesse du CoM return com_dot; } RigidBodyDynamics::Math::Vector3d biorbd::rigidbody::Joints::CoMddot( const biorbd::rigidbody::GeneralizedCoordinates &Q, const biorbd::rigidbody::GeneralizedCoordinates &Qdot, const biorbd::rigidbody::GeneralizedCoordinates &Qddot) { // Retour l'accélération du centre de masse a partir des coordonnées généralisées biorbd::utils::Error::raise("Com DDot is wrong, to be modified..."); // S'assurer que le modele est dans la bonne configuration UpdateKinematicsCustom(&Q, &Qdot, &Qddot); // Pour chaque segment, trouver le CoM RigidBodyDynamics::Math::Vector3d com_ddot(0,0,0); // CoMdot = somme(masse_seg * Jacobienne * qdot)/masse totale biorbd::utils::Matrix Jac(biorbd::utils::Matrix(3,this->dof_count)); for (auto bone : *m_bones){ Jac.setZero(); RigidBodyDynamics::CalcPointJacobian(*this, Q, this->GetBodyId(bone.name().c_str()), bone.caract().mCenterOfMass, Jac, false); // False for speed com_ddot += ((Jac*Qddot) * bone.caract().mMass); } // Diviser par la masse totale com_ddot = com_ddot/this->mass(); // Retourner l'accélération du CoM return com_ddot; } biorbd::utils::Matrix biorbd::rigidbody::Joints::CoMJacobian(const biorbd::rigidbody::GeneralizedCoordinates &Q) { // Retour la position du centre de masse a partir des coordonnées généralisées // S'assurer que le modele est dans la bonne configuration UpdateKinematicsCustom(&Q, nullptr, nullptr); // Jacobienne totale biorbd::utils::Matrix JacTotal(biorbd::utils::Matrix::Zero(3,this->dof_count)); // CoMdot = somme(masse_seg * Jacobienne * qdot)/masse totale biorbd::utils::Matrix Jac(biorbd::utils::Matrix::Zero(3,this->dof_count)); for (auto bone : *m_bones){ Jac.setZero(); RigidBodyDynamics::CalcPointJacobian(*this, Q, this->GetBodyId(bone.name().c_str()), bone.caract().mCenterOfMass, Jac, false); // False for speed JacTotal += bone.caract().mMass*Jac; } // Diviser par la masse totale JacTotal /= this->mass(); // Retourner la jacobienne du CoM return JacTotal; } std::vector<biorbd::rigidbody::NodeBone> biorbd::rigidbody::Joints::CoMbySegment( const biorbd::rigidbody::GeneralizedCoordinates &Q, bool updateKin) {// Position du centre de masse de chaque segment std::vector<biorbd::rigidbody::NodeBone> tp; // vecteur de vecteurs de sortie for (unsigned int i=0; i<m_bones->size(); ++i){ tp.push_back(CoMbySegment(Q,i,updateKin)); updateKin = false; // ne le faire que la premiere fois } return tp; } biorbd::utils::Node3d biorbd::rigidbody::Joints::CoMbySegment( const biorbd::rigidbody::GeneralizedCoordinates &Q, const unsigned int i, bool updateKin) { // Position du centre de masse du segment i biorbd::utils::Error::check(i < m_bones->size(), "Choosen segment doesn't exist"); return RigidBodyDynamics::CalcBodyToBaseCoordinates( *this, Q, (*m_bones)[i].id(), (*m_bones)[i].caract().mCenterOfMass, updateKin); } std::vector<RigidBodyDynamics::Math::Vector3d> biorbd::rigidbody::Joints::CoMdotBySegment( const biorbd::rigidbody::GeneralizedCoordinates &Q, const biorbd::rigidbody::GeneralizedCoordinates &Qdot, bool updateKin) {// Position du centre de masse de chaque segment std::vector<RigidBodyDynamics::Math::Vector3d> tp; // vecteur de vecteurs de sortie for (unsigned int i=0; i<m_bones->size(); ++i){ tp.push_back(CoMdotBySegment(Q,Qdot,i,updateKin)); updateKin = false; // ne le faire que la premiere fois } return tp; } RigidBodyDynamics::Math::Vector3d biorbd::rigidbody::Joints::CoMdotBySegment( const biorbd::rigidbody::GeneralizedCoordinates &Q, const biorbd::rigidbody::GeneralizedCoordinates &Qdot, const unsigned int i, bool updateKin) { // Position du centre de masse du segment i biorbd::utils::Error::check(i < m_bones->size(), "Choosen segment doesn't exist"); return CalcPointVelocity(*this, Q, Qdot, (*m_bones)[i].id(),(*m_bones)[i].caract().mCenterOfMass,updateKin); } std::vector<RigidBodyDynamics::Math::Vector3d> biorbd::rigidbody::Joints::CoMddotBySegment( const biorbd::rigidbody::GeneralizedCoordinates &Q, const biorbd::rigidbody::GeneralizedCoordinates &Qdot, const biorbd::rigidbody::GeneralizedCoordinates &Qddot, bool updateKin) {// Position du centre de masse de chaque segment std::vector<RigidBodyDynamics::Math::Vector3d> tp; // vecteur de vecteurs de sortie for (unsigned int i=0; i<m_bones->size(); ++i){ tp.push_back(CoMddotBySegment(Q,Qdot,Qddot,i,updateKin)); updateKin = false; // ne le faire que la premiere fois } return tp; } RigidBodyDynamics::Math::Vector3d biorbd::rigidbody::Joints::CoMddotBySegment( const biorbd::rigidbody::GeneralizedCoordinates &Q, const biorbd::rigidbody::GeneralizedCoordinates &Qdot, const biorbd::rigidbody::GeneralizedCoordinates &Qddot, const unsigned int i, bool updateKin) { // Position du centre de masse du segment i biorbd::utils::Error::check(i < m_bones->size(), "Choosen segment doesn't exist"); return RigidBodyDynamics::CalcPointAcceleration(*this, Q, Qdot, Qddot, (*m_bones)[i].id(),(*m_bones)[i].caract().mCenterOfMass,updateKin); } std::vector<std::vector<biorbd::utils::Node3d>> biorbd::rigidbody::Joints::meshPoints( const biorbd::rigidbody::GeneralizedCoordinates &Q, bool updateKin) { if (updateKin) UpdateKinematicsCustom (&Q, nullptr, nullptr); std::vector<std::vector<biorbd::utils::Node3d>> v; // Vecteur de vecteur de sortie (mesh par segment) // Trouver la position des segments const std::vector<biorbd::utils::RotoTrans>& RT(allGlobalJCS()); // Pour tous les segments for (unsigned int i=0; i<nbBone(); ++i) v.push_back(meshPoints(RT,i)); return v; } std::vector<biorbd::utils::Node3d> biorbd::rigidbody::Joints::meshPoints( const biorbd::rigidbody::GeneralizedCoordinates &Q, unsigned int i, bool updateKin) { if (updateKin) UpdateKinematicsCustom (&Q, nullptr, nullptr); // Trouver la position des segments const std::vector<biorbd::utils::RotoTrans>& RT(allGlobalJCS()); return meshPoints(RT,i); } std::vector<biorbd::utils::Node3d> biorbd::rigidbody::Joints::meshPoints( const std::vector<biorbd::utils::RotoTrans> &RT, unsigned int i) const{ // Recueillir la position des meshings std::vector<biorbd::utils::Node3d> v; for (unsigned int j=0; j<boneMesh(i).size(); ++j){ biorbd::utils::Node3d tp (boneMesh(i).point(j)); tp.applyRT(RT[i]); v.push_back(tp); } return v; } std::vector<std::vector<biorbd::rigidbody::Patch>> biorbd::rigidbody::Joints::meshPatch() const{ // Recueillir la position des meshings pour tous les segments std::vector<std::vector<biorbd::rigidbody::Patch>> v_all; for (unsigned int j=0; j<nbBone(); ++j) v_all.push_back(meshPatch(j)); return v_all; } const std::vector<biorbd::rigidbody::Patch> &biorbd::rigidbody::Joints::meshPatch(unsigned int i) const{ // Recueillir la position des meshings pour un segment i return boneMesh(i).patch(); } std::vector<biorbd::rigidbody::BoneMesh> biorbd::rigidbody::Joints::boneMesh() const { std::vector<biorbd::rigidbody::BoneMesh> boneOut; for (unsigned int i=0; i<nbBone(); ++i) boneOut.push_back(boneMesh(i)); return boneOut; } const biorbd::rigidbody::BoneMesh &biorbd::rigidbody::Joints::boneMesh(unsigned int idx) const { return bone(idx).caract().mesh(); } RigidBodyDynamics::Math::Vector3d biorbd::rigidbody::Joints::CalcAngularMomentum ( const biorbd::rigidbody::GeneralizedCoordinates &Q, const biorbd::rigidbody::GeneralizedCoordinates &Qdot, bool update_kinematics) { // Qddot was added later in the RBDL. In order to keep backward compatilibity, biorbd::rigidbody::GeneralizedCoordinates Qddot(this->nbQddot()); return CalcAngularMomentum(Q, Qdot, Qddot, update_kinematics); } RigidBodyDynamics::Math::Vector3d biorbd::rigidbody::Joints::CalcAngularMomentum ( const biorbd::rigidbody::GeneralizedCoordinates &Q, const biorbd::rigidbody::GeneralizedCoordinates &Qdot, const biorbd::rigidbody::GeneralizedCoordinates &Qddot, bool update_kinematics) { // Définition des variables RigidBodyDynamics::Math::Vector3d com, angular_momentum; double mass; // Calcul du angular momentum par la fonction de la position du centre de masse RigidBodyDynamics::Utils::CalcCenterOfMass(*this, Q, Qdot, &Qddot, mass, com, nullptr, nullptr, &angular_momentum, nullptr, update_kinematics); return angular_momentum; } std::vector<RigidBodyDynamics::Math::Vector3d> biorbd::rigidbody::Joints::CalcSegmentsAngularMomentum ( const biorbd::rigidbody::GeneralizedCoordinates &Q, const biorbd::rigidbody::GeneralizedCoordinates &Qdot, bool update_kinematics) { biorbd::rigidbody::GeneralizedCoordinates Qddot(this->nbQddot()); return CalcSegmentsAngularMomentum(Q, Qdot, Qddot, update_kinematics); } std::vector<RigidBodyDynamics::Math::Vector3d> biorbd::rigidbody::Joints::CalcSegmentsAngularMomentum ( const biorbd::rigidbody::GeneralizedCoordinates &Q, const biorbd::rigidbody::GeneralizedCoordinates &Qdot, const biorbd::rigidbody::GeneralizedCoordinates &Qddot, bool update_kinematics) { if (update_kinematics) UpdateKinematicsCustom (&Q, &Qdot, &Qddot); double mass; RigidBodyDynamics::Math::Vector3d com; RigidBodyDynamics::Utils::CalcCenterOfMass (*this, Q, Qdot, &Qddot, mass, com, nullptr, nullptr, nullptr, nullptr, false); RigidBodyDynamics::Math::SpatialTransform X_to_COM (RigidBodyDynamics::Math::Xtrans(com)); std::vector<RigidBodyDynamics::Math::Vector3d> h_segment; for (unsigned int i = 1; i < this->mBodies.size(); i++) { this->Ic[i] = this->I[i]; this->hc[i] = this->Ic[i].toMatrix() * this->v[i]; RigidBodyDynamics::Math::SpatialVector h = this->X_lambda[i].applyTranspose (this->hc[i]); if (this->lambda[i] != 0) { unsigned int j(i); do { j = this->lambda[j]; h = this->X_lambda[j].applyTranspose (h); } while (this->lambda[j]!=0); } h = X_to_COM.applyAdjoint (h); h_segment.push_back(RigidBodyDynamics::Math::Vector3d(h[0],h[1],h[2])); } return h_segment; } void biorbd::rigidbody::Joints::ForwardDynamicsContactsLagrangian ( const RigidBodyDynamics::Math::VectorNd &Q, const RigidBodyDynamics::Math::VectorNd &QDot, const RigidBodyDynamics::Math::VectorNd &GeneralizedTorque, RigidBodyDynamics::ConstraintSet &CS, RigidBodyDynamics::Math::VectorNd &QDDot ) { // Compute C CS.QDDot_0.setZero(); RigidBodyDynamics::InverseDynamics (*this, Q, QDot, CS.QDDot_0, CS.C); // Compute H CS.H = RigidBodyDynamics::Math::MatrixNd::Zero(this->dof_count, this->dof_count); RigidBodyDynamics::CompositeRigidBodyAlgorithm (*this, Q, CS.H, false); // Compute G unsigned int i,j; // variables to check whether we need to recompute G unsigned int prev_body_id = 0; RigidBodyDynamics::Math::Vector3d prev_body_point = RigidBodyDynamics::Math::Vector3d::Zero(); RigidBodyDynamics::Math::MatrixNd Gi (RigidBodyDynamics::Math::MatrixNd::Zero(3, this->dof_count)); for (i = 0; i < CS.size(); i++) { // Only alow contact normals along the coordinate axes // unsigned int axis_index = 0; // only compute the matrix Gi if actually needed if (prev_body_id != CS.body[i] || prev_body_point != CS.point[i]) { RigidBodyDynamics::CalcPointJacobian (*this, Q, CS.body[i], CS.point[i], Gi, false); prev_body_id = CS.body[i]; prev_body_point = CS.point[i]; } for (j = 0; j < this->dof_count; j++) { RigidBodyDynamics::Math::Vector3d gaxis (Gi(0,j), Gi(1,j), Gi(2,j)); CS.G(i,j) = gaxis.transpose() * CS.normal[i]; // CS.G(i,j) = Gi(axis_index, j); } } // Compute gamma prev_body_id = 0; prev_body_point = RigidBodyDynamics::Math::Vector3d::Zero(); RigidBodyDynamics::Math::Vector3d gamma_i = RigidBodyDynamics::Math::Vector3d::Zero(); // update Kinematics just once UpdateKinematics (*this, Q, QDot, CS.QDDot_0); for (i = 0; i < CS.size(); i++) { // Only alow contact normals along the coordinate axes unsigned int axis_index = 0; if (CS.normal[i] == RigidBodyDynamics::Math::Vector3d(1., 0., 0.)) axis_index = 0; else if (CS.normal[i] == RigidBodyDynamics::Math::Vector3d(0., 1., 0.)) axis_index = 1; else if (CS.normal[i] == RigidBodyDynamics::Math::Vector3d(0., 0., 1.)) axis_index = 2; else biorbd::utils::Error::raise("Invalid contact normal axis!"); // only compute point accelerations when necessary if (prev_body_id != CS.body[i] || prev_body_point != CS.point[i]) { gamma_i = CalcPointAcceleration (*this, Q, QDot, CS.QDDot_0, CS.body[i], CS.point[i], false); prev_body_id = CS.body[i]; prev_body_point = CS.point[i]; } // we also substract ContactData[i].acceleration such that the contact // point will have the desired acceleration CS.gamma[i] = gamma_i[axis_index] - CS.acceleration[i]; } // Build the system CS.A.setZero(); CS.b.setZero(); CS.x.setZero(); // Build the system: Copy H for (i = 0; i < this->dof_count; i++) { for (j = 0; j < this->dof_count; j++) { CS.A(i,j) = CS.H(i,j); } } // Build the system: Copy G, and G^T for (i = 0; i < CS.size(); i++) { for (j = 0; j < this->dof_count; j++) { CS.A(i + this->dof_count, j) = CS.G (i,j); CS.A(j, i + this->dof_count) = CS.G (i,j); } } // Build the system: Copy -C + \GeneralizedTorque for (i = 0; i < this->dof_count; i++) { CS.b[i] = -CS.C[i] + GeneralizedTorque[i]; } // Build the system: Copy -gamma for (i = 0; i < CS.size(); i++) { CS.b[i + this->dof_count] = - CS.gamma[i]; } // std::cout << "A = " << std::endl << CS.A << std::endl; //std::cout << "b = " << std::endl << CS.b << std::endl; switch (CS.linear_solver) { case (RigidBodyDynamics::Math::LinearSolverPartialPivLU) : CS.x = CS.A.partialPivLu().solve(CS.b); break; case (RigidBodyDynamics::Math::LinearSolverColPivHouseholderQR) : CS.x = CS.A.colPivHouseholderQr().solve(CS.b); break; default: #ifdef RBDL_ENABLE_LOGGING LOG << "Error: Invalid linear solver: " << CS.linear_solver << std::endl; #endif biorbd::utils::Error::raise("Error: Invalid linear solver"); break; } //std::cout << "x = " << std::endl << CS.x << std::endl; // Copy back QDDot for (i = 0; i < this->dof_count; i++) QDDot[i] = CS.x[i]; // Copy back contact forces for (i = 0; i < CS.size(); i++) { CS.force[i] = -CS.x[this->dof_count + i]; } } unsigned int biorbd::rigidbody::Joints::nbQuat() const{ return *m_nRotAQuat; } void biorbd::rigidbody::Joints::computeQdot( const biorbd::rigidbody::GeneralizedCoordinates &Q, const biorbd::rigidbody::GeneralizedCoordinates &QDot, biorbd::rigidbody::GeneralizedCoordinates &QDotOut) { // Vérifier s'il y a des quaternions, sinon la dérivée est directement QDot if (!m_nRotAQuat){ QDotOut = QDot; return; } QDotOut.resize(Q.size()); // Créer un vecteur vide de la dimension finale. unsigned int cmpQuat(0); unsigned int cmpDof(0); for (unsigned int i=0; i<nbBone(); ++i){ biorbd::rigidbody::Bone bone_i=bone(i); if (bone_i.isRotationAQuaternion()){ // Extraire le quaternion biorbd::utils::Quaternion quat_tp(Q.block(cmpDof+bone_i.nDofTrans(), 0, 3, 1), Q(Q.size()-*m_nRotAQuat+cmpQuat)); // Placer dans le vecteur de sortie QDotOut.block(cmpDof, 0, bone_i.nDofTrans(), 1) = QDot.block(cmpDof, 0, bone_i.nDofTrans(), 1); // La dérivée des translations est celle directement de qdot // Dériver quat_tp.derivate(QDot.block(cmpDof+bone_i.nDofTrans(), 0, 3, 1)); QDotOut.block(cmpDof+bone_i.nDofTrans(), 0, 3, 1) = quat_tp.block(0,0,3,1); QDotOut(Q.size()-*m_nRotAQuat+cmpQuat) = quat_tp(3);// Placer dans le vecteur de sortie // Incrémenter le nombre de quaternions faits ++cmpQuat; } else{ // Si c'est un normal, faire ce qu'il est fait d'habitude QDotOut.block(cmpDof, 0, bone_i.nDof(), 1) = QDot.block(cmpDof, 0, bone_i.nDof(), 1); } cmpDof += bone_i.nDof(); } } unsigned int biorbd::rigidbody::Joints::getDofIndex( const biorbd::utils::String& boneName, const biorbd::utils::String& dofName) { unsigned int idx = 0; unsigned int iB = 0; bool found = false; while (1){ biorbd::utils::Error::check(iB!=m_bones->size(), "Bone not found"); if (boneName.compare( (*m_bones)[iB].name() ) ) idx += (*m_bones)[iB].nDof(); else{ idx += (*m_bones)[iB].getDofIdx(dofName); found = true; break; } ++iB; } biorbd::utils::Error::check(found, "Dof not found"); return idx; } void biorbd::rigidbody::Joints::UpdateKinematicsCustom( const biorbd::rigidbody::GeneralizedCoordinates *Q, const biorbd::rigidbody::GeneralizedCoordinates *Qdot, const biorbd::rigidbody::GeneralizedCoordinates *Qddot) { RigidBodyDynamics::UpdateKinematicsCustom(*this, Q, Qdot, Qddot); } void biorbd::rigidbody::Joints::CalcMatRotJacobian( const RigidBodyDynamics::Math::VectorNd &Q, unsigned int body_id, const RigidBodyDynamics::Math::Matrix3d &rotation, RigidBodyDynamics::Math::MatrixNd &G, bool update_kinematics) { #ifdef RBDL_ENABLE_LOGGING LOG << "-------- " << __func__ << " --------" << std::endl; #endif // update the Kinematics if necessary if (update_kinematics) { RigidBodyDynamics::UpdateKinematicsCustom (*this, &Q, nullptr, nullptr); } assert (G.rows() == 9 && G.cols() == this->qdot_size ); std::vector<biorbd::utils::Node3d> axes; axes.push_back(biorbd::utils::Node3d(1,0,0)); axes.push_back(biorbd::utils::Node3d(0,1,0)); axes.push_back(biorbd::utils::Node3d(0,0,1)); for (unsigned int iAxes=0; iAxes<3; ++iAxes){ RigidBodyDynamics::Math::Matrix3d bodyMatRot ( RigidBodyDynamics::CalcBodyWorldOrientation (*this, Q, body_id, false).transpose()); RigidBodyDynamics::Math::SpatialTransform point_trans( RigidBodyDynamics::Math::SpatialTransform ( RigidBodyDynamics::Math::Matrix3d::Identity(), bodyMatRot * rotation * *(axes.begin()+iAxes))); unsigned int reference_body_id = body_id; if (this->IsFixedBodyId(body_id)) { unsigned int fbody_id = body_id - this->fixed_body_discriminator; reference_body_id = this->mFixedBodies[fbody_id].mMovableParent; } unsigned int j = reference_body_id; // e[j] is set to 1 if joint j contributes to the jacobian that we are // computing. For all other joints the column will be zero. while (j != 0) { unsigned int q_index = this->mJoints[j].q_index; // Si ce n'est pas un dof en translation (3 4 5 dans this->S) if (this->S[j](3)!=1.0 && this->S[j](4)!=1.0 && this->S[j](5)!=1.0) { RigidBodyDynamics::Math::SpatialTransform X_base = this->X_base[j]; X_base.r << 0,0,0; // Retirer tout concept de translation (ne garder que la matrice rotation) if (this->mJoints[j].mDoFCount == 3) { G.block(iAxes*3, q_index, 3, 3) = ((point_trans * X_base.inverse()).toMatrix() * this->multdof3_S[j]).block(3,0,3,3); } else { G.block(iAxes*3,q_index, 3, 1) = point_trans.apply(X_base.inverse().apply(this->S[j])).block(3,0,3,1); } } j = this->lambda[j]; // Passer au segment parent } } }
37.56685
168
0.66509
[ "mesh", "vector", "model" ]
c0b33e060f14973a946827aa4c50e6f9c9d95b77
1,982
hh
C++
src/engine/Constant.hh
weatherhead99/symdiff
ba21034fcffcc0fb84e1922549bb969f556c7741
[ "Apache-2.0" ]
8
2016-06-02T17:07:44.000Z
2021-03-13T16:21:54.000Z
src/engine/Constant.hh
weatherhead99/symdiff
ba21034fcffcc0fb84e1922549bb969f556c7741
[ "Apache-2.0" ]
4
2018-03-04T20:32:01.000Z
2020-01-15T15:42:41.000Z
src/engine/Constant.hh
devsim/symdiff
1f25961214c25c5142279ec771db3c378637c950
[ "Apache-2.0" ]
7
2015-10-28T17:24:05.000Z
2021-03-13T16:22:01.000Z
/*** Copyright 2012 Devsim LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ***/ #ifndef CONSTANT_HH #define CONSTANT_HH #include "EquationObject.hh" namespace Eqo { class Constant : public EquationObject { public: Constant(double); ~Constant() {}; EqObjPtr Derivative(EqObjPtr); EqObjPtr Simplify(); EqObjPtr CombineProduct(std::vector<EqObjPtr>); EqObjPtr CombineAdd(std::vector<EqObjPtr>); bool isZero(); bool isOne(); EqObjPtr getScale(); EqObjPtr getUnscaledValue(); double getSign(); EqObjPtr getUnsignedValue(); EqObjPtr clone(); EqObjPtr subst(const std::string &, EqObjPtr); EqObjPtr expand(); bool hasReciprocal() { return !(this->isZero()); } EqObjPtr getReciprocal(); double getDoubleValue() { return dvalue; } std::set<std::string> getReferencedType(Eqo::EqObjType rt) { return CreateSetIfThisType(rt); } friend class Pow; friend class Product; std::vector<EqObjPtr> getArgs() { return std::vector<EqObjPtr>(); } std::string getName() const { return EquationObject::stringValue(); } private: std::string createStringValue() const; Constant(const Constant &); Constant operator=(const Constant &); const double dvalue; }; } #endif
23.317647
72
0.62664
[ "vector" ]
c0b4a452aefa78f7b0539a0f0fbe29cadae92111
14,079
hpp
C++
include/future/dense.hpp
YuanL12/BATS
35a32facc87e17649b7fc32225c8ffaf0301bbfa
[ "MIT" ]
5
2020-04-24T17:34:54.000Z
2021-04-07T15:56:00.000Z
include/future/dense.hpp
YuanL12/BATS
35a32facc87e17649b7fc32225c8ffaf0301bbfa
[ "MIT" ]
5
2021-05-13T14:16:35.000Z
2021-08-15T15:11:55.000Z
include/future/dense.hpp
YuanL12/BATS
35a32facc87e17649b7fc32225c8ffaf0301bbfa
[ "MIT" ]
1
2021-05-09T12:17:30.000Z
2021-05-09T12:17:30.000Z
#pragma once /* Dense row matrix implementation */ #include <string> #include <iostream> #include <utility> #include <iterator> #include <algorithm> #include <vector> namespace bats { namespace future { // forward declarations template <typename T> class Matrix; template <typename T, typename I1, typename I2> class MatrixView; template <typename M1, typename M2> auto gemm(const M1& A, const M2& B); template <typename MT, typename VT> auto gemv(const MT& A, const VT& x); /* A strided iterator type */ template <typename T> class strided_iterator : public std::iterator<std::random_access_iterator_tag, T> { typedef ssize_t difference_type; typedef T value_type; typedef T& reference; typedef T* pointer; typedef std::random_access_iterator_tag iterator_category; typedef strided_iterator<T> iterator; pointer pos_; ssize_t stride_; public: strided_iterator() : pos_(nullptr), stride_(0) {} strided_iterator(T* v, ssize_t s) : pos_(v), stride_(s) {} ~strided_iterator() {} iterator operator++(int) { return iterator(pos_+=stride_, stride_); } // postfix iterator& operator++() {pos_+=stride_; return *this; } // prefix iterator operator--(int) {return iterator(pos_-=stride_, stride_); } // postfix iterator& operator--() {pos_-=stride_; return *this; } // prefix reference operator*() const { return *pos_; } pointer operator->() const { return pos_; } bool operator==(const iterator& rhs) const { return pos_ == rhs.pos_; } bool operator!=(const iterator& rhs) const {return pos_ != rhs.pos_; } iterator operator+(size_t i) const {return iterator(pos_ + stride_*i, stride_);} reference operator[](size_t i) const {return *(pos_ + stride_*i); } // TODO: more operators }; template <typename T> class const_strided_iterator : public std::iterator<std::random_access_iterator_tag, T> { typedef ssize_t difference_type; typedef T value_type; typedef const T& reference; typedef const T* pointer; typedef std::random_access_iterator_tag iterator_category; typedef const_strided_iterator<T> iterator; pointer pos_; ssize_t stride_; public: const_strided_iterator() : pos_(nullptr), stride_(0) {} const_strided_iterator(const T* v, ssize_t s) : pos_(v), stride_(s) {} ~const_strided_iterator() {} iterator operator++(int) { return iterator(pos_+=stride_, stride_); } // postfix iterator& operator++() {pos_+=stride_; return *this; } // prefix iterator operator--(int) {return iterator(pos_-=stride_, stride_); } // postfix iterator& operator--() {pos_-=stride_; return *this; } // prefix reference operator*() const { return *pos_; } pointer operator->() const { return pos_; } bool operator==(const iterator& rhs) const { return pos_ == rhs.pos_; } bool operator!=(const iterator& rhs) const {return pos_ != rhs.pos_; } iterator operator+(size_t i) const {return iterator(pos_ + stride_*i, stride_);} reference operator[](size_t i) const {return *(pos_ + stride_*i); } // TODO: more operators }; template <typename T> class range { private: T begin_; T end_; T stride_; public: range() : begin_(0), end_(0), stride_(0) {} range(T b, T e) : begin_(b), end_(e), stride_(1) { if (e < b) { begin_ = e; end_ = b; stride_ = T(-1); } } range(T b, T e, T s) : begin_(b), end_(e), stride_(s) {} T first() const { return begin_; } T last() const { return end_; } T stride() const { return stride_; } size_t size() const { return (end_ - begin_) / stride_; } T operator[](size_t i) const { return begin_ + i * stride_; } // TODO: iterator types for class class const_iterator : public std::iterator<std::random_access_iterator_tag, T> { typedef ssize_t difference_type; typedef T value_type; typedef const T& reference; typedef const T* pointer; typedef std::random_access_iterator_tag iterator_category; typedef const_iterator iterator; T val_; T stride_; // TODO: should implement this using a count to avoid floating point issues public: const_iterator() : val_(0), stride_(0) {} const_iterator(const T v, const T s) : val_(v), stride_(s) {} ~const_iterator() {} iterator operator++(int) { return iterator(val_+=stride_, stride_); } // postfix iterator& operator++() {val_+=stride_; return *this; } // prefix iterator operator--(int) {return iterator(val_-=stride_, stride_); } // postfix iterator& operator--() {val_-=stride_; return *this; } // prefix reference operator*() const { return val_; } pointer operator->() const { return &val_; } bool operator==(const iterator& rhs) const { return val_ == rhs.val_; } bool operator!=(const iterator& rhs) const {return val_ != rhs.val_; } // TODO: more operators }; typedef const_iterator iterator; // only use const iterator type const_iterator const begin() { return iterator(begin_, stride_); } const_iterator const end() { return iterator(end_, stride_); } const_iterator const cbegin() { return iterator(begin_, stride_); } const_iterator const cend() { return iterator(end_, stride_); } }; // view type - doesn't own data template <typename T> class VectorView { private: T* start_; T* end_; size_t stride_; public: typedef strided_iterator<T> iterator; typedef const_strided_iterator<T> const_iterator; VectorView(T* s, T* e, size_t stride) : \ start_(s), end_(e), stride_(stride) {} iterator begin() { return iterator(start_, stride_); } iterator end() { return iterator(end_ , stride_); } const_iterator begin() const { return const_iterator(start_, stride_); } const_iterator end() const { return const_iterator(end_, stride_); } const_iterator cbegin() const { return const_iterator(start_, stride_); } const_iterator cend() const { return const_iterator(end_, stride_); } T& operator[](size_t i) {return begin()[i];} const T& operator[](size_t i) const {return cbegin()[i];} void print() const { T* it = start_; while (it != end_) { std::cout << *it << ' '; it += stride_; } std::cout << std::endl; } void axpy(T a, const VectorView &other) { auto it1 = begin(); auto it2 = other.begin(); while (it1 != end()) { *it1++ += a * (*it2++); } } void axpy(T a, const VectorView &&other) { auto it1 = begin(); auto it2 = other.begin(); while (it1 != end()) { *it1++ += a * (*it2++); } } void scale(T a) { auto it = begin(); while (it != end()) { *it++ *= a; } } }; struct RowMajor {}; struct ColumnMajor {}; // template over type template <typename T> class Matrix { private: std::vector<T> data_; size_t dim[2]; // dimensions size_t stride[2]; // strides public: typedef T value_type; size_t len() const { return dim[0]*dim[1]; } void fill(T a) { std::fill(data_.begin(), data_.end(), a); } // empty constructor Matrix() : data_(), dim{0,0}, stride{0,0} {} // construct empty row major matrix Matrix(size_t m, size_t n, RowMajor) : dim{m,n}, stride{n,1} { data_ = std::vector<T>(len()); } Matrix(size_t m, size_t n, ColumnMajor) : dim{m,n}, stride{1,m} { data_ = std::vector<T>(len()); } // construct an empty matrix Matrix(size_t m, size_t n) : dim{m, n}, stride{n, 1} { data_ = std::vector<T>(len()); } // construct a matrix with a fill value a Matrix(size_t m, size_t n, T a) : Matrix(m, n) { fill(a); } template <typename Major> Matrix(size_t m, size_t n, T a, Major &ms): Matrix(m, n, ms) { fill(a); } Matrix(Matrix& other, ColumnMajor) : Matrix(other.dim[0], other.dim[1], ColumnMajor()) { for (size_t j = 0; j < dim[1]; j++) { for (size_t i = 0; i < dim[0]; i++) { operator()(i,j) = other(i,j); } } } T* data() { return data_.data(); } const T* data() const {return data_.data();} inline size_t nrow() const {return dim[0];} inline size_t ncol() const {return dim[1];} inline std::pair<size_t, size_t> dims() const { return std::make_pair(dim[0], dim[1]); } // access data inline T operator[](size_t k) const { return data_[k]; } inline T& operator[](size_t k) { return data_[k]; } inline T operator()(size_t k) const { return data_[k]; } inline T& operator()(size_t k) { return data_[k]; } template <typename I1, typename I2> inline MatrixView<T, I1, I2> view(I1 &rows, I2 &cols) {return MatrixView(this, rows, cols);} template <typename I1, typename I2> inline MatrixView<T, I1, I2> view(I1 &&rows, I2 &&cols) {return MatrixView(this, rows, cols);} // template <typename I1, typename I2> // inline MatrixView<T, I1, I2> operator()(I1 &rows, I2 &cols) {return view(rows, cols);} template <typename I1, typename I2> inline const MatrixView<T, I1, I2> view(I1 &rows, I2 &cols) const {return MatrixView(this, rows, cols);} template <typename I1, typename I2> inline const MatrixView<T, I1, I2> view(I1 &&rows, I2 &&cols) const {return MatrixView(this, rows, cols);} // template <typename I1, typename I2> // inline const MatrixView<T, I1, I2> operator()(I1 &rows, I2 &cols) const {return view(rows, cols);} // template <typename I1, typename I2> // inline const MatrixView<T, I1, I2> operator()(I1 &&rows, I2 &&cols) const {return view(rows, cols);} inline T operator()(size_t i, size_t j) const { return data_[stride[0]*i + stride[1]*j]; } inline T& operator()(size_t i, size_t j) { return data_[stride[0]*i + stride[1]*j]; } inline VectorView<T> row(size_t i) {return VectorView(data() + stride[0]*i, data() + stride[0]*i + stride[1]*dim[1], stride[1]);} inline VectorView<T> column(size_t j) {return VectorView(data() + stride[1]*j, data() + stride[1]*j + stride[0]*dim[0], stride[0]);} void print_info() const { std::cout << "[" << this << "] : " << nrow() << " x " << ncol() <<\ " Matrix" << std::endl; } void print() const { print_info(); for (size_t i = 0; i < nrow(); i++) { for (size_t j = 0; j < ncol(); j++) { std::cout << operator()(i, j) << ' '; } std::cout << std::endl; } } Matrix transpose() const { Matrix At(ncol(), nrow()); for (size_t i = 0; i < nrow(); i++) { for (size_t j = 0; j < ncol(); j++) { At(j,i) = operator()(i,j); } } return At; } // elementary operations // swap rows of the matrix void swap_rows(size_t i1, size_t i2) { if (i1 == i2) {return;} for (size_t j = 0; j < ncol(); j++) { std::swap(operator()(i1,j), operator()(i2, j)); } } void swap_columns(size_t j1, size_t j2) { if (j1 == j2) {return;} for (size_t i = 0; i < nrow(); i++) { std::swap(operator()(i,j1), operator()(i, j2)); } } // append column - return true if successful. bool append_column(const T val=T(0)) { if (stride[1] == dim[0]) { // column major - just need to resize dim[1]++; data_.resize(len(), val); return true; } // TODO: implement row-major return false; } bool delete_column() { if (stride[1] == dim[0]) { // column major - just need to resize dim[1]--; data_.resize(len()); return true; } // TODO: implement row-major return false; } // add a*row(i1) to row(i0) void add_row(T a, size_t i1, size_t i0) { row(i0).axpy(a, row(i1)); } inline void add_row(size_t i1, size_t i0) { return add_row(T(1), i1, i0); } // add a * column(i1) to column(i0) void add_column(T a, size_t j1, size_t j0) { column(j0).axpy(a, column(j1)); } inline void add_column(size_t j1, size_t j0) {return add_column(T(1), j1, j0); } void scale_row(T a, size_t i) { row(i).scale(a); } void scale_column(T a, size_t j) { column(j).scale(a); } // matrix-matrix multiplication template <typename TB> inline auto mm(const TB &B) const { return gemm(*this, B); } template <typename TB> inline Matrix operator*(const TB &B) const { return mm(B); } // matrix-vector multiplication template <typename Tx> inline auto mv(const Tx &x) const { return gemv(*this, x); } static Matrix identity(size_t n) { Matrix A(n, n, T(0)); for (size_t k = 0; k < n; k++) { A(k,k) = T(1); } return A; } }; // matrix-matrix multiplication template <typename M1, typename M2> auto gemm(const M1& A, const M2& B) { using T = typename M1::value_type; // TODO: static assert on value types // C = A * B size_t Cm = A.nrow(); size_t Cn = B.ncol(); Matrix C(Cm, Cn, T(0)); for (size_t i = 0; i < Cm; i++) { for (size_t j = 0; j < Cn; j++) { for (size_t k = 0; k < A.ncol(); k++) { C(i,j) += A(i,k) * B(k,j); } } } return C; } // matrix-vector multiplication // y <- A * x template <typename MT, typename VT1, typename VT2> VT2& gemv(const MT& A, const VT1& x, VT2&& y) { // clear y for (size_t i = 0; i < A.nrow(); i++) { y[i] = 0; } // perform matvec for (size_t j = 0; j < A.ncol(); j++) { for (size_t i = 0; i < A.nrow(); i++) { y[i] += A(i,j) * x[j]; } } return y; } // matrix-vector multiplication template <typename MT, typename VT> auto gemv(const MT& A, const VT& x) { using T = typename MT::value_type; // TODO: static assert on value types // C = A * B size_t Cm = A.nrow(); Matrix y(Cm, 1, T(0)); return gemv(A, x, y); } // another view type // template over types used to iterate over rows and columns. template <typename T, typename I1, typename I2> class MatrixView { private: Matrix<T>* data; I1 rows; I2 cols; public: typedef T val_type; MatrixView() : data(nullptr) {} // need to make copies of r and c anyways MatrixView(Matrix<T>* m, I1 r, I2 c) : data(m) { rows = std::move(r); cols = std::move(c); } MatrixView(Matrix<T>& m, I1 r, I2 c) : data(&m) { rows = std::move(r); cols = std::move(c); } inline T operator()(size_t i, size_t j) const { return data->operator()(rows[i], cols[j]); } inline T& operator()(size_t i, size_t j) { return data->operator()(rows[i], cols[j]); } inline size_t nrow() const { return rows.size(); } inline size_t ncol() const { return cols.size(); } void print_info() const { std::cout << "[" << this << "] : " << nrow() << " x " << ncol() <<\ " MatrixView of [" << data << "]" << std::endl; } void print() const { print_info(); for (size_t i = 0; i < nrow(); i++) { for (size_t j = 0; j < ncol(); j++) { std::cout << operator()(i, j) << ' '; } std::cout << std::endl; } } }; } }
26.514124
133
0.63719
[ "vector" ]
c0bf1510433720e43655199d34d586ecf05f4219
3,002
cpp
C++
Game Theory/Matching Game On A Graph.cpp
bazzyadb/all-code
cf3039641b5aa84b1c5b184a95d69bd4091974c9
[ "MIT" ]
1,639
2021-09-15T09:12:06.000Z
2022-03-31T22:58:57.000Z
Game Theory/Matching Game On A Graph.cpp
bazzyadb/all-code
cf3039641b5aa84b1c5b184a95d69bd4091974c9
[ "MIT" ]
16
2022-01-15T17:50:08.000Z
2022-01-28T12:55:21.000Z
Game Theory/Matching Game On A Graph.cpp
bazzyadb/all-code
cf3039641b5aa84b1c5b184a95d69bd4091974c9
[ "MIT" ]
444
2021-09-15T09:17:41.000Z
2022-03-29T18:21:46.000Z
#include<bits/stdc++.h> using namespace std; const int N = 2e3 + 9; mt19937 rnd(chrono::steady_clock::now().time_since_epoch().count()); struct Blossom { int vis[N], par[N], orig[N], match[N], aux[N], t; int n; bool ad[N]; vector<int> g[N]; queue<int> Q; Blossom() {} Blossom(int _n) { n = _n; t = 0; for (int i = 0; i <= _n; ++i) { g[i].clear(); match[i] = aux[i] = par[i] = vis[i] = aux[i] = ad[i] = orig[i] = 0; } } void add_edge(int u, int v) { g[u].push_back(v); g[v].push_back(u); } void augment(int u, int v) { int pv = v, nv; do { pv = par[v]; nv = match[pv]; match[v] = pv; match[pv] = v; v = nv; } while (u != pv); } int lca(int v, int w) { ++t; while (true) { if (v) { if (aux[v] == t) return v; aux[v] = t; v = orig[par[match[v]]]; } swap(v, w); } } void blossom(int v, int w, int a) { while (orig[v] != a) { par[v] = w; w = match[v]; ad[v] = true; if (vis[w] == 1) Q.push(w), vis[w] = 0; orig[v] = orig[w] = a; v = par[w]; } } //it finds an augmented path starting from u bool bfs(int u) { fill(vis + 1, vis + n + 1, -1); iota(orig + 1, orig + n + 1, 1); Q = queue<int> (); Q.push(u); vis[u] = 0; while (!Q.empty()) { int v = Q.front(); Q.pop(); ad[v] = true; for (int x : g[v]) { if (vis[x] == -1) { par[x] = v; vis[x] = 1; if (!match[x]) return augment(u, x), true; Q.push(match[x]); vis[match[x]] = 0; } else if (vis[x] == 0 && orig[v] != orig[x]) { int a = lca(orig[v], orig[x]); blossom(x, v, a); blossom(v, x, a); } } } return false; } int maximum_matching() { int ans = 0; vector<int> p(n - 1); iota(p.begin(), p.end(), 1); shuffle(p.begin(), p.end(), rnd); for (int i = 1; i <= n; i++) shuffle(g[i].begin(), g[i].end(), rnd); for (auto u : p) { if (!match[u]) { for(auto v : g[u]) { if (!match[v]) { match[u] = v, match[v] = u; ++ans; break; } } } } for(int i = 1; i <= n; ++i) if (!match[i] && bfs(i)) ++ans; return ans; } } M; int32_t main() { ios_base::sync_with_stdio(0); cin.tie(0); int t; cin >> t; while (t--) { int n, m; cin >> n >> m; M = Blossom (n); while (m--) { int u, v; cin >> u >> v; M.add_edge(u, v); } int ans = M.maximum_matching(); if (ans * 2 == n) cout << 0 << '\n'; else { memset(M.ad, 0, sizeof M.ad); for (int i = 1; i <= n; i++) if (M.match[i] == 0) M.bfs(i); int ans = 0; for (int i = 1; i <= n; i++) ans += M.ad[i]; //nodes which are unmatched in some maximum matching cout << ans << '\n'; } } return 0; } //https://www.codechef.com/problems/HAMILG
22.742424
103
0.427715
[ "vector" ]
c0c073825c0534d09f2c3c72bcb7b264e0c4d458
3,086
cc
C++
common/cpp/src/google_smart_card_common/logging/function_call_tracer.cc
SM-125F/chromeos_smart_card_connector
b375f282d3dbf92318a3321c580715f3ca68d793
[ "Apache-2.0" ]
79
2017-09-22T05:09:54.000Z
2022-03-13T01:11:06.000Z
common/cpp/src/google_smart_card_common/logging/function_call_tracer.cc
QPC-database/chromeos_smart_card_connector
3ced08b30ce3f2a557487c3bfba1d1cd36c5011c
[ "Apache-2.0" ]
191
2017-10-23T22:34:58.000Z
2022-03-05T18:10:06.000Z
common/cpp/src/google_smart_card_common/logging/function_call_tracer.cc
QPC-database/chromeos_smart_card_connector
3ced08b30ce3f2a557487c3bfba1d1cd36c5011c
[ "Apache-2.0" ]
32
2017-10-21T07:39:59.000Z
2021-11-10T22:55:32.000Z
// Copyright 2016 Google Inc. 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 <google_smart_card_common/logging/function_call_tracer.h> #include <stdint.h> #include <atomic> namespace google_smart_card { namespace { int64_t GenerateFunctionCallId() { static std::atomic<int64_t> next_function_call_id(0); return ++next_function_call_id; } } // namespace FunctionCallTracer::FunctionCallTracer(const std::string& function_name, const std::string& logging_prefix, LogSeverity log_severity) : function_call_id_(GenerateFunctionCallId()), function_name_(function_name), logging_prefix_(logging_prefix), log_severity_(log_severity) {} FunctionCallTracer::~FunctionCallTracer() = default; void FunctionCallTracer::AddPassedArg(const std::string& name, const std::string& dumped_value) { passed_args_.emplace_back(name, dumped_value); } void FunctionCallTracer::AddReturnValue(const std::string& dumped_value) { GOOGLE_SMART_CARD_CHECK(!dumped_return_value_); dumped_return_value_ = dumped_value; } void FunctionCallTracer::AddReturnedArg(const std::string& name, const std::string& dumped_value) { returned_args_.emplace_back(name, dumped_value); } void FunctionCallTracer::LogEntrance() const { GOOGLE_SMART_CARD_LOG(log_severity_) << logging_prefix_ << function_name_ << "#" << function_call_id_ << "(" << DumpArgs(passed_args_) << "): called..."; } void FunctionCallTracer::LogExit() const { std::string results_part; if (dumped_return_value_) results_part = *dumped_return_value_; if (!returned_args_.empty()) { if (!results_part.empty()) results_part += ", "; results_part += DumpArgs(returned_args_); } GOOGLE_SMART_CARD_LOG(log_severity_) << logging_prefix_ << function_name_ << "#" << function_call_id_ << ": returning" << (results_part.empty() ? "" : " ") << results_part; } FunctionCallTracer::ArgNameWithValue::ArgNameWithValue( const std::string& name, const std::string& dumped_value) : name(name), dumped_value(dumped_value) {} // static std::string FunctionCallTracer::DumpArgs( const std::vector<ArgNameWithValue>& args) { std::string result; for (const auto& arg : args) { if (!result.empty()) result += ", "; result += arg.name; result += "="; result += arg.dumped_value; } return result; } } // namespace google_smart_card
31.489796
77
0.689566
[ "vector" ]
c0c47e9ec9661653daa77533e76d084100d82ee9
925
hpp
C++
tests/test.hpp
eoseoul/eos-tapsonic-wc-vr
2c3030c7df2f27406371d1251bf0fccba23e0681
[ "MIT" ]
null
null
null
tests/test.hpp
eoseoul/eos-tapsonic-wc-vr
2c3030c7df2f27406371d1251bf0fccba23e0681
[ "MIT" ]
null
null
null
tests/test.hpp
eoseoul/eos-tapsonic-wc-vr
2c3030c7df2f27406371d1251bf0fccba23e0681
[ "MIT" ]
null
null
null
#include <boost/test/unit_test.hpp> #include <eosio/testing/tester.hpp> #include <eosio/chain/abi_serializer.hpp> #include <eosio/chain/wast_to_wasm.hpp> #include <fc/variant_object.hpp> #include <Runtime/Runtime.h> #include "contracts.hpp" using namespace eosio::testing; using namespace eosio; using namespace eosio::chain; using namespace eosio::testing; using namespace fc; using mvo = fc::mutable_variant_object; struct musicscore_t { uint16_t music_id; uint32_t score; bool operator == (const musicscore_t& rhs) { if (this->music_id == rhs.music_id) return true; return false; } }; FC_REFLECT( musicscore_t, (music_id)(score) ); struct record_t { name owner; vector<musicscore_t> scores; uint64_t timestamp; uint64_t reserve_1; uint64_t primary_key() const { return owner.value; } }; FC_REFLECT( record_t, (owner)(scores)(timestamp)(reserve_1) );
23.125
62
0.713514
[ "vector" ]
c0c61968baeb54a5dd4b725238b3ef3aeb8ce1f2
5,614
hpp
C++
blast/include/algo/blast/api/traceback_stage.hpp
mycolab/ncbi-blast
e59746cec78044d2bf6d65de644717c42f80b098
[ "Apache-2.0" ]
null
null
null
blast/include/algo/blast/api/traceback_stage.hpp
mycolab/ncbi-blast
e59746cec78044d2bf6d65de644717c42f80b098
[ "Apache-2.0" ]
null
null
null
blast/include/algo/blast/api/traceback_stage.hpp
mycolab/ncbi-blast
e59746cec78044d2bf6d65de644717c42f80b098
[ "Apache-2.0" ]
null
null
null
/* $Id: traceback_stage.hpp 457458 2015-01-23 12:27:33Z madden $ * =========================================================================== * * PUBLIC DOMAIN NOTICE * National Center for Biotechnology Information * * This software/database is a "United States Government Work" under the * terms of the United States Copyright Act. It was written as part of * the author's official duties as a United States Government employee and * thus cannot be copyrighted. This software/database is freely available * to the public for use. The National Library of Medicine and the U.S. * Government have not placed any restriction on its use or reproduction. * * Although all reasonable efforts have been taken to ensure the accuracy * and reliability of the software and data, the NLM and the U.S. * Government do not and cannot warrant the performance or results that * may be obtained by using this software or data. The NLM and the U.S. * Government disclaim all warranties, express or implied, including * warranties of performance, merchantability or fitness for any particular * purpose. * * Please cite the author in any work or product based on this material. * * =========================================================================== * * Author: Christiam Camacho, Kevin Bealer * */ /** @file traceback_stage.hpp * NOTE: This file contains work in progress and the APIs are likely to change, * please do not rely on them until this notice is removed. */ #ifndef ALGO_BLAST_API___TRACEBACK_STAGE_HPP #define ALGO_BLAST_API___TRACEBACK_STAGE_HPP #include <algo/blast/api/setup_factory.hpp> #include <algo/blast/api/query_data.hpp> #include <algo/blast/api/uniform_search.hpp> #include <objtools/blast/seqdb_reader/seqdb.hpp> #include <objects/scoremat/PssmWithParameters.hpp> /** @addtogroup AlgoBlast * * @{ */ BEGIN_NCBI_SCOPE BEGIN_SCOPE(blast) // Forward declaration class IBlastSeqInfoSrc; class NCBI_XBLAST_EXPORT CBlastTracebackSearch : public CObject, public CThreadable { public: /// Create a BlastSeqSrc re-using an already created BlastSeqSrc /// @note We don't own the BlastSeqSrc CBlastTracebackSearch(CRef<IQueryFactory> qf, CRef<CBlastOptions> opts, BlastSeqSrc * seqsrc, CRef<IBlastSeqInfoSrc> seqinfosrc, CRef<TBlastHSPStream> hsps, CConstRef<objects::CPssmWithParameters> pssm = null); /// Use the internal data and return value of the preliminary /// search to proceed with the traceback. CBlastTracebackSearch(CRef<IQueryFactory> query_factory, CRef<SInternalData> internal_data, CRef<CBlastOptions> opts, CRef<IBlastSeqInfoSrc> seqinfosrc, TSearchMessages& search_msgs); /// Destructor. virtual ~CBlastTracebackSearch(); /// Run the traceback search. CRef<CSearchResultSet> Run(); /// Runs the traceback but only returns the HSP's and not the Seq-Align. BlastHSPResults* RunSimple(); /// Specifies how the Seq-align-set returned as part of the /// results is formatted. void SetResultType(EResultType type); /// Sets the m_DBscanInfo field. void SetDBScanInfo(CRef<SDatabaseScanData> dbscan_info); /// Retrieve any error/warning messages that occurred during the search TSearchMessages GetSearchMessages() const; private: /// Common initialization performed when doing traceback only void x_Init(CRef<IQueryFactory> qf, CRef<CBlastOptions> opts, CConstRef<objects::CPssmWithParameters> pssm, const string & dbname, CRef<TBlastHSPStream> hsps); /// Prohibit copy constructor CBlastTracebackSearch(CBlastTracebackSearch &); /// Prohibit assignment operator CBlastTracebackSearch & operator =(CBlastTracebackSearch &); // C++ data /// The query to search for. CRef<IQueryFactory> m_QueryFactory; /// The options with which this search is configured. CRef<CBlastOptions> m_Options; /// Fields and data from the preliminary search. CRef<SInternalData> m_InternalData; /// Options from the preliminary search. const CBlastOptionsMemento* m_OptsMemento; /// Warnings and Errors TSearchMessages m_Messages; /// Pointer to the IBlastSeqInfoSrc object to use to generate the /// Seq-aligns CRef<IBlastSeqInfoSrc> m_SeqInfoSrc; /// Determines if BLAST database search or BLAST 2 sequences style of /// results should be produced EResultType m_ResultType; /// Tracks information from database scanning phase. Right now only used /// for the number of occurrences of a pattern in phiblast run. CRef<SDatabaseScanData> m_DBscanInfo; }; inline TSearchMessages CBlastTracebackSearch::GetSearchMessages() const { return m_Messages; } END_SCOPE(BLAST) END_NCBI_SCOPE /* @} */ #endif /* ALGO_BLAST_API___TRACEBACK_STAGE__HPP */
37.178808
83
0.618988
[ "object" ]
c0da01079ac94a39d726a5dbf98f546589160c0d
2,351
cpp
C++
problemsets/Codejam/2008/ROUND 2 2008/PA/PA.cpp
juarezpaulino/coderemite
a4649d3f3a89d234457032d14a6646b3af339ac1
[ "Apache-2.0" ]
null
null
null
problemsets/Codejam/2008/ROUND 2 2008/PA/PA.cpp
juarezpaulino/coderemite
a4649d3f3a89d234457032d14a6646b3af339ac1
[ "Apache-2.0" ]
null
null
null
problemsets/Codejam/2008/ROUND 2 2008/PA/PA.cpp
juarezpaulino/coderemite
a4649d3f3a89d234457032d14a6646b3af339ac1
[ "Apache-2.0" ]
null
null
null
/** * * Author: Juarez Paulino(coderemite) * Email: juarez.paulino@gmail.com * */ #include <vector> #include <list> #include <map> #include <set> #include <deque> #include <queue> #include <stack> #include <bitset> #include <algorithm> #include <functional> #include <numeric> #include <utility> #include <sstream> #include <iostream> #include <iomanip> #include <cstdio> #include <cmath> #include <cstdlib> #include <cctype> #include <string> #include <cstring> #include <cstdio> #include <cmath> #include <cstdlib> #include <ctime> #include <cassert> using namespace std; #define FOR(i,a,b) for (int i = a; i < b; i++) #define SI(V) (int)V.size() #define PB push_back typedef long long i64; typedef vector<int> VI; const int INF = 0x3F3F3F3F; const double EPS = 1E-14; const int MAXV = 10101; int M, V; int G[MAXV], C[MAXV], I[MAXV]; int DP[MAXV][2]; inline int apply(int a, int b, int op) { return (op) ? (a&b) : (a|b); } int go(int u, int v) { if (u > (M-1)/2) return (v==I[u])?0:INF; int &ret = DP[u][v]; if (ret != -1) return ret; ret = INF; // All possible children combination. FOR(a,0,2) FOR(b,0,2) { if (apply(a,b,G[u])==v) ret = min(ret, go(u*2,a) + go(u*2+1,b)); if (C[u] && apply(a,b,G[u]^1)==v) ret = min(ret, 1 + go(u*2,a) + go(u*2+1,b)); } return ret; } int main() { // freopen("A.in","r",stdin); // freopen("A-small-practice.in","r",stdin);freopen("A-small-practice.out","w",stdout); freopen("A-large-practice.in","r",stdin);freopen("A-large-practice.out","w",stdout); // freopen("A-small-attempt0.in","r",stdin);freopen("A-small-attempt0.out","w",stdout); // freopen("A-small-attempt1.in","r",stdin);freopen("A-small-attempt1.out","w",stdout); // freopen("A-small-attempt2.in","r",stdin);freopen("A-small-attempt2.out","w",stdout); // freopen("A-large.in","r",stdin);freopen("A-large.ans","w",stdout); int TC; scanf("%d", &TC); for (int tc = 1; tc <= TC; tc++) { scanf("%d%d", &M, &V); int i; for (i = 1; i <= (M-1)/2; i++) scanf("%d%d", &G[i], &C[i]); for (; i <= M; i++) scanf("%d", &I[i]); memset(DP, -1, sizeof(DP)); int ret = go(1, V); if (ret == INF) printf("Case #%d: IMPOSSIBLE\n", tc); else printf("Case #%d: %d\n", tc, ret); } return 0; }
23.51
87
0.572948
[ "vector" ]
c0dfd4207e28c947b7715c392a6a0919549e69d7
5,695
cc
C++
net/base/x509_util_nss_unittest.cc
GnorTech/chromium
e1c7731d5bd099ca5544fcf8eda3867d4ce5bab5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2018-03-10T13:08:49.000Z
2018-03-10T13:08:49.000Z
net/base/x509_util_nss_unittest.cc
GnorTech/chromium
e1c7731d5bd099ca5544fcf8eda3867d4ce5bab5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
net/base/x509_util_nss_unittest.cc
GnorTech/chromium
e1c7731d5bd099ca5544fcf8eda3867d4ce5bab5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2020-11-04T07:19:31.000Z
2020-11-04T07:19:31.000Z
// Copyright (c) 2012 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 "net/base/x509_util.h" #include "net/base/x509_util_nss.h" #include <cert.h> #include <secoid.h> #include "base/memory/scoped_ptr.h" #include "base/memory/ref_counted.h" #include "crypto/ec_private_key.h" #include "crypto/scoped_nss_types.h" #include "crypto/signature_verifier.h" #include "net/base/x509_certificate.h" #include "testing/gtest/include/gtest/gtest.h" namespace net { namespace { CERTCertificate* CreateNSSCertHandleFromBytes(const char* data, size_t length) { SECItem der_cert; der_cert.data = reinterpret_cast<unsigned char*>(const_cast<char*>(data)); der_cert.len = length; der_cert.type = siDERCertBuffer; // Parse into a certificate structure. return CERT_NewTempCertificate(CERT_GetDefaultCertDB(), &der_cert, NULL, PR_FALSE, PR_TRUE); } #if !defined(OS_WIN) && !defined(OS_MACOSX) void VerifyCertificateSignature(const std::string& der_cert, const std::vector<uint8>& der_spki) { crypto::ScopedPLArenaPool arena(PORT_NewArena(DER_DEFAULT_CHUNKSIZE)); CERTSignedData sd; memset(&sd, 0, sizeof(sd)); SECItem der_cert_item = { siDERCertBuffer, reinterpret_cast<unsigned char*>(const_cast<char*>(der_cert.data())), static_cast<unsigned int>(der_cert.size()) }; SECStatus rv = SEC_ASN1DecodeItem(arena.get(), &sd, SEC_ASN1_GET(CERT_SignedDataTemplate), &der_cert_item); ASSERT_EQ(SECSuccess, rv); // The CERTSignedData.signatureAlgorithm is decoded, but SignatureVerifier // wants the DER encoded form, so re-encode it again. SECItem* signature_algorithm = SEC_ASN1EncodeItem( arena.get(), NULL, &sd.signatureAlgorithm, SEC_ASN1_GET(SECOID_AlgorithmIDTemplate)); ASSERT_TRUE(signature_algorithm); crypto::SignatureVerifier verifier; bool ok = verifier.VerifyInit( signature_algorithm->data, signature_algorithm->len, sd.signature.data, sd.signature.len / 8, // Signature is a BIT STRING, convert to bytes. &der_spki[0], der_spki.size()); ASSERT_TRUE(ok); verifier.VerifyUpdate(sd.data.data, sd.data.len); ok = verifier.VerifyFinal(); EXPECT_TRUE(ok); } #endif // !defined(OS_WIN) && !defined(OS_MACOSX) void VerifyDomainBoundCert(const std::string& domain, const std::string& der_cert) { // Origin Bound Cert OID. static const char oid_string[] = "1.3.6.1.4.1.11129.2.1.6"; // Create object neccessary for extension lookup call. SECItem extension_object = { siAsciiString, (unsigned char*)domain.data(), static_cast<unsigned int>(domain.size()) }; // IA5Encode and arena allocate SECItem. PLArenaPool* arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); SECItem* expected = SEC_ASN1EncodeItem(arena, NULL, &extension_object, SEC_ASN1_GET(SEC_IA5StringTemplate)); ASSERT_NE(static_cast<SECItem*>(NULL), expected); // Create OID SECItem. SECItem ob_cert_oid = { siDEROID, NULL, 0 }; SECStatus ok = SEC_StringToOID(arena, &ob_cert_oid, oid_string, 0); ASSERT_EQ(SECSuccess, ok); SECOidTag ob_cert_oid_tag = SECOID_FindOIDTag(&ob_cert_oid); ASSERT_NE(SEC_OID_UNKNOWN, ob_cert_oid_tag); // This test is run on Mac and Win where X509Certificate::os_cert_handle isn't // an NSS type, so we have to manually create a NSS certificate object so we // can use CERT_FindCertExtension. We also check the subject and validity // times using NSS since X509Certificate will fail with EC certs on OSX 10.5 // (http://crbug.com/101231). CERTCertificate* nss_cert = CreateNSSCertHandleFromBytes( der_cert.data(), der_cert.size()); char* common_name = CERT_GetCommonName(&nss_cert->subject); ASSERT_TRUE(common_name); EXPECT_STREQ("anonymous.invalid", common_name); PORT_Free(common_name); EXPECT_EQ(SECSuccess, CERT_CertTimesValid(nss_cert)); // Lookup Origin Bound Cert extension in generated cert. SECItem actual = { siBuffer, NULL, 0 }; ok = CERT_FindCertExtension(nss_cert, ob_cert_oid_tag, &actual); CERT_DestroyCertificate(nss_cert); ASSERT_EQ(SECSuccess, ok); // Compare expected and actual extension values. PRBool result = SECITEM_ItemsAreEqual(expected, &actual); ASSERT_TRUE(result); // Do Cleanup. SECITEM_FreeItem(&actual, PR_FALSE); PORT_FreeArena(arena, PR_FALSE); } } // namespace // This test creates a domain-bound cert from an EC private key and // then verifies the content of the certificate. TEST(X509UtilNSSTest, CreateDomainBoundCertEC) { // Create a sample ASCII weborigin. std::string domain = "weborigin.com"; base::Time now = base::Time::Now(); scoped_ptr<crypto::ECPrivateKey> private_key( crypto::ECPrivateKey::Create()); std::string der_cert; ASSERT_TRUE(x509_util::CreateDomainBoundCertEC( private_key.get(), domain, 1, now, now + base::TimeDelta::FromDays(1), &der_cert)); VerifyDomainBoundCert(domain, der_cert); #if !defined(OS_WIN) && !defined(OS_MACOSX) // signature_verifier_win and signature_verifier_mac can't handle EC certs. std::vector<uint8> spki; ASSERT_TRUE(private_key->ExportPublicKey(&spki)); VerifyCertificateSignature(der_cert, spki); #endif } } // namespace net
33.110465
80
0.684284
[ "object", "vector" ]
c0e305e6421f12221adc620aed4e3c7f4ca4a127
5,669
cpp
C++
qpvr_tests/Tests.cpp
kusharami/qpvr
cf5ca2511e613265d765909b3181320cfaacab25
[ "MIT" ]
null
null
null
qpvr_tests/Tests.cpp
kusharami/qpvr
cf5ca2511e613265d765909b3181320cfaacab25
[ "MIT" ]
null
null
null
qpvr_tests/Tests.cpp
kusharami/qpvr
cf5ca2511e613265d765909b3181320cfaacab25
[ "MIT" ]
1
2019-03-23T15:21:03.000Z
2019-03-23T15:21:03.000Z
#include "Tests.h" #include <QImageReader> #include <QImageWriter> #include <QImage> #include <QPainter> #include <QTemporaryDir> #include <QDir> #include <QtTest> #include <QDebug> struct PVRTests::Options { int quality; int ver; QByteArray subType; QImageIOHandler::Transformations transform; QImage::Format resultFormat; static const Options OPTIONS[]; }; const PVRTests::Options PVRTests::Options::OPTIONS[] = { { -1, 2, QByteArray("rgba8888"), QImageIOHandler::TransformationNone, QImage::Format_RGBA8888 }, { -1, 2, QByteArray("rgba8888"), QImageIOHandler::TransformationFlip, QImage::Format_RGBA8888 }, { -1, 3, QByteArray("rgba8888"), QImageIOHandler::TransformationMirror, QImage::Format_RGBA8888 }, { 80, 2, QByteArrayLiteral("pvrtc2_2"), QImageIOHandler::TransformationNone, QImage::Format_RGBA8888 }, { 50, 2, QByteArrayLiteral("pvrtc2_4"), QImageIOHandler::TransformationFlip, QImage::Format_RGBA8888 }, { 0, 3, QByteArrayLiteral("pvrtc1_2"), QImageIOHandler::TransformationMirror, QImage::Format_RGBA8888 }, { 100, 3, QByteArrayLiteral("pvrtc1_4"), QImageIOHandler::TransformationRotate180, QImage::Format_RGBA8888 }, { 100, 2, QByteArrayLiteral("etc1"), QImageIOHandler::TransformationNone, QImage::Format_RGB888 }, { 0, 3, QByteArrayLiteral("etc2"), QImageIOHandler::TransformationMirror, QImage::Format_RGBA8888 } }; template <typename CLASS> static void checkSupportedOptions(const CLASS &io) { // supported options QVERIFY(io.supportsOption(QImageIOHandler::SubType)); QVERIFY(io.supportsOption(QImageIOHandler::SupportedSubTypes)); QVERIFY(io.supportsOption(QImageIOHandler::Size)); QVERIFY(io.supportsOption(QImageIOHandler::ScaledSize)); QVERIFY(io.supportsOption(QImageIOHandler::Quality)); QVERIFY(io.supportsOption(QImageIOHandler::ImageFormat)); QVERIFY(io.supportsOption(QImageIOHandler::ImageTransformation)); // unsupported options QVERIFY(!io.supportsOption(QImageIOHandler::Gamma)); QVERIFY(!io.supportsOption(QImageIOHandler::Animation)); QVERIFY(!io.supportsOption(QImageIOHandler::IncrementalReading)); QVERIFY(!io.supportsOption(QImageIOHandler::Endianness)); QVERIFY(!io.supportsOption(QImageIOHandler::BackgroundColor)); QVERIFY(!io.supportsOption(QImageIOHandler::OptimizedWrite)); QVERIFY(!io.supportsOption(QImageIOHandler::ProgressiveScanWrite)); QVERIFY(!io.supportsOption(QImageIOHandler::Name)); QVERIFY(!io.supportsOption(QImageIOHandler::Description)); QVERIFY(!io.supportsOption(QImageIOHandler::ClipRect)); QVERIFY(!io.supportsOption(QImageIOHandler::ScaledClipRect)); } static const QImage &fetchImage() { static bool imageInitialized = false; static QImage image(32, 32, QImage::Format_RGBA8888); if (!imageInitialized) { imageInitialized = true; QPainter painter(&image); painter.fillRect(QRect(0, 0, 16, 16), QColor(Qt::red)); painter.fillRect(QRect(16, 0, 16, 16), QColor(Qt::green)); painter.fillRect(QRect(0, 16, 16, 16), QColor(Qt::blue)); painter.fillRect(QRect(16, 16, 16, 16), QColor(Qt::transparent)); } return image; } void PVRTests::testInstallation() { QList<QList<QByteArray>> supported; supported.append(QImageReader::supportedImageFormats()); supported.append(QImageWriter::supportedImageFormats()); for (auto &s : supported) { QVERIFY(s.indexOf("pvr") >= 0); } } void PVRTests::testIO() { QTemporaryDir tempDir; tempDir.setAutoRemove(true); QVERIFY(tempDir.isValid()); QDir dir(tempDir.path()); for (const Options &options : Options::OPTIONS) { testWrite(options, dir); testRead(options, dir); } } void PVRTests::testWrite(const Options &options, const QDir &dir) { QImageWriter writer; auto subType = getSubType(options.ver, options.subType); writer.setFileName(filePathForSubType(dir, subType)); QVERIFY(writer.canWrite()); checkSupportedOptions(writer); auto supportedSubTypes = writer.supportedSubTypes(); QVERIFY(supportedSubTypes.indexOf(subType) >= 0); writer.setQuality(options.quality); writer.setSubType(subType); writer.setTransformation(options.transform); QVERIFY(writer.write(fetchImage())); } void PVRTests::testRead(const Options &options, const QDir &dir) { auto &image = fetchImage(); QImageReader reader; auto subType = getSubType(options.ver, options.subType); reader.setFileName(filePathForSubType(dir, subType)); QVERIFY(reader.canRead()); checkSupportedOptions(reader); #if QT_VERSION >= QT_VERSION_CHECK(5, 9, 1) // QImageReader::supportedSubTypes always empty in previous versions { QImageWriter writer; writer.setFormat(QByteArrayLiteral("pvr")); QCOMPARE(reader.supportedSubTypes(), writer.supportedSubTypes()); } #endif QCOMPARE(reader.imageFormat(), options.resultFormat); QCOMPARE(reader.size(), image.size()); QCOMPARE(reader.supportsAnimation(), false); QCOMPARE(reader.transformation(), options.transform); QCOMPARE(reader.loopCount(), 0); QCOMPARE(reader.imageCount(), 1); QCOMPARE(reader.subType(), subType); QImage readImage; QVERIFY(reader.read(&readImage)); QCOMPARE(readImage.size(), image.size()); QCOMPARE(readImage.format(), options.resultFormat); reader.setScaledSize(QSize(16, 16)); QVERIFY(reader.read(&readImage)); QCOMPARE(readImage.size(), reader.scaledSize()); QCOMPARE(readImage.format(), options.resultFormat); } QByteArray PVRTests::getSubType(int ver, const QByteArray &str) { auto subType = QByteArrayLiteral("pvr") + QByteArray().setNum(ver); if (!str.isEmpty()) subType += '.' + str; return subType; } QString PVRTests::filePathForSubType(const QDir &dir, const QByteArray &subType) { return dir.filePath( QString::fromLatin1(subType + QByteArrayLiteral(".pvr"))); }
28.77665
80
0.756924
[ "transform" ]
c0ea2d7e39bd7caee90a400e874192bd3775eef1
17,490
cpp
C++
Feather/src/Math/Matrix.cpp
pedrolmcastro/feather
e4581fb119706505dfcb25b5d982b47ee21e0746
[ "Apache-2.0" ]
null
null
null
Feather/src/Math/Matrix.cpp
pedrolmcastro/feather
e4581fb119706505dfcb25b5d982b47ee21e0746
[ "Apache-2.0" ]
null
null
null
Feather/src/Math/Matrix.cpp
pedrolmcastro/feather
e4581fb119706505dfcb25b5d982b47ee21e0746
[ "Apache-2.0" ]
null
null
null
#include "Precompiled.hpp" #include "Math/Matrix.hpp" #include "Math/Vector.hpp" #include "Math/Quaternion.hpp" using namespace std; using namespace Feather; Math::Matrix2::Matrix2(float diagonal) { elements.fill(0.0f); (*this)(0, 0) = diagonal; (*this)(1, 1) = diagonal; } Math::Matrix2 Math::Matrix2::Fill(float scalar) { Matrix2 matrix; matrix.elements.fill(scalar); return matrix; } Math::Matrix2 Math::Matrix2::operator*(const Matrix2& other) const { Matrix2 product; for (size_t i = 0; i < 2; i++) { for (size_t j = 0; j < 2; j++) { for (size_t k = 0; k < 2; k++) product(i, j) += (*this)(i, k) * other(k, j); } } return product; } Math::Float2 Math::Matrix2::operator*(const Float2& vector) const { return Float2( (*this)(0, 0) * vector.x + (*this)(0, 1) * vector.y, (*this)(1, 0) * vector.x + (*this)(1, 1) * vector.y ); } Math::Matrix2 Math::Matrix2::Inverse() const { Matrix2 inverse; inverse(0, 0) = (*this)(1, 1); inverse(0, 1) = - (*this)(0, 1); inverse(1, 0) = - (*this)(1, 0); inverse(1, 1) = (*this)(1, 0); return inverse * (1.0f / Determinant()); } Math::Matrix2 Math::Matrix2::Transpose() const { Matrix2 transpose(*this); transpose(0, 1) = (*this)(1, 0); transpose(1, 0) = (*this)(0, 1); return transpose; } float Math::Matrix2::Determinant() const { return (*this)(0, 0) * (*this)(1, 1) - (*this)(0, 1) * (*this)(1, 0); } Math::Matrix3::Matrix3(float diagonal) { elements.fill(0.0f); (*this)(0, 0) = diagonal; (*this)(1, 1) = diagonal; (*this)(2, 2) = diagonal; } Math::Matrix3 Math::Matrix3::Fill(float scalar) { Matrix3 matrix; matrix.elements.fill(scalar); return matrix; } Math::Matrix3 Math::Matrix3::operator*(const Matrix3& other) const { Matrix3 product; for (size_t i = 0; i < 3; i++) { for (size_t j = 0; j < 3; j++) { for (size_t k = 0; k < 3; k++) product(i, j) += (*this)(i, k) * other(k, j); } } return product; } Math::Float3 Math::Matrix3::operator*(const Float3& vector) const { return Float3( (*this)(0, 0) * vector.x + (*this)(0, 1) * vector.y + (*this)(0, 2) * vector.z, (*this)(1, 0) * vector.x + (*this)(1, 1) * vector.y + (*this)(1, 2) * vector.z, (*this)(2, 0) * vector.x + (*this)(2, 1) * vector.y + (*this)(2, 2) * vector.z ); } Math::Matrix3 Math::Matrix3::Inverse() const { Matrix3 inverse; inverse(0, 0) = (*this)(1, 1) * (*this)(2, 2) - (*this)(2, 1) * (*this)(1, 2); inverse(0, 1) = (*this)(0, 2) * (*this)(2, 1) - (*this)(0, 1) * (*this)(2, 2); inverse(0, 2) = (*this)(0, 1) * (*this)(1, 2) - (*this)(0, 2) * (*this)(1, 1); inverse(1, 0) = (*this)(1, 2) * (*this)(2, 0) - (*this)(1, 0) * (*this)(2, 2); inverse(1, 1) = (*this)(0, 0) * (*this)(2, 2) - (*this)(0, 2) * (*this)(2, 0); inverse(1, 2) = (*this)(1, 0) * (*this)(0, 2) - (*this)(0, 0) * (*this)(1, 2); inverse(2, 0) = (*this)(1, 0) * (*this)(2, 1) - (*this)(2, 0) * (*this)(1, 1); inverse(2, 1) = (*this)(2, 0) * (*this)(0, 1) - (*this)(0, 0) * (*this)(2, 1); inverse(2, 2) = (*this)(0, 0) * (*this)(1, 1) - (*this)(1, 0) * (*this)(0, 1); return inverse * (1.0f / Determinant()); } Math::Matrix3 Math::Matrix3::Transpose() const { Matrix3 transpose(*this); transpose(0, 1) = (*this)(1, 0); transpose(0, 2) = (*this)(2, 0); transpose(1, 0) = (*this)(0, 1); transpose(1, 2) = (*this)(2, 1); transpose(2, 0) = (*this)(0, 2); transpose(2, 1) = (*this)(1, 2); return transpose; } float Math::Matrix3::Determinant() const { return ( (*this)(0, 0) * ((*this)(1, 1) * (*this)(2, 2) - (*this)(2, 1) * (*this)(1, 2)) - (*this)(0, 1) * ((*this)(1, 0) * (*this)(2, 2) - (*this)(1, 2) * (*this)(2, 0)) + (*this)(0, 2) * ((*this)(1, 0) * (*this)(2, 1) - (*this)(1, 1) * (*this)(2, 0)) ); } Math::Matrix4::Matrix4(float diagonal) { elements.fill(0.0f); (*this)(0, 0) = diagonal; (*this)(1, 1) = diagonal; (*this)(2, 2) = diagonal; (*this)(3, 3) = diagonal; } Math::Matrix4 Math::Matrix4::Fill(float scalar) { Matrix4 matrix; matrix.elements.fill(scalar); return matrix; } Math::Matrix4 Math::Matrix4::Scale(const Float3& scale) { Matrix4 matrix(1.0f); matrix(0, 0) = scale.x; matrix(1, 1) = scale.y; matrix(2, 2) = scale.z; return matrix; } Math::Matrix4 Math::Matrix4::Translate(const Float3& translation) { Matrix4 matrix(1.0f); matrix(0, 3) = translation.x; matrix(1, 3) = translation.y; matrix(2, 3) = translation.z; return matrix; } Math::Matrix4 Math::Matrix4::Rotate(const Quaternion& quaternion) { Matrix4 rotation(1.0f); Quaternion normalized = quaternion.Normalize(); rotation(0, 0) = 1.0f - 2.0f * (normalized.y * normalized.y + normalized.z * normalized.z); rotation(1, 0) = 2.0f * (normalized.x * normalized.y + normalized.z * normalized.w); rotation(2, 0) = 2.0f * (normalized.x * normalized.z - normalized.y * normalized.w); rotation(0, 1) = 2.0f * (normalized.x * normalized.y - normalized.z * normalized.w); rotation(1, 1) = 1.0f - 2.0f * (normalized.x * normalized.x + normalized.z * normalized.z); rotation(2, 1) = 2.0f * (normalized.y * normalized.z + normalized.x * normalized.w); rotation(0, 2) = 2.0f * (normalized.x * normalized.z + normalized.y * normalized.w); rotation(1, 2) = 2.0f * (normalized.y * normalized.z - normalized.x * normalized.w); rotation(2, 2) = 1.0f - 2.0f * (normalized.x * normalized.x + normalized.y * normalized.y); return rotation; } Math::Matrix4 Math::Matrix4::Rotate(const Float3& axis, float angle) { Matrix4 rotation(1.0f); float sine = sin(angle); float cosine = cos(angle); Float3 normalized = axis.Normalize(); Float3 auxiliar = normalized * (1.0f - cosine); rotation(0, 0) = auxiliar.x * normalized.x + cosine; rotation(1, 0) = auxiliar.x * normalized.y + normalized.z * sine; rotation(2, 0) = auxiliar.x * normalized.z - normalized.y * sine; rotation(0, 1) = auxiliar.y * normalized.x - normalized.z * sine; rotation(1, 1) = auxiliar.y * normalized.y + cosine; rotation(2, 1) = auxiliar.y * normalized.z + normalized.x * sine; rotation(0, 2) = auxiliar.z * normalized.x + normalized.y * sine; rotation(1, 2) = auxiliar.z * normalized.y - normalized.x * sine; rotation(2, 2) = auxiliar.z * normalized.z + cosine; return rotation; } Math::Matrix4 Math::Matrix4::Perspective(float fov, float aspect, float near, float far) { Matrix4 perspective; float tangent = tan(fov * 0.5f); perspective(0, 0) = 1.0f / (aspect * tangent); perspective(1, 1) = 1.0f / tangent; perspective(2, 2) = - (far + near) / (far - near); perspective(3, 2) = - 1.0f; perspective(2, 3) = - (2.0f * far * near) / (far - near); return perspective; } Math::Matrix4 Math::Matrix4::Orthographic(float left, float right, float bottom, float top, float near, float far) { Matrix4 orthographic(1.0f); float width = (right - left); float height = (top - bottom); float clip = (far - near); orthographic(0, 0) = 2.0f / width; orthographic(1, 1) = 2.0f / height; orthographic(2, 2) = - 2.0f / clip; orthographic(0, 3) = - (right + left) / width; orthographic(1, 3) = - (top + bottom) / height; orthographic(2, 3) = - (far + near) / clip; return orthographic; } Math::Matrix4 Math::Matrix4::LookAt(const Float3& position, const Float3& target, const Float3& up) { Matrix4 look(1.0f); Float3 zaxis = (target - position).Normalize(); Float3 xaxis = zaxis.Cross(up).Normalize(); Float3 yaxis = zaxis.Cross(xaxis); look(0, 0) = xaxis.x; look(0, 1) = xaxis.y; look(0, 2) = xaxis.z; look(0, 3) = - xaxis.Dot(position); look(1, 0) = yaxis.x; look(1, 1) = yaxis.y; look(1, 2) = yaxis.z; look(1, 3) = - yaxis.Dot(position); look(2, 0) = - zaxis.x; look(2, 1) = - zaxis.y; look(2, 2) = - zaxis.z; look(2, 3) = zaxis.Dot(position); return look; } Math::Matrix4 Math::Matrix4::operator*(const Matrix4& other) const { Matrix4 product; for (size_t i = 0; i < 4; i++) { for (size_t j = 0; j < 4; j++) { for (size_t k = 0; k < 4; k++) product(i, j) += (*this)(i, k) * other(k, j); } } return product; } Math::Float4 Math::Matrix4::operator*(const Float4& vector) const { return Float4( (*this)(0, 0) * vector.x + (*this)(0, 1) * vector.y + (*this)(0, 2) * vector.z + (*this)(0, 3) * vector.w, (*this)(1, 0) * vector.x + (*this)(1, 1) * vector.y + (*this)(1, 2) * vector.z + (*this)(1, 3) * vector.w, (*this)(2, 0) * vector.x + (*this)(2, 1) * vector.y + (*this)(2, 2) * vector.z + (*this)(2, 3) * vector.w, (*this)(3, 0) * vector.x + (*this)(3, 1) * vector.y + (*this)(3, 2) * vector.z + (*this)(3, 3) * vector.w ); } Math::Matrix4 Math::Matrix4::Inverse() const { Matrix4 inverse; inverse(0, 0) = ( (*this)(1, 1) * (*this)(2, 2) * (*this)(3, 3) - (*this)(1, 1) * (*this)(3, 2) * (*this)(2, 3) - (*this)(1, 2) * (*this)(2, 1) * (*this)(3, 3) + (*this)(1, 2) * (*this)(3, 1) * (*this)(2, 3) + (*this)(1, 3) * (*this)(2, 1) * (*this)(3, 2) - (*this)(1, 3) * (*this)(3, 1) * (*this)(2, 2) ); inverse(0, 1) = ( - (*this)(0, 1) * (*this)(2, 2) * (*this)(3, 3) + (*this)(0, 1) * (*this)(3, 2) * (*this)(2, 3) + (*this)(0, 2) * (*this)(2, 1) * (*this)(3, 3) - (*this)(0, 2) * (*this)(3, 1) * (*this)(2, 3) - (*this)(0, 3) * (*this)(2, 1) * (*this)(3, 2) + (*this)(0, 3) * (*this)(3, 1) * (*this)(2, 2) ); inverse(0, 2) = ( (*this)(0, 1) * (*this)(1, 2) * (*this)(3, 3) - (*this)(0, 1) * (*this)(3, 2) * (*this)(1, 3) - (*this)(0, 2) * (*this)(1, 1) * (*this)(3, 3) + (*this)(0, 2) * (*this)(3, 1) * (*this)(1, 3) + (*this)(0, 3) * (*this)(1, 1) * (*this)(3, 2) - (*this)(0, 3) * (*this)(3, 1) * (*this)(1, 2) ); inverse(0, 3) = ( - (*this)(0, 1) * (*this)(1, 2) * (*this)(2, 3) + (*this)(0, 1) * (*this)(2, 2) * (*this)(1, 3) + (*this)(0, 2) * (*this)(1, 1) * (*this)(2, 3) - (*this)(0, 2) * (*this)(2, 1) * (*this)(1, 3) - (*this)(0, 3) * (*this)(1, 1) * (*this)(2, 2) + (*this)(0, 3) * (*this)(2, 1) * (*this)(1, 2) ); inverse(1, 0) = ( - (*this)(1, 0) * (*this)(2, 2) * (*this)(3, 3) + (*this)(1, 0) * (*this)(3, 2) * (*this)(2, 3) + (*this)(1, 2) * (*this)(2, 0) * (*this)(3, 3) - (*this)(1, 2) * (*this)(3, 0) * (*this)(2, 3) - (*this)(1, 3) * (*this)(2, 0) * (*this)(3, 2) + (*this)(1, 3) * (*this)(3, 0) * (*this)(2, 2) ); inverse(1, 1) = ( (*this)(0, 0) * (*this)(2, 2) * (*this)(3, 3) - (*this)(0, 0) * (*this)(3, 2) * (*this)(2, 3) - (*this)(0, 2) * (*this)(2, 0) * (*this)(3, 3) + (*this)(0, 2) * (*this)(3, 0) * (*this)(2, 3) + (*this)(0, 3) * (*this)(2, 0) * (*this)(3, 2) - (*this)(0, 3) * (*this)(3, 0) * (*this)(2, 2) ); inverse(1, 2) = ( - (*this)(0, 0) * (*this)(1, 2) * (*this)(3, 3) + (*this)(0, 0) * (*this)(3, 2) * (*this)(1, 3) + (*this)(0, 2) * (*this)(1, 0) * (*this)(3, 3) - (*this)(0, 2) * (*this)(3, 0) * (*this)(1, 3) - (*this)(0, 3) * (*this)(1, 0) * (*this)(3, 2) + (*this)(0, 3) * (*this)(3, 0) * (*this)(1, 2) ); inverse(1, 3) = ( (*this)(0, 0) * (*this)(1, 2) * (*this)(2, 3) - (*this)(0, 0) * (*this)(2, 2) * (*this)(1, 3) - (*this)(0, 2) * (*this)(1, 0) * (*this)(2, 3) + (*this)(0, 2) * (*this)(2, 0) * (*this)(1, 3) + (*this)(0, 3) * (*this)(1, 0) * (*this)(2, 2) - (*this)(0, 3) * (*this)(2, 0) * (*this)(1, 2) ); inverse(2, 0) = ( (*this)(1, 0) * (*this)(2, 1) * (*this)(3, 3) - (*this)(1, 0) * (*this)(3, 1) * (*this)(2, 3) - (*this)(1, 1) * (*this)(2, 0) * (*this)(3, 3) + (*this)(1, 1) * (*this)(3, 0) * (*this)(2, 3) + (*this)(1, 3) * (*this)(2, 0) * (*this)(3, 1) - (*this)(1, 3) * (*this)(3, 0) * (*this)(2, 1) ); inverse(2, 1) = ( - (*this)(0, 0) * (*this)(2, 1) * (*this)(3, 3) + (*this)(0, 0) * (*this)(3, 1) * (*this)(2, 3) + (*this)(0, 1) * (*this)(2, 0) * (*this)(3, 3) - (*this)(0, 1) * (*this)(3, 0) * (*this)(2, 3) - (*this)(0, 3) * (*this)(2, 0) * (*this)(3, 1) + (*this)(0, 3) * (*this)(3, 0) * (*this)(2, 1) ); inverse(2, 2) = ( (*this)(0, 0) * (*this)(1, 1) * (*this)(3, 3) - (*this)(0, 0) * (*this)(3, 1) * (*this)(1, 3) - (*this)(0, 1) * (*this)(1, 0) * (*this)(3, 3) + (*this)(0, 1) * (*this)(3, 0) * (*this)(1, 3) + (*this)(0, 3) * (*this)(1, 0) * (*this)(3, 1) - (*this)(0, 3) * (*this)(3, 0) * (*this)(1, 1) ); inverse(2, 3) = ( - (*this)(0, 0) * (*this)(1, 1) * (*this)(2, 3) + (*this)(0, 0) * (*this)(2, 1) * (*this)(1, 3) + (*this)(0, 1) * (*this)(1, 0) * (*this)(2, 3) - (*this)(0, 1) * (*this)(2, 0) * (*this)(1, 3) - (*this)(0, 3) * (*this)(1, 0) * (*this)(2, 1) + (*this)(0, 3) * (*this)(2, 0) * (*this)(1, 1) ); inverse(3, 0) = ( - (*this)(1, 0) * (*this)(2, 1) * (*this)(3, 2) + (*this)(1, 0) * (*this)(3, 1) * (*this)(2, 2) + (*this)(1, 1) * (*this)(2, 0) * (*this)(3, 2) - (*this)(1, 1) * (*this)(3, 0) * (*this)(2, 2) - (*this)(1, 2) * (*this)(2, 0) * (*this)(3, 1) + (*this)(1, 2) * (*this)(3, 0) * (*this)(2, 1) ); inverse(3, 1) = ( (*this)(0, 0) * (*this)(2, 1) * (*this)(3, 2) - (*this)(0, 0) * (*this)(3, 1) * (*this)(2, 2) - (*this)(0, 1) * (*this)(2, 0) * (*this)(3, 2) + (*this)(0, 1) * (*this)(3, 0) * (*this)(2, 2) + (*this)(0, 2) * (*this)(2, 0) * (*this)(3, 1) - (*this)(0, 2) * (*this)(3, 0) * (*this)(2, 1) ); inverse(3, 2) = ( - (*this)(0, 0) * (*this)(1, 1) * (*this)(3, 2) + (*this)(0, 0) * (*this)(3, 1) * (*this)(1, 2) + (*this)(0, 1) * (*this)(1, 0) * (*this)(3, 2) - (*this)(0, 1) * (*this)(3, 0) * (*this)(1, 2) - (*this)(0, 2) * (*this)(1, 0) * (*this)(3, 1) + (*this)(0, 2) * (*this)(3, 0) * (*this)(1, 1) ); inverse(3, 3) = ( (*this)(0, 0) * (*this)(1, 1) * (*this)(2, 2) - (*this)(0, 0) * (*this)(2, 1) * (*this)(1, 2) - (*this)(0, 1) * (*this)(1, 0) * (*this)(2, 2) + (*this)(0, 1) * (*this)(2, 0) * (*this)(1, 2) + (*this)(0, 2) * (*this)(1, 0) * (*this)(2, 1) - (*this)(0, 2) * (*this)(2, 0) * (*this)(1, 1) ); float determinant = (*this)(0, 0) * inverse(0, 0) + (*this)(1, 0) * inverse(0, 1) + (*this)(2, 0) * inverse(0, 2) + (*this)(3, 0) * inverse(0, 3); return inverse * (1.0f / determinant); } Math::Matrix4 Math::Matrix4::Transpose() const { Matrix4 transpose(*this); transpose(0, 1) = (*this)(1, 0); transpose(0, 2) = (*this)(2, 0); transpose(0, 3) = (*this)(3, 0); transpose(1, 0) = (*this)(0, 1); transpose(1, 2) = (*this)(2, 1); transpose(1, 3) = (*this)(3, 1); transpose(2, 0) = (*this)(0, 2); transpose(2, 1) = (*this)(1, 2); transpose(2, 3) = (*this)(3, 2); transpose(3, 0) = (*this)(0, 3); transpose(3, 1) = (*this)(1, 3); transpose(3, 2) = (*this)(2, 3); return transpose; } float Math::Matrix4::Determinant() const { return ( (*this)(0, 3) * (*this)(1, 2) * (*this)(2, 1) * (*this)(3, 0) - (*this)(0, 2) * (*this)(1, 3) * (*this)(2, 1) * (*this)(3, 0) - (*this)(0, 3) * (*this)(1, 1) * (*this)(2, 2) * (*this)(3, 0) + (*this)(0, 1) * (*this)(1, 3) * (*this)(2, 2) * (*this)(3, 0) + (*this)(0, 2) * (*this)(1, 1) * (*this)(2, 3) * (*this)(3, 0) - (*this)(0, 1) * (*this)(1, 2) * (*this)(2, 3) * (*this)(3, 0) - (*this)(0, 3) * (*this)(1, 2) * (*this)(2, 0) * (*this)(3, 1) + (*this)(0, 2) * (*this)(1, 3) * (*this)(2, 0) * (*this)(3, 1) + (*this)(0, 3) * (*this)(1, 0) * (*this)(2, 2) * (*this)(3, 1) - (*this)(0, 0) * (*this)(1, 3) * (*this)(2, 2) * (*this)(3, 1) - (*this)(0, 2) * (*this)(1, 0) * (*this)(2, 3) * (*this)(3, 1) + (*this)(0, 0) * (*this)(1, 2) * (*this)(2, 3) * (*this)(3, 1) + (*this)(0, 3) * (*this)(1, 1) * (*this)(2, 0) * (*this)(3, 2) - (*this)(0, 1) * (*this)(1, 3) * (*this)(2, 0) * (*this)(3, 2) - (*this)(0, 3) * (*this)(1, 0) * (*this)(2, 1) * (*this)(3, 2) + (*this)(0, 0) * (*this)(1, 3) * (*this)(2, 1) * (*this)(3, 2) + (*this)(0, 1) * (*this)(1, 0) * (*this)(2, 3) * (*this)(3, 2) - (*this)(0, 0) * (*this)(1, 1) * (*this)(2, 3) * (*this)(3, 2) - (*this)(0, 2) * (*this)(1, 1) * (*this)(2, 0) * (*this)(3, 3) + (*this)(0, 1) * (*this)(1, 2) * (*this)(2, 0) * (*this)(3, 3) + (*this)(0, 2) * (*this)(1, 0) * (*this)(2, 1) * (*this)(3, 3) - (*this)(0, 0) * (*this)(1, 2) * (*this)(2, 1) * (*this)(3, 3) - (*this)(0, 1) * (*this)(1, 0) * (*this)(2, 2) * (*this)(3, 3) + (*this)(0, 0) * (*this)(1, 1) * (*this)(2, 2) * (*this)(3, 3) ); }
35.766871
150
0.453802
[ "vector" ]
c0ead2c7b8457c6d515b6d0703f6b5a3fa059265
1,010
hpp
C++
engine/alice/backend/asio_backend.hpp
stereoboy/isaac_sdk_20191213
73c863254e626c8d498870189fbfb20be4e10fb3
[ "FSFAP" ]
1
2020-04-14T13:55:16.000Z
2020-04-14T13:55:16.000Z
engine/alice/backend/asio_backend.hpp
stereoboy/isaac_sdk_20191213
73c863254e626c8d498870189fbfb20be4e10fb3
[ "FSFAP" ]
4
2020-09-25T22:34:29.000Z
2022-02-09T23:45:12.000Z
engine/alice/backend/asio_backend.hpp
stereoboy/isaac_sdk_20191213
73c863254e626c8d498870189fbfb20be4e10fb3
[ "FSFAP" ]
1
2020-07-02T11:51:17.000Z
2020-07-02T11:51:17.000Z
/* Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. NVIDIA CORPORATION and its licensors retain all intellectual property and proprietary rights in and to this software, related documentation and any modifications thereto. Any use, reproduction, disclosure or distribution of this software and related documentation without an express license agreement from NVIDIA CORPORATION is strictly prohibited. */ #pragma once #include <memory> namespace asio { class io_context; } namespace isaac { namespace scheduler { class Scheduler; } // namespace scheduler } // namespace isaac namespace isaac { namespace alice { // Hold the ASIO object for other backends class AsioBackend { public: AsioBackend(scheduler::Scheduler* scheduler); ~AsioBackend(); void start(); void stop(); // The ASIO IO service object asio::io_context& io_context(); private: class Impl; std::unique_ptr<Impl> impl_; scheduler::Scheduler* scheduler_; }; } // namespace alice } // namespace isaac
21.489362
74
0.756436
[ "object" ]
c0ef6b5c5146559bb527c5ef50f8528f6b9a9887
1,410
hpp
C++
src/mathFunctions/constantValue.hpp
owenmylotte/ablate
92b190a2d422eb89748338c04fd7b29976be54b1
[ "BSD-3-Clause" ]
null
null
null
src/mathFunctions/constantValue.hpp
owenmylotte/ablate
92b190a2d422eb89748338c04fd7b29976be54b1
[ "BSD-3-Clause" ]
null
null
null
src/mathFunctions/constantValue.hpp
owenmylotte/ablate
92b190a2d422eb89748338c04fd7b29976be54b1
[ "BSD-3-Clause" ]
null
null
null
#ifndef ABLATELIBRARY_CONSTANTVALUE_HPP #define ABLATELIBRARY_CONSTANTVALUE_HPP #include "mathFunction.hpp" #include "memory" namespace ablate::mathFunctions { class ConstantValue : public MathFunction { private: const std::vector<double> value; const bool uniformValue; static PetscErrorCode ConstantValuePetscFunction(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nf, PetscScalar* u, void* ctx); static PetscErrorCode ConstantValueUniformPetscFunction(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nf, PetscScalar* u, void* ctx); public: explicit ConstantValue(double value); explicit ConstantValue(std::vector<double> values); double Eval(const double& x, const double& y, const double& z, const double& t) const override; double Eval(const double* xyz, const int& ndims, const double& t) const override; void Eval(const double& x, const double& y, const double& z, const double& t, std::vector<double>& result) const override; void Eval(const double* xyz, const int& ndims, const double& t, std::vector<double>& result) const override; PetscFunction GetPetscFunction() override { return uniformValue ? ConstantValueUniformPetscFunction : ConstantValuePetscFunction; } void* GetContext() override { return (void*)value.data(); } }; } // namespace ablate::mathFunctions #endif // ABLATELIBRARY_CONSTANTVALUE_HPP
39.166667
151
0.75461
[ "vector" ]
c0f32213757e525b715bf1e6a8f8f8e63d0ed5c4
8,561
hh
C++
util-wx/fwd-wx.hh
lukas-ke/faint-graphics-editor
33eb9e6a3f2216fb2cf6ef9709a14f3d20b78fbf
[ "Apache-2.0" ]
10
2016-12-28T22:06:31.000Z
2021-05-24T13:42:30.000Z
util-wx/fwd-wx.hh
lukas-ke/faint-graphics-editor
33eb9e6a3f2216fb2cf6ef9709a14f3d20b78fbf
[ "Apache-2.0" ]
4
2015-10-09T23:55:10.000Z
2020-04-04T08:09:22.000Z
util-wx/fwd-wx.hh
lukas-ke/faint-graphics-editor
33eb9e6a3f2216fb2cf6ef9709a14f3d20b78fbf
[ "Apache-2.0" ]
null
null
null
// -*- coding: us-ascii-unix -*- // Copyright 2015 Lukas Kemmer // // Licensed under the Apache License, Version 2.0 (the "License"); you // may not use this file except in compliance with the License. You // may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or // implied. See the License for the specific language governing // permissions and limitations under the License. #ifndef FAINT_FWD_WX_HH #define FAINT_FWD_WX_HH #include <functional> #include <type_traits> #include <vector> #include "geo/primitive.hh" #include "gui/gui-string-types.hh" #include "text/precision.hh" #include "util-wx/window-types-wx.hh" #include "util/distinct.hh" class wxCommandEvent; class wxCursor; class wxObject; namespace faint{ class Bitmap; class Color; class IntPoint; class IntSize; class utf8_string; class category_fwd_wx; using Width = Distinct<int, category_fwd_wx, 0>; using FontSize = Distinct<int, category_fwd_wx, 1>; using Bold = Distinct<bool, category_fwd_wx, 2>; void destroy(window_t); void destroy(wxDialog*); wxDialog* center_over_parent(wxDialog*); void center_over_parent(unique_dialog_ptr&); void enable(window_t, bool); void hide(window_t); bool is_shown(window_t); void show(wxDialog*); void show(unique_dialog_ptr&); void show(window_t, bool show=true); void set_bitmap(wxButton&, const wxBitmap&); void set_bitmap(wxButton&, const Bitmap&); IntSize get_size(const wxBitmap&); int get_id(window_t); void set_focus(window_t); using button_fn = std::function<void()>; using checkbox_fn = std::function<void()>; wxButton* create_button(window_t parent, const char* label, const IntPoint& pos, const button_fn&); wxButton* create_button(window_t parent, const char* label, const IntSize& initialSize, const button_fn&); wxButton* create_button(window_t parent, const char* label, const Width&, const button_fn&); wxButton* create_button(window_t, const wxBitmap&, const button_fn&); wxButton* create_button(window_t, const wxBitmap&, const Tooltip&, const button_fn&); wxButton* create_button(window_t, const wxBitmap&, const IntSize&, const button_fn&); wxButton* create_button(window_t, const wxBitmap&, const IntSize&, const Tooltip&, const button_fn&); wxButton* create_button(window_t, const char* label, const button_fn&); wxButton* create_ok_button(window_t parent); wxButton* create_cancel_button(window_t parent); wxButton* create_cancel_button(window_t parent, const IntSize&); // Bitmap or text button which inhibits the noise on keypresses if button has // focus. wxButton* noiseless_button(wxWindow* parent, const wxBitmap&, const Tooltip&, const IntSize&, const button_fn&); wxButton* noiseless_button(wxWindow* parent, const wxBitmap&, const Tooltip&, const IntSize&, const button_fn&); wxButton* noiseless_button(wxWindow* parent, const utf8_string&, const Tooltip&, const IntSize&); wxStaticText* create_label(window_t parent, const utf8_string&, FontSize, Bold, const Color&); wxStaticText* create_label(window_t parent, const char*, Bold, const Color&); wxStaticText* create_label(window_t parent, const char*, const IntPoint&); wxStaticText* create_label(window_t parent, const utf8_string&); enum class TextAlign{ CENTER, LEFT, RIGHT }; wxStaticText* create_label(window_t parent, const utf8_string&, TextAlign); unique_dialog_ptr resizable_dialog(window_t parent, const utf8_string& title); unique_dialog_ptr fixed_size_dialog(window_t parent, const utf8_string& title); unique_dialog_ptr null_dialog(); wxTextCtrl* create_text_control(window_t parent, const char* initialText); wxTextCtrl* create_text_control(window_t parent, const char*, const IntPoint&, const Width&); wxTextCtrl* create_text_control(window_t parent, const Width&); wxTextCtrl* create_text_control(window_t parent, const IntPoint&, const Width&); wxTextCtrl* create_multiline_text_control(window_t parent, const IntSize&); wxChoice* create_choice(window_t parent, const std::vector<utf8_string>&); // Returns a sizer with OK and Cancel-buttons organized as // expected on the current platform. wxSizer* create_ok_cancel_buttons(wxDialog*); wxSizer* create_ok_cancel_buttons(window_t parent, wxDialog* ancestor ); bool select(wxChoice*, const utf8_string&); wxWindow* create_panel(window_t parent); utf8_string get_text(wxTextCtrl*); utf8_string get_text(wxChoice*); void make_uniformly_sized(const std::initializer_list<window_t>&); void set_sizer(window_t, wxSizer*); void select_all(wxTextCtrl*); void set_pos(window_t, const IntPoint&); void set_size(window_t, const IntSize&); IntPoint get_pos(window_t); IntSize get_size(window_t); int get_width(window_t); int get_height(window_t); // Converter to wxWindow* for any wxWidgets pointer that is implicitly // convertible to window_t. This allows upcasting wxWidgets classes // known only by a forward declaration so that they can be passed to // functions expecting a wxWindow*. wxWindow* raw(window_t); wxWindow* raw(unique_dialog_ptr&); wxWindow* create_hline(window_t parent); wxCheckBox* create_checkbox(window_t parent, const char* label, bool checked); wxCheckBox* create_checkbox(window_t parent, const char* label, const IntPoint&); wxCheckBox* create_checkbox(window_t parent, const char* label, bool checked, const IntPoint&); wxCheckBox* create_checkbox(window_t parent, const char* label, bool checked, checkbox_fn&&); wxCheckBox* create_checkbox(window_t parent, const char* label, bool checked, const IntPoint&, checkbox_fn&&); bool get(wxCheckBox*); bool not_set(wxCheckBox*); // Unchecks the checkbox and sends a change event. void clear(wxCheckBox*); // Toggles the checked-state and sends a change event. bool toggle(wxCheckBox*); // Sets the checked-state and sends a change event if it changed. void set(wxCheckBox*, bool); class AcceleratorEntry; void set_accelerators(wxWindow*, const std::vector<AcceleratorEntry>&); void end_modal_ok(wxDialog*); void set_tooltip(window_t, const Tooltip&); void set_tooltip(window_t, const utf8_string&); wxBookCtrlBase* create_notebook(window_t parent); void add_page(wxBookCtrlBase*, window_t, const utf8_string&); void set_selection(wxBookCtrlBase*, int); wxWindow* create_hyperlink(window_t parent, const utf8_string& url); class wxWidgetsVersion{ public: wxWidgetsVersion(); int majorVersion; int minorVersion; int release_number; int subrelease_number; }; enum class Signal{ // Whether a value change should trigger an event or not YES, NO }; void set_number_text(wxTextCtrl*, int value, Signal); void set_number_text(wxTextCtrl*, coord value, Signal) = delete; void set_number_text(wxTextCtrl*, coord value, const Precision&, Signal); void append_text(wxTextCtrl*, const utf8_string&); bool is_empty(wxTextCtrl*); void refresh(window_t); void set_bgstyle_paint(window_t); void set_initial_size(window_t, const IntSize&); void set_background_color(window_t, const Color&); Color get_background_color(window_t); void set_stock_cursor(window_t, int); void set_cursor(window_t, const wxCursor&); void process_event(window_t, wxCommandEvent&); void fit_size_to(wxTextCtrl*, const utf8_string&); void refresh_layout(window_t); // These functions (deleted_by_wx) merely set the pointer to nullptr, // but also convey that the object is probably (eventually-) released // by wxWidgets. void deleted_by_wx(wxWindow*&); void deleted_by_wx(wxPanel*&); // The template version allows using deleted_by_wx for derived types // in translation units where the base classes are known, while also // preventing attempts to use it for non wx-types by static_assert template<typename T> void deleted_by_wx(T*& v){ static_assert(std::is_base_of_v<wxWindow, T>, "deleted_by_wx is only valid for wxWidgets types"); v = nullptr; } // Helper to distinguish new:s that should be deleted from new:ed // wxWidgets objects, which are usually automatically deleted // hierarchically. template<typename T, typename ...Args> T* make_wx(Args&& ...args){ static_assert(std::is_base_of_v<wxObject, T>, "make_wx should only be used for subtypes of wxObject"); return new T(std::forward<Args>(args)...); } int from_DIP(int, const wxWindow*); IntSize from_DIP(const IntSize&, const wxWindow*); } // namespace #endif
26.753125
80
0.770004
[ "object", "vector" ]
c0f82ab68fc79f9db7a8de7a21f62a6d39ffe909
4,294
cpp
C++
test/tutorial/main.cpp
MarcToussaint/KOMO
fb8e06bfb481b2d7ebfa464d88a60d4e4a408b0b
[ "MIT" ]
null
null
null
test/tutorial/main.cpp
MarcToussaint/KOMO
fb8e06bfb481b2d7ebfa464d88a60d4e4a408b0b
[ "MIT" ]
1
2019-01-04T12:41:28.000Z
2019-01-04T13:31:47.000Z
test/tutorial/main.cpp
MarcToussaint/KOMO
fb8e06bfb481b2d7ebfa464d88a60d4e4a408b0b
[ "MIT" ]
4
2017-12-14T07:42:13.000Z
2021-04-26T20:58:56.000Z
#include <KOMO/komo.h> //=========================================================================== void tutorialBasics(){ rai::Configuration C("model.g"); KOMO komo; /* there are essentially three things that KOMO needs to be specified: * 1) the kinematic model * 2) the timing parameters (duration/phases, number os time slices per phase) * 3) the tasks */ //-- setting the model; false -> NOT calling collision detection (SWIFT) -> faster komo.setModel(C, false); //-- the timing parameters: 2 phases, 20 time slices, 5 seconds, k=2 (acceleration mode) komo.setTiming(2, 20, 5., 2); //-- default tasks for transition costs komo.setSquaredQAccVelHoming(); komo.setSquaredQuaternionNorms(-1., -1., 1e1); //when the kinematics includes quaternion joints, keep them roughly regularized //-- simple tasks, called low-level //in phase-time [1,\infty] position-difference between "endeff" and "target" shall be zero (eq objective) komo.addObjective({1.,-1.}, FS_positionDiff, {"endeff", "target"}, OT_eq, {1e0}); //in phase-time [1,\infty] quaternion-difference between "endeff" and "target" shall be zero (eq objective) komo.addObjective({1., -1.}, FS_quaternionDiff, {"endeff", "target"}, OT_eq, {1e1}); //I don't always recommend setting quaternion tasks! This is only for testing here. As an alternative, one can use alignment tasks as in test/KOMO/komo //slow down around phase-time 1. (not measured in seconds, but phase) komo.setSlow(1., -1., 1e1); //-- call the optimizer komo.reset(); komo.run(); // komo.checkGradients(); //this checks all gradients of the problem by finite difference komo.getReport(true); //true -> plot the cost curves for(uint i=0;i<2;i++) komo.displayTrajectory(.1, true); //play the trajectory /* next step: * * Have a look at all the other set*** methods, which all add tasks to the KOMO problem. Look into * their implementation: they mainly just call setTask(..) with various TaskMaps. * * The last three arguments of setTask are important: * * type allows to define whether this is a sumOfSqr, equality, or inequality task * * target defines the target value in the task space; {} is interpreted as the zero vector * * order=0 means that the task is about the position(absolute value) in task space * order=1 means that the task is about the velocity in task space * order=2 means that the task is about the acceleration in task space * * For instance, setSquaredQAccelerations sets a tasks about the acceleration in the identity map * * Next, perhaps learn about all the available taskMaps, or implement new differentiable MappingSuccess * */ } //=========================================================================== void tutorialInverseKinematics(){ /* The only difference is that the timing parameters are set differently and the tranision * costs need to be velocities (which is just sumOfSqr of the difference to initialization). * All tasks should refer to phase-time 1. Internally, the system still created a banded-diagonal * Hessian representation, which is some overhead. It then calles exactly the same constrained optimizers */ rai::Configuration C("model.g"); KOMO komo; komo.setModel(C, false); //-- the timing parameters: 1 phase, 1 time slice komo.setTiming(1, 1); //-- default tasks for transition costs komo.setSquaredQAccVelHoming(1., -1., 0., 1., 1e-2); komo.setSquaredQuaternionNorms(-1., -1., 1e3); //when the kinematics includes quaternion joints, keep them roughly regularized //-- simple tasks, called low-level komo.addObjective({}, FS_positionDiff, {"endeff", "target"}, OT_eq, {1e0}); komo.addObjective({}, FS_quaternionDiff, {"endeff", "target"}, OT_eq, {1e1}); //-- call the optimizer komo.reset(); komo.run(); // komo.checkGradients(); //this checks all gradients of the problem by finite difference komo.getReport(); //true -> plot the cost curves for(uint i=0;i<2;i++) komo.displayTrajectory(.1, true); //play the trajectory } //=========================================================================== int main(int argc,char** argv){ rai::initCmdLine(argc,argv); tutorialBasics(); tutorialInverseKinematics(); return 0; }
39.759259
153
0.668374
[ "vector", "model" ]
c0fa457476284186cf1740b8436c15a42b676e26
3,298
cpp
C++
src/sampapi/0.3.7-R1/CObject.cpp
kin4stat/SAMP-API
94eb9a0d8218038b7ea0c1132e37b6420e576dbf
[ "MIT" ]
25
2020-01-02T06:13:58.000Z
2022-03-15T12:23:04.000Z
src/sampapi/0.3.7-R1/CObject.cpp
kin4stat/SAMP-API
94eb9a0d8218038b7ea0c1132e37b6420e576dbf
[ "MIT" ]
null
null
null
src/sampapi/0.3.7-R1/CObject.cpp
kin4stat/SAMP-API
94eb9a0d8218038b7ea0c1132e37b6420e576dbf
[ "MIT" ]
29
2019-07-07T15:37:03.000Z
2022-02-23T18:36:16.000Z
/* This is a SAMP (0.3.7-R1) API project file. Developer: LUCHARE <luchare.dev@gmail.com> See more here https://github.com/LUCHARE/SAMP-API Copyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved. */ #include "sampapi/0.3.7-R1/CObject.h" SAMPAPI_BEGIN_V037R1 CObject::CObject(int nModel, CVector position, CVector rotation, float fDrawDistance, int arg5) { ((void(__thiscall*)(CObject*, int, CVector, CVector, float, int))GetAddress(0xA3AB0))(this, nModel, position, rotation, fDrawDistance, arg5); } CObject::~CObject() { } float CObject::GetDistance(const CMatrix* pMatrix) { return ((float(__thiscall*)(CObject*, const CMatrix*))GetAddress(0xA2960))(this, pMatrix); } void CObject::Stop() { ((void(__thiscall*)(CObject*))GetAddress(0xA29D0))(this); } void CObject::SetRotation(const CVector* pRotation) { ((void(__thiscall*)(CObject*, const CVector*))GetAddress(0xA2A40))(this, pRotation); } void CObject::AttachToVehicle(CVehicle* pVehicle) { ((void(__thiscall*)(CObject*, CVehicle * pVehicle)) GetAddress(0xA2BE0))(this, pVehicle); } void CObject::AttachToObject(CObject* pObject) { ((void(__thiscall*)(CObject*, CObject*))GetAddress(0xA2C60))(this, pObject); } void CObject::Rotate(CVector vRotation) { ((void(__thiscall*)(CObject*, CVector))GetAddress(0xA2D60))(this, vRotation); } void CObject::Process(float fTimeElapsed) { ((void(__thiscall*)(CObject*, float))GetAddress(0xA3F70))(this, fTimeElapsed); } void CObject::SetAttachedToVehicle(ID nId, const CVector* pOffset, const CVector* pRotation) { ((void(__thiscall*)(CObject*, ID, const CVector*, const CVector*))GetAddress(0xA2AB0))(this, nId, pOffset, pRotation); } void CObject::SetAttachedToObject(ID nId, const CVector* pOffset, const CVector* pRotation, char a5) { ((void(__thiscall*)(CObject*, ID, const CVector*, const CVector*, char))GetAddress(0xA2B40))(this, nId, pOffset, pRotation, a5); } BOOL CObject::AttachedToMovingEntity() { return ((BOOL(__thiscall*)(CObject*))GetAddress(0xA2E60))(this); } void CObject::SetMaterial(int nModel, int nIndex, const char* szTxd, const char* szTexture, D3DCOLOR color) { ((void(__thiscall*)(CObject*, int, int, const char*, const char*, D3DCOLOR))GetAddress(0xA2ED0))(this, nModel, nIndex, szTxd, szTexture, color); } void CObject::SetMaterialText(int nIndex, const char* szText, char nMaterialSize, const char* szFont, char nFontSize, bool bBold, D3DCOLOR fontColor, D3DCOLOR backgroundColor, char align) { ((void(__thiscall*)(CObject*, int, const char*, char, const char*, char, bool, D3DCOLOR, D3DCOLOR, char))GetAddress(0xA3050))(this, nIndex, szText, nMaterialSize, szFont, nFontSize, bBold, fontColor, backgroundColor, align); } bool CObject::GetMaterialSize(int nSize, int* x, int* y) { return ((bool(__thiscall*)(CObject*, int, int*, int*))GetAddress(0xA3620))(this, nSize, x, y); } void CObject::Render() { ((void(__thiscall*)(CObject*))GetAddress(0xA3900))(this); } void CObject::ConstructMaterialText() { ((void(__thiscall*)(CObject*))GetAddress(0xA47F0))(this); } void CObject::Draw() { ((void(__thiscall*)(CObject*))GetAddress(0xA48A0))(this); } void CObject::ShutdownMaterialText() { ((void(__thiscall*)(CObject*))GetAddress(0xA3870))(this); } SAMPAPI_END
36.644444
228
0.720133
[ "render" ]
8d0b959d0373cca16ba2ee426ca991be6cf0b3a1
8,989
cpp
C++
3rdparty/webkit/Source/WebCore/page/History.cpp
mchiasson/PhaserNative
f867454602c395484bf730a7c43b9c586c102ac2
[ "MIT" ]
null
null
null
3rdparty/webkit/Source/WebCore/page/History.cpp
mchiasson/PhaserNative
f867454602c395484bf730a7c43b9c586c102ac2
[ "MIT" ]
null
null
null
3rdparty/webkit/Source/WebCore/page/History.cpp
mchiasson/PhaserNative
f867454602c395484bf730a7c43b9c586c102ac2
[ "MIT" ]
1
2019-01-25T13:55:25.000Z
2019-01-25T13:55:25.000Z
/* * Copyright (C) 2007 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. 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 "config.h" #include "History.h" #include "BackForwardController.h" #include "Document.h" #include "Frame.h" #include "FrameLoader.h" #include "FrameLoaderClient.h" #include "HistoryController.h" #include "HistoryItem.h" #include "Logging.h" #include "MainFrame.h" #include "NavigationScheduler.h" #include "Page.h" #include "ScriptController.h" #include "SecurityOrigin.h" #include <wtf/CheckedArithmetic.h> #include <wtf/MainThread.h> namespace WebCore { History::History(Frame& frame) : DOMWindowProperty(&frame) { } unsigned History::length() const { if (!m_frame) return 0; auto* page = m_frame->page(); if (!page) return 0; return page->backForward().count(); } ExceptionOr<History::ScrollRestoration> History::scrollRestoration() const { if (!m_frame) return Exception { SecurityError }; auto* historyItem = m_frame->loader().history().currentItem(); if (!historyItem) return ScrollRestoration::Auto; return historyItem->shouldRestoreScrollPosition() ? ScrollRestoration::Auto : ScrollRestoration::Manual; } ExceptionOr<void> History::setScrollRestoration(ScrollRestoration scrollRestoration) { if (!m_frame) return Exception { SecurityError }; auto* historyItem = m_frame->loader().history().currentItem(); if (historyItem) historyItem->setShouldRestoreScrollPosition(scrollRestoration == ScrollRestoration::Auto); return { }; } SerializedScriptValue* History::state() { m_lastStateObjectRequested = stateInternal(); return m_lastStateObjectRequested.get(); } SerializedScriptValue* History::stateInternal() const { if (!m_frame) return nullptr; auto* historyItem = m_frame->loader().history().currentItem(); if (!historyItem) return nullptr; return historyItem->stateObject(); } bool History::stateChanged() const { return m_lastStateObjectRequested != stateInternal(); } bool History::isSameAsCurrentState(SerializedScriptValue* state) const { return state == stateInternal(); } void History::back() { go(-1); } void History::back(Document& document) { go(document, -1); } void History::forward() { go(1); } void History::forward(Document& document) { go(document, 1); } void History::go(int distance) { LOG(History, "History %p go(%d) frame %p (main frame %d)", this, distance, m_frame, m_frame ? m_frame->isMainFrame() : false); if (!m_frame) return; m_frame->navigationScheduler().scheduleHistoryNavigation(distance); } void History::go(Document& document, int distance) { LOG(History, "History %p go(%d) in document %p frame %p (main frame %d)", this, distance, &document, m_frame, m_frame ? m_frame->isMainFrame() : false); if (!m_frame) return; ASSERT(isMainThread()); if (!document.canNavigate(m_frame)) return; m_frame->navigationScheduler().scheduleHistoryNavigation(distance); } URL History::urlForState(const String& urlString) { URL baseURL = m_frame->document()->baseURL(); if (urlString.isEmpty()) return baseURL; return URL(baseURL, urlString); } ExceptionOr<void> History::stateObjectAdded(RefPtr<SerializedScriptValue>&& data, const String& title, const String& urlString, StateObjectType stateObjectType) { // Each unique main-frame document is only allowed to send 64MB of state object payload to the UI client/process. static uint32_t totalStateObjectPayloadLimit = 0x4000000; static Seconds stateObjectTimeSpan { 30_s }; static unsigned perStateObjectTimeSpanLimit = 100; if (!m_frame || !m_frame->page()) return { }; URL fullURL = urlForState(urlString); if (!fullURL.isValid()) return Exception { SecurityError }; const URL& documentURL = m_frame->document()->url(); auto createBlockedURLSecurityErrorWithMessageSuffix = [&] (const char* suffix) { const char* functionName = stateObjectType == StateObjectType::Replace ? "history.replaceState()" : "history.pushState()"; return Exception { SecurityError, makeString("Blocked attempt to use ", functionName, " to change session history URL from ", documentURL.stringCenterEllipsizedToLength(), " to ", fullURL.stringCenterEllipsizedToLength(), ". ", suffix) }; }; if (!protocolHostAndPortAreEqual(fullURL, documentURL) || fullURL.user() != documentURL.user() || fullURL.pass() != documentURL.pass()) return createBlockedURLSecurityErrorWithMessageSuffix("Protocols, domains, ports, usernames, and passwords must match."); if (!m_frame->document()->securityOrigin().canRequest(fullURL) && (fullURL.path() != documentURL.path() || fullURL.query() != documentURL.query())) return createBlockedURLSecurityErrorWithMessageSuffix("Paths and fragments must match for a sandboxed document."); Document* mainDocument = m_frame->page()->mainFrame().document(); History* mainHistory = nullptr; if (mainDocument) { if (auto* mainDOMWindow = mainDocument->domWindow()) mainHistory = mainDOMWindow->history(); } if (!mainHistory) return { }; WallTime currentTimestamp = WallTime::now(); if (currentTimestamp - mainHistory->m_currentStateObjectTimeSpanStart > stateObjectTimeSpan) { mainHistory->m_currentStateObjectTimeSpanStart = currentTimestamp; mainHistory->m_currentStateObjectTimeSpanObjectsAdded = 0; } if (mainHistory->m_currentStateObjectTimeSpanObjectsAdded >= perStateObjectTimeSpanLimit) { if (stateObjectType == StateObjectType::Replace) return Exception { SecurityError, String::format("Attempt to use history.replaceState() more than %u times per %f seconds", perStateObjectTimeSpanLimit, stateObjectTimeSpan.seconds()) }; return Exception { SecurityError, String::format("Attempt to use history.pushState() more than %u times per %f seconds", perStateObjectTimeSpanLimit, stateObjectTimeSpan.seconds()) }; } Checked<unsigned> titleSize = title.length(); titleSize *= 2; Checked<unsigned> urlSize = fullURL.string().length(); urlSize *= 2; Checked<uint64_t> payloadSize = titleSize; payloadSize += urlSize; payloadSize += data ? data->data().size() : 0; Checked<uint64_t> newTotalUsage = mainHistory->m_totalStateObjectUsage; if (stateObjectType == StateObjectType::Replace) newTotalUsage -= m_mostRecentStateObjectUsage; newTotalUsage += payloadSize; if (newTotalUsage > totalStateObjectPayloadLimit) { if (stateObjectType == StateObjectType::Replace) return Exception { QuotaExceededError, ASCIILiteral("Attempt to store more data than allowed using history.replaceState()") }; return Exception { QuotaExceededError, ASCIILiteral("Attempt to store more data than allowed using history.pushState()") }; } m_mostRecentStateObjectUsage = payloadSize.unsafeGet(); mainHistory->m_totalStateObjectUsage = newTotalUsage.unsafeGet(); ++mainHistory->m_currentStateObjectTimeSpanObjectsAdded; if (!urlString.isEmpty()) m_frame->document()->updateURLForPushOrReplaceState(fullURL); if (stateObjectType == StateObjectType::Push) { m_frame->loader().history().pushState(WTFMove(data), title, fullURL.string()); m_frame->loader().client().dispatchDidPushStateWithinPage(); } else if (stateObjectType == StateObjectType::Replace) { m_frame->loader().history().replaceState(WTFMove(data), title, fullURL.string()); m_frame->loader().client().dispatchDidReplaceStateWithinPage(); } return { }; } } // namespace WebCore
35.25098
246
0.714317
[ "object" ]
8d1471e961c9228c4495affaca15eb055bdc7f0f
7,797
cc
C++
src/win32/base/deleter.cc
dancerj/mozc
a5a4927c1f709d2ff0c681585c746f73a434e4c9
[ "BSD-3-Clause" ]
null
null
null
src/win32/base/deleter.cc
dancerj/mozc
a5a4927c1f709d2ff0c681585c746f73a434e4c9
[ "BSD-3-Clause" ]
1
2021-06-30T14:59:51.000Z
2021-06-30T15:31:56.000Z
src/win32/base/deleter.cc
dancerj/mozc
a5a4927c1f709d2ff0c681585c746f73a434e4c9
[ "BSD-3-Clause" ]
1
2022-03-25T09:01:39.000Z
2022-03-25T09:01:39.000Z
// Copyright 2010-2020, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "win32/base/deleter.h" #include <deque> #include <vector> #include "base/logging.h" #include "protocol/commands.pb.h" #include "win32/base/input_state.h" #include "win32/base/keyboard.h" namespace mozc { namespace win32 { class VKBackBasedDeleterQueue : public std::deque<std::pair<VKBackBasedDeleter::DeletionWaitState, VKBackBasedDeleter::ClientAction>> {}; VKBackBasedDeleter::VKBackBasedDeleter() : wait_queue_(new VKBackBasedDeleterQueue), keyboard_(Win32KeyboardInterface::CreateDefault()), pending_ime_state_(new InputState()), pending_output_(new mozc::commands::Output()) {} VKBackBasedDeleter::VKBackBasedDeleter(Win32KeyboardInterface *keyboard_mock) : wait_queue_(new VKBackBasedDeleterQueue), keyboard_(keyboard_mock), pending_ime_state_(new InputState()), pending_output_(new mozc::commands::Output()) {} VKBackBasedDeleter::~VKBackBasedDeleter() {} void VKBackBasedDeleter::BeginDeletion(int deletion_count, const mozc::commands::Output &output, const InputState &ime_state) { std::vector<INPUT> inputs; wait_queue_->clear(); *pending_ime_state_ = InputState(); pending_output_->Clear(); if (deletion_count == 0) { return; } *pending_ime_state_ = ime_state; pending_output_->CopyFrom(output); wait_queue_->push_back( std::make_pair(WAIT_INITIAL_VK_BACK_TESTDOWN, SEND_KEY_TO_APPLICATION)); wait_queue_->push_back( std::make_pair(WAIT_VK_BACK_TESTUP, SEND_KEY_TO_APPLICATION)); for (int i = 1; i < deletion_count; ++i) { wait_queue_->push_back( std::make_pair(WAIT_VK_BACK_TESTDOWN, SEND_KEY_TO_APPLICATION)); wait_queue_->push_back( std::make_pair(WAIT_VK_BACK_TESTUP, SEND_KEY_TO_APPLICATION)); } wait_queue_->push_back(std::make_pair(WAIT_VK_BACK_TESTDOWN, CONSUME_KEY_BUT_NEVER_SEND_TO_SERVER)); wait_queue_->push_back( std::make_pair(WAIT_VK_BACK_DOWN, APPLY_PENDING_STATUS)); wait_queue_->push_back(std::make_pair(WAIT_VK_BACK_TESTUP, CONSUME_KEY_BUT_NEVER_SEND_TO_SERVER)); wait_queue_->push_back(std::make_pair( WAIT_VK_BACK_UP, CALL_END_DELETION_BUT_NEVER_SEND_TO_SERVER)); const KEYBDINPUT keyboard_input = {VK_BACK, 0, 0, 0, 0}; INPUT keydown = {}; keydown.type = INPUT_KEYBOARD; keydown.ki = keyboard_input; INPUT keyup = keydown; keyup.type = INPUT_KEYBOARD; keyup.ki.dwFlags = KEYEVENTF_KEYUP; for (size_t i = 0; i < deletion_count; ++i) { inputs.push_back(keydown); inputs.push_back(keyup); } inputs.push_back(keydown); // Sentinel Keydown inputs.push_back(keyup); // Sentinel Keyup UnsetModifiers(); keyboard_->SendInput(inputs); } VKBackBasedDeleter::ClientAction VKBackBasedDeleter::OnKeyEvent( UINT vk, bool is_keydown, bool is_test_key) { // Default action when no auto-deletion is ongoing. if (!IsDeletionOngoing()) { return DO_DEFAULT_ACTION; } // Hereafter, auto-deletion is ongoing. const std::pair<DeletionWaitState, ClientAction> next = wait_queue_->front(); if (next.first == WAIT_INITIAL_VK_BACK_TESTDOWN) { if ((vk == VK_BACK) && is_keydown && is_test_key) { wait_queue_->pop_front(); return next.second; } else { // Do not pop front. return DO_DEFAULT_ACTION; } } wait_queue_->pop_front(); bool matched = false; switch (next.first) { case WAIT_VK_BACK_TESTDOWN: matched = ((vk == VK_BACK) && is_keydown && is_test_key); break; case WAIT_VK_BACK_TESTUP: matched = ((vk == VK_BACK) && !is_keydown && is_test_key); break; case WAIT_VK_BACK_DOWN: matched = ((vk == VK_BACK) && is_keydown && !is_test_key); break; case WAIT_VK_BACK_UP: matched = ((vk == VK_BACK) && !is_keydown && !is_test_key); break; default: DLOG(FATAL) << "unexpected state found"; break; } if (matched) { return next.second; } return CALL_END_DELETION_THEN_DO_DEFAULT_ACTION; } void VKBackBasedDeleter::UnsetModifiers() { // Ensure that Shift, Control, and Alt key do not affect generated key // events. See b/3419452 for details. // TODO(yukawa): Use 3rd argument of ImeToAsciiEx to obtain the keyboard // state instead of GetKeyboardState API. // TODO(yukawa): Update VKBackBasedDeleter to consider this case. KeyboardStatus keyboard_state; if (!keyboard_->GetKeyboardState(&keyboard_state)) { return; } // If any side-effect is found, we might want to clear only the highest // bit. const BYTE kUnsetState = 0; bool to_be_updated = false; if (keyboard_state.IsPressed(VK_SHIFT)) { to_be_updated = true; keyboard_state.SetState(VK_SHIFT, kUnsetState); } if (keyboard_state.IsPressed(VK_CONTROL)) { to_be_updated = true; keyboard_state.SetState(VK_CONTROL, kUnsetState); } if (keyboard_state.IsPressed(VK_MENU)) { to_be_updated = true; keyboard_state.SetState(VK_MENU, kUnsetState); } if (to_be_updated) { keyboard_->SetKeyboardState(keyboard_state); } } void VKBackBasedDeleter::EndDeletion() { bool to_be_updated = false; KeyboardStatus keyboard_state; if (!keyboard_->GetKeyboardState(&keyboard_state)) { return; } const BYTE kPressed = 0x80; if (keyboard_->AsyncIsKeyPressed(VK_SHIFT)) { to_be_updated = true; keyboard_state.SetState(VK_SHIFT, kPressed); } if (keyboard_->AsyncIsKeyPressed(VK_CONTROL)) { to_be_updated = true; keyboard_state.SetState(VK_CONTROL, kPressed); } if (keyboard_->AsyncIsKeyPressed(VK_MENU)) { to_be_updated = true; keyboard_state.SetState(VK_MENU, kPressed); } if (to_be_updated) { keyboard_->SetKeyboardState(keyboard_state); } wait_queue_->clear(); } bool VKBackBasedDeleter::IsDeletionOngoing() const { return !wait_queue_->empty(); } const mozc::commands::Output &VKBackBasedDeleter::pending_output() const { return *pending_output_; } const InputState &VKBackBasedDeleter::pending_ime_state() const { return *pending_ime_state_; } } // namespace win32 } // namespace mozc
32.898734
79
0.709247
[ "vector" ]
8d16cd45d02f29326c26dc76b8fc7b9e2655af8a
32,746
cpp
C++
tests/tests.cpp
catid/fp61
2eddbeaa19f3b838a833b1a2ba256d32aa9bfaa5
[ "BSD-3-Clause" ]
8
2018-07-30T01:33:53.000Z
2021-01-26T21:12:42.000Z
tests/tests.cpp
catid/fp61
2eddbeaa19f3b838a833b1a2ba256d32aa9bfaa5
[ "BSD-3-Clause" ]
1
2018-08-13T05:33:47.000Z
2018-08-15T22:05:33.000Z
tests/tests.cpp
catid/fp61
2eddbeaa19f3b838a833b1a2ba256d32aa9bfaa5
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2018 Christopher A. Taylor. 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 Fp61 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "../fp61.h" #include <iostream> #include <iomanip> #include <sstream> #include <vector> using namespace std; //------------------------------------------------------------------------------ // Portability macros // Compiler-specific debug break #if defined(_DEBUG) || defined(DEBUG) #define FP61_DEBUG #ifdef _WIN32 #define FP61_DEBUG_BREAK() __debugbreak() #else #define FP61_DEBUG_BREAK() __builtin_trap() #endif #define FP61_DEBUG_ASSERT(cond) { if (!(cond)) { FP61_DEBUG_BREAK(); } } #else #define FP61_DEBUG_BREAK() do {} while (false); #define FP61_DEBUG_ASSERT(cond) do {} while (false); #endif //------------------------------------------------------------------------------ // Constants #define FP61_RET_FAIL -1 #define FP61_RET_SUCCESS 0 static const uint64_t MASK61 = ((uint64_t)1 << 61) - 1; static const uint64_t MASK62 = ((uint64_t)1 << 62) - 1; static const uint64_t MASK63 = ((uint64_t)1 << 63) - 1; static const uint64_t MASK64 = ~(uint64_t)0; static const uint64_t MASK64_NO62 = MASK64 ^ ((uint64_t)1 << 62); static const uint64_t MASK64_NO61 = MASK64 ^ ((uint64_t)1 << 61); static const uint64_t MASK64_NO60 = MASK64 ^ ((uint64_t)1 << 60); static const uint64_t MASK63_NO61 = MASK63 ^ ((uint64_t)1 << 61); static const uint64_t MASK63_NO60 = MASK63 ^ ((uint64_t)1 << 60); static const uint64_t MASK62_NO60 = MASK62 ^ ((uint64_t)1 << 60); #if defined(FP61_DEBUG) static const unsigned kRandomTestLoops = 100000; static const unsigned kMaxDataLength = 4000; #else static const unsigned kRandomTestLoops = 10000000; static const unsigned kMaxDataLength = 10000; #endif //------------------------------------------------------------------------------ // Tools static std::string HexString(uint64_t x) { std::stringstream ss; ss << hex << setfill('0') << setw(16) << x; return ss.str(); } //------------------------------------------------------------------------------ // Tests: Negate static bool test_negate(uint64_t x) { uint64_t n = fp61::Negate(x); uint64_t s = (x + n) % fp61::kPrime; if (s != 0) { cout << "Failed for x = " << hex << HexString(x) << endl; FP61_DEBUG_BREAK(); return false; } return true; } static bool TestNegate() { cout << "TestNegate..."; // Input is allowed to be 0 <= x <= p for (uint64_t x = 0; x < 1000; ++x) { if (!test_negate(x)) { return false; } } for (uint64_t x = fp61::kPrime; x >= fp61::kPrime - 1000; --x) { if (!test_negate(x)) { return false; } } fp61::Random prng; prng.Seed(1); for (unsigned i = 0; i < kRandomTestLoops; ++i) { uint64_t x = prng.Next() & fp61::kPrime; if (!test_negate(x)) { return false; } } cout << "Passed" << endl; return true; } //------------------------------------------------------------------------------ // Tests: Add static bool TestAdd() { cout << "TestAdd..."; // Preconditions: x,y,z,w <2^62 const uint64_t largest = ((uint64_t)1 << 62) - 1; const uint64_t reduced = largest % fp61::kPrime; for (uint64_t x = largest; x >= largest - 1000; --x) { uint64_t r = fp61::Add4(largest, largest, largest, x); uint64_t expected = 0; expected = (expected + reduced) % fp61::kPrime; expected = (expected + reduced) % fp61::kPrime; expected = (expected + reduced) % fp61::kPrime; expected = (expected + (x % fp61::kPrime)) % fp61::kPrime; if (r % fp61::kPrime != expected) { cout << "Failed for x = " << HexString(x) << endl; FP61_DEBUG_BREAK(); return false; } } for (uint64_t x = largest; x >= largest - 1000; --x) { for (uint64_t y = largest; y >= largest - 1000; --y) { uint64_t r = fp61::Add4(largest, largest, x, y); uint64_t expected = 0; expected = (expected + reduced) % fp61::kPrime; expected = (expected + reduced) % fp61::kPrime; expected = (expected + (y % fp61::kPrime)) % fp61::kPrime; expected = (expected + (x % fp61::kPrime)) % fp61::kPrime; if (r % fp61::kPrime != expected) { cout << "Failed for x=" << HexString(x) << " y=" << HexString(y) << endl; FP61_DEBUG_BREAK(); return false; } } } fp61::Random prng; prng.Seed(0); for (unsigned i = 0; i < kRandomTestLoops; ++i) { // Select 4 values from 0..2^62-1 uint64_t x = prng.Next() & MASK62; uint64_t y = prng.Next() & MASK62; uint64_t w = prng.Next() & MASK62; uint64_t z = prng.Next() & MASK62; uint64_t r = fp61::Add4(x, y, z, w); uint64_t expected = 0; expected = (expected + (x % fp61::kPrime)) % fp61::kPrime; expected = (expected + (y % fp61::kPrime)) % fp61::kPrime; expected = (expected + (z % fp61::kPrime)) % fp61::kPrime; expected = (expected + (w % fp61::kPrime)) % fp61::kPrime; if (r % fp61::kPrime != expected) { cout << "Failed (random) for i = " << i << endl; FP61_DEBUG_BREAK(); return false; } } cout << "Passed" << endl; return true; } //------------------------------------------------------------------------------ // Tests: Partial Reduction static bool test_pred(uint64_t x) { uint64_t expected = x % fp61::kPrime; uint64_t r = fp61::PartialReduce(x); if ((r >> 62) != 0) { cout << "High bit overflow failed for x=" << HexString(x) << endl; FP61_DEBUG_BREAK(); return false; } uint64_t actual = fp61::PartialReduce(x) % fp61::kPrime; if (actual != expected) { cout << "Failed for x=" << HexString(x) << endl; FP61_DEBUG_BREAK(); return false; } return true; } static bool TestPartialReduction() { cout << "TestPartialReduction..."; // Input can have any bit set for (uint64_t x = 0; x < 1000; ++x) { if (!test_pred(x)) { return false; } } for (uint64_t x = MASK64; x > MASK64 - 1000; --x) { if (!test_pred(x)) { return false; } } for (uint64_t x = MASK64_NO62 + 1000; x > MASK64_NO62 - 1000; --x) { if (!test_pred(x)) { return false; } } for (uint64_t x = MASK64_NO61 + 1000; x > MASK64_NO61 - 1000; --x) { if (!test_pred(x)) { return false; } } for (uint64_t x = MASK64_NO60 + 1000; x > MASK64_NO60 - 1000; --x) { if (!test_pred(x)) { return false; } } for (uint64_t x = MASK63; x > MASK63 - 1000; --x) { if (!test_pred(x)) { return false; } } for (uint64_t x = MASK63_NO61 + 1000; x > MASK63_NO61 - 1000; --x) { if (!test_pred(x)) { return false; } } for (uint64_t x = MASK63_NO60 + 1000; x > MASK63_NO60 - 1000; --x) { if (!test_pred(x)) { return false; } } for (uint64_t x = MASK62 + 1000; x > MASK62 - 1000; --x) { if (!test_pred(x)) { return false; } } for (uint64_t x = MASK62_NO60 + 1000; x > MASK62_NO60 - 1000; --x) { if (!test_pred(x)) { return false; } } for (uint64_t x = MASK61 + 1000; x > MASK61 - 1000; --x) { if (!test_pred(x)) { return false; } } fp61::Random prng; prng.Seed(2); for (unsigned i = 0; i < kRandomTestLoops; ++i) { uint64_t x = prng.Next(); if (!test_pred(x)) { return false; } } cout << "Passed" << endl; return true; } //------------------------------------------------------------------------------ // Tests: Finalize Reduction static bool test_fred(uint64_t x) { // EXCEPTION: This input is known to not work if (x == 0x3ffffffffffffffeULL) { return true; } uint64_t actual = fp61::Finalize(x); uint64_t expected = x % fp61::kPrime; if (actual != expected) { cout << "Failed for x=" << HexString(x) << endl; FP61_DEBUG_BREAK(); return false; } return true; } static bool TestFinalizeReduction() { cout << "TestFinalizeReduction..."; // Input has #63 and #62 clear, other bits can take on any value for (uint64_t x = 0; x < 1000; ++x) { if (!test_fred(x)) { return false; } } for (uint64_t x = MASK62; x > MASK62 - 1000; --x) { if (!test_fred(x)) { return false; } } for (uint64_t x = MASK62_NO60 + 1000; x > MASK62_NO60 - 1000; --x) { if (!test_fred(x)) { return false; } } for (uint64_t x = MASK61 + 1000; x > MASK61 - 1000; --x) { if (!test_fred(x)) { return false; } } fp61::Random prng; prng.Seed(3); for (unsigned i = 0; i < kRandomTestLoops; ++i) { uint64_t x = prng.Next() & MASK62; if (!test_fred(x)) { return false; } } cout << "Passed" << endl; return true; } //------------------------------------------------------------------------------ // Tests: Multiply static bool test_mul(uint64_t x, uint64_t y) { uint64_t p = fp61::Multiply(x, y); if ((p >> 62) != 0) { cout << "Failed (high bit overflow) for x=" << HexString(x) << ", y=" << HexString(y) << endl; FP61_DEBUG_BREAK(); return false; } uint64_t r0, r1; CAT_MUL128(r1, r0, x, y); //A % B == (((AH % B) * (2^64 % B)) + (AL % B)) % B // == (((AH % B) * ((2^64 - B) % B)) + (AL % B)) % B r1 %= fp61::kPrime; uint64_t NB = (uint64_t)(-(int64_t)fp61::kPrime); uint64_t mod = r1 * (NB % fp61::kPrime); mod += r0 % fp61::kPrime; mod %= fp61::kPrime; if (p % fp61::kPrime != mod) { cout << "Failed (reduced result mismatch) for x=" << HexString(x) << ", y=" << HexString(y) << endl; FP61_DEBUG_BREAK(); return false; } return true; } static bool TestMultiply() { cout << "TestMultiply..."; // Number of bits between x, y must be 124 or fewer. for (uint64_t x = 0; x < 1000; ++x) { for (uint64_t y = x; y < 1000; ++y) { if (!test_mul(x, y)) { return false; } } } for (uint64_t x = MASK62; x > MASK62 - 1000; --x) { for (uint64_t y = x; y > MASK62 - 1000; --y) { if (!test_mul(x, y)) { return false; } } } for (uint64_t x = MASK62_NO60 + 1000; x > MASK62_NO60 - 1000; --x) { for (uint64_t y = x; y > MASK62_NO60 - 1000; --y) { if (!test_mul(x, y)) { return false; } } } for (uint64_t x = MASK61 + 1000; x > MASK61 - 1000; --x) { for (uint64_t y = x; y > MASK61 - 1000; --y) { if (!test_mul(x, y)) { return false; } } } fp61::Random prng; prng.Seed(4); // 62 + 62 = 124 bits for (unsigned i = 0; i < kRandomTestLoops; ++i) { uint64_t x = prng.Next() & MASK62; uint64_t y = prng.Next() & MASK62; if (!test_mul(x, y)) { return false; } } // 61 + 63 = 124 bits for (unsigned i = 0; i < kRandomTestLoops; ++i) { uint64_t x = prng.Next() & MASK61; uint64_t y = prng.Next() & MASK63; if (!test_mul(x, y)) { return false; } } // Commutivity test for (unsigned i = 0; i < kRandomTestLoops; ++i) { uint64_t x = prng.Next() & MASK62; uint64_t y = prng.Next() & MASK62; uint64_t z = prng.Next() & MASK62; uint64_t r = fp61::Finalize(fp61::Multiply(fp61::Multiply(z, y), x)); uint64_t s = fp61::Finalize(fp61::Multiply(fp61::Multiply(x, z), y)); uint64_t t = fp61::Finalize(fp61::Multiply(fp61::Multiply(x, y), z)); if (r != s || s != t) { cout << "Failed (does not commute) for i=" << i << endl; FP61_DEBUG_BREAK(); return false; } } // Direct function test uint64_t r1, r0; r0 = Emulate64x64to128(r1, MASK64, MASK64); if (r1 != 0xfffffffffffffffe || r0 != 1) { cout << "Failed (Emulate64x64to128 failed)" << endl; FP61_DEBUG_BREAK(); return false; } cout << "Passed" << endl; return true; } //------------------------------------------------------------------------------ // Tests: Inverse static bool test_inv(uint64_t x) { uint64_t i = fp61::Inverse(x); // If no inverse existed: if (i == 0) { // Then it must have evenly divided if (x % fp61::kPrime == 0) { return true; } // Otherwise this should have had a result cout << "Failed (no result) for x=" << HexString(x) << endl; FP61_DEBUG_BREAK(); return false; } // Result must be in Fp if (i >= fp61::kPrime) { cout << "Failed (result too large) for x=" << HexString(x) << endl; FP61_DEBUG_BREAK(); return false; } // mul requires partially reduced input x = fp61::PartialReduce(x); uint64_t p = fp61::Multiply(x, i); // If result is not 1 then it is not a multiplicative inverse if (fp61::Finalize(p) != 1) { cout << "Failed (finalized result not 1) for x=" << HexString(x) << endl; FP61_DEBUG_BREAK(); return false; } // Double check the reduce function... if (p % fp61::kPrime != 1) { cout << "Failed (remainder not 1) for x=" << HexString(x) << endl; FP61_DEBUG_BREAK(); return false; } return true; } static bool TestMulInverse() { cout << "TestMulInverse..."; // x < p // Small values for (uint64_t x = 1; x < 1000; ++x) { if (!test_inv(x)) { return false; } } fp61::Random prng; prng.Seed(5); for (unsigned i = 0; i < kRandomTestLoops; ++i) { uint64_t x = prng.Next(); if (!test_inv(x)) { return false; } } cout << "Passed" << endl; return true; } //------------------------------------------------------------------------------ // Tests: ByteReader bool test_byte_reader(const uint8_t* data, unsigned bytes) { fp61::ByteReader reader; reader.BeginRead(data, bytes); // Round up to the next 61 bits uint64_t expandedBits = bytes * 8; unsigned actualReads = 0; unsigned bits = 0; bool packed = false; unsigned packedBit = 0; uint64_t fp; while (fp61::ReadResult::Success == reader.Read(fp)) { unsigned readStart = bits / 8; if (readStart >= bytes) { // We can read one extra bit if the packing is the last thing if (!packed || readStart != bytes) { FP61_DEBUG_BREAK(); cout << "Failed (too many reads) for bytes=" << bytes << " actualReads=" << actualReads << endl; return false; } } int readBytes = (int)bytes - (int)readStart; if (readBytes < 0) { readBytes = 0; } else if (readBytes > 8) { readBytes = 8; } uint64_t x = fp61::ReadBytes_LE(data + readStart, readBytes) >> (bits % 8); int readBits = (readBytes * 8) - (bits % 8); if (readBytes >= 8 && readBits > 0 && readBits < 61 && readStart + readBytes < bytes) { // Need to read one more byte sometimes uint64_t high = data[readStart + readBytes]; high <<= readBits; x |= high; } // Test packing if (packed) { x <<= 1; x |= packedBit; bits += 60; ++expandedBits; } else { bits += 61; } x &= fp61::kPrime; packed = fp61::IsU64Ambiguous(x); if (packed) { packedBit = (x == fp61::kPrime); x = fp61::kAmbiguityMask; } if (fp != x) { FP61_DEBUG_BREAK(); cout << "Failed (wrong value) for bytes=" << bytes << " actualReads=" << actualReads << endl; return false; } ++actualReads; } const unsigned expectedReads = (unsigned)((expandedBits + 60) / 61); if (actualReads != expectedReads) { FP61_DEBUG_BREAK(); cout << "Failed (read count wrong) for bytes=" << bytes << endl; return false; } const unsigned maxWords = fp61::ByteReader::MaxWords(bytes); if (maxWords < actualReads) { FP61_DEBUG_BREAK(); cout << "Failed (MaxWords wrong) for bytes=" << bytes << endl; return false; } return true; } bool TestByteReader() { cout << "TestByteReader..."; uint8_t data[10 + 8] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 0, 0, 0, 0, 0, 0, 0, 0 // Padding to simplify test }; uint64_t w = fp61::ReadU64_LE(data); if (w != 0x0807060504030201ULL) { cout << "Failed (ReadU64_LE)" << endl; FP61_DEBUG_BREAK(); return false; } uint32_t u = fp61::ReadU32_LE(data); if (u != 0x04030201UL) { cout << "Failed (ReadU32_LE)" << endl; FP61_DEBUG_BREAK(); return false; } uint64_t z = fp61::ReadBytes_LE(data, 0); if (z != 0) { cout << "Failed (ReadBytes_LE 0)" << endl; FP61_DEBUG_BREAK(); return false; } for (unsigned i = 1; i <= 8; ++i) { uint64_t v = fp61::ReadBytes_LE(data, i); uint64_t d = v ^ w; d <<= 8 * (8 - i); if (d != 0) { cout << "Failed (ReadBytes_LE) for i = " << i << endl; FP61_DEBUG_BREAK(); return false; } } uint8_t simpledata[16 + 8] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0 }; for (unsigned i = 0; i <= 16; ++i) { if (!test_byte_reader(simpledata, i)) { return false; } } uint8_t allones[16 + 8] = { 254,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255, 0 }; for (unsigned i = 0; i <= 16; ++i) { if (!test_byte_reader(allones, i)) { return false; } } uint8_t mixed[20 + 8] = { 254,255,255,255,255,255,255,255,0, // Inject a non-overflowing bit in the middle 255,255,255,255,255,255,255, 255,255,255,255, 0 }; for (unsigned i = 0; i <= 16; ++i) { if (!test_byte_reader(allones, i)) { return false; } } vector<uint8_t> randBytes(kMaxDataLength + 8, 0); // +8 to avoid bounds checking fp61::Random prng; prng.Seed(10); for (unsigned i = 0; i < kMaxDataLength; ++i) { for (unsigned j = 0; j < 1; ++j) { // Fill the data with random bytes for (unsigned k = 0; k < i; k += 8) { uint64_t w; if (prng.Next() % 100 <= 3) { w = ~(uint64_t)0; } else { w = prng.Next(); } fp61::WriteU64_LE(&randBytes[k], w); } if (!test_byte_reader(&randBytes[0], i)) { return false; } } } cout << "Passed" << endl; return true; } //------------------------------------------------------------------------------ // Tests: Random static bool TestRandom() { cout << "TestRandom..."; for (int i = -1000; i < 1000; ++i) { uint64_t loWord = static_cast<int64_t>(i); loWord <<= 3; // Put it in the high bits uint64_t loResult = fp61::Random::ConvertRandToFp(loWord); if (loResult >= fp61::kPrime) { cout << "Failed (RandToFp low) at i = " << i << endl; FP61_DEBUG_BREAK(); return false; } uint64_t hiWord = fp61::kPrime + static_cast<int64_t>(i); hiWord <<= 3; // Put it in the high bits uint64_t hiResult = fp61::Random::ConvertRandToFp(hiWord); if (hiResult >= fp61::kPrime) { cout << "Failed (RandToFp high) at i = " << i << endl; FP61_DEBUG_BREAK(); return false; } } for (int i = -1000; i < 1000; ++i) { uint64_t loWord = static_cast<int64_t>(i); loWord <<= 3; // Put it in the high bits uint64_t loResult = fp61::Random::ConvertRandToNonzeroFp(loWord); if (loResult <= 0 || loResult >= fp61::kPrime) { cout << "Failed (RandToNonzeroFp low) at i = " << i << endl; FP61_DEBUG_BREAK(); return false; } uint64_t hiWord = fp61::kPrime + static_cast<int64_t>(i); hiWord <<= 3; // Put it in the high bits uint64_t hiResult = fp61::Random::ConvertRandToNonzeroFp(hiWord); if (hiResult <= 0 || hiResult >= fp61::kPrime) { cout << "Failed (RandToNonzeroFp high) at i = " << i << endl; FP61_DEBUG_BREAK(); return false; } } cout << "Passed" << endl; return true; } //------------------------------------------------------------------------------ // Tests: WordReader/WordWriter static bool TestWordSerialization() { cout << "TestWordSerialization..."; fp61::WordWriter writer; fp61::WordReader reader; fp61::Random prng; prng.Seed(11); std::vector<uint8_t> data; std::vector<uint64_t> wordData; for (unsigned i = 1; i < kMaxDataLength; ++i) { unsigned words = i; unsigned bytesNeeded = fp61::WordWriter::BytesNeeded(words); data.resize(bytesNeeded); wordData.resize(words); writer.BeginWrite(&data[0]); reader.BeginRead(&data[0], bytesNeeded); for (unsigned j = 0; j < words; ++j) { // Generate a value from 0..p because the writer technically does not care about staying within the field uint64_t w = prng.Next() & MASK61; wordData[j] = w; writer.Write(w); } writer.Flush(); for (unsigned j = 0; j < words; ++j) { uint64_t u = reader.Read(); if (u != wordData[j]) { cout << "Failed (readback failed) at i = " << i << " j = " << j << endl; FP61_DEBUG_BREAK(); return false; } } } cout << "Passed" << endl; return true; } //------------------------------------------------------------------------------ // Tests: ByteWriter bool TestByteWriter() { cout << "TestByteWriter..."; fp61::ByteReader reader; fp61::ByteWriter writer; fp61::Random prng; prng.Seed(14); std::vector<uint8_t> original, recovered; for (unsigned i = 1; i < kMaxDataLength; ++i) { unsigned bytes = i; for (unsigned j = 0; j < 10; ++j) { // Padding to simplify tester original.resize(bytes + 8); // Fill the data with random bytes for (unsigned k = 0; k < i; k += 8) { uint64_t w; if (prng.Next() % 100 <= 3) { w = ~(uint64_t)0; } else { w = prng.Next(); } fp61::WriteU64_LE(&original[k], w); } reader.BeginRead(&original[0], bytes); unsigned maxWords = fp61::ByteReader::MaxWords(bytes); unsigned maxBytes = fp61::ByteWriter::MaxBytesNeeded(maxWords); recovered.resize(maxBytes); writer.BeginWrite(&recovered[0]); // Write words we get directly back out uint64_t word; while (reader.Read(word) != fp61::ReadResult::Empty) { writer.Write(word); } unsigned writtenBytes = writer.Flush(); // TBD: Check if high bits are 0? if (writtenBytes > maxBytes || writtenBytes > bytes + 8) { cout << "Failed (byte count mismatch) at i = " << i << " j = " << j << endl; FP61_DEBUG_BREAK(); return false; } if (0 != memcmp(&recovered[0], &original[0], bytes)) { cout << "Failed (data corruption) at i = " << i << " j = " << j << endl; FP61_DEBUG_BREAK(); return false; } } } cout << "Passed" << endl; return true; } //------------------------------------------------------------------------------ // Tests: Integration // Tests all of the serialization/deserialization and some math code bool TestIntegration() { cout << "TestIntegration..."; std::vector<uint8_t> data, recovery, recovered; fp61::Random prng; prng.Seed(13); // Test a range of data sizes for (unsigned i = 1; i < kMaxDataLength; ++i) { unsigned bytes = i; // Run a few tests for each size for (unsigned j = 0; j < 10; ++j) { // Generate some test data: // Allocate padded data to simplify tester data.resize(bytes + 8); // Fill the data with random bytes for (unsigned k = 0; k < i; k += 8) { uint64_t w; if (prng.Next() % 100 <= 3) { w = ~(uint64_t)0; } else { w = prng.Next(); } fp61::WriteU64_LE(&data[k], w); } // Read data from the simulated packet, // perform some example Fp operation on it, // and then store it to a simulated recovery packet. // Preallocate enough space in recovery packets for the worst case const unsigned maxWords = fp61::ByteReader::MaxWords(bytes); recovery.resize(fp61::WordWriter::BytesNeeded(maxWords)); fp61::WordWriter recovery_writer; recovery_writer.BeginWrite(&recovery[0]); fp61::ByteReader original_reader; original_reader.BeginRead(&data[0], bytes); fp61::Random coeff_prng; coeff_prng.Seed(bytes + j * 500000); // Start reading words from the original file/packet, // multiplying them by a random coefficient, // and writing them to the recovery file/packet. uint64_t r; while (original_reader.Read(r) == fp61::ReadResult::Success) { // Pick random coefficient to multiply between 1..p-1 uint64_t coeff = coeff_prng.NextNonzeroFp(); // x = r * coeff (62 bits) uint64_t x = fp61::Multiply(r, coeff); // Finalize x (61 bits < p) uint64_t f = fp61::Finalize(x); // Write to recovery file/packet recovery_writer.Write(f); } // Flush the remaining bits to the recovery file/packet unsigned writtenRecoveryBytes = recovery_writer.Flush(); // Simulate reading data from the recovery file/packet // and recovering the original data: fp61::WordReader recovery_reader; recovery_reader.BeginRead(&recovery[0], writtenRecoveryBytes); // Allocate space for recovered data (may be up to 1.6% larger than needed) const unsigned recoveryWords = fp61::WordReader::WordCount(writtenRecoveryBytes); const unsigned maxBytes = fp61::ByteWriter::MaxBytesNeeded(recoveryWords); recovered.resize(maxBytes); fp61::ByteWriter original_writer; original_writer.BeginWrite(&recovered[0]); // Reproduce the same random sequence coeff_prng.Seed(bytes + j * 500000); // For each word to read: const unsigned readWords = fp61::WordReader::WordCount(writtenRecoveryBytes); for (unsigned i = 0; i < readWords; ++i) { // Pick random coefficient to multiply between 1..p-1 uint64_t coeff = coeff_prng.NextNonzeroFp(); uint64_t inv_coeff = fp61::Inverse(coeff); // Read the next word (61 bits) uint64_t f = recovery_reader.Read(); // Invert the multiplication (62 bits) uint64_t x = fp61::Multiply(f, inv_coeff); // Finalize x (61 bits < p) x = fp61::Finalize(x); // Write to recovered original data buffer original_writer.Write(x); } // Flush the remaining bits to the recovered original file/packet unsigned recoveredBytes = original_writer.Flush(); if (recoveredBytes > maxBytes || recoveredBytes > bytes + 8) { cout << "Failed (byte count mismatch) at i = " << i << " j = " << j << endl; FP61_DEBUG_BREAK(); return false; } if (0 != memcmp(&recovered[0], &data[0], bytes)) { cout << "Failed (data corruption) at i = " << i << " j = " << j << endl; FP61_DEBUG_BREAK(); return false; } } } cout << "Passed" << endl; return true; } //------------------------------------------------------------------------------ // Entrypoint int main() { cout << "Unit tester for Fp61. Exits with -1 on failure, 0 on success" << endl; cout << endl; int result = FP61_RET_SUCCESS; if (!TestByteWriter()) { result = FP61_RET_FAIL; } if (!TestIntegration()) { result = FP61_RET_FAIL; } if (!TestRandom()) { result = FP61_RET_FAIL; } if (!TestWordSerialization()) { result = FP61_RET_FAIL; } if (!TestNegate()) { result = FP61_RET_FAIL; } if (!TestAdd()) { result = FP61_RET_FAIL; } if (!TestPartialReduction()) { result = FP61_RET_FAIL; } if (!TestFinalizeReduction()) { result = FP61_RET_FAIL; } if (!TestMultiply()) { result = FP61_RET_FAIL; } if (!TestMulInverse()) { result = FP61_RET_FAIL; } if (!TestByteReader()) { result = FP61_RET_FAIL; } cout << endl; if (result == FP61_RET_FAIL) { cout << "*** Tests failed (see above)! Returning -1" << endl; } else { cout << "*** Tests succeeded! Returning 0" << endl; } return result; }
27.018152
117
0.50116
[ "vector" ]
8d1afb1b8368e99b135da16f8ec2dd782d4e881d
1,945
cpp
C++
IOTest/STLAsciiFileReaderTest.cpp
SatoshiMabuchi/Crystal
91b2d72e5544cf86183587d2cfea48ca7f390dd4
[ "MIT" ]
null
null
null
IOTest/STLAsciiFileReaderTest.cpp
SatoshiMabuchi/Crystal
91b2d72e5544cf86183587d2cfea48ca7f390dd4
[ "MIT" ]
null
null
null
IOTest/STLAsciiFileReaderTest.cpp
SatoshiMabuchi/Crystal
91b2d72e5544cf86183587d2cfea48ca7f390dd4
[ "MIT" ]
null
null
null
#include "gtest/gtest.h" #include "../Math/Vector3d.h" #include "../IO/STLAsciiFileReader.h" using namespace Crystal::Math; using namespace Crystal::IO; using T = float; namespace { std::stringstream getSampleAscii() { std::stringstream stream; stream << "solid cube-ascii" << std::endl << "facet normal 0.0 0.0 1.0" << std::endl << " outer loop" << std::endl << " vertex 0.0 0.0 1.0" << std::endl << " vertex 1.0 0.0 1.0" << std::endl << " vertex 0.0 1.0 1.0" << std::endl << "endloop" << std::endl << "endfacet" << std::endl << "facet normal 0.0 0.0 1.0" << std::endl << " outer loop" << std::endl << " vertex 1.0 1.0 1.0" << std::endl << " vertex 0.0 1.0 1.0" << std::endl << " vertex 1.0 0.0 1.0" << std::endl << " endloop" << std::endl << "endfacet" << std::endl << "endsolid" << std::endl; return stream; } } TEST(STLAsciiFileReaderTest, TestReadAscii) { std::stringstream stream = getSampleAscii(); STLAsciiFileReader reader; EXPECT_TRUE(reader.read(stream)); const auto& faces = reader.getFaces(); EXPECT_EQ(2, faces.size()); const auto& face1 = faces[0]; EXPECT_EQ( Vector3dd(0,0,1), face1.getNormal() ); EXPECT_EQ( Vector3dd(0,0,1), face1.getVertices()[0]); EXPECT_EQ( Vector3dd(1,0,1), face1.getVertices()[1]); EXPECT_EQ( Vector3dd(0,1,1), face1.getVertices()[2]); const auto& face2 = faces[1]; EXPECT_EQ( Vector3dd(0,0,1), face2.getNormal()); EXPECT_EQ( Vector3dd(1,1,1), face2.getVertices()[0]); EXPECT_EQ( Vector3dd(0,1,1), face2.getVertices()[1]); EXPECT_EQ( Vector3dd(1,0,1), face2.getVertices()[2]); /* const Vector3dd normal2(0.0, 0.0, 1.0); const std::vector< Vector3dd > positions2 = { Vector3dd(1.0, 1.0, 1.0), Vector3dd(0.0, 1.0, 1.0), Vector3dd(1.0, 0.0, 1.0) }; STLFile expected(cells, " cube-ascii"); EXPECT_EQ(expected, file); */ }
28.602941
55
0.59383
[ "vector", "solid" ]
8d1b593748156ad2f6d142872352d048411fff81
36,696
cpp
C++
src/WholeBodyStateDisplay.cpp
cmastalli/state_rviz_plugin
2fcefbd5167f260ba663a2817dbcc21024170235
[ "BSD-3-Clause" ]
1
2020-08-05T20:20:01.000Z
2020-08-05T20:20:01.000Z
src/WholeBodyStateDisplay.cpp
cmastalli/state_rviz_plugin
2fcefbd5167f260ba663a2817dbcc21024170235
[ "BSD-3-Clause" ]
1
2020-08-05T11:45:23.000Z
2020-08-06T10:14:30.000Z
src/WholeBodyStateDisplay.cpp
cmastalli/state_rviz_plugin
2fcefbd5167f260ba663a2817dbcc21024170235
[ "BSD-3-Clause" ]
null
null
null
/////////////////////////////////////////////////////////////////////////////// // BSD 3-Clause License // // Copyright (C) 2020-2021, University of Edinburgh, Istituto Italiano di // Tecnologia, University of Oxford. // Copyright note valid unless otherwise stated in individual files. // All rights reserved. /////////////////////////////////////////////////////////////////////////////// #include "whole_body_state_rviz_plugin/WholeBodyStateDisplay.h" #include "whole_body_state_rviz_plugin/PinocchioLinkUpdater.h" #include <Eigen/Dense> #include <QTimer> #include <pinocchio/algorithm/center-of-mass.hpp> #include <pinocchio/parsers/urdf.hpp> using namespace rviz; namespace whole_body_state_rviz_plugin { void linkUpdaterStatusFunction(rviz::StatusLevel level, const std::string &link_name, const std::string &text, WholeBodyStateDisplay *display) { display->setStatus(level, QString::fromStdString(link_name), QString::fromStdString(text)); } WholeBodyStateDisplay::WholeBodyStateDisplay() : has_new_msg_(false), initialized_model_(false), force_threshold_(0.), use_contact_status_in_cop_(true), use_contact_status_in_grf_(true), use_contact_status_in_support_(true), use_contact_status_in_friction_cone_(true), weight_(0.), gravity_(9.81), com_real_(true), com_enable_(true), cop_enable_(true), icp_enable_(true), cmp_enable_(true), grf_enable_(true), support_enable_(true), cone_enable_(true) { // Category Groups robot_category_ = new rviz::Property("Robot", QVariant(), "", this); com_category_ = new rviz::Property("Center Of Mass", QVariant(), "", this); cop_category_ = new rviz::Property("Center Of Pressure", QVariant(), "", this); icp_category_ = new rviz::Property("Instantaneous Capture Point", QVariant(), "", this); cmp_category_ = new rviz::Property("Centroidal Momentum Pivot", QVariant(), "", this); grf_category_ = new rviz::Property("Contact Forces", QVariant(), "", this); support_category_ = new rviz::Property("Support Region", QVariant(), "", this); friction_category_ = new rviz::Property("Friction Cone", QVariant(), "", this); // Robot properties robot_enable_property_ = new BoolProperty("Enable", true, "Enable/disable the target display", robot_category_, SLOT(updateRobotEnable()), this); robot_model_property_ = new StringProperty("Robot Description", "robot_description", "Name of the parameter to search for to load the robot description.", robot_category_, SLOT(updateRobotModel()), this); robot_visual_enabled_property_ = new Property("Robot Visual", true, "Whether to display the visual representation of the robot.", robot_category_, SLOT(updateRobotVisualVisible()), this); robot_collision_enabled_property_ = new Property("Robot Collision", false, "Whether to display the collision representation of the robot.", robot_category_, SLOT(updateRobotCollisionVisible()), this); robot_alpha_property_ = new FloatProperty("Robot Alpha", 1., "Amount of transparency to apply to the links.", robot_category_, SLOT(updateRobotAlpha()), this); robot_alpha_property_->setMin(0.0); robot_alpha_property_->setMax(1.0); // CoM position and velocity properties com_enable_property_ = new BoolProperty("Enable", true, "Enable/disable the CoM display", com_category_, SLOT(updateCoMEnable()), this); com_style_property_ = new EnumProperty("CoM Style", "Real", "The rendering operation to use to draw the CoM.", com_category_, SLOT(updateCoMStyle()), this); com_style_property_->addOption("Real", REAL); com_style_property_->addOption("Projected", PROJECTED); com_color_property_ = new rviz::ColorProperty("Color", QColor(255, 85, 0), "Color of a point", com_category_, SLOT(updateCoMColorAndAlpha()), this); com_alpha_property_ = new rviz::FloatProperty("Alpha", 1.0, "0 is fully transparent, 1.0 is fully opaque.", com_category_, SLOT(updateCoMColorAndAlpha()), this); com_alpha_property_->setMin(0); com_alpha_property_->setMax(1); com_radius_property_ = new rviz::FloatProperty("Radius", 0.04, "Radius of a point", com_category_, SLOT(updateCoMColorAndAlpha()), this); com_shaft_length_property_ = new FloatProperty("Shaft Length", 0.4, "Length of the arrow's shaft, in meters.", com_category_, SLOT(updateCoMArrowGeometry()), this); com_shaft_radius_property_ = new FloatProperty("Shaft Radius", 0.02, "Radius of the arrow's shaft, in meters.", com_category_, SLOT(updateCoMArrowGeometry()), this); com_head_length_property_ = new FloatProperty("Head Length", 0.08, "Length of the arrow's head, in meters.", com_category_, SLOT(updateCoMArrowGeometry()), this); com_head_radius_property_ = new FloatProperty("Head Radius", 0.04, "Radius of the arrow's head, in meters.", com_category_, SLOT(updateCoMArrowGeometry()), this); // CoP properties cop_enable_property_ = new BoolProperty("Enable", true, "Enable/disable the CoP display", cop_category_, SLOT(updateCoPEnable()), this); cop_enable_status_property_ = new BoolProperty("Use Contact Status", true, "Use contact status to detect whether a contact is active", cop_category_, SLOT(updateCoPEnable()), this); cop_color_property_ = new rviz::ColorProperty("Color", QColor(204, 41, 204), "Color of a point", cop_category_, SLOT(updateCoPColorAndAlpha()), this); cop_alpha_property_ = new rviz::FloatProperty("Alpha", 1.0, "0 is fully transparent, 1.0 is fully opaque.", cop_category_, SLOT(updateCoPColorAndAlpha()), this); cop_alpha_property_->setMin(0); cop_alpha_property_->setMax(1); cop_radius_property_ = new rviz::FloatProperty("Radius", 0.04, "Radius of a point", cop_category_, SLOT(updateCoPColorAndAlpha()), this); // Instantaneous Capture Point properties icp_enable_property_ = new BoolProperty("Enable", true, "Enable/disable the ICP display", icp_category_, SLOT(updateICPEnable()), this); icp_color_property_ = new rviz::ColorProperty("Color", QColor(10, 41, 10), "Color of a point", icp_category_, SLOT(updateICPColorAndAlpha()), this); icp_alpha_property_ = new rviz::FloatProperty("Alpha", 1.0, "0 is fully transparent, 1.0 is fully opaque.", icp_category_, SLOT(updateICPColorAndAlpha()), this); icp_alpha_property_->setMin(0); icp_alpha_property_->setMax(1); icp_radius_property_ = new rviz::FloatProperty("Radius", 0.04, "Radius of a point", icp_category_, SLOT(updateICPColorAndAlpha()), this); // CMP properties cmp_enable_property_ = new BoolProperty("Enable", true, "Enable/disable the CMP display", cmp_category_, SLOT(updateCMPEnable()), this); cmp_color_property_ = new rviz::ColorProperty("Color", QColor(200, 41, 10), "Color of a point", cmp_category_, SLOT(updateCMPColorAndAlpha()), this); cmp_alpha_property_ = new rviz::FloatProperty("Alpha", 1.0, "0 is fully transparent, 1.0 is fully opaque.", cmp_category_, SLOT(updateCMPColorAndAlpha()), this); cmp_alpha_property_->setMin(0); cmp_alpha_property_->setMax(1); cmp_radius_property_ = new rviz::FloatProperty("Radius", 0.04, "Radius of a point", cmp_category_, SLOT(updateCMPColorAndAlpha()), this); // GRF properties grf_enable_property_ = new BoolProperty("Enable", true, "Enable/disable the contact force display", grf_category_, SLOT(updateGRFEnable()), this); grf_enable_status_property_ = new BoolProperty("Use Contact Status", true, "Use contact status to detect whether a contact is active", grf_category_, SLOT(updateGRFEnable()), this); grf_color_property_ = new ColorProperty("Color", QColor(85, 0, 255), "Color to draw the arrow.", grf_category_, SLOT(updateGRFColorAndAlpha()), this); grf_alpha_property_ = new FloatProperty("Alpha", 1.0, "Amount of transparency to apply to the arrow.", grf_category_, SLOT(updateGRFColorAndAlpha()), this); grf_alpha_property_->setMin(0); grf_alpha_property_->setMax(1); grf_shaft_length_property_ = new FloatProperty("Shaft Length", 0.8, "Length of the arrow's shaft, in meters.", grf_category_, SLOT(updateGRFArrowGeometry()), this); grf_shaft_radius_property_ = new FloatProperty("Shaft Radius", 0.02, "Radius of the arrow's shaft, in meters.", grf_category_, SLOT(updateGRFArrowGeometry()), this); grf_head_length_property_ = new FloatProperty("Head Length", 0.08, "Length of the arrow's head, in meters.", grf_category_, SLOT(updateGRFArrowGeometry()), this); grf_head_radius_property_ = new FloatProperty("Head Radius", 0.04, "Radius of the arrow's head, in meters.", grf_category_, SLOT(updateGRFArrowGeometry()), this); // Support region properties support_enable_property_ = new BoolProperty("Enable", true, "Enable/disable the support polygon display", support_category_, SLOT(updateSupportEnable()), this); support_enable_status_property_ = new BoolProperty("Use Contact Status", true, "Use contact status to detect whether a contact is active", support_category_, SLOT(updateSupportEnable()), this); support_line_color_property_ = new ColorProperty("Line Color", QColor(85, 0, 255), "Color to draw the line.", support_category_, SLOT(updateSupportLineColorAndAlpha()), this); support_line_alpha_property_ = new FloatProperty("Line Alpha", 1.0, "Amount of transparency to apply to the line.", support_category_, SLOT(updateSupportLineColorAndAlpha()), this); support_line_alpha_property_->setMin(0); support_line_alpha_property_->setMax(1); support_line_radius_property_ = new FloatProperty("Line Radius", 0.005, "Radius of the line in m.", support_category_, SLOT(updateSupportLineColorAndAlpha()), this); support_mesh_color_property_ = new ColorProperty("Mesh Color", QColor(85, 0, 255), "Color to draw the mesh.", support_category_, SLOT(updateSupportMeshColorAndAlpha()), this); support_mesh_alpha_property_ = new FloatProperty("Mesh Alpha", 0.2, "Amount of transparency to apply to the mesh.", support_category_, SLOT(updateSupportMeshColorAndAlpha()), this); support_mesh_alpha_property_->setMin(0); support_mesh_alpha_property_->setMax(1); support_force_threshold_property_ = new FloatProperty("Force Threshold", 1.0, "Threshold for defining active contacts.", support_category_, SLOT(updateSupportLineColorAndAlpha()), this); // Friction cone properties friction_cone_enable_property_ = new BoolProperty("Enable", true, "Enable/disable the friction cone display", friction_category_, SLOT(updateFrictionConeEnable()), this); friction_cone_enable_status_property_ = new BoolProperty("Use Contact Status", true, "Use contact status to detect whether a contact is active", friction_category_, SLOT(updateFrictionConeEnable()), this); friction_cone_color_property_ = new ColorProperty("Color", QColor(255, 0, 127), "Color to draw the friction cone.", friction_category_, SLOT(updateFrictionConeColorAndAlpha()), this); friction_cone_alpha_property_ = new FloatProperty("Alpha", 0.5, "Amount of transparency to apply to the friction cone.", friction_category_, SLOT(updateFrictionConeColorAndAlpha()), this); friction_cone_alpha_property_->setMin(0); friction_cone_alpha_property_->setMax(1); friction_cone_length_property_ = new FloatProperty("Length", 0.2, "Length of the friction cone in m.", friction_category_, SLOT(updateFrictionConeGeometry()), this); } WholeBodyStateDisplay::~WholeBodyStateDisplay() {} void WholeBodyStateDisplay::onInitialize() { MFDClass::onInitialize(); robot_.reset(new rviz::Robot(scene_node_, context_, "Robot: " + getName().toStdString(), this)); updateRobotVisualVisible(); updateRobotCollisionVisible(); updateRobotAlpha(); updateGRFColorAndAlpha(); } void WholeBodyStateDisplay::onEnable() { MFDClass::onEnable(); loadRobotModel(); updateRobotEnable(); updateCoMEnable(); updateCoPEnable(); updateICPEnable(); updateCMPEnable(); updateGRFEnable(); updateSupportEnable(); updateFrictionConeEnable(); } void WholeBodyStateDisplay::onDisable() { MFDClass::onDisable(); robot_->setVisible(false); clearRobotModel(); // Remove all artefacts: com_visual_.reset(); comd_visual_.reset(); cop_visual_.reset(); icp_visual_.reset(); cmp_visual_.reset(); grf_visual_.clear(); support_visual_.reset(); cones_visual_.clear(); context_->queueRender(); } void WholeBodyStateDisplay::fixedFrameChanged() { MFDClass::fixedFrameChanged(); if (msg_ != nullptr) { processWholeBodyState(); } } void WholeBodyStateDisplay::reset() { MFDClass::reset(); grf_visual_.clear(); cones_visual_.clear(); } void WholeBodyStateDisplay::loadRobotModel() { std::string content; if (!update_nh_.getParam(robot_model_property_->getStdString(), content)) { std::string loc; if (update_nh_.searchParam(robot_model_property_->getStdString(), loc)) { update_nh_.getParam(loc, content); } else { clearRobotModel(); setStatus( StatusProperty::Error, "URDF", "Parameter [" + robot_model_property_->getString() + "] does not exist, and was not found by searchParam()"); // try again in a second QTimer::singleShot(1000, this, SLOT(updateRobotModel())); return; } } if (content.empty()) { clearRobotModel(); setStatus(StatusProperty::Error, "URDF", "URDF is empty"); return; } if (content == robot_model_) { return; } robot_model_ = content; urdf::Model descr; if (!descr.initString(robot_model_)) { clearRobotModel(); setStatus(StatusProperty::Error, "URDF", "Failed to parse URDF model"); return; } // Initializing the dynamics from the URDF model try { pinocchio::urdf::buildModelFromXML(robot_model_, pinocchio::JointModelFreeFlyer(), model_); } catch (const std::invalid_argument &e) { std::string error_msg = "Failed to instantiate model: "; error_msg += e.what(); setStatus(StatusProperty::Error, "Pinocchio-URDFParser", QString::fromStdString(error_msg)); ROS_ERROR_STREAM(error_msg); // This message is potentially quite detailed. return; } data_ = pinocchio::Data(model_); gravity_ = model_.gravity.linear().norm(); weight_ = pinocchio::computeTotalMass(model_) * gravity_; initialized_model_ = true; robot_->load(descr); updateRobotEnable(); setStatus(StatusProperty::Ok, "URDF", "URDF parsed OK"); } void WholeBodyStateDisplay::clearRobotModel() { clearStatuses(); robot_model_.clear(); model_ = pinocchio::Model(); data_ = pinocchio::Data(); initialized_model_ = false; } void WholeBodyStateDisplay::updateRobotEnable() { robot_enable_ = robot_enable_property_->getBool(); if (robot_enable_) { robot_->setVisible(true); } else { robot_->setVisible(false); } } void WholeBodyStateDisplay::updateRobotModel() { if (isEnabled()) { loadRobotModel(); context_->queueRender(); } } void WholeBodyStateDisplay::updateRobotVisualVisible() { robot_->setVisualVisible(robot_visual_enabled_property_->getValue().toBool()); context_->queueRender(); } void WholeBodyStateDisplay::updateRobotCollisionVisible() { robot_->setCollisionVisible(robot_collision_enabled_property_->getValue().toBool()); context_->queueRender(); } void WholeBodyStateDisplay::updateRobotAlpha() { robot_->setAlpha(robot_alpha_property_->getFloat()); context_->queueRender(); } void WholeBodyStateDisplay::updateCoMEnable() { com_enable_ = com_enable_property_->getBool(); if (com_visual_ && !com_enable_) { com_visual_.reset(); } if (comd_visual_ && !com_enable_) { comd_visual_.reset(); } context_->queueRender(); } void WholeBodyStateDisplay::updateCoMStyle() { CoMStyle style = (CoMStyle)com_style_property_->getOptionInt(); switch (style) { case REAL: default: com_real_ = true; break; case PROJECTED: com_real_ = false; break; } } void WholeBodyStateDisplay::updateCoMColorAndAlpha() { const float &radius = com_radius_property_->getFloat(); Ogre::ColourValue color = com_color_property_->getOgreColor(); color.a = com_alpha_property_->getFloat(); if (com_visual_) { com_visual_->setColor(color.r, color.g, color.b, color.a); com_visual_->setRadius(radius); } if (comd_visual_) { comd_visual_->setColor(color.r, color.g, color.b, color.a); } context_->queueRender(); } void WholeBodyStateDisplay::updateCoMArrowGeometry() { const float &shaft_length = com_shaft_length_property_->getFloat(); const float &shaft_radius = com_shaft_radius_property_->getFloat(); const float &head_length = com_head_length_property_->getFloat(); const float &head_radius = com_head_radius_property_->getFloat(); if (comd_visual_) { comd_visual_->setProperties(shaft_length, shaft_radius, head_length, head_radius); } context_->queueRender(); } void WholeBodyStateDisplay::updateCoPEnable() { cop_enable_ = cop_enable_property_->getBool(); use_contact_status_in_cop_ = cop_enable_status_property_->getBool(); if (cop_visual_ && !cop_enable_) { cop_visual_.reset(); } context_->queueRender(); } void WholeBodyStateDisplay::updateCoPColorAndAlpha() { const float &radius = cop_radius_property_->getFloat(); Ogre::ColourValue color = cop_color_property_->getOgreColor(); color.a = cop_alpha_property_->getFloat(); if (cop_visual_) { cop_visual_->setColor(color.r, color.g, color.b, color.a); cop_visual_->setRadius(radius); } context_->queueRender(); } void WholeBodyStateDisplay::updateICPEnable() { icp_enable_ = icp_enable_property_->getBool(); if (icp_visual_ && !icp_enable_) { icp_visual_.reset(); } context_->queueRender(); } void WholeBodyStateDisplay::updateICPColorAndAlpha() { float radius = icp_radius_property_->getFloat(); Ogre::ColourValue color = icp_color_property_->getOgreColor(); color.a = icp_alpha_property_->getFloat(); if (icp_visual_) { icp_visual_->setColor(color.r, color.g, color.b, color.a); icp_visual_->setRadius(radius); } context_->queueRender(); } void WholeBodyStateDisplay::updateCMPEnable() { cmp_enable_ = cmp_enable_property_->getBool(); if (cmp_visual_ && !cmp_enable_) { cmp_visual_.reset(); } context_->queueRender(); } void WholeBodyStateDisplay::updateCMPColorAndAlpha() { const float &radius = cmp_radius_property_->getFloat(); Ogre::ColourValue color = cmp_color_property_->getOgreColor(); color.a = cmp_alpha_property_->getFloat(); if (cmp_visual_) { cmp_visual_->setColor(color.r, color.g, color.b, color.a); cmp_visual_->setRadius(radius); } context_->queueRender(); } void WholeBodyStateDisplay::updateGRFEnable() { grf_enable_ = grf_enable_property_->getBool(); use_contact_status_in_grf_ = grf_enable_status_property_->getBool(); if (grf_visual_.size() != 0 && !grf_enable_) { grf_visual_.clear(); } context_->queueRender(); } void WholeBodyStateDisplay::updateGRFColorAndAlpha() { Ogre::ColourValue color = grf_color_property_->getOgreColor(); color.a = grf_alpha_property_->getFloat(); for (size_t i = 0; i < grf_visual_.size(); ++i) { grf_visual_[i]->setColor(color.r, color.g, color.b, color.a); } context_->queueRender(); } void WholeBodyStateDisplay::updateGRFArrowGeometry() { const float &shaft_length = grf_shaft_length_property_->getFloat(); const float &shaft_radius = grf_shaft_radius_property_->getFloat(); const float &head_length = grf_head_length_property_->getFloat(); const float &head_radius = grf_head_radius_property_->getFloat(); for (size_t i = 0; i < grf_visual_.size(); ++i) { grf_visual_[i]->setProperties(shaft_length, shaft_radius, head_length, head_radius); } context_->queueRender(); } void WholeBodyStateDisplay::updateSupportEnable() { support_enable_ = support_enable_property_->getBool(); use_contact_status_in_support_ = support_enable_status_property_->getBool(); if (support_visual_ && !support_enable_) { support_visual_.reset(); } context_->queueRender(); } void WholeBodyStateDisplay::updateSupportLineColorAndAlpha() { Ogre::ColourValue color = support_line_color_property_->getOgreColor(); color.a = support_line_alpha_property_->getFloat(); force_threshold_ = support_force_threshold_property_->getFloat(); float radius = support_line_radius_property_->getFloat(); if (support_visual_) { support_visual_->setLineColor(color.r, color.g, color.b, color.a); support_visual_->setLineRadius(radius); } context_->queueRender(); } void WholeBodyStateDisplay::updateSupportMeshColorAndAlpha() { Ogre::ColourValue color = support_mesh_color_property_->getOgreColor(); color.a = support_mesh_alpha_property_->getFloat(); if (support_visual_) { support_visual_->setMeshColor(color.r, color.g, color.b, color.a); } context_->queueRender(); } void WholeBodyStateDisplay::updateFrictionConeEnable() { cone_enable_ = friction_cone_enable_property_->getBool(); use_contact_status_in_friction_cone_ = friction_cone_enable_status_property_->getBool(); if (cones_visual_.size() != 0 && !cone_enable_) { cones_visual_.clear(); } context_->queueRender(); } void WholeBodyStateDisplay::updateFrictionConeColorAndAlpha() { Ogre::ColourValue oc = friction_cone_color_property_->getOgreColor(); float alpha = friction_cone_alpha_property_->getFloat(); for (size_t i = 0; i < cones_visual_.size(); ++i) { cones_visual_[i]->setColor(oc.r, oc.g, oc.b, alpha); } context_->queueRender(); } void WholeBodyStateDisplay::updateFrictionConeGeometry() { const float &cone_length = friction_cone_length_property_->getFloat(); const float cone_width = 2.0 * cone_length * tan(friction_mu_ / sqrt(2.)); for (size_t i = 0; i < cones_visual_.size(); ++i) { cones_visual_[i]->setProperties(cone_width, cone_length); } context_->queueRender(); } void WholeBodyStateDisplay::processMessage(const whole_body_state_msgs::WholeBodyState::ConstPtr &msg) { msg_ = msg; has_new_msg_ = true; } void WholeBodyStateDisplay::processWholeBodyState() { // Checking if the urdf model was initialized if (!initialized_model_) return; // Here we call the rviz::FrameManager to get the transform from the // fixed frame to the frame in the header of this Point message. If // it fails, we can't do anything else so we return. Ogre::Quaternion orientation; Ogre::Vector3 position; if (!context_->getFrameManager()->getTransform(msg_->header.frame_id, msg_->header.stamp, position, orientation)) { ROS_DEBUG("Error transforming from frame '%s' to frame '%s'", msg_->header.frame_id.c_str(), qPrintable(fixed_frame_)); return; } // Display the robot if (robot_enable_) { Eigen::VectorXd q = Eigen::VectorXd::Zero(model_.nq); q(3) = msg_->centroidal.base_orientation.x; q(4) = msg_->centroidal.base_orientation.y; q(5) = msg_->centroidal.base_orientation.z; q(6) = msg_->centroidal.base_orientation.w; std::size_t n_joints = msg_->joints.size(); for (std::size_t j = 0; j < n_joints; ++j) { pinocchio::JointIndex jointId = model_.getJointId(msg_->joints[j].name) - 2; q(jointId + 7) = msg_->joints[j].position; } pinocchio::centerOfMass(model_, data_, q); q(0) = msg_->centroidal.com_position.x - data_.com[0](0); q(1) = msg_->centroidal.com_position.y - data_.com[0](1); q(2) = msg_->centroidal.com_position.z - data_.com[0](2); robot_->setPosition(position); robot_->setOrientation(orientation); robot_->update(PinocchioLinkUpdater(model_, data_, q, boost::bind(linkUpdaterStatusFunction, _1, _2, _3, this))); } // Resetting the point visualizers if (com_enable_) { com_visual_.reset(new PointVisual(context_->getSceneManager(), scene_node_)); comd_visual_.reset(new ArrowVisual(context_->getSceneManager(), scene_node_)); } if (support_enable_) { support_visual_.reset(new PolygonVisual(context_->getSceneManager(), scene_node_)); } // Now set or update the contents of the chosen GRF visual std::vector<Ogre::Vector3> support; size_t num_contacts = msg_->contacts.size(); size_t n_suppcontacts = 0; grf_visual_.clear(); cones_visual_.clear(); Eigen::Vector3d cop_pos = Eigen::Vector3d::Zero(); Eigen::Vector3d total_force = Eigen::Vector3d::Zero(); for (size_t i = 0; i < num_contacts; ++i) { const whole_body_state_msgs::ContactState &contact = msg_->contacts[i]; std::string name = contact.name; // Getting the contact position Ogre::Vector3 contact_pos(contact.pose.position.x, contact.pose.position.y, contact.pose.position.z); // Getting the force direction Eigen::Vector3d for_ref_dir = -Eigen::Vector3d::UnitZ(); Eigen::Vector3d for_dir(contact.wrench.force.x, contact.wrench.force.y, contact.wrench.force.z); // Updating the center of pressure bool active_contact_in_cop = false; if (use_contact_status_in_cop_) { active_contact_in_cop = contact.status == contact.ACTIVE; } else { active_contact_in_cop = for_dir.norm() > force_threshold_; } if (contact.type == contact.LOCOMOTION && active_contact_in_cop) { cop_pos += contact.wrench.force.z * Eigen::Vector3d(contact.pose.position.x, contact.pose.position.y, contact.pose.position.z); Eigen::Vector3d force_lin = Eigen::Vector3d(contact.wrench.force.x, contact.wrench.force.y, contact.wrench.force.z); total_force += force_lin; if (force_lin.norm() != 0) { n_suppcontacts += 1; } } // Building the support polygon if (std::isfinite(contact_pos.x) && std::isfinite(contact_pos.y) && std::isfinite(contact_pos.z)) { Eigen::Quaterniond for_q; for_q.setFromTwoVectors(for_ref_dir, for_dir); Ogre::Quaternion contact_for_orientation(for_q.w(), for_q.x(), for_q.y(), for_q.z()); // We are keeping a vector of visual pointers. This creates the next // one and stores it in the vector bool active_contact_in_grf = false; if (use_contact_status_in_grf_) { active_contact_in_grf = contact.status == contact.ACTIVE; } else { active_contact_in_grf = for_dir.norm() > force_threshold_; } if (grf_enable_ && active_contact_in_grf) { boost::shared_ptr<ArrowVisual> arrow; arrow.reset(new ArrowVisual(context_->getSceneManager(), scene_node_)); arrow->setArrow(contact_pos, contact_for_orientation); arrow->setFramePosition(position); arrow->setFrameOrientation(orientation); // Setting the arrow color and properties Ogre::ColourValue color = grf_color_property_->getOgreColor(); color.a = grf_alpha_property_->getFloat(); arrow->setColor(color.r, color.g, color.b, color.a); const float &shaft_length = grf_shaft_length_property_->getFloat() * for_dir.norm() / weight_; const float &shaft_radius = grf_shaft_radius_property_->getFloat(); const float &head_length = grf_head_length_property_->getFloat(); const float &head_radius = grf_head_radius_property_->getFloat(); arrow->setProperties(shaft_length, shaft_radius, head_length, head_radius); // And send it to the end of the vector if (std::isfinite(shaft_length) && std::isfinite(shaft_radius) && std::isfinite(head_length) && std::isfinite(head_radius)) { grf_visual_.push_back(arrow); } } bool active_contact_in_support = false; if (use_contact_status_in_support_) { active_contact_in_support = contact.status == contact.ACTIVE; } else { active_contact_in_support = for_dir.norm() > force_threshold_; } if (support_enable_ && active_contact_in_support && contact.type == contact.LOCOMOTION) { support.push_back(contact_pos); } } // Building the friction cones bool active_contact_in_cone = false; if (use_contact_status_in_friction_cone_) { active_contact_in_cone = contact.status == contact.ACTIVE; } else { active_contact_in_cone = for_dir.norm() > force_threshold_; } Eigen::Vector3d cone_dir(contact.surface_normal.x, contact.surface_normal.y, contact.surface_normal.z); friction_mu_ = contact.friction_coefficient; if (cone_enable_ && active_contact_in_cone && cone_dir.norm() != 0 && friction_mu_ != 0) { Eigen::Vector3d cone_ref_dir = -Eigen::Vector3d::UnitY(); Eigen::Quaterniond cone_q; cone_q.setFromTwoVectors(cone_ref_dir, cone_dir); Ogre::Quaternion cone_orientation(cone_q.w(), cone_q.x(), cone_q.y(), cone_q.z()); boost::shared_ptr<ConeVisual> cone; cone.reset(new ConeVisual(context_->getSceneManager(), scene_node_)); cone->setCone(contact_pos, cone_orientation); cone->setFramePosition(position); cone->setFrameOrientation(orientation); // Setting the cone color and properties Ogre::ColourValue color = friction_cone_color_property_->getOgreColor(); color.a = friction_cone_alpha_property_->getFloat(); cone->setColor(color.r, color.g, color.b, color.a); const float &cone_length = friction_cone_length_property_->getFloat(); const float cone_width = 2.0 * cone_length * tan(friction_mu_ / sqrt(2.)); cone->setProperties(cone_width, cone_length); // And send it to the end of the vector if (std::isfinite(cone_width) && std::isfinite(cone_length)) { cones_visual_.push_back(cone); } } } // Building the CoP visual if (n_suppcontacts != 0) { cop_pos /= total_force(2); } // Defining the center of mass as Ogre::Vector3 Ogre::Vector3 com_point; if (!com_real_ && n_suppcontacts != 0) { Eigen::Vector3d cop_z = Eigen::Vector3d::Zero(); cop_z(2) = cop_pos(2); pinocchio::SE3::Quaternion q(msg_->centroidal.base_orientation.w, msg_->centroidal.base_orientation.x, msg_->centroidal.base_orientation.y, msg_->centroidal.base_orientation.z); Eigen::Vector3d rot_cop_z = q.matrix() * cop_z; com_point.x = msg_->centroidal.com_position.x + rot_cop_z(0); com_point.y = msg_->centroidal.com_position.y + rot_cop_z(1); com_point.z = cop_z(2); } else { com_point.x = msg_->centroidal.com_position.x; com_point.y = msg_->centroidal.com_position.y; com_point.z = msg_->centroidal.com_position.z; } // Defining the center of mass velocity orientation Eigen::Vector3d com_ref_dir = -Eigen::Vector3d::UnitZ(); Eigen::Vector3d com_vel(msg_->centroidal.com_velocity.x, msg_->centroidal.com_velocity.y, msg_->centroidal.com_velocity.z); Eigen::Quaterniond com_q; com_q.setFromTwoVectors(com_ref_dir, com_vel); Ogre::Quaternion comd_for_orientation(com_q.w(), com_q.x(), com_q.y(), com_q.z()); // Now set or update the contents of the chosen CoM visual updateCoMColorAndAlpha(); if (com_enable_ && std::isfinite(com_point.x) && std::isfinite(com_point.y) && std::isfinite(com_point.z)) { com_visual_->setPoint(com_point); com_visual_->setFramePosition(position); com_visual_->setFrameOrientation(orientation); const double &com_vel_norm = com_vel.norm(); const float &shaft_length = com_shaft_length_property_->getFloat() * com_vel_norm; const float &shaft_radius = com_shaft_radius_property_->getFloat(); float head_length = 0., head_radius = 0.; if (com_vel_norm > 0.01) { head_length = com_head_length_property_->getFloat(); head_radius = com_head_radius_property_->getFloat(); } comd_visual_->setProperties(shaft_length, shaft_radius, head_length, head_radius); comd_visual_->setArrow(com_point, comd_for_orientation); comd_visual_->setFramePosition(position); comd_visual_->setFrameOrientation(orientation); } // Now set or update the contents of the chosen CoP visual if (n_suppcontacts != 0) { if (cop_enable_) { cop_visual_.reset(new PointVisual(context_->getSceneManager(), scene_node_)); } if (icp_enable_) { icp_visual_.reset(new PointVisual(context_->getSceneManager(), scene_node_)); } if (cmp_enable_) { cmp_visual_.reset(new PointVisual(context_->getSceneManager(), scene_node_)); } if (cop_enable_ && std::isfinite(cop_pos(0)) && std::isfinite(cop_pos(1)) && std::isfinite(cop_pos(2))) { updateCoPColorAndAlpha(); Ogre::Vector3 cop_point(cop_pos(0), cop_pos(1), cop_pos(2)); cop_visual_->setPoint(cop_point); cop_visual_->setFramePosition(position); cop_visual_->setFrameOrientation(orientation); } // Computing the ICP double height = abs(msg_->centroidal.com_position.z - cop_pos(2)); double omega = sqrt(gravity_ / height); Eigen::Vector3d com_pos = Eigen::Vector3d(msg_->centroidal.com_position.x, msg_->centroidal.com_position.y, msg_->centroidal.com_position.z); Eigen::Vector3d icp_pos = com_pos + com_vel / omega; icp_pos(2) = cop_pos(2); // Now set or update the contents of the chosen Inst CP visual if (icp_enable_ && std::isfinite(icp_pos(0)) && std::isfinite(icp_pos(1)) && std::isfinite(icp_pos(2))) { updateICPColorAndAlpha(); Ogre::Vector3 icp_point(icp_pos(0), icp_pos(1), icp_pos(2)); icp_visual_->setPoint(icp_point); icp_visual_->setFramePosition(position); icp_visual_->setFrameOrientation(orientation); } // Computing the CMP Eigen::Vector3d cmp_pos; cmp_pos(0) = com_pos(0) - total_force(0) / total_force(2) * height; cmp_pos(1) = com_pos(1) - total_force(1) / total_force(2) * height; cmp_pos(2) = com_pos(2) - height; if (cmp_enable_ && std::isfinite(cmp_pos(0)) && std::isfinite(cmp_pos(1)) && std::isfinite(cmp_pos(2))) { updateCMPColorAndAlpha(); Ogre::Vector3 cmp_point(cmp_pos(0), cmp_pos(1), cmp_pos(2)); cmp_visual_->setPoint(cmp_point); cmp_visual_->setFramePosition(position); cmp_visual_->setFrameOrientation(orientation); } } else { if (cop_visual_) { cop_visual_.reset(); } if (icp_visual_) { icp_visual_.reset(); } if (cmp_visual_) { cmp_visual_.reset(); } } // Now set or update the contents of the chosen CoP visual if (support_enable_) { support_visual_->setVertices(support); updateSupportLineColorAndAlpha(); updateSupportMeshColorAndAlpha(); support_visual_->setFramePosition(position); support_visual_->setFrameOrientation(orientation); } } void WholeBodyStateDisplay::update(float wall_dt, float /*ros_dt*/) { if (has_new_msg_) { processWholeBodyState(); has_new_msg_ = false; } } } // namespace whole_body_state_rviz_plugin #include <pluginlib/class_list_macros.h> PLUGINLIB_EXPORT_CLASS(whole_body_state_rviz_plugin::WholeBodyStateDisplay, rviz::Display)
43.789976
119
0.68081
[ "mesh", "vector", "model", "transform" ]
8d1d45cf3dcbfd0e33fd66f9d01ed2f241f23c50
4,216
cpp
C++
EpLibrary2.0/EpLibrary/Sources/epBaseOutputter.cpp
juhgiyo/EpLibrary
130c3ec3fdd4af829c63f0f8b142d0cc3349100e
[ "Unlicense", "MIT" ]
34
2015-01-01T12:08:15.000Z
2022-03-19T15:34:41.000Z
EpLibrary2.0/EpLibrary/Sources/epBaseOutputter.cpp
darongE/EpLibrary
a637612ceff19e4106c7972ce1bca3ccfe666087
[ "Unlicense", "MIT" ]
1
2021-01-26T05:07:27.000Z
2021-01-26T05:19:45.000Z
EpLibrary2.0/EpLibrary/Sources/epBaseOutputter.cpp
darongE/EpLibrary
a637612ceff19e4106c7972ce1bca3ccfe666087
[ "Unlicense", "MIT" ]
25
2015-01-17T19:27:57.000Z
2021-11-17T06:26:20.000Z
/*! BaseOutputter for the EpLibrary The MIT License (MIT) Copyright (c) 2008-2013 Woong Gyu La <juhgiyo@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. */ #include "epBaseOutputter.h" #include "epException.h" using namespace epl; #if defined(_DEBUG) && defined(EP_ENABLE_CRTDBG) #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif // defined(_DEBUG) && defined(EP_ENABLE_CRTDBG) DECLARE_THREAD_SAFE_CLASS(System); BaseOutputter::OutputNode::OutputNode() {} BaseOutputter::OutputNode::OutputNode(const OutputNode& b) {} BaseOutputter::OutputNode::~OutputNode() {} BaseOutputter::BaseOutputter(LockPolicy lockPolicyType) { m_lockPolicy=lockPolicyType; switch(lockPolicyType) { case LOCK_POLICY_CRITICALSECTION: m_nodeListLock=EP_NEW CriticalSectionEx(); break; case LOCK_POLICY_MUTEX: m_nodeListLock=EP_NEW Mutex(); break; case LOCK_POLICY_NONE: m_nodeListLock=EP_NEW NoLock(); break; default: m_nodeListLock=NULL; break; } } BaseOutputter::BaseOutputter(const BaseOutputter& b) { m_lockPolicy=b.m_lockPolicy; switch(m_lockPolicy) { case LOCK_POLICY_CRITICALSECTION: m_nodeListLock=EP_NEW CriticalSectionEx(); break; case LOCK_POLICY_MUTEX: m_nodeListLock=EP_NEW Mutex(); break; case LOCK_POLICY_NONE: m_nodeListLock=EP_NEW NoLock(); break; default: m_nodeListLock=NULL; break; } m_fileName=b.m_fileName; LockObj lock(b.m_nodeListLock); m_list=b.m_list; } BaseOutputter::~BaseOutputter() { Clear(); if(m_nodeListLock) EP_DELETE m_nodeListLock; m_nodeListLock=NULL; } BaseOutputter & BaseOutputter::operator=(const BaseOutputter&b) { if(this!=&b) { Clear(); if(m_nodeListLock) EP_DELETE m_nodeListLock; m_nodeListLock=NULL; m_lockPolicy=b.m_lockPolicy; switch(m_lockPolicy) { case LOCK_POLICY_CRITICALSECTION: m_nodeListLock=EP_NEW CriticalSectionEx(); break; case LOCK_POLICY_MUTEX: m_nodeListLock=EP_NEW Mutex(); break; case LOCK_POLICY_NONE: m_nodeListLock=EP_NEW NoLock(); break; default: m_nodeListLock=NULL; break; } m_fileName=b.m_fileName; LockObj lock(b.m_nodeListLock); m_list=b.m_list; } return *this; } void BaseOutputter::Clear() { LockObj lock(m_nodeListLock); std::vector<OutputNode*>::iterator iter; for(iter=m_list.begin();iter!=m_list.end();iter++) { EP_DELETE (*iter); } m_list.clear(); } void BaseOutputter::Print() const { LockObj lock(m_nodeListLock); std::vector<OutputNode*>::const_iterator iter; for(iter=m_list.begin();iter!=m_list.end();iter++) { (*iter)->Print(); } } void BaseOutputter::FlushToFile() { LockObj lock(m_nodeListLock); EpFile *file=NULL; System::FTOpen(file,m_fileName.c_str(),_T("at")); EP_ASSERT_EXPR(file,_T("Cannot open the file(%s)!"),m_fileName.c_str()); writeToFile(file); System::FClose(file); } void BaseOutputter::SetFileName(const TCHAR *fileName) { LockObj lock(m_nodeListLock); m_fileName=fileName; } void BaseOutputter::writeToFile(EpFile* const file) { if(file) { System::FTPrintf(file,_T("Log Starts...\n")); std::vector<OutputNode*>::iterator iter; for(iter=m_list.begin();iter!=m_list.end();iter++) { (*iter)->Write(file); } System::FTPrintf(file,_T("Log Ends...\n")); } }
24.511628
77
0.75166
[ "vector" ]
8d27dea78f4b12267a3a39830b41fc97b58d4bd2
6,422
cpp
C++
mask_ultra.cpp
rsingh2083/Face-Mask-Detection-Jetson-Nano
7153e27c002d022bd1f0467489d0eebbabe84ac7
[ "BSD-3-Clause" ]
12
2020-12-11T08:19:43.000Z
2022-03-09T18:21:46.000Z
mask_ultra.cpp
rsingh2083/Face-Mask-Detection-Jetson-Nano
7153e27c002d022bd1f0467489d0eebbabe84ac7
[ "BSD-3-Clause" ]
3
2021-01-01T05:52:29.000Z
2021-01-05T19:26:11.000Z
mask_ultra.cpp
rsingh2083/Face-Mask-Detection-Jetson-Nano
7153e27c002d022bd1f0467489d0eebbabe84ac7
[ "BSD-3-Clause" ]
7
2020-12-31T20:49:06.000Z
2022-03-09T18:21:57.000Z
// Copyright (c) 2019 PaddlePaddle 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 <iostream> #include <string> #include <vector> #include "opencv2/core.hpp" #include "opencv2/imgcodecs.hpp" #include "opencv2/imgproc.hpp" #include <opencv2/highgui.hpp> #include "paddle_api.h" // NOLINT #include "paddle_use_kernels.h" // NOLINT #include "paddle_use_ops.h" // NOLINT #include "UltraFace.hpp" using namespace std; using namespace paddle::lite_api; // NOLINT int main(int argc,char ** argv) { float f; float FPS[16]; int i, Fcnt=0; cv::Mat frame; int classify_w = 128; int classify_h = 128; float scale_factor = 1.f / 256; int FaceImgSz = classify_w * classify_h; // Mask detection (second phase, when the faces are located) MobileConfig Mconfig; std::shared_ptr<PaddlePredictor> Mpredictor; //some timing chrono::steady_clock::time_point Tbegin, Tend; for(i=0;i<16;i++) FPS[i]=0.0; //load SSD face detection model and get predictor // UltraFace ultraface("slim_320.bin","slim_320.param", 320, 240, 2, 0.7); // config model input UltraFace ultraface("RFB-320.bin","RFB-320.param", 320, 240, 2, 0.7); // config model input //load mask detection model Mconfig.set_model_from_file("mask_detector_opt2.nb"); Mpredictor = CreatePaddlePredictor<MobileConfig>(Mconfig); std::cout << "Load classification model succeed." << std::endl; // Get Input Tensor std::unique_ptr<Tensor> input_tensor1(std::move(Mpredictor->GetInput(0))); input_tensor1->Resize({1, 3, classify_h, classify_w}); // Get Output Tensor std::unique_ptr<const Tensor> output_tensor1(std::move(Mpredictor->GetOutput(0))); cv::VideoCapture cap("Face_Mask_Video.mp4"); if (!cap.isOpened()) { cerr << "ERROR: Unable to open the camera" << endl; return 0; } cout << "Start grabbing, press ESC on Live window to terminate" << endl; while(1){ // frame=cv::imread("Face_2.jpg"); //if you want to run just one picture need to refresh frame before class detection cap >> frame; if (frame.empty()) { cerr << "ERROR: Unable to grab from the camera" << endl; break; } Tbegin = chrono::steady_clock::now(); ncnn::Mat inmat = ncnn::Mat::from_pixels(frame.data, ncnn::Mat::PIXEL_BGR2RGB, frame.cols, frame.rows); //get the faces std::vector<FaceInfo> face_info; ultraface.detect(inmat, face_info); auto* input_data = input_tensor1->mutable_data<float>(); for(long unsigned int i = 0; i < face_info.size(); i++) { auto face = face_info[i]; //enlarge 10% float w = (face.x2 - face.x1)/20.0; float h = (face.y2 - face.y1)/20.0; cv::Point pt1(std::max(face.x1-w,float(0.0)),std::max(face.y1-h,float(0.0))); cv::Point pt2(std::min(face.x2+w,float(frame.cols)),std::min(face.y2+h,float(frame.rows))); //RecClip is completly inside the frame cv::Rect RecClip(pt1, pt2); cv::Mat resized_img; cv::Mat imgf; if(RecClip.width>0 && RecClip.height>0){ //roi has size RecClip cv::Mat roi = frame(RecClip); //resized_img has size 128x128 (uchar) cv::resize(roi, resized_img, cv::Size(classify_w, classify_h), 0.f, 0.f, cv::INTER_CUBIC); //imgf has size 128x128 (float in range 0.0 - +1.0) resized_img.convertTo(imgf, CV_32FC3, scale_factor); //input tensor has size 128x128 (float in range -0.5 - +0.5) // fill tensor with mean and scale and trans layout: nhwc -> nchw, neon speed up //offset_nchw(n, c, h, w) = n * CHW + c * HW + h * W + w //offset_nhwc(n, c, h, w) = n * HWC + h * WC + w * C + c const float* dimg = reinterpret_cast<const float*>(imgf.data); float* dout_c0 = input_data; float* dout_c1 = input_data + FaceImgSz; float* dout_c2 = input_data + FaceImgSz * 2; for(int i=0;i<FaceImgSz;i++){ *(dout_c0++) = (*(dimg++) - 0.5); *(dout_c1++) = (*(dimg++) - 0.5); *(dout_c2++) = (*(dimg++) - 0.5); } // Classification Model Run Mpredictor->Run(); auto* outptr = output_tensor1->data<float>(); float prob = outptr[1]; // Draw Detection and Classification Results bool flag_mask = prob > 0.5f; cv::Scalar roi_color; if(flag_mask) roi_color = cv::Scalar(0, 255, 0); else roi_color = cv::Scalar(0, 0, 255); // Draw roi object cv::rectangle(frame, RecClip, roi_color, 2); } } Tend = chrono::steady_clock::now(); //calculate frame rate f = chrono::duration_cast <chrono::milliseconds> (Tend - Tbegin).count(); if(f>0.0) FPS[((Fcnt++)&0x0F)]=1000.0/f; for(f=0.0, i=0;i<16;i++){ f+=FPS[i]; } cv::putText(frame, cv::format("FPS %0.2f", f/16),cv::Point(10,20),cv::FONT_HERSHEY_SIMPLEX,0.6, cv::Scalar(0, 0, 255)); //cv::imwrite("FaceResult.jpg",frame); //in case you run only a jpg picture //show output cv::imshow("RPi 64 OS - 1,95 GHz - 2 Mb RAM", frame); char esc = cv::waitKey(5); if(esc == 27) break; } cout << "Closing the camera" << endl; cv::destroyAllWindows(); cout << "Bye!" << endl; return 0; }
38.45509
128
0.566646
[ "object", "vector", "model" ]
8d30bad9be200f0bdadbdfc9457c216503d5f415
1,111
hpp
C++
machiavelli/src/list_dialog.hpp
robhendriks/avans-cpp2
beaae5650d4446cd271f7f9b07b0e90deb80d994
[ "WTFPL" ]
null
null
null
machiavelli/src/list_dialog.hpp
robhendriks/avans-cpp2
beaae5650d4446cd271f7f9b07b0e90deb80d994
[ "WTFPL" ]
null
null
null
machiavelli/src/list_dialog.hpp
robhendriks/avans-cpp2
beaae5650d4446cd271f7f9b07b0e90deb80d994
[ "WTFPL" ]
null
null
null
#ifndef list_dialog_hpp #define list_dialog_hpp #include "dialog.hpp" namespace machiavelli { class list_dialog : public dialog { std::vector<std::string> m_items; protected: static const uint8_t item_first, item_last, item_odd, item_even; virtual void fill(std::initializer_list<string_utils::string_convertible> il); virtual void format(std::stringstream& ss) const override; virtual void format_items(std::stringstream& ss) const; virtual void format_item(std::stringstream& ss, const std::string& item, size_t index, uint8_t flags) const; public: list_dialog() : dialog{} {} list_dialog(const std::vector<std::string>& items) : m_items{items} {} list_dialog(std::initializer_list<std::string> il) : dialog{}, m_items{il} {} list_dialog(std::initializer_list<string_utils::string_convertible> il) : dialog{} { fill(il); } std::vector<std::string>& get_items() { return m_items; } const std::vector<std::string>& get_items() const { return m_items; } }; } #endif
35.83871
116
0.662466
[ "vector" ]
8d33c22adbaeef4afccae9258d1b227bb2dad2fc
4,023
cc
C++
src/developer/debug/zxdb/console/actions.cc
bootingman/fuchsia2
04012f0aa1edd1d4108a2ac647a65e59730fc4c2
[ "BSD-3-Clause" ]
1
2019-10-09T10:50:57.000Z
2019-10-09T10:50:57.000Z
src/developer/debug/zxdb/console/actions.cc
bootingman/fuchsia2
04012f0aa1edd1d4108a2ac647a65e59730fc4c2
[ "BSD-3-Clause" ]
null
null
null
src/developer/debug/zxdb/console/actions.cc
bootingman/fuchsia2
04012f0aa1edd1d4108a2ac647a65e59730fc4c2
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2018 The Fuchsia 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/developer/debug/zxdb/console/actions.h" #include "src/developer/debug/shared/message_loop.h" #include "src/lib/files/file.h" #include "src/lib/files/path.h" #include "src/lib/fxl/strings/split_string.h" #include "src/lib/fxl/strings/string_printf.h" namespace zxdb { namespace { using Option = fxl::CommandLine::Option; } // namespace // Action ---------------------------------------------------------------------- Action::Action() = default; Action::Action(std::string name, Action::ActionFunction action) : name_(name), action_(action) {} Action::Action(Action&&) = default; Action& Action::operator=(Action&& other) { this->name_ = std::move(other.name_); this->action_ = std::move(other.action_); return *this; } void Action::operator()(const Session& session, Console* console) const { // The next_action_ chaining will take care of calling the following command // when the time is due. action_(*this, session, console); } // ActionFlow ------------------------------------------------------------------ void ActionFlow::ScheduleActions(std::vector<Action>&& actions, const Session* session, Console* console, Callback callback) { // If there are no actions, we schedule the callback. if (actions.empty()) { callback_(Err()); return; } // We store the parameters as they will be used in the future. flow_ = std::move(actions); session_ = session; console_ = console; callback_ = std::move(callback); // We schedule the first action to run debug_ipc::MessageLoop::Current()->PostTask(FROM_HERE, [&]() { const auto& action = flow_.front(); action(*session_, console_); }); } ActionFlow& ActionFlow::Singleton() { // We use the global callback function so that the user doesn't have to // worry about tracking an instance. static ActionFlow flow; return flow; } ActionFlow::ActionFlow() = default; void ActionFlow::PostActionCallback(Err err) { ActionFlow& flow = ActionFlow::Singleton(); // We log the callback flow.callbacks_.push_back(err); // If the command wants us to stop processing, we call the complete callback. if ((err.type() == ErrType::kCanceled) || err.has_error()) { flow.callback_(err); return; } flow.current_action_index_++; // In no more actions available, communicate to caller. if (flow.current_action_index_ >= flow.flow_.size()) { flow.callback_(Err()); return; } // Schedule the next action. const auto& next_action = flow.current_action(); debug_ipc::MessageLoop::Current()->PostTask( FROM_HERE, [&]() { next_action(*flow.session_, flow.console_); }); } void ActionFlow::Clear() { flow_.clear(); current_action_index_ = 0; session_ = nullptr; console_ = nullptr; callback_ = nullptr; callbacks_.clear(); } std::vector<Action> CommandsToActions(const std::string& input) { auto commands = fxl::SplitStringCopy(input, "\n", fxl::kTrimWhitespace, fxl::kSplitWantNonEmpty); std::vector<Action> result; for (size_t i = 0; i < commands.size(); i++) { result.push_back(Action(commands[i], [&, cmd = commands[i]]( const Action& action, const Session& session, Console* console) { console->ProcessInputLine(cmd.c_str(), ActionFlow::PostActionCallback); })); } return result; } Err ScriptFileToActions(const std::string& path, std::vector<Action>* actions) { std::string contents; if (!files::ReadFileToString(files::AbsolutePath(path), &contents)) return Err(fxl::StringPrintf("Could not read file \"%s\"", path.c_str())); *actions = CommandsToActions(contents); return Err(); } } // namespace zxdb
30.709924
80
0.632364
[ "vector" ]
8d37f459b576bd759f3bc14280517ed1b6caa4c7
821
hpp
C++
Includes/CubbyDNN/Node/Input.hpp
utilForever/CubbyDNN
b044957e42eff8f14e826160b1bca1c82839a93b
[ "MIT" ]
34
2018-10-18T02:30:26.000Z
2021-06-13T19:11:23.000Z
Includes/CubbyDNN/Node/Input.hpp
utilForever/CubbyDNN
b044957e42eff8f14e826160b1bca1c82839a93b
[ "MIT" ]
31
2018-11-04T08:33:48.000Z
2020-10-07T14:59:55.000Z
Includes/CubbyDNN/Node/Input.hpp
utilForever/CubbyDNN
b044957e42eff8f14e826160b1bca1c82839a93b
[ "MIT" ]
9
2018-11-05T09:31:59.000Z
2020-12-25T13:04:26.000Z
#ifndef CUBBYDNN_INPUT_HPP #define CUBBYDNN_INPUT_HPP #include <CubbyDNN/Core/Graph.hpp> #include <CubbyDNN/Node/Node.hpp> namespace CubbyDNN::Node { class Input final : public Node { public: Input(Core::Graph* graph, std::string_view name); Input(const Input& rhs) = delete; Input(Input&& rhs) noexcept = delete; virtual ~Input() noexcept = default; Input& operator=(const Input& rhs) = delete; Input& operator=(Input&& rhs) noexcept = delete; const NodeType* Type() const override; static std::string_view TypeName(); void Feed(const Core::Shape& shape, Core::Span<float> span); private: void EvalShapeInternal() override; void EvalOutputInternal() override; Core::Shape m_inputShape; Core::Span<float> m_inputSpan; }; } // namespace CubbyDNN::Node #endif
23.457143
64
0.699147
[ "shape" ]
8d42731d1cd523f47bdbe1f03b95e9573ba6361c
2,923
cpp
C++
LeetCode/Problems/Algorithms/#692_TopKFrequentWords_sol3_trie_28ms_15.9MB.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
1
2022-01-26T14:50:07.000Z
2022-01-26T14:50:07.000Z
LeetCode/Problems/Algorithms/#692_TopKFrequentWords_sol3_trie_28ms_15.9MB.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
null
null
null
LeetCode/Problems/Algorithms/#692_TopKFrequentWords_sol3_trie_28ms_15.9MB.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
null
null
null
class TrieNode{ public: static const int ALPHABET_SIZE = 26; static const char FIRST_LETTER = 'a'; int terminal_node_cnt; vector<TrieNode*> children; int max_word_freq; TrieNode(){ this->terminal_node_cnt = 0; this->children.resize(ALPHABET_SIZE, NULL); this->max_word_freq = 0; } void insert(TrieNode* node, const string& word, int pos){ if(pos == word.length()){ node->terminal_node_cnt += 1; node->max_word_freq = max(node->terminal_node_cnt, node->max_word_freq); }else{ short int edge_id = word[pos] - FIRST_LETTER; if(node->children[edge_id] == NULL){ node->children[edge_id] = new TrieNode(); } insert(node->children[edge_id], word, pos + 1); node->max_word_freq = max(node->children[edge_id]->max_word_freq, node->max_word_freq); } } void insert(const string& word){ insert(this, word, 0); } void extract_top_k_freq_words(TrieNode* node, string& st, vector<string>& answer, bool& found){ if(found){ return; } int node_max_word_freq = node->max_word_freq; node->max_word_freq = 0; if(node->terminal_node_cnt > 0){ found = true; node->terminal_node_cnt = 0; for(int edge_id = 0; edge_id < ALPHABET_SIZE; ++edge_id){ TrieNode* next_node = node->children[edge_id]; if(next_node){ node->max_word_freq = max(next_node->max_word_freq, node->max_word_freq); } } answer.push_back(st); } for(int edge_id = 0; edge_id < ALPHABET_SIZE; ++edge_id){ TrieNode* next_node = node->children[edge_id]; if(next_node && node_max_word_freq == next_node->max_word_freq){ st.push_back(char(FIRST_LETTER + edge_id)); extract_top_k_freq_words(next_node, st, answer, found); st.pop_back(); } if(next_node){ node->max_word_freq = max(next_node->max_word_freq, node->max_word_freq); } } } void extract_top_k_freq_words(int k, vector<string>& answer){ for(; k > 0; --k){ string st; bool found = false; extract_top_k_freq_words(this, st, answer, found); } } }; class Solution { public: vector<string> topKFrequent(vector<string>& words, int k) { TrieNode* trie = new TrieNode(); for(const string& word: words){ trie->insert(word); } vector<string> answer; trie->extract_top_k_freq_words(k, answer); return answer; } };
33.597701
106
0.529935
[ "vector" ]
1d28e26e8fb15e39c936d74e738294b6d753c2fc
10,068
cpp
C++
app/interaction_service/core-algo/src/graph/graph.cpp
Philippe-Guyard/XOptimizer
d09644eb6b92253b1d56ca2ab9c1be681993d931
[ "MIT" ]
1
2021-11-07T18:34:20.000Z
2021-11-07T18:34:20.000Z
app/interaction_service/core-algo/temp/graph/graph.cpp
Philippe-Guyard/XOptimizer
d09644eb6b92253b1d56ca2ab9c1be681993d931
[ "MIT" ]
1
2021-11-16T21:29:32.000Z
2021-11-16T21:29:32.000Z
app/interaction_service/core-algo/temp/graph/graph.cpp
Philippe-Guyard/XOptimizer
d09644eb6b92253b1d56ca2ab9c1be681993d931
[ "MIT" ]
2
2021-11-05T11:06:18.000Z
2021-11-07T18:49:17.000Z
#include<iostream> #include<unordered_map> #include<set> #include<vector> #include<cstdio> #include<assert.h> #include "graph.hpp" // Graph Class Implementation Graph::Graph(){ num_vertices = 0; num_edges = 0; // Add default constructor to vertex_position } Graph::Graph(int num_vertices, VertexData* vertex_data_array, std::vector<std::vector<EdgeWeight>> distances){ /** * Constructor of Graph. * * PARAMETERS: * * int num_vertices : Number of vertices in the graph * * VertexData* vertex_data_array : An array of size num_vertices that contains the data of the vertices to be added. * * vector<vector<EdgeWeight> distances : An num_vertices x num_vertices matrix with the distances between the vertices. * * * ASSUMPTIONS: * All data in vertex_data_array correspond to different locations. * * The size of vertex_data_array is num_vertices. * * Distances is ideally an num_vertices x num_vertices symmetric matrix. * */ this->num_vertices = num_vertices; num_edges = 0; for(int i=0; i<num_vertices; ++i){ vertices.push_back(new Vertex(vertex_data_array[i], i)); } // Resizing adjacency_list adjacency_list.resize(num_vertices); for(int i=0; i<num_vertices; ++i){ adjacency_list[i].resize(num_vertices); } // we are ignoring the edge that goes from i to i for(int i=0; i<num_vertices; ++i){ for(int j=i+1; j<num_vertices; ++j){ // Passing vertices by address Edge* new_edge_ptr = new Edge(std::make_pair(vertices[i], vertices[j]), distances[i][j], num_edges); // Passing edge by reference edges.push_back( new_edge_ptr ); num_edges++; adjacency_list[i][j] = adjacency_list[j][i] = new_edge_ptr; } } //unordered_map construction for(int i=0; i<num_vertices; ++i){ vertex_position[vertex_data_array[i]] = i; } } Graph::~Graph(){ /** * Default Destructor * */ adjacency_list.clear(); while( edges.size() > 0 ){ Edge* edge_to_delete = edges.back(); edges.pop_back(); delete edge_to_delete; } while( vertices.size() > 0 ){ Vertex* vertex_to_delete = vertices.back(); vertices.pop_back(); delete vertex_to_delete; } } int Graph::get_num_vertices() const{ return num_vertices; } int Graph::get_num_edges() const{ return edges.size(); } Edge* Graph::get_edge(int index) const{ return edges[index]; } void Graph::update_vertex_data(VertexData& data){ return; } void Graph::add_vertex(VertexData& data, std::vector<std::pair<VertexData, EdgeWeight>>& distances){ /** * Adds a vertex to the graph with the corresponding edges. * * PARAMETERS: * VertexData& data : * The data that should be stored in the vertex. * * * std::vector<std::pair<VertexData, EdgeWeight>>& distances : * Contains the distances from this new vertex to all vertices already in the graph. The structure of pair<VertexData, EdgeWeight> * means distances[i].second is the distance of the new vertex to the vertex with data distances[i].first * * * RETURN: * void * */ // It is necessary to try to update the vertex before just adding it // e.g. repeated vertices /*== Maybe unecessary ==*/ if( vertex_position.count(data) ){ // repeated vertex this->update_vertex_data(data); return; } // Main code Vertex *new_vertex = new Vertex(data, num_vertices); vertices.push_back( new_vertex ); adjacency_list.emplace_back(); adjacency_list[num_vertices].resize(num_vertices); for(int i=0; i<num_vertices; ++i){ int j = vertex_position[ distances[i].first ]; Edge *new_edge = new Edge(std::make_pair(new_vertex, vertices[j]), distances[i].second, num_edges); adjacency_list[j].push_back( new_edge ); adjacency_list[num_vertices][j] = new_edge; edges.push_back( new_edge ); num_edges++; } Edge *trivial_edge = new Edge(std::pair<Vertex*, Vertex*> {new_vertex, new_vertex}, 0, num_edges); adjacency_list[num_vertices].push_back( trivial_edge ); edges.push_back( trivial_edge ); num_edges++; vertex_position[data] = num_vertices; num_vertices++; } int Graph::get_edge_index(int u, int v) const{ return adjacency_list[u][v]->get_index(); } int Graph::get_vertex_position(VertexData &d) const{ /** * A const member function to get the position of the vertex that has data d. * It will raise an error if d is not a valid data. * * PARAMETERS: * VertexData &d : The data corresponding to the vertex that we want to find. * * RETURN: * int : The position of the vertex with data d in vertices. * */ if( !vertex_position.count(d) ){ return -1; } return vertex_position.at(d); } void Graph::swap_vertex_indices(int pos1, int pos2){ /** * Swap the indices of the vertices vertices[pos1] and vertices[pos2] and the corresponding graph structure. * * PARAMETERS: * int pos1 * * int pos2 * * RETURN: * void * */ if(pos1==pos2) return; Vertex *vertex_1 = vertices[pos1]; Vertex *vertex_2 = vertices[pos2]; vertex_1->set_index(pos2); vertex_2->set_index(pos1); vertices[pos1] = vertex_2; vertices[pos2] = vertex_1; // Fixing adjacency list for(int i=0; i<num_vertices; ++i){ if(i==pos1 || i==pos2) continue; Edge *edge1 = adjacency_list[i][pos1]; Edge *edge2 = adjacency_list[i][pos2]; adjacency_list[i][pos1] = adjacency_list[pos1][i] = edge2; adjacency_list[i][pos2] = adjacency_list[pos2][i] = edge1; } } void Graph::swap_vertex_to_last(int pos){ /** * Swaps vertex vertices[pos] with the vertex in the last position of vertices. * * PARAMETERS: * int pos * * RETURN: * void */ swap_vertex_indices(pos, num_vertices-1); } void Graph::delete_vertex(VertexData& data){ /** * Deletes the vertex that carries the data given as parameter. Also delete the edges connected to this vertex and * mantains the graph structure. * * PARAMETERS: * VertexData& data : * Data that specifies which vertex will be deleted. * * RETURN: * void * */ // prevent deletion of vertices that don't exist if( get_vertex_position(data) == -1){ return; } int pos = vertex_position[data]; swap_vertex_to_last(pos); std::vector<Edge*> edges_to_delete; // Fixing adjacency_list adjacency_list.pop_back(); for(int i=0; i<num_vertices-1; ++i){ edges_to_delete.push_back(adjacency_list[i][num_vertices-1]); adjacency_list[i].pop_back(); } // removing the edges from edges for(int i=0; i<edges_to_delete.size(); ++i){ Edge *edge_to_delete = edges_to_delete[i]; int position_edge_to_delete = edge_to_delete->get_index(); std::swap(edges[position_edge_to_delete], edges[num_edges-edges_to_delete.size()+i]); } for(int i=0; i<edges_to_delete.size(); ++i){ edges.pop_back(); } for(int i=0; i<edges_to_delete.size(); ++i){ Edge *edge_to_delete = edges_to_delete[edges_to_delete.size()-1]; edges_to_delete.pop_back(); delete edge_to_delete; } vertex_position.erase(data); num_edges -= edges_to_delete.size(); num_vertices--; } // get edge member functions EdgeWeight Graph::get_edge_weight(int i, int j) const{ /** * Returns the weight of the edge between i and j. * * PARAMETERS: * int i * * int j * * RETURN: * * EdgeWeight : distance between i and j * */ if( !(i>=0 && i<num_vertices) ){ throw std::exception(); } if( !(j>=0 && j<num_vertices)){ throw std::exception(); } if(i==j){ return (EdgeWeight) 0; } return adjacency_list[i][j]->get_weight(); } EdgeWeight Graph::get_edge_weight(VertexData di, int j) const{ /** * Returns the weight of the edge between i and j. Here, i corresponds to the * vertex with data di. * * PARAMETERS: * VertexData di * * int j * * RETURN: * * EdgeWeight : distance between i and j * */ return get_edge_weight( get_vertex_position(di), j); } EdgeWeight Graph::get_edge_weight(int i, VertexData dj) const{ /** * Returns the weight of the edge between i and j. Here, j corresponds to the * vertex with data dj. * * PARAMETERS: * int i * * VertexData dj * * RETURN: * * EdgeWeight : distance between i and j * */ return get_edge_weight(i, get_vertex_position(dj)); } EdgeWeight Graph::get_edge_weight(VertexData di, VertexData dj) const{ /** * Returns the weight of the edge between i and j. Here, i,j correspond to the * vertices with data di,dj. * * PARAMETERS: * VertexData di * * VertexData dj * * RETURN: * * EdgeWeight : distance between i and j * */ return get_edge_weight(get_vertex_position(di), get_vertex_position(dj)); } // sort edges member function void Graph::sort_edges(){ /** * Sorts the edges inside the edges data attribute in ascending weight. It makes * sure that the indices of vertices are adjusted accordingly. * * PARAMETERS: * void * * RETURN: * void * */ std::sort(edges.begin(), edges.end(), [](Edge* ptr1, Edge* ptr2) {return ptr1->get_weight() < ptr2->get_weight();}); for(int i=0; i<num_edges; ++i){ edges[i]->set_index(i); } } std::vector<std::vector<double>> Graph::build_adjacency_matrix() const{ std::vector< std::vector<double> > adjacency_matrix_return(num_vertices); for(int i=0; i < num_vertices; ++i){ adjacency_matrix_return[i].resize(num_vertices); } for(int i=0; i<num_vertices; ++i){ for(int j=i; j<num_vertices; ++j){ adjacency_matrix_return[i][j] = adjacency_matrix_return[j][i] = get_edge_weight(i, j); } } return adjacency_matrix_return; }
22.176211
130
0.640445
[ "vector" ]
1d30f844040d5fbdfcab726537ccc621af066b68
43,199
cpp
C++
src/octUtils.cpp
lanl/Dendro-GRCA
8a475b1abd8832c3dfc19d00cc0ec4b9e2789c8a
[ "BSD-3-Clause" ]
1
2021-06-21T08:38:53.000Z
2021-06-21T08:38:53.000Z
src/octUtils.cpp
lanl/Dendro-GRCA
8a475b1abd8832c3dfc19d00cc0ec4b9e2789c8a
[ "BSD-3-Clause" ]
null
null
null
src/octUtils.cpp
lanl/Dendro-GRCA
8a475b1abd8832c3dfc19d00cc0ec4b9e2789c8a
[ "BSD-3-Clause" ]
1
2020-09-23T17:09:34.000Z
2020-09-23T17:09:34.000Z
// // Created by milinda on 9/6/16. // /** @brief A collection of simple functions for manipulating octrees. Examples: Regular Refinements, Linearizing an octree, I/O, Nearest Common Ancestor, adding positive boundaries, marking hanging nodes @author Rahul S. Sampath, rahul.sampath@gmail.com @author Hari Sundar, hsundar@gmail.com @author Milinda Fernando ,milinda@cs.utah.edu @remarks Most of the functions used for the mesh generation. Most of the implementations are based on the previous implementation of dendro version 4.0 */ #include "octUtils.h" // This will add boundary nodes and will also embed the octree one level higher // to enable the addition of the boundary nodes. The positive boundary nodes // are also marked as BOUNDARY. void addBoundaryNodesType1(std::vector<ot::TreeNode> &in, std::vector<ot::TreeNode>& bdy, unsigned int dim, unsigned int maxDepth) { assert(bdy.empty()); for (unsigned int i = 0; i < in.size(); i++) { // get basic info ... unsigned int d = in[i].getLevel(); unsigned int x = in[i].getX(); unsigned int y = in[i].getY(); unsigned int z = in[i].getZ(); unsigned char bdyFlags; // check if this is a boundary octant or not ... if ( in[i].isBoundaryOctant(ot::TreeNode::POSITIVE, &bdyFlags) ) { // bdy flags tells us which octants to add ... //NOTE: == is important since a&(b+c) will be true if //a=b, a=c and a=b+c // +x and more ... add additional octant in +x dir if ( bdyFlags & ot::TreeNode::X_POS_BDY ) { bdy.push_back(ot::TreeNode( (1u << maxDepth), y, z, (d+1) | ot::TreeNode::BOUNDARY, dim, maxDepth+1)); } // +y and more ... add additional octant in +y dir if ( bdyFlags & ot::TreeNode::Y_POS_BDY ) { bdy.push_back(ot::TreeNode(x, (1u << maxDepth), z, (d+1) | ot::TreeNode::BOUNDARY, dim, maxDepth+1)); } // +z and more ... add additional octant in +z dir if ( bdyFlags & ot::TreeNode::Z_POS_BDY ) { bdy.push_back(ot::TreeNode(x, y, (1u << maxDepth), (d+1) | ot::TreeNode::BOUNDARY, dim, maxDepth+1)); } //+x+y and more if ( (bdyFlags & (ot::TreeNode::X_POS_BDY + ot::TreeNode::Y_POS_BDY)) == (ot::TreeNode::X_POS_BDY + ot::TreeNode::Y_POS_BDY) ) { bdy.push_back(ot::TreeNode((1u << maxDepth),(1u << maxDepth), z, (d+1) | ot::TreeNode::BOUNDARY, dim, maxDepth+1)); } //+x+z and more if ( (bdyFlags & (ot::TreeNode::X_POS_BDY + ot::TreeNode::Z_POS_BDY)) == (ot::TreeNode::X_POS_BDY + ot::TreeNode::Z_POS_BDY) ) { bdy.push_back(ot::TreeNode((1u << maxDepth), y, (1u << maxDepth), (d+1) | ot::TreeNode::BOUNDARY, dim, maxDepth+1)); } //+y+z and more if ( (bdyFlags & (ot::TreeNode::Y_POS_BDY + ot::TreeNode::Z_POS_BDY)) == (ot::TreeNode::Y_POS_BDY + ot::TreeNode::Z_POS_BDY) ) { bdy.push_back(ot::TreeNode(x, (1u << maxDepth),(1u << maxDepth), (d+1) | ot::TreeNode::BOUNDARY, dim, maxDepth+1)); } // if global corner ... //+x +y and +z only if ( (bdyFlags & (ot::TreeNode::X_POS_BDY + ot::TreeNode::Y_POS_BDY + ot::TreeNode::Z_POS_BDY)) == (ot::TreeNode::X_POS_BDY + ot::TreeNode::Y_POS_BDY + ot::TreeNode::Z_POS_BDY) ) { bdy.push_back(ot::TreeNode((1u << maxDepth), (1u << maxDepth), (1u << maxDepth), (d+1) | ot::TreeNode::BOUNDARY, dim, maxDepth+1)); } }//end if boundary // Embed the actual octant in one level higher ... in[i] = ot::TreeNode(x, y, z, d+1, dim, maxDepth+1); }//end for i // A Parallel Sort for the bdy nodes follows in the constructor. //Then in and bdy will be merged. }//end function int refineOctree(const std::vector<ot::TreeNode> & inp, std::vector<ot::TreeNode> &out) { out.clear(); for(unsigned int i = 0; i < inp.size(); i++) { if(inp[i].getLevel() < inp[i].getMaxDepth()) { inp[i].addChildren(out); } else { out.push_back(inp[i]); } } return 1; }//end function int refineAndPartitionOctree(const std::vector<ot::TreeNode> & inp, std::vector<ot::TreeNode> &out, MPI_Comm comm) { refineOctree(inp,out); par::partitionW<ot::TreeNode>(out, NULL,comm); return 1; }//end function int createRegularOctree(std::vector<ot::TreeNode>& out, unsigned int lev, unsigned int dim, unsigned int maxDepth, MPI_Comm comm) { ot::TreeNode root(0,0,0,0,dim,maxDepth); out.clear(); int rank; MPI_Comm_rank(comm,&rank); if(!rank) { out.push_back(root); } for(int i = 0; i < lev; i++) { std::vector<ot::TreeNode> tmp; refineAndPartitionOctree(out,tmp,comm); out = tmp; tmp.clear(); } return 1; } int function2Octree(std::function<double(double,double,double)> fx, std::vector<ot::TreeNode> & nodes,unsigned int maxDepth, const double & tol ,unsigned int elementOrder, MPI_Comm comm ) { int size, rank; MPI_Comm_size(comm, &size); MPI_Comm_rank(comm, &rank); nodes.clear(); std::vector<ot::TreeNode> nodes_new; unsigned int depth = 1; unsigned int num_intersected=1; unsigned int num_intersected_g=1; const unsigned int nodesPerElement=(elementOrder+1)*(elementOrder+1)*(elementOrder+1); double h, h1,h2; double* dist_parent=new double[nodesPerElement]; double* dist_child=new double[nodesPerElement]; double* dist_child_ip=new double[nodesPerElement]; Point pt; Point pt_child; h = 1.0/(1<<(maxDepth)); unsigned int mySz; RefElement refEl(m_uiDim,elementOrder); double l2_norm=0; bool splitOctant=false; if (!rank) { // root does the initial refinement //std::cout<<"initial ref:"<<std::endl; ot::TreeNode root = ot::TreeNode(m_uiDim, maxDepth); root.addChildren(nodes); while ( (num_intersected > 0 ) && (num_intersected < size/**size*/ ) && (depth < maxDepth) ) { std::cout << "Depth: " << depth << " n = " << nodes.size() << std::endl; num_intersected = 0; for (auto elem: nodes ){ splitOctant=false; if ( elem.getLevel() != depth ) { nodes_new.push_back(elem); continue; } mySz=( 1 << (maxDepth - elem.getLevel())); h1 = mySz/(double)elementOrder; // check and split pt = elem.getAnchor(); for( int k=0;k<(elementOrder+1);k++) for( int j=0;j<(elementOrder+1);j++) for( int i=0;i<(elementOrder+1);i++) dist_parent[k*(elementOrder+1)*(elementOrder+1)+j*(elementOrder+1)+i]=fx(pt.x()+i*h1,pt.y()+j*h1,pt.z()+k*h1); for(unsigned int cnum=0;cnum<NUM_CHILDREN;cnum++) { refEl.I3D_Parent2Child(dist_parent,dist_child_ip,cnum); pt_child =Point((pt.x() +(((int)((bool)(cnum & 1u)))<<(m_uiMaxDepth-elem.getLevel()-1))),(pt.y()+(((int)((bool)(cnum & 2u)))<<(m_uiMaxDepth-elem.getLevel()-1))), (pt.z() +(((int)((bool)(cnum & 4u)))<<(m_uiMaxDepth-elem.getLevel()-1)))); //std::cout<<"parent: "<<elem<<" child "<<cnum<<" value: "<<pt_child.x()<<" , "<<pt_child.y()<<" , "<<pt_child.z()<<std::endl; h2=h1/2.0; for( int k=0;k<(elementOrder+1);k++) for( int j=0;j<(elementOrder+1);j++) for( int i=0;i<(elementOrder+1);i++) dist_child[k*(elementOrder+1)*(elementOrder+1)+j*(elementOrder+1)+i]=fx(pt_child.x()+i*h2,pt_child.y()+j*h2,pt_child.z()+k*h2); l2_norm=normLInfty(dist_child,dist_child_ip,nodesPerElement);//normL2(dist_child,dist_child_ip,nodesPerElement)/normL2(dist_child_ip,nodesPerElement); //std::cout<<"l2: "<<l2_norm<<std::endl; if(l2_norm>tol){ splitOctant=true; break; } } if (!splitOctant) { // if (!skipInternal) nodes_new.push_back(elem); }else { // intersection. elem.addChildren(nodes_new); num_intersected++; } } depth++; std::swap(nodes, nodes_new); nodes_new.clear(); } } // !rank // now scatter the elements. DendroIntL totalNumOcts = nodes.size(), numOcts; par::Mpi_Bcast<DendroIntL>(&totalNumOcts, 1, 0, comm); // TODO do proper load balancing. numOcts = totalNumOcts/size + (rank < totalNumOcts%size); par::scatterValues<ot::TreeNode>(nodes, nodes_new, numOcts, comm); std::swap(nodes, nodes_new); nodes_new.clear(); // now refine in parallel. par::Mpi_Bcast(&depth, 1, 0, comm); num_intersected=1; ot::TreeNode root(m_uiDim,m_uiMaxDepth); while ( (num_intersected > 0 ) && (depth < maxDepth) ) { if(!rank)std::cout << "Depth: " << depth << " n = " << nodes.size() << std::endl; num_intersected = 0; for (auto elem: nodes ){ splitOctant=false; if ( elem.getLevel() != depth ) { nodes_new.push_back(elem); continue; } mySz=( 1 << (maxDepth - elem.getLevel())); h1 = mySz/(double)elementOrder; // check and split pt = elem.getAnchor(); for( int k=0;k<(elementOrder+1);k++) for( int j=0;j<(elementOrder+1);j++) for( int i=0;i<(elementOrder+1);i++) dist_parent[k*(elementOrder+1)*(elementOrder+1)+j*(elementOrder+1)+i]=fx(pt.x()+i*h1,pt.y()+j*h1,pt.z()+k*h1); for(unsigned int cnum=0;cnum<NUM_CHILDREN;cnum++) { refEl.I3D_Parent2Child(dist_parent,dist_child_ip,cnum); pt_child =Point((pt.x() +(((int)((bool)(cnum & 1u)))<<(m_uiMaxDepth-elem.getLevel()-1))),(pt.y()+(((int)((bool)(cnum & 2u)))<<(m_uiMaxDepth-elem.getLevel()-1))), (pt.z() +(((int)((bool)(cnum & 4u)))<<(m_uiMaxDepth-elem.getLevel()-1)))); //std::cout<<"parent: "<<elem<<" child "<<cnum<<" value: "<<pt_child.x()<<" , "<<pt_child.y()<<" , "<<pt_child.z()<<std::endl; h2=h1/2.0; for( int k=0;k<(elementOrder+1);k++) for( int j=0;j<(elementOrder+1);j++) for( int i=0;i<(elementOrder+1);i++) dist_child[k*(elementOrder+1)*(elementOrder+1)+j*(elementOrder+1)+i]=fx(pt_child.x()+i*h2,pt_child.y()+j*h2,pt_child.z()+k*h2); l2_norm=normLInfty(dist_child,dist_child_ip,nodesPerElement);//normL2(dist_child,dist_child_ip,nodesPerElement)/normL2(dist_child_ip,nodesPerElement); //std::cout<<"l2: "<<l2_norm<<std::endl; if(l2_norm>tol){ splitOctant=true; break; } } if (!splitOctant) { // if (!skipInternal) nodes_new.push_back(elem); }else { // intersection. elem.addChildren(nodes_new); num_intersected++; } } depth++; std::swap(nodes, nodes_new); nodes_new.clear(); SFC::parSort::SFC_treeSort(nodes,nodes_new,nodes_new,nodes_new,0.1,m_uiMaxDepth,root,ROOT_ROTATION,1,TS_REMOVE_DUPLICATES,2,comm); std::swap(nodes,nodes_new); nodes_new.clear(); par::Mpi_Allreduce(&num_intersected,&num_intersected_g,1,MPI_MAX,comm); num_intersected=num_intersected_g; } delete[] dist_child; delete[] dist_child_ip; delete[] dist_parent; return 0; } int function2Octree(std::function<void(double,double,double,double*)> fx,const unsigned int numVars,const unsigned int* varIndex,const unsigned int numInterpVars, std::vector<ot::TreeNode> & nodes,unsigned int maxDepth, const double & tol ,unsigned int elementOrder,MPI_Comm comm ) { int size, rank; MPI_Comm_size(comm, &size); MPI_Comm_rank(comm, &rank); nodes.clear(); std::vector<ot::TreeNode> nodes_new; unsigned int depth = 1; unsigned int num_intersected=1; unsigned int num_intersected_g=1; const unsigned int nodesPerElement=(elementOrder+1)*(elementOrder+1)*(elementOrder+1); double h, h1,h2; double* varVal=new double [numVars]; double* dist_parent=new double[numVars*nodesPerElement]; double* dist_child=new double[numVars*nodesPerElement]; double* dist_child_ip=new double[numVars*nodesPerElement]; Point pt; Point pt_child; h = 1.0/(1<<(maxDepth)); unsigned int mySz; RefElement refEl(m_uiDim,elementOrder); double l2_norm=0; bool splitOctant=false; if (!rank) { // root does the initial refinement //std::cout<<"initial ref:"<<std::endl; ot::TreeNode root = ot::TreeNode(m_uiDim, maxDepth); root.addChildren(nodes); while ( (num_intersected > 0 ) && (num_intersected < size/**size*/ ) && (depth < maxDepth) ) { std::cout << "Depth: " << depth << " n = " << nodes.size() << std::endl; num_intersected = 0; for (auto elem: nodes ){ splitOctant=false; if ( elem.getLevel() != depth ) { nodes_new.push_back(elem); continue; } mySz=( 1 << (maxDepth - elem.getLevel())); h1 = mySz/(double)elementOrder; h2=h1/2.0; // check and split pt = elem.getAnchor(); for( int k=0;k<(elementOrder+1);k++) for( int j=0;j<(elementOrder+1);j++) for( int i=0;i<(elementOrder+1);i++) { fx(pt.x()+i*h1,pt.y()+j*h1,pt.z()+k*h1,varVal); for(unsigned int var=0;var<numInterpVars;var++) dist_parent[varIndex[var]*nodesPerElement+k*(elementOrder+1)*(elementOrder+1)+j*(elementOrder+1)+i]=varVal[varIndex[var]]; } for(unsigned int cnum=0;cnum<NUM_CHILDREN;cnum++) { pt_child =Point((pt.x() +(((int)((bool)(cnum & 1u)))<<(m_uiMaxDepth-elem.getLevel()-1))),(pt.y()+(((int)((bool)(cnum & 2u)))<<(m_uiMaxDepth-elem.getLevel()-1))), (pt.z() +(((int)((bool)(cnum & 4u)))<<(m_uiMaxDepth-elem.getLevel()-1)))); //std::cout<<"parent: "<<elem<<" child "<<cnum<<" value: "<<pt_child.x()<<" , "<<pt_child.y()<<" , "<<pt_child.z()<<std::endl; for( int k=0;k<(elementOrder+1);k++) for( int j=0;j<(elementOrder+1);j++) for( int i=0;i<(elementOrder+1);i++) { fx(pt_child.x()+i*h2,pt_child.y()+j*h2,pt_child.z()+k*h2,varVal); for(unsigned int var=0;var<numInterpVars;var++) dist_child[varIndex[var]*nodesPerElement+k*(elementOrder+1)*(elementOrder+1)+j*(elementOrder+1)+i]=varVal[varIndex[var]]; } for(unsigned int var=0;var<numInterpVars;var++) { refEl.I3D_Parent2Child(dist_parent+varIndex[var]*nodesPerElement,dist_child_ip+varIndex[var]*nodesPerElement,cnum); l2_norm=normLInfty(dist_child+varIndex[var]*nodesPerElement,dist_child_ip+varIndex[var]*nodesPerElement,nodesPerElement); if(l2_norm>tol) { splitOctant=true; break; } } if(splitOctant) break; } if (!splitOctant) { nodes_new.push_back(elem); }else { elem.addChildren(nodes_new); num_intersected++; } } depth++; std::swap(nodes, nodes_new); nodes_new.clear(); } } // !rank // now scatter the elements. DendroIntL totalNumOcts = nodes.size(), numOcts; par::Mpi_Bcast<DendroIntL>(&totalNumOcts, 1, 0, comm); // TODO do proper load balancing. numOcts = totalNumOcts/size + (rank < totalNumOcts%size); par::scatterValues<ot::TreeNode>(nodes, nodes_new, numOcts, comm); std::swap(nodes, nodes_new); nodes_new.clear(); // now refine in parallel. par::Mpi_Bcast(&depth, 1, 0, comm); num_intersected=1; ot::TreeNode root(m_uiDim,m_uiMaxDepth); while ( (num_intersected > 0 ) && (depth < maxDepth) ) { if(!rank)std::cout << "Depth: " << depth << " n = " << nodes.size() << std::endl; num_intersected = 0; for (auto elem: nodes ){ splitOctant=false; if ( elem.getLevel() != depth ) { nodes_new.push_back(elem); continue; } mySz=( 1 << (maxDepth - elem.getLevel())); h1 = mySz/(double)elementOrder; h2=h1/2.0; // check and split pt = elem.getAnchor(); for( int k=0;k<(elementOrder+1);k++) for( int j=0;j<(elementOrder+1);j++) for( int i=0;i<(elementOrder+1);i++) { fx(pt.x()+i*h1,pt.y()+j*h1,pt.z()+k*h1,varVal); for(unsigned int var=0;var<numInterpVars;var++) dist_parent[varIndex[var]*nodesPerElement+k*(elementOrder+1)*(elementOrder+1)+j*(elementOrder+1)+i]=varVal[varIndex[var]]; } for(unsigned int cnum=0;cnum<NUM_CHILDREN;cnum++) { pt_child =Point((pt.x() +(((int)((bool)(cnum & 1u)))<<(m_uiMaxDepth-elem.getLevel()-1))),(pt.y()+(((int)((bool)(cnum & 2u)))<<(m_uiMaxDepth-elem.getLevel()-1))), (pt.z() +(((int)((bool)(cnum & 4u)))<<(m_uiMaxDepth-elem.getLevel()-1)))); //std::cout<<"parent: "<<elem<<" child "<<cnum<<" value: "<<pt_child.x()<<" , "<<pt_child.y()<<" , "<<pt_child.z()<<std::endl; for( int k=0;k<(elementOrder+1);k++) for( int j=0;j<(elementOrder+1);j++) for( int i=0;i<(elementOrder+1);i++) { fx(pt_child.x()+i*h2,pt_child.y()+j*h2,pt_child.z()+k*h2,varVal); for(unsigned int var=0;var<numInterpVars;var++) dist_child[varIndex[var]*nodesPerElement+k*(elementOrder+1)*(elementOrder+1)+j*(elementOrder+1)+i]=varVal[varIndex[var]]; } for(unsigned int var=0;var<numInterpVars;var++) { refEl.I3D_Parent2Child(dist_parent+varIndex[var]*nodesPerElement,dist_child_ip+varIndex[var]*nodesPerElement,cnum); l2_norm=normLInfty(dist_child+varIndex[var]*nodesPerElement,dist_child_ip+varIndex[var]*nodesPerElement,nodesPerElement); //std::cout<<"rank: "<<rank<<" node: "<<elem<<" l2 norm : "<<l2_norm<<" var: "<<varIndex[var]<<std::endl; if(l2_norm>tol) { splitOctant=true; break; } } if(splitOctant) break; } if (!splitOctant) { nodes_new.push_back(elem); }else { elem.addChildren(nodes_new); num_intersected++; } } depth++; std::swap(nodes, nodes_new); nodes_new.clear(); //par::partitionW<ot::TreeNode>(nodes,NULL,comm); SFC::parSort::SFC_treeSort(nodes,nodes_new,nodes_new,nodes_new,0.1,m_uiMaxDepth,root,ROOT_ROTATION,1,TS_REMOVE_DUPLICATES,2,comm); std::swap(nodes,nodes_new); nodes_new.clear(); par::Mpi_Allreduce(&num_intersected,&num_intersected_g,1,MPI_MAX,comm); num_intersected=num_intersected_g; } delete[] dist_child; delete[] dist_child_ip; delete[] dist_parent; delete[] varVal; return 0; } void octree2BlockDecomposition(std::vector<ot::TreeNode>& pNodes, std::vector<ot::Block>& blockList,unsigned int maxDepth,unsigned int & d_min, unsigned int & d_max,DendroIntL localBegin, DendroIntL localEnd,unsigned int eleOrder,unsigned int coarsetLev) { // Note that we assume pnodes to be sorted. assert(seq::test::isUniqueAndSorted(pNodes)); // Note: Commented out code is for debugging purposes. #ifdef OCT2BLK_DEBUG int rank; MPI_Comm_rank(MPI_COMM_WORLD,&rank); treeNodesTovtk(pNodes,rank,"balOct"); #endif unsigned int x,y,z,hindex,hindexN,index; unsigned int rot_id=ROOT_ROTATION; std::vector<ot::Block> initialBLocks; ot::TreeNode rootNode(0,0,0,0,m_uiDim,maxDepth); d_min=maxDepth; d_max=0; // Computes the dmin and dmax of the tree. for(unsigned int k=0;k<pNodes.size();k++) { if(d_min>pNodes[k].getLevel()) d_min=pNodes[k].getLevel(); if(d_max < pNodes[k].getLevel()) d_max=pNodes[k].getLevel(); } DendroIntL nBegin,nEnd; ot::Block rootBlock(rootNode,ROOT_ROTATION,d_min,localBegin,localEnd,eleOrder); initialBLocks.push_back(rootBlock); unsigned int currRegGridLev=d_min; ot::TreeNode parent; ot::Block tmpBlock; DendroIntL splitters[NUM_CHILDREN+1]; unsigned int childHasRegLev[NUM_CHILDREN]; // 0 if child i does not have any octants at the reg grid lev , and 1 otherwise. //unsigned int numChildHasRegLev=0; unsigned int numRegGridOcts=0; // total number of children that has given reg grid levels. unsigned int pMaxDepthBit=0; //unsigned int debug_rank=1; DendroIntL numIdealRegGridOct=0; double blockFillRatio=0.0; // ratio between number of octants in ideal regular grid and actually available. DendroUInt_128 blockVolume=0; // 128-bit integer to store the volume of the block. . DendroUInt_128 octVolume=0; // 128-bit integer to store oct volume inside a block. bool octLevelGap; while(!initialBLocks.empty()) { tmpBlock=initialBLocks.back(); initialBLocks.pop_back(); parent=tmpBlock.getBlockNode(); currRegGridLev=tmpBlock.getRegularGridLev(); rot_id=tmpBlock.getRotationID(); nBegin=tmpBlock.getLocalElementBegin(); nEnd=tmpBlock.getLocalElementEnd(); assert(parent.getLevel()<=currRegGridLev); octLevelGap=true; if(parent.getLevel()==currRegGridLev) { assert((nEnd-nBegin)==1); assert(pNodes[nBegin]==parent); blockList.push_back(tmpBlock); continue; } numRegGridOcts=0; numIdealRegGridOct=(1u<<(currRegGridLev-parent.getLevel())); blockVolume=1u<<((maxDepth-parent.getLevel())*3); (m_uiDim==3)? numIdealRegGridOct=numIdealRegGridOct*numIdealRegGridOct*numIdealRegGridOct : numIdealRegGridOct=numIdealRegGridOct*numIdealRegGridOct; octVolume=0; for(unsigned int elem=nBegin;elem<nEnd;elem++) { if(pNodes[elem].getLevel()==currRegGridLev) numRegGridOcts++; else if(abs((int)pNodes[elem].getLevel()-(int)currRegGridLev)>OCT2BLK_DECOMP_LEV_GAP){ octLevelGap=false; break; } octVolume+=1u<<(3*(maxDepth-pNodes[elem].getLevel())); } //if(rank==debug_rank) std::cout<<"current parent: "<<parent<<" rot id: "<<(int)rot_id<<" curRegGridLev: "<<currRegGridLev<<" begin: "<<nBegin<<" end: "<<nEnd<<" numRegGridOcts: "<<numRegGridOcts<<std::endl; blockFillRatio=(double) numRegGridOcts/numIdealRegGridOct; if((parent.getLevel()>=coarsetLev) && (octLevelGap) && blockFillRatio>=OCT2BLK_DECOMP_BLK_FILL_RATIO && (octVolume==blockVolume)) { blockList.push_back(tmpBlock); if((currRegGridLev+1)<=d_max) initialBLocks.push_back(ot::Block(parent,rot_id,(currRegGridLev+1),nBegin,nEnd,eleOrder)); }else { // implies that we need to split the tmpBlock. assert(parent.getLevel()<maxDepth); pMaxDepthBit=maxDepth-parent.getLevel()-1; SFC::seqSort::SFC_bucketing(&(*(pNodes.begin())),parent.getLevel(),maxDepth,rot_id,nBegin,nEnd,splitters); for (int i = 0; i < NUM_CHILDREN; i++) { childHasRegLev[i]=0; hindex = (rotations[2 * NUM_CHILDREN * rot_id + i] - '0'); if (i == (NUM_CHILDREN-1)) hindexN = i + 1; else hindexN = (rotations[2 * NUM_CHILDREN * rot_id + i + 1] - '0'); assert(splitters[hindex] <= splitters[hindexN]); for(unsigned int elem=splitters[hindex];elem<splitters[hindexN];elem++) { if(pNodes[elem].getLevel()==currRegGridLev) { childHasRegLev[i]=1; break; } } } for(unsigned int i=0;i<(NUM_CHILDREN);i++) { hindex = (rotations[2 * NUM_CHILDREN * rot_id + i] - '0'); if (i == (NUM_CHILDREN-1)) hindexN = i + 1; else hindexN = (rotations[2 * NUM_CHILDREN * rot_id + i + 1] - '0'); assert(splitters[hindex] <= splitters[hindexN]); index = HILBERT_TABLE[NUM_CHILDREN * rot_id + hindex]; x=parent.getX() +(((int)((bool)(hindex & 1u)))<<(pMaxDepthBit)); y=parent.getY() +(((int)((bool)(hindex & 2u)))<<(pMaxDepthBit)); z=parent.getZ() +(((int)((bool)(hindex & 4u)))<<(pMaxDepthBit)); if((childHasRegLev[i]==1)) { if((parent.getLevel()+1)<=currRegGridLev) { tmpBlock=ot::Block(ot::TreeNode(x,y,z,parent.getLevel()+1,m_uiDim,maxDepth),index,currRegGridLev,splitters[hindex],splitters[hindexN],eleOrder); initialBLocks.push_back(tmpBlock); } }else if(((childHasRegLev[i]==0 && (splitters[hindex]!= splitters[hindexN])))) { if((currRegGridLev+1)<=d_max && ((parent.getLevel()+1) <=(currRegGridLev+1))) { tmpBlock=ot::Block(ot::TreeNode(x,y,z,parent.getLevel()+1,m_uiDim,maxDepth),index,(currRegGridLev+1),splitters[hindex],splitters[hindexN],eleOrder); //if(rank==debug_rank) std::cout<<"block node pushed (initialBlocks): "<<tmpBlock.getBlockNode()<<std::endl; initialBLocks.push_back(tmpBlock); } } } } } std::reverse(blockList.begin(),blockList.end()); #ifdef OCT2BLK_DEBUG std::vector<ot::TreeNode> blockNodes; blockNodes.resize(blockList.size()); for(unsigned int k=0;k<blockList.size();k++) { blockNodes[k]=blockList[k].getBlockNode(); } treeNodesTovtk(blockNodes,rank,"blockNodes"); #endif #ifdef OCT2BLK_DEBUG unsigned int numIdealRegOcts=0; unsigned int numActualRegOcts=0; unsigned int singleOctBlockCount=0; for(unsigned int i=0;i<blockList.size();i++) { numIdealRegOcts=1u<<(blockList[i].getRegularGridLev()-blockList[i].getBlockNode().getLevel()); numIdealRegOcts=numIdealRegOcts*numIdealRegOcts*numIdealRegOcts; numActualRegOcts=0; for(unsigned int j=blockList[i].getLocalElementBegin();j<(blockList[i].getLocalElementEnd());j++) { if(pNodes[j].getLevel()==blockList[i].getRegularGridLev()) numActualRegOcts++; } if(numActualRegOcts==1) singleOctBlockCount++; //std::cout<<"rank: "<<rank<<" block ID: "<<i<<" : "<<blockList[i].getBlockNode()<<" reg lev: "<<blockList[i].getRegularGridLev()<<" ideal reg: "<<numIdealRegOcts<<" actual reg oct: "<<numActualRegOcts<<" ratio: "<<((double)numActualRegOcts/numIdealRegOcts)<<std::endl; } std::cout<<"rank: "<<rank<<" singleOctBlocks: "<<singleOctBlockCount<<" pNodes size: "<<pNodes.size()<<" ratio: "<<(double(singleOctBlockCount)/pNodes.size())<<std::endl; #endif } void blockListToVtk(std::vector<ot::Block>& blkList, const std::vector<ot::TreeNode>& pNodes,char* fNamePrefix, MPI_Comm comm) { int rank,npes; MPI_Comm_rank(comm,&rank); MPI_Comm_size(comm,&npes); std::vector<ot::TreeNode> blockNodeList; std::vector<ot::TreeNode> octsEmbedded; char fNameBlk[256]; char fNameEmbed[256]; for(unsigned int k=0;k<blkList.size();k++) { octsEmbedded.clear(); blockNodeList.clear(); blockNodeList.push_back(blkList[k].getBlockNode()); for(unsigned int j=blkList[k].getLocalElementBegin();j<blkList[k].getLocalElementEnd();j++) octsEmbedded.push_back(pNodes[j]); sprintf(fNameEmbed,"%s_embed_%d",fNamePrefix,k); sprintf(fNameBlk,"%s_blk_%d",fNamePrefix,k); if(rank==0)treeNodesTovtk(blockNodeList,rank,fNameBlk); if(rank==0)treeNodesTovtk(octsEmbedded,rank,fNameEmbed); } } void enforceSiblingsAreNotPartitioned(std::vector<ot::TreeNode> & in,MPI_Comm comm) { // handles the empty octree case. MPI_Comm newComm; par::splitComm2way(in.empty(),&newComm,comm); if(!in.empty()) { comm=newComm; int rank,npes; MPI_Comm_rank(comm,&rank); MPI_Comm_size(comm,&npes); unsigned int prev,next; (rank<(npes-1)) ? next=rank+1: next=0; (rank>0) ? prev=rank-1: prev=(npes-1); //if(in.size()<NUM_CHILDREN) return ; unsigned int blCount=0; int sendCount=0; int recvCount=0; MPI_Request req; MPI_Status status; ot::TreeNode maxNode=in.back(); ot::TreeNode prev_max; if(rank<(npes-1)) sendCount=1; if(rank>0) recvCount=1; par::Mpi_Sendrecv(&maxNode,sendCount,next,0,&prev_max,recvCount,prev,0,comm,&status); sendCount=0; recvCount=0; for(unsigned int elem=0;elem<NUM_CHILDREN;elem++) { if ((elem < in.size()) && (in.front().getParent() == in[elem].getParent())) sendCount++; else break; } if((rank>0) && (sendCount==1) && (in.front().getParent()!=prev_max.getParent())) sendCount=0; if(sendCount==NUM_CHILDREN || rank==0) sendCount=0; //std::cout<<"m_uiActiveRank: "<<m_uiActiveRank<<" sendCount: "<<sendCount<<std::endl; par::Mpi_Sendrecv(&sendCount,1,prev,1,&recvCount,1,next,1,comm,&status); /* MPI_Isend(&sendCount,1,MPI_INT,prev,0,m_uiCommActive,&req); MPI_Recv(&recvCount,1,MPI_INT,next,0,m_uiCommActive,&status);*/ //std::cout<<"m_uiActiveRank: "<<m_uiActiveRank<<" recvCount: "<<recvCount<<std::endl; assert(in.size()>=sendCount); std::vector<ot::TreeNode> recvBuffer; recvBuffer.resize(recvCount); par::Mpi_Sendrecv(&(*(in.begin())),sendCount,prev,2,&(*(recvBuffer.begin())),recvCount,next,2,comm,&status); //std::cout<<"rank: "<<m_uiActiveRank<<" send recv ended "<<std::endl; if(sendCount) { std::vector<ot::TreeNode> tmpElements; std::swap(in,tmpElements); in.clear(); in.resize(tmpElements.size()-sendCount); for(unsigned int ele=sendCount;ele<tmpElements.size();ele++) in[ele-sendCount]=tmpElements[ele]; tmpElements.clear(); } for(unsigned int ele=0;ele<recvBuffer.size();ele++) in.push_back(recvBuffer[ele]); recvBuffer.clear(); assert(seq::test::isUniqueAndSorted(in)); } MPI_Comm_free(&newComm); return ; } void mergeKeys(std::vector<ot::SearchKey>& sKeys,std::vector<ot::Key> & keys) { if(sKeys.size()==0) return; ot::SearchKey rootSkey(m_uiDim,m_uiMaxDepth); std::vector<ot::SearchKey> tmpSKeys; SFC::seqSort::SFC_treeSort(&(*(sKeys.begin())),sKeys.size(),tmpSKeys,tmpSKeys,tmpSKeys,m_uiMaxDepth,m_uiMaxDepth,rootSkey,ROOT_ROTATION,1,TS_SORT_ONLY); assert(seq::test::isSorted(sKeys)); ot::Key tmpKey; unsigned int skip=0; const unsigned int K=1; for(unsigned int e=0;e<(sKeys.size());e++) { tmpKey=ot::Key(sKeys[e].getX(),sKeys[e].getY(),sKeys[e].getZ(),sKeys[e].getLevel(),m_uiDim,m_uiMaxDepth); if(sKeys[e].getOwner()>=0){ tmpKey.addOwner(sKeys[e].getOwner()); tmpKey.addStencilIndexAndDirection(K-1,sKeys[e].getStencilIndexDirectionList()); } skip=1; while(((e+skip)<sKeys.size()) && (sKeys[e]==sKeys[e+skip])) { if(sKeys[e+skip].getOwner()>=0){ tmpKey.addOwner(sKeys[e+skip].getOwner()); tmpKey.addStencilIndexAndDirection(K-1,sKeys[e+skip].getStencilIndexDirectionList()); } skip++; } keys.push_back(tmpKey); e+=(skip-1); } } void generateBlkEdgeSKeys(const ot::Block & blk, std::vector<ot::SearchKey>& sKeys) { const unsigned int domain_max = 1u<<(m_uiMaxDepth); const ot::TreeNode blkNode=blk.getBlockNode(); const unsigned int regLev=blk.getRegularGridLev(); const unsigned int blkElem_1D=(1u<<(regLev-blkNode.getLevel()))*2; const unsigned int myX=blkNode.getX(); const unsigned int myY=blkNode.getY(); const unsigned int myZ=blkNode.getZ(); const unsigned int mySz=1u<<(m_uiMaxDepth-blkNode.getLevel()); const unsigned int hsz=1u<<(m_uiMaxDepth-regLev-1); //hx/2 std::vector<ot::SearchKey>::iterator hint; if(myX>0 && myY>0) { for(unsigned int k=0;k<blkElem_1D;k++) { hint=sKeys.emplace(sKeys.end(),ot::SearchKey((myX-1),(myY-1),(myZ+k*hsz), m_uiMaxDepth, m_uiDim, m_uiMaxDepth)); hint->addOwner(k); hint->addStencilIndexAndDirection(OCT_DIR_LEFT_DOWN); } } if(myX>0 && (myY+mySz)<domain_max) { for(unsigned int k=0;k<blkElem_1D;k++) { hint = sKeys.emplace(sKeys.end(),ot::SearchKey((myX - 1), (myY + mySz), (myZ+k*hsz), m_uiMaxDepth, m_uiDim, m_uiMaxDepth)); hint->addOwner(k); hint->addStencilIndexAndDirection(OCT_DIR_LEFT_UP); } } if(myX>0 && myZ>0) { for(unsigned int k=0;k<blkElem_1D;k++) { hint = sKeys.emplace(sKeys.end(), ot::SearchKey((myX - 1), (myY+k*hsz), (myZ - 1), m_uiMaxDepth, m_uiDim, m_uiMaxDepth)); hint->addOwner(k); hint->addStencilIndexAndDirection(OCT_DIR_LEFT_BACK); } } if(myX>0 && (myZ+mySz)<domain_max) { for(unsigned int k=0;k<blkElem_1D;k++) { hint=sKeys.emplace(sKeys.end(),ot::SearchKey((myX-1),(myY+k*hsz),(myZ+mySz), m_uiMaxDepth, m_uiDim, m_uiMaxDepth)); hint->addOwner(k); hint->addStencilIndexAndDirection(OCT_DIR_LEFT_FRONT); } } if((myX+mySz) < domain_max && myY>0) { for(unsigned int k=0;k<blkElem_1D;k++) { hint=sKeys.emplace(sKeys.end(),ot::SearchKey((myX+mySz),(myY-1),(myZ+k*hsz), m_uiMaxDepth, m_uiDim, m_uiMaxDepth)); hint->addOwner(k); hint->addStencilIndexAndDirection(OCT_DIR_RIGHT_DOWN); } } if((myX+mySz)<domain_max && (myY+mySz)<domain_max) { for(unsigned int k=0;k<blkElem_1D;k++) { hint=sKeys.emplace(sKeys.end(),ot::SearchKey((myX+mySz),(myY+mySz),(myZ+k*hsz), m_uiMaxDepth, m_uiDim, m_uiMaxDepth)); hint->addOwner(k); hint->addStencilIndexAndDirection(OCT_DIR_RIGHT_UP); } } if((myX+mySz)<domain_max && myZ>0) { for(unsigned int k=0;k<blkElem_1D;k++) { hint = sKeys.emplace(sKeys.end(), ot::SearchKey((myX + mySz), (myY+k*hsz), (myZ - 1), m_uiMaxDepth, m_uiDim, m_uiMaxDepth)); hint->addOwner(k); hint->addStencilIndexAndDirection(OCT_DIR_RIGHT_BACK); } } if((myX+mySz)<domain_max && (myZ+mySz)<domain_max) { for(unsigned int k=0;k<blkElem_1D;k++) { hint=sKeys.emplace(sKeys.end(),ot::SearchKey((myX+mySz),(myY+k*hsz),(myZ+mySz), m_uiMaxDepth, m_uiDim, m_uiMaxDepth)); hint->addOwner(k); hint->addStencilIndexAndDirection(OCT_DIR_RIGHT_FRONT); } } if(myY>0 && myZ>0) { for(unsigned int k=0;k<blkElem_1D;k++) { hint=sKeys.emplace(sKeys.end(),ot::SearchKey((myX+k*hsz),(myY-1),(myZ-1), m_uiMaxDepth, m_uiDim, m_uiMaxDepth)); hint->addOwner(k); hint->addStencilIndexAndDirection(OCT_DIR_DOWN_BACK); } } if(myY > 0 && (myZ+mySz)<domain_max) { for(unsigned int k=0;k<blkElem_1D;k++) { hint=sKeys.emplace(sKeys.end(),ot::SearchKey((myX+k*hsz),(myY-1),(myZ+mySz), m_uiMaxDepth, m_uiDim, m_uiMaxDepth)); hint->addOwner(k); hint->addStencilIndexAndDirection(OCT_DIR_DOWN_FRONT); } } if((myY+mySz)<domain_max && myZ>0) { for(unsigned int k=0;k<blkElem_1D;k++) { hint=sKeys.emplace(sKeys.end(),ot::SearchKey((myX+k*hsz),(myY+mySz),(myZ-1), m_uiMaxDepth, m_uiDim, m_uiMaxDepth)); hint->addOwner(k); hint->addStencilIndexAndDirection(OCT_DIR_UP_BACK); } } if((myY+mySz)<domain_max && (myZ+mySz)<domain_max) { for(unsigned int k=0;k<blkElem_1D;k++) { hint = sKeys.emplace(sKeys.end(), ot::SearchKey((myX+k*hsz), (myY + mySz), (myZ + mySz), m_uiMaxDepth, m_uiDim, m_uiMaxDepth)); hint->addOwner(k); hint->addStencilIndexAndDirection(OCT_DIR_UP_FRONT); } } } void generateBlkVertexSKeys(const ot::Block & blk, std::vector<ot::SearchKey>& sKeys) { const unsigned int domain_max = 1u<<(m_uiMaxDepth); const ot::TreeNode blkNode=blk.getBlockNode(); const unsigned int regLev=blk.getRegularGridLev(); const unsigned int blkElem_1D=(1u<<(regLev-blkNode.getLevel()))*2; const unsigned int myX=blkNode.getX(); const unsigned int myY=blkNode.getY(); const unsigned int myZ=blkNode.getZ(); const unsigned int mySz=1u<<(m_uiMaxDepth-blkNode.getLevel()); std::vector<ot::SearchKey>::iterator hint; if((myX>0) && (myY>0) && (myZ>0)) { hint=sKeys.emplace(sKeys.end(),ot::SearchKey((myX-1),(myY-1),(myZ-1), m_uiMaxDepth, m_uiDim, m_uiMaxDepth)); hint->addOwner(0); hint->addStencilIndexAndDirection(OCT_DIR_LEFT_DOWN_BACK); } if(((myX+mySz)<domain_max) && (myY>0) && (myZ>0)) { hint=sKeys.emplace(sKeys.end(),ot::SearchKey((myX+mySz),(myY-1),(myZ-1), m_uiMaxDepth, m_uiDim, m_uiMaxDepth)); hint->addOwner(1); hint->addStencilIndexAndDirection(OCT_DIR_RIGHT_DOWN_BACK); } if((myX>0) && ((myY+mySz)<domain_max) && (myZ>0)) { hint=sKeys.emplace(sKeys.end(),ot::SearchKey((myX-1),(myY+mySz),(myZ-1), m_uiMaxDepth, m_uiDim, m_uiMaxDepth)); hint->addOwner(2); hint->addStencilIndexAndDirection(OCT_DIR_LEFT_UP_BACK); } if(((myX+mySz)<domain_max) && ((myY+mySz)<domain_max) && (myZ>0)) { hint=sKeys.emplace(sKeys.end(),ot::SearchKey((myX+mySz),(myY+mySz),(myZ-1), m_uiMaxDepth, m_uiDim, m_uiMaxDepth)); hint->addOwner(3); hint->addStencilIndexAndDirection(OCT_DIR_RIGHT_UP_BACK); } if((myX>0) && (myY>0) && ((myZ+mySz)<domain_max)) { hint=sKeys.emplace(sKeys.end(),ot::SearchKey((myX-1),(myY-1),(myZ+mySz), m_uiMaxDepth, m_uiDim, m_uiMaxDepth)); hint->addOwner(4); hint->addStencilIndexAndDirection(OCT_DIR_LEFT_DOWN_FRONT); } if(((myX+mySz)<domain_max) && (myY>0) && ((myZ+mySz)<domain_max)) { hint=sKeys.emplace(sKeys.end(),ot::SearchKey((myX+mySz),(myY-1),(myZ+mySz), m_uiMaxDepth, m_uiDim, m_uiMaxDepth)); hint->addOwner(5); hint->addStencilIndexAndDirection(OCT_DIR_RIGHT_DOWN_FRONT); } if((myX>0) && ((myY+mySz)<domain_max) && ((myZ+mySz)<domain_max)) { hint=sKeys.emplace(sKeys.end(),ot::SearchKey((myX-1),(myY+mySz),(myZ+mySz), m_uiMaxDepth, m_uiDim, m_uiMaxDepth)); hint->addOwner(6); hint->addStencilIndexAndDirection(OCT_DIR_LEFT_UP_FRONT); } if(((myX+mySz)<domain_max) && ((myY+mySz)<domain_max) && ((myZ+mySz)<domain_max)) { hint=sKeys.emplace(sKeys.end(),ot::SearchKey((myX+mySz),(myY+mySz),(myZ+mySz), m_uiMaxDepth, m_uiDim, m_uiMaxDepth)); hint->addOwner(7); hint->addStencilIndexAndDirection(OCT_DIR_RIGHT_UP_FRONT); } } unsigned int rankSelectRule(unsigned int size_global,unsigned int rank_global, unsigned int size_local,unsigned int rank_i) { if(size_local>size_global){std::cout<<"[Error] : "<<__func__<<" rank: "<<rank_global<<" size_local > size_global "<<std::endl; exit(0);} // Rule 1 [enable this code to choose consecative ranks (deafult) works with any size_global and size_local] #ifdef BSSN_CONSEC_COMM_SELECT return rank_i; #else // Rule 2 [select ranks which is equivalent to complete binary tree fashion (size_global) & (rank_global) needs to be power of two.] if((!binOp::isPowerOfTwo(size_global)) || (!binOp::isPowerOfTwo(size_local))) return rank_i; else { const unsigned int commMaxLevel=binOp::fastLog2(size_global); const unsigned int commLevel=binOp::fastLog2(size_local); const unsigned int commK=1u<<(commMaxLevel-commLevel); return rank_i*commK; } #endif }
35.999167
281
0.561657
[ "mesh", "vector" ]
1d3280f5481dfede29dbc25d8e132a99156cc641
39,324
cpp
C++
deadjustice/GameLevel.cpp
Andrewich/deadjustice
48bea56598e79a1a10866ad41aa3517bf7d7c724
[ "BSD-3-Clause" ]
3
2019-04-20T10:16:36.000Z
2021-03-21T19:51:38.000Z
deadjustice/GameLevel.cpp
Andrewich/deadjustice
48bea56598e79a1a10866ad41aa3517bf7d7c724
[ "BSD-3-Clause" ]
null
null
null
deadjustice/GameLevel.cpp
Andrewich/deadjustice
48bea56598e79a1a10866ad41aa3517bf7d7c724
[ "BSD-3-Clause" ]
2
2020-04-18T20:04:24.000Z
2021-09-19T05:07:41.000Z
#include "GameLevel.h" #include "GameCamera.h" #include "GameFlareSet.h" #include "GameBSPTree.h" #include "GameCharacter.h" #include "GameCell.h" #include "GameRenderPass.h" #include "GameCutScene.h" #include "GamePortal.h" #include "GameWeapon.h" #include "GameNoiseManager.h" #include "ProjectileManager.h" #include "GameBoxTrigger.h" #include "ScriptUtil.h" #include <anim/Control.h> #include <io/File.h> #include <io/InputStream.h> #include <io/InputStreamArchive.h> #include <sg/Dummy.h> #include <sg/Effect.h> #include <sg/LineList.h> #include <ps/ParticleSystemManager.h> #include <sg/Node.h> #include <sg/Camera.h> #include <sg/Mesh.h> #include <sg/Model.h> #include <sg/VertexLock.h> #include <lang/Math.h> #include <lang/Debug.h> #include <lang/String.h> #include <lang/Float.h> #include <lang/Character.h> #include <math/lerp.h> #include <math/Vector3.h> #include <music/MusicManager.h> #include <script/VM.h> #include <script/ClassTag.h> #include <script/ScriptException.h> #include <sgu/NodeGroupSet.h> #include <sgu/SceneManager.h> #include <snd/SoundManager.h> #include <util/Vector.h> #include <algorithm> #include "config.h" //----------------------------------------------------------------------------- ScriptMethod<GameLevel> GameLevel::sm_methods[] = { ScriptMethod<GameLevel>( "createBoxTrigger", script_createBoxTrigger ), ScriptMethod<GameLevel>( "createCharacter", script_createCharacter ), ScriptMethod<GameLevel>( "createNoise", script_createNoise ), ScriptMethod<GameLevel>( "createWeapon", script_createWeapon ), ScriptMethod<GameLevel>( "createFlareSet", script_createFlareSet ), ScriptMethod<GameLevel>( "endLevel", script_endLevel ), ScriptMethod<GameLevel>( "getCell", script_getCell ), ScriptMethod<GameLevel>( "getPath", script_getPath ), ScriptMethod<GameLevel>( "getCharacter", script_getCharacter ), ScriptMethod<GameLevel>( "getDynamicObject", script_getDynamicObject ), ScriptMethod<GameLevel>( "loadDynamicObjects", script_loadDynamicObjects ), ScriptMethod<GameLevel>( "loadProjectiles", script_loadProjectiles ), ScriptMethod<GameLevel>( "importGeometry", script_importGeometry ), ScriptMethod<GameLevel>( "isActiveCutScene", script_isActiveCutScene ), ScriptMethod<GameLevel>( "playCutScene", script_playCutScene ), ScriptMethod<GameLevel>( "setBackgroundToCells", script_setBackgroundToCells ), ScriptMethod<GameLevel>( "setShadowColor", script_setShadowColor ), ScriptMethod<GameLevel>( "setMainCharacter", script_setMainCharacter ), ScriptMethod<GameLevel>( "signalExplosion", script_signalExplosion ), ScriptMethod<GameLevel>( "skipCutScene", script_skipCutScene ), ScriptMethod<GameLevel>( "removeCharacter", script_removeCharacter ), ScriptMethod<GameLevel>( "removeWeapon", script_removeWeapon ), ScriptMethod<GameLevel>( "removeTrigger", script_removeTrigger ), ScriptMethod<GameLevel>( "removeDynamicObjects", script_removeDynamicObjects ), }; //----------------------------------------------------------------------------- using namespace io; using namespace sg; using namespace ps; using namespace sgu; using namespace snd; using namespace pix; using namespace anim; using namespace lang; using namespace math; using namespace util; using namespace music; using namespace script; //----------------------------------------------------------------------------- GameLevel::GameLevel( script::VM* vm, io::InputStreamArchive* arch, snd::SoundManager* soundMgr, ps::ParticleSystemManager* particleMgr, sgu::SceneManager* sceneMgr, music::MusicManager* musicMgr, ProjectileManager* projectileMgr, GameNoiseManager* noiseMgr, int bspBuildPolySkip ) : GameScriptable( vm, arch, soundMgr, particleMgr ), m_methodBase( -1 ), m_vm( vm ), m_arch( arch ), m_soundMgr( soundMgr ), m_particleMgr( particleMgr ), m_sceneMgr( sceneMgr ), m_musicMgr( musicMgr ), m_projectileMgr( projectileMgr ), m_noiseMgr( noiseMgr ), m_levelEnded( false ), m_animSet( new NodeGroupSet ), m_cells( Allocator<P(GameCell)>(__FILE__) ), m_bspBuildPolySkip( bspBuildPolySkip ), m_defaultCollisionMaterialType( 0 ), m_collisionMaterialTypes( Allocator<P(GameSurface)>(__FILE__) ), m_shadowColor(1,1,1,1), m_backgrounds( Allocator<P(Node)>(__FILE__) ), m_lightmapShader( 0 ), m_triggerList( Allocator<P(GameBoxTrigger)>(__FILE__) ), m_pathList( Allocator<P(GamePath)>(__FILE__) ), m_characterList( Allocator<P(GameCharacter)>(__FILE__) ), m_weaponList( Allocator<P(GameWeapon)>(__FILE__) ), m_dynamicObjectList( Allocator<P(GameDynamicObject)>(__FILE__) ), m_dynamicObjectBSPs( Allocator< HashtablePair<String,P(bsp::BSPTree)> >(__FILE__) ), m_flareSetList( Allocator<P(GameFlareSet)>(__FILE__) ), m_mainCharacter( 0 ), m_cutScene( 0 ), m_removed( Allocator<P(GameObject)>(__FILE__) ) { m_methodBase = ScriptUtil<GameLevel,GameScriptable>::addMethods( this, sm_methods, sizeof(sm_methods)/sizeof(sm_methods[0]) ); // load lightmap shader P(InputStream) in = m_arch->getInputStream( "misc/lightmap.fx" ); m_lightmapShader = new Effect( in ); in->close(); } GameLevel::~GameLevel() { m_vm = 0; m_arch = 0; m_soundMgr = 0; m_particleMgr = 0; m_sceneMgr = 0; m_musicMgr = 0; m_projectileMgr = 0; m_animSet = 0; m_characterList.clear(); m_weaponList.clear(); m_mainCharacter = 0; for ( int i = 0; i < m_cells.size() ; ++i ) m_cells[i]->m_level = 0; m_cells.clear(); } GameDynamicObject* GameLevel::createDynamicObject( sg::Node* node, const lang::String& bspFileName, const math::Matrix4x4& tm, GameCell* cell ) { if ( m_dynamicObjectBSPs[bspFileName] ) Debug::println( "Creating dynamic object {0} (BSP from cache)", node->name() ); else Debug::println( "Creating dynamic object {0}", node->name() ); // create DO P(GameDynamicObject) dynamicObject = new GameDynamicObject( vm(), archive(), m_sceneMgr, soundManager(), particleSystemManager(), m_projectileMgr, m_noiseMgr, node, bspFileName, m_bspBuildPolySkip, m_collisionMaterialTypes, m_dynamicObjectBSPs[bspFileName] ); dynamicObject->setTransform( cell, tm ); dynamicObject->setName( node->name() ); // cache BSP m_dynamicObjectBSPs[bspFileName] = dynamicObject->bspTree()->tree(); // check for unique names for ( int i = 0 ; i < m_dynamicObjectList.size() ; ++i ) { if ( m_dynamicObjectList[i]->name() == dynamicObject->name() ) throw Exception( Format("Tried to add second dynamic object with name {0}", dynamicObject->name()) ); } m_dynamicObjectList.add( dynamicObject ); return dynamicObject; } void GameLevel::loadFile( const String& filename ) { String path = File(m_arch->getInputStream( filename )->toString()).getParent(); P(sg::Node) scene = m_sceneMgr->getScene( filename )->clone(); replaceLightmapMaterialsWithShader( scene, m_lightmapShader ); // Check that all top level nodes are either cells or portals for ( Node* it = scene->firstChild() ; it ; it = scene->getNextChild(it) ) { if ( getNodeClass(it) == NODECLASS_NORMAL ) Debug::printlnWarning( "Top-level object {0} is not CELL, PORTAL or BACKGROUND", it->name() ); } // Extract background objects for ( Node* it = scene; it ; it = it->nextInHierarchy() ) { if ( getNodeClass(it) == NODECLASS_BACKGROUND ) { P(Node) bg = it->clone(); Debug::println( "Found background {0}", bg->name() ); bg->setTransform( it->worldTransform() ); m_backgrounds.add( bg ); } } // Build list of Cells Vector<Matrix4x4> dynamicObjectTms( Allocator<Matrix4x4>(__FILE__) ); Vector<P(Node)> dynamicObjects( Allocator<P(Node)>(__FILE__) ); for ( Node* iterator = scene; iterator; iterator = iterator->nextInHierarchy() ) { // Detect CELL if ( getNodeClass( iterator ) == NODECLASS_CELL ) { P(Node) cellScene = iterator->clone(); Debug::println( "Found cell {0}", cellScene->name() ); setRenderPasses( cellScene, GameRenderPass::RENDERPASS_LEVEL_SOLID, GameRenderPass::RENDERPASS_LEVEL_TRANSPARENT ); // translate cell to origin (=cell children to world space) // NOTE: this breaks animated objects parented to cell like cameras Matrix4x4 celltm = cellScene->transform(); for ( Node* child = cellScene->firstChild() ; child ; child = cellScene->getNextChild(child) ) child->setTransform( celltm * child->transform() ); cellScene->setTransform( Matrix4x4(1.f) ); // find and remove dynamic object nodes from the scene graph dynamicObjectTms.clear(); dynamicObjects.clear(); for ( Node* child = cellScene ; child ; child = child->nextInHierarchy() ) { if ( child->name().indexOf("DYNAMIC") != -1 ) { dynamicObjectTms.add( child->worldTransform() ); dynamicObjects.add( child ); } } for ( int i = 0 ; i < dynamicObjects.size() ; ++i ) dynamicObjects[i]->unlink(); // create cell object String name = cellScene->name(); String path = File(m_arch->getInputStream( filename )->toString()).getParent(); String bspFileName = path + "/" + name + ".bsp"; P(GameCell) cell = new GameCell( m_vm, m_arch, m_soundMgr, m_particleMgr, name, cellScene, bspFileName, m_bspBuildPolySkip, m_collisionMaterialTypes ); cell->m_level = this; m_cells.add( cell ); // create dynamic objects for ( int i = 0 ; i < dynamicObjects.size() ; ++i ) { P(Node) node = dynamicObjects[i]; Matrix4x4 tm = dynamicObjectTms[i]; String bspFileName = path + "/" + removeEndNumberSuffix(node->name()) + ".bsp"; createDynamicObject( node, bspFileName, tm, cell ); } } } // Add portals to cells, each portal is mirrored to two cells (the ones it is connecting) for ( sg::Node* iterator = scene; iterator; iterator = iterator->nextInHierarchy() ) { // Detect PORTAL if ( getNodeClass( iterator ) == NODECLASS_PORTAL ) { // check that we have Dummy node Dummy* dummy = dynamic_cast<Dummy*>( iterator ); if ( !dummy ) throw Exception( Format("Portal {0} must be dummy object", iterator->name()) ); // check name const String& name = dummy->name(); int separator = name.indexOf('-'); if ( separator == -1 ) throw Exception( Format("Cell Separator '-' not found in Portal {0} node name!", dummy->name()) ); // get cell names String firstcell = name.substring( 7, separator ); String secondcell = name.substring( separator + 1 ); // make portal corners Matrix4x4 worldtransform = dummy->worldTransform(); Matrix3x3 wrot = worldtransform.rotation(); Vector3 dx = wrot.getColumn(0) * dummy->boxMax().x; Vector3 dy = wrot.getColumn(1) * dummy->boxMax().y; Vector3 dz = wrot.getColumn(2) * dummy->boxMax().z; Vector3 center = worldtransform.translation(); float scalex = dx.length(); float scaley = dy.length(); float scalez = dz.length(); float absminscale = Math::min( Math::abs(scalex), Math::min(Math::abs(scaley),Math::abs(scalez)) ); Vector3 corners[4]; if ( Math::abs(scalex) <= absminscale ) { // portal in y,z plane corners[0] = center - dz + dy; corners[1] = center + dz + dy; corners[2] = center + dz - dy; corners[3] = center - dz - dy; } else if ( Math::abs(scaley) <= absminscale ) { // portal in x,z plane corners[0] = center - dx + dz; corners[1] = center + dx + dz; corners[2] = center + dx - dz; corners[3] = center - dx - dz; } else if ( Math::abs(scalez) <= absminscale ) { // portal in x,y plane corners[0] = center - dx + dy; corners[1] = center + dx + dy; corners[2] = center + dx - dy; corners[3] = center - dx - dy; } else { throw Exception( Format("Portal {0} is not smallest in X-dimension", dummy->name()) ); } GameCell* first = getCell( firstcell ); GameCell* second = getCell( secondcell ); if ( first == 0 || second == 0 ) throw Exception( Format( "Portal name {0} contains invalid Cell names!", dummy->name()) ); // add portals to the cells P(GamePortal) portal1 = new GamePortal( corners, second ); first->addPortal( portal1 ); std::reverse( corners, corners+GamePortal::NUM_CORNERS ); P(GamePortal) portal2 = new GamePortal( corners, first ); second->addPortal( portal2 ); } } // Build list of AI guard paths for ( int i = 0 ; i < cells() ; ++i ) { GameCell* cell = getCell(i); for ( Node* it = cell->getRenderObject(0) ; it ; it = it->nextInHierarchy() ) { Mesh* mesh = dynamic_cast<Mesh*>( it ); if ( mesh ) { Matrix4x4 tm = mesh->worldTransform(); for ( int k = 0 ; k < mesh->primitives() ; ++k ) { P(LineList) lineList = dynamic_cast<LineList*>( mesh->getPrimitive(k) ); if ( lineList ) { VertexLock<LineList> lk( lineList, LineList::LOCK_READ ); Debug::println( "Found AI guard path {0} from cell {1}", mesh->name(), cell->name() ); Debug::println( "AI guard path (lines={1}) found from {0}", mesh->name(), lineList->lines() ); if ( mesh->primitives() > 1 ) throw Exception( Format("AI guard path in {0} must be defined by single poly line", mesh->name() ) ); P(GamePath) path = new GamePath( m_vm, m_arch, mesh->name() ); for ( int n = 0 ; n < lineList->lines() ; ++n ) { Vector3 start, end; lineList->getLine( n, &start, &end ); start = tm.transform( start ); path->addPoint( start ); } Vector3 xaxis = (path->getPoint(1) - path->getPoint(0)).normalize(); path->setNumber( "startPointDirection0", xaxis.x ); path->setNumber( "startPointDirection1", xaxis.y ); path->setNumber( "startPointDirection2", xaxis.z ); path->setTable( "startPointCell", cell ); m_pathList.add( path ); mesh->removePrimitive(k); break; } } } Dummy* dummy = dynamic_cast<Dummy*>( it ); if ( dummy ) { Debug::println( "Found AI guard dummy {0} from cell {1}", dummy->name(), cell->name() ); P(GamePath) path = new GamePath( m_vm, m_arch, dummy->name() ); path->addPoint( dummy->worldTransform().translation() ); Vector3 xaxis = dummy->worldTransform().rotation().getColumn(0).normalize(); path->setNumber( "startPointDirection0", xaxis.x ); path->setNumber( "startPointDirection1", xaxis.y ); path->setNumber( "startPointDirection2", xaxis.z ); path->setTable( "startPointCell", cell ); m_pathList.add( path ); } } } } bool GameLevel::ended() const { return m_levelEnded; } GameLevel::NodeClass GameLevel::getNodeClass( sg::Node* node ) { const String& name = node->name(); if ( name.indexOf("PORTAL") != -1 ) return NODECLASS_PORTAL; else if ( name.indexOf("CELL") != -1 ) return NODECLASS_CELL; else if ( name.indexOf("PATH") != -1 ) return NODECLASS_PATH; else if ( dynamic_cast<Camera*>(node) ) return NODECLASS_CAMERA; else if ( name.indexOf("BACKGROUND") != -1 ) return NODECLASS_BACKGROUND; else return NODECLASS_NORMAL; } void GameLevel::update( float dt ) { m_removed.clear(); GameScriptable::update( dt ); // update cells for ( int i = 0 ; i < m_cells.size() ; ++i ) m_cells[i]->update( dt ); // update active cut scene if any if ( m_cutScene ) { m_cutScene->update( dt ); if ( m_cutScene->ended() ) m_cutScene = 0; } } void GameLevel::removeObject( GameObject* obj ) { P(GameObject) o = obj; obj->removeTimerEvents(); obj->setPosition( 0, Vector3(0,0,0) ); m_removed.add( obj ); } void GameLevel::removeNonMainCharacters() { for ( int i = 0 ; i < m_characterList.size() ; ++i ) { if ( m_characterList[i] != mainCharacter() ) { removeObject( m_characterList[i] ); m_characterList.remove( i-- ); } } } void GameLevel::skipCutScene() { if ( m_cutScene ) { pushMethod( "signalSkipCutScene" ); vm()->pushTable( m_cutScene ); call( 1, 0 ); } } int GameLevel::cells() const { return m_cells.size(); } int GameLevel::characters() const { return m_characterList.size(); } int GameLevel::triggers() const { return m_triggerList.size(); } int GameLevel::paths() const { return m_pathList.size(); } GameCell* GameLevel::getCell( int index ) const { return m_cells[index].ptr(); } GameCell* GameLevel::getCell( const String& name ) const { for ( int i = 0; i < m_cells.size(); ++i ) if ( m_cells[i]->name() == name ) return m_cells[i].ptr(); throw Exception( Format("Cell {0} not found", name) ); return 0; } GameCharacter* GameLevel::getCharacter( const String& name ) const { for ( int i = 0; i < m_characterList.size(); ++i ) if ( m_characterList[i]->name() == name ) return m_characterList[i].ptr(); throw Exception( Format("Character {0} not found", name) ); return 0; } GameCharacter* GameLevel::getCharacter( int index ) const { return m_characterList[index]; } GameBoxTrigger* GameLevel::getTrigger( int index ) const { return m_triggerList[index]; } GamePath* GameLevel::getPath( int index ) const { return m_pathList[index]; } int GameLevel::dynamicObjects() const { return m_dynamicObjectList.size(); } GameDynamicObject* GameLevel::getDynamicObject( int i ) const { return m_dynamicObjectList[i]; } GameDynamicObject* GameLevel::getDynamicObject( const String& name ) const { for ( int i = 0; i < m_dynamicObjectList.size(); ++i ) if ( m_dynamicObjectList[i]->name() == name ) return m_dynamicObjectList[i].ptr(); throw Exception( Format("Dynamic object {0} not found", name) ); return 0; } GamePath* GameLevel::getPath( const String& name ) const { for ( int i = 0; i < m_pathList.size(); ++i ) if ( m_pathList[i]->name() == name ) return m_pathList[i].ptr(); throw Exception( Format("Path {0} not found", name) ); return 0; } GameCharacter* GameLevel::mainCharacter() const { assert( m_mainCharacter ); return m_mainCharacter; } GameSurface* GameLevel::defaultCollisionMaterialType() const { return m_defaultCollisionMaterialType; } GameWeapon* GameLevel::getWeapon( int index ) const { return m_weaponList[index]; } int GameLevel::weapons() const { return m_weaponList.size(); } GameCutScene* GameLevel::activeCutScene() const { assert( m_cutScene ); return m_cutScene; } bool GameLevel::isActiveCutScene() const { return m_cutScene != 0; } pix::Color GameLevel::shadowColor() const { return m_shadowColor; } void GameLevel::removeWeapon( GameWeapon* weapon ) { int index = m_weaponList.indexOf(weapon); if ( index != -1 ) { P(GameWeapon) weapon = m_weaponList[index]; removeObject( m_weaponList[index] ); m_projectileMgr->removeWeaponProjectiles( m_weaponList[index] ); m_weaponList.remove( index ); } } void GameLevel::signalViewChanged() { for ( int i = 0 ; i < m_characterList.size() ; ++i ) { GameCharacter* obj = m_characterList[i]; obj->forceVisible(); if ( obj->hasWeapon() ) obj->weapon()->forceVisible(); } for ( int i = 0 ; i < m_flareSetList.size() ; ++i ) { GameFlareSet* flareSet = m_flareSetList[i]; for ( int k = 0 ; k < flareSet->flares() ; ++k ) flareSet->getFlare(k).setFade( -1.f ); } } String GameLevel::removeEndNumberSuffix( const String& str ) { String s = str; int suffix = s.length()-1; while ( suffix > 0 && Character::isDigit(s.charAt(suffix)) ) --suffix; if ( suffix != s.length()-1 && suffix > 0 && s.charAt(suffix) == '_' ) s = s.substring( 0, suffix ); return s; } int GameLevel::methodCall( VM* vm, int i ) { return ScriptUtil<GameLevel,GameScriptable>::methodCall( this, vm, i, m_methodBase, sm_methods, sizeof(sm_methods)/sizeof(sm_methods[0]) ); } int GameLevel::script_importGeometry( script::VM* vm, const char* funcName ) { int tags1[] = {VM::TYPE_STRING, VM::TYPE_TABLE}; if ( !hasParams(tags1,sizeof(tags1)/sizeof(tags1[0])) ) throw ScriptException( Format("{0} expects level scene file name and a table of collision material types (first one default)", funcName) ); String sceneName = vm->toString(1); // create collision material types Vector<P(GameSurface)> collisionMaterialTypes( Allocator<P(GameSurface)>(__FILE__) ); Table tab = vm->toTable(2); for ( int i = 1 ; !tab.isNil(i) ; ++i ) { Table mtl = tab.getTable(i); String typeName = mtl.getString( "typeName" ); float sneakingNoiseLevel = mtl.getNumber( "sneakingNoiseLevel" ); float walkingNoiseLevel = mtl.getNumber( "walkingNoiseLevel" ); float runningNoiseLevel = mtl.getNumber( "runningNoiseLevel" ); float movementNoiseDistance = mtl.getNumber( "movementNoiseDistance" ); P(GameSurface) gameSurface = new GameSurface( m_vm, m_arch, typeName ); gameSurface->setString( "typeName", typeName ); gameSurface->setNumber( "sneakingNoiseLevel", sneakingNoiseLevel ); gameSurface->setNumber( "walkingNoiseLevel", walkingNoiseLevel ); gameSurface->setNumber( "runningNoiseLevel", runningNoiseLevel ); gameSurface->setNumber( "movementNoiseDistance", movementNoiseDistance ); collisionMaterialTypes.add( gameSurface ); } if ( collisionMaterialTypes.size() == 0 ) throw ScriptException( Format("No collision material types given to {0} call", funcName) ); m_collisionMaterialTypes = collisionMaterialTypes; m_defaultCollisionMaterialType = collisionMaterialTypes.firstElement(); loadFile( sceneName ); return 0; } int GameLevel::script_loadDynamicObjects( script::VM* vm, const char* funcName ) { int tags1[] = {VM::TYPE_STRING}; if ( !hasParams(tags1,sizeof(tags1)/sizeof(tags1[0])) ) throw ScriptException( Format("{0} expects level scene file name", funcName) ); String filename = vm->toString(1); String path = File(m_arch->getInputStream( filename )->toString()).getParent(); P(Node) scene = m_sceneMgr->getScene( filename )->clone(); Table names( vm ); int nameIndex = 0; Vector<Matrix4x4> dynamicObjectTms( Allocator<Matrix4x4>(__FILE__) ); Vector<P(Node)> dynamicObjects( Allocator<P(Node)>(__FILE__) ); for ( Node* iterator = scene; iterator; iterator = iterator->nextInHierarchy() ) { // Detect CELL if ( getNodeClass( iterator ) == NODECLASS_CELL ) { P(Node) cellScene = iterator->clone(); Debug::println( "loadDynamicObjects: Found cell {0}", cellScene->name() ); // translate cell to origin (=cell children to world space) // NOTE: this breaks animated objects parented to cell like cameras Matrix4x4 celltm = cellScene->transform(); for ( Node* child = cellScene->firstChild() ; child ; child = cellScene->getNextChild(child) ) child->setTransform( celltm * child->transform() ); cellScene->setTransform( Matrix4x4(1.f) ); // find and remove dynamic object nodes from the scene graph dynamicObjectTms.clear(); dynamicObjects.clear(); for ( Node* child = cellScene ; child ; child = child->nextInHierarchy() ) { if ( child->name().indexOf("DYNAMIC") != -1 ) { dynamicObjectTms.add( child->worldTransform() ); dynamicObjects.add( child ); } } for ( int i = 0 ; i < dynamicObjects.size() ; ++i ) dynamicObjects[i]->unlink(); // find cell object String name = cellScene->name(); GameCell* cell = getCell( name ); // create dynamic objects for ( int i = 0 ; i < dynamicObjects.size() ; ++i ) { P(Node) node = dynamicObjects[i]; Matrix4x4 tm = dynamicObjectTms[i]; tm.setTranslation( Vector3(0,-1e6f,0) ); String bspFileName = path + "/" + removeEndNumberSuffix(node->name()) + ".bsp"; P(GameDynamicObject) dynamicObject = createDynamicObject( node, bspFileName, tm, cell ); // return names of added dynamic objects names.setString( ++nameIndex, dynamicObject->name() ); } } } vm->pushTable( names ); return 1; } int GameLevel::script_removeCharacter( script::VM* vm, const char* funcName ) { int tags[] = {VM::TYPE_TABLE}; if ( !hasParams(tags,sizeof(tags)/sizeof(tags[0])) ) throw ScriptException( Format("{0} expects character object", funcName) ); P(GameCharacter) obj = dynamic_cast<GameCharacter*>( getThisPtr(vm, 1) ); if ( !obj ) throw ScriptException( Format("{0} expects character object", funcName) ); int index = m_characterList.indexOf( obj ); if ( index != -1 ) { removeObject( m_characterList[index] ); m_characterList.remove( index ); Debug::println( "Removed character {0}", obj->name() ); P(GameWeapon) weapon = obj->weapon(); if ( weapon ) { int index = m_weaponList.indexOf( weapon ); if ( index != -1 ) { removeObject( m_weaponList[index] ); m_projectileMgr->removeWeaponProjectiles( m_weaponList[index] ); m_weaponList.remove( index ); Debug::println( "Removed weapon {0}", weapon->name() ); } } } return 0; } int GameLevel::script_removeWeapon( script::VM* vm, const char* funcName ) { int tags[] = {VM::TYPE_TABLE}; if ( !hasParams(tags,sizeof(tags)/sizeof(tags[0])) ) throw ScriptException( Format("{0} expects weapon object", funcName) ); P(GameWeapon) obj = dynamic_cast<GameWeapon*>( getThisPtr(vm, 1) ); if ( !obj ) throw ScriptException( Format("{0} expects weapon object", funcName) ); int index = m_weaponList.indexOf( obj ); if ( index != -1 ) { removeObject( m_weaponList[index] ); m_projectileMgr->removeWeaponProjectiles( m_weaponList[index] ); m_weaponList.remove( index ); Debug::println( "Removed weapon {0}", obj->name() ); } return 0; } int GameLevel::script_removeTrigger( script::VM* vm, const char* funcName ) { int tags[] = {VM::TYPE_TABLE}; if ( !hasParams(tags,sizeof(tags)/sizeof(tags[0])) ) throw ScriptException( Format("{0} expects trigger object", funcName) ); P(GameBoxTrigger) obj = dynamic_cast<GameBoxTrigger*>( getThisPtr(vm, 1) ); if ( !obj ) throw ScriptException( Format("{0} expects trigger object", funcName) ); int index = m_triggerList.indexOf( obj ); if ( index != -1 ) { removeObject( m_triggerList[index] ); m_triggerList.remove( index ); Debug::println( "Removed trigger {0}", obj->name() ); } return 0; } int GameLevel::script_removeDynamicObjects( script::VM* vm, const char* funcName ) { int tags1[] = {VM::TYPE_TABLE}; if ( !hasParams(tags1,sizeof(tags1)/sizeof(tags1[0])) ) throw ScriptException( Format("{0} expects table of dynamic object names", funcName) ); Table names = vm->toTable(1); for ( int i = 1 ; !names.isNil(i) ; ++i ) { String name = names.getString(i); P(GameDynamicObject) obj = getDynamicObject(name); removeObject( obj ); m_dynamicObjectList.remove( m_dynamicObjectList.indexOf(obj) ); Debug::println( "Removed dynamic object {0}", name ); } return 0; } int GameLevel::script_getCell( script::VM* vm, const char* funcName ) { int tags1[] = {VM::TYPE_STRING}; int tags2[] = {VM::TYPE_NUMBER}; if ( !hasParams(tags1,sizeof(tags1)/sizeof(tags1[0])) && !hasParams(tags2,sizeof(tags2)/sizeof(tags2[0])) ) throw ScriptException( Format("{0} returns cell by name or index.", funcName) ); if ( vm->isNumber(1) ) { int index = (int)vm->toNumber(1); if ( index < 1 || index > cells() ) throw ScriptException( Format("{0}: Invalid index {1}, number of cells is {2}.", funcName, index, cells()) ); index -= 1; vm->pushTable( getCell(index) ); } else { String name = vm->toString(1); GameCell* cell = getCell( name ); if ( !cell ) throw ScriptException( Format("{0}: Cell {1} not found", funcName, name) ); vm->pushTable( cell ); } return 1; } int GameLevel::script_createBoxTrigger( script::VM* vm, const char* funcName ) { int tags[] = {VM::TYPE_STRING, VM::TYPE_STRING}; if ( !hasParams(tags,sizeof(tags)/sizeof(tags[0])) ) throw ScriptException( Format("{0} expects trigger script filename and trigger dummy object name", funcName ) ); String scriptName = vm->toString(1); String dummyName = vm->toString(2); P(GameBoxTrigger) trigger = new GameBoxTrigger( m_vm, m_arch, m_soundMgr ); trigger->compile( scriptName ); bool triggerCellFound = false; for ( int i = 0 ; i < m_cells.size() && !triggerCellFound ; ++i ) { for ( Node* node = m_cells[i]->getRenderObject(0) ; node ; node = node->nextInHierarchy() ) { if ( node->name() == dummyName ) { Dummy* dummy = dynamic_cast<Dummy*>( node ); if ( !dummy ) throw ScriptException( Format("Tried to create box trigger {0} but {1} is not dummy object", scriptName, dummyName) ); trigger->setTransform( m_cells[i], dummy->worldTransform() ); trigger->setDimensions( dummy->boxMax() ); triggerCellFound = true; break; } } } if ( !triggerCellFound ) throw ScriptException( Format("Tried to create box trigger {0} but dummy object {1} was not found", scriptName, dummyName) ); m_triggerList.add( trigger ); vm->pushTable( trigger ); return 1; } int GameLevel::script_createCharacter( script::VM* vm, const char* funcName ) { int tags[] = {VM::TYPE_STRING}; if ( !hasParams(tags,sizeof(tags)/sizeof(tags[0])) ) throw ScriptException( Format("{0} expects script filename", funcName ) ); P(GameCharacter) nu = new GameCharacter( m_vm, m_arch, m_animSet, m_sceneMgr, m_soundMgr, m_particleMgr, m_projectileMgr, m_noiseMgr ); nu->compile( vm->toString(1) ); m_characterList.add( nu ); vm->pushTable( nu ); return 1; } int GameLevel::script_createWeapon( script::VM* vm, const char* funcName ) { int tags[] = {VM::TYPE_STRING}; if ( !hasParams(tags,sizeof(tags)/sizeof(tags[0])) ) throw ScriptException( Format("{0} expects script filename", funcName ) ); P(GameWeapon) nu = new GameWeapon( m_vm, m_arch, m_soundMgr, m_particleMgr, m_sceneMgr, m_projectileMgr, m_noiseMgr ); nu->compile( vm->toString(1) ); m_weaponList.add( nu ); vm->pushTable( nu ); return 1; } int GameLevel::script_setMainCharacter( script::VM* vm, const char* funcName ) { int tags[] = {VM::TYPE_TABLE}; if ( !hasParams(tags,sizeof(tags)/sizeof(tags[0])) ) throw ScriptException( Format("{0} expects GameCharacter object table", funcName ) ); GameCharacter* c = dynamic_cast<GameCharacter*>(getThisPtr(vm, 1 )); if ( !c ) throw ScriptException( Format("{0} expects GameCharacter object table", funcName ) ); m_mainCharacter = c; m_mainCharacter->setControlSource( GameCharacter::CONTROL_USER ); return 0; } int GameLevel::script_getPath( script::VM* vm, const char* funcName ) { int tags[] = {VM::TYPE_STRING}; if ( !hasParams(tags,sizeof(tags)/sizeof(tags[0])) ) throw ScriptException( Format("{0} returns guard path by name", funcName ) ); String pathName = vm->toString(1); GamePath* path = getPath( pathName ); vm->pushTable( path ); return 1; } int GameLevel::script_getCharacter( script::VM* vm, const char* funcName ) { int tags[] = {VM::TYPE_STRING}; if ( !hasParams(tags,sizeof(tags)/sizeof(tags[0])) ) throw ScriptException( Format("{0} returns character by name", funcName ) ); String characterName = vm->toString(1); GameCharacter* character = getCharacter( characterName ); vm->pushTable( character ); return 1; } int GameLevel::script_getDynamicObject( script::VM* vm, const char* funcName ) { int tags[] = {VM::TYPE_STRING}; if ( !hasParams(tags,sizeof(tags)/sizeof(tags[0])) ) throw ScriptException( Format("{0} returns dynamic level geometry object by name", funcName ) ); String name = vm->toString(1); GameDynamicObject* obj = getDynamicObject( name ); vm->pushTable( obj ); return 1; } int GameLevel::script_createNoise( VM* vm, const char* funcName ) { int tags[] = {VM::TYPE_TABLE, VM::TYPE_NUMBER, VM::TYPE_NUMBER, VM::TYPE_NUMBER, VM::TYPE_NUMBER, VM::TYPE_NUMBER}; if ( !hasParams(tags,sizeof(tags)/sizeof(tags[0])) ) throw ScriptException( Format("{0} expects noise source game object, noise level, fade distance start, fade distance end, fade out time start, fade out time end", funcName) ); int param = 1; GameObject* source = dynamic_cast<GameObject*>( getThisPtr(vm, param++) ); float noiseLevel = vm->toNumber( param++ ); float fadeDistanceStart = vm->toNumber( param++ ); float fadeDistanceEnd = vm->toNumber( param++ ); float fadeOutTimeStart = vm->toNumber( param++ ); float fadeOutTimeEnd = vm->toNumber( param++ ); if ( isActiveCutScene() ) { noiseLevel = 0.f; fadeDistanceStart = 0.f; fadeDistanceEnd = 0.f; } if ( !source ) throw ScriptException( Format("{0} expects noise source game object, noise level, fade distance start, fade distance end, fade out time start, fade out time end", funcName) ); Debug::println( "{0} created noise: level={1}, distance={2}", source->name(), noiseLevel, fadeDistanceEnd ); GameNoise* noise = m_noiseMgr->createNoise( source, noiseLevel, fadeDistanceStart, fadeDistanceEnd, fadeOutTimeStart, fadeOutTimeEnd ); vm->pushTable( noise ); return 1; } int GameLevel::script_signalExplosion( script::VM* vm, const char* funcName ) { int tags[] = {VM::TYPE_TABLE, VM::TYPE_NUMBER, VM::TYPE_NUMBER, VM::TYPE_NUMBER}; if ( !hasParams(tags,sizeof(tags)/sizeof(tags[0])) ) throw ScriptException( Format("{0} expects explosion source, damage, damage fade out start distance, damage fade out end distance", funcName) ); int param = 1; GameObject* source = dynamic_cast<GameObject*>( getThisPtr(vm, param++) ); float damage = vm->toNumber( param++ ); float fadeDistanceStart = vm->toNumber( param++ ); float fadeDistanceEnd = vm->toNumber( param++ ); float endDistanceSqr = fadeDistanceEnd * fadeDistanceEnd; if ( !source ) throw ScriptException( Format("{0} expects explosion source, damage, damage fade out start distance, damage fade out end distance", funcName) ); for ( int i = 0 ; i < m_characterList.size() ; ++i ) { GameCharacter* obj = m_characterList[i]; float distSqr = Math::max( 0.f, (obj->position() - source->position()).lengthSquared() - obj->boundSphere()*obj->boundSphere() ); if ( distSqr < endDistanceSqr ) { float causedDamage = lerp( damage, 0.f, (Math::sqrt(distSqr)-fadeDistanceStart)/Math::max(fadeDistanceEnd-fadeDistanceStart,1e-6f) ); obj->receiveExplosion( source, causedDamage ); } } for ( int i = 0 ; i < m_dynamicObjectList.size() ; ++i ) { GameDynamicObject* obj = m_dynamicObjectList[i]; if ( obj != source ) { float distSqr = Math::max( 0.f, (obj->position() - source->position()).lengthSquared() - obj->boundSphere()*obj->boundSphere() ); if ( distSqr < endDistanceSqr ) { float causedDamage = lerp( damage, 0.f, (Math::sqrt(distSqr)-fadeDistanceStart)/Math::max(fadeDistanceEnd-fadeDistanceStart,1e-6f) ); obj->receiveExplosion( source, causedDamage ); } } } return 0; } int GameLevel::script_isActiveCutScene( script::VM* vm, const char* funcName ) { if ( vm->top() != 0 ) throw ScriptException( Format("{0} returns true if cut scene is active.", funcName) ); vm->pushBoolean( m_cutScene != 0 ); return 1; } int GameLevel::script_playCutScene( script::VM* vm, const char* funcName ) { int tags[] = {VM::TYPE_STRING}; if ( !hasParams(tags,sizeof(tags)/sizeof(tags[0])) ) throw ScriptException( Format("{0} expects cut scene lua file name", funcName) ); skipCutScene(); String cutSceneName = vm->toString(1); P(GameCutScene) cutScene = new GameCutScene( vm, m_arch, m_sceneMgr, m_soundMgr, m_particleMgr, m_projectileMgr ); cutScene->compile( cutSceneName ); m_cutScene = cutScene; vm->pushTable( m_cutScene ); return 1; } int GameLevel::script_loadProjectiles( script::VM* vm, const char* funcName ) { int tags[] = {VM::TYPE_STRING, VM::TYPE_NUMBER}; if ( !hasParams(tags,sizeof(tags)/sizeof(tags[0])) ) throw ScriptException( Format("{0} pre-loads 'count' projectiles to projectilemanager cache, expects projectile source file name and count", funcName) ); String projectileName = vm->toString(1); int count = (int)vm->toNumber(2); m_projectileMgr->allocateProjectiles( projectileName, count ); return 0; } int GameLevel::script_setShadowColor( VM* vm, const char* funcName ) { float v[4]; int rv = getParams( vm, funcName, "RGBA 0-255", v, 4 ); for ( int i = 0 ; i < 4 ; ++i ) if ( v[i] < 0.f || v[i] > 255.f ) throw ScriptException( Format("Func {0} expects integer RGBA 0-255", funcName) ); m_shadowColor = Color( (uint8_t)v[0], (uint8_t)v[1], (uint8_t)v[2], (uint8_t)v[3] ); return rv; } int GameLevel::script_setBackgroundToCells( VM* vm, const char* funcName ) { int tags[] = {VM::TYPE_STRING, VM::TYPE_TABLE}; if ( !hasParams(tags,sizeof(tags)/sizeof(tags[0])) ) throw ScriptException( Format("{0} background (BACKGROUND tagged) object name and table of cell names", funcName) ); String backgroundName = vm->toString(1); Table cellNames = vm->toTable(2); // find background object P(Node) background = 0; for ( int i = 0 ; i < m_backgrounds.size() ; ++i ) { if ( m_backgrounds[i]->name() == backgroundName ) { background = m_backgrounds[i]; break; } } if ( !background ) throw ScriptException( Format("{0}: Cannot find background object {1} (no BACKGROUND tag?)", funcName, backgroundName) ); // set background object to cells for ( int i = 1 ; !cellNames.isNil(i) ; ++i ) { String cellName = cellNames.getString(i); GameCell* cell = getCell(cellName); cell->setBackground( background ); } return 0; } int GameLevel::script_createFlareSet( VM* vm, const char* funcName ) { int tags[] = {VM::TYPE_STRING, VM::TYPE_NUMBER, VM::TYPE_NUMBER, VM::TYPE_NUMBER, VM::TYPE_STRING}; if ( !hasParams(tags,sizeof(tags)/sizeof(tags[0])) ) throw ScriptException( Format("{0} expects flare image name, flare world diameter, fade time, max count and cell name", funcName) ); int param = 1; String imageName = vm->toString( param++ ); float worldSize = vm->toNumber( param++ ); float fadeTime = vm->toNumber( param++ ); int maxFlares = (int)vm->toNumber( param++ ); String cellName = vm->toString( param++ ); P(GameFlareSet) flareSet = new GameFlareSet( vm, m_arch, imageName, worldSize, fadeTime, maxFlares ); flareSet->setPosition( getCell(cellName), Vector3(0,0,0) ); m_flareSetList.add( flareSet ); vm->pushTable( flareSet ); return 1; } int GameLevel::script_endLevel( VM* vm, const char* funcName ) { if ( vm->top() != 0 ) throw ScriptException( Format("{0} ends active level", funcName) ); m_levelEnded = true; return 0; } int GameLevel::script_skipCutScene( VM* vm, const char* funcName ) { if ( vm->top() != 0 ) throw ScriptException( Format("{0} skips any active cut scene", funcName) ); if ( m_cutScene ) { m_cutScene->skip(); m_cutScene = 0; } return 0; }
32.85213
261
0.660742
[ "mesh", "geometry", "object", "vector", "model", "transform" ]
1d3452b4ac5cf6c3748a12f14f1a0c9b971030d1
937
cpp
C++
rdp/src/test_json.cpp
wmacevoy/languages-wmacevoy
fe80126597a652f7c480c81d12b2764395a7c5b5
[ "MIT" ]
null
null
null
rdp/src/test_json.cpp
wmacevoy/languages-wmacevoy
fe80126597a652f7c480c81d12b2764395a7c5b5
[ "MIT" ]
null
null
null
rdp/src/test_json.cpp
wmacevoy/languages-wmacevoy
fe80126597a652f7c480c81d12b2764395a7c5b5
[ "MIT" ]
1
2022-02-17T16:43:06.000Z
2022-02-17T16:43:06.000Z
// https://github.com/nlohmann/json #include "port.h" #include "gtest/gtest.h" // using json = JSON; TEST(json,string) { // https://pspdfkit.com/blog/2021/string-literals-character- -and-multiplatform-cpp std::string s = u8R"-=-({ "happy": "😀", "pi": 3.141 })-=-"_string; JSON j = JSON::parse(s); ASSERT_EQ(j["happy"],u8R"-=-(😀)-=-"); ASSERT_EQ(j["pi"],3.141); } TEST(json,object) { JSON j1; j1["answer"]["everything"] = 42; j1["fibonacci"]={1,1,2,3,5,8}; JSON j2=u8R"-=-({ "answer": { "everything": 42 }, "fibonacci" : [1,1,2,3,5,8] })-=-"_JSON; ASSERT_EQ(j1,j2); for (auto& [key, value] : j1.items()) { std::ostringstream oss; oss << "j1[" << key << "]=" << value; std::string expect; if (key == "answer") expect=u8R"-=-(j1[answer]={"everything":42})-=-"_string; if (key == "fibonacci") expect=u8R"-=-(j1[fibonacci]=[1,1,2,3,5,8])-=-"_string; ASSERT_EQ(expect,oss.str()); } }
26.027778
92
0.565635
[ "object" ]
1d3847ba9c1240f4b1449521b7e89cc65d799cbf
4,157
cc
C++
homeworks/ParametricElementMatrices/templates/parametricelementmatrices_main.cc
padomu/NPDECODES
d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e
[ "MIT" ]
null
null
null
homeworks/ParametricElementMatrices/templates/parametricelementmatrices_main.cc
padomu/NPDECODES
d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e
[ "MIT" ]
null
null
null
homeworks/ParametricElementMatrices/templates/parametricelementmatrices_main.cc
padomu/NPDECODES
d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e
[ "MIT" ]
null
null
null
/** @brief NPDE homework ParametricElementMatrices code * @author Simon Meierhans, Erick Schulz (refactoring) * @date 13/03/2019, 19/11/2019 (refactoring) * @copyright Developed at ETH Zurich */ // Lehrfempp includes #include <lf/io/io.h> // ParametricElementMatrices internal includes #include "anisotropicdiffusionelementmatrixprovider.h" #include "fesourceelemvecprovider.h" #include "impedanceboundaryedgematrixprovider.h" int main() { /* PRODUCE MESH AND FE SPACE */ // Create a Lehrfem++ square tensor product mesh using internal routines lf::mesh::hybrid2d::TPTriagMeshBuilder builder( std::make_unique<lf::mesh::hybrid2d::MeshFactory>(2)); // Set mesh parameters following the Builder pattern // Domain is the unit square builder.setBottomLeftCorner(Eigen::Vector2d{-1.0, -1.0}) .setTopRightCorner(Eigen::Vector2d{1, 1}) .setNumXCells(50) .setNumYCells(50); auto mesh_p = builder.Build(); // Finite element space auto fe_space = std::make_shared<lf::uscalfe::FeSpaceLagrangeO1<double>>(mesh_p); // Obtain local->global index mapping for current finite element space const lf::assemble::DofHandler &dofh{fe_space->LocGlobMap()}; // Dimension of finite element space const lf::base::size_type N_dofs(dofh.NumDofs()); /* GENERATE BVP DATA */ // Interpolate variable coefficient function w(x) = sin(|x|) auto w_func = [](Eigen::Vector2d x) -> double { return std::sin(x.norm()); }; lf::mesh::utils::MeshFunctionGlobal mf_w_func{w_func}; auto w = lf::uscalfe::NodalProjection<double>(*fe_space, mf_w_func); // Create direction vector entering the anisotropic diffusion tensor auto d = [](Eigen::Vector2d x) -> Eigen::Vector2d { return x; }; /* PRODUCE LINEAR SYSTEM OF EQUATIONS */ // Initialize Galerkin matrix in triplets format lf::assemble::COOMatrix<double> A(N_dofs, N_dofs); // Initialize load vector Eigen::Matrix<double, Eigen::Dynamic, 1> phi(N_dofs); phi.setZero(); // Create the classes containing the information required for the local // computations of the Galerkin matrices and the load vector. auto elmat_builder = ParametricElementMatrices::AnisotropicDiffusionElementMatrixProvider(d); auto edgemat_builder = ParametricElementMatrices::ImpedanceBoundaryEdgeMatrixProvider(fe_space, w); auto elvec_builder = ParametricElementMatrices::FESourceElemVecProvider(fe_space, w); // Compute the Galerkin matrices // Invoke assembly on cells (co-dimension = 0 as first argument) and edges // (co-dimension = 1 as first argument). Information about the mesh and the // local-to-global map is passed through the Dofhandler object, argument // 'dofh'. This function call adds triplets to the internal COO-format // representation of the sparse matrixA. lf::assemble::AssembleMatrixLocally(0, dofh, dofh, elmat_builder, A); lf::assemble::AssembleMatrixLocally(1, dofh, dofh, edgemat_builder, A); // Compute the load vector // Invoke assembly on cells (co-dimension = 0 as first argument) AssembleVectorLocally(0, dofh, elvec_builder, phi); /* SOLVE LINEAR SYSTEM OF EQUATIONS */ Eigen::SparseMatrix<double> A_crs = A.makeSparse(); Eigen::SparseLU<Eigen::SparseMatrix<double>> solver; solver.compute(A_crs); Eigen::VectorXd sol_vec = solver.solve(phi); /* SAVE RESULTS */ // Output results to vtk file lf::io::VtkWriter vtk_writer(mesh_p, "parametric_element_matrices_solution.vtk"); // Write nodal data taking the values of the discrete solution at the vertices auto nodal_data = lf::mesh::utils::make_CodimMeshDataSet<double>(mesh_p, 2); for (int global_idx = 0; global_idx < N_dofs; global_idx++) { nodal_data->operator()(dofh.Entity(global_idx)) = sol_vec[global_idx]; }; vtk_writer.WritePointData("parametric_element_matrices_solution", *nodal_data); /* SAM_LISTING_END_1 */ std::cout << "\n The approximate solution was written to:" << std::endl; std::cout << ">> parametric_element_matrices_solution.vtk\n" << std::endl; return 0; }
45.184783
80
0.712052
[ "mesh", "object", "vector" ]
1d3b0b7edd6f1b1bb4a90787c9e0e0ed1b53382d
3,023
hpp
C++
RL/rlConcept.hpp
roamiri/GeoNS
48789d9b382adddfad8223425249088a3050abdb
[ "MIT" ]
2
2020-01-11T04:41:58.000Z
2020-04-27T16:38:40.000Z
RL/rlConcept.hpp
roamiri/GeoNS
48789d9b382adddfad8223425249088a3050abdb
[ "MIT" ]
null
null
null
RL/rlConcept.hpp
roamiri/GeoNS
48789d9b382adddfad8223425249088a3050abdb
[ "MIT" ]
null
null
null
/* This file is part of rl-lib * * Copyright (C) 2010, Supelec * * Author : Herve Frezza-Buet and Matthieu Geist * * Contributor : * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License (GPL) as published by the Free Software Foundation; either * version 3 of the License, or any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Contact : Herve.Frezza-Buet@supelec.fr Matthieu.Geist@supelec.fr * */ namespace rl { namespace concept { /** * @short The simulator itself * * A simulator is the external world, or the dynamical process * that is controlled by the agent through successive actions. It * also includes the reward. Its current state is calle the * current phase, to avoid ambiguity with the state in * reinforcement learning. Indeed, the state space is a model use * by the agent to represent the phase of the simulator. From each * phase, an observation can be provided, as with sensors for a * real robotic system. In most simulated cases, phase and state * are the same, as well as observation if observable markovian * processes are used. */ template <typename ACTION,typename OBSERVATION, typename REWARD> class Simulator { public: Simulator(void); ~Simulator(void); /** * This gives the observation corresponding to current phase. */ const OBSERVATION& sense(void) const; /** * This triggers a transition to a new phase, consecutivly to action a. This call may raise a rl::exception::Terminal if some terminal state is reached. */ void timeStep(const ACTION& a); /** * This gives the reward obtained from the last phase transition. */ REWARD reward(void) const; }; template<typename S, typename A, typename R> class SarsaCritic { public: /** * This updates the critic internal model from a terminal transition. */ void learn(const S& s, const A& a, const R& r); /** * This updates the critic internal model from a non-terminal transition. */ void learn(const S& s, const A& a, const R& r, const S& s_, const A& a_); }; template<typename TRANSITION_ITER> class BatchCritic { public: /** * This learns from all transitions. */ void operator()(const TRANSITION_ITER& begin, const TRANSITION_ITER& end); }; } }
29.930693
158
0.649355
[ "model" ]
1d41955a6453073caa30c93d7e01d680cf833aae
43,319
cpp
C++
module.cpp
number201724/hlmaster
0c872c4fb8ad3c5f01b3b73fdfbc0f29cafdf683
[ "MIT" ]
null
null
null
module.cpp
number201724/hlmaster
0c872c4fb8ad3c5f01b3b73fdfbc0f29cafdf683
[ "MIT" ]
null
null
null
module.cpp
number201724/hlmaster
0c872c4fb8ad3c5f01b3b73fdfbc0f29cafdf683
[ "MIT" ]
null
null
null
/* AMX Mod X * * by the AMX Mod X Development Team * originally developed by OLO * * Parts Copyright (C) 2001-2003 Will Day <willday@hpgx.net> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * In addition, as a special exception, the author gives permission to * link the code of this program with the Half-Life Game Engine ("HL * Engine") and Modified Game Libraries ("MODs") developed by Valve, * L.L.C ("Valve"). You must obey the GNU General Public License in all * respects for all of the code used other than the HL Engine and MODs * from Valve. If you modify this file, you may extend this exception * to your version of the file, but you are not obligated to do so. If * you do not wish to do so, delete this exception statement from your * version. * * Description: AMX Mod X Module Interface Functions */ #include <string.h> #include <new> #include <stdarg.h> #include <stdlib.h> #include <stdio.h> #include "module.h" /************* METAMOD SUPPORT *************/ enginefuncs_t g_engfuncs; globalvars_t *gpGlobals; DLL_FUNCTIONS *g_pFunctionTable; DLL_FUNCTIONS *g_pFunctionTable_Post; enginefuncs_t *g_pengfuncsTable; enginefuncs_t *g_pengfuncsTable_Post; NEW_DLL_FUNCTIONS *g_pNewFunctionsTable; NEW_DLL_FUNCTIONS *g_pNewFunctionsTable_Post; // GetEntityAPI2 functions static DLL_FUNCTIONS g_EntityAPI_Table = { #ifdef FN_GameDLLInit FN_GameDLLInit, #else NULL, #endif #ifdef FN_DispatchSpawn FN_DispatchSpawn, #else NULL, #endif #ifdef FN_DispatchThink FN_DispatchThink, #else NULL, #endif #ifdef FN_DispatchUse FN_DispatchUse, #else NULL, #endif #ifdef FN_DispatchTouch FN_DispatchTouch, #else NULL, #endif #ifdef FN_DispatchBlocked FN_DispatchBlocked, #else NULL, #endif #ifdef FN_DispatchKeyValue FN_DispatchKeyValue, #else NULL, #endif #ifdef FN_DispatchSave FN_DispatchSave, #else NULL, #endif #ifdef FN_DispatchRestore FN_DispatchRestore, #else NULL, #endif #ifdef FN_DispatchObjectCollsionBox FN_DispatchObjectCollsionBox, #else NULL, #endif #ifdef FN_SaveWriteFields FN_SaveWriteFields, #else NULL, #endif #ifdef FN_SaveReadFields FN_SaveReadFields, #else NULL, #endif #ifdef FN_SaveGlobalState FN_SaveGlobalState, #else NULL, #endif #ifdef FN_RestoreGlobalState FN_RestoreGlobalState, #else NULL, #endif #ifdef FN_ResetGlobalState FN_ResetGlobalState, #else NULL, #endif #ifdef FN_ClientConnect FN_ClientConnect, #else NULL, #endif #ifdef FN_ClientDisconnect FN_ClientDisconnect, #else NULL, #endif #ifdef FN_ClientKill FN_ClientKill, #else NULL, #endif #ifdef FN_ClientPutInServer FN_ClientPutInServer, #else NULL, #endif #ifdef FN_ClientCommand FN_ClientCommand, #else NULL, #endif #ifdef FN_ClientUserInfoChanged FN_ClientUserInfoChanged, #else NULL, #endif #ifdef FN_ServerActivate FN_ServerActivate, #else NULL, #endif #ifdef FN_ServerDeactivate FN_ServerDeactivate, #else NULL, #endif #ifdef FN_PlayerPreThink FN_PlayerPreThink, #else NULL, #endif #ifdef FN_PlayerPostThink FN_PlayerPostThink, #else NULL, #endif #ifdef FN_StartFrame FN_StartFrame, #else NULL, #endif #ifdef FN_ParmsNewLevel FN_ParmsNewLevel, #else NULL, #endif #ifdef FN_ParmsChangeLevel FN_ParmsChangeLevel, #else NULL, #endif #ifdef FN_GetGameDescription FN_GetGameDescription, #else NULL, #endif #ifdef FN_PlayerCustomization FN_PlayerCustomization, #else NULL, #endif #ifdef FN_SpectatorConnect FN_SpectatorConnect, #else NULL, #endif #ifdef FN_SpectatorDisconnect FN_SpectatorDisconnect, #else NULL, #endif #ifdef FN_SpectatorThink FN_SpectatorThink, #else NULL, #endif #ifdef FN_Sys_Error FN_Sys_Error, #else NULL, #endif #ifdef FN_PM_Move FN_PM_Move, #else NULL, #endif #ifdef FN_PM_Init FN_PM_Init, #else NULL, #endif #ifdef FN_PM_FindTextureType FN_PM_FindTextureType, #else NULL, #endif #ifdef FN_SetupVisibility FN_SetupVisibility, #else NULL, #endif #ifdef FN_UpdateClientData FN_UpdateClientData, #else NULL, #endif #ifdef FN_AddToFullPack FN_AddToFullPack, #else NULL, #endif #ifdef FN_CreateBaseline FN_CreateBaseline, #else NULL, #endif #ifdef FN_RegisterEncoders FN_RegisterEncoders, #else NULL, #endif #ifdef FN_GetWeaponData FN_GetWeaponData, #else NULL, #endif #ifdef FN_CmdStart FN_CmdStart, #else NULL, #endif #ifdef FN_CmdEnd FN_CmdEnd, #else NULL, #endif #ifdef FN_ConnectionlessPacket FN_ConnectionlessPacket, #else NULL, #endif #ifdef FN_GetHullBounds FN_GetHullBounds, #else NULL, #endif #ifdef FN_CreateInstancedBaselines FN_CreateInstancedBaselines, #else NULL, #endif #ifdef FN_InconsistentFile FN_InconsistentFile, #else NULL, #endif #ifdef FN_AllowLagCompensation FN_AllowLagCompensation #else NULL #endif }; // g_EntityAPI2_Table // GetEntityAPI2_Post functions static DLL_FUNCTIONS g_EntityAPI_Post_Table = { #ifdef FN_GameDLLInit_Post FN_GameDLLInit_Post, #else NULL, #endif #ifdef FN_DispatchSpawn_Post FN_DispatchSpawn_Post, #else NULL, #endif #ifdef FN_DispatchThink_Post FN_DispatchThink_Post, #else NULL, #endif #ifdef FN_DispatchUse_Post FN_DispatchUse_Post, #else NULL, #endif #ifdef FN_DispatchTouch_Post FN_DispatchTouch_Post, #else NULL, #endif #ifdef FN_DispatchBlocked_Post FN_DispatchBlocked_Post, #else NULL, #endif #ifdef FN_DispatchKeyValue_Post FN_DispatchKeyValue_Post, #else NULL, #endif #ifdef FN_DispatchSave_Post FN_DispatchSave_Post, #else NULL, #endif #ifdef FN_DispatchRestore_Post FN_DispatchRestore_Post, #else NULL, #endif #ifdef FN_DispatchObjectCollsionBox_Post FN_DispatchObjectCollsionBox_Post, #else NULL, #endif #ifdef FN_SaveWriteFields_Post FN_SaveWriteFields_Post, #else NULL, #endif #ifdef FN_SaveReadFields_Post FN_SaveReadFields_Post, #else NULL, #endif #ifdef FN_SaveGlobalState_Post FN_SaveGlobalState_Post, #else NULL, #endif #ifdef FN_RestoreGlobalState_Post FN_RestoreGlobalState_Post, #else NULL, #endif #ifdef FN_ResetGlobalState_Post FN_ResetGlobalState_Post, #else NULL, #endif #ifdef FN_ClientConnect_Post FN_ClientConnect_Post, #else NULL, #endif #ifdef FN_ClientDisconnect_Post FN_ClientDisconnect_Post, #else NULL, #endif #ifdef FN_ClientKill_Post FN_ClientKill_Post, #else NULL, #endif #ifdef FN_ClientPutInServer_Post FN_ClientPutInServer_Post, #else NULL, #endif #ifdef FN_ClientCommand_Post FN_ClientCommand_Post, #else NULL, #endif #ifdef FN_ClientUserInfoChanged_Post FN_ClientUserInfoChanged_Post, #else NULL, #endif #ifdef FN_ServerActivate_Post FN_ServerActivate_Post, #else NULL, #endif #ifdef FN_ServerDeactivate_Post FN_ServerDeactivate_Post, #else NULL, #endif #ifdef FN_PlayerPreThink_Post FN_PlayerPreThink_Post, #else NULL, #endif #ifdef FN_PlayerPostThink_Post FN_PlayerPostThink_Post, #else NULL, #endif #ifdef FN_StartFrame_Post FN_StartFrame_Post, #else NULL, #endif #ifdef FN_ParmsNewLevel_Post FN_ParmsNewLevel_Post, #else NULL, #endif #ifdef FN_ParmsChangeLevel_Post FN_ParmsChangeLevel_Post, #else NULL, #endif #ifdef FN_GetGameDescription_Post FN_GetGameDescription_Post, #else NULL, #endif #ifdef FN_PlayerCustomization_Post FN_PlayerCustomization_Post, #else NULL, #endif #ifdef FN_SpectatorConnect_Post FN_SpectatorConnect_Post, #else NULL, #endif #ifdef FN_SpectatorDisconnect_Post FN_SpectatorDisconnect_Post, #else NULL, #endif #ifdef FN_SpectatorThink_Post FN_SpectatorThink_Post, #else NULL, #endif #ifdef FN_Sys_Error_Post FN_Sys_Error_Post, #else NULL, #endif #ifdef FN_PM_Move_Post FN_PM_Move_Post, #else NULL, #endif #ifdef FN_PM_Init_Post FN_PM_Init_Post, #else NULL, #endif #ifdef FN_PM_FindTextureType_Post FN_PM_FindTextureType_Post, #else NULL, #endif #ifdef FN_SetupVisibility_Post FN_SetupVisibility_Post, #else NULL, #endif #ifdef FN_UpdateClientData_Post FN_UpdateClientData_Post, #else NULL, #endif #ifdef FN_AddToFullPack_Post FN_AddToFullPack_Post, #else NULL, #endif #ifdef FN_CreateBaseline_Post FN_CreateBaseline_Post, #else NULL, #endif #ifdef FN_RegisterEncoders_Post FN_RegisterEncoders_Post, #else NULL, #endif #ifdef FN_GetWeaponData_Post FN_GetWeaponData_Post, #else NULL, #endif #ifdef FN_CmdStart_Post FN_CmdStart_Post, #else NULL, #endif #ifdef FN_CmdEnd_Post FN_CmdEnd_Post, #else NULL, #endif #ifdef FN_ConnectionlessPacket_Post FN_ConnectionlessPacket_Post, #else NULL, #endif #ifdef FN_GetHullBounds_Post FN_GetHullBounds_Post, #else NULL, #endif #ifdef FN_CreateInstancedBaselines_Post FN_CreateInstancedBaselines_Post, #else NULL, #endif #ifdef FN_InconsistentFile_Post FN_InconsistentFile_Post, #else NULL, #endif #ifdef FN_AllowLagCompensation FN_AllowLagCompensation, #else NULL, #endif }; // g_EntityAPI2_Table static enginefuncs_t g_EngineFuncs_Table = { #ifdef FN_PrecacheModel FN_PrecacheModel, #else NULL, #endif #ifdef FN_PrecacheSound FN_PrecacheSound, #else NULL, #endif #ifdef FN_SetModel FN_SetModel, #else NULL, #endif #ifdef FN_ModelIndex FN_ModelIndex, #else NULL, #endif #ifdef FN_ModelFrames FN_ModelFrames, #else NULL, #endif #ifdef FN_SetSize FN_SetSize, #else NULL, #endif #ifdef FN_ChangeLevel FN_ChangeLevel, #else NULL, #endif #ifdef FN_GetSpawnParms FN_GetSpawnParms, #else NULL, #endif #ifdef FN_SaveSpawnParms FN_SaveSpawnParms, #else NULL, #endif #ifdef FN_VecToYaw FN_VecToYaw, #else NULL, #endif #ifdef FN_VecToAngles FN_VecToAngles, #else NULL, #endif #ifdef FN_MoveToOrigin FN_MoveToOrigin, #else NULL, #endif #ifdef FN_ChangeYaw FN_ChangeYaw, #else NULL, #endif #ifdef FN_ChangePitch FN_ChangePitch, #else NULL, #endif #ifdef FN_FindEntityByString FN_FindEntityByString, #else NULL, #endif #ifdef FN_GetEntityIllum FN_GetEntityIllum, #else NULL, #endif #ifdef FN_FindEntityInSphere FN_FindEntityInSphere, #else NULL, #endif #ifdef FN_FindClientInPVS FN_FindClientInPVS, #else NULL, #endif #ifdef FN_EntitiesInPVS FN_EntitiesInPVS, #else NULL, #endif #ifdef FN_MakeVectors FN_MakeVectors, #else NULL, #endif #ifdef FN_AngleVectors FN_AngleVectors, #else NULL, #endif #ifdef FN_CreateEntity FN_CreateEntity, #else NULL, #endif #ifdef FN_RemoveEntity FN_RemoveEntity, #else NULL, #endif #ifdef FN_CreateNamedEntity FN_CreateNamedEntity, #else NULL, #endif #ifdef FN_MakeStatic FN_MakeStatic, #else NULL, #endif #ifdef FN_EntIsOnFloor FN_EntIsOnFloor, #else NULL, #endif #ifdef FN_DropToFloor FN_DropToFloor, #else NULL, #endif #ifdef FN_WalkMove FN_WalkMove, #else NULL, #endif #ifdef FN_SetOrigin FN_SetOrigin, #else NULL, #endif #ifdef FN_EmitSound FN_EmitSound, #else NULL, #endif #ifdef FN_EmitAmbientSound FN_EmitAmbientSound, #else NULL, #endif #ifdef FN_TraceLine FN_TraceLine, #else NULL, #endif #ifdef FN_TraceToss FN_TraceToss, #else NULL, #endif #ifdef FN_TraceMonsterHull FN_TraceMonsterHull, #else NULL, #endif #ifdef FN_TraceHull FN_TraceHull, #else NULL, #endif #ifdef FN_TraceModel FN_TraceModel, #else NULL, #endif #ifdef FN_TraceTexture FN_TraceTexture, #else NULL, #endif #ifdef FN_TraceSphere FN_TraceSphere, #else NULL, #endif #ifdef FN_GetAimVector FN_GetAimVector, #else NULL, #endif #ifdef FN_ServerCommand FN_ServerCommand, #else NULL, #endif #ifdef FN_ServerExecute FN_ServerExecute, #else NULL, #endif #ifdef FN_engClientCommand FN_engClientCommand, #else NULL, #endif #ifdef FN_ParticleEffect FN_ParticleEffect, #else NULL, #endif #ifdef FN_LightStyle FN_LightStyle, #else NULL, #endif #ifdef FN_DecalIndex FN_DecalIndex, #else NULL, #endif #ifdef FN_PointContents FN_PointContents, #else NULL, #endif #ifdef FN_MessageBegin FN_MessageBegin, #else NULL, #endif #ifdef FN_MessageEnd FN_MessageEnd, #else NULL, #endif #ifdef FN_WriteByte FN_WriteByte, #else NULL, #endif #ifdef FN_WriteChar FN_WriteChar, #else NULL, #endif #ifdef FN_WriteShort FN_WriteShort, #else NULL, #endif #ifdef FN_WriteLong FN_WriteLong, #else NULL, #endif #ifdef FN_WriteAngle FN_WriteAngle, #else NULL, #endif #ifdef FN_WriteCoord FN_WriteCoord, #else NULL, #endif #ifdef FN_WriteString FN_WriteString, #else NULL, #endif #ifdef FN_WriteEntity FN_WriteEntity, #else NULL, #endif #ifdef FN_CVarRegister FN_CVarRegister, #else NULL, #endif #ifdef FN_CVarGetFloat FN_CVarGetFloat, #else NULL, #endif #ifdef FN_CVarGetString FN_CVarGetString, #else NULL, #endif #ifdef FN_CVarSetFloat FN_CVarSetFloat, #else NULL, #endif #ifdef FN_CVarSetString FN_CVarSetString, #else NULL, #endif #ifdef FN_AlertMessage FN_AlertMessage, #else NULL, #endif #ifdef FN_EngineFprintf FN_EngineFprintf, #else NULL, #endif #ifdef FN_PvAllocEntPrivateData FN_PvAllocEntPrivateData, #else NULL, #endif #ifdef FN_PvEntPrivateData FN_PvEntPrivateData, #else NULL, #endif #ifdef FN_FreeEntPrivateData FN_FreeEntPrivateData, #else NULL, #endif #ifdef FN_SzFromIndex FN_SzFromIndex, #else NULL, #endif #ifdef FN_AllocString FN_AllocString, #else NULL, #endif #ifdef FN_GetVarsOfEnt FN_GetVarsOfEnt, #else NULL, #endif #ifdef FN_PEntityOfEntOffset FN_PEntityOfEntOffset, #else NULL, #endif #ifdef FN_EntOffsetOfPEntity FN_EntOffsetOfPEntity, #else NULL, #endif #ifdef FN_IndexOfEdict FN_IndexOfEdict, #else NULL, #endif #ifdef FN_PEntityOfEntIndex FN_PEntityOfEntIndex, #else NULL, #endif #ifdef FN_FindEntityByVars FN_FindEntityByVars, #else NULL, #endif #ifdef FN_GetModelPtr FN_GetModelPtr, #else NULL, #endif #ifdef FN_RegUserMsg FN_RegUserMsg, #else NULL, #endif #ifdef FN_AnimationAutomove FN_AnimationAutomove, #else NULL, #endif #ifdef FN_GetBonePosition FN_GetBonePosition, #else NULL, #endif #ifdef FN_FunctionFromName FN_FunctionFromName, #else NULL, #endif #ifdef FN_NameForFunction FN_NameForFunction, #else NULL, #endif #ifdef FN_ClientPrintf FN_ClientPrintf, #else NULL, #endif #ifdef FN_ServerPrint FN_ServerPrint, #else NULL, #endif #ifdef FN_Cmd_Args FN_Cmd_Args, #else NULL, #endif #ifdef FN_Cmd_Argv FN_Cmd_Argv, #else NULL, #endif #ifdef FN_Cmd_Argc FN_Cmd_Argc, #else NULL, #endif #ifdef FN_GetAttachment FN_GetAttachment, #else NULL, #endif #ifdef FN_CRC32_Init FN_CRC32_Init, #else NULL, #endif #ifdef FN_CRC32_ProcessBuffer FN_CRC32_ProcessBuffer, #else NULL, #endif #ifdef FN_CRC32_ProcessByte FN_CRC32_ProcessByte, #else NULL, #endif #ifdef FN_CRC32_Final FN_CRC32_Final, #else NULL, #endif #ifdef FN_RandomLong FN_RandomLong, #else NULL, #endif #ifdef FN_RandomFloat FN_RandomFloat, #else NULL, #endif #ifdef FN_SetView FN_SetView, #else NULL, #endif #ifdef FN_Time FN_Time, #else NULL, #endif #ifdef FN_CrosshairAngle FN_CrosshairAngle, #else NULL, #endif #ifdef FN_LoadFileForMe FN_LoadFileForMe, #else NULL, #endif #ifdef FN_FreeFile FN_FreeFile, #else NULL, #endif #ifdef FN_EndSection FN_EndSection, #else NULL, #endif #ifdef FN_CompareFileTime FN_CompareFileTime, #else NULL, #endif #ifdef FN_GetGameDir FN_GetGameDir, #else NULL, #endif #ifdef FN_Cvar_RegisterVariable FN_Cvar_RegisterVariable, #else NULL, #endif #ifdef FN_FadeClientVolume FN_FadeClientVolume, #else NULL, #endif #ifdef FN_SetClientMaxspeed FN_SetClientMaxspeed, #else NULL, #endif #ifdef FN_CreateFakeClient FN_CreateFakeClient, #else NULL, #endif #ifdef FN_RunPlayerMove FN_RunPlayerMove, #else NULL, #endif #ifdef FN_NumberOfEntities FN_NumberOfEntities, #else NULL, #endif #ifdef FN_GetInfoKeyBuffer FN_GetInfoKeyBuffer, #else NULL, #endif #ifdef FN_InfoKeyValue FN_InfoKeyValue, #else NULL, #endif #ifdef FN_SetKeyValue FN_SetKeyValue, #else NULL, #endif #ifdef FN_SetClientKeyValue FN_SetClientKeyValue, #else NULL, #endif #ifdef FN_IsMapValid FN_IsMapValid, #else NULL, #endif #ifdef FN_StaticDecal FN_StaticDecal, #else NULL, #endif #ifdef FN_PrecacheGeneric FN_PrecacheGeneric, #else NULL, #endif #ifdef FN_GetPlayerUserId FN_GetPlayerUserId, #else NULL, #endif #ifdef FN_BuildSoundMsg FN_BuildSoundMsg, #else NULL, #endif #ifdef FN_IsDedicatedServer FN_IsDedicatedServer, #else NULL, #endif #ifdef FN_CVarGetPointer FN_CVarGetPointer, #else NULL, #endif #ifdef FN_GetPlayerWONId FN_GetPlayerWONId, #else NULL, #endif #ifdef FN_Info_RemoveKey FN_Info_RemoveKey, #else NULL, #endif #ifdef FN_GetPhysicsKeyValue FN_GetPhysicsKeyValue, #else NULL, #endif #ifdef FN_SetPhysicsKeyValue FN_SetPhysicsKeyValue, #else NULL, #endif #ifdef FN_GetPhysicsInfoString FN_GetPhysicsInfoString, #else NULL, #endif #ifdef FN_PrecacheEvent FN_PrecacheEvent, #else NULL, #endif #ifdef FN_PlaybackEvent FN_PlaybackEvent, #else NULL, #endif #ifdef FN_SetFatPVS FN_SetFatPVS, #else NULL, #endif #ifdef FN_SetFatPAS FN_SetFatPAS, #else NULL, #endif #ifdef FN_CheckVisibility FN_CheckVisibility, #else NULL, #endif #ifdef FN_DeltaSetField FN_DeltaSetField, #else NULL, #endif #ifdef FN_DeltaUnsetField FN_DeltaUnsetField, #else NULL, #endif #ifdef FN_DeltaAddEncoder FN_DeltaAddEncoder, #else NULL, #endif #ifdef FN_GetCurrentPlayer FN_GetCurrentPlayer, #else NULL, #endif #ifdef FN_CanSkipPlayer FN_CanSkipPlayer, #else NULL, #endif #ifdef FN_DeltaFindField FN_DeltaFindField, #else NULL, #endif #ifdef FN_DeltaSetFieldByIndex FN_DeltaSetFieldByIndex, #else NULL, #endif #ifdef FN_DeltaUnsetFieldByIndex FN_DeltaUnsetFieldByIndex, #else NULL, #endif #ifdef FN_SetGroupMask FN_SetGroupMask, #else NULL, #endif #ifdef FN_engCreateInstancedBaseline FN_engCreateInstancedBaseline, #else NULL, #endif #ifdef FN_Cvar_DirectSet FN_Cvar_DirectSet, #else NULL, #endif #ifdef FN_ForceUnmodified FN_ForceUnmodified, #else NULL, #endif #ifdef FN_GetPlayerStats FN_GetPlayerStats, #else NULL, #endif #ifdef FN_AddServerCommand FN_AddServerCommand, #else NULL, #endif #ifdef FN_Voice_GetClientListening FN_Voice_GetClientListening, #else NULL, #endif #ifdef FN_Voice_SetClientListening FN_Voice_SetClientListening, #else NULL, #endif #ifdef FN_GetPlayerAuthId FN_GetPlayerAuthId #else NULL #endif }; // g_EngineFuncs_Table static enginefuncs_t g_EngineFuncs_Post_Table = { #ifdef FN_PrecacheModel_Post FN_PrecacheModel_Post, #else NULL, #endif #ifdef FN_PrecacheSound_Post FN_PrecacheSound_Post, #else NULL, #endif #ifdef FN_SetModel_Post FN_SetModel_Post, #else NULL, #endif #ifdef FN_ModelIndex_Post FN_ModelIndex_Post, #else NULL, #endif #ifdef FN_ModelFrames_Post FN_ModelFrames_Post, #else NULL, #endif #ifdef FN_SetSize_Post FN_SetSize_Post, #else NULL, #endif #ifdef FN_ChangeLevel_Post FN_ChangeLevel_Post, #else NULL, #endif #ifdef FN_GetSpawnParms_Post FN_GetSpawnParms_Post, #else NULL, #endif #ifdef FN_SaveSpawnParms_Post FN_SaveSpawnParms_Post, #else NULL, #endif #ifdef FN_VecToYaw_Post FN_VecToYaw_Post, #else NULL, #endif #ifdef FN_VecToAngles_Post FN_VecToAngles_Post, #else NULL, #endif #ifdef FN_MoveToOrigin_Post FN_MoveToOrigin_Post, #else NULL, #endif #ifdef FN_ChangeYaw_Post FN_ChangeYaw_Post, #else NULL, #endif #ifdef FN_ChangePitch_Post FN_ChangePitch_Post, #else NULL, #endif #ifdef FN_FindEntityByString_Post FN_FindEntityByString_Post, #else NULL, #endif #ifdef FN_GetEntityIllum_Post FN_GetEntityIllum_Post, #else NULL, #endif #ifdef FN_FindEntityInSphere_Post FN_FindEntityInSphere_Post, #else NULL, #endif #ifdef FN_FindClientInPVS_Post FN_FindClientInPVS_Post, #else NULL, #endif #ifdef FN_EntitiesInPVS_Post FN_EntitiesInPVS_Post, #else NULL, #endif #ifdef FN_MakeVectors_Post FN_MakeVectors_Post, #else NULL, #endif #ifdef FN_AngleVectors_Post FN_AngleVectors_Post, #else NULL, #endif #ifdef FN_CreateEntity_Post FN_CreateEntity_Post, #else NULL, #endif #ifdef FN_RemoveEntity_Post FN_RemoveEntity_Post, #else NULL, #endif #ifdef FN_CreateNamedEntity_Post FN_CreateNamedEntity_Post, #else NULL, #endif #ifdef FN_MakeStatic_Post FN_MakeStatic_Post, #else NULL, #endif #ifdef FN_EntIsOnFloor_Post FN_EntIsOnFloor_Post, #else NULL, #endif #ifdef FN_DropToFloor_Post FN_DropToFloor_Post, #else NULL, #endif #ifdef FN_WalkMove_Post FN_WalkMove_Post, #else NULL, #endif #ifdef FN_SetOrigin_Post FN_SetOrigin_Post, #else NULL, #endif #ifdef FN_EmitSound_Post FN_EmitSound_Post, #else NULL, #endif #ifdef FN_EmitAmbientSound_Post FN_EmitAmbientSound_Post, #else NULL, #endif #ifdef FN_TraceLine_Post FN_TraceLine_Post, #else NULL, #endif #ifdef FN_TraceToss_Post FN_TraceToss_Post, #else NULL, #endif #ifdef FN_TraceMonsterHull_Post FN_TraceMonsterHull_Post, #else NULL, #endif #ifdef FN_TraceHull_Post FN_TraceHull_Post, #else NULL, #endif #ifdef FN_TraceModel_Post FN_TraceModel_Post, #else NULL, #endif #ifdef FN_TraceTexture_Post FN_TraceTexture_Post, #else NULL, #endif #ifdef FN_TraceSphere_Post FN_TraceSphere_Post, #else NULL, #endif #ifdef FN_GetAimVector_Post FN_GetAimVector_Post, #else NULL, #endif #ifdef FN_ServerCommand_Post FN_ServerCommand_Post, #else NULL, #endif #ifdef FN_ServerExecute_Post FN_ServerExecute_Post, #else NULL, #endif #ifdef FN_engClientCommand_Post FN_engClientCommand_Post, #else NULL, #endif #ifdef FN_ParticleEffect_Post FN_ParticleEffect_Post, #else NULL, #endif #ifdef FN_LightStyle_Post FN_LightStyle_Post, #else NULL, #endif #ifdef FN_DecalIndex_Post FN_DecalIndex_Post, #else NULL, #endif #ifdef FN_PointContents_Post FN_PointContents_Post, #else NULL, #endif #ifdef FN_MessageBegin_Post FN_MessageBegin_Post, #else NULL, #endif #ifdef FN_MessageEnd_Post FN_MessageEnd_Post, #else NULL, #endif #ifdef FN_WriteByte_Post FN_WriteByte_Post, #else NULL, #endif #ifdef FN_WriteChar_Post FN_WriteChar_Post, #else NULL, #endif #ifdef FN_WriteShort_Post FN_WriteShort_Post, #else NULL, #endif #ifdef FN_WriteLong_Post FN_WriteLong_Post, #else NULL, #endif #ifdef FN_WriteAngle_Post FN_WriteAngle_Post, #else NULL, #endif #ifdef FN_WriteCoord_Post FN_WriteCoord_Post, #else NULL, #endif #ifdef FN_WriteString_Post FN_WriteString_Post, #else NULL, #endif #ifdef FN_WriteEntity_Post FN_WriteEntity_Post, #else NULL, #endif #ifdef FN_CVarRegister_Post FN_CVarRegister_Post, #else NULL, #endif #ifdef FN_CVarGetFloat_Post FN_CVarGetFloat_Post, #else NULL, #endif #ifdef FN_CVarGetString_Post FN_CVarGetString_Post, #else NULL, #endif #ifdef FN_CVarSetFloat_Post FN_CVarSetFloat_Post, #else NULL, #endif #ifdef FN_CVarSetString_Post FN_CVarSetString_Post, #else NULL, #endif #ifdef FN_AlertMessage_Post FN_AlertMessage_Post, #else NULL, #endif #ifdef FN_EngineFprintf_Post FN_EngineFprintf_Post, #else NULL, #endif #ifdef FN_PvAllocEntPrivateData_Post FN_PvAllocEntPrivateData_Post, #else NULL, #endif #ifdef FN_PvEntPrivateData_Post FN_PvEntPrivateData_Post, #else NULL, #endif #ifdef FN_FreeEntPrivateData_Post FN_FreeEntPrivateData_Post, #else NULL, #endif #ifdef FN_SzFromIndex_Post FN_SzFromIndex_Post, #else NULL, #endif #ifdef FN_AllocString_Post FN_AllocString_Post, #else NULL, #endif #ifdef FN_GetVarsOfEnt_Post FN_GetVarsOfEnt_Post, #else NULL, #endif #ifdef FN_PEntityOfEntOffset_Post FN_PEntityOfEntOffset_Post, #else NULL, #endif #ifdef FN_EntOffsetOfPEntity_Post FN_EntOffsetOfPEntity_Post, #else NULL, #endif #ifdef FN_IndexOfEdict_Post FN_IndexOfEdict_Post, #else NULL, #endif #ifdef FN_PEntityOfEntIndex_Post FN_PEntityOfEntIndex_Post, #else NULL, #endif #ifdef FN_FindEntityByVars_Post FN_FindEntityByVars_Post, #else NULL, #endif #ifdef FN_GetModelPtr_Post FN_GetModelPtr_Post, #else NULL, #endif #ifdef FN_RegUserMsg_Post FN_RegUserMsg_Post, #else NULL, #endif #ifdef FN_AnimationAutomove_Post FN_AnimationAutomove_Post, #else NULL, #endif #ifdef FN_GetBonePosition_Post FN_GetBonePosition_Post, #else NULL, #endif #ifdef FN_FunctionFromName_Post FN_FunctionFromName_Post, #else NULL, #endif #ifdef FN_NameForFunction_Post FN_NameForFunction_Post, #else NULL, #endif #ifdef FN_ClientPrintf_Post FN_ClientPrintf_Post, #else NULL, #endif #ifdef FN_ServerPrint_Post FN_ServerPrint_Post, #else NULL, #endif #ifdef FN_Cmd_Args_Post FN_Cmd_Args_Post, #else NULL, #endif #ifdef FN_Cmd_Argv_Post FN_Cmd_Argv_Post, #else NULL, #endif #ifdef FN_Cmd_Argc_Post FN_Cmd_Argc_Post, #else NULL, #endif #ifdef FN_GetAttachment_Post FN_GetAttachment_Post, #else NULL, #endif #ifdef FN_CRC32_Init_Post FN_CRC32_Init_Post, #else NULL, #endif #ifdef FN_CRC32_ProcessBuffer_Post FN_CRC32_ProcessBuffer_Post, #else NULL, #endif #ifdef FN_CRC32_ProcessByte_Post FN_CRC32_ProcessByte_Post, #else NULL, #endif #ifdef FN_CRC32_Final_Post FN_CRC32_Final_Post, #else NULL, #endif #ifdef FN_RandomLong_Post FN_RandomLong_Post, #else NULL, #endif #ifdef FN_RandomFloat_Post FN_RandomFloat_Post, #else NULL, #endif #ifdef FN_SetView_Post FN_SetView_Post, #else NULL, #endif #ifdef FN_Time_Post FN_Time_Post, #else NULL, #endif #ifdef FN_CrosshairAngle_Post FN_CrosshairAngle_Post, #else NULL, #endif #ifdef FN_LoadFileForMe_Post FN_LoadFileForMe_Post, #else NULL, #endif #ifdef FN_FreeFile_Post FN_FreeFile_Post, #else NULL, #endif #ifdef FN_EndSection_Post FN_EndSection_Post, #else NULL, #endif #ifdef FN_CompareFileTime_Post FN_CompareFileTime_Post, #else NULL, #endif #ifdef FN_GetGameDir_Post FN_GetGameDir_Post, #else NULL, #endif #ifdef FN_Cvar_RegisterVariable_Post FN_Cvar_RegisterVariable_Post, #else NULL, #endif #ifdef FN_FadeClientVolume_Post FN_FadeClientVolume_Post, #else NULL, #endif #ifdef FN_SetClientMaxspeed_Post FN_SetClientMaxspeed_Post, #else NULL, #endif #ifdef FN_CreateFakeClient_Post FN_CreateFakeClient_Post, #else NULL, #endif #ifdef FN_RunPlayerMove_Post FN_RunPlayerMove_Post, #else NULL, #endif #ifdef FN_NumberOfEntities_Post FN_NumberOfEntities_Post, #else NULL, #endif #ifdef FN_GetInfoKeyBuffer_Post FN_GetInfoKeyBuffer_Post, #else NULL, #endif #ifdef FN_InfoKeyValue_Post FN_InfoKeyValue_Post, #else NULL, #endif #ifdef FN_SetKeyValue_Post FN_SetKeyValue_Post, #else NULL, #endif #ifdef FN_SetClientKeyValue_Post FN_SetClientKeyValue_Post, #else NULL, #endif #ifdef FN_IsMapValid_Post FN_IsMapValid_Post, #else NULL, #endif #ifdef FN_StaticDecal_Post FN_StaticDecal_Post, #else NULL, #endif #ifdef FN_PrecacheGeneric_Post FN_PrecacheGeneric_Post, #else NULL, #endif #ifdef FN_GetPlayerUserId_Post FN_GetPlayerUserId_Post, #else NULL, #endif #ifdef FN_BuildSoundMsg_Post FN_BuildSoundMsg_Post, #else NULL, #endif #ifdef FN_IsDedicatedServer_Post FN_IsDedicatedServer_Post, #else NULL, #endif #ifdef FN_CVarGetPointer_Post FN_CVarGetPointer_Post, #else NULL, #endif #ifdef FN_GetPlayerWONId_Post FN_GetPlayerWONId_Post, #else NULL, #endif #ifdef FN_Info_RemoveKey_Post FN_Info_RemoveKey_Post, #else NULL, #endif #ifdef FN_GetPhysicsKeyValue_Post FN_GetPhysicsKeyValue_Post, #else NULL, #endif #ifdef FN_SetPhysicsKeyValue_Post FN_SetPhysicsKeyValue_Post, #else NULL, #endif #ifdef FN_GetPhysicsInfoString_Post FN_GetPhysicsInfoString_Post, #else NULL, #endif #ifdef FN_PrecacheEvent_Post FN_PrecacheEvent_Post, #else NULL, #endif #ifdef FN_PlaybackEvent_Post FN_PlaybackEvent_Post, #else NULL, #endif #ifdef FN_SetFatPVS_Post FN_SetFatPVS_Post, #else NULL, #endif #ifdef FN_SetFatPAS_Post FN_SetFatPAS_Post, #else NULL, #endif #ifdef FN_CheckVisibility_Post FN_CheckVisibility_Post, #else NULL, #endif #ifdef FN_DeltaSetField_Post FN_DeltaSetField_Post, #else NULL, #endif #ifdef FN_DeltaUnsetField_Post FN_DeltaUnsetField_Post, #else NULL, #endif #ifdef FN_DeltaAddEncoder_Post FN_DeltaAddEncoder_Post, #else NULL, #endif #ifdef FN_GetCurrentPlayer_Post FN_GetCurrentPlayer_Post, #else NULL, #endif #ifdef FN_CanSkipPlayer_Post FN_CanSkipPlayer_Post, #else NULL, #endif #ifdef FN_DeltaFindField_Post FN_DeltaFindField_Post, #else NULL, #endif #ifdef FN_DeltaSetFieldByIndex_Post FN_DeltaSetFieldByIndex_Post, #else NULL, #endif #ifdef FN_DeltaUnsetFieldByIndex_Post FN_DeltaUnsetFieldByIndex_Post, #else NULL, #endif #ifdef FN_SetGroupMask_Post FN_SetGroupMask_Post, #else NULL, #endif #ifdef FN_engCreateInstancedBaseline_Post FN_engCreateInstancedBaseline_Post, #else NULL, #endif #ifdef FN_Cvar_DirectSet_Post FN_Cvar_DirectSet_Post, #else NULL, #endif #ifdef FN_ForceUnmodified_Post FN_ForceUnmodified_Post, #else NULL, #endif #ifdef FN_GetPlayerStats_Post FN_GetPlayerStats_Post, #else NULL, #endif #ifdef FN_AddServerCommand_Post FN_AddServerCommand_Post, #else NULL, #endif #ifdef FN_Voice_GetClientListening_Post FN_Voice_GetClientListening_Post, #else NULL, #endif #ifdef FN_Voice_SetClientListening_Post FN_Voice_SetClientListening_Post, #else NULL, #endif #ifdef FN_GetPlayerAuthId_Post FN_GetPlayerAuthId_Post #else NULL #endif }; // g_EngineFuncs_Post_Table static NEW_DLL_FUNCTIONS g_NewFuncs_Table = { #ifdef FN_OnFreeEntPrivateData FN_OnFreeEntPrivateData, #else NULL, #endif #ifdef FN_GameShutdown FN_GameShutdown, #else NULL, #endif #ifdef FN_ShouldCollide ShouldCollide, #else NULL, #endif }; static NEW_DLL_FUNCTIONS g_NewFuncs_Post_Table = { #ifdef FN_OnFreeEntPrivateData_Post FN_OnFreeEntPrivateData_Post, #else NULL, #endif #ifdef FN_GameShutdown_Post FN_GameShutdown_Post, #else NULL, #endif #ifdef FN_ShouldCollide_Post ShouldCollide_Post, #else NULL, #endif }; // Global variables from metamod. These variable names are referenced by // various macros. meta_globals_t *gpMetaGlobals; // metamod globals gamedll_funcs_t *gpGamedllFuncs; // gameDLL function tables mutil_funcs_t *gpMetaUtilFuncs; // metamod utility functions plugin_info_t Plugin_info = { META_INTERFACE_VERSION, MODULE_NAME, MODULE_VERSION, MODULE_DATE, MODULE_AUTHOR, MODULE_URL, MODULE_LOGTAG, PT_ANYTIME, PT_ANYTIME }; C_DLLEXPORT int GetEntityAPI2(DLL_FUNCTIONS *pFunctionTable, int *interfaceVersion) { LOG_DEVELOPER(PLID, "called: GetEntityAPI2; version=%d", *interfaceVersion); if(!pFunctionTable) { LOG_ERROR(PLID, "GetEntityAPI2 called with null pFunctionTable"); return(FALSE); } else if(*interfaceVersion != INTERFACE_VERSION) { LOG_ERROR(PLID, "GetEntityAPI2 version mismatch; requested=%d ours=%d", *interfaceVersion, INTERFACE_VERSION); //! Tell engine what version we had, so it can figure out who is //! out of date. *interfaceVersion = INTERFACE_VERSION; return(FALSE); } memcpy(pFunctionTable, &g_EntityAPI_Table, sizeof(DLL_FUNCTIONS)); g_pFunctionTable=pFunctionTable; return(TRUE); } C_DLLEXPORT int GetEntityAPI2_Post(DLL_FUNCTIONS *pFunctionTable, int *interfaceVersion) { LOG_DEVELOPER(PLID, "called: GetEntityAPI2_Post; version=%d", *interfaceVersion); if(!pFunctionTable) { LOG_ERROR(PLID, "GetEntityAPI2_Post called with null pFunctionTable"); return(FALSE); } else if(*interfaceVersion != INTERFACE_VERSION) { LOG_ERROR(PLID, "GetEntityAPI2_Post version mismatch; requested=%d ours=%d", *interfaceVersion, INTERFACE_VERSION); //! Tell engine what version we had, so it can figure out who is out of date. *interfaceVersion = INTERFACE_VERSION; return(FALSE); } memcpy( pFunctionTable, &g_EntityAPI_Post_Table, sizeof( DLL_FUNCTIONS ) ); g_pFunctionTable_Post=pFunctionTable; return(TRUE); } C_DLLEXPORT int GetEngineFunctions(enginefuncs_t *pengfuncsFromEngine, int *interfaceVersion) { LOG_DEVELOPER(PLID, "called: GetEngineFunctions; version=%d", *interfaceVersion); if(!pengfuncsFromEngine) { LOG_ERROR(PLID, "GetEngineFunctions called with null pengfuncsFromEngine"); return(FALSE); } else if(*interfaceVersion != ENGINE_INTERFACE_VERSION) { LOG_ERROR(PLID, "GetEngineFunctions version mismatch; requested=%d ours=%d", *interfaceVersion, ENGINE_INTERFACE_VERSION); // Tell metamod what version we had, so it can figure out who is // out of date. *interfaceVersion = ENGINE_INTERFACE_VERSION; return(FALSE); } memcpy(pengfuncsFromEngine, &g_EngineFuncs_Table, sizeof(enginefuncs_t)); g_pengfuncsTable=pengfuncsFromEngine; return TRUE; } C_DLLEXPORT int GetEngineFunctions_Post(enginefuncs_t *pengfuncsFromEngine, int *interfaceVersion) { LOG_DEVELOPER(PLID, "called: GetEngineFunctions_Post; version=%d", *interfaceVersion); if(!pengfuncsFromEngine) { LOG_ERROR(PLID, "GetEngineFunctions_Post called with null pengfuncsFromEngine"); return(FALSE); } else if(*interfaceVersion != ENGINE_INTERFACE_VERSION) { LOG_ERROR(PLID, "GetEngineFunctions_Post version mismatch; requested=%d ours=%d", *interfaceVersion, ENGINE_INTERFACE_VERSION); // Tell metamod what version we had, so it can figure out who is out of date. *interfaceVersion = ENGINE_INTERFACE_VERSION; return(FALSE); } memcpy(pengfuncsFromEngine, &g_EngineFuncs_Post_Table, sizeof(enginefuncs_t)); g_pengfuncsTable_Post=pengfuncsFromEngine; return TRUE; } C_DLLEXPORT int GetNewDLLFunctions(NEW_DLL_FUNCTIONS *pNewFunctionTable, int *interfaceVersion) { LOG_DEVELOPER(PLID, "called: GetNewDLLFunctions; version=%d", *interfaceVersion); if(!pNewFunctionTable) { LOG_ERROR(PLID, "GetNewDLLFunctions called with null pNewFunctionTable"); return(FALSE); } else if(*interfaceVersion != NEW_DLL_FUNCTIONS_VERSION) { LOG_ERROR(PLID, "GetNewDLLFunctions version mismatch; requested=%d ours=%d", *interfaceVersion, NEW_DLL_FUNCTIONS_VERSION); //! Tell engine what version we had, so it can figure out who is //! out of date. *interfaceVersion = NEW_DLL_FUNCTIONS_VERSION; return(FALSE); } memcpy(pNewFunctionTable, &g_NewFuncs_Table, sizeof(NEW_DLL_FUNCTIONS)); g_pNewFunctionsTable=pNewFunctionTable; return TRUE; } C_DLLEXPORT int GetNewDLLFunctions_Post( NEW_DLL_FUNCTIONS *pNewFunctionTable, int *interfaceVersion ) { LOG_DEVELOPER(PLID, "called: GetNewDLLFunctions_Post; version=%d", *interfaceVersion); if(!pNewFunctionTable) { LOG_ERROR(PLID, "GetNewDLLFunctions_Post called with null pNewFunctionTable"); return(FALSE); } else if(*interfaceVersion != NEW_DLL_FUNCTIONS_VERSION) { LOG_ERROR(PLID, "GetNewDLLFunctions_Post version mismatch; requested=%d ours=%d", *interfaceVersion, NEW_DLL_FUNCTIONS_VERSION); //! Tell engine what version we had, so it can figure out who is out of date. *interfaceVersion = NEW_DLL_FUNCTIONS_VERSION; return(FALSE); } memcpy(pNewFunctionTable, &g_NewFuncs_Post_Table, sizeof(NEW_DLL_FUNCTIONS)); g_pNewFunctionsTable_Post=pNewFunctionTable; return TRUE; } static META_FUNCTIONS g_MetaFunctions_Table = { NULL, NULL, GetEntityAPI2, GetEntityAPI2_Post, GetNewDLLFunctions, GetNewDLLFunctions_Post, GetEngineFunctions, GetEngineFunctions_Post }; C_DLLEXPORT int Meta_Query(char *ifvers, plugin_info_t **pPlugInfo, mutil_funcs_t *pMetaUtilFuncs) { if ((int) CVAR_GET_FLOAT("developer") != 0) UTIL_LogPrintf("[%s] dev: called: Meta_Query; version=%s, ours=%s\n", Plugin_info.logtag, ifvers, Plugin_info.ifvers); // Check for valid pMetaUtilFuncs before we continue. if(!pMetaUtilFuncs) { UTIL_LogPrintf("[%s] ERROR: Meta_Query called with null pMetaUtilFuncs\n", Plugin_info.logtag); return(FALSE); } gpMetaUtilFuncs = pMetaUtilFuncs; *pPlugInfo = &Plugin_info; // Check for interface version compatibility. if(!FStrEq(ifvers, Plugin_info.ifvers)) { int mmajor=0, mminor=0, pmajor=0, pminor=0; LOG_MESSAGE(PLID, "WARNING: meta-interface version mismatch; requested=%s ours=%s", Plugin_info.logtag, ifvers); // If plugin has later interface version, it's incompatible (update // metamod). sscanf(ifvers, "%d:%d", &mmajor, &mminor); sscanf(META_INTERFACE_VERSION, "%d:%d", &pmajor, &pminor); if(pmajor > mmajor || (pmajor==mmajor && pminor > mminor)) { LOG_ERROR(PLID, "metamod version is too old for this module; update metamod"); return(FALSE); } // If plugin has older major interface version, it's incompatible // (update plugin). else if(pmajor < mmajor) { LOG_ERROR(PLID, "metamod version is incompatible with this module; please find a newer version of this module"); return(FALSE); } // Minor interface is older, but this is guaranteed to be backwards // compatible, so we warn, but we still accept it. else if(pmajor==mmajor && pminor < mminor) LOG_MESSAGE(PLID, "WARNING: metamod version is newer than expected; consider finding a newer version of this module"); else LOG_ERROR(PLID, "unexpected version comparison; metavers=%s, mmajor=%d, mminor=%d; plugvers=%s, pmajor=%d, pminor=%d", ifvers, mmajor, mminor, META_INTERFACE_VERSION, pmajor, pminor); } #ifdef FN_META_QUERY FN_META_QUERY(); #endif // FN_META_QUERY return 1; } bool InitEngineParser(void); bool FindNetchan_OutOfBandPrint(void); C_DLLEXPORT int Meta_Attach(PLUG_LOADTIME now, META_FUNCTIONS *pFunctionTable, meta_globals_t *pMGlobals, gamedll_funcs_t *pGamedllFuncs) { if(now > Plugin_info.loadable) { LOG_ERROR(PLID, "Can't load module right now"); return(FALSE); } if(!pMGlobals) { LOG_ERROR(PLID, "Meta_Attach called with null pMGlobals"); return(FALSE); } gpMetaGlobals=pMGlobals; if(!pFunctionTable) { LOG_ERROR(PLID, "Meta_Attach called with null pFunctionTable"); return(FALSE); } memcpy(pFunctionTable, &g_MetaFunctions_Table, sizeof(META_FUNCTIONS)); gpGamedllFuncs=pGamedllFuncs; if(!InitEngineParser()) { LOG_ERROR(PLID, "Initialize Engine Parser failed."); return FALSE; } if(!FindNetchan_OutOfBandPrint()) { LOG_ERROR(PLID, " Can't find Netchan_OutOfBandPrint."); return(FALSE); } // Let's go. #ifdef FN_META_ATTACH FN_META_ATTACH(); #endif // FN_META_ATTACH return TRUE; } C_DLLEXPORT int Meta_Detach(PLUG_LOADTIME now, PL_UNLOAD_REASON reason) { if(now > Plugin_info.unloadable && reason != PNL_CMD_FORCED) { LOG_ERROR(PLID, "Can't unload plugin right now"); return(FALSE); } #ifdef FN_META_DETACH FN_META_DETACH(); #endif // FN_META_DETACH return TRUE; } #ifdef __linux__ // linux prototype C_DLLEXPORT void GiveFnptrsToDll( enginefuncs_t* pengfuncsFromEngine, globalvars_t *pGlobals ) { #else #ifdef _MSC_VER // MSVC: Simulate __stdcall calling convention C_DLLEXPORT __declspec(naked) void GiveFnptrsToDll( enginefuncs_t* pengfuncsFromEngine, globalvars_t *pGlobals ) { __asm // Prolog { // Save ebp push ebp // Set stack frame pointer mov ebp, esp // Allocate space for local variables // The MSVC compiler gives us the needed size in __LOCAL_SIZE. sub esp, __LOCAL_SIZE // Push registers push ebx push esi push edi } #else // _MSC_VER #ifdef __GNUC__ // GCC can also work with this C_DLLEXPORT void __stdcall GiveFnptrsToDll( enginefuncs_t* pengfuncsFromEngine, globalvars_t *pGlobals ) { #else // __GNUC__ // compiler not known #error There is no support (yet) for your compiler. Please use MSVC or GCC compilers or contact the AMX Mod X dev team. #endif // __GNUC__ #endif // _MSC_VER #endif // __linux__ // ** Function core <-- memcpy(&g_engfuncs, pengfuncsFromEngine, sizeof(enginefuncs_t)); gpGlobals = pGlobals; // NOTE! Have to call logging function _after_ copying into g_engfuncs, so // that g_engfuncs.pfnAlertMessage() can be resolved properly, heh. :) // UTIL_LogPrintf("[%s] dev: called: GiveFnptrsToDll\n", Plugin_info.logtag); // --> ** Function core #ifdef _MSC_VER // Epilog if (sizeof(int*) == 8) { // 64 bit __asm { // Pop registers pop edi pop esi pop ebx // Restore stack frame pointer mov esp, ebp // Restore ebp pop ebp // 2 * sizeof(int*) = 16 on 64 bit ret 16 } } else { // 32 bit __asm { // Pop registers pop edi pop esi pop ebx // Restore stack frame pointer mov esp, ebp // Restore ebp pop ebp // 2 * sizeof(int*) = 8 on 32 bit ret 8 } } #endif // #ifdef _MSC_VER } /************* stuff from dlls/util.cpp *************/ // must come here because cbase.h declares it's own operator new // Selected portions of dlls/util.cpp from SDK 2.1. // Functions copied from there as needed... // And modified to avoid buffer overflows (argh). /*** * * Copyright (c) 1999, 2000 Valve LLC. All rights reserved. * * This product contains software technology licensed from Id * Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. * All Rights Reserved. * * Use, distribution, and modification of this source code and/or resulting * object code is restricted to non-commercial enhancements to products from * Valve LLC. All other use, distribution, or modification is prohibited * without written permission from Valve LLC. * ****/ /* ===== util.cpp ======================================================== Utility code. Really not optional after all. */ #include <extdll.h> #include "sdk_util.h" #include <cbase.h> #include <string.h> // for strncpy(), etc #include "osdep.h" // win32 vsnprintf, etc char* UTIL_VarArgs( char *format, ... ) { va_list argptr; static char string[1024]; va_start (argptr, format); vsnprintf (string, sizeof(string), format, argptr); va_end (argptr); return string; } //========================================================= // UTIL_LogPrintf - Prints a logged message to console. // Preceded by LOG: ( timestamp ) < message > //========================================================= void UTIL_LogPrintf( char *fmt, ... ) { va_list argptr; static char string[1024]; va_start ( argptr, fmt ); vsnprintf ( string, sizeof(string), fmt, argptr ); va_end ( argptr ); // Print to server console ALERT( at_logged, "%s", string ); } void UTIL_HudMessage(CBaseEntity *pEntity, const hudtextparms_t &textparms, const char *pMessage) { if ( !pEntity ) return; MESSAGE_BEGIN( MSG_ONE, SVC_TEMPENTITY, NULL, ENT(pEntity->pev) ); WRITE_BYTE( TE_TEXTMESSAGE ); WRITE_BYTE( textparms.channel & 0xFF ); WRITE_SHORT( FixedSigned16( textparms.x, 1<<13 ) ); WRITE_SHORT( FixedSigned16( textparms.y, 1<<13 ) ); WRITE_BYTE( textparms.effect ); WRITE_BYTE( textparms.r1 ); WRITE_BYTE( textparms.g1 ); WRITE_BYTE( textparms.b1 ); WRITE_BYTE( textparms.a1 ); WRITE_BYTE( textparms.r2 ); WRITE_BYTE( textparms.g2 ); WRITE_BYTE( textparms.b2 ); WRITE_BYTE( textparms.a2 ); WRITE_SHORT( FixedUnsigned16( textparms.fadeinTime, 1<<8 ) ); WRITE_SHORT( FixedUnsigned16( textparms.fadeoutTime, 1<<8 ) ); WRITE_SHORT( FixedUnsigned16( textparms.holdTime, 1<<8 ) ); if ( textparms.effect == 2 ) WRITE_SHORT( FixedUnsigned16( textparms.fxTime, 1<<8 ) ); if ( strlen( pMessage ) < 512 ) { WRITE_STRING( pMessage ); } else { char tmp[512]; strncpy( tmp, pMessage, 511 ); tmp[511] = 0; WRITE_STRING( tmp ); } MESSAGE_END(); } short FixedSigned16( float value, float scale ) { int output; output = (int) (value * scale); if ( output > 32767 ) output = 32767; if ( output < -32768 ) output = -32768; return (short)output; } unsigned short FixedUnsigned16( float value, float scale ) { int output; output = (int) (value * scale); if ( output < 0 ) output = 0; if ( output > 0xFFFF ) output = 0xFFFF; return (unsigned short)output; }
17.081625
186
0.77945
[ "object" ]
1d5319da1b4cf6de91360aa23c53ff222a515d70
791
hpp
C++
headers/game.hpp
KingAlone0/Tetris-Clone
0f6d4b81e51a290f03b5bbe74c5464fe1d41f2d7
[ "MIT" ]
null
null
null
headers/game.hpp
KingAlone0/Tetris-Clone
0f6d4b81e51a290f03b5bbe74c5464fe1d41f2d7
[ "MIT" ]
null
null
null
headers/game.hpp
KingAlone0/Tetris-Clone
0f6d4b81e51a290f03b5bbe74c5464fe1d41f2d7
[ "MIT" ]
null
null
null
#ifndef GAME_H #define GAME_H #include <SFML/Graphics.hpp> #include "tetromino.hpp" #include "renderWindow.hpp" #include <ctime> #include <random> #include <thread> short int scoreMultiplier(short int row); TilesType getRandomTetromino(); void deleteRowAt(std::vector<Mino>& grid, unsigned short int h); bool isRowFullAt(const std::vector<Mino>& grid, unsigned short int); void setGrid(std::array<sf::Sprite, 56>& g); void holdTetromino(Tetromino& tetromino, Tetromino& holded_tetromino, Tetromino& next_tetromino); void nextTetromino(Tetromino& tetromino, Tetromino& next_tetromino); void defeatMenu(RenderWindow* window, int score, bool* is_paused, bool* exit); void pauseMenu(RenderWindow* window, bool* is_paused, bool* exit); void Tetris(RenderWindow& window); #endif //GAME_H
28.25
97
0.77244
[ "vector" ]
1d5c06139225b011e31651c4b92082999c199cfd
3,573
cpp
C++
mecab/mecab/example/example_lattice.cpp
xmanh/mecab
d1ad0c5fd616c4aa4d5d96008c90d810befbb3d3
[ "MIT" ]
21
2018-11-15T08:23:14.000Z
2022-03-30T15:44:59.000Z
mecab/mecab/example/example_lattice.cpp
xmanh/mecab
d1ad0c5fd616c4aa4d5d96008c90d810befbb3d3
[ "MIT" ]
19
2020-01-28T22:42:46.000Z
2022-02-10T09:08:36.000Z
mecab/mecab/example/example_lattice.cpp
xmanh/mecab
d1ad0c5fd616c4aa4d5d96008c90d810befbb3d3
[ "MIT" ]
1
2021-12-08T01:17:27.000Z
2021-12-08T01:17:27.000Z
#include <iostream> #include <mecab.h> #define CHECK(eval) if (! eval) { \ const char *e = tagger ? tagger->what() : MeCab::getTaggerError(); \ std::cerr << "Exception:" << e << std::endl; \ delete tagger; \ return -1; } int main (int argc, char **argv) { char input[] = "太郎は次郎が持っている本を花子に渡した。"; // Create model object. MeCab::Model *model = MeCab::createModel(argc, argv); // Create Tagger // All taggers generated by Model::createTagger() method share // the same model/dictoinary. MeCab::Tagger *tagger = model->createTagger(); CHECK(tagger); // Create lattice object per thread. MeCab::Lattice *lattice = model->createLattice(); // Gets tagged result in string lattice->set_sentence(input); // this method is thread safe, as long as |lattice| is thread local. CHECK(tagger->parse(lattice)); std::cout << lattice->toString() << std::endl; // Gets node object. const MeCab::Node* node = lattice->bos_node(); CHECK(node); for (; node; node = node->next) { std::cout << node->id << ' '; if (node->stat == MECAB_BOS_NODE) std::cout << "BOS"; else if (node->stat == MECAB_EOS_NODE) std::cout << "EOS"; else std::cout.write (node->surface, node->length); std::cout << ' ' << node->feature << ' ' << (int)(node->surface - input) << ' ' << (int)(node->surface - input + node->length) << ' ' << node->rcAttr << ' ' << node->lcAttr << ' ' << node->posid << ' ' << (int)node->char_type << ' ' << (int)node->stat << ' ' << (int)node->isbest << ' ' << node->alpha << ' ' << node->beta << ' ' << node->prob << ' ' << node->cost << std::endl; } // begin_nodes/end_nodes const size_t len = lattice->size(); for (int i = 0; i <= len; ++i) { MeCab::Node *b = lattice->begin_nodes(i); MeCab::Node *e = lattice->end_nodes(i); for (; b; b = b->bnext) { printf("B[%d] %s\t%s\n", i, b->surface, b->feature); } for (; e; e = e->enext) { printf("E[%d] %s\t%s\n", i, e->surface, e->feature); } } // N best results lattice->set_request_type(MECAB_NBEST); lattice->set_sentence(input); CHECK(tagger->parse(lattice)); for (int i = 0; i < 10; ++i) { std::cout << "NBEST: " << i << std::endl; std::cout << lattice->toString(); if (!lattice->next()) { // No more results break; } } // Marginal probabilities lattice->remove_request_type(MECAB_NBEST); lattice->set_request_type(MECAB_MARGINAL_PROB); lattice->set_sentence(input); CHECK(tagger->parse(lattice)); std::cout << lattice->theta() << std::endl; for (const MeCab::Node *node = lattice->bos_node(); node; node = node->next) { std::cout.write(node->surface, node->length); std::cout << "\t" << node->feature; std::cout << "\t" << node->prob << std::endl; } // Dictionary info const MeCab::DictionaryInfo *d = model->dictionary_info(); for (; d; d = d->next) { std::cout << "filename: " << d->filename << std::endl; std::cout << "charset: " << d->charset << std::endl; std::cout << "size: " << d->size << std::endl; std::cout << "type: " << d->type << std::endl; std::cout << "lsize: " << d->lsize << std::endl; std::cout << "rsize: " << d->rsize << std::endl; std::cout << "version: " << d->version << std::endl; } // Swap model atomically. MeCab::Model *another_model = MeCab::createModel(""); model->swap(another_model); delete lattice; delete tagger; delete model; return 0; }
29.528926
71
0.561713
[ "object", "model" ]
1d5c23387afd2e5d39081887b6098a7272b5a0a2
2,463
cpp
C++
BlackVision/Test/Tools/BVProjectEditor/Source/AssetsTest/TestSyncLoading.cpp
black-vision-engine/bv-engine
85089d41bb22afeaa9de070646e12aa1777ecedf
[ "MIT" ]
1
2022-01-28T11:43:47.000Z
2022-01-28T11:43:47.000Z
BlackVision/Test/Tools/BVProjectEditor/Source/AssetsTest/TestSyncLoading.cpp
black-vision-engine/bv-engine
85089d41bb22afeaa9de070646e12aa1777ecedf
[ "MIT" ]
null
null
null
BlackVision/Test/Tools/BVProjectEditor/Source/AssetsTest/TestSyncLoading.cpp
black-vision-engine/bv-engine
85089d41bb22afeaa9de070646e12aa1777ecedf
[ "MIT" ]
null
null
null
#include "Framework/FrameworkTest.h" #include "Utils/TwoScenesFixture.h" #include "Framework/BVTestAppLogic.h" #include "Engine/Models/Plugins/Simple/ShaderPlugins/DefaultTexturePlugin.h" using namespace bv; // *********************** // Loads assets synchronously from main thread. BV should hang on loading. class SyncLoadTest : public bv::FrameworkTest { DECALRE_GTEST_INFO_WITH_CONSTRUCTOR( SyncLoadTest ) public: virtual void PreEvents () override; private: AssetDescConstPtr m_assetDesc; }; REGISTER_FRAMEWORK_GTEST_INFO( SyncLoadTest, BVProjectEditor_Assets_Loading, SyncLoadTest ) // ========================================================================= // // Implementation // ========================================================================= // auto imagePath_32x32 = "TestAssets/BVProjectEditor/checkerboard2_32x32.png"; // *********************** // void SyncLoadTest::PreEvents () { // Create scene auto editor = GetAppLogic()->GetBVProject()->GetProjectEditor(); CreateOneScene( editor ); auto firstNode = editor->GetNode( "FirstScene", "root/Group1" ); auto secondNode = editor->GetNode( "FirstScene", "root/Group2" ); UInt32 idx = 1; ASSERT_TRUE( editor->AddPlugin( "FirstScene", "root/Group1", "DEFAULT_TEXTURE", "texture", "default", idx ) ); ASSERT_TRUE( editor->AddPlugin( "FirstScene", "root/Group2", "DEFAULT_TEXTURE", "texture", "default", idx ) ); auto assetDesc = TextureAssetDesc::Create( imagePath_32x32, true ); // Loading assets synchronously. BV should hang and load assets immediately. ASSERT_TRUE( editor->LoadAsset( "FirstScene", "root/Group1", "texture", assetDesc ) ); ASSERT_TRUE( editor->LoadAsset( "FirstScene", "root/Group2", "texture", assetDesc ) ); // Check if assets were loaded corectly. auto texPlugin1 = std::static_pointer_cast< model::DefaultTexturePlugin >( firstNode->GetPlugin( "texture" ) ); auto texPlugin2 = std::static_pointer_cast< model::DefaultTexturePlugin >( secondNode->GetPlugin( "texture" ) ); auto lassets1 = texPlugin1->GetLAssets(); auto lassets2 = texPlugin2->GetLAssets(); ASSERT_EQ( lassets1.size(), 1 ); ASSERT_EQ( lassets2.size(), 1 ); EXPECT_EQ( lassets1[ 0 ].assetDesc, assetDesc ); EXPECT_EQ( lassets2[ 0 ].assetDesc, assetDesc ); }
31.576923
117
0.62363
[ "model" ]
1d66e1431bd4cd7a81142d925b5104fde3b31e2a
808
cpp
C++
niuke_HW/MianJing1.cpp
drt4243566/leetcode_learn
ef51f215079556895eec2252d84965cd1c3a7bf4
[ "MIT" ]
null
null
null
niuke_HW/MianJing1.cpp
drt4243566/leetcode_learn
ef51f215079556895eec2252d84965cd1c3a7bf4
[ "MIT" ]
null
null
null
niuke_HW/MianJing1.cpp
drt4243566/leetcode_learn
ef51f215079556895eec2252d84965cd1c3a7bf4
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <stack> using namespace std; // n个整数的无序数组,找到每个元素后面比它大的第一个数字,要求时间复杂度为O(N); vector<int> find(vector<int>& num){ int len=num.size(); // 空数组返回空 if(len==0) return {}; // 单调栈的思想 stack<int> notFind; // 栈中存放num中还未找到符合条件的元素索引 vector<int> res(len,-1); //存放结果,-1表示未找到 int i=0; while(i<len){ // 如果栈空,或者当前num元素不大于栈顶,将当前元素的索引压栈,索引后移 if(notFind.empty()||num[i]<=num[notFind.top()]) notFind.push(i++); // 当发现有更大的数字,先将栈顶元素保存到结果,出栈后不更新i,继续比较 else{ res[notFind.top()]=num[i]; notFind.pop(); } } return res; } int main() { vector<int> num = {1, 3, 2, 4, 99, 101, 5, 8}; vector<int> res = find(num); for(auto i : res) cout << i << " "; return 0; }
22.444444
74
0.555693
[ "vector" ]
1d6864db7d78cc3bc28c021a46316f6c9b909d9c
3,775
cc
C++
chrome/browser/speech/tts_crosapi_util.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
76
2020-09-02T03:05:41.000Z
2022-03-30T04:40:55.000Z
chrome/browser/speech/tts_crosapi_util.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
45
2020-09-02T03:21:37.000Z
2022-03-31T22:19:45.000Z
chrome/browser/speech/tts_crosapi_util.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
8
2020-07-22T18:49:18.000Z
2022-02-08T10:27:16.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 "chrome/browser/speech/tts_crosapi_util.h" namespace tts_crosapi_util { content::TtsEventType FromMojo(crosapi::mojom::TtsEventType mojo_event) { switch (mojo_event) { case crosapi::mojom::TtsEventType::kStart: return content::TtsEventType::TTS_EVENT_START; case crosapi::mojom::TtsEventType::kEnd: return content::TtsEventType::TTS_EVENT_END; case crosapi::mojom::TtsEventType::kWord: return content::TtsEventType::TTS_EVENT_WORD; case crosapi::mojom::TtsEventType::kSentence: return content::TtsEventType::TTS_EVENT_SENTENCE; case crosapi::mojom::TtsEventType::kMarker: return content::TtsEventType::TTS_EVENT_MARKER; case crosapi::mojom::TtsEventType::kInterrupted: return content::TtsEventType::TTS_EVENT_INTERRUPTED; case crosapi::mojom::TtsEventType::kCanceled: return content::TtsEventType::TTS_EVENT_CANCELLED; case crosapi::mojom::TtsEventType::kError: return content::TtsEventType::TTS_EVENT_ERROR; case crosapi::mojom::TtsEventType::kPause: return content::TtsEventType::TTS_EVENT_PAUSE; case crosapi::mojom::TtsEventType::kResume: return content::TtsEventType::TTS_EVENT_RESUME; } } crosapi::mojom::TtsEventType ToMojo(content::TtsEventType event_type) { switch (event_type) { case content::TtsEventType::TTS_EVENT_START: return crosapi::mojom::TtsEventType::kStart; case content::TtsEventType::TTS_EVENT_END: return crosapi::mojom::TtsEventType::kEnd; case content::TtsEventType::TTS_EVENT_WORD: return crosapi::mojom::TtsEventType::kWord; case content::TtsEventType::TTS_EVENT_SENTENCE: return crosapi::mojom::TtsEventType::kSentence; case content::TtsEventType::TTS_EVENT_MARKER: return crosapi::mojom::TtsEventType::kMarker; case content::TtsEventType::TTS_EVENT_INTERRUPTED: return crosapi::mojom::TtsEventType::kInterrupted; case content::TtsEventType::TTS_EVENT_CANCELLED: return crosapi::mojom::TtsEventType::kCanceled; case content::TtsEventType::TTS_EVENT_ERROR: return crosapi::mojom::TtsEventType::kError; case content::TtsEventType::TTS_EVENT_PAUSE: return crosapi::mojom::TtsEventType::kPause; case content::TtsEventType::TTS_EVENT_RESUME: return crosapi::mojom::TtsEventType::kResume; } } content::VoiceData FromMojo(const crosapi::mojom::TtsVoicePtr& mojo_voice) { content::VoiceData voice_data; #if BUILDFLAG(IS_CHROMEOS_ASH) voice_data.from_crosapi = true; #endif voice_data.name = mojo_voice->voice_name; voice_data.lang = mojo_voice->lang; voice_data.engine_id = mojo_voice->engine_id; voice_data.remote = mojo_voice->remote; voice_data.native = mojo_voice->native; voice_data.native_voice_identifier = mojo_voice->native_voice_identifier; for (const auto& mojo_event : mojo_voice->events) voice_data.events.insert(tts_crosapi_util::FromMojo(mojo_event)); return voice_data; } crosapi::mojom::TtsVoicePtr ToMojo(const content::VoiceData& voice) { auto mojo_voice = crosapi::mojom::TtsVoice::New(); mojo_voice->voice_name = voice.name; mojo_voice->lang = voice.lang; mojo_voice->remote = voice.remote; mojo_voice->engine_id = voice.engine_id; mojo_voice->native = voice.native; mojo_voice->native_voice_identifier = voice.native_voice_identifier; std::vector<crosapi::mojom::TtsEventType> mojo_events; for (const auto& event : voice.events) { mojo_events.push_back(tts_crosapi_util::ToMojo(event)); } mojo_voice->events = std::move(mojo_events); return mojo_voice; } } // namespace tts_crosapi_util
39.736842
76
0.752848
[ "vector" ]
1d71967b002485fb8bdd6a5c8f45debceb39ddd6
5,677
cxx
C++
GPU/TPCFastTransformation/TPCFastTransform.cxx
sprasad-commits/AliRoot
41acc2e128fc8d502df15b9beae83e1fdcdb38f0
[ "BSD-3-Clause" ]
null
null
null
GPU/TPCFastTransformation/TPCFastTransform.cxx
sprasad-commits/AliRoot
41acc2e128fc8d502df15b9beae83e1fdcdb38f0
[ "BSD-3-Clause" ]
null
null
null
GPU/TPCFastTransformation/TPCFastTransform.cxx
sprasad-commits/AliRoot
41acc2e128fc8d502df15b9beae83e1fdcdb38f0
[ "BSD-3-Clause" ]
null
null
null
//**************************************************************************\ //* This file is property of and copyright by the ALICE Project *\ //* ALICE Experiment at CERN, All rights reserved. *\ //* *\ //* Primary Authors: Matthias Richter <Matthias.Richter@ift.uib.no> *\ //* for The ALICE HLT Project. *\ //* *\ //* Permission to use, copy, modify and distribute this software and its *\ //* documentation strictly for non-commercial purposes is hereby granted *\ //* without fee, provided that the above copyright notice appears in all *\ //* copies and that both the copyright notice and this permission notice *\ //* appear in the supporting documentation. The authors make no claims *\ //* about the suitability of this software for any purpose. It is *\ //* provided "as is" without express or implied warranty. *\ //************************************************************************** /// \file TPCFastTransform.cxx /// \brief Implementation of TPCFastTransform class /// /// \author Sergey Gorbunov <sergey.gorbunov@cern.ch> #include "TPCFastTransform.h" #if !defined(GPUCA_GPUCODE) #include <iostream> #endif using namespace GPUCA_NAMESPACE::gpu; TPCFastTransform::TPCFastTransform() : FlatObject(), mTimeStamp(0), mDistortion(), mApplyDistortion(1), mT0(0.f), mVdrift(0.f), mVdriftCorrY(0.f), mLdriftCorr(0.f), mTOFcorr(0.f), mPrimVtxZ(0.f) { // Default Constructor: creates an empty uninitialized object } void TPCFastTransform::relocateBufferPointers(const char* oldBuffer, char* actualBuffer) { char* distBuffer = FlatObject::relocatePointer(oldBuffer, actualBuffer, mDistortion.getFlatBufferPtr()); mDistortion.setActualBufferAddress(distBuffer); } void TPCFastTransform::cloneFromObject(const TPCFastTransform& obj, char* newFlatBufferPtr) { /// See FlatObject for description const char* oldFlatBufferPtr = obj.mFlatBufferPtr; FlatObject::cloneFromObject(obj, newFlatBufferPtr); mTimeStamp = obj.mTimeStamp; mApplyDistortion = obj.mApplyDistortion; mT0 = obj.mT0; mVdrift = obj.mVdrift; mVdriftCorrY = obj.mVdriftCorrY; mLdriftCorr = obj.mLdriftCorr; mTOFcorr = obj.mTOFcorr; mPrimVtxZ = obj.mPrimVtxZ; // variable-size data char* distBuffer = FlatObject::relocatePointer(oldFlatBufferPtr, mFlatBufferPtr, obj.mDistortion.getFlatBufferPtr()); mDistortion.cloneFromObject(obj.mDistortion, distBuffer); } void TPCFastTransform::moveBufferTo(char* newFlatBufferPtr) { /// See FlatObject for description const char* oldFlatBufferPtr = mFlatBufferPtr; FlatObject::moveBufferTo(newFlatBufferPtr); relocateBufferPointers(oldFlatBufferPtr, mFlatBufferPtr); } void TPCFastTransform::setActualBufferAddress(char* actualFlatBufferPtr) { /// See FlatObject for description const char* oldFlatBufferPtr = mFlatBufferPtr; FlatObject::setActualBufferAddress(actualFlatBufferPtr); relocateBufferPointers(oldFlatBufferPtr, mFlatBufferPtr); } void TPCFastTransform::setFutureBufferAddress(char* futureFlatBufferPtr) { /// See FlatObject for description const char* oldFlatBufferPtr = mFlatBufferPtr; char* distBuffer = FlatObject::relocatePointer(oldFlatBufferPtr, futureFlatBufferPtr, mDistortion.getFlatBufferPtr()); mDistortion.setFutureBufferAddress(distBuffer); FlatObject::setFutureBufferAddress(futureFlatBufferPtr); } void TPCFastTransform::startConstruction(const TPCDistortionIRS& distortion) { /// Starts the construction procedure, reserves temporary memory FlatObject::startConstruction(); assert(distortion.isConstructed()); mTimeStamp = 0; mApplyDistortion = 1; mT0 = 0.f; mVdrift = 0.f; mVdriftCorrY = 0.f; mLdriftCorr = 0.f; mTOFcorr = 0.f; mPrimVtxZ = 0.f; // variable-size data mDistortion.cloneFromObject(distortion, nullptr); } void TPCFastTransform::setCalibration(long int timeStamp, float t0, float vDrift, float vDriftCorrY, float lDriftCorr, float tofCorr, float primVtxZ) { /// Sets all drift calibration parameters and the time stamp /// /// It must be called once during initialization, /// but also may be called after to reset these parameters. mTimeStamp = timeStamp; mT0 = t0; mVdrift = vDrift; mVdriftCorrY = vDriftCorrY; mLdriftCorr = lDriftCorr; mTOFcorr = tofCorr; mPrimVtxZ = primVtxZ; mConstructionMask |= ConstructionExtraState::CalibrationIsSet; } void TPCFastTransform::finishConstruction() { /// Finishes initialization: puts everything to the flat buffer, releases temporary memory assert(mConstructionMask & ConstructionState::InProgress); // construction in process assert(mConstructionMask & ConstructionExtraState::CalibrationIsSet); // all parameters are set FlatObject::finishConstruction(mDistortion.getFlatBufferSize()); mDistortion.moveBufferTo(mFlatBufferPtr); } void TPCFastTransform::print() const { #if !defined(GPUCA_GPUCODE) std::cout << "TPC Fast Transformation: " << std::endl; std::cout << "mTimeStamp = " << mTimeStamp << std::endl; std::cout << "mApplyDistortion = " << mApplyDistortion << std::endl; std::cout << "mT0 = " << mT0 << std::endl; std::cout << "mVdrift = " << mVdrift << std::endl; std::cout << "mVdriftCorrY = " << mVdriftCorrY << std::endl; std::cout << "mLdriftCorr = " << mLdriftCorr << std::endl; std::cout << "mTOFcorr = " << mTOFcorr << std::endl; std::cout << "mPrimVtxZ = " << mPrimVtxZ << std::endl; mDistortion.print(); #endif }
35.93038
159
0.690682
[ "object" ]
1d7b132867336dc785cce308503d2984c0bfc24f
2,481
hpp
C++
src/l2_hashtable.hpp
ramcn/flappie-darwin
e542a6117eb61d7424f58ec8bb2f31f3c8a2039f
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
src/l2_hashtable.hpp
ramcn/flappie-darwin
e542a6117eb61d7424f58ec8bb2f31f3c8a2039f
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
src/l2_hashtable.hpp
ramcn/flappie-darwin
e542a6117eb61d7424f58ec8bb2f31f3c8a2039f
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
#ifndef L2_HASHTABLE_H_ #define L2_HASHTABLE_H_ #include <string> #include "stdint.h" #include "stdlib.h" #include "hash_common.hpp" #include <vector> class Hashtable; class L2Hashtable{ private: uint64_t l2seed_size = 10; uint64_t l2num_tables = 0; uint64_t l2table_size = (36<<8); uint32_t * l2hashtable = 0; uint32_t * l2locations = 0; size_t l2locations_size = 0; uint32_t l2threshold = 0; size_t l2overflow_size = 0; uint32_t * l2overflow_values = 0; const static uint64_t L2_OVERFLOW = 0x100000000; public: L2Hashtable(); L2Hashtable(uint32_t threshold); L2Hashtable(uint64_t num_tables, uint64_t locations, uint64_t overflow); L2Hashtable(std::string filename); ~L2Hashtable(); std::string get_name(); uint8_t pearsonHash(const char * seed); void l2_set_num_tables(uint64_t number); uint64_t l2_get_num_tables(); uint64_t l2_get_table_size(); size_t l2_get_locations_size(); uint32_t l2_get_threshold(); uint32_t l2_get_l2_seed_size(); void l2_init_hashtable(uint64_t num_tables); void l2_init_locations(uint64_t size); void l2_init_overflow(uint64_t size); uint64_t l2_get_index(uint32_t offset, uint32_t I, uint32_t J, uint8_t hash); uint64_t l2_get_overflow(uint64_t index); void l2_set_overflow(uint32_t i, uint64_t index); uint32_t l2_get_frequency(uint32_t offset, uint32_t I, uint32_t J, uint8_t hash); uint64_t l2_get_offset(uint32_t offset, uint32_t I, uint32_t J, uint8_t hash); uint32_t l2_get_frequency2(uint64_t index); uint64_t l2_get_offset2(uint64_t index); void l2_set_frequency(uint64_t index, uint32_t frequency); void l2_set_offset(uint64_t index, uint32_t offset); uint32_t l2_get_location(uint64_t offset); void l2_set_location(uint64_t offset, uint32_t location); void l2_write_to_file(const char * name); void l2_write_hashtable_to_file(const char * name); void l2_write_locations_to_file(const char * name); void l2_write_overflow_to_file(const char * name); void l2_read_from_file(const char * name); void l2_read_hashtable_from_file(const char * name); void l2_read_locations_from_file(const char * name); void l2_read_overflow_from_file(const char * name); static void construct_l2_tables(L2Hashtable & l2hashtable, Hashtable & hashtable, uint32_t big_buckets, std::vector<uint32_t> *buckets, std::vector<std::vector<char>* > *genome_vector, std::vector<uint32_t> ** l1table); void l2_free_memory(); }; #endif //L2_HASHTABLE_H_
30.62963
221
0.770254
[ "vector" ]
1d7cc75f67eea22c26c2337823e6b13eaa746146
27,575
cpp
C++
tests/array/testArrayBase.cpp
seagater/zfp
520596bdcb631ee98d43ff63d0955e34e56035ed
[ "BSD-3-Clause" ]
1
2022-01-30T00:22:55.000Z
2022-01-30T00:22:55.000Z
tests/array/testArrayBase.cpp
ncnight/zfp
520596bdcb631ee98d43ff63d0955e34e56035ed
[ "BSD-3-Clause" ]
1
2022-03-03T14:48:04.000Z
2022-03-03T14:51:03.000Z
tests/array/testArrayBase.cpp
ncnight/zfp
520596bdcb631ee98d43ff63d0955e34e56035ed
[ "BSD-3-Clause" ]
null
null
null
extern "C" { #include "utils/testMacros.h" #include "utils/zfpChecksums.h" #include "utils/zfpHash.h" } #include <cstring> #include <sstream> TEST_F(TEST_FIXTURE, when_constructorCalled_then_rateSetWithWriteRandomAccess) { double rate = ZFP_RATE_PARAM_BITS; #if DIMS == 1 ZFP_ARRAY_TYPE arr(inputDataSideLen, rate); EXPECT_LT(rate, arr.rate()); #elif DIMS == 2 ZFP_ARRAY_TYPE arr(inputDataSideLen, inputDataSideLen, rate); EXPECT_LT(rate, arr.rate()); #elif DIMS == 3 ZFP_ARRAY_TYPE arr(inputDataSideLen, inputDataSideLen, inputDataSideLen, rate); // wra in 3D supports integer fixed-rates [1, 64] (use <=) EXPECT_LE(rate, arr.rate()); #endif } TEST_F(TEST_FIXTURE, when_constructorCalledWithCacheSize_then_minCacheSizeEnforced) { size_t cacheSize = 300; #if DIMS == 1 ZFP_ARRAY_TYPE arr(inputDataSideLen, ZFP_RATE_PARAM_BITS, 0, cacheSize); #elif DIMS == 2 ZFP_ARRAY_TYPE arr(inputDataSideLen, inputDataSideLen, ZFP_RATE_PARAM_BITS, 0, cacheSize); #elif DIMS == 3 ZFP_ARRAY_TYPE arr(inputDataSideLen, inputDataSideLen, inputDataSideLen, ZFP_RATE_PARAM_BITS, 0, cacheSize); #endif EXPECT_LE(cacheSize, arr.cache_size()); } TEST_F(TEST_FIXTURE, when_setRate_then_compressionRateChanged) { double oldRate = ZFP_RATE_PARAM_BITS; #if DIMS == 1 ZFP_ARRAY_TYPE arr(inputDataSideLen, oldRate, inputDataArr); #elif DIMS == 2 ZFP_ARRAY_TYPE arr(inputDataSideLen, inputDataSideLen, oldRate, inputDataArr); #elif DIMS == 3 ZFP_ARRAY_TYPE arr(inputDataSideLen, inputDataSideLen, inputDataSideLen, oldRate, inputDataArr); #endif double actualOldRate = arr.rate(); size_t oldCompressedSize = arr.compressed_size(); uint64 oldChecksum = hashBitstream((uint64*)arr.compressed_data(), oldCompressedSize); double newRate = oldRate - 10; EXPECT_LT(1, newRate); arr.set_rate(newRate); EXPECT_GT(actualOldRate, arr.rate()); arr.set(inputDataArr); size_t newCompressedSize = arr.compressed_size(); uint64 checksum = hashBitstream((uint64*)arr.compressed_data(), newCompressedSize); EXPECT_PRED_FORMAT2(ExpectNeqPrintHexPred, oldChecksum, checksum); EXPECT_GT(oldCompressedSize, newCompressedSize); } void VerifyProperHeaderWritten(const zfp::array::header& h, uint chosenSizeX, uint chosenSizeY, uint chosenSizeZ, double chosenRate) { // copy header into aligned memory suitable for bitstream r/w size_t num_64bit_entries = DIV_ROUND_UP(ZFP_HEADER_SIZE_BITS, CHAR_BIT * sizeof(uint64)); uint64* buffer = new uint64[num_64bit_entries]; memcpy(buffer, &h, BITS_TO_BYTES(ZFP_HEADER_SIZE_BITS)); // verify valid header (manually through C API) bitstream* stream = stream_open(buffer, BITS_TO_BYTES(ZFP_HEADER_SIZE_BITS)); zfp_field* field = zfp_field_alloc(); zfp_stream* zfp = zfp_stream_open(stream); EXPECT_EQ(ZFP_HEADER_SIZE_BITS, zfp_read_header(zfp, field, ZFP_HEADER_FULL)); // verify header contents EXPECT_EQ(chosenSizeX, field->nx); EXPECT_EQ(chosenSizeY, field->ny); EXPECT_EQ(chosenSizeZ, field->nz); EXPECT_EQ(ZFP_TYPE, field->type); // to verify rate, we can only compare the 4 compression-param basis zfp_stream* expectedZfpStream = zfp_stream_open(0); zfp_stream_set_rate(expectedZfpStream, chosenRate, ZFP_TYPE, testEnv->getDims(), 1); EXPECT_EQ(expectedZfpStream->minbits, zfp->minbits); EXPECT_EQ(expectedZfpStream->maxbits, zfp->maxbits); EXPECT_EQ(expectedZfpStream->maxprec, zfp->maxprec); EXPECT_EQ(expectedZfpStream->minexp, zfp->minexp); zfp_stream_close(expectedZfpStream); zfp_stream_close(zfp); zfp_field_free(field); stream_close(stream); delete[] buffer; } TEST_F(TEST_FIXTURE, when_writeHeader_then_cCompatibleHeaderWritten) { double chosenRate = ZFP_RATE_PARAM_BITS; uint chosenSizeX, chosenSizeY, chosenSizeZ; #if DIMS == 1 chosenSizeX = 55; chosenSizeY = 0; chosenSizeZ = 0; ZFP_ARRAY_TYPE arr(chosenSizeX, chosenRate); #elif DIMS == 2 chosenSizeX = 55; chosenSizeY = 23; chosenSizeZ = 0; ZFP_ARRAY_TYPE arr(chosenSizeX, chosenSizeY, chosenRate); #elif DIMS == 3 chosenSizeX = 55; chosenSizeY = 23; chosenSizeZ = 31; ZFP_ARRAY_TYPE arr(chosenSizeX, chosenSizeY, chosenSizeZ, chosenRate); #endif zfp::array::header h = arr.get_header(); VerifyProperHeaderWritten(h, chosenSizeX, chosenSizeY, chosenSizeZ, chosenRate); } TEST_F(TEST_FIXTURE, when_generateRandomData_then_checksumMatches) { uint64 key1, key2; computeKeyOriginalInput(ARRAY_TEST, dimLens, &key1, &key2); EXPECT_PRED_FORMAT2(ExpectEqPrintHexPred, getChecksumByKey(DIMS, ZFP_TYPE, key1, key2), _catFunc2(hashArray, SCALAR_BITS)((UINT*)inputDataArr, inputDataTotalLen, 1)); } void FailWhenNoExceptionThrown() { FAIL() << "No exception was thrown when one was expected"; } void FailAndPrintException(std::exception const & e) { FAIL() << "Unexpected exception thrown: " << typeid(e).name() << std::endl << "With message: " << e.what(); } TEST_F(TEST_FIXTURE, when_constructorFromSerializedWithInvalidHeader_then_exceptionThrown) { zfp::array::header h = {0}; try { ZFP_ARRAY_TYPE arr(h, NULL); FailWhenNoExceptionThrown(); } catch (zfp::array::header::exception const & e) { EXPECT_EQ(e.what(), std::string("Invalid ZFP header.")); } catch (std::exception const & e) { FailAndPrintException(e); } } TEST_F(TEST_FIXTURE, given_zfpHeaderForCertainDimensionalityButHeaderMissing_when_construct_expect_zfpArrayHeaderExceptionThrown) { uint missingDim = ((DIMS + 1) % 3) + 1; zfp_stream_set_rate(stream, 12, ZFP_TYPE, missingDim, 1); zfp_field_set_type(field, ZFP_TYPE); switch(missingDim) { case 3: zfp_field_set_size_3d(field, 12, 12, 12); break; case 2: zfp_field_set_size_2d(field, 12, 12); break; case 1: zfp_field_set_size_1d(field, 12); break; } // write header to buffer with C API zfp_stream_rewind(stream); EXPECT_EQ(ZFP_HEADER_SIZE_BITS, zfp_write_header(stream, field, ZFP_HEADER_FULL)); zfp_stream_flush(stream); zfp::array::header h; // zfp::array::header collects header up to next byte memcpy(h.buffer, buffer, BITS_TO_BYTES(ZFP_HEADER_SIZE_BITS)); try { zfp::array* arr = zfp::array::construct(h); FailWhenNoExceptionThrown(); } catch (zfp::array::header::exception const & e) { std::stringstream ss; ss << "Header files for " << missingDim << " dimensional ZFP compressed arrays were not included."; EXPECT_EQ(e.what(), ss.str()); } catch (std::exception const & e) { FailAndPrintException(e); } } TEST_F(TEST_FIXTURE, given_serializedCompressedArrayFromWrongScalarType_when_constructorFromSerialized_then_exceptionThrown) { #if DIMS == 1 ZFP_ARRAY_TYPE_WRONG_SCALAR arr(inputDataSideLen, ZFP_RATE_PARAM_BITS); #elif DIMS == 2 ZFP_ARRAY_TYPE_WRONG_SCALAR arr(inputDataSideLen, inputDataSideLen, ZFP_RATE_PARAM_BITS); #elif DIMS == 3 ZFP_ARRAY_TYPE_WRONG_SCALAR arr(inputDataSideLen, inputDataSideLen, inputDataSideLen, ZFP_RATE_PARAM_BITS); #endif zfp::array::header h = arr.get_header(); try { ZFP_ARRAY_TYPE arr2(h, arr.compressed_data()); FailWhenNoExceptionThrown(); } catch (zfp::array::header::exception const & e) { EXPECT_EQ(e.what(), std::string("ZFP header specified an underlying scalar type different than that for this object.")); } catch (std::exception const & e) { FailAndPrintException(e); } } TEST_F(TEST_FIXTURE, given_serializedCompressedArrayFromWrongDimensionality_when_constructorFromSerialized_then_exceptionThrown) { #if DIMS == 1 ZFP_ARRAY_TYPE_WRONG_DIM arr(100, 100, ZFP_RATE_PARAM_BITS); #elif DIMS == 2 ZFP_ARRAY_TYPE_WRONG_DIM arr(100, 100, 100, ZFP_RATE_PARAM_BITS); #elif DIMS == 3 ZFP_ARRAY_TYPE_WRONG_DIM arr(100, ZFP_RATE_PARAM_BITS); #endif zfp::array::header h = arr.get_header(); try { ZFP_ARRAY_TYPE arr2(h, arr.compressed_data()); FailWhenNoExceptionThrown(); } catch (zfp::array::header::exception const & e) { EXPECT_EQ(e.what(), std::string("ZFP header specified a dimensionality different than that for this object.")); } catch (std::exception const & e) { FailAndPrintException(e); } } TEST_F(TEST_FIXTURE, given_serializedNonFixedRateHeader_when_constructorFromSerialized_then_exceptionThrown) { // create a compressed stream through C API // (one that is not supported with compressed arrays) zfp_field* field; #if DIMS == 1 field = zfp_field_1d(inputDataArr, ZFP_TYPE, inputDataSideLen); #elif DIMS == 2 field = zfp_field_2d(inputDataArr, ZFP_TYPE, inputDataSideLen, inputDataSideLen); #elif DIMS == 3 field = zfp_field_3d(inputDataArr, ZFP_TYPE, inputDataSideLen, inputDataSideLen, inputDataSideLen); #endif zfp_stream* stream = zfp_stream_open(NULL); size_t bufsizeBytes = zfp_stream_maximum_size(stream, field); uchar* buffer = new uchar[bufsizeBytes]; memset(buffer, 0, bufsizeBytes); bitstream* bs = stream_open(buffer, bufsizeBytes); zfp_stream_set_bit_stream(stream, bs); zfp_stream_rewind(stream); zfp_stream_set_precision(stream, 10); EXPECT_NE(zfp_mode_fixed_rate, zfp_stream_compression_mode(stream)); // write header size_t writtenBits = zfp_write_header(stream, field, ZFP_HEADER_FULL); EXPECT_EQ(ZFP_HEADER_SIZE_BITS, writtenBits); zfp_stream_flush(stream); // copy header into header size_t headerSizeBytes = DIV_ROUND_UP(writtenBits, CHAR_BIT); zfp::array::header h; memcpy(h.buffer, buffer, headerSizeBytes); // compress data uchar* compressedDataPtr = (uchar*)stream_data(bs) + headerSizeBytes; zfp_compress(stream, field); // close/free C API things (keep buffer) zfp_field_free(field); zfp_stream_close(stream); stream_close(bs); try { ZFP_ARRAY_TYPE arr2(h, compressedDataPtr, bufsizeBytes - headerSizeBytes); FailWhenNoExceptionThrown(); } catch (zfp::array::header::exception const & e) { EXPECT_EQ(e.what(), std::string("ZFP header specified a non fixed-rate mode, unsupported by this object.")); } catch (std::exception const & e) { FailAndPrintException(e); } delete[] buffer; } TEST_F(TEST_FIXTURE, given_serializedNonFixedRateWrongScalarTypeWrongDimensionalityHeader_when_constructorFromSerialized_then_exceptionsThrown) { // create a compressed stream through C API // (one that is not supported with compressed arrays) zfp_field* field; // (inputDataSideLen specific to that dimensionality, can request too much memory if fitted to higher dimensionality) #if DIMS == 1 field = zfp_field_1d(inputDataArr, zfp_type_int32, 100); #elif DIMS == 2 field = zfp_field_2d(inputDataArr, zfp_type_int32, 100, 100); #elif DIMS == 3 field = zfp_field_3d(inputDataArr, zfp_type_int32, 100, 100, 100); #endif zfp_stream* stream = zfp_stream_open(NULL); size_t bufsizeBytes = zfp_stream_maximum_size(stream, field); uchar* buffer = new uchar[bufsizeBytes]; memset(buffer, 0, bufsizeBytes); bitstream* bs = stream_open(buffer, bufsizeBytes); zfp_stream_set_bit_stream(stream, bs); zfp_stream_rewind(stream); zfp_stream_set_precision(stream, 10); EXPECT_NE(zfp_mode_fixed_rate, zfp_stream_compression_mode(stream)); // write header size_t writtenBits = zfp_write_header(stream, field, ZFP_HEADER_FULL); EXPECT_EQ(ZFP_HEADER_SIZE_BITS, writtenBits); zfp_stream_flush(stream); // copy header into header size_t headerSizeBytes = (writtenBits + CHAR_BIT - 1) / CHAR_BIT; zfp::array::header h; memcpy(h.buffer, buffer, headerSizeBytes); // compress data uchar* compressedDataPtr = (uchar*)stream_data(bs) + headerSizeBytes; zfp_compress(stream, field); // close/free C API things (keep buffer) zfp_field_free(field); zfp_stream_close(stream); stream_close(bs); try { ZFP_ARRAY_TYPE_WRONG_SCALAR_DIM arr2(h, compressedDataPtr, bufsizeBytes - headerSizeBytes); FailWhenNoExceptionThrown(); } catch (zfp::array::header::exception const & e) { EXPECT_TRUE(strstr(e.what(), "ZFP header specified an underlying scalar type different than that for this object.") != NULL); EXPECT_TRUE(strstr(e.what(), "ZFP header specified a dimensionality different than that for this object.") != NULL); EXPECT_TRUE(strstr(e.what(), "ZFP compressed arrays do not yet support scalar types beyond floats and doubles.") != NULL); EXPECT_TRUE(strstr(e.what(), "ZFP header specified a non fixed-rate mode, unsupported by this object.") != NULL); // print exception if any of above were not met if (HasFailure()) { FailAndPrintException(e); } } catch (std::exception const & e) { FailAndPrintException(e); } delete[] buffer; } TEST_F(TEST_FIXTURE, given_compatibleHeaderWrittenViaCApi_when_constructorFromSerialized_then_successWithParamsSet) { // create a compressed stream through C API // (one that is supported with compressed arrays) zfp_field* field; #if DIMS == 1 field = zfp_field_1d(inputDataArr, ZFP_TYPE, inputDataSideLen); #elif DIMS == 2 field = zfp_field_2d(inputDataArr, ZFP_TYPE, inputDataSideLen, inputDataSideLen); #elif DIMS == 3 field = zfp_field_3d(inputDataArr, ZFP_TYPE, inputDataSideLen, inputDataSideLen, inputDataSideLen); #endif zfp_stream* stream = zfp_stream_open(NULL); size_t bufsizeBytes = zfp_stream_maximum_size(stream, field); uchar* buffer = new uchar[bufsizeBytes]; memset(buffer, 0, bufsizeBytes); bitstream* bs = stream_open(buffer, bufsizeBytes); zfp_stream_set_bit_stream(stream, bs); zfp_stream_rewind(stream); double rate = zfp_stream_set_rate(stream, 10, ZFP_TYPE, DIMS, 1); EXPECT_EQ(zfp_mode_fixed_rate, zfp_stream_compression_mode(stream)); // write header size_t writtenBits = zfp_write_header(stream, field, ZFP_HEADER_FULL); EXPECT_EQ(ZFP_HEADER_SIZE_BITS, writtenBits); zfp_stream_flush(stream); // copy header into header size_t headerSizeBytes = (writtenBits + CHAR_BIT - 1) / CHAR_BIT; zfp::array::header h; memcpy(h.buffer, buffer, headerSizeBytes); // compress data uchar* compressedDataPtr = (uchar*)stream_data(bs) + headerSizeBytes; zfp_compress(stream, field); try { ZFP_ARRAY_TYPE arr2(h, compressedDataPtr, bufsizeBytes - headerSizeBytes); EXPECT_EQ(arr2.dimensionality(), zfp_field_dimensionality(field)); EXPECT_EQ(arr2.scalar_type(), zfp_field_type(field)); uint n[4]; EXPECT_EQ(arr2.size(), zfp_field_size(field, n)); #if DIMS == 1 EXPECT_EQ(arr2.size_x(), n[0]); #elif DIMS == 2 EXPECT_EQ(arr2.size_x(), n[0]); EXPECT_EQ(arr2.size_y(), n[1]); #elif DIMS == 3 EXPECT_EQ(arr2.size_x(), n[0]); EXPECT_EQ(arr2.size_y(), n[1]); EXPECT_EQ(arr2.size_z(), n[2]); #endif EXPECT_EQ(arr2.rate(), rate); } catch (std::exception const & e) { FailAndPrintException(e); } zfp_stream_close(stream); stream_close(bs); zfp_field_free(field); delete[] buffer; } TEST_F(TEST_FIXTURE, given_incompleteChunkOfSerializedCompressedArray_when_constructorFromSerialized_then_exceptionThrown) { #if DIMS == 1 ZFP_ARRAY_TYPE arr(inputDataSideLen, ZFP_RATE_PARAM_BITS); #elif DIMS == 2 ZFP_ARRAY_TYPE arr(inputDataSideLen, inputDataSideLen, ZFP_RATE_PARAM_BITS); #elif DIMS == 3 ZFP_ARRAY_TYPE arr(inputDataSideLen, inputDataSideLen, inputDataSideLen, ZFP_RATE_PARAM_BITS); #endif zfp::array::header h = arr.get_header(); try { ZFP_ARRAY_TYPE arr2(h, arr.compressed_data(), arr.compressed_size() - 1); FailWhenNoExceptionThrown(); } catch (zfp::array::header::exception const & e) { EXPECT_EQ(e.what(), std::string("ZFP header expects a longer buffer than what was passed in.")); } catch (std::exception const & e) { FailAndPrintException(e); } } TEST_F(TEST_FIXTURE, given_serializedCompressedArrayHeader_when_factoryFuncConstruct_then_correctTypeConstructed) { #if DIMS == 1 ZFP_ARRAY_TYPE arr(inputDataSideLen, ZFP_RATE_PARAM_BITS); #elif DIMS == 2 ZFP_ARRAY_TYPE arr(inputDataSideLen, inputDataSideLen, ZFP_RATE_PARAM_BITS); #elif DIMS == 3 ZFP_ARRAY_TYPE arr(inputDataSideLen, inputDataSideLen, inputDataSideLen, ZFP_RATE_PARAM_BITS); #endif zfp::array::header h = arr.get_header(); array* arr2 = zfp::array::construct(h); ASSERT_TRUE(arr2 != 0); ASSERT_TRUE(dynamic_cast<ZFP_ARRAY_TYPE *>(arr2) != NULL); ASSERT_TRUE(dynamic_cast<ZFP_ARRAY_TYPE_WRONG_DIM *>(arr2) == NULL); delete arr2; } TEST_F(TEST_FIXTURE, given_serializedCompressedArray_when_factoryFuncConstruct_then_correctTypeConstructedWithPopulatedEntries) { #if DIMS == 1 ZFP_ARRAY_TYPE arr(inputDataSideLen, ZFP_RATE_PARAM_BITS); #elif DIMS == 2 ZFP_ARRAY_TYPE arr(inputDataSideLen, inputDataSideLen, ZFP_RATE_PARAM_BITS); #elif DIMS == 3 ZFP_ARRAY_TYPE arr(inputDataSideLen, inputDataSideLen, inputDataSideLen, ZFP_RATE_PARAM_BITS); #endif arr[1] = 999.; zfp::array::header h = arr.get_header(); array* arr2 = zfp::array::construct(h, arr.compressed_data(), arr.compressed_size()); ASSERT_TRUE(arr2 != 0); EXPECT_EQ(arr.compressed_size(), arr2->compressed_size()); ASSERT_TRUE(std::memcmp(arr.compressed_data(), arr2->compressed_data(), arr.compressed_size()) == 0); delete arr2; } TEST_F(TEST_FIXTURE, given_uncompatibleSerializedMem_when_factoryFuncConstruct_then_throwsZfpHeaderException) { zfp::array::header h = {0}; size_t dummyLen = 1024; uchar* dummyMem = new uchar[dummyLen]; memset(dummyMem, 0, dummyLen); try { array* arr = zfp::array::construct(h, dummyMem, dummyLen); } catch (zfp::array::header::exception const & e) { EXPECT_EQ(e.what(), std::string("Invalid ZFP header.")); } catch (std::exception const & e) { FailAndPrintException(e); } delete[] dummyMem; } #if DIMS == 1 // with write random access in 1D, fixed-rate params rounded up to multiples of 16 INSTANTIATE_TEST_CASE_P(TestManyCompressionRates, TEST_FIXTURE, ::testing::Values(1, 2)); #else INSTANTIATE_TEST_CASE_P(TestManyCompressionRates, TEST_FIXTURE, ::testing::Values(0, 1, 2)); #endif TEST_P(TEST_FIXTURE, given_dataset_when_set_then_underlyingBitstreamChecksumMatches) { #if DIMS == 1 ZFP_ARRAY_TYPE arr(inputDataSideLen, getRate()); #elif DIMS == 2 ZFP_ARRAY_TYPE arr(inputDataSideLen, inputDataSideLen, getRate()); #elif DIMS == 3 ZFP_ARRAY_TYPE arr(inputDataSideLen, inputDataSideLen, inputDataSideLen, getRate()); #endif uint64 key1, key2; computeKey(ARRAY_TEST, COMPRESSED_BITSTREAM, dimLens, zfp_mode_fixed_rate, GetParam(), &key1, &key2); uint64 expectedChecksum = getChecksumByKey(DIMS, ZFP_TYPE, key1, key2); uint64 checksum = hashBitstream((uint64*)arr.compressed_data(), arr.compressed_size()); EXPECT_PRED_FORMAT2(ExpectNeqPrintHexPred, expectedChecksum, checksum); arr.set(inputDataArr); checksum = hashBitstream((uint64*)arr.compressed_data(), arr.compressed_size()); EXPECT_PRED_FORMAT2(ExpectEqPrintHexPred, expectedChecksum, checksum); } TEST_P(TEST_FIXTURE, given_setArray_when_get_then_decompressedValsReturned) { #if DIMS == 1 ZFP_ARRAY_TYPE arr(inputDataSideLen, getRate(), inputDataArr); #elif DIMS == 2 ZFP_ARRAY_TYPE arr(inputDataSideLen, inputDataSideLen, getRate(), inputDataArr); #elif DIMS == 3 ZFP_ARRAY_TYPE arr(inputDataSideLen, inputDataSideLen, inputDataSideLen, getRate(), inputDataArr); #endif SCALAR* decompressedArr = new SCALAR[inputDataTotalLen]; arr.get(decompressedArr); uint64 key1, key2; computeKey(ARRAY_TEST, DECOMPRESSED_ARRAY, dimLens, zfp_mode_fixed_rate, GetParam(), &key1, &key2); uint64 expectedChecksum = getChecksumByKey(DIMS, ZFP_TYPE, key1, key2); uint64 checksum = _catFunc2(hashArray, SCALAR_BITS)((UINT*)decompressedArr, inputDataTotalLen, 1); EXPECT_PRED_FORMAT2(ExpectEqPrintHexPred, expectedChecksum, checksum); delete[] decompressedArr; } TEST_P(TEST_FIXTURE, given_populatedCompressedArray_when_resizeWithClear_then_bitstreamZeroed) { #if DIMS == 1 ZFP_ARRAY_TYPE arr(inputDataSideLen, getRate()); #elif DIMS == 2 ZFP_ARRAY_TYPE arr(inputDataSideLen, inputDataSideLen, getRate()); #elif DIMS == 3 ZFP_ARRAY_TYPE arr(inputDataSideLen, inputDataSideLen, inputDataSideLen, getRate()); #endif arr.set(inputDataArr); EXPECT_NE(0u, hashBitstream((uint64*)arr.compressed_data(), arr.compressed_size())); #if DIMS == 1 arr.resize(inputDataSideLen + 1, true); #elif DIMS == 2 arr.resize(inputDataSideLen + 1, inputDataSideLen + 1, true); #elif DIMS == 3 arr.resize(inputDataSideLen + 1, inputDataSideLen + 1, inputDataSideLen + 1, true); #endif EXPECT_EQ(0u, hashBitstream((uint64*)arr.compressed_data(), arr.compressed_size())); } TEST_P(TEST_FIXTURE, when_configureCompressedArrayFromDefaultConstructor_then_bitstreamChecksumMatches) { ZFP_ARRAY_TYPE arr; #if DIMS == 1 arr.resize(inputDataSideLen, false); #elif DIMS == 2 arr.resize(inputDataSideLen, inputDataSideLen, false); #elif DIMS == 3 arr.resize(inputDataSideLen, inputDataSideLen, inputDataSideLen, false); #endif arr.set_rate(getRate()); arr.set(inputDataArr); uint64 key1, key2; computeKey(ARRAY_TEST, COMPRESSED_BITSTREAM, dimLens, zfp_mode_fixed_rate, GetParam(), &key1, &key2); uint64 expectedChecksum = getChecksumByKey(DIMS, ZFP_TYPE, key1, key2); uint64 checksum = hashBitstream((uint64*)arr.compressed_data(), arr.compressed_size()); EXPECT_PRED_FORMAT2(ExpectEqPrintHexPred, expectedChecksum, checksum); } // assumes arr1 was given a dirty cache // this irreversibly changes arr1 (clears entries) void CheckDeepCopyPerformedViaDirtyCache(ZFP_ARRAY_TYPE& arr1, ZFP_ARRAY_TYPE& arr2, uchar* arr1UnflushedBitstreamPtr) { // flush arr2 first, to ensure arr1 remains unflushed uint64 checksum = hashBitstream((uint64*)arr2.compressed_data(), arr2.compressed_size()); uint64 arr1UnflushedChecksum = hashBitstream((uint64*)arr1UnflushedBitstreamPtr, arr1.compressed_size()); EXPECT_PRED_FORMAT2(ExpectNeqPrintHexPred, arr1UnflushedChecksum, checksum); // flush arr1, compute its checksum, clear its bitstream, re-compute arr2's checksum uint64 expectedChecksum = hashBitstream((uint64*)arr1.compressed_data(), arr1.compressed_size()); #if DIMS == 1 arr1.resize(arr1.size(), true); #elif DIMS == 2 arr1.resize(arr1.size_x(), arr1.size_y(), true); #elif DIMS == 3 arr1.resize(arr1.size_x(), arr1.size_y(), arr1.size_z(), true); #endif checksum = hashBitstream((uint64*)arr2.compressed_data(), arr2.compressed_size()); EXPECT_PRED_FORMAT2(ExpectEqPrintHexPred, expectedChecksum, checksum); } // this irreversibly changes arr1 (resize + clears entries) void CheckMemberVarsCopied(ZFP_ARRAY_TYPE& arr1, const ZFP_ARRAY_TYPE& arr2, bool assertCacheSize) { double oldRate = arr1.rate(); size_t oldCompressedSize = arr1.compressed_size(); size_t oldCacheSize = arr1.cache_size(); #if DIMS == 1 size_t oldSizeX = arr1.size(); arr1.resize(oldSizeX - 10); #elif DIMS == 2 size_t oldSizeX = arr1.size_x(); size_t oldSizeY = arr1.size_y(); arr1.resize(oldSizeX - 10, oldSizeY - 5); #elif DIMS == 3 size_t oldSizeX = arr1.size_x(); size_t oldSizeY = arr1.size_y(); size_t oldSizeZ = arr1.size_z(); arr1.resize(oldSizeX - 10, oldSizeY - 5, oldSizeZ - 8); #endif arr1.set_rate(oldRate + 10); arr1.set(inputDataArr); arr1.set_cache_size(oldCacheSize + 10); EXPECT_EQ(oldRate, arr2.rate()); EXPECT_EQ(oldCompressedSize, arr2.compressed_size()); if (assertCacheSize) EXPECT_EQ(oldCacheSize, arr2.cache_size()); #if DIMS == 1 EXPECT_EQ(oldSizeX, arr2.size()); #elif DIMS == 2 EXPECT_EQ(oldSizeX, arr2.size_x()); EXPECT_EQ(oldSizeY, arr2.size_y()); #elif DIMS == 3 EXPECT_EQ(oldSizeX, arr2.size_x()); EXPECT_EQ(oldSizeY, arr2.size_y()); EXPECT_EQ(oldSizeZ, arr2.size_z()); #endif } TEST_P(TEST_FIXTURE, given_compressedArray_when_copyConstructor_then_memberVariablesCopied) { #if DIMS == 1 ZFP_ARRAY_TYPE arr(inputDataSideLen, getRate(), inputDataArr, 128); #elif DIMS == 2 ZFP_ARRAY_TYPE arr(inputDataSideLen, inputDataSideLen, getRate(), inputDataArr, 128); #elif DIMS == 3 ZFP_ARRAY_TYPE arr(inputDataSideLen, inputDataSideLen, inputDataSideLen, getRate(), inputDataArr, 128); #endif ZFP_ARRAY_TYPE arr2(arr); CheckMemberVarsCopied(arr, arr2, true); } TEST_P(TEST_FIXTURE, given_compressedArray_when_copyConstructor_then_deepCopyPerformed) { #if DIMS == 1 ZFP_ARRAY_TYPE arr(inputDataSideLen, getRate(), inputDataArr); #elif DIMS == 2 ZFP_ARRAY_TYPE arr(inputDataSideLen, inputDataSideLen, getRate(), inputDataArr); #elif DIMS == 3 ZFP_ARRAY_TYPE arr(inputDataSideLen, inputDataSideLen, inputDataSideLen, getRate(), inputDataArr); #endif // create arr with dirty cache uchar* arrUnflushedBitstreamPtr = arr.compressed_data(); arr[0] = 999; ZFP_ARRAY_TYPE arr2(arr); CheckDeepCopyPerformedViaDirtyCache(arr, arr2, arrUnflushedBitstreamPtr); } TEST_P(TEST_FIXTURE, given_compressedArray_when_setSecondArrayEqualToFirst_then_memberVariablesCopied) { #if DIMS == 1 ZFP_ARRAY_TYPE arr(inputDataSideLen, getRate(), inputDataArr, 128); #elif DIMS == 2 ZFP_ARRAY_TYPE arr(inputDataSideLen, inputDataSideLen, getRate(), inputDataArr, 128); #elif DIMS == 3 ZFP_ARRAY_TYPE arr(inputDataSideLen, inputDataSideLen, inputDataSideLen, getRate(), inputDataArr, 128); #endif ZFP_ARRAY_TYPE arr2 = arr; CheckMemberVarsCopied(arr, arr2, true); } TEST_P(TEST_FIXTURE, given_compressedArray_when_setSecondArrayEqualToFirst_then_deepCopyPerformed) { #if DIMS == 1 ZFP_ARRAY_TYPE arr(inputDataSideLen, getRate(), inputDataArr); #elif DIMS == 2 ZFP_ARRAY_TYPE arr(inputDataSideLen, inputDataSideLen, getRate(), inputDataArr); #elif DIMS == 3 ZFP_ARRAY_TYPE arr(inputDataSideLen, inputDataSideLen, inputDataSideLen, getRate(), inputDataArr); #endif // create arr with dirty cache uchar* arrUnflushedBitstreamPtr = arr.compressed_data(); arr[0] = 999; ZFP_ARRAY_TYPE arr2 = arr; CheckDeepCopyPerformedViaDirtyCache(arr, arr2, arrUnflushedBitstreamPtr); } void CheckHeadersEquivalent(const ZFP_ARRAY_TYPE& arr1, const ZFP_ARRAY_TYPE& arr2) { zfp::array::header h[2]; h[0] = arr1.get_header(); h[1] = arr2.get_header(); uint64 header1Checksum = hashBitstream((uint64*)(h + 0), BITS_TO_BYTES(ZFP_HEADER_SIZE_BITS)); uint64 header2Checksum = hashBitstream((uint64*)(h + 1), BITS_TO_BYTES(ZFP_HEADER_SIZE_BITS)); EXPECT_PRED_FORMAT2(ExpectEqPrintHexPred, header1Checksum, header2Checksum); } // this clears arr1's entries void CheckDeepCopyPerformed(ZFP_ARRAY_TYPE& arr1, ZFP_ARRAY_TYPE& arr2) { // flush arr1, compute its checksum, clear its bitstream, re-compute arr2's checksum uint64 expectedChecksum = hashBitstream((uint64*)arr1.compressed_data(), arr1.compressed_size()); #if DIMS == 1 arr1.resize(arr1.size(), true); #elif DIMS == 2 arr1.resize(arr1.size_x(), arr1.size_y(), true); #elif DIMS == 3 arr1.resize(arr1.size_x(), arr1.size_y(), arr1.size_z(), true); #endif uint64 checksum = hashBitstream((uint64*)arr2.compressed_data(), arr2.compressed_size()); EXPECT_PRED_FORMAT2(ExpectEqPrintHexPred, expectedChecksum, checksum); } TEST_P(TEST_FIXTURE, given_serializedCompressedArray_when_constructorFromSerialized_then_constructedArrIsBasicallyADeepCopy) { #if DIMS == 1 ZFP_ARRAY_TYPE arr(inputDataSideLen, getRate(), inputDataArr); #elif DIMS == 2 ZFP_ARRAY_TYPE arr(inputDataSideLen, inputDataSideLen, getRate(), inputDataArr); #elif DIMS == 3 ZFP_ARRAY_TYPE arr(inputDataSideLen, inputDataSideLen, inputDataSideLen, getRate(), inputDataArr); #endif zfp::array::header h = arr.get_header(); ZFP_ARRAY_TYPE arr2(h, arr.compressed_data(), arr.compressed_size()); CheckHeadersEquivalent(arr, arr2); CheckDeepCopyPerformed(arr, arr2); // cache size not preserved CheckMemberVarsCopied(arr, arr2, false); }
33.505468
168
0.756011
[ "object", "3d" ]
1d7d93b99cb4e749dafbe21c26df84f5c78ef4e9
8,961
cc
C++
examples/pxScene2d/external/breakpad-chrome_55/src/client/linux/crash_generation/crash_generation_server.cc
madanagopaltcomcast/pxCore
c4a3a40a190521c8b6383d126c87612eca5b3c42
[ "Apache-2.0" ]
46
2017-09-07T14:59:22.000Z
2020-10-31T20:34:12.000Z
examples/pxScene2d/external/breakpad-chrome_55/src/client/linux/crash_generation/crash_generation_server.cc
madanagopaltcomcast/pxCore
c4a3a40a190521c8b6383d126c87612eca5b3c42
[ "Apache-2.0" ]
1,432
2017-06-21T04:08:48.000Z
2020-08-25T16:21:15.000Z
examples/pxScene2d/external/breakpad-chrome_55/src/client/linux/crash_generation/crash_generation_server.cc
madanagopaltcomcast/pxCore
c4a3a40a190521c8b6383d126c87612eca5b3c42
[ "Apache-2.0" ]
317
2017-06-20T19:57:17.000Z
2020-09-16T10:28:30.000Z
// Copyright (c) 2010 Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include <assert.h> #include <dirent.h> #include <fcntl.h> #include <limits.h> #include <poll.h> #include <stdio.h> #include <string.h> #include <sys/socket.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include <vector> #include "client/linux/crash_generation/crash_generation_server.h" #include "client/linux/crash_generation/client_info.h" #include "client/linux/handler/exception_handler.h" #include "client/linux/minidump_writer/minidump_writer.h" #include "common/linux/eintr_wrapper.h" #include "common/linux/guid_creator.h" #include "common/linux/safe_readlink.h" static const char kCommandQuit = 'x'; namespace google_breakpad { CrashGenerationServer::CrashGenerationServer( const int listen_fd, OnClientDumpRequestCallback dump_callback, void* dump_context, OnClientExitingCallback exit_callback, void* exit_context, bool generate_dumps, const string* dump_path) : server_fd_(listen_fd), dump_callback_(dump_callback), dump_context_(dump_context), exit_callback_(exit_callback), exit_context_(exit_context), generate_dumps_(generate_dumps), started_(false) { if (dump_path) dump_dir_ = *dump_path; else dump_dir_ = "/tmp"; } CrashGenerationServer::~CrashGenerationServer() { if (started_) Stop(); } bool CrashGenerationServer::Start() { if (started_ || 0 > server_fd_) return false; int control_pipe[2]; if (pipe(control_pipe)) return false; if (fcntl(control_pipe[0], F_SETFD, FD_CLOEXEC)) return false; if (fcntl(control_pipe[1], F_SETFD, FD_CLOEXEC)) return false; if (fcntl(control_pipe[0], F_SETFL, O_NONBLOCK)) return false; control_pipe_in_ = control_pipe[0]; control_pipe_out_ = control_pipe[1]; if (pthread_create(&thread_, NULL, ThreadMain, reinterpret_cast<void*>(this))) return false; started_ = true; return true; } void CrashGenerationServer::Stop() { assert(pthread_self() != thread_); if (!started_) return; HANDLE_EINTR(write(control_pipe_out_, &kCommandQuit, 1)); void* dummy; pthread_join(thread_, &dummy); close(control_pipe_in_); close(control_pipe_out_); started_ = false; } //static bool CrashGenerationServer::CreateReportChannel(int* server_fd, int* client_fd) { int fds[2]; if (socketpair(AF_UNIX, SOCK_SEQPACKET, 0, fds)) return false; static const int on = 1; // Enable passcred on the server end of the socket if (setsockopt(fds[1], SOL_SOCKET, SO_PASSCRED, &on, sizeof(on))) return false; if (fcntl(fds[1], F_SETFL, O_NONBLOCK)) return false; if (fcntl(fds[1], F_SETFD, FD_CLOEXEC)) return false; *client_fd = fds[0]; *server_fd = fds[1]; return true; } // The following methods/functions execute on the server thread void CrashGenerationServer::Run() { struct pollfd pollfds[2]; memset(&pollfds, 0, sizeof(pollfds)); pollfds[0].fd = server_fd_; pollfds[0].events = POLLIN; pollfds[1].fd = control_pipe_in_; pollfds[1].events = POLLIN; while (true) { // infinite timeout int nevents = poll(pollfds, sizeof(pollfds)/sizeof(pollfds[0]), -1); if (-1 == nevents) { if (EINTR == errno) { continue; } else { return; } } if (pollfds[0].revents && !ClientEvent(pollfds[0].revents)) return; if (pollfds[1].revents && !ControlEvent(pollfds[1].revents)) return; } } bool CrashGenerationServer::ClientEvent(short revents) { if (POLLHUP & revents) return false; assert(POLLIN & revents); // A process has crashed and has signaled us by writing a datagram // to the death signal socket. The datagram contains the crash context needed // for writing the minidump as well as a file descriptor and a credentials // block so that they can't lie about their pid. // The length of the control message: static const unsigned kControlMsgSize = CMSG_SPACE(sizeof(int)) + CMSG_SPACE(sizeof(struct ucred)); // The length of the regular payload: static const unsigned kCrashContextSize = sizeof(google_breakpad::ExceptionHandler::CrashContext); struct msghdr msg = {0}; struct iovec iov[1]; char crash_context[kCrashContextSize]; char control[kControlMsgSize]; const ssize_t expected_msg_size = sizeof(crash_context); iov[0].iov_base = crash_context; iov[0].iov_len = sizeof(crash_context); msg.msg_iov = iov; msg.msg_iovlen = sizeof(iov)/sizeof(iov[0]); msg.msg_control = control; msg.msg_controllen = kControlMsgSize; const ssize_t msg_size = HANDLE_EINTR(recvmsg(server_fd_, &msg, 0)); if (msg_size != expected_msg_size) return true; if (msg.msg_controllen != kControlMsgSize || msg.msg_flags & ~MSG_TRUNC) return true; // Walk the control payload and extract the file descriptor and validated pid. pid_t crashing_pid = -1; int signal_fd = -1; for (struct cmsghdr *hdr = CMSG_FIRSTHDR(&msg); hdr; hdr = CMSG_NXTHDR(&msg, hdr)) { if (hdr->cmsg_level != SOL_SOCKET) continue; if (hdr->cmsg_type == SCM_RIGHTS) { const unsigned len = hdr->cmsg_len - (((uint8_t*)CMSG_DATA(hdr)) - (uint8_t*)hdr); assert(len % sizeof(int) == 0u); const unsigned num_fds = len / sizeof(int); if (num_fds > 1 || num_fds == 0) { // A nasty process could try and send us too many descriptors and // force a leak. for (unsigned i = 0; i < num_fds; ++i) close(reinterpret_cast<int*>(CMSG_DATA(hdr))[i]); return true; } else { signal_fd = reinterpret_cast<int*>(CMSG_DATA(hdr))[0]; } } else if (hdr->cmsg_type == SCM_CREDENTIALS) { const struct ucred *cred = reinterpret_cast<struct ucred*>(CMSG_DATA(hdr)); crashing_pid = cred->pid; } } if (crashing_pid == -1 || signal_fd == -1) { if (signal_fd) close(signal_fd); return true; } string minidump_filename; if (!MakeMinidumpFilename(minidump_filename)) return true; if (!google_breakpad::WriteMinidump(minidump_filename.c_str(), crashing_pid, crash_context, kCrashContextSize)) { close(signal_fd); return true; } if (dump_callback_) { ClientInfo info(crashing_pid, this); dump_callback_(dump_context_, &info, &minidump_filename); } // Send the done signal to the process: it can exit now. // (Closing this will make the child's sys_read unblock and return 0.) close(signal_fd); return true; } bool CrashGenerationServer::ControlEvent(short revents) { if (POLLHUP & revents) return false; assert(POLLIN & revents); char command; if (read(control_pipe_in_, &command, 1)) return false; switch (command) { case kCommandQuit: return false; default: assert(0); } return true; } bool CrashGenerationServer::MakeMinidumpFilename(string& outFilename) { GUID guid; char guidString[kGUIDStringLength+1]; if (!(CreateGUID(&guid) && GUIDToString(&guid, guidString, sizeof(guidString)))) return false; char path[PATH_MAX]; snprintf(path, sizeof(path), "%s/%s.dmp", dump_dir_.c_str(), guidString); outFilename = path; return true; } // static void* CrashGenerationServer::ThreadMain(void *arg) { reinterpret_cast<CrashGenerationServer*>(arg)->Run(); return NULL; } } // namespace google_breakpad
26.829341
80
0.694565
[ "vector" ]
1d86c3658a28a38d50c4d5cafad72a0a8afcde98
2,314
cpp
C++
Plugins/org.mitk.gui.qt.application/src/QmitkDataNodeGlobalReinitAction.cpp
zhaomengxiao/MITK
a09fd849a4328276806008bfa92487f83a9e2437
[ "BSD-3-Clause" ]
1
2022-03-03T12:03:32.000Z
2022-03-03T12:03:32.000Z
Plugins/org.mitk.gui.qt.application/src/QmitkDataNodeGlobalReinitAction.cpp
zhaomengxiao/MITK
a09fd849a4328276806008bfa92487f83a9e2437
[ "BSD-3-Clause" ]
1
2021-12-22T10:19:02.000Z
2021-12-22T10:19:02.000Z
Plugins/org.mitk.gui.qt.application/src/QmitkDataNodeGlobalReinitAction.cpp
zhaomengxiao/MITK_lancet
a09fd849a4328276806008bfa92487f83a9e2437
[ "BSD-3-Clause" ]
1
2020-11-27T09:41:18.000Z
2020-11-27T09:41:18.000Z
/*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include <QmitkDataNodeGlobalReinitAction.h> // mitk core #include <mitkRenderingManager.h> // mitk gui common plugin #include <mitkWorkbenchUtil.h> const QString QmitkDataNodeGlobalReinitAction::ACTION_ID = "org.mitk.gui.qt.application.globalreinitaction"; // namespace that contains the concrete action namespace GlobalReinitAction { void Run(berry::IWorkbenchPartSite::Pointer workbenchPartSite, mitk::DataStorage::Pointer dataStorage) { auto renderWindow = mitk::WorkbenchUtil::GetRenderWindowPart(workbenchPartSite->GetPage(), mitk::WorkbenchUtil::NONE); if (nullptr == renderWindow) { renderWindow = mitk::WorkbenchUtil::OpenRenderWindowPart(workbenchPartSite->GetPage(), false); if (nullptr == renderWindow) { // no render window available return; } } mitk::RenderingManager::GetInstance()->InitializeViewsByBoundingObjects(dataStorage); } } QmitkDataNodeGlobalReinitAction::QmitkDataNodeGlobalReinitAction(QWidget* parent, berry::IWorkbenchPartSite::Pointer workbenchPartSite) : QAction(parent) , QmitkAbstractDataNodeAction(workbenchPartSite) { setText(tr("Global Reinit")); InitializeAction(); } QmitkDataNodeGlobalReinitAction::QmitkDataNodeGlobalReinitAction(QWidget* parent, berry::IWorkbenchPartSite* workbenchPartSite) : QAction(parent) , QmitkAbstractDataNodeAction(berry::IWorkbenchPartSite::Pointer(workbenchPartSite)) { setText(tr("Global Reinit")); InitializeAction(); } void QmitkDataNodeGlobalReinitAction::InitializeAction() { connect(this, &QmitkDataNodeGlobalReinitAction::triggered, this, &QmitkDataNodeGlobalReinitAction::OnActionTriggered); } void QmitkDataNodeGlobalReinitAction::OnActionTriggered(bool /*checked*/) { if (m_WorkbenchPartSite.Expired()) { return; } if (m_DataStorage.IsExpired()) { return; } GlobalReinitAction::Run(m_WorkbenchPartSite.Lock(), m_DataStorage.Lock()); }
29.666667
135
0.715644
[ "render" ]
1d8805890a569641da61b845105df35e87af64a6
3,540
cpp
C++
packages/Search/test/tstDetailsUtils.cpp
flyingcat007/DTK_Test
ef8e0e791b76f138045354715a8ce23436ea0edf
[ "BSD-3-Clause" ]
null
null
null
packages/Search/test/tstDetailsUtils.cpp
flyingcat007/DTK_Test
ef8e0e791b76f138045354715a8ce23436ea0edf
[ "BSD-3-Clause" ]
null
null
null
packages/Search/test/tstDetailsUtils.cpp
flyingcat007/DTK_Test
ef8e0e791b76f138045354715a8ce23436ea0edf
[ "BSD-3-Clause" ]
null
null
null
/**************************************************************************** * Copyright (c) 2012-2017 by the DataTransferKit authors * * All rights reserved. * * * * This file is part of the DataTransferKit library. DataTransferKit is * * distributed under a BSD 3-clause license. For the licensing terms see * * the LICENSE file in the top-level directory. * ****************************************************************************/ #include <DTK_DetailsUtils.hpp> #include <Teuchos_UnitTestHarness.hpp> #include <algorithm> #include <vector> TEUCHOS_UNIT_TEST_TEMPLATE_1_DECL( DetailsUtils, fill, DeviceType ) { int const n = 10; Kokkos::View<float *, DeviceType> v( "v", n ); float const pi = 3.14; DataTransferKit::fill( v, pi ); auto v_host = Kokkos::create_mirror_view( v ); Kokkos::deep_copy( v_host, v ); TEST_COMPARE_ARRAYS( std::vector<float>( n, pi ), v_host ); } TEUCHOS_UNIT_TEST_TEMPLATE_1_DECL( DetailsUtils, prefix_sum, DeviceType ) { int const n = 10; Kokkos::View<int *, DeviceType> x( "x", n ); std::vector<int> x_ref( n, 1 ); x_ref.back() = 0; auto x_host = Kokkos::create_mirror_view( x ); for ( int i = 0; i < n; ++i ) x_host( i ) = x_ref[i]; Kokkos::deep_copy( x, x_host ); Kokkos::View<int *, DeviceType> y( "y", n ); DataTransferKit::exclusivePrefixSum( x, y ); std::vector<int> y_ref( n ); std::iota( y_ref.begin(), y_ref.end(), 0 ); auto y_host = Kokkos::create_mirror_view( y ); Kokkos::deep_copy( y_host, y ); Kokkos::deep_copy( x_host, x ); TEST_COMPARE_ARRAYS( y_host, y_ref ); TEST_COMPARE_ARRAYS( x_host, x_ref ); // in-place DataTransferKit::exclusivePrefixSum( x, x ); Kokkos::deep_copy( x_host, x ); TEST_COMPARE_ARRAYS( x_host, y_ref ); int const m = 11; TEST_INEQUALITY( n, m ); Kokkos::View<int *, DeviceType> z( "z", m ); TEST_THROW( DataTransferKit::exclusivePrefixSum( x, z ), DataTransferKit::DataTransferKitException ); } TEUCHOS_UNIT_TEST_TEMPLATE_1_DECL( DetailsUtils, last_element, DeviceType ) { Kokkos::View<int *, DeviceType> v( "v", 2 ); auto v_host = Kokkos::create_mirror_view( v ); v_host( 0 ) = 33; v_host( 1 ) = 24; Kokkos::deep_copy( v, v_host ); TEST_EQUALITY( DataTransferKit::lastElement( v ), 24 ); Kokkos::View<int *, DeviceType> w( "w", 0 ); TEST_THROW( DataTransferKit::lastElement( w ), DataTransferKit::DataTransferKitException ); } // Include the test macros. #include "DataTransferKitSearch_ETIHelperMacros.h" // Create the test group #define UNIT_TEST_GROUP( NODE ) \ using DeviceType##NODE = typename NODE::device_type; \ TEUCHOS_UNIT_TEST_TEMPLATE_1_INSTANT( DetailsUtils, fill, \ DeviceType##NODE ) \ TEUCHOS_UNIT_TEST_TEMPLATE_1_INSTANT( DetailsUtils, prefix_sum, \ DeviceType##NODE ) \ TEUCHOS_UNIT_TEST_TEMPLATE_1_INSTANT( DetailsUtils, last_element, \ DeviceType##NODE ) // Demangle the types DTK_ETI_MANGLING_TYPEDEFS() // Instantiate the tests DTK_INSTANTIATE_N( UNIT_TEST_GROUP )
39.775281
80
0.561864
[ "vector" ]
1d907f6c13ac23193b30bfd565d2003f26e83250
5,386
cpp
C++
ql/models/marketmodels/driftcomputation/cmsmmdriftcalculator.cpp
mshojatalab/QuantLib
7801a0fb3226bc1b001e310bacdd35ddb2e51661
[ "BSD-3-Clause" ]
76
2017-06-28T21:24:38.000Z
2021-12-19T18:07:37.000Z
ql/models/marketmodels/driftcomputation/cmsmmdriftcalculator.cpp
mshojatalab/QuantLib
7801a0fb3226bc1b001e310bacdd35ddb2e51661
[ "BSD-3-Clause" ]
3
2022-03-09T16:19:13.000Z
2022-03-29T07:33:42.000Z
ql/models/marketmodels/driftcomputation/cmsmmdriftcalculator.cpp
sweemer/QuantLib
1341223e3d839dd77bb7231d0913809f01437740
[ "BSD-3-Clause" ]
34
2017-07-02T14:49:21.000Z
2021-11-26T15:32:04.000Z
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* Copyright (C) 2007 Ferdinando Ametrano Copyright (C) 2007 François du Vignaud Copyright (C) 2007 Mark Joshi This file is part of QuantLib, a free-software/open-source library for financial quantitative analysts and developers - http://quantlib.org/ QuantLib is free software: you can redistribute it and/or modify it under the terms of the QuantLib license. You should have received a copy of the license along with this program; if not, please email <quantlib-dev@lists.sf.net>. The license is also available online at <http://quantlib.org/license.shtml>. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the license for more details. */ #include <ql/models/marketmodels/driftcomputation/cmsmmdriftcalculator.hpp> #include <ql/models/marketmodels/curvestates/cmswapcurvestate.hpp> namespace QuantLib { CMSMMDriftCalculator::CMSMMDriftCalculator( const Matrix& pseudo, const std::vector<Spread>& displacements, const std::vector<Time>& taus, Size numeraire, Size alive, Size spanningFwds) : numberOfRates_(taus.size()), numberOfFactors_(pseudo.columns()), numeraire_(numeraire), alive_(alive), displacements_(displacements), oneOverTaus_(taus.size()), pseudo_(pseudo), tmp_(taus.size(), 0.0), PjPnWk_(numberOfFactors_,1+taus.size()), wkaj_(numberOfFactors_, taus.size()), wkajN_(numberOfFactors_, taus.size()), downs_(taus.size()), ups_(taus.size()), spanningFwds_(spanningFwds) { // Check requirements QL_REQUIRE(numberOfRates_>0, "Dim out of range"); QL_REQUIRE(displacements.size() == numberOfRates_, "Displacements out of range"); QL_REQUIRE(pseudo.rows()==numberOfRates_, "pseudo.rows() not consistent with dim"); QL_REQUIRE(pseudo.columns()>0 && pseudo.columns()<=numberOfRates_, "pseudo.rows() not consistent with pseudo.columns()"); QL_REQUIRE(alive<numberOfRates_, "Alive out of bounds"); QL_REQUIRE(numeraire_<=numberOfRates_, "Numeraire larger than dim"); QL_REQUIRE(numeraire_>=alive, "Numeraire smaller than alive"); // Precompute 1/taus for (Size i=0; i<taus.size(); ++i) oneOverTaus_[i] = 1.0/taus[i]; // Compute covariance matrix from pseudoroot Matrix pT = transpose(pseudo_); C_ = pseudo_*pT; // Compute lower and upper extrema for (non reduced) drift calculation for (Size i=alive_; i<numberOfRates_; ++i) { downs_[i] = std::min(i+1, numeraire_); ups_[i] = std::max(i+1, numeraire_); } } void CMSMMDriftCalculator::compute(const CMSwapCurveState& cs, std::vector<Real>& drifts) const { #if defined(QL_EXTRA_SAFETY_CHECKS) QL_REQUIRE(drifts.size()==cs.numberOfRates(), "drifts.size() <> numberOfRates"); #endif const std::vector<Time>& taus = cs.rateTaus(); // final bond is numeraire // Compute cross variations for (Size k=0; k<PjPnWk_.rows(); ++k) { PjPnWk_[k][numberOfRates_]=0.0; wkaj_[k][numberOfRates_-1]=0.0; for (Integer j=static_cast<Integer>(numberOfRates_)-2; j>=static_cast<Integer>(alive_)-1; --j) { Real sr = cs.cmSwapRate(j+1,spanningFwds_); Integer endIndex = std::min<Integer>(j + static_cast<Integer>(spanningFwds_) + 1, static_cast<Integer>(numberOfRates_)); Real first = sr * wkaj_[k][j+1]; Real second = cs.cmSwapAnnuity(numberOfRates_,j+1,spanningFwds_) * (sr+displacements_[j+1]) *pseudo_[j+1][k]; Real third = PjPnWk_[k][endIndex]; PjPnWk_[k][j+1] = first + second + third; if (j>=static_cast<Integer>(alive_)) { wkaj_[k][j] = wkaj_[k][j+1] + PjPnWk_[k][j+1]*taus[j]; if (j+spanningFwds_+1 <= numberOfRates_) wkaj_[k][j] -= PjPnWk_[k][endIndex]*taus[endIndex-1]; } } } Real PnOverPN = cs.discountRatio(numberOfRates_, numeraire_); //Real PnOverPN = 1.0; for (Size j=alive_; j<numberOfRates_; ++j) for (Size k=0; k<numberOfFactors_; ++k) wkajN_[k][j] = wkaj_[k][j]*PnOverPN -PjPnWk_[k][numeraire_]*PnOverPN*cs.cmSwapAnnuity(numeraire_,j,spanningFwds_); for (Size j=alive_; j<numberOfRates_; ++j) { drifts[j]=0.0; for (Size k=0; k<numberOfFactors_; ++k) { drifts[j] += pseudo_[j][k]*wkajN_[k][j]; } drifts[j] /= -cs.cmSwapAnnuity(numeraire_,j,spanningFwds_); } } }
39.028986
98
0.569625
[ "vector" ]
1d9485d06512162c1e526d6cb96dea61a29e412f
13,890
cpp
C++
Sources/Elastos/LibCore/src/elastos/utility/CLocaleBuilder.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
7
2017-07-13T10:34:54.000Z
2021-04-16T05:40:35.000Z
Sources/Elastos/LibCore/src/elastos/utility/CLocaleBuilder.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
null
null
null
Sources/Elastos/LibCore/src/elastos/utility/CLocaleBuilder.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
9
2017-07-13T12:33:20.000Z
2021-06-19T02:46:48.000Z
//========================================================================= // Copyright (C) 2012 The Elastos Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //========================================================================= #include "CLocaleBuilder.h" #include "CTreeSet.h" #include "CTreeMap.h" #include "CLocale.h" #include "StringUtils.h" #include "CString.h" #include "CChar32.h" #include "CoreUtils.h" #include <cutils/log.h> using Elastos::Core::CString; using Elastos::Core::ICharSequence; using Elastos::Core::CoreUtils; using Elastos::Core::StringUtils; using Elastos::Core::IChar32; using Elastos::Core::CChar32; namespace Elastos { namespace Utility { CAR_INTERFACE_IMPL(CLocaleBuilder, Object, ILocaleBuilder) CAR_OBJECT_IMPL(CLocaleBuilder) CLocaleBuilder::CLocaleBuilder() : mLanguage("") , mRegion("") , mVariant("") , mScript("") { } ECode CLocaleBuilder::constructor() { // NOTE: We use sorted maps in the builder & the locale class itself // because serialized forms of the unicode locale extension (and // of the extension map itself) are specified to be in alphabetic // order of keys. CTreeSet::New((ISet**)&mAttributes); CTreeMap::New((IMap**)&mKeywords); CTreeMap::New((IMap**)&mExtensions); return NOERROR; } ECode CLocaleBuilder::SetLanguage( /* [in] */ const String& language) { return NormalizeAndValidateLanguage(language, TRUE /* strict */, &mLanguage); } ECode CLocaleBuilder::NormalizeAndValidateLanguage( /* [in] */ const String& language, /* [in] */ Boolean strict, /* [out] */ String* str) { VALIDATE_NOT_NULL(str); *str = String(""); if (language.IsNullOrEmpty()) { return NOERROR; } String lowercaseLanguage = language.ToLowerCase();//ToLowerCase(Locale.ROOT); if (!CLocale::IsValidBcp47Alpha(lowercaseLanguage, 2, 3)) { if (strict) { ALOGE("CLocaleBuilder::NormalizeAndValidateLanguage: error Invalid language: %s", language.string()); return E_ILLFORMED_LOCALE_EXCEPTION; } else { *str = CLocale::UNDETERMINED_LANGUAGE; return NOERROR; } } *str = lowercaseLanguage; return NOERROR; } ECode CLocaleBuilder::SetLanguageTag( /* [in] */ const String& languageTag) { if (languageTag.IsNullOrEmpty()) { Clear(); return NOERROR; } AutoPtr<ILocale> fromIcu; FAIL_RETURN(CLocale::ForLanguageTag(languageTag, true /* strict */, (ILocale**)&fromIcu)); // When we ask ICU for strict parsing, it might return a null locale // if the language tag is malformed. if (fromIcu == NULL) { ALOGE("CLocaleBuilder::SetLanguageTag: IllformedLocaleException, Invalid languageTag: %s", languageTag.string()); return E_ILLFORMED_LOCALE_EXCEPTION; } SetLocale(fromIcu); return NOERROR; } ECode CLocaleBuilder::SetRegion( /* [in] */ const String& region) { return NormalizeAndValidateRegion(region, TRUE /* strict */, &mRegion); } ECode CLocaleBuilder::NormalizeAndValidateRegion( /* [in] */ const String& region, /* [in] */ Boolean strict, /* [out] */ String* str) { VALIDATE_NOT_NULL(str) *str = String(""); if (region.IsNullOrEmpty()) { return NOERROR; } String uppercaseRegion = region.ToUpperCase(); // toUpperCase(Locale.ROOT); if (!CLocale::IsValidBcp47Alpha(uppercaseRegion, 2, 2) && !CLocale::IsUnM49AreaCode(uppercaseRegion)) { if (strict) { ALOGE("CLocaleBuilder::NormalizeAndValidateRegion: IllformedLocaleException, Invalid region: %s", region.string()); return E_ILLFORMED_LOCALE_EXCEPTION; } else { return NOERROR; } } *str = uppercaseRegion; return NOERROR; } ECode CLocaleBuilder::SetVariant( /* [in] */ const String& variant) { return NormalizeAndValidateVariant(variant, &mVariant); } ECode CLocaleBuilder::NormalizeAndValidateVariant( /* [in] */ const String& variant, /* [out] */ String* str) { VALIDATE_NOT_NULL(str) *str = String(""); if (variant.IsNullOrEmpty()) { return NOERROR; } // Note that unlike extensions, we canonicalize to lower case alphabets // and underscores instead of hyphens. String normalizedVariant = variant.Replace('-', '_'); AutoPtr<ArrayOf<String> > subTags; StringUtils::Split(normalizedVariant, String("_"), (ArrayOf<String>**)&subTags); for (Int32 i = 0; i < subTags->GetLength(); ++i) { if (!IsValidVariantSubtag((*subTags)[i])) { ALOGE("CLocaleBuilder::NormalizeAndValidateVariant: IllformedLocaleException, Invalid variant: %s", variant.string()); return E_ILLFORMED_LOCALE_EXCEPTION; } } *str = normalizedVariant; return NOERROR; } Boolean CLocaleBuilder::IsValidVariantSubtag( /* [in] */ const String& subTag) { // The BCP-47 spec states that : // - Subtags can be between [5, 8] alphanumeric chars in length. // - Subtags that start with a number are allowed to be 4 chars in length. if (subTag.GetLength() >= 5 && subTag.GetLength() <= 8) { if (CLocale::IsAsciiAlphaNum(subTag)) { return TRUE; } } else if (subTag.GetLength() == 4) { Char32 firstChar = subTag.GetChar(0); if ((firstChar >= '0' && firstChar <= '9') && CLocale::IsAsciiAlphaNum(subTag)) { return TRUE; } } return FALSE; } ECode CLocaleBuilder::SetScript( /* [in] */ const String& script) { return NormalizeAndValidateScript(script, TRUE /* strict */, &mScript); } ECode CLocaleBuilder::NormalizeAndValidateScript( /* [in] */ const String& script, /* [in] */ Boolean strict, /* [out] */ String* str) { VALIDATE_NOT_NULL(str) *str = String(""); if (script.IsNullOrEmpty()) { return NOERROR; } if (!CLocale::IsValidBcp47Alpha(script, 4, 4)) { if (strict) { ALOGE("CLocaleBuilder::NormalizeAndValidateScript: IllformedLocaleException, Invalid script: %s", script.string()); return E_ILLFORMED_LOCALE_EXCEPTION; } else { return NOERROR; } } return CLocale::TitleCaseAsciiWord(script, str); } ECode CLocaleBuilder::SetLocale( /* [in] */ ILocale* locale) { if (locale == NULL) { ALOGE("CLocaleBuilder::SetLocale, NullPointerExceptionm, locale == null"); return E_NULL_POINTER_EXCEPTION; } CLocale* l = (CLocale*)locale; // Make copies of the existing values so that we don't partially // update the state if we encounter an error. String backupLanguage = mLanguage; String backupRegion = mRegion; String backupVariant = mVariant; String language, country, variant; locale->GetLanguage(&language); locale->GetCountry(&country); locale->GetVariant(&variant); ECode ec = SetLanguage(language); FAIL_GOTO(ec, _FAIL_) ec = SetRegion(country); FAIL_GOTO(ec, _FAIL_) ec = SetVariant(variant); FAIL_GOTO(ec, _FAIL_) // The following values can be set only via the builder class, so // there's no need to normalize them or check their validity. locale->GetScript(&mScript); mExtensions->Clear(); mExtensions->PutAll(IMap::Probe(l->mExtensions)); mKeywords->Clear(); mKeywords->PutAll(IMap::Probe(l->mUnicodeKeywords)); mAttributes->Clear(); mAttributes->AddAll(ICollection::Probe(l->mUnicodeAttributes)); return NOERROR; _FAIL_: mLanguage = backupLanguage; mRegion = backupRegion; mVariant = backupVariant; return ec; } ECode CLocaleBuilder::AddUnicodeLocaleAttribute( /* [in] */ const String& attribute) { if (attribute.IsNull()) { return E_NULL_POINTER_EXCEPTION; } String lowercaseAttribute = attribute.ToLowerCase();//toLowerCase(Locale.ROOT); if (!CLocale::IsValidBcp47Alphanum(lowercaseAttribute, 3, 8)) { ALOGE("CLocaleBuilder::AddUnicodeLocaleAttribute: IllformedLocaleException, Invalid attribute: %s", attribute.string()); return E_ILLFORMED_LOCALE_EXCEPTION; } AutoPtr<ICharSequence> csq; CString::New(lowercaseAttribute, (ICharSequence**)&csq); return mAttributes->Add(csq->Probe(EIID_IInterface)); } ECode CLocaleBuilder::RemoveUnicodeLocaleAttribute( /* [in] */ const String& attribute) { if (attribute.IsNull()) { return E_NULL_POINTER_EXCEPTION; } // Weirdly, remove is specified to check whether the attribute // is valid, so we have to perform the full alphanumeric check here. String lowercaseAttribute = attribute.ToLowerCase();//toLowerCase(Locale.ROOT); if (!CLocale::IsValidBcp47Alphanum(lowercaseAttribute, 3, 8)) { ALOGE("CLocaleBuilder::RemoveUnicodeLocaleAttribute: IllformedLocaleException, Invalid attribute: %s", attribute.string()); return E_ILLFORMED_LOCALE_EXCEPTION; } AutoPtr<ICharSequence> csq; CString::New(lowercaseAttribute, (ICharSequence**)&csq); return mAttributes->Remove(csq->Probe(EIID_IInterface)); } ECode CLocaleBuilder::SetExtension( /* [in] */ Char32 key, /* [in] */ const String& value) { AutoPtr<IChar32> keyObj; CChar32::New(key, (IChar32**)&keyObj); if (value.IsNullOrEmpty()) { mExtensions->Remove(keyObj->Probe(EIID_IInterface)); return NOERROR; } String normalizedValue = value.ToLowerCase();//ToLowerCase(Locale.ROOT) normalizedValue = normalizedValue.Replace('_', '-'); AutoPtr<ArrayOf<String> > subtags; StringUtils::Split(normalizedValue, String("-"), (ArrayOf<String>**)&subtags); // Lengths for subtags in the private use extension should be [1, 8] chars. // For all other extensions, they should be [2, 8] chars. // // http://www.rfc-editor.org/rfc/bcp/bcp47.txt Int32 minimumLength = (key == ILocale::PRIVATE_USE_EXTENSION) ? 1 : 2; for (Int32 i = 0; i < subtags->GetLength(); ++i) { String subtag = (*subtags)[i]; if (!CLocale::IsValidBcp47Alphanum(subtag, minimumLength, 8)) { ALOGE("CLocaleBuilder::SetExtension: IllformedLocaleException, Invalid private use extension : %s", value.string()); return E_ILLFORMED_LOCALE_EXCEPTION; } } // We need to take special action in the case of unicode extensions, // since we claim to understand their keywords and mAttributes-> if (key == ILocale::UNICODE_LOCALE_EXTENSION) { // First clear existing attributes and mKeywords-> mExtensions->Clear(); mAttributes->Clear(); CLocale::ParseUnicodeExtension(subtags, mKeywords, mAttributes); } else { AutoPtr<ICharSequence> csq; CString::New(normalizedValue, (ICharSequence**)&csq); mExtensions->Put(keyObj, TO_IINTERFACE(csq)); } return NOERROR; } ECode CLocaleBuilder::ClearExtensions() { mExtensions->Clear(); mAttributes->Clear(); mKeywords->Clear(); return NOERROR; } ECode CLocaleBuilder::SetUnicodeLocaleKeyword( /* [in] */ const String& key, /* [in] */ const String& type) { if (key.IsNull()) { return E_NULL_POINTER_EXCEPTION; } if (type.IsNull() && mKeywords != NULL) { AutoPtr<ICharSequence> csq; CString::New(key, (ICharSequence**)&csq); mKeywords->Remove(TO_IINTERFACE(csq)); return NOERROR; } String lowerCaseKey = key.ToLowerCase();//ToLowerCase(Locale.ROOT) // The key must be exactly two alphanumeric characters. if (lowerCaseKey.GetLength() != 2 || !CLocale::IsAsciiAlphaNum(lowerCaseKey)) { ALOGE("CLocaleBuilder::SetExtension: IllformedLocaleException, Invalid unicode locale keyword : %s", key.string()); return E_ILLFORMED_LOCALE_EXCEPTION; } // The type can be one or more alphanumeric strings of length [3, 8] characters, // separated by a separator char, which is one of "_" or "-". Though the spec // doesn't require it, we normalize all "_" to "-" to make the rest of our // processing easier. String lowerCaseType = type.ToLowerCase();//ToLowerCase(Locale.ROOT) lowerCaseType = lowerCaseType.Replace('_', '-'); if (!CLocale::IsValidTypeList(lowerCaseType)) { ALOGE("CLocaleBuilder::SetExtension: IllformedLocaleException, Invalid unicode locale type : %s", type.string()); return E_ILLFORMED_LOCALE_EXCEPTION; } // Everything checks out fine, add the <key, type> mapping to the list. AutoPtr<ICharSequence> keycsq = CoreUtils::Convert(lowerCaseKey); AutoPtr<ICharSequence> typecsq = CoreUtils::Convert(lowerCaseType); mKeywords->Put(TO_IINTERFACE(keycsq), TO_IINTERFACE(typecsq)); return NOERROR; } ECode CLocaleBuilder::Clear() { ClearExtensions(); mLanguage = mRegion = mVariant = mScript = String(""); return NOERROR; } ECode CLocaleBuilder::Build( /* [out] */ ILocale** result) { VALIDATE_NOT_NULL(result) *result = NULL; // NOTE: We need to make a copy of attributes, keywords and extensions // because the RI allows this builder to reused. return CLocale::New(mLanguage, mRegion, mVariant, mScript, mAttributes, mKeywords, mExtensions, TRUE /* has validated fields */, result); } } // namespace Utility } // namespace Elastos
31.712329
131
0.658315
[ "object" ]
1d94d0f2d781ef6878fede4282cc8db8297b98ec
16,879
cc
C++
dali/kernels/imgproc/convolution/laplacian_cpu_test.cc
L-Net-1992/DALI
982224d8b53e1156ae092f73f5a7d600982a1eb9
[ "ECL-2.0", "Apache-2.0" ]
2
2022-02-17T19:54:05.000Z
2022-02-17T19:54:08.000Z
dali/kernels/imgproc/convolution/laplacian_cpu_test.cc
L-Net-1992/DALI
982224d8b53e1156ae092f73f5a7d600982a1eb9
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
dali/kernels/imgproc/convolution/laplacian_cpu_test.cc
L-Net-1992/DALI
982224d8b53e1156ae092f73f5a7d600982a1eb9
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
// Copyright (c) 2021-2022, NVIDIA CORPORATION & AFFILIATES. 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 <gtest/gtest.h> #include <array> #include "dali/kernels/common/utils.h" #include "dali/kernels/imgproc/convolution/laplacian_cpu.h" #include "dali/kernels/imgproc/convolution/laplacian_test.h" #include "dali/kernels/scratch.h" #include "dali/test/tensor_test_utils.h" #include "dali/test/test_tensors.h" namespace dali { namespace kernels { template <typename Out, int axes> inline std::enable_if_t<std::is_integral<Out>::value> CompareOut( TensorView<StorageCPU, Out, axes>& out, TensorView<StorageCPU, Out, axes>& baseline) { Check(out, baseline); } template <typename Out, int axes> inline std::enable_if_t<!std::is_integral<Out>::value> CompareOut( TensorView<StorageCPU, Out, axes>& out, TensorView<StorageCPU, Out, axes>& baseline) { Check(out, baseline, EqualEpsRel(1e-6, 1e-5)); } void FillSobelWindow(span<float> window, int d_order) { int window_size = window.size(); window[0] = 1.; for (int i = 1; i < window_size - d_order; i++) { auto prevval = window[0]; for (int j = 1; j < i; j++) { auto val = window[j]; window[j] = prevval + window[j]; prevval = val; } window[i] = prevval; } for (int i = window_size - d_order; i < window_size; i++) { auto prevval = window[0]; window[0] = -prevval; for (int j = 1; j < i; j++) { auto val = window[j]; window[j] = prevval - window[j]; prevval = val; } window[i] = prevval; } } template <int axes, int window_size> void FillKernel(const TensorView<StorageCPU, float, axes>& kernel, const std::array<std::array<std::array<float, window_size>, axes>, axes>& windows, int padding) { for (int d = 0; d < axes; d++) { for (int i = 0; i < volume(kernel.shape); i++) { int offset = i; float r = 1.f; for (int j = axes - 1; j >= 0; j--) { int ind = offset % (window_size + padding); ind -= padding / 2; r *= (ind < 0 || ind >= window_size) ? 0.f : windows[d][j][ind]; offset /= (window_size + padding); } kernel.data[i] += r; } } } template <int axes_, int window_size_, bool use_smoothing_> struct LaplacianWindows { static constexpr int axes = axes_; static constexpr int window_size = window_size_; static constexpr bool use_smoothing = use_smoothing_; LaplacianWindows() { for (int i = 0; i < axes; i++) { for (int j = 0; j < axes; j++) { if (i == j) { window_sizes[i][j] = window_size; FillSobelWindow(make_span(windows[i][j]), 2); tensor_windows[i][j] = {windows[i][j].data(), window_size}; } else if (use_smoothing) { window_sizes[i][j] = window_size; FillSobelWindow(make_span(windows[i][j]), 0); tensor_windows[i][j] = {windows[i][j].data(), window_size}; } else { window_sizes[i][j] = 1; windows[i][j] = uniform_array<window_size>(0.f); auto middle = window_size / 2; windows[i][j][middle] = 1.f; tensor_windows[i][j] = {windows[i][j].data() + middle, 1}; } } } } std::array<std::array<int, axes>, axes> window_sizes; std::array<std::array<std::array<float, window_size>, axes>, axes> windows; std::array<std::array<TensorView<StorageCPU, const float, 1>, axes>, axes> tensor_windows; }; /** * @brief ``ndim`` laplacian is sum of ``ndim`` separable convolutions, each consiting of ``ndim`` * one dimensional convolutions. It is equivalent to computing ``ndim`` convolution with a kernel * being the sum of ``ndim`` outer products of ``ndim`` 1 dimensional kernels. This test suite * computes that kernel and checks if it matches the laplacian computed on the tensor consising * of a single 1 surrounded with zeros. */ template <typename T> struct LaplacianCpuKernelTest : public ::testing::Test { static constexpr int axes = T::axes; static constexpr int window_size = T::window_size; using Kernel = LaplacianCpu<float, float, float, axes, false>; void SetUp() override { int padding = 2; // add padding zeros so that border101 has no effect auto dims = uniform_array<axes>(window_size + padding); TensorListShape<axes> kernel_shape = uniform_list_shape<axes>(3, dims); tensor_list_.reshape(kernel_shape); kernel_ = tensor_list_.cpu()[0]; in_ = tensor_list_.cpu()[1]; out_ = tensor_list_.cpu()[2]; ConstantFill(kernel_, 0); FillKernel<axes, window_size>(kernel_, lapl_params_.windows, padding); ConstantFill(in_, 0); in_.data[volume(in_.shape) / 2] = 1.f; } void RunTest() { Kernel kernel; KernelContext ctx = {}; auto req = kernel.Setup(ctx, in_.shape, lapl_params_.window_sizes); ScratchpadAllocator scratch_alloc; scratch_alloc.Reserve(req.scratch_sizes); auto scratchpad = scratch_alloc.GetScratchpad(); ctx.scratchpad = &scratchpad; kernel.Run(ctx, out_, in_, lapl_params_.tensor_windows, uniform_array<axes>(1.f)); CompareOut(out_, kernel_); } T lapl_params_; TestTensorList<float, axes> tensor_list_; TensorView<StorageCPU, float, axes> kernel_; TensorView<StorageCPU, float, axes> in_; TensorView<StorageCPU, float, axes> out_; }; TYPED_TEST_SUITE_P(LaplacianCpuKernelTest); using LaplacianKernelTestValues = ::testing::Types< LaplacianWindows<1, 3, false>, LaplacianWindows<1, 5, false>, LaplacianWindows<1, 7, false>, LaplacianWindows<1, 9, false>, LaplacianWindows<1, 11, false>, LaplacianWindows<1, 13, false>, LaplacianWindows<1, 15, false>, LaplacianWindows<1, 17, false>, LaplacianWindows<1, 19, false>, LaplacianWindows<1, 23, false>, LaplacianWindows<2, 3, true>, LaplacianWindows<2, 5, true>, LaplacianWindows<2, 7, true>, LaplacianWindows<2, 9, true>, LaplacianWindows<2, 11, true>, LaplacianWindows<2, 13, true>, LaplacianWindows<2, 15, true>, LaplacianWindows<2, 17, true>, LaplacianWindows<2, 19, true>, LaplacianWindows<2, 23, true>, LaplacianWindows<2, 3, false>, LaplacianWindows<2, 5, false>, LaplacianWindows<2, 7, false>, LaplacianWindows<2, 9, false>, LaplacianWindows<2, 11, false>, LaplacianWindows<2, 13, false>, LaplacianWindows<2, 15, false>, LaplacianWindows<2, 17, false>, LaplacianWindows<2, 19, false>, LaplacianWindows<2, 23, false>, LaplacianWindows<3, 3, true>, LaplacianWindows<3, 5, true>, LaplacianWindows<3, 7, true>, LaplacianWindows<3, 9, true>, LaplacianWindows<3, 11, true>, LaplacianWindows<3, 13, true>, LaplacianWindows<3, 15, true>, LaplacianWindows<3, 17, true>, LaplacianWindows<3, 19, true>, LaplacianWindows<3, 23, true>, LaplacianWindows<3, 3, false>, LaplacianWindows<3, 5, false>, LaplacianWindows<3, 7, false>, LaplacianWindows<3, 9, false>, LaplacianWindows<3, 11, false>, LaplacianWindows<3, 13, false>, LaplacianWindows<3, 15, false>, LaplacianWindows<3, 17, false>, LaplacianWindows<3, 19, false>, LaplacianWindows<3, 23, false>>; TYPED_TEST_P(LaplacianCpuKernelTest, ExtractKernel) { this->RunTest(); } REGISTER_TYPED_TEST_SUITE_P(LaplacianCpuKernelTest, ExtractKernel); INSTANTIATE_TYPED_TEST_SUITE_P(LaplacianCpuKernel, LaplacianCpuKernelTest, LaplacianKernelTestValues); template <typename Out_, typename In_, int axes_, int window_size_, bool has_channels_, bool use_smoothing_> struct test_laplacian { static constexpr int axes = axes_; static constexpr bool has_channels = has_channels_; static constexpr int ndim = has_channels ? axes + 1 : axes; static constexpr int window_size = window_size_; static constexpr bool use_smoothing = use_smoothing_; using Out = Out_; using In = In_; }; /** * @brief Computes laplacian and compares it against simple baseline implementation * that accumulates all the separable convolutions in a separate buffer. */ template <typename T> struct LaplacianCpuTest : public ::testing::Test { static constexpr int axes = T::axes; static constexpr bool has_channels = T::has_channels; static constexpr int ndim = T::ndim; static constexpr int window_size = T::window_size; static constexpr bool use_smoothing = T::use_smoothing; static constexpr std::array<int, 3> dim_sizes = {41, 19, 37}; static constexpr std::array<float, 3> axe_weights = {0.5f, 0.25f, 1.f}; using Out = typename T::Out; using In = typename T::In; using W = float; using Kernel = LaplacianCpu<Out, In, W, axes, has_channels>; using Conv = SeparableConvolutionCpu<W, In, W, axes, has_channels>; static std::array<int, ndim> GetShape() { static_assert(ndim == axes + has_channels); std::array<int, ndim> shape; for (int i = 0; i < axes; i++) { shape[i] = dim_sizes[i]; } if (has_channels) { shape[ndim - 1] = 3; } return shape; } static std::array<float, axes> GetWeights() { std::array<float, axes> weights; for (int i = 0; i < axes; i++) { weights[i] = axe_weights[i]; } return weights; } LaplacianCpuTest() : shape_{GetShape()}, weights_{GetWeights()} {} void RunBaseline() { Conv kernel; KernelContext ctx = {}; auto vol = volume(shape_); for (int axis = 0; axis < axes; axis++) { auto req = kernel.Setup(ctx, shape_, lapl_params_.window_sizes[axis]); ScratchpadAllocator scratch_alloc; scratch_alloc.Reserve(req.scratch_sizes); auto scratchpad = scratch_alloc.GetScratchpad(); ctx.scratchpad = &scratchpad; kernel.Run(ctx, intermediate_, in_, lapl_params_.tensor_windows[axis]); for (int i = 0; i < vol; i++) { baseline_acc_.data[i] += weights_[axis] * intermediate_.data[i]; } } for (int i = 0; i < vol; i++) { baseline_out_.data[i] = ConvertSat<Out>(baseline_acc_.data[i]); } } void SetUp() override { TensorListShape<ndim> in_data_shape = uniform_list_shape<ndim>(1, shape_); TensorListShape<ndim> out_data_shape = uniform_list_shape<ndim>(2, shape_); in_list_.reshape(in_data_shape); in_ = in_list_.cpu()[0]; std::mt19937 rng; UniformRandomFill(in_, rng, 0, 255); out_list_.reshape(out_data_shape); out_ = out_list_.cpu()[0]; ConstantFill(out_, -1); baseline_out_ = out_list_.cpu()[1]; acc_list_.reshape(out_data_shape); intermediate_ = acc_list_.cpu()[0]; baseline_acc_ = acc_list_.cpu()[1]; ConstantFill(baseline_acc_, 0); } void RunTest() { Kernel kernel; KernelContext ctx = {}; auto req = kernel.Setup(ctx, in_.shape, lapl_params_.window_sizes); ScratchpadAllocator scratch_alloc; scratch_alloc.Reserve(req.scratch_sizes); auto scratchpad = scratch_alloc.GetScratchpad(); ctx.scratchpad = &scratchpad; kernel.Run(ctx, out_, in_, lapl_params_.tensor_windows, weights_); RunBaseline(); CompareOut(out_, baseline_out_); } std::array<int, ndim> shape_; std::array<float, axes> weights_; LaplacianWindows<axes, window_size, use_smoothing> lapl_params_; TestTensorList<In, ndim> in_list_; TestTensorList<Out, ndim> out_list_; TestTensorList<float, ndim> acc_list_; TensorView<StorageCPU, In, ndim> in_; TensorView<StorageCPU, Out, ndim> out_; TensorView<StorageCPU, Out, ndim> baseline_out_; TensorView<StorageCPU, float, ndim> intermediate_; TensorView<StorageCPU, float, ndim> baseline_acc_; }; TYPED_TEST_SUITE_P(LaplacianCpuTest); using LaplacianTestValues = ::testing::Types< test_laplacian<float, float, 1, 3, true, false>, test_laplacian<float, float, 1, 7, true, false>, test_laplacian<float, float, 1, 11, true, false>, test_laplacian<float, float, 1, 23, true, false>, test_laplacian<uint8_t, uint8_t, 1, 3, true, false>, test_laplacian<uint8_t, uint8_t, 1, 7, true, false>, test_laplacian<uint8_t, uint8_t, 1, 11, true, false>, test_laplacian<uint8_t, uint8_t, 1, 23, true, false>, test_laplacian<float, float, 1, 3, false, false>, test_laplacian<float, float, 1, 7, false, false>, test_laplacian<float, float, 1, 11, false, false>, test_laplacian<float, float, 1, 23, false, false>, test_laplacian<uint8_t, uint8_t, 1, 3, false, false>, test_laplacian<uint8_t, uint8_t, 1, 7, false, false>, test_laplacian<uint8_t, uint8_t, 1, 11, false, false>, test_laplacian<uint8_t, uint8_t, 1, 23, false, false>, test_laplacian<float, float, 2, 3, true, true>, test_laplacian<float, float, 2, 5, true, true>, test_laplacian<float, float, 2, 19, true, true>, test_laplacian<float, float, 2, 23, true, true>, test_laplacian<uint8_t, uint8_t, 2, 3, true, true>, test_laplacian<uint8_t, uint8_t, 2, 5, true, true>, test_laplacian<uint8_t, uint8_t, 2, 7, true, true>, test_laplacian<uint8_t, uint8_t, 2, 23, true, true>, test_laplacian<float, float, 2, 3, true, false>, test_laplacian<float, float, 2, 7, true, false>, test_laplacian<float, float, 2, 11, true, false>, test_laplacian<float, float, 2, 23, true, false>, test_laplacian<uint8_t, uint8_t, 2, 3, true, false>, test_laplacian<uint8_t, uint8_t, 2, 7, true, false>, test_laplacian<uint8_t, uint8_t, 2, 11, true, false>, test_laplacian<uint8_t, uint8_t, 2, 23, true, false>, test_laplacian<float, float, 2, 3, false, true>, test_laplacian<float, float, 2, 5, false, true>, test_laplacian<float, float, 2, 19, false, true>, test_laplacian<float, float, 2, 23, false, true>, test_laplacian<uint8_t, uint8_t, 2, 3, false, true>, test_laplacian<uint8_t, uint8_t, 2, 5, false, true>, test_laplacian<uint8_t, uint8_t, 2, 7, false, true>, test_laplacian<uint8_t, uint8_t, 2, 23, false, true>, test_laplacian<float, float, 2, 3, false, false>, test_laplacian<float, float, 2, 7, false, false>, test_laplacian<float, float, 2, 11, false, false>, test_laplacian<float, float, 2, 23, false, false>, test_laplacian<uint8_t, uint8_t, 2, 3, false, false>, test_laplacian<uint8_t, uint8_t, 2, 7, false, false>, test_laplacian<uint8_t, uint8_t, 2, 11, false, false>, test_laplacian<uint8_t, uint8_t, 2, 23, false, false>, test_laplacian<float, float, 3, 3, true, true>, test_laplacian<float, float, 3, 5, true, true>, test_laplacian<float, float, 3, 19, true, true>, test_laplacian<float, float, 3, 23, true, true>, test_laplacian<uint8_t, uint8_t, 3, 3, true, true>, test_laplacian<uint8_t, uint8_t, 3, 5, true, true>, test_laplacian<uint8_t, uint8_t, 3, 7, true, true>, test_laplacian<uint8_t, uint8_t, 3, 23, true, true>, test_laplacian<float, float, 3, 3, true, false>, test_laplacian<float, float, 3, 7, true, false>, test_laplacian<float, float, 3, 11, true, false>, test_laplacian<float, float, 3, 23, true, false>, test_laplacian<uint8_t, uint8_t, 3, 3, true, false>, test_laplacian<uint8_t, uint8_t, 3, 7, true, false>, test_laplacian<uint8_t, uint8_t, 3, 11, true, false>, test_laplacian<uint8_t, uint8_t, 3, 23, true, false>, test_laplacian<float, float, 3, 3, false, true>, test_laplacian<float, float, 3, 5, false, true>, test_laplacian<float, float, 3, 19, false, true>, test_laplacian<float, float, 3, 23, false, true>, test_laplacian<uint8_t, uint8_t, 3, 3, false, true>, test_laplacian<uint8_t, uint8_t, 3, 5, false, true>, test_laplacian<uint8_t, uint8_t, 3, 7, false, true>, test_laplacian<uint8_t, uint8_t, 3, 23, false, true>, test_laplacian<float, float, 3, 3, false, false>, test_laplacian<float, float, 3, 7, false, false>, test_laplacian<float, float, 3, 11, false, false>, test_laplacian<float, float, 3, 23, false, false>, test_laplacian<uint8_t, uint8_t, 3, 3, false, false>, test_laplacian<uint8_t, uint8_t, 3, 7, false, false>, test_laplacian<uint8_t, uint8_t, 3, 11, false, false>, test_laplacian<uint8_t, uint8_t, 3, 23, false, false>>; TYPED_TEST_P(LaplacianCpuTest, DoLaplacian) { this->RunTest(); } REGISTER_TYPED_TEST_SUITE_P(LaplacianCpuTest, DoLaplacian); INSTANTIATE_TYPED_TEST_SUITE_P(LaplacianCpuKernel, LaplacianCpuTest, LaplacianTestValues); } // namespace kernels } // namespace dali
38.10158
98
0.674448
[ "shape" ]
1d965a9626a43dc1a937681df829204988b0522c
34,480
cpp
C++
tel_ril/src/tel_ril_sim.cpp
chaoyangcui/telephony_core_service
00cfcad14279d165bcd8f26d3078462caffc39a6
[ "Apache-2.0" ]
null
null
null
tel_ril/src/tel_ril_sim.cpp
chaoyangcui/telephony_core_service
00cfcad14279d165bcd8f26d3078462caffc39a6
[ "Apache-2.0" ]
null
null
null
tel_ril/src/tel_ril_sim.cpp
chaoyangcui/telephony_core_service
00cfcad14279d165bcd8f26d3078462caffc39a6
[ "Apache-2.0" ]
1
2021-09-13T12:07:12.000Z
2021-09-13T12:07:12.000Z
/* * Copyright (C) 2021 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "tel_ril_sim.h" #include "sim_data_type.h" namespace OHOS { namespace Telephony { void TelRilSim::AddHandlerToMap() { // Notification memberFuncMap_[HNOTI_SIM_STATUS_CHANGED] = &TelRilSim::SimStateUpdated; // response memberFuncMap_[HREQ_SIM_IO] = &TelRilSim::RequestSimIOResponse; memberFuncMap_[HREQ_SIM_GET_SIM_STATUS] = &TelRilSim::GetSimStatusResponse; memberFuncMap_[HREQ_SIM_GET_IMSI] = &TelRilSim::GetImsiResponse; memberFuncMap_[HREQ_SIM_GET_ICCID] = &TelRilSim::GetIccIDResponse; memberFuncMap_[HREQ_SIM_GET_LOCK_STATUS] = &TelRilSim::GetSimLockStatusResponse; memberFuncMap_[HREQ_SIM_SET_LOCK] = &TelRilSim::SetSimLockResponse; memberFuncMap_[HREQ_SIM_CHANGE_PASSWD] = &TelRilSim::ChangeSimPasswordResponse; memberFuncMap_[HREQ_SIM_ENTER_PIN] = &TelRilSim::EnterSimPinResponse; memberFuncMap_[HREQ_SIM_UNLOCK_PIN] = &TelRilSim::UnlockSimPinResponse; memberFuncMap_[HREQ_SIM_GET_PIN_INPUT_TIMES] = &TelRilSim::GetSimPinInputTimesResponse; } TelRilSim::TelRilSim(sptr<IRemoteObject> cellularRadio, std::shared_ptr<ObserverHandler> observerHandler) : TelRilBase(cellularRadio, observerHandler) { AddHandlerToMap(); } bool TelRilSim::IsSimResponse(uint32_t code) { return ((code >= HREQ_SIM_BASE) && (code < HREQ_DATA_BASE)); } bool TelRilSim::IsSimNotification(uint32_t code) { return ((code >= HNOTI_SIM_BASE) && (code < HNOTI_DATA_BASE)); } bool TelRilSim::IsSimRespOrNotify(uint32_t code) { return IsSimResponse(code) || IsSimNotification(code); } void TelRilSim::ProcessSimRespOrNotify(uint32_t code, MessageParcel &data) { TELEPHONY_LOGD( "TelRilSim ProcessSimRespOrNotify code:%{public}d, GetDataSize:%{public}zu", code, data.GetDataSize()); auto itFunc = memberFuncMap_.find(code); if (itFunc != memberFuncMap_.end()) { auto memberFunc = itFunc->second; if (memberFunc != nullptr) { (this->*memberFunc)(data); } } } void TelRilSim::SimStateUpdated(MessageParcel &data) { TELEPHONY_LOGD("TelRilSim SimStateUpdated"); if (observerHandler_ == nullptr) { TELEPHONY_LOGE("TelRilSim observerHandler_ is null!!"); return; } observerHandler_->NotifyObserver(ObserverHandler::RADIO_SIM_STATE_CHANGE); } // response void TelRilSim::RequestSimIOResponse(MessageParcel &data) { TELEPHONY_LOGD("TelRilSim::RequestSimIOResponse --> "); std::shared_ptr<IccIoResultInfo> iccIoResult = std::make_shared<IccIoResultInfo>(); if (iccIoResult == nullptr) { TELEPHONY_LOGE("ERROR : RequestSimIOResponse --> iccIoResult == nullptr !!!"); return; } iccIoResult->ReadFromParcel(data); const size_t readSpSize = sizeof(struct HRilRadioResponseInfo); const uint8_t *spBuffer = data.ReadUnpadBuffer(readSpSize); if (spBuffer == nullptr) { TELEPHONY_LOGE("ERROR : RequestSimIOResponse --> read spBuffer(HRilRadioResponseInfo) failed !!!"); return; } const struct HRilRadioResponseInfo *radioResponseInfo = reinterpret_cast<const struct HRilRadioResponseInfo *>(spBuffer); if (radioResponseInfo == nullptr) { TELEPHONY_LOGE("ERROR : RequestSimIOResponse --> radioResponseInfo == nullptr !!!"); return; } TELEPHONY_LOGD( "RequestSimIOResponse --> radioResponseInfo->serial:%{public}d," " radioResponseInfo->error:%{public}d", radioResponseInfo->serial, radioResponseInfo->error); std::shared_ptr<TelRilRequest> telRilRequest = FindTelRilRequest(*radioResponseInfo); if (telRilRequest != nullptr && telRilRequest->pointer_ != nullptr) { if (radioResponseInfo->error == HRilErrType::NONE) { ProcessIccIoInfo(telRilRequest, iccIoResult); } else { ErrorIccIoResponse(telRilRequest, *radioResponseInfo); } } else { TELEPHONY_LOGE( "ERROR : RequestSimIOResponse --> telRilRequest == nullptr || radioResponseInfo error !!!"); } } void TelRilSim::ErrorIccIoResponse( std::shared_ptr<TelRilRequest> telRilRequest, const HRilRadioResponseInfo &responseInfo) { TELEPHONY_LOGD("======>enter"); std::shared_ptr<HRilRadioResponseInfo> respInfo = std::make_shared<HRilRadioResponseInfo>(); if (respInfo == nullptr) { TELEPHONY_LOGE("ERROR : ErrorIccIoResponse == nullptr failed !!!"); return; } if (telRilRequest != nullptr && telRilRequest->pointer_ != nullptr) { const std::shared_ptr<OHOS::AppExecFwk::EventHandler> &handler = telRilRequest->pointer_->GetOwner(); if (handler == nullptr) { TELEPHONY_LOGE("ERROR : ErrorIccIoResponse --> handler == nullptr !!!"); return; } respInfo->serial = responseInfo.serial; respInfo->error = responseInfo.error; respInfo->flag = telRilRequest->pointer_->GetParam(); uint32_t eventId = telRilRequest->pointer_->GetInnerEventId(); std::unique_ptr<Telephony::IccToRilMsg> toMsg = telRilRequest->pointer_->GetUniqueObject<Telephony::IccToRilMsg>(); std::shared_ptr<Telephony::IccFromRilMsg> object = std::make_shared<Telephony::IccFromRilMsg>(toMsg->controlHolder); object->controlHolder = toMsg->controlHolder; object->fileData.exception = static_cast<std::shared_ptr<void>>(respInfo); handler->SendEvent(eventId, object); } else { TELEPHONY_LOGE("ERROR : telRilRequest or telRilRequest->pointer_ == nullptr !!!"); return; } } void TelRilSim::ProcessIccIoInfo( std::shared_ptr<TelRilRequest> telRilRequest, std::shared_ptr<IccIoResultInfo> iccIoResult) { if (telRilRequest == nullptr) { TELEPHONY_LOGE("ERROR : ProcessIccIoInfo --> telRilRequest == nullptr !!!"); return; } const std::shared_ptr<OHOS::AppExecFwk::EventHandler> &handler = telRilRequest->pointer_->GetOwner(); if (handler == nullptr) { TELEPHONY_LOGE("ERROR : ProcessIccIoInfo --> handler == nullptr !!!"); return; } uint32_t eventId = telRilRequest->pointer_->GetInnerEventId(); std::unique_ptr<Telephony::IccToRilMsg> toMsg = telRilRequest->pointer_->GetUniqueObject<Telephony::IccToRilMsg>(); if (toMsg == nullptr) { TELEPHONY_LOGE("ERROR : ProcessIccIoInfo --> GetUniqueObject<IccToRilMsg>() failed !!!"); return; } std::unique_ptr<Telephony::IccFromRilMsg> object = std::make_unique<Telephony::IccFromRilMsg>(toMsg->controlHolder); object->fileData.resultData = iccIoResult->response; object->fileData.sw1 = iccIoResult->sw1; object->fileData.sw2 = iccIoResult->sw2; object->controlHolder = toMsg->controlHolder; object->arg1 = toMsg->arg1; object->arg2 = toMsg->arg2; if (telRilRequest == nullptr || iccIoResult == nullptr) { TELEPHONY_LOGE("ERROR : telRilRequest == nullptr || iccIoResult == nullptr !!!"); return; } handler->SendEvent(eventId, object); } void TelRilSim::GetSimStatusResponse(MessageParcel &data) { TELEPHONY_LOGD("OHOS::TelRilSim::GetSimStatusResponse --> "); std::shared_ptr<CardStatusInfo> cardStatusInfo = std::make_unique<CardStatusInfo>(); if (cardStatusInfo == nullptr) { TELEPHONY_LOGE("ERROR : GetSimStatusResponse --> cardStatusInfo == nullptr !!!"); return; } cardStatusInfo->ReadFromParcel(data); const size_t readSpSize = sizeof(struct HRilRadioResponseInfo); const uint8_t *spBuffer = data.ReadUnpadBuffer(readSpSize); if (spBuffer == nullptr) { TELEPHONY_LOGE("ERROR : GetSimStatusResponse --> spBuffer == nullptr !!!"); return; } const struct HRilRadioResponseInfo *radioResponseInfo = reinterpret_cast<const struct HRilRadioResponseInfo *>(spBuffer); if (radioResponseInfo == nullptr) { TELEPHONY_LOGE("ERROR : GetSimStatusResponse --> radioResponseInfo == nullptr !!!"); return; } TELEPHONY_LOGD( "GetSimStatusResponse --> radioResponseInfo->serial:%{public}d, " "radioResponseInfo->error:%{public}d", radioResponseInfo->serial, radioResponseInfo->error); std::shared_ptr<TelRilRequest> telRilRequest = FindTelRilRequest(*radioResponseInfo); if (telRilRequest != nullptr && telRilRequest->pointer_ != nullptr) { if (radioResponseInfo->error == HRilErrType::NONE) { const std::shared_ptr<OHOS::AppExecFwk::EventHandler> &handler = telRilRequest->pointer_->GetOwner(); if (handler == nullptr) { TELEPHONY_LOGE("ERROR : GetSimStatusResponse --> handler == nullptr !!!"); return; } uint32_t eventId = telRilRequest->pointer_->GetInnerEventId(); handler->SendEvent(eventId, cardStatusInfo); } else { ErrorResponse(telRilRequest, *radioResponseInfo); } } else { TELEPHONY_LOGE("ERROR : GetSimStatusResponse --> telRilRequest == nullptr || radioResponseInfo error !!!"); } } void TelRilSim::GetImsiResponse(MessageParcel &data) { TELEPHONY_LOGD("TelRilSim::GetImsiResponse --> "); const char *buffer = data.ReadCString(); std::shared_ptr<std::string> imsi = std::make_shared<std::string>(buffer); if (buffer == nullptr || imsi == nullptr) { TELEPHONY_LOGE("ERROR : GetImsiResponse --> buffer == nullptr || imsi == nullptr !!!"); return; } const size_t readSpSize = sizeof(struct HRilRadioResponseInfo); const uint8_t *spBuffer = data.ReadUnpadBuffer(readSpSize); if (spBuffer == nullptr) { TELEPHONY_LOGE("ERROR : GetImsiResponse --> spBuffer == nullptr!!!"); return; } const struct HRilRadioResponseInfo *radioResponseInfo = reinterpret_cast<const struct HRilRadioResponseInfo *>(spBuffer); if (radioResponseInfo == nullptr) { TELEPHONY_LOGE("ERROR : GetImsiResponse --> radioResponseInfo == nullptr !!!"); return; } TELEPHONY_LOGD( "GetImsiResponse --> radioResponseInfo->serial:%{public}d, " "radioResponseInfo->error:%{public}d", radioResponseInfo->serial, radioResponseInfo->error); std::shared_ptr<TelRilRequest> telRilRequest = FindTelRilRequest(*radioResponseInfo); if (telRilRequest != nullptr && telRilRequest->pointer_ != nullptr) { if (radioResponseInfo->error == HRilErrType::NONE) { TELEPHONY_LOGD("GetImsiResponse --> data.ReadCString() success"); std::shared_ptr<OHOS::AppExecFwk::EventHandler> handler = telRilRequest->pointer_->GetOwner(); if (handler == nullptr) { TELEPHONY_LOGE("ERROR : GetImsiResponse --> handler == nullptr !!!"); return; } uint32_t eventId = telRilRequest->pointer_->GetInnerEventId(); handler->SendEvent(eventId, imsi); } else { ErrorResponse(telRilRequest, *radioResponseInfo); } } else { TELEPHONY_LOGE( "ERROR : GetSimLockStatusResponse --> telRilRequest == nullptr || radioResponseInfo error !!!"); } } void TelRilSim::GetIccIDResponse(MessageParcel &data) { TELEPHONY_LOGD("TelRilSim::GetIccIDResponse --> "); const char *buffer = data.ReadCString(); std::shared_ptr<std::string> iccID = std::make_shared<std::string>(buffer); if (buffer == nullptr || iccID == nullptr) { TELEPHONY_LOGE("ERROR : GetIccIDResponse --> buffer == nullptr || IccID == nullptr !!!"); return; } const size_t readSpSize = sizeof(struct HRilRadioResponseInfo); const uint8_t *spBuffer = data.ReadUnpadBuffer(readSpSize); if (spBuffer == nullptr) { TELEPHONY_LOGE("ERROR : GetIccIDResponse --> spBuffer == nullptr!!!"); return; } const struct HRilRadioResponseInfo *radioResponseInfo = reinterpret_cast<const struct HRilRadioResponseInfo *>(spBuffer); if (radioResponseInfo == nullptr) { TELEPHONY_LOGE("ERROR : GetIccIDResponse --> radioResponseInfo == nullptr !!!"); return; } TELEPHONY_LOGD( "GetIccIDResponse --> radioResponseInfo->serial:%{public}d, " "radioResponseInfo->error:%{public}d", radioResponseInfo->serial, radioResponseInfo->error); std::shared_ptr<TelRilRequest> telRilRequest = FindTelRilRequest(*radioResponseInfo); if (telRilRequest != nullptr && telRilRequest->pointer_ != nullptr) { if (radioResponseInfo->error == HRilErrType::NONE) { TELEPHONY_LOGD("GetIccIDResponse --> data.ReadCString() success"); std::shared_ptr<OHOS::AppExecFwk::EventHandler> handler = telRilRequest->pointer_->GetOwner(); if (handler == nullptr) { TELEPHONY_LOGE("ERROR : GetIccIDResponse --> handler == nullptr !!!"); return; } uint32_t eventId = telRilRequest->pointer_->GetInnerEventId(); handler->SendEvent(eventId, iccID); } else { ErrorResponse(telRilRequest, *radioResponseInfo); } } else { TELEPHONY_LOGE("ERROR : GetIccIDResponse --> telRilRequest == nullptr || radioResponseInfo error !!!"); } } void TelRilSim::GetSimLockStatusResponse(MessageParcel &data) { TELEPHONY_LOGD("TelRilSim::GetSimLockStatusResponse --> "); std::shared_ptr<int> SimLockStatus = std::make_shared<int>(); *SimLockStatus = data.ReadInt32(); const size_t readSpSize = sizeof(struct HRilRadioResponseInfo); const uint8_t *spBuffer = data.ReadUnpadBuffer(readSpSize); if (spBuffer == nullptr) { TELEPHONY_LOGE("ERROR : GetSimLockStatusResponse --> spBuffer == nullptr!!!"); return; } const struct HRilRadioResponseInfo *radioResponseInfo = reinterpret_cast<const struct HRilRadioResponseInfo *>(spBuffer); if (radioResponseInfo == nullptr) { TELEPHONY_LOGE("ERROR : GetSimLockStatusResponse --> radioResponseInfo == nullptr !!!"); return; } TELEPHONY_LOGD( "GetSimLockStatusResponse --> radioResponseInfo->serial:%{public}d, " "radioResponseInfo->error:%{public}d", radioResponseInfo->serial, radioResponseInfo->error); std::shared_ptr<TelRilRequest> telRilRequest = FindTelRilRequest(*radioResponseInfo); if (telRilRequest != nullptr && telRilRequest->pointer_ != nullptr) { if (radioResponseInfo->error == HRilErrType::NONE) { TELEPHONY_LOGD("GetSimLockStatusResponse --> data.ReadCString() success"); std::shared_ptr<OHOS::AppExecFwk::EventHandler> handler = telRilRequest->pointer_->GetOwner(); if (handler == nullptr) { TELEPHONY_LOGE("ERROR : GetSimLockStatusResponse --> handler == nullptr !!!"); return; } uint32_t eventId = telRilRequest->pointer_->GetInnerEventId(); handler->SendEvent(eventId, SimLockStatus); } else { ErrorResponse(telRilRequest, *radioResponseInfo); } } else { TELEPHONY_LOGE( "ERROR : GetSimLockStatusResponse --> telRilRequest == nullptr || radioResponseInfo error !!!"); } } void TelRilSim::SetSimLockResponse(MessageParcel &data) { TELEPHONY_LOGD("TelRilSim::SetSimLockResponse --> "); const size_t readSpSize = sizeof(struct HRilRadioResponseInfo); const uint8_t *spBuffer = data.ReadUnpadBuffer(readSpSize); if (spBuffer == nullptr) { TELEPHONY_LOGE("ChangeSimPasswordResponse -->spBuffer == nullptr"); return; } const struct HRilRadioResponseInfo *radioResponseInfo = reinterpret_cast<const struct HRilRadioResponseInfo *>(spBuffer); if (radioResponseInfo == nullptr) { TELEPHONY_LOGE("ERROR : ChangeSimPasswordResponse --> radioResponseInfo == nullptr !!!"); return; } std::shared_ptr<TelRilRequest> telRilRequest = FindTelRilRequest(*radioResponseInfo); if (telRilRequest != nullptr && telRilRequest->pointer_ != nullptr) { if (radioResponseInfo->error == HRilErrType::NONE) { const std::shared_ptr<OHOS::AppExecFwk::EventHandler> &handler = telRilRequest->pointer_->GetOwner(); if (handler == nullptr) { TELEPHONY_LOGE("ERROR : ChangeSimPasswordResponse --> handler == nullptr !!!"); return; } uint32_t eventId = telRilRequest->pointer_->GetInnerEventId(); std::shared_ptr<HRilErrType> errorCode = std::make_shared<HRilErrType>(); *errorCode = radioResponseInfo->error; handler->SendEvent(eventId, errorCode); } else { ErrorResponse(telRilRequest, *radioResponseInfo); } } else { TELEPHONY_LOGE("ERROR : SetSimLockResponse --> telRilRequest == nullptr || radioResponseInfo error !!!"); } } void TelRilSim::ChangeSimPasswordResponse(MessageParcel &data) { TELEPHONY_LOGD("TelRilSim::ChangeSimPasswordResponse --> "); const size_t readSpSize = sizeof(struct HRilRadioResponseInfo); const uint8_t *spBuffer = data.ReadUnpadBuffer(readSpSize); if (spBuffer == nullptr) { TELEPHONY_LOGE("SetSimLockResponse -->spBuffer == nullptr"); return; } const struct HRilRadioResponseInfo *radioResponseInfo = reinterpret_cast<const struct HRilRadioResponseInfo *>(spBuffer); if (radioResponseInfo == nullptr) { TELEPHONY_LOGE("ERROR : SetSimLockResponse --> radioResponseInfo == nullptr !!!"); return; } std::shared_ptr<TelRilRequest> telRilRequest = FindTelRilRequest(*radioResponseInfo); if (telRilRequest != nullptr && telRilRequest->pointer_ != nullptr) { if (radioResponseInfo->error == HRilErrType::NONE) { const std::shared_ptr<OHOS::AppExecFwk::EventHandler> &handler = telRilRequest->pointer_->GetOwner(); if (handler == nullptr) { TELEPHONY_LOGE("ERROR : EnterSimPinResponse --> handler == nullptr !!!"); return; } uint32_t eventId = telRilRequest->pointer_->GetInnerEventId(); std::shared_ptr<HRilErrType> errorCode = std::make_shared<HRilErrType>(); *errorCode = radioResponseInfo->error; handler->SendEvent(eventId, errorCode); } else { ErrorResponse(telRilRequest, *radioResponseInfo); } } } void TelRilSim::EnterSimPinResponse(MessageParcel &data) { TELEPHONY_LOGD("TelRilSim::EnterSimPinResponse --> "); const size_t readSpSize = sizeof(struct HRilRadioResponseInfo); const uint8_t *spBuffer = data.ReadUnpadBuffer(readSpSize); if (spBuffer == nullptr) { TELEPHONY_LOGE("EnterSimPinResponse -->spBuffer == nullptr"); return; } const struct HRilRadioResponseInfo *radioResponseInfo = reinterpret_cast<const struct HRilRadioResponseInfo *>(spBuffer); if (radioResponseInfo == nullptr) { TELEPHONY_LOGE("ERROR : EnterSimPinResponse --> radioResponseInfo == nullptr !!!"); return; } std::shared_ptr<TelRilRequest> telRilRequest = FindTelRilRequest(*radioResponseInfo); if (telRilRequest != nullptr && telRilRequest->pointer_ != nullptr) { if (radioResponseInfo->error == HRilErrType::NONE) { const std::shared_ptr<OHOS::AppExecFwk::EventHandler> &handler = telRilRequest->pointer_->GetOwner(); if (handler == nullptr) { TELEPHONY_LOGE("ERROR : SetSimLockResponse --> handler == nullptr !!!"); return; } uint32_t eventId = telRilRequest->pointer_->GetInnerEventId(); std::shared_ptr<HRilErrType> errorCode = std::make_shared<HRilErrType>(); *errorCode = radioResponseInfo->error; handler->SendEvent(eventId, errorCode); } else { ErrorResponse(telRilRequest, *radioResponseInfo); } } } void TelRilSim::UnlockSimPinResponse(MessageParcel &data) { TELEPHONY_LOGD("TelRilSim::UnlockSimPinResponse --> "); const size_t readSpSize = sizeof(struct HRilRadioResponseInfo); const uint8_t *spBuffer = data.ReadUnpadBuffer(readSpSize); if (spBuffer == nullptr) { TELEPHONY_LOGE("UnlockSimPinResponse -->spBuffer == nullptr"); return; } const struct HRilRadioResponseInfo *radioResponseInfo = reinterpret_cast<const struct HRilRadioResponseInfo *>(spBuffer); if (radioResponseInfo == nullptr) { TELEPHONY_LOGE("ERROR : UnlockSimPinResponse --> radioResponseInfo == nullptr !!!"); return; } std::shared_ptr<TelRilRequest> telRilRequest = FindTelRilRequest(*radioResponseInfo); if (telRilRequest != nullptr && telRilRequest->pointer_ != nullptr) { if (radioResponseInfo->error == HRilErrType::NONE) { const std::shared_ptr<OHOS::AppExecFwk::EventHandler> &handler = telRilRequest->pointer_->GetOwner(); if (handler == nullptr) { TELEPHONY_LOGE("ERROR : UnlockSimPinResponse --> handler == nullptr !!!"); return; } uint32_t eventId = telRilRequest->pointer_->GetInnerEventId(); std::shared_ptr<HRilErrType> errorCode = std::make_shared<HRilErrType>(); *errorCode = radioResponseInfo->error; handler->SendEvent(eventId, errorCode); } else { ErrorResponse(telRilRequest, *radioResponseInfo); } } } void TelRilSim::GetSimPinInputTimesResponse(MessageParcel &data) { TELEPHONY_LOGD("TelRilSim GetSimPinInputTimesResponse -->"); std::shared_ptr<SimPinInputTimes> pSimPinInputTimes = std::make_shared<SimPinInputTimes>(); if (pSimPinInputTimes == nullptr) { TELEPHONY_LOGE("ERROR : GetSimPinInputTimesResponse --> callInfo == nullptr !!!"); return; } pSimPinInputTimes->ReadFromParcel(data); const size_t readSpSize = sizeof(struct HRilRadioResponseInfo); const uint8_t *spBuffer = data.ReadUnpadBuffer(readSpSize); if (spBuffer == nullptr) { TELEPHONY_LOGE("GetSimPinInputTimesResponse -->spBuffer == nullptr"); return; } const struct HRilRadioResponseInfo *radioResponseInfo = reinterpret_cast<const struct HRilRadioResponseInfo *>(spBuffer); if (radioResponseInfo == nullptr) { TELEPHONY_LOGE("ERROR : GetSimPinInputTimesResponse --> radioResponseInfo == nullptr !!!"); return; } std::shared_ptr<TelRilRequest> telRilRequest = FindTelRilRequest(*radioResponseInfo); if (telRilRequest != nullptr && telRilRequest->pointer_ != nullptr) { if (radioResponseInfo->error == HRilErrType::NONE) { const std::shared_ptr<OHOS::AppExecFwk::EventHandler> &handler = telRilRequest->pointer_->GetOwner(); if (handler == nullptr) { TELEPHONY_LOGE("ERROR : GetSimPinInputTimesResponse --> handler == nullptr !!!"); return; } uint32_t eventId = telRilRequest->pointer_->GetInnerEventId(); handler->SendEvent(eventId, pSimPinInputTimes); } else { ErrorResponse(telRilRequest, *radioResponseInfo); } } else { TELEPHONY_LOGE("ERROR : GetSimPinInputTimesResponse or telRilRequest->pointer_ == nullptr !!!"); return; } } // request void TelRilSim::GetSimStatus(const AppExecFwk::InnerEvent::Pointer &result) { TELEPHONY_LOGD("TelRilSim::GetSimStatus -->"); if (cellularRadio_ != nullptr) { std::shared_ptr<TelRilRequest> telRilRequest = CreateTelRilRequest(HREQ_SIM_GET_SIM_STATUS, result); if (telRilRequest == nullptr) { TELEPHONY_LOGE("TelRilSim GetSimStatus::telRilRequest is nullptr"); return; } TELEPHONY_LOGD("GetSimStatus --> telRilRequest->mSerial = %{public}d", telRilRequest->serialId_); int32_t ret = SendInt32Event(HREQ_SIM_GET_SIM_STATUS, telRilRequest->serialId_); TELEPHONY_LOGD("GetSimStatus --> HREQ_SIM_GET_SIM_STATUS ret = %{public}d", ret); } else { TELEPHONY_LOGE("ERROR : GetSimStatus --> cellularRadio_ == nullptr !!!"); } } void TelRilSim::RequestSimIO(int32_t command, int32_t fileId, int32_t p1, int32_t p2, int32_t p3, std::string data, std::string path, const AppExecFwk::InnerEvent::Pointer &response) { TELEPHONY_LOGD("TelRilSim::RequestSimIO --> "); if (cellularRadio_ != nullptr) { std::shared_ptr<TelRilRequest> telRilRequest = CreateTelRilRequest(HREQ_SIM_IO, response); if (telRilRequest == nullptr) { TELEPHONY_LOGE("TelRilSim RequestSimIO::telRilRequest is nullptr"); return; } MessageParcel wData; SimIoRequestInfo iccIoRequestInfo; iccIoRequestInfo.serial = telRilRequest->serialId_; iccIoRequestInfo.command = command; iccIoRequestInfo.fileId = fileId; iccIoRequestInfo.p1 = p1; iccIoRequestInfo.p2 = p2; iccIoRequestInfo.p3 = p3; iccIoRequestInfo.data = ChangeNullToEmptyString(data); iccIoRequestInfo.path = ChangeNullToEmptyString(path); iccIoRequestInfo.Marshalling(wData); MessageParcel reply; OHOS::MessageOption option = {OHOS::MessageOption::TF_ASYNC}; int ret = cellularRadio_->SendRequest(HREQ_SIM_IO, wData, reply, option); TELEPHONY_LOGD("RequestSimIO --> SendBufferEvent(HREQ_SIM_IO, wData) return ID: %{public}d", ret); } else { TELEPHONY_LOGE("ERROR : RequestSimIO --> cellularRadio_ == nullptr !!!"); } } void TelRilSim::GetImsi(const AppExecFwk::InnerEvent::Pointer &result) { TELEPHONY_LOGD("TelRilSim::GetImsi -->"); if (cellularRadio_ != nullptr) { std::shared_ptr<TelRilRequest> telRilRequest = CreateTelRilRequest(HREQ_SIM_GET_IMSI, result); if (telRilRequest == nullptr) { TELEPHONY_LOGE("TelRilSim GetImsi::telRilRequest is nullptr"); return; } MessageParcel data; data.WriteInt32(telRilRequest->serialId_); int32_t ret = SendBufferEvent(HREQ_SIM_GET_IMSI, data); TELEPHONY_LOGD("GetImsi --> SendBufferEvent(HREQ_SIM_GET_IMSI, wData) return ID: %{public}d", ret); } else { TELEPHONY_LOGE("ERROR : GetImsi --> cellularRadio_ == nullptr !!!"); } } void TelRilSim::GetIccID(const AppExecFwk::InnerEvent::Pointer &result) { TELEPHONY_LOGD("TelRilSim::GetIccID -->"); if (cellularRadio_ != nullptr) { std::shared_ptr<TelRilRequest> telRilRequest = CreateTelRilRequest(HREQ_SIM_GET_ICCID, result); if (telRilRequest == nullptr) { TELEPHONY_LOGE("TelRilSim GetIccID::telRilRequest is nullptr"); return; } MessageParcel data; data.WriteInt32(telRilRequest->serialId_); int32_t ret = SendBufferEvent(HREQ_SIM_GET_ICCID, data); TELEPHONY_LOGD("GetIccID --> SendBufferEvent(HREQ_SIM_GET_ICCID, wData) return ID: %{public}d", ret); } else { TELEPHONY_LOGE("ERROR : GetIccID --> cellularRadio_ == nullptr !!!"); } } void TelRilSim::GetSimLockStatus(std::string fac, const AppExecFwk::InnerEvent::Pointer &response) { TELEPHONY_LOGD("TelRilSim::GetSimLockStatus --> "); if (cellularRadio_ != nullptr) { std::shared_ptr<TelRilRequest> telRilRequest = CreateTelRilRequest(HREQ_SIM_GET_LOCK_STATUS, response); if (telRilRequest == nullptr) { TELEPHONY_LOGE("TelRilSim GetSimLockStatus::telRilRequest is nullptr"); return; } int mode = 2; MessageParcel wData; SimLockInfo simLockInfo; simLockInfo.serial = telRilRequest->serialId_; simLockInfo.fac = ChangeNullToEmptyString(fac); simLockInfo.mode = mode; simLockInfo.Marshalling(wData); MessageParcel reply; OHOS::MessageOption option = {OHOS::MessageOption::TF_ASYNC}; int ret = cellularRadio_->SendRequest(HREQ_SIM_GET_LOCK_STATUS, wData, reply, option); TELEPHONY_LOGD( "GetSimLockStatus --> SendBufferEvent(HREQ_SIM_GET_LOCK_STATUS, wData) return ID: %{public}d", ret); } else { TELEPHONY_LOGE("ERROR : HREQ_SIM_GET_LOCK_STATUS --> cellularRadio_ == nullptr !!!"); } } void TelRilSim::SetSimLock( std::string fac, int32_t mode, std::string passwd, const AppExecFwk::InnerEvent::Pointer &response) { TELEPHONY_LOGD("TelRilSim::SetSimLock --> "); if (cellularRadio_ != nullptr) { std::shared_ptr<TelRilRequest> telRilRequest = CreateTelRilRequest(HREQ_SIM_SET_LOCK, response); if (telRilRequest == nullptr) { TELEPHONY_LOGE("TelRilSim SetSimLock:t:elRilRequest is nullptr"); return; } MessageParcel wData; SimLockInfo simLockInfo; simLockInfo.serial = telRilRequest->serialId_; simLockInfo.fac = ChangeNullToEmptyString(fac); simLockInfo.mode = mode; simLockInfo.passwd = ChangeNullToEmptyString(passwd); simLockInfo.Marshalling(wData); MessageParcel reply; OHOS::MessageOption option = {OHOS::MessageOption::TF_ASYNC}; int ret = cellularRadio_->SendRequest(HREQ_SIM_SET_LOCK, wData, reply, option); TELEPHONY_LOGD("SetSimLock --> SendBufferEvent(HREQ_SIM_SET_LOCK, wData) return ID: %{public}d", ret); } else { TELEPHONY_LOGE("ERROR : HREQ_SIM_SET_LOCK --> cellularRadio_ == nullptr !!!"); } } void TelRilSim::ChangeSimPassword(std::string fac, std::string oldPassword, std::string newPassword, int32_t passwordLength, const AppExecFwk::InnerEvent::Pointer &response) { TELEPHONY_LOGD("TelRilSim::ChangeSimPassword --> "); if (cellularRadio_ != nullptr) { std::shared_ptr<TelRilRequest> telRilRequest = CreateTelRilRequest(HREQ_SIM_CHANGE_PASSWD, response); if (telRilRequest == nullptr) { TELEPHONY_LOGE("TelRilSim ChangeSimPassword::telRilRequest is nullptr"); return; } MessageParcel wData; SimPasswordInfo simPasswordInfo; simPasswordInfo.serial = telRilRequest->serialId_; simPasswordInfo.fac = ChangeNullToEmptyString(fac); simPasswordInfo.oldPassword = ChangeNullToEmptyString(oldPassword); simPasswordInfo.newPassword = ChangeNullToEmptyString(newPassword); simPasswordInfo.passwordLength = passwordLength; simPasswordInfo.Marshalling(wData); MessageParcel reply; OHOS::MessageOption option = {OHOS::MessageOption::TF_ASYNC}; int ret = cellularRadio_->SendRequest(HREQ_SIM_CHANGE_PASSWD, wData, reply, option); TELEPHONY_LOGD( "ChangeSimPassword --> SendBufferEvent(HREQ_SIM_CHANGE_PASSWD, wData) return ID: %{public}d", ret); } else { TELEPHONY_LOGE("ERROR : HREQ_SIM_CHANGE_PASSWD --> cellularRadio_ == nullptr !!!"); } } void TelRilSim::EnterSimPin(std::string pin, const AppExecFwk::InnerEvent::Pointer &response) { TELEPHONY_LOGD("TelRilSim::EnterSimPin --> "); if (cellularRadio_ != nullptr) { std::shared_ptr<TelRilRequest> telRilRequest = CreateTelRilRequest(HREQ_SIM_ENTER_PIN, response); if (telRilRequest == nullptr) { TELEPHONY_LOGE("TelRilSim EnterSimPin::telRilRequest is nullptr"); return; } MessageParcel data; data.WriteInt32(telRilRequest->serialId_); data.WriteCString(pin.c_str()); MessageParcel reply; OHOS::MessageOption option = {OHOS::MessageOption::TF_ASYNC}; int ret = cellularRadio_->SendRequest(HREQ_SIM_ENTER_PIN, data, reply, option); TELEPHONY_LOGD("EnterSimPin --> SendBufferEvent(HREQ_SIM_ENTER_PIN, wData) return ID: %{public}d", ret); } else { TELEPHONY_LOGE("ERROR : HREQ_SIM_ENTER_PIN --> cellularRadio_ == nullptr !!!"); } } void TelRilSim::UnlockSimPin(std::string puk, std::string pin, const AppExecFwk::InnerEvent::Pointer &response) { TELEPHONY_LOGD("TelRilSim::UnlockSimPin --> "); if (cellularRadio_ != nullptr) { std::shared_ptr<TelRilRequest> telRilRequest = CreateTelRilRequest(HREQ_SIM_UNLOCK_PIN, response); if (telRilRequest == nullptr) { TELEPHONY_LOGE("TelRilSim UnlockSimPin::telRilRequest is nullptr"); return; } MessageParcel data; data.WriteInt32(telRilRequest->serialId_); data.WriteCString(puk.c_str()); data.WriteCString(pin.c_str()); MessageParcel reply; OHOS::MessageOption option = {OHOS::MessageOption::TF_ASYNC}; int ret = cellularRadio_->SendRequest(HREQ_SIM_UNLOCK_PIN, data, reply, option); TELEPHONY_LOGD("UnlockSimPin --> SendBufferEvent(HREQ_SIM_UNLOCK_PIN, wData) return ID: %{public}d", ret); } else { TELEPHONY_LOGE("ERROR : HREQ_SIM_UNLOCK_PIN --> cellularRadio_ == nullptr !!!"); } } void TelRilSim::GetSimPinInputTimes(const AppExecFwk::InnerEvent::Pointer &result) { TELEPHONY_LOGD("TelRilSim::GetSimPinInputTimes -->"); if (cellularRadio_ != nullptr) { std::shared_ptr<TelRilRequest> telRilRequest = CreateTelRilRequest(HREQ_SIM_GET_PIN_INPUT_TIMES, result); if (telRilRequest == nullptr) { TELEPHONY_LOGE("TelRilSim GetSimPinInputTimes::telRilRequest is nullptr"); return; } TELEPHONY_LOGD("GetSimPinInputTimes --> telRilRequest->mSerial = %{public}d", telRilRequest->serialId_); int32_t ret = SendInt32Event(HREQ_SIM_GET_PIN_INPUT_TIMES, telRilRequest->serialId_); TELEPHONY_LOGD("GetSimPinInputTimes --> HREQ_SIM_GET_PIN_INPUT_TIMES ret = %{public}d", ret); } else { TELEPHONY_LOGE("ERROR : GetSimPinInputTimes --> cellularRadio_ == nullptr !!!"); } } std::string TelRilSim::ChangeNullToEmptyString(std::string str) { return !str.empty() ? str : ""; } } // namespace Telephony } // namespace OHOS
44.490323
115
0.6721
[ "object" ]
1d9754a3f98a8fa1c85b7ecee9a6617f9796092b
4,476
cpp
C++
src/Map/CMap.cpp
AntonBogomolov/SummonMaster
71b185d03c26cd77a5015ff91a4bd423952918c1
[ "MIT" ]
null
null
null
src/Map/CMap.cpp
AntonBogomolov/SummonMaster
71b185d03c26cd77a5015ff91a4bd423952918c1
[ "MIT" ]
null
null
null
src/Map/CMap.cpp
AntonBogomolov/SummonMaster
71b185d03c26cd77a5015ff91a4bd423952918c1
[ "MIT" ]
null
null
null
#include "CMap.h" #include "CHeightMap.h" #include "CMapObject.h" #include "src/Objects/CMovableObject.h" #include <iostream> #include <iomanip> CMap::CMap(const CMapCreationParams& param) : IEventHandler() { tileMap = nullptr; blockMap = nullptr; this->width = param.width; this->height = param.height; tileMap = new CTileData*[height]; blockMap = new bool*[height]; for(unsigned int row = 0; row < height; row++) { tileMap[row] = new CTileData[width]; blockMap[row] = new bool[width]; } pathFinder = new CPathFinderAStar(this); generateTileMap(param.generationParams); updateBlockMap(CCellCoords(0,0), CCellCoords(width-1, height-1)); } void CMap::updateBlockMap(const CCellCoords& leftDownCorner, const CCellCoords& rightUpCorner) { for(unsigned int x = leftDownCorner.col; x <= rightUpCorner.col; ++x) { for(unsigned int y = leftDownCorner.row; y <= rightUpCorner.row; ++y) { std::vector<CMapObject*>& objectsInCell = objectsOnMap.getAllMapObjectInCell(CCellCoords(x,y)); for(auto it = objectsInCell.begin(); it != objectsInCell.end(); ++it) { CMapObject* mapObject = (*it); if(mapObject && mapObject->getBlockMode() != ENMapObjectBlockMode::notBlock) { std::vector<CCellCoords> blockedCells; mapObject->getBlockedCells(blockedCells); for(auto cellsIt = blockedCells.begin(); cellsIt != blockedCells.end(); ++cellsIt) { CCellCoords& coords = (*cellsIt); blockMap[coords.row][coords.col] = true; } } } } } } void CMap::updateTileMap(const CCellCoords& leftDownCorner, const CCellCoords& rightUpCorner) { } void CMap::generateTileMap(const CMapGenerateParams& params) { CHeightMapGenerator generator; unsigned int maxDim = width; if(height > maxDim) maxDim = height; heightMap = generator.generateHeightMap(maxDim, 101); CTileData defaultTile(ENBioms::GRASS); for(unsigned int row = 0; row < height; row++) { for(unsigned int col = 0; col < width; col++) { float height = heightMap->get(col, row); if(height > heightMap->getAverageValue() * 3 ) tileMap[row][col] = CTileData(ENBioms::LAVA); else if(height > heightMap->getAverageValue() * 2 ) tileMap[row][col] = CTileData(ENBioms::SNOW); else if(height > heightMap->getAverageValue() ) tileMap[row][col] = CTileData(ENBioms::DESERT); else if(height > 0.0f ) tileMap[row][col] = CTileData(ENBioms::GRASS); else tileMap[row][col] = CTileData(ENBioms::WATER); blockMap[row][col] = false; } } } unsigned int CMap::getMoveWeight(const CCellCoords& cell, const CMovableObject* object) const { if(cell.col >= width || cell.row >= height) return std::numeric_limits<unsigned int>::max(); if(!object || !object->isValid() ) return std::numeric_limits<unsigned int>::max(); if(getIsBlockAt(cell.row, cell.col)) return std::numeric_limits<unsigned int>::max(); CTileData& tile = tileMap[cell.row][cell.col]; return object->getMoveCost(tile); } void CMap::update(const float dt) { std::unordered_map<unsigned int, CMapObject*>& objects = objectsOnMap.getObjectsPoolForModify().getObjectsForModify(); for(auto it = objects.begin(); it != objects.end(); ++it) { CMapObject* currMapObj = (it->second); if(currMapObj->getIsNeedToUpdate()) currMapObj->update(dt); } } void CMap::receiveMessage(const IEventHandler& messageSender, const CEventParam* eventParams) { if(eventParams->getEventType() == ENEvent::CHANGE_OBJECT_CELL) { const CChangeObjectCellEventParam* params = dynamic_cast<const CChangeObjectCellEventParam*>(eventParams); objectsOnMap.moveObjectToCell(params->getMapObject(), params->getSourceCell(), params->getDestCell()); } } CMap::~CMap() { delete heightMap; delete pathFinder; for(unsigned int i = 0; i < height; i++) { delete [] tileMap[i]; delete [] blockMap[i]; } delete [] tileMap; delete [] blockMap; }
34.96875
122
0.605675
[ "object", "vector" ]
1d9a4b5bd20e1da4483f6a1db1566fad43c58b06
11,978
cpp
C++
backEnd/src/serverLogicFunctions.cpp
amagood/handyPC
f862dfa1f0df83c41a8720d5411d85dbb77792ca
[ "MIT" ]
null
null
null
backEnd/src/serverLogicFunctions.cpp
amagood/handyPC
f862dfa1f0df83c41a8720d5411d85dbb77792ca
[ "MIT" ]
null
null
null
backEnd/src/serverLogicFunctions.cpp
amagood/handyPC
f862dfa1f0df83c41a8720d5411d85dbb77792ca
[ "MIT" ]
null
null
null
#include <stdio.h> #include <stdlib.h> #include <sqlite3.h> #include <vector> #include <string> #include <iostream> #include "json.hpp" std::vector<std::vector<std::string>> output; std::vector<std::string> colName; std::vector<std::string> tmp; using json = nlohmann::json; static int callback(void *data, int argc, char **argv, char **azColName){ int i; //fprintf(stderr, "%s: ", (const char*)data); for(i=0; i<argc; i++){ //printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL"); tmp.emplace_back(argv[i] ? argv[i] : "NULL"); colName.emplace_back(azColName[i]); } output.emplace_back(tmp); tmp.clear(); //printf("\n"); return 0; } bool isAllDigit(std::string in) { for(int i = 0;i < in.size();i ++) { if(!isdigit(in[i])) return false; } return true; } json vector_to_json(std::vector<std::vector<std::string>> in, std::vector<std::string> col) { json out; if(in.size() == 0) return out; for(int i = 0;i < in[0].size();i ++) { if(in.size() == 1) { if(isAllDigit(in[0][i])) out[col[i]] = std::stoi(in[0][i]); else { if(in[0][i] != "NULL") out[col[i]] = in[0][i]; else out[col[i]] = nullptr; } } else { std::vector<int> js; for(int j = 0;j < in.size();j ++) { int a = 0; if(isdigit(in[j][i].c_str()[0])) { js.emplace_back(std::stoi(in[j][i])); } } out[col[i]] = js; } } return out; } void vector_output(std::vector<std::vector<std::string>> in, std::vector<std::string> col) { if(in.size() != 0) { for(int j = 0; j < in[0].size(); j ++) { std::cout << col[j] << " "; } printf("\n"); for(int i = 0; i < in.size(); i ++) { for(int j = 0; j < in[0].size(); j ++) { std::cout << in[i][j] << " "; } printf("\n"); } } } json getProductById(int id) { sqlite3 *db; char *zErrMsg = 0; int rc; char sql[100]; const char* data = "Callback function called"; /* Open database */ rc = sqlite3_open("HandyPC.db", &db); if( rc ) { //fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db)); exit(0); } else { //fprintf(stderr, "Opened database successfully\n"); } /* Create SQL statement */ //sql = "SELECT * from Product WHERE ID = %d"; sprintf(sql,"SELECT * FROM Product WHERE ID = %d;",id); /* Execute SQL statement */ rc = sqlite3_exec(db, sql, callback, (void*)data, &zErrMsg); if( rc != SQLITE_OK ) { fprintf(stderr, "SQL error: %s\n", zErrMsg); sqlite3_free(zErrMsg); } else { //fprintf(stdout, "Operation done successfully\n"); } json result; result = vector_to_json(output,colName); //vector_output(output,colName) sqlite3_close(db); output.clear(); colName.clear(); tmp.clear(); return result; } json getProductDetailsById(int id) { sqlite3 *db; char *zErrMsg = 0; int rc; char sql[100]; const char* data = "Callback function called"; std::vector<std::string> subclass; subclass.emplace_back("ProductCPU"); subclass.emplace_back("ProductGPU"); subclass.emplace_back("ProductRAM"); /* Open database */ rc = sqlite3_open("HandyPC.db", &db); if( rc ) { //fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db)); exit(0); } else { //fprintf(stderr, "Opened database successfully\n"); } /* Create SQL statement */ //sql = "SELECT * from Product WHERE ID = %d"; for(int i = 0; i < subclass.size(); i ++) { sprintf(sql,"SELECT * FROM %s WHERE Product_ID = %d;",subclass[i].c_str(),id); /* Execute SQL statement */ rc = sqlite3_exec(db, sql, callback, (void*)data, &zErrMsg); if(output.size() != 0) break; output.clear(); colName.clear(); tmp.clear(); } if( rc != SQLITE_OK ) { //fprintf(stderr, "SQL error: %s\n", zErrMsg); sqlite3_free(zErrMsg); } else { //fprintf(stdout, "Operation done successfully\n"); } json result; result = vector_to_json(output,colName); //vector_output(output,colName); sqlite3_close(db); output.clear(); colName.clear(); tmp.clear(); return result; } json getCategoryById(int id) { sqlite3 *db; char *zErrMsg = 0; int rc; char sql[500]; const char* data = "Callback function called"; /* Open database */ rc = sqlite3_open("HandyPC.db", &db); if( rc ) { //fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db)); exit(0); } else { //fprintf(stderr, "Opened database successfully\n"); } /* Create SQL statement */ //sql = "SELECT * from Product WHERE ID = %d"; sprintf(sql,"SELECT * FROM Category WHERE ID = %d;",id); /* Execute SQL statement */ rc = sqlite3_exec(db, sql, callback, (void*)data, &zErrMsg); if( rc != SQLITE_OK ) { //fprintf(stderr, "SQL error: %s\n", zErrMsg); sqlite3_free(zErrMsg); } else { //fprintf(stdout, "Operation done successfully\n"); } json result; result = vector_to_json(output,colName); output.clear(); colName.clear(); tmp.clear(); sprintf(sql,"SELECT Product_ID FROM Include WHERE EXISTS(SELECT Name FROM Model WHERE Name = Model_Name AND Category_ID = %d);",id); /* Execute SQL statement */ rc = sqlite3_exec(db, sql, callback, (void*)data, &zErrMsg); if( rc != SQLITE_OK ) { //fprintf(stderr, "SQL error: %s\n", zErrMsg); sqlite3_free(zErrMsg); } else { //fprintf(stdout, "Operation done successfully\n"); } std::vector<int> ids; for(int i = 0;i < output.size();i ++) { int a = 0; if(isdigit(output[i][0].c_str()[0])) { a = std::stoi(output[i][0]); } ids.emplace_back(a); } result["AllProductID"] = ids; //vector_output(output,colName); sqlite3_close(db); output.clear(); colName.clear(); tmp.clear(); return result; } json getEvaluationById(int id) { sqlite3 *db; char *zErrMsg = 0; int rc; char sql[100]; const char* data = "Callback function called"; /* Open database */ rc = sqlite3_open("HandyPC.db", &db); if( rc ) { //fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db)); exit(0); } else { //fprintf(stderr, "Opened database successfully\n"); } /* Create SQL statement */ sprintf(sql,"SELECT * FROM ProductList WHERE ID = %d;",id); rc = sqlite3_exec(db, sql, callback, (void*)data, &zErrMsg); if( rc != SQLITE_OK ) { //fprintf(stderr, "SQL error: %s\n", zErrMsg); sqlite3_free(zErrMsg); } if(!output.empty()) { output.clear(); colName.clear(); tmp.clear(); sprintf(sql,"SELECT Product_ID FROM Contain WHERE ProductList_ID = %d;",id); /* Execute SQL statement */ rc = sqlite3_exec(db, sql, callback, (void*)data, &zErrMsg); if( rc != SQLITE_OK ) { //fprintf(stderr, "SQL error: %s\n", zErrMsg); sqlite3_free(zErrMsg); } else { //fprintf(stdout, "Operation done successfully\n"); } } //sql = "SELECT * from Product WHERE ID = %d"; json result; result = vector_to_json(output,colName); //vector_output(output,colName); sqlite3_close(db); output.clear(); colName.clear(); tmp.clear(); return result; } int createEvaluationByIds(std::vector<int> productIds) { sqlite3 *db; char *zErrMsg = 0; int rc; char sql[500]; const char* data = "Callback function called"; /* Open database */ rc = sqlite3_open("HandyPC.db", &db); if( rc ) { //fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db)); exit(0); } else { //fprintf(stderr, "Opened database successfully\n"); } /* Create SQL statement */ sprintf(sql,"INSERT INTO ProductList(Total_Price, Product_Count) VALUES(0,0);"); /* Execute SQL statement */ rc = sqlite3_exec(db, sql, callback, (void*)data, &zErrMsg); if(rc != SQLITE_OK) return -1; int id = sqlite3_last_insert_rowid(db); //int id = 0; //sprintf(sql,"SELECT last_insert_rowid();"); //rc = sqlite3_exec(db, sql, callback, (void*)data, &zErrMsg); printf("%d\n",id); for(int i = 0;i < productIds.size();i ++) { sprintf(sql,"INSERT INTO Contain(Product_ID,ProductList_ID) VALUES(%d, %d)",productIds[i],id); rc = sqlite3_exec(db, sql, callback, (void*)data, &zErrMsg); if(rc != SQLITE_OK) return -1; } if( rc != SQLITE_OK ) { //fprintf(stderr, "SQL error: %s\n", zErrMsg); sqlite3_free(zErrMsg); } else { //fprintf(stdout, "Operation done successfully\n"); } //json result; //result = vector_to_json(output,colName); //vector_output(output,colName); sqlite3_close(db); output.clear(); colName.clear(); tmp.clear(); return id; } //returns id of the new evaluation (< 0 if anything went wrong) bool deleteEvaluationById(int id) { sqlite3 *db; char *zErrMsg = 0; int rc; char sql[500]; const char* data = "Callback function called"; /* Open database */ rc = sqlite3_open("HandyPC.db", &db); if( rc ) { //fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db)); exit(0); } else { //fprintf(stderr, "Opened database successfully\n"); } /* Create SQL statement */ sprintf(sql,"DELETE FROM ProductList WHERE ID = %d;",id); /* Execute SQL statement */ rc = sqlite3_exec(db, sql, callback, (void*)data, &zErrMsg); if( rc != SQLITE_OK ) { //fprintf(stderr, "SQL error: %s\n", zErrMsg); sqlite3_free(zErrMsg); return false; } sprintf(sql,"DELETE FROM Contain WHERE ProductList_ID = %d;",id); /* Execute SQL statement */ rc = sqlite3_exec(db, sql, callback, (void*)data, &zErrMsg); if( rc != SQLITE_OK ) { //fprintf(stderr, "SQL error: %s\n", zErrMsg); sqlite3_free(zErrMsg); return false; } //json result; //result = vector_to_json(output,colName); //vector_output(output,colName); sqlite3_close(db); output.clear(); colName.clear(); tmp.clear(); return true; } //false if failed json getAllCategories() { sqlite3 *db; char *zErrMsg = 0; int rc; char sql[100]; const char* data = "Callback function called"; /* Open database */ rc = sqlite3_open("HandyPC.db", &db); if( rc ) { //fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db)); exit(0); } else { //fprintf(stderr, "Opened database successfully\n"); } /* Create SQL statement */ //sql = "SELECT * from Product WHERE ID = %d"; sprintf(sql,"SELECT ID FROM Category;"); /* Execute SQL statement */ rc = sqlite3_exec(db, sql, callback, (void*)data, &zErrMsg); if( rc != SQLITE_OK ) { fprintf(stderr, "SQL error: %s\n", zErrMsg); sqlite3_free(zErrMsg); } else { //fprintf(stdout, "Operation done successfully\n"); } json result; result = vector_to_json(output,colName); //vector_output(output,colName) sqlite3_close(db); output.clear(); colName.clear(); tmp.clear(); return result; }
24.696907
136
0.546752
[ "vector", "model" ]
1da743fc01fd26527480b59ec35b44c804ab1730
3,792
hpp
C++
include/Agui/Widgets/RadioButton/RadioButtonGroup.hpp
ZweiEuro/Agui
0062150c732a85a0811a29caa9493d159b17f75f
[ "BSD-3-Clause-Clear", "BSD-3-Clause" ]
84
2015-01-31T15:43:07.000Z
2022-01-28T13:02:57.000Z
include/Agui/Widgets/RadioButton/RadioButtonGroup.hpp
ZweiEuro/Agui
0062150c732a85a0811a29caa9493d159b17f75f
[ "BSD-3-Clause-Clear", "BSD-3-Clause" ]
5
2015-04-14T11:13:46.000Z
2021-03-01T21:23:14.000Z
include/Agui/Widgets/RadioButton/RadioButtonGroup.hpp
ZweiEuro/Agui
0062150c732a85a0811a29caa9493d159b17f75f
[ "BSD-3-Clause-Clear", "BSD-3-Clause" ]
21
2015-03-25T00:28:50.000Z
2021-05-11T05:50:35.000Z
/* _____ * /\ _ \ __ * \ \ \_\ \ __ __ __ /\_\ * \ \ __ \ /'_ `\ /\ \/\ \\/\ \ * \ \ \/\ \ /\ \_\ \\ \ \_\ \\ \ \ * \ \_\ \_\\ \____ \\ \____/ \ \_\ * \/_/\/_/ \/____\ \\/___/ \/_/ * /\____/ * \_/__/ * * Copyright (c) 2011 Joshua Larouche * * * License: (BSD) * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name of Agui nor the names of its contributors may * be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef AGUI_RADIO_BUTTON_GROUP_HPP #define AGUI_RADIO_BUTTON_GROUP_HPP #include "Agui/Widgets/RadioButton/RadioButtonListener.hpp" #include "Agui/Widgets/RadioButton/RadioButton.hpp" namespace agui { /** * Class to group RadioButtons. Will manage them and ensure only 1 is selected. * * A RadioButton can be part of multiple groups. * @author Joshua Larouche * @since 0.1.0 */ class AGUI_CORE_DECLSPEC RadioButtonGroup : public RadioButtonListener { std::string groupId; std::vector<RadioButton*> radioButtons; RadioButton* selectedRButton; protected: /** * Manages which RadioButton will be selected when one of them is clicked. * @since 0.1.0 */ virtual void checkedStateChanged(RadioButton* source, RadioButton::RadioButtonCheckedEnum state); protected: /** * Removes the RadioButton from itself when the RadioButton dies. * @since 0.1.0 */ virtual void death(RadioButton* source); public: /** * Default constructor. * @since 0.1.0 */ RadioButtonGroup(void); /** * Constructs with a group id string. * @since 0.1.0 */ RadioButtonGroup(const std::string &id); /** * @return The group id string. * @since 0.1.0 */ const std::string& getGroupId() const; /** * Adds the parameter RadioButton to the group. * @since 0.1.0 */ void add(RadioButton* radioButton); /** * Removes the parameter RadioButton to the group. * @since 0.1.0 */ void remove(RadioButton* radioButton); /** * @return The selected RadioButton. * @since 0.1.0 */ RadioButton* getSelected() const; /** * Default destructor. * @since 0.1.0 */ virtual ~RadioButtonGroup(void); }; } #endif
33.857143
84
0.63212
[ "vector" ]
1daf6c2c54845fb596b00a246b4c585d6fe62d5c
2,625
cpp
C++
GeeksForGeeks/LRU Cache.cpp
tanishq1g/cp_codes
80b8ccc9e195a66d6d317076fdd54a02cd21275b
[ "MIT" ]
null
null
null
GeeksForGeeks/LRU Cache.cpp
tanishq1g/cp_codes
80b8ccc9e195a66d6d317076fdd54a02cd21275b
[ "MIT" ]
null
null
null
GeeksForGeeks/LRU Cache.cpp
tanishq1g/cp_codes
80b8ccc9e195a66d6d317076fdd54a02cd21275b
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <vector> #include <locale> #include <algorithm> #include <cmath> #include <unordered_map> #include <unordered_set> #include <set> #include <bitset> #include <climits> #include <list> #include <queue> #include <stack> #include <utility> using namespace std; #define INF 1e7 // STACK AND HEAPS class LRUCache{ private: unordered_map<int, list<pair<int, int>>::iterator > umap; list<pair<int, int> > li; int cap; public: LRUCache(int c){ cap = c; } int get(int key){ unordered_map<int, list<pair<int, int>>::iterator >::iterator itr = umap.find(key); if(itr == umap.end()){ return -1; } int x = itr->second->second; li.erase(itr->second); li.push_back(make_pair(key, value)); list<pair<int, int>>::iterator it = li.end(); advance(it, -1); umap[key] = it; return x; } void set(int key, int value){ unordered_map<int, list<pair<int, int>>::iterator >::iterator itr = umap.find(key); if(itr == umap.end()){ if(li.size() == cap){ umap.erase(li.front().first); li.pop_front(); } li.push_back(make_pair(key, value)); list<pair<int, int>>::iterator it = li.end(); advance(it, -1); umap[key] = it; } else{ li.erase(itr->second); li.push_back(make_pair(key, value)); list<pair<int, int>>::iterator it = li.end(); advance(it, -1); umap[key] = it; } // cout << "\nstart " << li.size() << '\n'; // for(list<pair<int, int> >::iterator itr = li.begin(); itr != li.end(); itr++){ // cout << itr->first << ' ' << itr->second << ' ' << ' ' ; // }cout << "\nend"; } }; 8 82 SET 97 30 GET 43 GET 13 SET 48 56 GET 67 GET 60 SET 74 43 SET 72 39 SET 100 59 GET 85 SET 91 62 GET 72 SET 1 4 GET 1 GET 53 GET 5 SET 59 60 SET 18 95 GET 37 GET 61 GET 15 SET 66 38 GET 22 GET 10 SET 33 1 GET 5 SET 57 59 SET 69 11 SET 29 70 SET 75 47 GET 6 GET 2 SET 68 90 GET 27 GET 39 SET 1 6 GET 58 GET 49 SET 8 18 SET 70 98 GET 29 SET 71 19 SET 81 93 GET 55 SET 44 8 GET 51 SET 89 86 GET 91 GET 35 SET 84 26 SET 43 95 GET 92 SET 21 21 GET 39 GET 93 GET 23 GET 86 GET 95 GET 9 GET 3 SET 23 85 SET 58 26 1 SET 93 3 GET 97 GET 31 GET 50 2 SET 57 13 3 SET 49 55 GET 29 GET 58 GET 77 4 SET 21 98 5 SET 6 95 GET 83 GET 24 6 SET 16 37 7 SET 54 85 8 SET 55 25 GET 37 GET 93 GET 59 GET 24
23.648649
157
0.549714
[ "vector" ]
1db1748f4e3942950018fa0ca741dc4e20acb960
6,113
cpp
C++
inference-engine/samples/hello_classification/main.cpp
mypopydev/dldt
8cd639116b261adbbc8db860c09807c3be2cc2ca
[ "Apache-2.0" ]
3
2019-07-08T09:03:03.000Z
2020-09-09T10:34:17.000Z
inference-engine/samples/hello_classification/main.cpp
openvino-pushbot/dldt
e607ee70212797cf9ca51dac5b7ac79f66a1c73f
[ "Apache-2.0" ]
3
2020-11-13T18:59:18.000Z
2022-02-10T02:14:53.000Z
inference-engine/samples/hello_classification/main.cpp
openvino-pushbot/dldt
e607ee70212797cf9ca51dac5b7ac79f66a1c73f
[ "Apache-2.0" ]
1
2018-12-05T07:38:25.000Z
2018-12-05T07:38:25.000Z
/* // Copyright (c) 2018 Intel Corporation // // 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 <iomanip> #include <vector> #include <memory> #include <string> #include <cstdlib> #include <opencv2/opencv.hpp> #include <inference_engine.hpp> using namespace InferenceEngine; int main(int argc, char *argv[]) { try { // ------------------------------ Parsing and validation of input args --------------------------------- if (argc != 3) { std::cout << "Usage : ./hello_classification <path_to_model> <path_to_image>" << std::endl; return EXIT_FAILURE; } const std::string input_model{argv[1]}; const std::string input_image_path{argv[2]}; // ----------------------------------------------------------------------------------------------------- // --------------------------- 1. Load Plugin for inference engine ------------------------------------- PluginDispatcher dispatcher({"../../../lib/intel64", ""}); InferencePlugin plugin(dispatcher.getSuitablePlugin(TargetDevice::eCPU)); // ----------------------------------------------------------------------------------------------------- // --------------------------- 2. Read IR Generated by ModelOptimizer (.xml and .bin files) ------------ CNNNetReader network_reader; network_reader.ReadNetwork(input_model); network_reader.ReadWeights(input_model.substr(0, input_model.size() - 4) + ".bin"); network_reader.getNetwork().setBatchSize(1); CNNNetwork network = network_reader.getNetwork(); // ----------------------------------------------------------------------------------------------------- // --------------------------- 3. Configure input & output --------------------------------------------- // --------------------------- Prepare input blobs ----------------------------------------------------- InputInfo::Ptr input_info = network.getInputsInfo().begin()->second; std::string input_name = network.getInputsInfo().begin()->first; input_info->setLayout(Layout::NCHW); input_info->setPrecision(Precision::U8); // --------------------------- Prepare output blobs ---------------------------------------------------- DataPtr output_info = network.getOutputsInfo().begin()->second; std::string output_name = network.getOutputsInfo().begin()->first; output_info->setPrecision(Precision::FP32); // ----------------------------------------------------------------------------------------------------- // --------------------------- 4. Loading model to the plugin ------------------------------------------ ExecutableNetwork executable_network = plugin.LoadNetwork(network, {}); // ----------------------------------------------------------------------------------------------------- // --------------------------- 5. Create infer request ------------------------------------------------- InferRequest infer_request = executable_network.CreateInferRequest(); // ----------------------------------------------------------------------------------------------------- // --------------------------- 6. Prepare input -------------------------------------------------------- cv::Mat image = cv::imread(input_image_path); /* Resize manually and copy data from the image to the input blob */ Blob::Ptr input = infer_request.GetBlob(input_name); auto input_data = input->buffer().as<PrecisionTrait<Precision::U8>::value_type *>(); cv::resize(image, image, cv::Size(input_info->getTensorDesc().getDims()[3], input_info->getTensorDesc().getDims()[2])); size_t channels_number = input->getTensorDesc().getDims()[1]; size_t image_size = input->getTensorDesc().getDims()[3] * input->getTensorDesc().getDims()[2]; for (size_t pid = 0; pid < image_size; ++pid) { for (size_t ch = 0; ch < channels_number; ++ch) { input_data[ch * image_size + pid] = image.at<cv::Vec3b>(pid)[ch]; } } // ----------------------------------------------------------------------------------------------------- // --------------------------- 7. Do inference -------------------------------------------------------- /* Running the request synchronously */ infer_request.Infer(); // ----------------------------------------------------------------------------------------------------- // --------------------------- 8. Process output ------------------------------------------------------ Blob::Ptr output = infer_request.GetBlob(output_name); auto output_data = output->buffer().as<PrecisionTrait<Precision::FP32>::value_type*>(); std::vector<unsigned> results; /* This is to sort output probabilities and put it to results vector */ TopResults(10, *output, results); std::cout << std::endl << "Top 10 results:" << std::endl << std::endl; for (size_t id = 0; id < 10; ++id) { std::cout.precision(7); auto result = output_data[results[id]]; std::cout << std::left << std::fixed << result << " label #" << results[id] << std::endl; } // ----------------------------------------------------------------------------------------------------- } catch (const std::exception & ex) { std::cerr << ex.what() << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; }
50.106557
127
0.446098
[ "vector", "model" ]
1db186e3308e981f3bd465a38aa188ed8ade02d9
4,202
cpp
C++
libdvblinkremote/src/parental_lock.cpp
marefr/dvblinkremote
a8e05b8ab35e62c11a410c943b91abf742f5a9c1
[ "Unlicense", "MIT" ]
2
2021-06-24T17:25:26.000Z
2021-06-24T17:26:44.000Z
libdvblinkremote/src/parental_lock.cpp
marefr/dvblinkremote
a8e05b8ab35e62c11a410c943b91abf742f5a9c1
[ "Unlicense", "MIT" ]
1
2015-10-20T16:13:07.000Z
2015-10-20T16:13:07.000Z
libdvblinkremote/src/parental_lock.cpp
marefr/dvblinkremote
a8e05b8ab35e62c11a410c943b91abf742f5a9c1
[ "Unlicense", "MIT" ]
2
2015-02-13T14:22:40.000Z
2015-04-08T14:03:25.000Z
/*************************************************************************** * Copyright (C) 2012 Marcus Efraimsson. * * 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 "request.h" #include "response.h" #include "xml_object_serializer.h" using namespace dvblinkremote; using namespace dvblinkremoteserialization; ParentalStatus::ParentalStatus() { IsEnabled = false; } ParentalStatus::ParentalStatus(ParentalStatus& parentalStatus) { IsEnabled = parentalStatus.IsEnabled; } ParentalStatus::~ParentalStatus() { } GetParentalStatusRequest::GetParentalStatusRequest(const std::string& clientId) : m_clientId(clientId) { } GetParentalStatusRequest::~GetParentalStatusRequest() { } std::string& GetParentalStatusRequest::GetClientID() { return m_clientId; } SetParentalLockRequest::SetParentalLockRequest(const std::string& clientId) : m_clientId(clientId), m_enabled(false), m_code("") { } SetParentalLockRequest::SetParentalLockRequest(const std::string& clientId, const std::string& code) : m_clientId(clientId), m_enabled(true), m_code(code) { } SetParentalLockRequest::~SetParentalLockRequest() { } std::string& SetParentalLockRequest::GetClientID() { return m_clientId; } bool SetParentalLockRequest::IsEnabled() { return m_enabled; } std::string& SetParentalLockRequest::GetCode() { return m_code; } bool ParentalStatusSerializer::ReadObject(ParentalStatus& object, const std::string& xml) { tinyxml2::XMLDocument& doc = GetXmlDocument(); if (doc.Parse(xml.c_str()) == tinyxml2::XML_NO_ERROR) { tinyxml2::XMLElement* elRoot = doc.FirstChildElement("parental_status"); object.IsEnabled = Util::GetXmlFirstChildElementTextAsBoolean(elRoot, "is_enabled"); return true; } return false; } bool GetParentalStatusRequestSerializer::WriteObject(std::string& serializedData, GetParentalStatusRequest& objectGraph) { tinyxml2::XMLElement* rootElement = PrepareXmlDocumentForObjectSerialization("parental_lock"); rootElement->InsertEndChild(Util::CreateXmlElementWithText(&GetXmlDocument(), "client_id", objectGraph.GetClientID())); tinyxml2::XMLPrinter* printer = new tinyxml2::XMLPrinter(); GetXmlDocument().Accept(printer); serializedData = std::string(printer->CStr()); return true; } bool SetParentalLockRequestSerializer::WriteObject(std::string& serializedData, SetParentalLockRequest& objectGraph) { tinyxml2::XMLElement* rootElement = PrepareXmlDocumentForObjectSerialization("parental_lock"); rootElement->InsertEndChild(Util::CreateXmlElementWithText(&GetXmlDocument(), "client_id", objectGraph.GetClientID())); rootElement->InsertEndChild(Util::CreateXmlElementWithText(&GetXmlDocument(), "is_enable", objectGraph.IsEnabled())); if (objectGraph.IsEnabled()) { rootElement->InsertEndChild(Util::CreateXmlElementWithText(&GetXmlDocument(), "code", objectGraph.GetCode())); } tinyxml2::XMLPrinter* printer = new tinyxml2::XMLPrinter(); GetXmlDocument().Accept(printer); serializedData = std::string(printer->CStr()); return true; }
31.125926
121
0.732746
[ "object" ]
1db3cb48a699d1e7d6c308473835fe8829fd41d5
16,118
hpp
C++
ajg/synth/engines/ssi/builtin_tags.hpp
legutierr/synth
7540072bde2ea9c8258c2dca69d2ed3bd62fb991
[ "BSL-1.0" ]
1
2016-04-10T14:13:34.000Z
2016-04-10T14:13:34.000Z
ajg/synth/engines/ssi/builtin_tags.hpp
legutierr/synth
7540072bde2ea9c8258c2dca69d2ed3bd62fb991
[ "BSL-1.0" ]
null
null
null
ajg/synth/engines/ssi/builtin_tags.hpp
legutierr/synth
7540072bde2ea9c8258c2dca69d2ed3bd62fb991
[ "BSL-1.0" ]
null
null
null
// (C) Copyright 2014 Alvaro J. Genial (http://alva.ro) // Use, modification and distribution are subject to the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt). #ifndef AJG_SYNTH_ENGINES_SSI_BUILTIN_TAGS_HPP_INCLUDED #define AJG_SYNTH_ENGINES_SSI_BUILTIN_TAGS_HPP_INCLUDED #include <map> #include <string> #include <functional> #include <boost/bind.hpp> #include <boost/foreach.hpp> #include <ajg/synth/detail/pipe.hpp> #include <ajg/synth/detail/text.hpp> namespace ajg { namespace synth { namespace engines { namespace ssi { template <class Kernel> struct builtin_tags { private: typedef Kernel kernel_type; typedef typename kernel_type::id_type id_type; typedef typename kernel_type::regex_type regex_type; typedef typename kernel_type::match_type match_type; typedef typename kernel_type::string_regex_type string_regex_type; typedef typename kernel_type::string_match_type string_match_type; typedef typename kernel_type::args_type args_type; typedef typename kernel_type::engine_type engine_type; typedef typename engine_type::environment_type environment_type; typedef typename engine_type::context_type context_type; typedef typename engine_type::options_type options_type; typedef typename engine_type::value_type value_type; typedef typename engine_type::traits_type traits_type; typedef typename traits_type::boolean_type boolean_type; typedef typename traits_type::char_type char_type; typedef typename traits_type::size_type size_type; typedef typename traits_type::floating_type floating_type; typedef typename traits_type::datetime_type datetime_type; typedef typename traits_type::path_type path_type; typedef typename traits_type::string_type string_type; typedef typename traits_type::ostream_type ostream_type; typedef detail::text<string_type> text; public: typedef void (*tag_type)(args_type const&); private: typedef std::map<id_type, tag_type> tags_type; public: inline void initialize(kernel_type& kernel) { kernel.tag = add(kernel, config_tag::syntax(kernel), config_tag::render) | add(kernel, echo_tag::syntax(kernel), echo_tag::render) | add(kernel, exec_tag::syntax(kernel), exec_tag::render) | add(kernel, fsize_tag::syntax(kernel), fsize_tag::render) | add(kernel, flastmod_tag::syntax(kernel), flastmod_tag::render) | add(kernel, if_tag::syntax(kernel), if_tag::render) | add(kernel, include_tag::syntax(kernel), include_tag::render) | add(kernel, printenv_tag::syntax(kernel), printenv_tag::render) | add(kernel, set_tag::syntax(kernel), set_tag::render) ; } private: inline regex_type const& add(kernel_type& kernel, regex_type const& regex, tag_type const tag) { tags_[regex.regex_id()] = tag; return regex; } tags_type tags_; public: // // get //////////////////////////////////////////////////////////////////////////////////////////////////// inline tag_type get(id_type const id) const { typename tags_type::const_iterator it = tags_.find(id); return it == tags_.end() ? 0 : it->second; } // // AJG_SYNTH_SSI_FOREACH_ATTRIBUTE_IN, AJG_SYNTH_SSI_NO_ATTRIBUTES_IN: // Macros to facilitate iterating over and validating tag attributes. //////////////////////////////////////////////////////////////////////////////////////////////////// enum { interpolated = true, raw = false }; // TODO: Make `name` and `value` arguments. #define AJG_SYNTH_SSI_FOREACH_ATTRIBUTE_IN(x, how, if_statement) do { \ BOOST_FOREACH(match_type const& attr, args.kernel.unnest(x).nested_results()) { \ std::pair<string_type, string_type> const attribute = args.kernel.parse_attribute(attr, args, how); \ string_type const name = attribute.first, value = attribute.second; \ if_statement else AJG_SYNTH_THROW(invalid_attribute(text::narrow(name))); \ } \ } while (0) #define AJG_SYNTH_SSI_NO_ATTRIBUTES_IN(x) AJG_SYNTH_SSI_FOREACH_ATTRIBUTE_IN(x, raw, if (false) {}) // // validate_attribute //////////////////////////////////////////////////////////////////////////////////////////////////// inline static void validate_attribute( char const* const name , string_type const& value , char const* const a = 0 , char const* const b = 0 , char const* const c = 0 ) { if ((a == 0 || value != text::literal(a)) && (b == 0 || value != text::literal(b)) && (c == 0 || value != text::literal(c))) { AJG_SYNTH_THROW(invalid_attribute(name)); } } // // config_tag //////////////////////////////////////////////////////////////////////////////////////////////////// struct config_tag { static regex_type syntax(kernel_type const& kernel) { return kernel.make_tag(text::literal("config")); } static void render(args_type const& args) { AJG_SYNTH_SSI_FOREACH_ATTRIBUTE_IN(args.match, interpolated, if (name == text::literal("sizefmt")) { validate_attribute("sizefmt", value, "bytes", "abbrev"); args.options.size_format = value; } else if (name == text::literal("timefmt")) args.options.time_format = value; else if (name == text::literal("echomsg")) args.options.echo_message = value; else if (name == text::literal("errmsg")) args.options.error_message = value; ); } }; // // echo_tag //////////////////////////////////////////////////////////////////////////////////////////////////// struct echo_tag { static regex_type syntax(kernel_type const& kernel) { return kernel.make_tag(text::literal("echo")); } static void render(args_type const& args) { string_type encoding = text::literal("entity"); AJG_SYNTH_SSI_FOREACH_ATTRIBUTE_IN(args.match, interpolated, if (name == text::literal("var")) { string_type const result = args.kernel.lookup_variable(args.context, args.options, value); if (encoding == text::literal("none")) args.ostream << result; else if (encoding == text::literal("url")) args.ostream << text::uri_encode(result); else if (encoding == text::literal("entity")) args.ostream << text::escape_entities(result); else AJG_SYNTH_THROW(invalid_attribute("encoding")); } else if (name == text::literal("encoding")) { validate_attribute("encoding", value, "none", "url", "entity"); encoding = value; } ); } }; // // exec_tag //////////////////////////////////////////////////////////////////////////////////////////////////// struct exec_tag { static regex_type syntax(kernel_type const& kernel) { return kernel.make_tag(text::literal("exec")); } static void render(args_type const& args) { AJG_SYNTH_SSI_FOREACH_ATTRIBUTE_IN(args.match, interpolated, if (name == text::literal("cgi")) { // TODO: // BOOST_ASSERT(detail::file_exists(value)); AJG_SYNTH_THROW(not_implemented("exec cgi")); } else if (name == text::literal("cmd")) { detail::pipe pipe(text::narrow(value)); pipe.read_into(args.ostream); } ); } }; // // flastmod_tag //////////////////////////////////////////////////////////////////////////////////////////////////// struct flastmod_tag { static regex_type syntax(kernel_type const& kernel) { return kernel.make_tag(text::literal("flastmod")); } static void render(args_type const& args) { AJG_SYNTH_SSI_FOREACH_ATTRIBUTE_IN(args.match, interpolated, if (name == text::literal("virtual")) { // TODO: Parse REQUEST_URI and figure our path out. AJG_SYNTH_THROW(not_implemented("fsize virtual")); } else if (name == text::literal("file")) { std::time_t const stamp = detail::stat_file(text::narrow(value)).st_mtime; args.ostream << traits_type::format_time(args.options.time_format, traits_type::to_time(stamp)); } ); } }; // // fsize_tag //////////////////////////////////////////////////////////////////////////////////////////////////// struct fsize_tag { static regex_type syntax(kernel_type const& kernel) { return kernel.make_tag(text::literal("fsize")); } static void render(args_type const& args) { boolean_type const abbreviate = args.options.size_format == text::literal("abbrev"); validate_attribute("size_format", args.options.size_format, "bytes", "abbrev"); AJG_SYNTH_SSI_FOREACH_ATTRIBUTE_IN(args.match, interpolated, if (name == text::literal("virtual")) { // TODO: Parse REQUEST_URI and figure our path out. AJG_SYNTH_THROW(not_implemented("fsize virtual")); } else if (name == text::literal("file")) { size_type const size = detail::stat_file(text::narrow(value)).st_size; abbreviate ? args.ostream << traits_type::format_size(size) : args.ostream << size; } ); } }; // // if_tag //////////////////////////////////////////////////////////////////////////////////////////////////// struct if_tag { static regex_type syntax(kernel_type const& kernel) { return (kernel.make_tag(text::literal("if")) >> kernel.block) >> *(kernel.make_tag(text::literal("elif")) >> kernel.block) >> !(kernel.make_tag(text::literal("else")) >> kernel.block) >> (kernel.make_tag(text::literal("endif"))); } static void render(args_type const& args) { boolean_type condition = false; BOOST_FOREACH(match_type const& nested, args.match.nested_results()) { if (kernel_type::is(nested, args.kernel.block)) { if (condition) { args.kernel.render_block(args.ostream, nested, args.context, args.options); break; } } else { condition = evaluate_tag(args, nested); } } } inline static boolean_type evaluate_tag(args_type const& args, match_type const& tag) { boolean_type has_expr = false, result = false; string_match_type match; string_type const name = tag[s1].str(); if (name == text::literal("if") || name == text::literal("elif")) { AJG_SYNTH_SSI_FOREACH_ATTRIBUTE_IN(tag, raw, if (name == text::literal("expr")) { if (!has_expr) has_expr = true; else AJG_SYNTH_THROW(duplicate_attribute("expr")); if (x::regex_match(value, match, args.kernel.expression)) { result = args.kernel.evaluate_expression(args, match); } else { AJG_SYNTH_THROW(invalid_attribute("expr")); } } ); if (has_expr) return result; else AJG_SYNTH_THROW(missing_attribute("expr")); } else { AJG_SYNTH_SSI_NO_ATTRIBUTES_IN(tag); if (name == text::literal("else")) return true; else if (name == text::literal("endif")) return false; else AJG_SYNTH_THROW(std::logic_error("invalid tag")); } } }; // // include_tag //////////////////////////////////////////////////////////////////////////////////////////////////// struct include_tag { static regex_type syntax(kernel_type const& kernel) { return kernel.make_tag(text::literal("include")); } static void render(args_type const& args) { AJG_SYNTH_SSI_FOREACH_ATTRIBUTE_IN(args.match, interpolated, if (name == text::literal("virtual")) { // TODO: Parse REQUEST_URI and figure our path out. AJG_SYNTH_THROW(not_implemented("include virtual")); } else if (name == text::literal("file")) { args.kernel.render_path(args.ostream, traits_type::to_path(value), args.context, args.options); } ); } }; // // printenv_tag //////////////////////////////////////////////////////////////////////////////////////////////////// struct printenv_tag { static regex_type syntax(kernel_type const& kernel) { return kernel.make_tag(text::literal("printenv")); } static void render(args_type const& args) { AJG_SYNTH_SSI_NO_ATTRIBUTES_IN(args.match); BOOST_FOREACH(typename environment_type::value_type const& nv, args.kernel.environment) { args.ostream << text::widen(nv.first) << '=' << text::widen(nv.second) << std::endl; } } }; // // set_tag //////////////////////////////////////////////////////////////////////////////////////////////////// struct set_tag { static regex_type syntax(kernel_type const& kernel) { return kernel.make_tag(text::literal("set")); } static void render(args_type const& args) { optional<string_type> name_; optional<value_type> value_; AJG_SYNTH_SSI_FOREACH_ATTRIBUTE_IN(args.match, interpolated, if (name == text::literal("var")) { if (name_) AJG_SYNTH_THROW(duplicate_attribute("name")); else name_ = value; } else if (name == text::literal("value")) { if (value_) AJG_SYNTH_THROW(duplicate_attribute("value")); else value_ = value; } ); if (!name_) AJG_SYNTH_THROW(missing_attribute("name")); if (!value_) AJG_SYNTH_THROW(missing_attribute("value")); args.context[*name_] = *value_; } }; #undef AJG_SYNTH_SSI_FOREACH_ATTRIBUTE_IN #undef AJG_SYNTH_SSI_NO_ATTRIBUTES_IN }; // builtin_tags }}}} // namespace ajg::synth::engines::ssi #endif // AJG_SYNTH_ENGINES_SSI_BUILTIN_TAGS_HPP_INCLUDED
40.908629
116
0.506825
[ "render" ]
1db57bb9c506d6ff4b0727b3c408df8ebb218c3c
10,708
hh
C++
arith.hh
nurettin/libnuwen
5b3012d9e75552c372a4d09b218b7af04a928e68
[ "BSL-1.0" ]
9
2019-09-17T10:33:58.000Z
2021-07-29T10:03:42.000Z
arith.hh
nurettin/libnuwen
5b3012d9e75552c372a4d09b218b7af04a928e68
[ "BSL-1.0" ]
null
null
null
arith.hh
nurettin/libnuwen
5b3012d9e75552c372a4d09b218b7af04a928e68
[ "BSL-1.0" ]
1
2019-10-05T04:31:22.000Z
2019-10-05T04:31:22.000Z
// Copyright Stephan T. Lavavej, http://nuwen.net . // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE_1_0.txt or copy at // http://boost.org/LICENSE_1_0.txt . #ifndef PHAM_ARITH_HH #define PHAM_ARITH_HH #include "compiler.hh" #ifdef NUWEN_PLATFORM_MSVC #pragma once #endif // Based on the ANSI C Arithmetic Coding Library by Fred Wheeler, // which was adapted from the program in "Arithmetic Coding For Data // Compression", by Ian H. Witten, Radford M. Neal, and John G. Cleary, // Communications Of The ACM, June 1987, Vol. 30, No. 6. #include "typedef.hh" #include "vector.hh" #include "external_begin.hh" #include <boost/utility.hpp> #include "external_end.hh" namespace nuwen { inline vuc_t arith(const vuc_t& v); inline vuc_t unarith(const vuc_t& v); } namespace pham { namespace arith { // The triple of (CODE_VALUE_BITS, MAX_FREQUENCY, INCREMENT_VALUE) is deeply magic. // It controls how much compression is achieved by BWT/MTF-2/ZLE/Arith. // The CACM paper explains that when frequency counts are represented in F bits, // code values are represented in C bits, and arithmetic is performed with // P bits of precision, the following must hold: F <= C - 2 and F + C <= P. // For sl_t arithmetic, P = 31, so F = 14 and C = 16 are possible. // For ul_t arithmetic, P = 32, so F = 15 and C = 17 are possible. // CODE_VALUE_BITS is C, while MAX_FREQUENCY may be as large as 2^F - 1. // As MAX_FREQUENCY becomes larger, the arithmetic coder gains a more precise // memory (its model of the frequencies becomes closer to the true, unscaled // frequencies), but the arithmetic coder also becomes less adaptive, as // rescalings are forced less frequently. Adaptiveness is good for compressing // BWT/MTF-2/ZLE data, which consists of lengthy stretches of "boring" low bytes, // interspersed with bursts of "exciting" high bytes. When the arithmetic coder // adapts quickly, better compression is achieved. A generalization of the // CACM model can achieve the best of both worlds: use the largest possible // MAX_FREQUENCY to give the coder a good memory, but increment the frequency counts // by more than 1. This forces more frequent rescaling. // (16, 16383, 1): Used by the CACM code (as well as Fred Wheeler's). As they used // sl_t arithmetic, this was "maximally" precise but not very adaptive. // (16, 8192, 16): Suggested by Fenwick, this forces rescaling 32x more often, // at the cost of precision. // (16, 16383, 32): Used by the first libnuwen implementation, 1.0.22.0. Combines // Fenwick's rescaling with CACM's precision. // (17, 32767, 1): Used by libnuwen 1.0.23.0 through 1.0.28.0. I reread the CACM // paper and realized that ul_t arithmetic allowed higher precision. // (17, 32767, 64): Used by libnuwen 2.0.0.0 and beyond. Combines maximum precision // with Fenwick's frequent rescaling. // Here is how BWT/MTF-2/ZLE/Arith behaves on suall10.txt (9873495 bytes) // with the various triples: // CACM (16, 16383, 1): 2073812 bytes, 1.680 bits/byte: The untuned baseline. // Fenwick (16, 8192, 16): 2050015 bytes, 1.661 bits/byte: A clear improvement. // 1.0.22.0 (16, 16383, 32): 2033592 bytes, 1.648 bits/byte: Even better. // 1.0.23.0 (17, 32767, 1): 2078591 bytes, 1.684 bits/byte: Crippling regression. // 2.0.0.0 (17, 32767, 64): 2026462 bytes, 1.642 bits/byte: Best of all worlds. const nuwen::ul_t CODE_VALUE_BITS = 17; const nuwen::ul_t MAX_FREQUENCY = 32767; const nuwen::ul_t INCREMENT_VALUE = 64; const nuwen::ul_t TOP_VALUE = (1 << CODE_VALUE_BITS) - 1; const nuwen::ul_t FIRST_QTR = TOP_VALUE / 4 + 1; const nuwen::ul_t HALF = 2 * FIRST_QTR; const nuwen::ul_t THIRD_QTR = 3 * FIRST_QTR; typedef nuwen::us_t symbol_t; const symbol_t SENTINEL = 256; const symbol_t NUM_SYMBOLS = 257; class model : public boost::noncopyable { public: model() { for (nuwen::ul_t i = 0; i < NUM_SYMBOLS; ++i) { m_freq[i] = 1; } for (nuwen::ul_t i = 0; i < NUM_SYMBOLS + 1; ++i) { m_cfreq[i] = NUM_SYMBOLS - i; } } nuwen::ul_t operator[](const symbol_t i) const { return m_cfreq[i]; } void update(const symbol_t sym) { // The CACM code used a hardcoded increment value of 1 and wrote this test // (using current terminology) as m_cfreq[0] == MAX_FREQUENCY, which was correct. // libnuwen 1.0.28.0 and earlier used a generalized INCREMENT_VALUE and wrote this test // (using current terminology) as m_cfreq[0] >= MAX_FREQUENCY, which was WRONG. // The correct generalization is below; an invariant of the model is that // m_cfreq[0] is ALWAYS <= MAX_FREQUENCY. If we detect that adding INCREMENT_VALUE // will destroy this invariant, we must rescale so that the invariant will be // maintained. if (m_cfreq[0] + INCREMENT_VALUE > MAX_FREQUENCY) { nuwen::ul_t cum = 0; m_cfreq[NUM_SYMBOLS] = 0; for (int i = NUM_SYMBOLS - 1; i >= 0; --i) { m_freq[i] = (m_freq[i] + 1) / 2; cum += m_freq[i]; m_cfreq[i] = cum; } } m_freq[sym] += INCREMENT_VALUE; for (int i = 0; i < sym + 1; ++i) { m_cfreq[i] += INCREMENT_VALUE; } } private: nuwen::ul_t m_freq[NUM_SYMBOLS]; nuwen::ul_t m_cfreq[NUM_SYMBOLS + 1]; }; class encoder : public boost::noncopyable { public: encoder() : m_low(0), m_high(TOP_VALUE), m_fbits(0), m_out(), m_acm() { } void encode(const symbol_t sym) { const nuwen::ul_t range = m_high - m_low + 1; m_high = m_low + range * m_acm[sym] / m_acm[0] - 1; m_low = m_low + range * m_acm[static_cast<symbol_t>(sym + 1)] / m_acm[0]; while (true) { if (m_high < HALF) { bit_plus_follow(0); } else if (m_low >= HALF) { bit_plus_follow(1); m_low -= HALF; m_high -= HALF; } else if (m_low >= FIRST_QTR && m_high < THIRD_QTR) { ++m_fbits; m_low -= FIRST_QTR; m_high -= FIRST_QTR; } else { break; } m_low = 2 * m_low; m_high = 2 * m_high + 1; } m_acm.update(sym); } nuwen::vuc_t finalize() { ++m_fbits; bit_plus_follow(m_low >= FIRST_QTR); return m_out.vuc(); } private: void bit_plus_follow(const bool bit) { m_out.push_back(bit); while (m_fbits > 0) { m_out.push_back(!bit); --m_fbits; } } nuwen::ul_t m_low; nuwen::ul_t m_high; nuwen::ul_t m_fbits; nuwen::pack::packed_bits m_out; model m_acm; }; class decoder : public boost::noncopyable { public: decoder(const nuwen::vuc_ci_t start, const nuwen::vuc_ci_t finish) : m_curr(start), m_shift(7), m_end(finish), m_value(0), m_low(0), m_high(TOP_VALUE), m_acm() { for (nuwen::ul_t i = 0; i < CODE_VALUE_BITS; ++i) { m_value <<= 1; m_value += input_bit(); } } symbol_t decode() { const nuwen::ul_t range = m_high - m_low + 1; const nuwen::ul_t cum = ((m_value - m_low + 1) * m_acm[0] - 1) / range; symbol_t sym; for (sym = 0; m_acm[static_cast<symbol_t>(sym + 1)] > cum; ++sym) { } m_high = m_low + range * m_acm[sym] / m_acm[0] - 1; m_low = m_low + range * m_acm[static_cast<symbol_t>(sym + 1)] / m_acm[0]; while (true) { if (m_high < HALF) { } else if (m_low >= HALF) { m_value -= HALF; m_low -= HALF; m_high -= HALF; } else if (m_low >= FIRST_QTR && m_high < THIRD_QTR) { m_value -= FIRST_QTR; m_low -= FIRST_QTR; m_high -= FIRST_QTR; } else { break; } m_low = 2 * m_low; m_high = 2 * m_high + 1; m_value = 2 * m_value + input_bit(); } m_acm.update(sym); return sym; } private: bool input_bit() { if (m_curr != m_end) { const bool ret = *m_curr >> m_shift & 1; if (m_shift == 0) { m_shift = 7; ++m_curr; } else { --m_shift; } return ret; } else { return 0; } } nuwen::vuc_ci_t m_curr; nuwen::uc_t m_shift; nuwen::vuc_ci_t m_end; nuwen::ul_t m_value; nuwen::ul_t m_low; nuwen::ul_t m_high; model m_acm; }; } } inline nuwen::vuc_t nuwen::arith(const vuc_t& v) { pham::arith::encoder ae; for (vuc_ci_t i = v.begin(); i != v.end(); ++i) { ae.encode(*i); } ae.encode(pham::arith::SENTINEL); return ae.finalize(); } inline nuwen::vuc_t nuwen::unarith(const vuc_t& v) { pham::arith::decoder ad(v.begin(), v.end()); vuc_t ret; while (true) { const pham::arith::symbol_t decoded = ad.decode(); if (decoded != pham::arith::SENTINEL) { ret.push_back(static_cast<uc_t>(decoded)); } else { return ret; } } } #endif // Idempotency
36.298305
110
0.519518
[ "vector", "model" ]
1db9711e7423e32741ac12fe1c4b3019b7abbe7f
8,798
hpp
C++
include/mango/math/vector256_int32x8.hpp
NeRdTheNed/mango
ec7fde75fc0daf642df7c4efd8f652853c6deee3
[ "Zlib" ]
null
null
null
include/mango/math/vector256_int32x8.hpp
NeRdTheNed/mango
ec7fde75fc0daf642df7c4efd8f652853c6deee3
[ "Zlib" ]
null
null
null
include/mango/math/vector256_int32x8.hpp
NeRdTheNed/mango
ec7fde75fc0daf642df7c4efd8f652853c6deee3
[ "Zlib" ]
1
2021-12-19T18:30:06.000Z
2021-12-19T18:30:06.000Z
/* MANGO Multimedia Development Platform Copyright (C) 2012-2020 Twilight Finland 3D Oy Ltd. All rights reserved. */ #pragma once #include <mango/math/vector.hpp> namespace mango::math { template <> struct Vector<s32, 8> { using VectorType = simd::s32x8; using ScalarType = s32; enum { VectorSize = 8 }; VectorType m; ScalarType& operator [] (size_t index) { assert(index < VectorSize); return data()[index]; } ScalarType operator [] (size_t index) const { assert(index < VectorSize); return data()[index]; } ScalarType* data() { return reinterpret_cast<ScalarType *>(this); } const ScalarType* data() const { return reinterpret_cast<const ScalarType *>(this); } explicit Vector() {} Vector(s32 s) : m(simd::s32x8_set(s)) { } Vector(s32 s0, s32 s1, s32 s2, s32 s3, s32 s4, s32 s5, s32 s6, s32 s7) : m(simd::s32x8_set(s0, s1, s2, s3, s4, s5, s6, s7)) { } Vector(simd::s32x8 v) : m(v) { } template <typename T, int I> Vector& operator = (const ScalarAccessor<ScalarType, T, I>& accessor) { *this = ScalarType(accessor); return *this; } Vector(const Vector& v) = default; Vector& operator = (const Vector& v) { m = v.m; return *this; } Vector& operator = (simd::s32x8 v) { m = v; return *this; } Vector& operator = (s32 s) { m = simd::s32x8_set(s); return *this; } operator simd::s32x8 () const { return m; } #ifdef int256_is_hardware_vector operator simd::s32x8::vector () const { return m.data; } #endif static Vector ascend() { return Vector(0, 1, 2, 3, 4, 5, 6, 7); } }; static inline const Vector<s32, 8> operator + (Vector<s32, 8> v) { return v; } static inline Vector<s32, 8> operator - (Vector<s32, 8> v) { return simd::neg(v); } static inline Vector<s32, 8>& operator += (Vector<s32, 8>& a, Vector<s32, 8> b) { a = simd::add(a, b); return a; } static inline Vector<s32, 8>& operator -= (Vector<s32, 8>& a, Vector<s32, 8> b) { a = simd::sub(a, b); return a; } static inline Vector<s32, 8> operator + (Vector<s32, 8> a, Vector<s32, 8> b) { return simd::add(a, b); } static inline Vector<s32, 8> operator - (Vector<s32, 8> a, Vector<s32, 8> b) { return simd::sub(a, b); } static inline Vector<s32, 8> unpacklo(Vector<s32, 8> a, Vector<s32, 8> b) { return simd::unpacklo(a, b); } static inline Vector<s32, 8> unpackhi(Vector<s32, 8> a, Vector<s32, 8> b) { return simd::unpackhi(a, b); } static inline Vector<s32, 8> abs(Vector<s32, 8> a) { return simd::abs(a); } static inline Vector<s32, 8> abs(Vector<s32, 8> a, mask32x8 mask) { return simd::abs(a, mask); } static inline Vector<s32, 8> abs(Vector<s32, 8> a, mask32x8 mask, Vector<s32, 8> value) { return simd::abs(a, mask, value); } static inline Vector<s32, 8> add(Vector<s32, 8> a, Vector<s32, 8> b, mask32x8 mask) { return simd::add(a, b, mask); } static inline Vector<s32, 8> add(Vector<s32, 8> a, Vector<s32, 8> b, mask32x8 mask, Vector<s32, 8> value) { return simd::add(a, b, mask, value); } static inline Vector<s32, 8> sub(Vector<s32, 8> a, Vector<s32, 8> b, mask32x8 mask) { return simd::sub(a, b, mask); } static inline Vector<s32, 8> sub(Vector<s32, 8> a, Vector<s32, 8> b, mask32x8 mask, Vector<s32, 8> value) { return simd::sub(a, b, mask, value); } static inline Vector<s32, 8> adds(Vector<s32, 8> a, Vector<s32, 8> b) { return simd::adds(a, b); } static inline Vector<s32, 8> adds(Vector<s32, 8> a, Vector<s32, 8> b, mask32x8 mask) { return simd::adds(a, b, mask); } static inline Vector<s32, 8> adds(Vector<s32, 8> a, Vector<s32, 8> b, mask32x8 mask, Vector<s32, 8> value) { return simd::adds(a, b, mask, value); } static inline Vector<s32, 8> subs(Vector<s32, 8> a, Vector<s32, 8> b) { return simd::subs(a, b); } static inline Vector<s32, 8> subs(Vector<s32, 8> a, Vector<s32, 8> b, mask32x8 mask) { return simd::subs(a, b, mask); } static inline Vector<s32, 8> subs(Vector<s32, 8> a, Vector<s32, 8> b, mask32x8 mask, Vector<s32, 8> value) { return simd::subs(a, b, mask, value); } static inline Vector<s32, 8> hadd(Vector<s32, 8> a, Vector<s32, 8> b) { return simd::hadd(a, b); } static inline Vector<s32, 8> hsub(Vector<s32, 8> a, Vector<s32, 8> b) { return simd::hsub(a, b); } static inline Vector<s32, 8> min(Vector<s32, 8> a, Vector<s32, 8> b) { return simd::min(a, b); } static inline Vector<s32, 8> min(Vector<s32, 8> a, Vector<s32, 8> b, mask32x8 mask) { return simd::min(a, b, mask); } static inline Vector<s32, 8> min(Vector<s32, 8> a, Vector<s32, 8> b, mask32x8 mask, Vector<s32, 8> value) { return simd::min(a, b, mask, value); } static inline Vector<s32, 8> max(Vector<s32, 8> a, Vector<s32, 8> b) { return simd::max(a, b); } static inline Vector<s32, 8> max(Vector<s32, 8> a, Vector<s32, 8> b, mask32x8 mask) { return simd::max(a, b, mask); } static inline Vector<s32, 8> max(Vector<s32, 8> a, Vector<s32, 8> b, mask32x8 mask, Vector<s32, 8> value) { return simd::max(a, b, mask, value); } static inline Vector<s32, 8> clamp(Vector<s32, 8> a, Vector<s32, 8> low, Vector<s32, 8> high) { return simd::clamp(a, low, high); } // ------------------------------------------------------------------ // bitwise operators // ------------------------------------------------------------------ static inline Vector<s32, 8> nand(Vector<s32, 8> a, Vector<s32, 8> b) { return simd::bitwise_nand(a, b); } static inline Vector<s32, 8> operator & (Vector<s32, 8> a, Vector<s32, 8> b) { return simd::bitwise_and(a, b); } static inline Vector<s32, 8> operator | (Vector<s32, 8> a, Vector<s32, 8> b) { return simd::bitwise_or(a, b); } static inline Vector<s32, 8> operator ^ (Vector<s32, 8> a, Vector<s32, 8> b) { return simd::bitwise_xor(a, b); } static inline Vector<s32, 8> operator ~ (Vector<s32, 8> a) { return simd::bitwise_not(a); } // ------------------------------------------------------------------ // compare / select // ------------------------------------------------------------------ static inline mask32x8 operator > (Vector<s32, 8> a, Vector<s32, 8> b) { return simd::compare_gt(a, b); } static inline mask32x8 operator < (Vector<s32, 8> a, Vector<s32, 8> b) { return simd::compare_gt(b, a); } static inline mask32x8 operator == (Vector<s32, 8> a, Vector<s32, 8> b) { return simd::compare_eq(a, b); } static inline mask32x8 operator >= (Vector<s32, 8> a, Vector<s32, 8> b) { return simd::compare_ge(a, b); } static inline mask32x8 operator <= (Vector<s32, 8> a, Vector<s32, 8> b) { return simd::compare_le(b, a); } static inline mask32x8 operator != (Vector<s32, 8> a, Vector<s32, 8> b) { return simd::compare_neq(a, b); } static inline Vector<s32, 8> select(mask32x8 mask, Vector<s32, 8> a, Vector<s32, 8> b) { return simd::select(mask, a, b); } // ------------------------------------------------------------------ // shift // ------------------------------------------------------------------ static inline Vector<s32, 8> operator << (Vector<s32, 8> a, int b) { return simd::sll(a, b); } static inline Vector<s32, 8> operator >> (Vector<s32, 8> a, int b) { return simd::sra(a, b); } static inline Vector<s32, 8> operator << (Vector<s32, 8> a, Vector<u32, 8> b) { return simd::sll(a, b); } static inline Vector<s32, 8> operator >> (Vector<s32, 8> a, Vector<u32, 8> b) { return simd::sra(a, b); } } // namespace mango::math
25.137143
110
0.505683
[ "vector", "3d" ]
1dbbcc3663bf9753230ebcd3eb6486c8ec2bf2d0
809
cpp
C++
Algorithms on Strings/Programming-Assignment-2/suffix_array/suffix_array.cpp
hovmikayelyan/Data_Structures_and_Algorithms
abfd3c63f8bce200c2379c44e755e53611f26ac7
[ "MIT" ]
26
2019-05-18T09:59:02.000Z
2022-01-09T01:04:10.000Z
LearningSeries/UCSanDeigoAlgorithmsCourse/String Algorithms/Week 2/suffix_array/suffix_array.cpp
pawan-nirpal-031/Algorithms-And-ProblemSolving
24ce9649345dabe7275920f6912e410efc2c8e84
[ "Apache-2.0" ]
null
null
null
LearningSeries/UCSanDeigoAlgorithmsCourse/String Algorithms/Week 2/suffix_array/suffix_array.cpp
pawan-nirpal-031/Algorithms-And-ProblemSolving
24ce9649345dabe7275920f6912e410efc2c8e84
[ "Apache-2.0" ]
8
2020-01-19T15:45:07.000Z
2021-01-09T08:51:41.000Z
#include <algorithm> #include <iostream> #include <string> #include <vector> #include <utility> using std::cin; using std::cout; using std::endl; using std::make_pair; using std::pair; using std::string; using std::vector; // Build suffix array of the string text and // return a vector result of the same length as the text // such that the value result[i] is the index (0-based) // in text where the i-th lexicographically smallest // suffix of text starts. vector<int> BuildSuffixArray(const string& text) { vector<int> result; // Implement this function yourself return result; } int main() { string text; cin >> text; vector<int> suffix_array = BuildSuffixArray(text); for (int i = 0; i < suffix_array.size(); ++i) { cout << suffix_array[i] << ' '; } cout << endl; return 0; }
22.472222
56
0.68974
[ "vector" ]
1dc0dc9c8255e975bd8ca6d75129aad325dfad8d
10,399
cpp
C++
cxx/isce3/core/EulerAngles.cpp
piyushrpt/isce3
1741af321470cb5939693459765d11a19c5c6fc2
[ "Apache-2.0" ]
null
null
null
cxx/isce3/core/EulerAngles.cpp
piyushrpt/isce3
1741af321470cb5939693459765d11a19c5c6fc2
[ "Apache-2.0" ]
null
null
null
cxx/isce3/core/EulerAngles.cpp
piyushrpt/isce3
1741af321470cb5939693459765d11a19c5c6fc2
[ "Apache-2.0" ]
null
null
null
//-*- C++ -*- //-*- coding: utf-8 -*- // // Author: Bryan V. Riel // Copyright 2018 // // std #include <iostream> #include <string> #include <cmath> #include <map> // pyre #include <pyre/journal.h> #include "Attitude.h" #include "DenseMatrix.h" #include "EulerAngles.h" #include "Quaternion.h" #include "Utilities.h" #include "Vector.h" constexpr auto EulerAngles_t = isce3::core::Attitude::Type::EulerAngles_t; /** @param[in] yaw_orientation Can be "normal" or "center" */ isce3::core::EulerAngles:: EulerAngles(const std::string yaw_orientation) : Attitude(EulerAngles_t) { if (yaw_orientation.compare("normal") == 0 || yaw_orientation.compare("center") == 0) { yawOrientation(yaw_orientation); } else { std::cerr << "Unsupported yaw orientation. Must be normal or center." << std::endl; throw std::invalid_argument("Unsupported yaw orientation."); } } // Constructor with data vectors /** @param[in] time Vector of observation times in seconds since reference epoch * @param[in] yaw Vector of yaw angles * @param[in] pitch Vector of pitch angles * @param[in] roll Vector of roll angles */ isce3::core::EulerAngles:: EulerAngles(const std::vector<double> & time, const std::vector<double> & yaw, const std::vector<double> & pitch, const std::vector<double> & roll, const std::string yaw_orientation) : EulerAngles(yaw_orientation) { // Call setter for data this->data(time, yaw, pitch, roll); } // Copy constructor /** @param[in] euler EulerAngles object */ isce3::core::EulerAngles:: EulerAngles(const EulerAngles & euler) : Attitude(EulerAngles_t), _time(euler.time()), _yaw(euler.yaw()), _pitch(euler.pitch()), _roll(euler.roll()) { const std::string yaw_orientation = euler.yawOrientation(); if (yaw_orientation.compare("normal") == 0 || yaw_orientation.compare("center") == 0) { yawOrientation(yaw_orientation); } else { std::cerr << "Unsupported yaw orientation. Must be normal or center." << std::endl; throw std::invalid_argument("Unsupported yaw orientation."); } } // Comparison operator bool isce3::core::EulerAngles:: operator==(const EulerAngles & other) const { // Easy checks first bool equal = this->nVectors() == other.nVectors(); equal *= _refEpoch == other.refEpoch(); if (!equal) { return false; } // If we pass the easy checks, check the contents for (size_t i = 0; i < this->nVectors(); ++i) { equal *= isce3::core::compareFloatingPoint(_time[i], other.time()[i]); equal *= isce3::core::compareFloatingPoint(_yaw[i], other.yaw()[i]); equal *= isce3::core::compareFloatingPoint(_pitch[i], other.pitch()[i]); equal *= isce3::core::compareFloatingPoint(_roll[i], other.roll()[i]); } return equal; } // Assignment operator /** @param[in] euler EulerAngles object */ isce3::core::EulerAngles & isce3::core::EulerAngles:: operator=(const EulerAngles & euler) { _time = euler.time(); _yaw = euler.yaw(); _pitch = euler.pitch(); _roll = euler.roll(); _refEpoch = euler.refEpoch(); yawOrientation(euler.yawOrientation()); return *this; } // Set data after construction /** @param[in] time Vector of observation times in seconds since reference epoch * @param[in] yaw Vector of yaw angles * @param[in] pitch Vector of pitch angles * @param[in] roll Vector of roll angles */ void isce3::core::EulerAngles:: data(const std::vector<double> & time, const std::vector<double> & yaw, const std::vector<double> & pitch, const std::vector<double> & roll) { // Check size consistency const bool flag = (time.size() == yaw.size()) && (yaw.size() == pitch.size()) && (pitch.size() == roll.size()); if (!flag) { pyre::journal::error_t errorChannel("isce.core.EulerAngles"); errorChannel << pyre::journal::at(__HERE__) << "Inconsistent vector sizes" << pyre::journal::endl; } // Copy vectors _time = time; _yaw = yaw; _pitch = pitch; _roll = roll; } /** @param[in] tintp Seconds since reference epoch * @param[out] oyaw Interpolated yaw angle * @param[out] opitch Interpolated pitch angle * @param[out] oroll Interpolated roll angle */ void isce3::core::EulerAngles:: ypr(double tintp, double & oyaw, double & opitch, double & oroll) { // Check we have enough state vectors const int n = nVectors(); if (n < 9) { pyre::journal::error_t errorChannel("isce.core.EulerAngles"); errorChannel << pyre::journal::at(__HERE__) << "EulerAngles::ypr requires at least 9 state vectors to interpolate. " << "EulerAngles only contains " << n << pyre::journal::endl; } // Check time bounds; warn if invalid time requested if (tintp < _time[0] || tintp > _time[n-1]) { pyre::journal::warning_t warnChannel("isce.core.EulerAngles"); warnChannel << pyre::journal::at(__HERE__) << "Requested out-of-bounds time. Attitude will be invalid." << pyre::journal::endl; return; } // Get nearest time index int idx = -1; for (int i = 0; i < n; ++i) { if (_time[i] >= tintp) { idx = i; break; } } idx -= 5; idx = std::min(std::max(idx, 0), n - 9); // Load inteprolation arrays std::vector<double> t(9), yaw(9), pitch(9), roll(9); for (int i = 0; i < 9; i++) { t[i] = _time[idx+i]; yaw[i] = _yaw[idx+i]; pitch[i] = _pitch[idx+i]; roll[i] = _roll[idx+i]; } const double trel = (8. * (tintp - t[0])) / (t[8] - t[0]); double teller = 1.0; for (int i = 0; i < 9; i++) teller *= trel - i; // Perform polynomial interpolation oyaw = 0.0; opitch = 0.0; oroll = 0.0; if (teller == 0.0) { oyaw = yaw[int(trel)]; opitch = pitch[int(trel)]; oroll = roll[int(trel)]; } else { const std::vector<double> noemer = { 40320.0, -5040.0, 1440.0, -720.0, 576.0, -720.0, 1440.0, -5040.0, 40320.0 }; for (int i = 0; i < 9; i++) { double coeff = (teller / noemer[i]) / (trel - i); oyaw += coeff * yaw[i]; opitch += coeff * pitch[i]; oroll += coeff * roll[i]; } } } // Rotation matrix for a given sequence and time /** @param[in] tintp Seconds since reference epoch * @param[in] sequence String of rotation sequence * @param[in] dyaw Yaw perturbation * @param[in] dpitch Pitch perturbation * @param[in] d2 (Not used) * @param[in] d3 (Not used) * @param[out] R Rotation matrix for given sequence */ isce3::core::cartmat_t isce3::core::EulerAngles:: rotmat(double tintp, const std::string sequence, double dyaw, double dpitch, double, double) { // Interpolate to get YPR angles double yaw, pitch, roll; this->ypr(tintp, yaw, pitch, roll); // Construct map for Euler angles to elementary rotation matrices std::map<const char, cartmat_t> R_map; R_map['y'] = T3(yaw + dyaw); R_map['p'] = T2(pitch + dpitch); R_map['r'] = T1(roll); // Build composite matrix return R_map[sequence[0]] * R_map[sequence[1]] * R_map[sequence[2]]; } // Rotation around Z-axis isce3::core::cartmat_t isce3::core::EulerAngles::T3(double angle) { const double cos = std::cos(angle); const double sin = std::sin(angle); return cartmat_t {{ {cos, -sin, 0.0}, {sin, cos, 0.0}, {0.0, 0.0, 1.0} }}; } // Rotation around Y-axis isce3::core::cartmat_t isce3::core::EulerAngles::T2(double angle) { const double cos = std::cos(angle); const double sin = std::sin(angle); return cartmat_t {{ {cos, 0.0, sin}, {0.0, 1.0, 0.0}, {-sin, 0.0, cos} }}; } // Rotation around X-axis isce3::core::cartmat_t isce3::core::EulerAngles::T1(double angle) { const double cos = std::cos(angle); const double sin = std::sin(angle); cartmat_t T{{ {1.0, 0.0, 0.0}, {0.0, cos, -sin}, {0.0, sin, cos} }}; return T; } // Extract YPR angles from a rotation matrix isce3::core::cartesian_t isce3::core::EulerAngles::rotmat2ypr(const cartmat_t & R) { const double sy = std::sqrt(R[0][0]*R[0][0] + R[1][0]*R[1][0]); double yaw, pitch, roll; if (sy >= 1.0e-6) { roll = std::atan2(R[2][1], R[2][2]); pitch = std::atan2(-R[2][0], sy); yaw = std::atan2(R[1][0], R[0][0]); } else { roll = std::atan2(-R[1][2], R[1][1]); pitch = std::atan2(-R[2][0], sy); yaw = 0.0; } // Make vector and return cartesian_t angles{yaw, pitch, roll}; return angles; } // Return quaternion elements at a given time; multiply by -1 to get consistent signs /** @param[in] tintp Seconds since reference epoch * @param[out] q Vector of quaternion elements */ std::vector<double> isce3::core::EulerAngles::toQuaternionElements(double tintp) { // Interpolate to get YPR angles double yaw, pitch, roll; this->ypr(tintp, yaw, pitch, roll); // Compute trig quantities const double cy = std::cos(yaw * 0.5); const double sy = std::sin(yaw * 0.5); const double cp = std::cos(pitch * 0.5); const double sp = std::sin(pitch * 0.5); const double cr = std::cos(roll * 0.5); const double sr = std::sin(roll * 0.5); // Make a vector std::vector<double> q = { -1.0 * (cy * cr * cp + sy * sr * sp), -1.0 * (cy * sr * cp - sy * cr * sp), -1.0 * (cy * cr * sp + sy * sr * cp), -1.0 * (sy * cr * cp - cy * sr * sp) }; return q; } // Return quaternion representation for all epochs /** @param[out] quat Quaternion instance */ isce3::core::Quaternion isce3::core::EulerAngles::toQuaternion() { // Vector to fill std::vector<double> qvec(nVectors()*4); // Loop over epochs and convert to quaternion values for (size_t i = 0; i < nVectors(); ++i) { std::vector<double> q = toQuaternionElements(_time[i]); for (size_t j = 0; j < 4; ++j) { qvec[i*4 + j] = q[j]; } } // Make a quaternion Quaternion quat(_time, qvec); return quat; } // end of file
31.416918
91
0.589287
[ "object", "vector" ]
1dc40d729ff144d68c89d485594bb33683baa52b
1,574
cpp
C++
dlls/noffice/flashlightspot.cpp
malortie/hl-nato
1c6f6fa4d6f72612d4d28ddb459eb8d074154746
[ "Apache-2.0" ]
null
null
null
dlls/noffice/flashlightspot.cpp
malortie/hl-nato
1c6f6fa4d6f72612d4d28ddb459eb8d074154746
[ "Apache-2.0" ]
null
null
null
dlls/noffice/flashlightspot.cpp
malortie/hl-nato
1c6f6fa4d6f72612d4d28ddb459eb8d074154746
[ "Apache-2.0" ]
null
null
null
/*** * * Copyright (c) 1996-2001, Valve LLC. All rights reserved. * * This product contains software technology licensed from Id * Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. * All Rights Reserved. * * Use, distribution, and modification of this source code and/or resulting * object code is restricted to non-commercial enhancements to products from * Valve LLC. All other use, distribution, or modification is prohibited * without written permission from Valve LLC. * ****/ #include "extdll.h" #include "util.h" #include "cbase.h" #include "weapons.h" #include "player.h" #include "gamerules.h" #include "flashlightspot.h" LINK_ENTITY_TO_CLASS(flashlight_spot, CFlashlightSpot); //========================================================= //========================================================= CFlashlightSpot *CFlashlightSpot::CreateSpot(void) { CFlashlightSpot *pSpot = GetClassPtr((CFlashlightSpot *)NULL); pSpot->Spawn(); pSpot->pev->classname = MAKE_STRING("flashlight_spot"); return pSpot; } //========================================================= //========================================================= void CFlashlightSpot::Spawn(void) { Precache(); pev->movetype = MOVETYPE_NONE; pev->solid = SOLID_NOT; pev->rendermode = kRenderGlow; // kRenderGlow pev->renderfx = kRenderFxNoDissipation; pev->renderamt = 128; pev->scale = 4; SET_MODEL(ENT(pev), "sprites/beam2.spr"); UTIL_SetOrigin(pev, pev->origin); }; void CFlashlightSpot::Precache(void) { PRECACHE_MODEL("sprites/beam2.spr"); };
26.677966
77
0.622618
[ "object", "solid" ]
1dc6b1b2bb6a5c2f038911d334a1ccd6b90483ed
4,534
cc
C++
serving/core/version_control/version_controller.cc
i4oolish/mindspore
dac3be31d0f2c0a3516200f47af30980e566601b
[ "Apache-2.0" ]
2
2020-08-12T16:14:40.000Z
2020-12-04T03:05:57.000Z
serving/core/version_control/version_controller.cc
dilingsong/mindspore
4276050f2494cfbf8682560a1647576f859991e8
[ "Apache-2.0" ]
null
null
null
serving/core/version_control/version_controller.cc
dilingsong/mindspore
4276050f2494cfbf8682560a1647576f859991e8
[ "Apache-2.0" ]
null
null
null
/** * Copyright 2020 Huawei Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "core/version_control/version_controller.h" #include <string> #include <iostream> #include <ctime> #include <memory> #include "util/file_system_operation.h" #include "include/infer_log.h" #include "core/server.h" namespace mindspore { namespace serving { volatile bool stop_poll = false; std::string GetVersionFromPath(const std::string &path) { std::string new_path = path; if (path.back() == '/') { new_path = path.substr(0, path.size() - 1); } std::string::size_type index = new_path.find_last_of("/"); std::string version = new_path.substr(index + 1); return version; } void PeriodicFunction::operator()() { while (true) { std::this_thread::sleep_for(std::chrono::milliseconds(poll_model_wait_seconds_ * 1000)); std::vector<std::string> SubDirs = GetAllSubDirs(models_path_); if (version_control_strategy_ == VersionController::VersionControllerStrategy::kLastest) { auto path = SubDirs.empty() ? models_path_ : SubDirs.back(); std::string model_version = GetVersionFromPath(path); time_t last_update_time = GetModifyTime(path); if (model_version != valid_models_.back()->GetModelVersion()) { MindSporeModelPtr model_ptr = std::make_shared<MindSporeModel>(valid_models_.front()->GetModelName(), path, model_version, last_update_time); valid_models_.back() = model_ptr; Session::Instance().Warmup(valid_models_.back()); } else { if (difftime(valid_models_.back()->GetLastUpdateTime(), last_update_time) < 0) { valid_models_.back()->SetLastUpdateTime(last_update_time); } } } else { // not support } if (stop_poll == true) { break; } } } VersionController::VersionController(int32_t poll_model_wait_seconds, const std::string &models_path, const std::string &model_name) : version_control_strategy_(kLastest), poll_model_wait_seconds_(poll_model_wait_seconds), models_path_(models_path), model_name_(model_name) {} void StopPollModelPeriodic() { stop_poll = true; } VersionController::~VersionController() { StopPollModelPeriodic(); if (poll_model_thread_.joinable()) { poll_model_thread_.join(); } } Status VersionController::Run() { Status ret; ret = CreateInitModels(); if (ret != SUCCESS) { return ret; } // disable periodic check // StartPollModelPeriodic(); return SUCCESS; } Status VersionController::CreateInitModels() { if (!DirOrFileExist(models_path_)) { MSI_LOG(ERROR) << "Model Path Not Exist!" << std::endl; return FAILED; } std::vector<std::string> SubDirs = GetAllSubDirs(models_path_); if (version_control_strategy_ == kLastest) { std::string model_version = GetVersionFromPath(models_path_); time_t last_update_time = GetModifyTime(models_path_); MindSporeModelPtr model_ptr = std::make_shared<MindSporeModel>(model_name_, models_path_, model_version, last_update_time); valid_models_.emplace_back(model_ptr); } else { for (auto &dir : SubDirs) { std::string model_version = GetVersionFromPath(dir); time_t last_update_time = GetModifyTime(dir); MindSporeModelPtr model_ptr = std::make_shared<MindSporeModel>(model_name_, dir, model_version, last_update_time); valid_models_.emplace_back(model_ptr); } } if (valid_models_.empty()) { MSI_LOG(ERROR) << "There is no valid model for serving"; return FAILED; } auto ret = Session::Instance().Warmup(valid_models_.back()); return ret; } void VersionController::StartPollModelPeriodic() { poll_model_thread_ = std::thread( PeriodicFunction(poll_model_wait_seconds_, models_path_, version_control_strategy_, std::ref(valid_models_))); } void VersionController::StopPollModelPeriodic() {} } // namespace serving } // namespace mindspore
33.835821
120
0.699382
[ "vector", "model" ]
1dc71f83aeb6254ebd7d67bdfa33748ce53fe4a0
54,402
cpp
C++
lib/fizzy/execute.cpp
poemm/fizzy
f384303dc6b594bdf36ed868ffdfebe912366604
[ "Apache-2.0" ]
null
null
null
lib/fizzy/execute.cpp
poemm/fizzy
f384303dc6b594bdf36ed868ffdfebe912366604
[ "Apache-2.0" ]
null
null
null
lib/fizzy/execute.cpp
poemm/fizzy
f384303dc6b594bdf36ed868ffdfebe912366604
[ "Apache-2.0" ]
null
null
null
// Fizzy: A fast WebAssembly interpreter // Copyright 2019-2020 The Fizzy Authors. // SPDX-License-Identifier: Apache-2.0 #include "execute.hpp" #include "limits.hpp" #include "stack.hpp" #include "types.hpp" #include <algorithm> #include <cassert> #include <cstring> #include <stack> namespace fizzy { namespace { struct LabelContext { const Instr* pc = nullptr; ///< The jump target instruction. const uint8_t* immediate = nullptr; ///< The jump target immediate pointer. size_t arity = 0; ///< The type arity of the label instruction. size_t stack_height = 0; ///< The stack height at the label instruction. }; using LabelStack = std::stack<LabelContext, std::vector<LabelContext>>; inline bool operator==(const FuncType& lhs, const FuncType& rhs) { return lhs.inputs == rhs.inputs && lhs.outputs == rhs.outputs; } inline bool operator!=(const FuncType& lhs, const FuncType& rhs) { return !(lhs == rhs); } void match_imported_functions(const std::vector<FuncType>& module_imported_types, const std::vector<ExternalFunction>& imported_functions) { if (module_imported_types.size() != imported_functions.size()) { throw instantiate_error("Module requires " + std::to_string(module_imported_types.size()) + " imported functions, " + std::to_string(imported_functions.size()) + " provided"); } for (size_t i = 0; i < imported_functions.size(); ++i) { if (module_imported_types[i] != imported_functions[i].type) { throw instantiate_error("Function " + std::to_string(i) + " type doesn't match module's imported function type"); } } } void match_limits(const Limits& external_limits, const Limits& module_limits) { if (external_limits.min < module_limits.min) throw instantiate_error("Provided import's min is below import's min defined in module."); if (!module_limits.max.has_value()) return; if (external_limits.max.has_value() && *external_limits.max <= *module_limits.max) return; throw instantiate_error("Provided import's max is above import's max defined in module."); } void match_imported_tables(const std::vector<Table>& module_imported_tables, const std::vector<ExternalTable>& imported_tables) { assert(module_imported_tables.size() <= 1); if (imported_tables.size() > 1) throw instantiate_error("Only 1 imported table is allowed."); if (module_imported_tables.empty()) { if (!imported_tables.empty()) { throw instantiate_error( "Trying to provide imported table to a module that doesn't define one."); } } else { if (imported_tables.empty()) throw instantiate_error("Module defines an imported table but none was provided."); match_limits(imported_tables[0].limits, module_imported_tables[0].limits); if (imported_tables[0].table == nullptr) throw instantiate_error("Provided imported table has a null pointer to data."); const auto size = imported_tables[0].table->size(); const auto min = imported_tables[0].limits.min; const auto& max = imported_tables[0].limits.max; if (size < min || (max.has_value() && size > *max)) throw instantiate_error("Provided imported table doesn't fit provided limits"); } } void match_imported_memories(const std::vector<Memory>& module_imported_memories, const std::vector<ExternalMemory>& imported_memories) { assert(module_imported_memories.size() <= 1); if (imported_memories.size() > 1) throw instantiate_error("Only 1 imported memory is allowed."); if (module_imported_memories.empty()) { if (!imported_memories.empty()) { throw instantiate_error( "Trying to provide imported memory to a module that doesn't define one."); } } else { if (imported_memories.empty()) throw instantiate_error("Module defines an imported memory but none was provided."); match_limits(imported_memories[0].limits, module_imported_memories[0].limits); if (imported_memories[0].data == nullptr) throw instantiate_error("Provided imported memory has a null pointer to data."); const auto size = imported_memories[0].data->size(); const auto min = imported_memories[0].limits.min; const auto& max = imported_memories[0].limits.max; if (size < min * PageSize || (max.has_value() && size > *max * PageSize)) throw instantiate_error("Provided imported memory doesn't fit provided limits"); } } void match_imported_globals(const std::vector<bool>& module_imports_mutability, const std::vector<ExternalGlobal>& imported_globals) { if (module_imports_mutability.size() != imported_globals.size()) { throw instantiate_error( "Module requires " + std::to_string(module_imports_mutability.size()) + " imported globals, " + std::to_string(imported_globals.size()) + " provided"); } for (size_t i = 0; i < imported_globals.size(); ++i) { if (imported_globals[i].is_mutable != module_imports_mutability[i]) { throw instantiate_error("Global " + std::to_string(i) + " mutability doesn't match module's global mutability"); } if (imported_globals[i].value == nullptr) { throw instantiate_error("Global " + std::to_string(i) + " has a null pointer to value"); } } } table_ptr allocate_table( const std::vector<Table>& module_tables, const std::vector<ExternalTable>& imported_tables) { static const auto table_delete = [](table_elements* t) noexcept { delete t; }; static const auto null_delete = [](table_elements*) noexcept {}; assert(module_tables.size() + imported_tables.size() <= 1); if (module_tables.size() == 1) return {new table_elements(module_tables[0].limits.min), table_delete}; else if (imported_tables.size() == 1) return {imported_tables[0].table, null_delete}; else return {nullptr, null_delete}; } std::tuple<bytes_ptr, size_t> allocate_memory(const std::vector<Memory>& module_memories, const std::vector<ExternalMemory>& imported_memories) { static const auto bytes_delete = [](bytes* b) noexcept { delete b; }; static const auto null_delete = [](bytes*) noexcept {}; assert(module_memories.size() + imported_memories.size() <= 1); if (module_memories.size() == 1) { const size_t memory_min = module_memories[0].limits.min; const size_t memory_max = (module_memories[0].limits.max.has_value() ? *module_memories[0].limits.max : MemoryPagesLimit); // FIXME: better error handling if ((memory_min > MemoryPagesLimit) || (memory_max > MemoryPagesLimit)) { throw instantiate_error("Cannot exceed hard memory limit of " + std::to_string(MemoryPagesLimit * PageSize) + " bytes."); } // NOTE: fill it with zeroes bytes_ptr memory{new bytes(memory_min * PageSize, 0), bytes_delete}; return {std::move(memory), memory_max}; } else if (imported_memories.size() == 1) { const size_t memory_min = imported_memories[0].limits.min; const size_t memory_max = (imported_memories[0].limits.max.has_value() ? *imported_memories[0].limits.max : MemoryPagesLimit); // FIXME: better error handling if ((memory_min > MemoryPagesLimit) || (memory_max > MemoryPagesLimit)) { throw instantiate_error("Imported memory limits cannot exceed hard memory limit of " + std::to_string(MemoryPagesLimit * PageSize) + " bytes."); } bytes_ptr memory{imported_memories[0].data, null_delete}; return {std::move(memory), memory_max}; } else { bytes_ptr memory{nullptr, null_delete}; return {std::move(memory), MemoryPagesLimit}; } } uint64_t eval_constant_expression(ConstantExpression expr, const std::vector<ExternalGlobal>& imported_globals, const std::vector<Global>& global_types, const std::vector<uint64_t>& globals) { if (expr.kind == ConstantExpression::Kind::Constant) return expr.value.constant; assert(expr.kind == ConstantExpression::Kind::GlobalGet); const auto global_idx = expr.value.global_index; const bool is_mutable = (global_idx < imported_globals.size() ? imported_globals[global_idx].is_mutable : global_types[global_idx - imported_globals.size()].is_mutable); if (is_mutable) throw instantiate_error("Constant expression can use global_get only for const globals."); if (global_idx < imported_globals.size()) return *imported_globals[global_idx].value; else return globals[global_idx - imported_globals.size()]; } void branch(uint32_t label_idx, LabelStack& labels, Stack<uint64_t>& stack, const Instr*& pc, const uint8_t*& immediates) noexcept { assert(labels.size() > label_idx); while (label_idx-- > 0) labels.pop(); // Drop skipped labels (does nothing for labelidx == 0). const auto label = labels.top(); labels.pop(); pc = label.pc; immediates = label.immediate; // When branch is taken, additional stack items must be dropped. assert(stack.size() >= label.stack_height + label.arity); if (label.arity != 0) { assert(label.arity == 1); const auto result = stack.peek(); stack.resize(label.stack_height); stack.push(result); } else stack.resize(label.stack_height); } const FuncType& function_type(const Instance& instance, FuncIdx idx) { assert(idx < instance.imported_functions.size() + instance.module.funcsec.size()); if (idx < instance.imported_functions.size()) return instance.imported_functions[idx].type; const auto type_idx = instance.module.funcsec[idx - instance.imported_functions.size()]; assert(type_idx < instance.module.typesec.size()); return instance.module.typesec[type_idx]; } template <class F> bool invoke_function( const FuncType& func_type, const F& func, Instance& instance, Stack<uint64_t>& stack, int depth) { const auto num_args = func_type.inputs.size(); assert(stack.size() >= num_args); std::vector<uint64_t> call_args(stack.end() - static_cast<ptrdiff_t>(num_args), stack.end()); stack.resize(stack.size() - num_args); const auto ret = func(instance, std::move(call_args), depth + 1); // Bubble up traps if (ret.trapped) return false; const auto num_outputs = func_type.outputs.size(); // NOTE: we can assume these two from validation assert(ret.stack.size() == num_outputs); assert(num_outputs <= 1); // Push back the result if (num_outputs != 0) stack.push(ret.stack[0]); return true; } inline bool invoke_function(const FuncType& func_type, uint32_t func_idx, Instance& instance, Stack<uint64_t>& stack, int depth) { const auto func = [func_idx](Instance& _instance, std::vector<uint64_t> args, int _depth) { return execute(_instance, func_idx, std::move(args), _depth); }; return invoke_function(func_type, func, instance, stack, depth); } template <typename T> inline void store(bytes& input, size_t offset, T value) noexcept { __builtin_memcpy(input.data() + offset, &value, sizeof(value)); } template <typename T> inline T load(bytes_view input, size_t offset) noexcept { T ret; __builtin_memcpy(&ret, input.data() + offset, sizeof(ret)); return ret; } template <typename T> inline T read(const uint8_t*& input) noexcept { T ret; __builtin_memcpy(&ret, input, sizeof(ret)); input += sizeof(ret); return ret; } template <typename DstT, typename SrcT> inline DstT extend(SrcT in) noexcept { if constexpr (std::is_signed<SrcT>::value) { using SignedDstT = typename std::make_signed<DstT>::type; return static_cast<DstT>(SignedDstT{in}); } else return DstT{in}; } template <typename DstT, typename SrcT = DstT> inline bool load_from_memory(bytes_view memory, Stack<uint64_t>& stack, const uint8_t*& immediates) { const auto address = static_cast<uint32_t>(stack.pop()); // NOTE: alignment is dropped by the parser const auto offset = read<uint32_t>(immediates); // Addressing is 32-bit, but we keep the value as 64-bit to detect overflows. if ((uint64_t{address} + offset + sizeof(SrcT)) > memory.size()) return false; const auto ret = load<SrcT>(memory, address + offset); stack.push(extend<DstT>(ret)); return true; } template <typename DstT> inline bool store_into_memory(bytes& memory, Stack<uint64_t>& stack, const uint8_t*& immediates) { const auto value = static_cast<DstT>(stack.pop()); const auto address = static_cast<uint32_t>(stack.pop()); // NOTE: alignment is dropped by the parser const auto offset = read<uint32_t>(immediates); // Addressing is 32-bit, but we keep the value as 64-bit to detect overflows. if ((uint64_t{address} + offset + sizeof(DstT)) > memory.size()) return false; store<DstT>(memory, address + offset, value); return true; } template <typename Op> inline void unary_op(Stack<uint64_t>& stack, Op op) noexcept { using T = decltype(op(stack.pop())); const auto a = static_cast<T>(stack.pop()); stack.push(op(a)); } template <typename Op> inline void binary_op(Stack<uint64_t>& stack, Op op) noexcept { using T = decltype(op(stack.pop(), stack.pop())); const auto val2 = static_cast<T>(stack.pop()); const auto val1 = static_cast<T>(stack.pop()); stack.push(static_cast<std::make_unsigned_t<T>>(op(val1, val2))); } template <typename T, template <typename> class Op> inline void comparison_op(Stack<uint64_t>& stack, Op<T> op) noexcept { const auto val2 = static_cast<T>(stack.pop()); const auto val1 = static_cast<T>(stack.pop()); stack.push(uint32_t{op(val1, val2)}); } template <typename T> inline T shift_left(T lhs, T rhs) noexcept { constexpr T num_bits{sizeof(T) * 8}; const auto k = rhs & (num_bits - 1); return lhs << k; } template <typename T> inline T shift_right(T lhs, T rhs) noexcept { constexpr T num_bits{sizeof(T) * 8}; const auto k = rhs & (num_bits - 1); return lhs >> k; } template <typename T> inline T rotl(T lhs, T rhs) noexcept { constexpr T num_bits{sizeof(T) * 8}; const auto k = rhs & (num_bits - 1); if (k == 0) return lhs; return (lhs << k) | (lhs >> (num_bits - k)); } template <typename T> inline T rotr(T lhs, T rhs) noexcept { constexpr T num_bits{sizeof(T) * 8}; const auto k = rhs & (num_bits - 1); if (k == 0) return lhs; return (lhs >> k) | (lhs << (num_bits - k)); } inline uint32_t clz32(uint32_t value) noexcept { // NOTE: Wasm specifies this case, but C/C++ intrinsic leaves it as undefined. if (value == 0) return 32; return static_cast<uint32_t>(__builtin_clz(value)); } inline uint32_t ctz32(uint32_t value) noexcept { // NOTE: Wasm specifies this case, but C/C++ intrinsic leaves it as undefined. if (value == 0) return 32; return static_cast<uint32_t>(__builtin_ctz(value)); } inline uint32_t popcnt32(uint32_t value) noexcept { return static_cast<uint32_t>(__builtin_popcount(value)); } inline uint64_t clz64(uint64_t value) noexcept { // NOTE: Wasm specifies this case, but C/C++ intrinsic leaves it as undefined. if (value == 0) return 64; return static_cast<uint64_t>(__builtin_clzll(value)); } inline uint64_t ctz64(uint64_t value) noexcept { // NOTE: Wasm specifies this case, but C/C++ intrinsic leaves it as undefined. if (value == 0) return 64; return static_cast<uint64_t>(__builtin_ctzll(value)); } inline uint64_t popcnt64(uint64_t value) noexcept { return static_cast<uint64_t>(__builtin_popcountll(value)); } std::optional<uint32_t> find_export(const Module& module, ExternalKind kind, std::string_view name) { const auto it = std::find_if(module.exportsec.begin(), module.exportsec.end(), [kind, name](const auto& export_) { return export_.kind == kind && export_.name == name; }); return (it != module.exportsec.end() ? std::make_optional(it->index) : std::nullopt); } } // namespace std::unique_ptr<Instance> instantiate(Module module, std::vector<ExternalFunction> imported_functions, std::vector<ExternalTable> imported_tables, std::vector<ExternalMemory> imported_memories, std::vector<ExternalGlobal> imported_globals) { assert(module.funcsec.size() == module.codesec.size()); match_imported_functions(module.imported_function_types, imported_functions); match_imported_tables(module.imported_table_types, imported_tables); match_imported_memories(module.imported_memory_types, imported_memories); match_imported_globals(module.imported_globals_mutability, imported_globals); // Init globals std::vector<uint64_t> globals; globals.reserve(module.globalsec.size()); for (auto const& global : module.globalsec) { // Wasm spec section 3.3.7 constrains initialization by another global to const imports only // https://webassembly.github.io/spec/core/valid/instructions.html#expressions if (global.expression.kind == ConstantExpression::Kind::GlobalGet && global.expression.value.global_index >= imported_globals.size()) { throw instantiate_error( "Global can be initialized by another const global only if it's imported."); } const auto value = eval_constant_expression( global.expression, imported_globals, module.globalsec, globals); globals.emplace_back(value); } auto table = allocate_table(module.tablesec, imported_tables); // Allocate memory auto [memory, memory_max] = allocate_memory(module.memorysec, imported_memories); // Before starting to fill memory and table, // check that data and element segments are within bounds. std::vector<uint64_t> datasec_offsets; datasec_offsets.reserve(module.datasec.size()); for (const auto& data : module.datasec) { const uint64_t offset = eval_constant_expression(data.offset, imported_globals, module.globalsec, globals); if (offset + data.init.size() > memory->size()) throw instantiate_error("Data segment is out of memory bounds"); datasec_offsets.emplace_back(offset); } assert(module.elementsec.empty() || table != nullptr); std::vector<ptrdiff_t> elementsec_offsets; elementsec_offsets.reserve(module.elementsec.size()); for (const auto& element : module.elementsec) { const uint64_t offset = eval_constant_expression(element.offset, imported_globals, module.globalsec, globals); if (offset + element.init.size() > table->size()) throw instantiate_error("Element segment is out of table bounds"); elementsec_offsets.emplace_back(offset); } // Fill out memory based on data segments for (size_t i = 0; i < module.datasec.size(); ++i) { // NOTE: these instructions can overlap std::copy(module.datasec[i].init.begin(), module.datasec[i].init.end(), memory->data() + datasec_offsets[i]); } // We need to create instance before filling table, // because table functions will capture the pointer to instance. // FIXME: clang-tidy warns about potential memory leak for moving memory (which is in fact // safe), but also erroneously points this warning to std::move(table) auto instance = std::make_unique<Instance>(std::move(module), std::move(memory), memory_max, // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks) std::move(table), std::move(globals), std::move(imported_functions), std::move(imported_globals)); // Fill the table based on elements segment for (size_t i = 0; i < instance->module.elementsec.size(); ++i) { // Overwrite table[offset..] with element.init auto it_table = instance->table->begin() + elementsec_offsets[i]; for (const auto idx : instance->module.elementsec[i].init) { auto func = [idx, &instance_ref = *instance]( fizzy::Instance&, std::vector<uint64_t> args, int depth) { return execute(instance_ref, idx, std::move(args), depth); }; *it_table++ = ExternalFunction{std::move(func), function_type(*instance, idx)}; } } // Run start function if present if (instance->module.startfunc) { const auto funcidx = *instance->module.startfunc; assert(funcidx < instance->imported_functions.size() + instance->module.funcsec.size()); if (execute(*instance, funcidx, {}).trapped) { // When element section modified imported table, and then start function trapped, // modifications to the table are not rolled back. // Instance in this case is not being returned to the user, so it needs to be kept alive // as long as functions using it are alive in the table. if (!imported_tables.empty() && !instance->module.elementsec.empty()) { // Instance may be used by several functions added to the table, // so we need a shared ownership here. std::shared_ptr<Instance> shared_instance = std::move(instance); for (size_t i = 0; i < shared_instance->module.elementsec.size(); ++i) { auto it_table = shared_instance->table->begin() + elementsec_offsets[i]; for ([[maybe_unused]] auto _ : shared_instance->module.elementsec[i].init) { // Wrap the function with the lambda capturing shared instance auto& table_function = (*it_table)->function; table_function = [shared_instance, func = std::move(table_function)]( fizzy::Instance& _instance, std::vector<uint64_t> args, int depth) { return func(_instance, std::move(args), depth); }; ++it_table; } } } throw instantiate_error("Start function failed to execute"); } } return instance; } execution_result execute( Instance& instance, FuncIdx func_idx, std::vector<uint64_t> args, int depth) { assert(depth >= 0); if (depth > CallStackLimit) return {true, {}}; if (func_idx < instance.imported_functions.size()) return instance.imported_functions[func_idx].function(instance, std::move(args), depth); const auto code_idx = func_idx - instance.imported_functions.size(); assert(code_idx < instance.module.codesec.size()); const auto& code = instance.module.codesec[code_idx]; auto* const memory = instance.memory.get(); std::vector<uint64_t> locals = std::move(args); locals.resize(locals.size() + code.local_count); // TODO: preallocate fixed stack depth properly Stack<uint64_t> stack; LabelStack labels; bool trap = false; const Instr* pc = code.instructions.data(); const uint8_t* immediates = code.immediates.data(); while (true) { const auto instruction = *pc++; switch (instruction) { case Instr::unreachable: trap = true; goto end; case Instr::nop: break; case Instr::block: { const auto arity = read<uint8_t>(immediates); const auto target_pc = read<uint32_t>(immediates); const auto target_imm = read<uint32_t>(immediates); LabelContext label{code.instructions.data() + target_pc, code.immediates.data() + target_imm, arity, stack.size()}; labels.push(label); break; } case Instr::loop: { LabelContext label{pc - 1, immediates, 0, stack.size()}; // Target this instruction. labels.push(label); break; } case Instr::if_: { const auto arity = read<uint8_t>(immediates); const auto target_pc = read<uint32_t>(immediates); const auto target_imm = read<uint32_t>(immediates); if (static_cast<uint32_t>(stack.pop()) != 0) { immediates += 2 * sizeof(uint32_t); // Skip the immediates for else instruction. LabelContext label{code.instructions.data() + target_pc, code.immediates.data() + target_imm, arity, stack.size()}; labels.push(label); } else { const auto target_else_pc = read<uint32_t>(immediates); const auto target_else_imm = read<uint32_t>(immediates); if (target_else_pc != 0) // If else block defined. { LabelContext label{code.instructions.data() + target_pc, code.immediates.data() + target_imm, arity, stack.size()}; labels.push(label); pc = code.instructions.data() + target_else_pc; immediates = code.immediates.data() + target_else_imm; } else // If else block not defined go to end of if. { assert(arity == 0); // if without else cannot have type signature. pc = code.instructions.data() + target_pc; immediates = code.immediates.data() + target_imm; } } break; } case Instr::else_: { // We reach else only at the end of if block. assert(!labels.empty()); const auto label = labels.top(); labels.pop(); pc = label.pc; immediates = label.immediate; break; } case Instr::end: { if (!labels.empty()) labels.pop(); else goto end; break; } case Instr::br: case Instr::br_if: { const auto label_idx = read<uint32_t>(immediates); // Check condition for br_if. if (instruction == Instr::br_if && static_cast<uint32_t>(stack.pop()) == 0) break; if (label_idx == labels.size()) goto case_return; branch(label_idx, labels, stack, pc, immediates); break; } case Instr::br_table: { // immediates are: size of label vector, labels, default label const auto br_table_size = read<uint32_t>(immediates); const auto br_table_idx = stack.pop(); const auto label_idx_offset = br_table_idx < br_table_size ? br_table_idx * sizeof(uint32_t) : br_table_size * sizeof(uint32_t); immediates += label_idx_offset; const auto label_idx = read<uint32_t>(immediates); if (label_idx == labels.size()) goto case_return; branch(label_idx, labels, stack, pc, immediates); break; } case Instr::call: { const auto called_func_idx = read<uint32_t>(immediates); const auto& func_type = function_type(instance, called_func_idx); if (!invoke_function(func_type, called_func_idx, instance, stack, depth)) { trap = true; goto end; } break; } case Instr::call_indirect: { assert(instance.table != nullptr); const auto expected_type_idx = read<uint32_t>(immediates); assert(expected_type_idx < instance.module.typesec.size()); const auto elem_idx = stack.pop(); if (elem_idx >= instance.table->size()) { trap = true; goto end; } const auto called_func = (*instance.table)[elem_idx]; if (!called_func.has_value()) { trap = true; goto end; } // check actual type against expected type const auto& actual_type = called_func->type; const auto& expected_type = instance.module.typesec[expected_type_idx]; if (expected_type != actual_type) { trap = true; goto end; } if (!invoke_function(actual_type, called_func->function, instance, stack, depth)) { trap = true; goto end; } break; } case Instr::return_: case_return: { // TODO: Not needed, but satisfies the assert in the end of the main loop. labels = {}; assert(code_idx < instance.module.funcsec.size()); const auto type_idx = instance.module.funcsec[code_idx]; assert(type_idx < instance.module.typesec.size()); const bool have_result = !instance.module.typesec[type_idx].outputs.empty(); if (have_result) { const auto result = stack.peek(); stack.clear(); stack.push(result); } else stack.clear(); goto end; } case Instr::drop: { stack.pop(); break; } case Instr::select: { const auto condition = static_cast<uint32_t>(stack.pop()); // NOTE: these two are the same type (ensured by validation) const auto val2 = stack.pop(); const auto val1 = stack.pop(); if (condition == 0) stack.push(val2); else stack.push(val1); break; } case Instr::local_get: { const auto idx = read<uint32_t>(immediates); assert(idx <= locals.size()); stack.push(locals[idx]); break; } case Instr::local_set: { const auto idx = read<uint32_t>(immediates); assert(idx <= locals.size()); locals[idx] = stack.pop(); break; } case Instr::local_tee: { const auto idx = read<uint32_t>(immediates); assert(idx <= locals.size()); locals[idx] = stack.peek(); break; } case Instr::global_get: { const auto idx = read<uint32_t>(immediates); assert(idx < instance.imported_globals.size() + instance.globals.size()); if (idx < instance.imported_globals.size()) { stack.push(*instance.imported_globals[idx].value); } else { const auto module_global_idx = idx - instance.imported_globals.size(); assert(module_global_idx < instance.module.globalsec.size()); stack.push(instance.globals[module_global_idx]); } break; } case Instr::global_set: { const auto idx = read<uint32_t>(immediates); if (idx < instance.imported_globals.size()) { assert(instance.imported_globals[idx].is_mutable); *instance.imported_globals[idx].value = stack.pop(); } else { const auto module_global_idx = idx - instance.imported_globals.size(); assert(module_global_idx < instance.module.globalsec.size()); assert(instance.module.globalsec[module_global_idx].is_mutable); instance.globals[module_global_idx] = stack.pop(); } break; } case Instr::i32_load: { if (!load_from_memory<uint32_t>(*memory, stack, immediates)) { trap = true; goto end; } break; } case Instr::i64_load: { if (!load_from_memory<uint64_t>(*memory, stack, immediates)) { trap = true; goto end; } break; } case Instr::i32_load8_s: { if (!load_from_memory<uint32_t, int8_t>(*memory, stack, immediates)) { trap = true; goto end; } break; } case Instr::i32_load8_u: { if (!load_from_memory<uint32_t, uint8_t>(*memory, stack, immediates)) { trap = true; goto end; } break; } case Instr::i32_load16_s: { if (!load_from_memory<uint32_t, int16_t>(*memory, stack, immediates)) { trap = true; goto end; } break; } case Instr::i32_load16_u: { if (!load_from_memory<uint32_t, uint16_t>(*memory, stack, immediates)) { trap = true; goto end; } break; } case Instr::i64_load8_s: { if (!load_from_memory<uint64_t, int8_t>(*memory, stack, immediates)) { trap = true; goto end; } break; } case Instr::i64_load8_u: { if (!load_from_memory<uint64_t, uint8_t>(*memory, stack, immediates)) { trap = true; goto end; } break; } case Instr::i64_load16_s: { if (!load_from_memory<uint64_t, int16_t>(*memory, stack, immediates)) { trap = true; goto end; } break; } case Instr::i64_load16_u: { if (!load_from_memory<uint64_t, uint16_t>(*memory, stack, immediates)) { trap = true; goto end; } break; } case Instr::i64_load32_s: { if (!load_from_memory<uint64_t, int32_t>(*memory, stack, immediates)) { trap = true; goto end; } break; } case Instr::i64_load32_u: { if (!load_from_memory<uint64_t, uint32_t>(*memory, stack, immediates)) { trap = true; goto end; } break; } case Instr::i32_store: { if (!store_into_memory<uint32_t>(*memory, stack, immediates)) { trap = true; goto end; } break; } case Instr::i64_store: { if (!store_into_memory<uint64_t>(*memory, stack, immediates)) { trap = true; goto end; } break; } case Instr::i32_store8: case Instr::i64_store8: { if (!store_into_memory<uint8_t>(*memory, stack, immediates)) { trap = true; goto end; } break; } case Instr::i32_store16: case Instr::i64_store16: { if (!store_into_memory<uint16_t>(*memory, stack, immediates)) { trap = true; goto end; } break; } case Instr::i64_store32: { if (!store_into_memory<uint32_t>(*memory, stack, immediates)) { trap = true; goto end; } break; } case Instr::memory_size: { stack.push(static_cast<uint32_t>(memory->size() / PageSize)); break; } case Instr::memory_grow: { const auto delta = static_cast<uint32_t>(stack.pop()); const auto cur_pages = memory->size() / PageSize; assert(cur_pages <= size_t(std::numeric_limits<int32_t>::max())); const auto new_pages = cur_pages + delta; assert(new_pages >= cur_pages); uint32_t ret = static_cast<uint32_t>(cur_pages); try { if (new_pages > instance.memory_max_pages) throw std::bad_alloc(); memory->resize(new_pages * PageSize); } catch (std::bad_alloc const&) { ret = static_cast<uint32_t>(-1); } stack.push(ret); break; } case Instr::i32_const: { const auto value = read<uint32_t>(immediates); stack.push(value); break; } case Instr::i64_const: { const auto value = read<uint64_t>(immediates); stack.push(value); break; } case Instr::i32_eqz: { const auto value = static_cast<uint32_t>(stack.pop()); stack.push(value == 0); break; } case Instr::i32_eq: { comparison_op(stack, std::equal_to<uint32_t>()); break; } case Instr::i32_ne: { comparison_op(stack, std::not_equal_to<uint32_t>()); break; } case Instr::i32_lt_s: { comparison_op(stack, std::less<int32_t>()); break; } case Instr::i32_lt_u: { comparison_op(stack, std::less<uint32_t>()); break; } case Instr::i32_gt_s: { comparison_op(stack, std::greater<int32_t>()); break; } case Instr::i32_gt_u: { comparison_op(stack, std::greater<uint32_t>()); break; } case Instr::i32_le_s: { comparison_op(stack, std::less_equal<int32_t>()); break; } case Instr::i32_le_u: { comparison_op(stack, std::less_equal<uint32_t>()); break; } case Instr::i32_ge_s: { comparison_op(stack, std::greater_equal<int32_t>()); break; } case Instr::i32_ge_u: { comparison_op(stack, std::greater_equal<uint32_t>()); break; } case Instr::i64_eqz: { stack.push(stack.pop() == 0); break; } case Instr::i64_eq: { comparison_op(stack, std::equal_to<uint64_t>()); break; } case Instr::i64_ne: { comparison_op(stack, std::not_equal_to<uint64_t>()); break; } case Instr::i64_lt_s: { comparison_op(stack, std::less<int64_t>()); break; } case Instr::i64_lt_u: { comparison_op(stack, std::less<uint64_t>()); break; } case Instr::i64_gt_s: { comparison_op(stack, std::greater<int64_t>()); break; } case Instr::i64_gt_u: { comparison_op(stack, std::greater<uint64_t>()); break; } case Instr::i64_le_s: { comparison_op(stack, std::less_equal<int64_t>()); break; } case Instr::i64_le_u: { comparison_op(stack, std::less_equal<uint64_t>()); break; } case Instr::i64_ge_s: { comparison_op(stack, std::greater_equal<int64_t>()); break; } case Instr::i64_ge_u: { comparison_op(stack, std::greater_equal<uint64_t>()); break; } case Instr::i32_clz: { unary_op(stack, clz32); break; } case Instr::i32_ctz: { unary_op(stack, ctz32); break; } case Instr::i32_popcnt: { unary_op(stack, popcnt32); break; } case Instr::i32_add: { binary_op(stack, std::plus<uint32_t>()); break; } case Instr::i32_sub: { binary_op(stack, std::minus<uint32_t>()); break; } case Instr::i32_mul: { binary_op(stack, std::multiplies<uint32_t>()); break; } case Instr::i32_div_s: { auto const rhs = static_cast<int32_t>(stack.peek(0)); auto const lhs = static_cast<int32_t>(stack.peek(1)); if (rhs == 0 || (lhs == std::numeric_limits<int32_t>::min() && rhs == -1)) { trap = true; goto end; } binary_op(stack, std::divides<int32_t>()); break; } case Instr::i32_div_u: { auto const rhs = static_cast<uint32_t>(stack.peek()); if (rhs == 0) { trap = true; goto end; } binary_op(stack, std::divides<uint32_t>()); break; } case Instr::i32_rem_s: { auto const rhs = static_cast<int32_t>(stack.peek()); if (rhs == 0) { trap = true; goto end; } auto const lhs = static_cast<int32_t>(stack.peek(1)); if (lhs == std::numeric_limits<int32_t>::min() && rhs == -1) { stack.drop(2); stack.push(0); } else binary_op(stack, std::modulus<int32_t>()); break; } case Instr::i32_rem_u: { auto const rhs = static_cast<uint32_t>(stack.peek()); if (rhs == 0) { trap = true; goto end; } binary_op(stack, std::modulus<uint32_t>()); break; } case Instr::i32_and: { binary_op(stack, std::bit_and<uint32_t>()); break; } case Instr::i32_or: { binary_op(stack, std::bit_or<uint32_t>()); break; } case Instr::i32_xor: { binary_op(stack, std::bit_xor<uint32_t>()); break; } case Instr::i32_shl: { binary_op(stack, shift_left<uint32_t>); break; } case Instr::i32_shr_s: { binary_op(stack, shift_right<int32_t>); break; } case Instr::i32_shr_u: { binary_op(stack, shift_right<uint32_t>); break; } case Instr::i32_rotl: { binary_op(stack, rotl<uint32_t>); break; } case Instr::i32_rotr: { binary_op(stack, rotr<uint32_t>); break; } case Instr::i64_clz: { unary_op(stack, clz64); break; } case Instr::i64_ctz: { unary_op(stack, ctz64); break; } case Instr::i64_popcnt: { unary_op(stack, popcnt64); break; } case Instr::i64_add: { binary_op(stack, std::plus<uint64_t>()); break; } case Instr::i64_sub: { binary_op(stack, std::minus<uint64_t>()); break; } case Instr::i64_mul: { binary_op(stack, std::multiplies<uint64_t>()); break; } case Instr::i64_div_s: { auto const rhs = static_cast<int64_t>(stack.peek(0)); auto const lhs = static_cast<int64_t>(stack.peek(1)); if (rhs == 0 || (lhs == std::numeric_limits<int64_t>::min() && rhs == -1)) { trap = true; goto end; } binary_op(stack, std::divides<int64_t>()); break; } case Instr::i64_div_u: { auto const rhs = static_cast<uint64_t>(stack.peek()); if (rhs == 0) { trap = true; goto end; } binary_op(stack, std::divides<uint64_t>()); break; } case Instr::i64_rem_s: { auto const rhs = static_cast<int64_t>(stack.peek()); if (rhs == 0) { trap = true; goto end; } auto const lhs = static_cast<int64_t>(stack.peek(1)); if (lhs == std::numeric_limits<int64_t>::min() && rhs == -1) { stack.drop(2); stack.push(0); } else binary_op(stack, std::modulus<int64_t>()); break; } case Instr::i64_rem_u: { auto const rhs = static_cast<uint64_t>(stack.peek()); if (rhs == 0) { trap = true; goto end; } binary_op(stack, std::modulus<uint64_t>()); break; } case Instr::i64_and: { binary_op(stack, std::bit_and<uint64_t>()); break; } case Instr::i64_or: { binary_op(stack, std::bit_or<uint64_t>()); break; } case Instr::i64_xor: { binary_op(stack, std::bit_xor<uint64_t>()); break; } case Instr::i64_shl: { binary_op(stack, shift_left<uint64_t>); break; } case Instr::i64_shr_s: { binary_op(stack, shift_right<int64_t>); break; } case Instr::i64_shr_u: { binary_op(stack, shift_right<uint64_t>); break; } case Instr::i64_rotl: { binary_op(stack, rotl<uint64_t>); break; } case Instr::i64_rotr: { binary_op(stack, rotr<uint64_t>); break; } case Instr::i32_wrap_i64: { stack.push(static_cast<uint32_t>(stack.pop())); break; } case Instr::i64_extend_i32_s: { const auto value = static_cast<int32_t>(stack.pop()); stack.push(static_cast<uint64_t>(int64_t{value})); break; } case Instr::i64_extend_i32_u: { // effectively no-op break; } case Instr::f32_load: case Instr::f64_load: case Instr::f32_store: case Instr::f64_store: case Instr::f32_const: case Instr::f64_const: case Instr::f32_eq: case Instr::f32_ne: case Instr::f32_lt: case Instr::f32_gt: case Instr::f32_le: case Instr::f32_ge: case Instr::f64_eq: case Instr::f64_ne: case Instr::f64_lt: case Instr::f64_gt: case Instr::f64_le: case Instr::f64_ge: case Instr::f32_abs: case Instr::f32_neg: case Instr::f32_ceil: case Instr::f32_floor: case Instr::f32_trunc: case Instr::f32_nearest: case Instr::f32_sqrt: case Instr::f32_add: case Instr::f32_sub: case Instr::f32_mul: case Instr::f32_div: case Instr::f32_min: case Instr::f32_max: case Instr::f32_copysign: case Instr::f64_abs: case Instr::f64_neg: case Instr::f64_ceil: case Instr::f64_floor: case Instr::f64_trunc: case Instr::f64_nearest: case Instr::f64_sqrt: case Instr::f64_add: case Instr::f64_sub: case Instr::f64_mul: case Instr::f64_div: case Instr::f64_min: case Instr::f64_max: case Instr::f64_copysign: case Instr::i32_trunc_f32_s: case Instr::i32_trunc_f32_u: case Instr::i32_trunc_f64_s: case Instr::i32_trunc_f64_u: case Instr::i64_trunc_f32_s: case Instr::i64_trunc_f32_u: case Instr::i64_trunc_f64_s: case Instr::i64_trunc_f64_u: case Instr::f32_convert_i32_s: case Instr::f32_convert_i32_u: case Instr::f32_convert_i64_s: case Instr::f32_convert_i64_u: case Instr::f32_demote_f64: case Instr::f64_convert_i32_s: case Instr::f64_convert_i32_u: case Instr::f64_convert_i64_s: case Instr::f64_convert_i64_u: case Instr::f64_promote_f32: case Instr::i32_reinterpret_f32: case Instr::i64_reinterpret_f64: case Instr::f32_reinterpret_i32: case Instr::f64_reinterpret_i64: throw unsupported_feature("Floating point instruction."); default: assert(false); break; } } end: assert(labels.empty() || trap); // move allows to return derived Stack<uint64_t> instance into base vector<uint64_t> value return {trap, std::move(stack)}; } execution_result execute(const Module& module, FuncIdx func_idx, std::vector<uint64_t> args) { auto instance = instantiate(module); return execute(*instance, func_idx, std::move(args)); } std::optional<FuncIdx> find_exported_function(const Module& module, std::string_view name) { for (const auto& export_ : module.exportsec) { if (export_.kind == ExternalKind::Function && name == export_.name) return export_.index; } return {}; } std::optional<ExternalFunction> find_exported_function(Instance& instance, std::string_view name) { const auto opt_index = find_export(instance.module, ExternalKind::Function, name); if (!opt_index.has_value()) return std::nullopt; const auto idx = *opt_index; auto func = [idx, &instance](fizzy::Instance&, std::vector<uint64_t> args, int depth) { return execute(instance, idx, std::move(args), depth); }; return ExternalFunction{std::move(func), function_type(instance, idx)}; } std::optional<ExternalGlobal> find_exported_global(Instance& instance, std::string_view name) { const auto opt_index = find_export(instance.module, ExternalKind::Global, name); if (!opt_index.has_value()) return std::nullopt; const auto global_idx = *opt_index; if (global_idx < instance.imported_globals.size()) { // imported global is reexported return ExternalGlobal{instance.imported_globals[global_idx].value, instance.imported_globals[global_idx].is_mutable}; } else { // global owned by instance const auto module_global_idx = global_idx - instance.imported_globals.size(); return ExternalGlobal{&instance.globals[module_global_idx], instance.module.globalsec[module_global_idx].is_mutable}; } } std::optional<ExternalTable> find_exported_table(Instance& instance, std::string_view name) { const auto& module = instance.module; // Index returned from find_export is discarded, because there's no more than 1 table if (!find_export(module, ExternalKind::Table, name)) return std::nullopt; if (module.tablesec.size() == 1) { // table owned by instance assert(module.imported_table_types.size() == 0); return ExternalTable{instance.table.get(), module.tablesec[0].limits}; } else { // imported table is reexported assert(module.imported_table_types.size() == 1); // FIXME: Limits here are not exactly correct: table could have been imported with limits // narrower than the ones defined in module's import definition, we don't save those during // instantiate. return ExternalTable{instance.table.get(), module.imported_table_types[0].limits}; } } std::optional<ExternalMemory> find_exported_memory(Instance& instance, std::string_view name) { const auto& module = instance.module; // Index returned from find_export is discarded, because there's no more than 1 memory if (!find_export(module, ExternalKind::Memory, name)) return std::nullopt; if (module.memorysec.size() == 1) { // memory owned by instance assert(module.imported_memory_types.size() == 0); return ExternalMemory{instance.memory.get(), module.memorysec[0].limits}; } else { // imported memory is reexported assert(module.imported_memory_types.size() == 1); // FIXME: Limits min here is not correct: memory could have been imported with limits // narrower than the ones defined in module's import definition, we save only max during // instantiate, but not min. Limits limits = module.imported_memory_types[0].limits; if (instance.memory_max_pages < MemoryPagesLimit) limits.max = instance.memory_max_pages; return ExternalMemory{instance.memory.get(), limits}; } } } // namespace fizzy
32.305226
100
0.560421
[ "vector" ]
1dcc21943e5d755eeb7d6a757803ae3865124343
10,153
cpp
C++
Reservation.cpp
LumpBloom7/vrBoothTicketing
3d939c0d577cfbdd8871b461cd2cf55ad8274a47
[ "MIT" ]
null
null
null
Reservation.cpp
LumpBloom7/vrBoothTicketing
3d939c0d577cfbdd8871b461cd2cf55ad8274a47
[ "MIT" ]
3
2018-06-17T09:05:02.000Z
2018-06-27T15:12:04.000Z
Reservation.cpp
LumpBloom7/vrBoothTicketing
3d939c0d577cfbdd8871b461cd2cf55ad8274a47
[ "MIT" ]
null
null
null
#include <chrono> #include <iomanip> #include <ctime> #include <cmath> #include <cstdlib> namespace booth { int guestCount = 0; class Reservation { public: Reservation() {} Reservation( std::chrono::system_clock::time_point &startTime, std::string &name, std::string &contactDetails, int &computerNumber ) : startTime( startTime ), name( name ), contactDetails( contactDetails ), computerNumber( computerNumber ), verificationCode( 0 ) { logFile( "Initialized variables with user data.", 2 ); guestCount++; logFile( "Incrementing guest counter.", 2 ); guestNumber = guestCount; logFile( "Assigning current number to user.", 2 ); endTime = startTime + std::chrono::seconds( 900 ); logFile( "Calculated user end time.", 2 ); // Generate random verification code here. logFile( "Generating verification code.", 2 ); for ( char i : name ) verificationCode += pow( int( i ), 2 ); logFile( "Successfully generated verification code.", 2 ); } std::string name; std::chrono::system_clock::time_point startTime; std::string contactDetails{""}; int verificationCode = 0; std::chrono::system_clock::time_point endTime = startTime + std::chrono::seconds( 900 ); int computerNumber; int guestNumber; template <class Archive> void serialize( Archive &archive ) { archive( CEREAL_NVP( name ), CEREAL_NVP( startTime ), CEREAL_NVP( contactDetails ), CEREAL_NVP( verificationCode ), CEREAL_NVP( endTime ), CEREAL_NVP( computerNumber ), CEREAL_NVP( guestNumber ) ); } }; std::vector<Reservation> guests{}; std::vector<std::vector<Reservation>> computers = std::vector<std::vector<Reservation>>( 4 ); void save() { std::ofstream os( "computers.json" ); cereal::JSONOutputArchive archive( os ); archive( CEREAL_NVP( computers[ 0 ] ), CEREAL_NVP( computers[ 1 ] ), CEREAL_NVP( computers[ 2 ] ), CEREAL_NVP( computers[ 3 ] ) ); std::ofstream os2( "guests.json" ); cereal::JSONOutputArchive archive2( os2 ); archive2( CEREAL_NVP( guests ) ); } void load() { std::ifstream is( "computers.json" ); cereal::JSONInputArchive archive( is ); archive( CEREAL_NVP( computers[ 0 ] ), CEREAL_NVP( computers[ 1 ] ), CEREAL_NVP( computers[ 2 ] ), CEREAL_NVP( computers[ 3 ] ) ); std::ifstream is2( "guests.json" ); cereal::JSONInputArchive archive2( is2 ); archive2( CEREAL_NVP( guests ) ); } void addReservation() { logFile( "Entered reservation screen.", 0 ); cligCore::console::clear(); std::string name = ""; std::cout << "Please input the customer's english or romanised name. Leave blank to cancel." << std::endl; std::getline( std::cin, name ); if ( name == "" ) { logFile( "Reservation process failed. (Cancelled by user)", 0 ); return; } logFile( "Successfully retrieved name from input.", 1 ); std::cout << "Please enter one or more way to contact you(Phone, Email; Seperated by commas)." << std::endl; std::string contactDetails; std::cin >> contactDetails; logFile( "Successfully retrieved contact info from input.", 1 ); std::chrono::system_clock::time_point currentTime = std::chrono::ceil<std::chrono::minutes>( std::chrono::system_clock::now() ); logFile( "Successfully retrieved current system time.", 1 ); bool init = false; int smallestNumber; logFile( "Finding suitable computer for user.", 1 ); for ( int i = 0; i < 4; i++ ) { if ( computers[ i ].size() == 0 ) { smallestNumber = i; break; } else { if ( i == 0 ) smallestNumber = i; else { if ( computers[ i ][ computers[ i ].size() - 1 ].endTime < computers[ smallestNumber ][ computers[ smallestNumber ].size() - 1 ].endTime ) smallestNumber = i; } } } logFile( "Found suitable computer for user.", 1 ); logFile( "Assigning time slot for user.", 1 ); std::chrono::system_clock::time_point startTime; if ( computers[ smallestNumber ].size() == 0 ) startTime = currentTime; else if ( computers[ smallestNumber ][ computers[ smallestNumber ].size() - 1 ].endTime < currentTime ) startTime = currentTime; else startTime = computers[ smallestNumber ][ computers[ smallestNumber ].size() - 1 ].endTime; // Check to see if we still have time. auto tmp = startTime + std::chrono::seconds( 900 ); std::time_t tmp2 = std::chrono::system_clock::to_time_t( tmp ); struct tm temp; localtime_s( &temp, &tmp2 ); int h = temp.tm_hour; int m = temp.tm_min - 15; int dt = tmp2; if ( ( ( h > 8 && h < 11 ) || ( h == 11 && m < 20 ) ) ) { logFile( "Could not assign time slot for user.(Outside of operating range)", 1 ); logFile( "Reservation failed!", 0 ); cligCore::console::clear(); std::cin.ignore(); std::cout << termcolor::red << "Reservation failed!" << std::endl << "We only allow reservations between 8 and 11:30." << std::endl << "Sorry for the inconvenience caused." << std::endl; std::string t; std::getline( std::cin, t ); return; } logFile( "Successfully assigned time slot for user.", 1 ); logFile( "Placing user data into \"Reservation\" data type", 1 ); Reservation guest = Reservation( startTime, name, contactDetails, smallestNumber ); logFile( "Successfully placed user data into \"Reservation\" data type", 1 ); logFile( "Adding user to the guest list", 1 ); computers[ smallestNumber ].emplace_back( guest ); guests.emplace_back( guest ); logFile( "Successfully Added user to the guest list", 1 ); logFile( "Outputting user data to screen.", 1 ); cligCore::console::clear(); std::time_t start = std::chrono::system_clock::to_time_t( guest.startTime ); std::time_t end = std::chrono::system_clock::to_time_t( guest.endTime ); std::cout << "Successfully found a suitable time for your session." << std::endl; std::cout << "Please write this down..." << std::endl << termcolor::cyan << "User name: " << guest.name << std::endl << "User number: " << guest.guestNumber << std::endl << "Computer number: " << guest.computerNumber << std::endl << "Verification code: " << guest.verificationCode << std::endl << std::endl << "Start time: " << std::put_time( std::localtime( &start ), "%H:%M" ) << std::endl << "End time: " << std::put_time( std::localtime( &end ), "%H:%M" ) << std::endl << std::endl << "It is recommended that you arrive at least 5 minutes before your start time." << std::endl << "Failure to arrive on time may result in your play session being shorter" << std::endl; std::cin.ignore(); std::getline( std::cin, contactDetails ); logFile( "Reservation successful!", 0 ); save(); } int inputCheck() { if ( std::cin.fail() ) { std::cin.clear(); std::cin.ignore(); std::cin.ignore(); std::string tmp; std::cout << termcolor::red << "Invalid input entered, returning to main menu." << std::endl; logFile( "Verification failed. (Invalid input)", 1 ); logFile( "Verification screen closed.", 0 ); std::getline( std::cin, tmp ); return -1; } return 0; } void verifyCode() { logFile( "Entered verification screen.", 0 ); cligCore::console::clear(); logFile( "Requesting user input.", 1 ); int userNumber; std::cout << "Please enter your user number: " << termcolor::green << std::flush; std::cin >> userNumber; if ( inputCheck() == -1 ) { return; } logFile( "Received user number.", 2 ); int computerNumber; std::cout << termcolor::reset << "Please enter your computer number: " << termcolor::green << std::flush; std::cin >> computerNumber; if ( inputCheck() == -1 ) { return; } logFile( "Received computer number.", 2 ); int verificationCode; std::cout << termcolor::reset << "Please enter your verification code: " << termcolor::green << std::flush; std::cin >> verificationCode; if ( inputCheck() == -1 ) { return; } logFile( "Received verification code.", 2 ); logFile( "Checking if information is valid.", 1 ); cligCore::console::clear(); if ( userNumber > 0 && guests.size() >= userNumber ) { if ( guests[ userNumber - 1 ].verificationCode == verificationCode && computerNumber == guests[ userNumber - 1 ].computerNumber ) { std::cout << "Verification Successful." << std::endl; if ( guests[ userNumber - 1 ].startTime - std::chrono::system_clock::now() > std::chrono::minutes( 10 ) ) { std::cout << "But it is a bit early don't you think?" << std::endl << "Please try again later, preferably about 5 minutes before your start time." << std::endl; logFile( "Verification failed. (User arrived too early)", 2 ); } else { std::cout << "A staff member will now guide you to your computer" << std::endl; logFile( "Verification successful.", 2 ); } } else { std::cout << "Verification failed." << std::endl << "One or more of the inputted values are incorrect" << std::endl; logFile( "Verification failed1. (Incorrect info)", 2 ); } } else { std::cout << "Verification failed." << std::endl << "One or more of the inputted values are incorrect" << std::endl; logFile( "Verification failed2. (Incorrect info)", 2 ); } logFile( "Finished checking.", 1 ); std::cin.ignore(); std::cin.ignore(); logFile( "Verification screen closed.", 0 ); } } // namespace booth
45.529148
116
0.591057
[ "vector" ]
1dcd9f95795303c434b5ffac90833adfd8ab75bc
3,729
cpp
C++
opencamlib-read-only/src/geo/bbox.cpp
play113/swer
78764c67885dfacb1fa24e494a20681265f5254c
[ "MIT" ]
null
null
null
opencamlib-read-only/src/geo/bbox.cpp
play113/swer
78764c67885dfacb1fa24e494a20681265f5254c
[ "MIT" ]
null
null
null
opencamlib-read-only/src/geo/bbox.cpp
play113/swer
78764c67885dfacb1fa24e494a20681265f5254c
[ "MIT" ]
1
2020-07-04T13:58:00.000Z
2020-07-04T13:58:00.000Z
/* $Id: bbox.cpp 745 2011-05-16 10:32:25Z anders.e.e.wallin $ * * Copyright 2010 Anders Wallin (anders.e.e.wallin "at" gmail.com) * * This file is part of OpenCAMlib. * * OpenCAMlib is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenCAMlib is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenCAMlib. If not, see <http://www.gnu.org/licenses/>. */ #include <cassert> #include "bbox.h" #include "point.h" #include "triangle.h" namespace ocl { //************* axis-aligned Bounding-Box **************/ Bbox::Bbox() { minpt = Point(0,0,0); maxpt = Point(0,0,0); initialized = false; } // minx maxx miny maxy minz maxz Bbox::Bbox(double b1, double b2, double b3, double b4, double b5, double b6) { minpt = Point(b1,b3,b5); maxpt = Point(b2,b4,b6); initialized = true; } void Bbox::clear() { initialized = false; } bool Bbox::isInside(Point& p) const { assert( initialized ); if (p.x > maxpt.x) return false; else if (p.x < minpt.x) return false; else if (p.y > maxpt.y) return false; else if (p.y < minpt.y) return false; else if (p.z > maxpt.z) return false; else if (p.z < minpt.z) return false; else return true; } void Bbox::addPoint(const Point &p) { if (!initialized) { maxpt = p; minpt = p; initialized = true; } else { if (p.x > maxpt.x) maxpt.x = p.x; if (p.x < minpt.x) minpt.x = p.x; if (p.y > maxpt.y) maxpt.y = p.y; if (p.y < minpt.y) minpt.y = p.y; if (p.z > maxpt.z) maxpt.z = p.z; if (p.z < minpt.z) minpt.z = p.z; } } /// add each vertex of the Triangle void Bbox::addTriangle(const Triangle &t) { addPoint( t.p[0] ); addPoint( t.p[1] ); addPoint( t.p[2] ); return; } /// does this Bbox overlap with b? bool Bbox::overlaps(const Bbox& b) const { if ( (this->maxpt.x < b.minpt.x) || (this->minpt.x > b.maxpt.x) ) return false; else if ( (this->maxpt.y < b.minpt.y) || (this->minpt.y > b.maxpt.y) ) return false; else if ( (this->maxpt.z < b.minpt.z) || (this->minpt.z > b.maxpt.z) ) return false; else return true; } // return the bounding box values as a vector: // 0 1 2 3 4 5 // [minx maxx miny maxy minz maxz] double Bbox::operator[](const unsigned int idx) const{ switch(idx) { case 0: return minpt.x; break; case 1: return maxpt.x; break; case 2: return minpt.y; break; case 3: return maxpt.y; break; case 4: return minpt.z; break; case 5: return maxpt.z; break; default: assert(0); break; } assert(0); return -1; } std::ostream &operator<<(std::ostream &stream, const Bbox b) { stream << " Bbox \n"; stream << " min= "<< b.minpt <<"\n"; stream << " max= "<< b.maxpt <<"\n"; return stream; } } // end namespace // end of file volume.cpp
25.026846
78
0.537141
[ "vector" ]
1dcfce0b56c8ae89b086f9419975a58f717e831e
10,188
cpp
C++
pick_and_place/src/right_arm_pnp.cpp
mjclements/TRINA-WPI-2.0
aa060819522ed9010d20e9db0cf45b19f6b083af
[ "MIT" ]
null
null
null
pick_and_place/src/right_arm_pnp.cpp
mjclements/TRINA-WPI-2.0
aa060819522ed9010d20e9db0cf45b19f6b083af
[ "MIT" ]
null
null
null
pick_and_place/src/right_arm_pnp.cpp
mjclements/TRINA-WPI-2.0
aa060819522ed9010d20e9db0cf45b19f6b083af
[ "MIT" ]
null
null
null
#include <ros/ros.h> #include <ros/console.h> // MoveIt #include <moveit/planning_scene_interface/planning_scene_interface.h> #include <moveit/move_group_interface/move_group_interface.h> // TF2 #include <tf2_geometry_msgs/tf2_geometry_msgs.h> // Gazebo #include <gazebo_msgs/GetModelState.h> #include <gazebo_msgs/SetModelState.h> #include "pick_and_place/PickSrv.h" #include "pick_and_place/PlaceSrv.h" moveit::planning_interface::PlanningSceneInterface *planning_scene_interface; boost::scoped_ptr<moveit::planning_interface::MoveGroupInterface> group; std::string held_object = ""; void add_coll_object(std::string obj) { moveit_msgs::CollisionObject object; // Add the bounding box for obj. object.id = obj; object.header.frame_id = "trina2_1/base_link"; /* Define the primitive and its dimensions. Update with dimensions from Gazebo when available*/ object.primitives.resize(1); object.primitives[0].type = object.primitives[0].BOX; object.primitives[0].dimensions.resize(3); if (obj == "unit_box") { //table object.primitives[0].dimensions[0] = 2.0; object.primitives[0].dimensions[1] = 1.0; object.primitives[0].dimensions[2] = 0.5; } else { object.primitives[0].dimensions[0] = 0.03; object.primitives[0].dimensions[1] = 0.03; object.primitives[0].dimensions[2] = 0.1; } gazebo_msgs::GetModelState block_state; block_state.request.model_name = obj; block_state.request.relative_entity_name = "trina2_1/base_link"; // get_block_client.call(block_state); // bool result = block_state.response.success; // if (!result) // ROS_WARN("service call to get_model_state failed!"); // else // ROS_INFO("Done"); if (ros::service::call("/gazebo/get_model_state", block_state)) ROS_INFO("Got model state"); else { ROS_WARN("service call to get_model_state failed!"); return; } /* Define the pose of the table. */ object.primitive_poses.resize(1); object.primitive_poses[0] = block_state.response.pose; object.operation = object.ADD; planning_scene_interface->applyCollisionObject(object); } void openGripper(trajectory_msgs::JointTrajectory &posture) { // Add all joints of right gripper move group. posture.joint_names.resize(6); posture.joint_names[0] = "trina2_1/right_arm_finger_joint"; posture.joint_names[1] = "trina2_1/right_arm_left_inner_finger_joint"; posture.joint_names[2] = "trina2_1/right_arm_left_inner_knuckle_joint"; posture.joint_names[3] = "trina2_1/right_arm_right_inner_knuckle_joint"; posture.joint_names[4] = "trina2_1/right_arm_right_outer_knuckle_joint"; posture.joint_names[5] = "trina2_1/right_arm_right_inner_finger_joint"; // Set them as open. posture.points.resize(1); posture.points[0].positions.resize(6); posture.points[0].positions[0] = 0.00; posture.points[0].time_from_start = ros::Duration(0.5); } void closedGripper(trajectory_msgs::JointTrajectory &posture) { // Add all joints of the left gripper move group - make these generic later posture.joint_names.resize(6); posture.joint_names[0] = "trina2_1/right_arm_finger_joint"; posture.joint_names[1] = "trina2_1/right_arm_left_inner_finger_joint"; posture.joint_names[2] = "trina2_1/right_arm_left_inner_knuckle_joint"; posture.joint_names[3] = "trina2_1/right_arm_right_inner_knuckle_joint"; posture.joint_names[4] = "trina2_1/right_arm_right_outer_knuckle_joint"; posture.joint_names[5] = "trina2_1/right_arm_right_inner_finger_joint"; /* Set them as closed. */ posture.points.resize(1); posture.points[0].positions.resize(6); posture.points[0].positions[0] = 0.8; posture.points[0].time_from_start = ros::Duration(0.5); } moveit::planning_interface::MoveItErrorCode pick_block(std::string pick_obj) { std::vector<moveit_msgs::Grasp> grasps; grasps.resize(1); moveit::planning_interface::MoveItErrorCode result = moveit::planning_interface::MoveItErrorCode::FAILURE; // Setting grasp pose // ++++++++++++++++++++++ gazebo_msgs::GetModelState block_state; block_state.request.relative_entity_name = "trina2_1/base_link"; block_state.request.model_name = pick_obj; if (ros::service::call("/gazebo/get_model_state", block_state)) ROS_INFO("Done"); else { ROS_WARN("service call to get_model_state failed!"); return result; } geometry_msgs::Pose target_pose1 = block_state.response.pose; grasps[0].grasp_pose.header.frame_id = "trina2_1/base_link"; tf2::Quaternion orientation; orientation.setRPY(-M_PI / 4, -M_PI, -M_PI / 2); grasps[0].grasp_pose.pose.orientation = tf2::toMsg(orientation); grasps[0].grasp_pose.pose.position = block_state.response.pose.position; grasps[0].grasp_pose.pose.position.x -= 0.08; grasps[0].grasp_pose.pose.position.y -= 0.01; grasps[0].grasp_pose.pose.position.z += 0.08; // Setting pre-grasp approach // ++++++++++++++++++++++++++ /* Defined with respect to frame_id */ grasps[0].pre_grasp_approach.direction.header.frame_id = "trina2_1/base_link"; /* Direction is set as positive x axis */ grasps[0].pre_grasp_approach.direction.vector.x = 1.0; grasps[0].pre_grasp_approach.min_distance = 0.095; grasps[0].pre_grasp_approach.desired_distance = 0.115; // Setting post-grasp retreat // ++++++++++++++++++++++++++ /* Defined with respect to frame_id */ grasps[0].post_grasp_retreat.direction.header.frame_id = "trina2_1/base_link"; /* Direction is set as positive z axis */ grasps[0].post_grasp_retreat.direction.vector.z = 1.0; grasps[0].post_grasp_retreat.min_distance = 0.1; grasps[0].post_grasp_retreat.desired_distance = 0.25; // Setting posture of eef before grasp // +++++++++++++++++++++++++++++++++++ openGripper(grasps[0].pre_grasp_posture); // Setting posture of eef during grasp // +++++++++++++++++++++++++++++++++++ closedGripper(grasps[0].grasp_posture); // Set support surface as table1. group->setSupportSurfaceName("unit_box"); // Call pick to pick up the object using the grasps given group->setGoalTolerance(0.05); group->setStartStateToCurrentState(); result = group->pick(pick_obj, grasps); held_object = pick_obj; return result; } bool trina_pick(pick_and_place::PickSrv::Request &req, pick_and_place::PickSrv::Response &res) { std::string pick_obj = req.pick_obj; ROS_INFO("Pick requested"); add_coll_object(pick_obj); res.success = (pick_block(pick_obj) == moveit::planning_interface::MoveItErrorCode::SUCCESS); return res.success; } moveit::planning_interface::MoveItErrorCode place_block(double x, double y) { // Create a vector of placings to be attempted, currently only creating single place location. std::vector<moveit_msgs::PlaceLocation> place_location; place_location.resize(1); moveit::planning_interface::MoveItErrorCode result = moveit::planning_interface::MoveItErrorCode::FAILURE; // Setting place location pose // +++++++++++++++++++++++++++ place_location[0].place_pose.header.frame_id = "trina2_1/base_link"; tf2::Quaternion orientation; orientation.setRPY(0, 0, M_PI / 2); place_location[0].place_pose.pose.orientation = tf2::toMsg(orientation); /* While placing it is the exact location of the center of the object. */ place_location[0].place_pose.pose.position.x = x; //0.8; place_location[0].place_pose.pose.position.y = y; //0.51; place_location[0].place_pose.pose.position.z = 0.54; // Setting pre-place approach // ++++++++++++++++++++++++++ /* Defined with respect to frame_id */ place_location[0].pre_place_approach.direction.header.frame_id = "trina2_1/base_link"; /* Direction is set as negative z axis */ place_location[0].pre_place_approach.direction.vector.z = -1.0; place_location[0].pre_place_approach.min_distance = 0.095; place_location[0].pre_place_approach.desired_distance = 0.115; // Setting post-grasp retreat // ++++++++++++++++++++++++++ /* Defined with respect to frame_id */ place_location[0].post_place_retreat.direction.header.frame_id = "trina2_1/base_link"; /* Direction is set as negative y axis */ place_location[0].post_place_retreat.direction.vector.x = -1.0; place_location[0].post_place_retreat.min_distance = 0.1; place_location[0].post_place_retreat.desired_distance = 0.25; // Setting posture of eef after placing object // +++++++++++++++++++++++++++++++++++++++++++ /* Similar to the pick case */ openGripper(place_location[0].post_place_posture); // Set support surface group->setSupportSurfaceName("unit_box"); // Call place to place the object using the place locations given. result = group->place(held_object, place_location); return result; } bool trina_place(pick_and_place::PlaceSrv::Request &req, pick_and_place::PlaceSrv::Response &res) { ROS_INFO("Place requested"); res.success = (place_block(req.x, req.y) == moveit::planning_interface::MoveItErrorCode::SUCCESS); return res.success; } int main(int argc, char **argv) { ros::init(argc, argv, "arm_to_block"); ros::NodeHandle nh; ros::AsyncSpinner spinner(0); spinner.start(); ros::WallDuration(1.0).sleep(); if (ros::console::set_logger_level(ROSCONSOLE_DEFAULT_NAME, ros::console::levels::Debug)) { ros::console::notifyLoggerLevelsChanged(); } group.reset(new moveit::planning_interface::MoveGroupInterface("right_arm")); group->setPlanningTime(45.0); planning_scene_interface = new moveit::planning_interface::PlanningSceneInterface(); moveit::planning_interface::MoveGroupInterface::Plan my_plan; //TODO: Clear collision objects before starting node? add_coll_object("unit_box"); ros::ServiceServer pick_service = nh.advertiseService("trina_pick", trina_pick); ros::ServiceServer place_service = nh.advertiseService("trina_place", trina_place); ros::waitForShutdown(); return 0; }
39.034483
110
0.697782
[ "object", "vector", "model" ]
1dd3bf58fdc5a22160765ce2443ed7d78e5135d6
5,080
hpp
C++
includes/eeros/hal/RealsenseT265.hpp
ClaudiaVisentin/eeros-framework
63739a2e33b0c5e9e573748fef675131c35181a6
[ "Apache-2.0" ]
null
null
null
includes/eeros/hal/RealsenseT265.hpp
ClaudiaVisentin/eeros-framework
63739a2e33b0c5e9e573748fef675131c35181a6
[ "Apache-2.0" ]
null
null
null
includes/eeros/hal/RealsenseT265.hpp
ClaudiaVisentin/eeros-framework
63739a2e33b0c5e9e573748fef675131c35181a6
[ "Apache-2.0" ]
null
null
null
#ifndef ORG_EEROS_HAL_REALSENSE_T265_HPP #define ORG_EEROS_HAL_REALSENSE_T265_HPP #include <eeros/core/Runnable.hpp> #include <eeros/control/TimeDomain.hpp> #include <eeros/logger/Logger.hpp> #include <eeros/core/Thread.hpp> #include <eeros/math/Matrix.hpp> #include <librealsense2/rs.hpp> #include <librealsense2/h/rs_types.h> // #include <iostream> // #include <unistd.h> // #include <chrono> // #include <cstring> // #include <eeros/logger/Logger.hpp> // #include <eeros/logger/StreamLogWriter.hpp> // #include <eeros/hal/RealsenseT265.hpp> // // using namespace eeros::logger; // using namespace eeros::math; // using namespace eeros::hal; namespace eeros { namespace hal { /** * This class is part of the hardware abstraction layer. * It is used by \ref eeros::control::RealsenseT265Input class. * Do not use it directly. * */ class RealsenseT265 : public eeros::Thread { public: // Struct to store trajectory points struct tracked_point { rs2_vector point; unsigned int confidence; }; /** * Constructs a Thread to get Realsense Tracking T265 sensors data \n * Calls RealsenseT265(std::string dev, int priority) * * @see RealsenseT265(std::string dev, int priority) * @param dev - string with device name (USB3) * @param priority - execution priority or RealsenseT265 thread, to get sensors data */ explicit RealsenseT265(std::string dev, int priority) : Thread(priority), log(eeros::logger::Logger::getLogger('P')){ started = false; cfg.enable_stream(RS2_STREAM_POSE, RS2_FORMAT_6DOF); // Add pose stream pipe.start(cfg); // Start pipeline with chosen configuration started = true; } /** * Destructs a Thread to get RealsenseT265 sensors data \n */ ~RealsenseT265() { running = false; join(); } eeros::math::Vector3 translation; eeros::math::Vector3 velocity; eeros::math::Vector3 acceleration; eeros::math::Vector4 quaternion; eeros::math::Vector3 angular_velocity; eeros::math::Vector3 angular_acceleration; private: eeros::logger::Logger log; /** * Runs methods for data acquisition from sensor * Gets data, performs scaling, saves tracked_point information on a vector * @see calc_transform * @see tracked_point * */ virtual void run(){ while(!started); running = true; while (running) { // Wait for the next set of frames from the camera auto frames = pipe.wait_for_frames(); // Get a frame from the pose stream auto f = frames.first_or_default(RS2_STREAM_POSE); // Cast the frame to pose_frame and get its data auto pose_data = f.as<rs2::pose_frame>().get_pose_data(); // outputs for eeros translation << pose_data.translation.x, pose_data.translation.y, pose_data.translation.z; velocity << pose_data.velocity.x, pose_data.velocity.y, pose_data.velocity.z; acceleration << pose_data.acceleration.x, pose_data.acceleration.y, pose_data.acceleration.z; quaternion << pose_data.rotation.w, pose_data.rotation.x, pose_data.rotation.y, pose_data.rotation.z; angular_velocity << pose_data.angular_velocity.x, pose_data.angular_velocity.y, pose_data.angular_velocity.z; angular_acceleration << pose_data.angular_acceleration.x, pose_data.angular_acceleration.y, pose_data.angular_acceleration.z; // Calculate current transformation matrix float r[16]; calc_transform(pose_data, r); // From the matrix we found, get the new location point rs2_vector tr{ r[12], r[13], r[14] }; // Create a new point to be added to the trajectory tracked_point p{ tr , pose_data.tracker_confidence }; } } volatile bool started; volatile bool running; rs2::pipeline pipe; // Declare RealSense pipeline, encapsulating the actual device and sensors rs2::config cfg; // Create a configuration for configuring the pipeline with a non default profile /** * Calculates transformation matrix based on pose data from the device * Is called by the run() method * @see run() */ void calc_transform(rs2_pose& pose_data, float mat[16]) { auto q = pose_data.rotation; auto t = pose_data.translation; // Set the matrix as column-major for convenient work with OpenGL and rotate by 180 degress (by negating 1st and 3rd columns) mat[0] = -(1 - 2 * q.y*q.y - 2 * q.z*q.z); mat[4] = 2 * q.x*q.y - 2 * q.z*q.w; mat[8] = -(2 * q.x*q.z + 2 * q.y*q.w); mat[12] = t.x; mat[1] = -(2 * q.x*q.y + 2 * q.z*q.w); mat[5] = 1 - 2 * q.x*q.x - 2 * q.z*q.z; mat[9] = -(2 * q.y*q.z - 2 * q.x*q.w); mat[13] = t.y; mat[2] = -(2 * q.x*q.z - 2 * q.y*q.w); mat[6] = 2 * q.y*q.z + 2 * q.x*q.w; mat[10] = -(1 - 2 * q.x*q.x - 2 * q.y*q.y); mat[14] = t.z; mat[3] = 0.0f; mat[7] = 0.0f; mat[11] = 0.0f; mat[15] = 1.0f; } /* void add_to_trajectory(tracked_point& p);*/ }; }; } #endif /* ORG_EEROS_HAL_REALSENSE_T265_HPP */
36.028369
145
0.654134
[ "vector" ]
1dd523ecab1a011fc4be02270bb76ece07858a27
8,653
cxx
C++
Utilities/Xdmf2/vtk/vtkXdmfDataArray.cxx
certik/paraview
973d37b466552ce770ac0674f30040bb7e31d7fe
[ "BSD-3-Clause" ]
1
2016-05-09T00:36:44.000Z
2016-05-09T00:36:44.000Z
Utilities/Xdmf2/vtk/vtkXdmfDataArray.cxx
certik/paraview
973d37b466552ce770ac0674f30040bb7e31d7fe
[ "BSD-3-Clause" ]
null
null
null
Utilities/Xdmf2/vtk/vtkXdmfDataArray.cxx
certik/paraview
973d37b466552ce770ac0674f30040bb7e31d7fe
[ "BSD-3-Clause" ]
3
2015-05-14T21:18:53.000Z
2022-03-07T02:53:45.000Z
/*******************************************************************/ /* XDMF */ /* eXtensible Data Model and Format */ /* */ /* Id : $Id: vtkXdmfDataArray.cxx,v 1.3 2007/02/23 21:54:21 clarke Exp $ */ /* Date : $Date: 2007/02/23 21:54:21 $ */ /* Version : $Revision: 1.3 $ */ /* */ /* Author: */ /* Jerry A. Clarke */ /* clarke@arl.army.mil */ /* US Army Research Laboratory */ /* Aberdeen Proving Ground, MD */ /* */ /* Copyright @ 2002 US Army Research Laboratory */ /* All Rights Reserved */ /* See Copyright.txt or http://www.arl.hpc.mil/ice 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 <vtkXdmfDataArray.h> #include <vtkObjectFactory.h> #include <vtkCommand.h> #include <vtkUnsignedCharArray.h> #include <vtkCharArray.h> #include <vtkIntArray.h> #include <vtkFloatArray.h> #include <vtkDoubleArray.h> #include <vtkUnsignedIntArray.h> #include "vtkShortArray.h" #include "vtkUnsignedShortArray.h" #include <XdmfArray.h> //---------------------------------------------------------------------------- vtkStandardNewMacro(vtkXdmfDataArray); //---------------------------------------------------------------------------- vtkXdmfDataArray::vtkXdmfDataArray() { this->Array = NULL; this->vtkArray = NULL; } //---------------------------------------------------------------------------- vtkDataArray *vtkXdmfDataArray::FromXdmfArray( char *ArrayName, int CopyShape, int rank, int Components ){ XdmfArray *array = this->Array; if ( ArrayName != NULL ) { array = TagNameToArray( ArrayName ); } if( array == NULL ){ XdmfErrorMessage("Array is NULL"); return(NULL); } if ( this->vtkArray ) { this->vtkArray->Delete(); this->vtkArray = 0; } switch( array->GetNumberType() ){ case XDMF_INT8_TYPE : if( this->vtkArray == NULL ) { this->vtkArray = vtkCharArray::New(); } break; case XDMF_UINT8_TYPE : if( this->vtkArray == NULL ) { this->vtkArray = vtkUnsignedCharArray::New(); } break; case XDMF_INT16_TYPE : if( this->vtkArray == NULL ) { this->vtkArray = vtkShortArray::New(); } break; case XDMF_UINT16_TYPE : if( this->vtkArray == NULL ) { this->vtkArray = vtkUnsignedShortArray::New(); } break; case XDMF_UINT32_TYPE : if( this->vtkArray == NULL ) { this->vtkArray = vtkUnsignedIntArray::New(); } break; case XDMF_INT32_TYPE : case XDMF_INT64_TYPE : if( this->vtkArray == NULL ) { this->vtkArray = vtkIntArray::New(); } break; case XDMF_FLOAT32_TYPE : if( this->vtkArray == NULL ) { this->vtkArray = vtkFloatArray::New(); } break; case XDMF_FLOAT64_TYPE : if( this->vtkArray == NULL ) { this->vtkArray = vtkDoubleArray::New(); } break; default: vtkErrorMacro("Cannot create VTK data array: " << array->GetNumberType()); return 0; } if ( CopyShape ) { XdmfInt64 components = 1; XdmfInt64 tuples = 0; if ( array->GetRank() > rank + 1 ) { this->vtkArray->Delete(); this->vtkArray = 0; vtkErrorMacro("Rank of Xdmf array is more than 1 + rank of dataset"); return 0; } if ( array->GetRank() > rank ) { components = array->GetDimension( rank ); } tuples = array->GetNumberOfElements() / components; /// this breaks components = Components; tuples = array->GetNumberOfElements() / components; // cout << "Tuples: " << tuples << " components: " << components << endl; // cout << "Rank: " << rank << endl; this->vtkArray->SetNumberOfComponents( components ); this->vtkArray->SetNumberOfTuples( tuples ); } else { this->vtkArray->SetNumberOfComponents( 1 ); this->vtkArray->SetNumberOfTuples( array->GetNumberOfElements() ); } //cout << "Number type: " << array->GetNumberType() << endl; switch( array->GetNumberType() ){ case XDMF_INT8_TYPE : array->GetValues( 0, ( XDMF_8_INT*)this->vtkArray->GetVoidPointer( 0 ), array->GetNumberOfElements() ); break; case XDMF_UINT8_TYPE : array->GetValues( 0, ( XDMF_8_U_INT*)this->vtkArray->GetVoidPointer( 0 ), array->GetNumberOfElements() ); break; case XDMF_INT32_TYPE : array->GetValues( 0, (XDMF_32_INT *)this->vtkArray->GetVoidPointer( 0 ), array->GetNumberOfElements() ); break; case XDMF_UINT32_TYPE : array->GetValues( 0, (XDMF_32_U_INT *)this->vtkArray->GetVoidPointer( 0 ), array->GetNumberOfElements() ); break; case XDMF_FLOAT32_TYPE : array->GetValues( 0, ( float *)this->vtkArray->GetVoidPointer( 0 ), array->GetNumberOfElements() ); break; case XDMF_FLOAT64_TYPE : array->GetValues( 0, ( double *)this->vtkArray->GetVoidPointer( 0 ), array->GetNumberOfElements() ); break; default : if ( array->GetNumberOfElements() > 0 ) { //cout << "Manual idx" << endl; //cout << "Tuples: " << vtkArray->GetNumberOfTuples() << endl; //cout << "Components: " << vtkArray->GetNumberOfComponents() << endl; //cout << "Elements: " << array->GetNumberOfElements() << endl; vtkIdType jj, kk; vtkIdType idx = 0; for ( jj = 0; jj < vtkArray->GetNumberOfTuples(); jj ++ ) { for ( kk = 0; kk < vtkArray->GetNumberOfComponents(); kk ++ ) { double val = array->GetValueAsFloat64(idx); //cout << "Value: " << val << endl; vtkArray->SetComponent(jj, kk, val); idx ++; } } } break; } return( this->vtkArray ); } //---------------------------------------------------------------------------- char *vtkXdmfDataArray::ToXdmfArray( vtkDataArray *DataArray, int CopyShape ){ XdmfArray *array; if ( DataArray == NULL ) { DataArray = this->vtkArray; } if ( DataArray == NULL ) { vtkDebugMacro(<< "Array is NULL"); return(NULL); } if ( this->Array == NULL ){ this->Array = new XdmfArray(); switch( DataArray->GetDataType() ){ case VTK_CHAR : case VTK_UNSIGNED_CHAR : this->Array->SetNumberType( XDMF_INT8_TYPE ); break; case VTK_SHORT : case VTK_UNSIGNED_SHORT : case VTK_INT : case VTK_UNSIGNED_INT : case VTK_LONG : case VTK_UNSIGNED_LONG : this->Array->SetNumberType( XDMF_INT32_TYPE ); break; case VTK_FLOAT : this->Array->SetNumberType( XDMF_FLOAT32_TYPE ); break; case VTK_DOUBLE : this->Array->SetNumberType( XDMF_FLOAT64_TYPE ); break; default : XdmfErrorMessage("Can't handle Data Type"); return( NULL ); } } array = this->Array; if( CopyShape ) { XdmfInt64 Shape[3]; Shape[0] = DataArray->GetNumberOfTuples(); Shape[1] = DataArray->GetNumberOfComponents(); if( Shape[1] == 1 ) { array->SetShape( 1, Shape ); } else { array->SetShape( 2, Shape ); } } switch( array->GetNumberType() ){ case XDMF_INT8_TYPE : array->SetValues( 0, ( unsigned char *)DataArray->GetVoidPointer( 0 ), array->GetNumberOfElements() ); break; case XDMF_INT32_TYPE : case XDMF_INT64_TYPE : array->SetValues( 0, ( int *)DataArray->GetVoidPointer( 0 ), array->GetNumberOfElements() ); break; case XDMF_FLOAT32_TYPE : array->SetValues( 0, ( float *)DataArray->GetVoidPointer( 0 ), array->GetNumberOfElements() ); break; default : array->SetValues( 0, ( double *)DataArray->GetVoidPointer( 0 ), array->GetNumberOfElements() ); break; } return( array->GetTagName() ); }
31.580292
78
0.525136
[ "shape", "model" ]
1b91de1e1f1ad994c712ceb8ab0d9c7477d1af6e
53,566
cpp
C++
src/TpMMPD/DIDRO/divers.cpp
kikislater/micmac
3009dbdad62b3ad906ec882b74b85a3db86ca755
[ "CECILL-B" ]
451
2016-11-25T09:40:28.000Z
2022-03-30T04:20:42.000Z
src/TpMMPD/DIDRO/divers.cpp
kikislater/micmac
3009dbdad62b3ad906ec882b74b85a3db86ca755
[ "CECILL-B" ]
143
2016-11-25T20:35:57.000Z
2022-03-01T11:58:02.000Z
src/TpMMPD/DIDRO/divers.cpp
kikislater/micmac
3009dbdad62b3ad906ec882b74b85a3db86ca755
[ "CECILL-B" ]
139
2016-12-02T10:26:21.000Z
2022-03-10T19:40:29.000Z
/*Header-MicMac-eLiSe-25/06/2007 MicMac : Multi Image Correspondances par Methodes Automatiques de Correlation eLiSe : ELements of an Image Software Environnement www.micmac.ign.fr Copyright : Institut Geographique National Author : Marc Pierrot Deseilligny Contributors : Gregoire Maillet, Didier Boldo. [1] M. Pierrot-Deseilligny, N. Paparoditis. "A multiresolution and optimization-based image matching approach: An application to surface reconstruction from SPOT5-HRS stereo imagery." In IAPRS vol XXXVI-1/W41 in ISPRS Workshop On Topographic Mapping From Space (With Special Emphasis on Small Satellites), Ankara, Turquie, 02-2006. [2] M. Pierrot-Deseilligny, "MicMac, un lociel de mise en correspondance d'images, adapte au contexte geograhique" to appears in Bulletin d'information de l'Institut Geographique National, 2007. Francais : MicMac est un logiciel de mise en correspondance d'image adapte au contexte de recherche en information geographique. Il s'appuie sur la bibliotheque de manipulation d'image eLiSe. Il est distibue sous la licences Cecill-B. Voir en bas de fichier et http://www.cecill.info. English : MicMac is an open source software specialized in image matching for research in geographic information. MicMac is built on the eLiSe image library. MicMac is governed by the "Cecill-B licence". See below and http://www.cecill.info. Header-MicMac-eLiSe-25/06/2007*/ #include "StdAfx.h" #include "cimgeo.h" #include "cero_modelonepaire.h" #include "cfeatheringandmosaicking.h" #include "../mergehomol.h" #include "ascii2tif.cpp" extern int RegTIRVIS_main(int , char **); class cLionPaw{ public: cLionPaw(int argc,char ** argv); private: cInterfChantierNameManipulateur * mICNM; bool DoOri,DoMEC,Purge,mF; std::string mDir,mDirPat,mWD,mOut,mOutSufix; bool mRestoreTrash; int mTPImSz1, mTPImSz2; }; class cOneLionPaw{ public: cOneLionPaw(int argc,char ** argv); void testMTD(); void SortImBlurred(); void Restore(); private: cInterfChantierNameManipulateur * mICNM; bool DoOri,DoMEC,Purge,mF; std::string mDir,mDirPat,mWD,mOut,mOutSufix; std::list<std::string> mImName; std::map<int,std::string> mIms; bool mRestoreTrash; int mTPImSz1, mTPImSz2; }; cLionPaw::cLionPaw(int argc,char ** argv): DoOri(1), DoMEC(0), Purge(1), mF(0), mOutSufix("_MM"), mRestoreTrash(1), mTPImSz1(500), mTPImSz2(1000) { mDir="./"; ElInitArgMain ( argc,argv, LArgMain() << EAMC(mDir,"Working Directory", eSAM_IsDir) << EAMC(mDirPat,"Directory Pattern to process", eSAM_IsPatFile) , LArgMain() << EAM(mOutSufix,"Suf",true, "resulting ply suffix , default result is Directory+'_MM'.ply .") << EAM(DoMEC,"DoMEC",true, "Perform dense matching, def false .") << EAM(DoOri,"DoOri",true, "Perform orientation, def true.") << EAM(Purge,"Purge",true, "Purge intermediate results, def true.") << EAM(mF,"F",true, "overwrite results, def false.") << EAM(mRestoreTrash,"Restore",true, "Restore images that are in the Poubelle folder prior to run the photogrammetric pipeline, def true.") << EAM(mTPImSz1,"TPImSz1",true, "Size of image to compute tie point at first iteration (prior to filter images), def=500") << EAM(mTPImSz2,"TPImSz2",true, "Size of image to compute tie point at second iteration (prior to compute orientation), def=1000") ); if (!MMVisualMode) { mICNM = cInterfChantierNameManipulateur::BasicAlloc(mDir); vector<std::string> aVDir = getDirListRegex(mDirPat); list<std::string> aLCom; for (auto & WD : aVDir){ std::string aCom=MMBinFile(MM3DStr)+" TestLib AllAuto " + WD + " " + " Suf="+ mOutSufix + " DoMEC="+ToString(DoMEC)+ " DoOri=" + ToString(DoOri) + " Purge="+ToString(Purge) + " F="+ToString(mF) + " Restore="+ToString(mRestoreTrash) + " TPImSz1="+ToString(mTPImSz1) + " TPImSz2="+ToString(mTPImSz2) ; aLCom.push_back(aCom); std::cout << aCom << "\n"; } cEl_GPAO::DoComInSerie(aLCom); } } cOneLionPaw::cOneLionPaw(int argc,char ** argv): DoOri(1), DoMEC(0), Purge(1), mF(0), mOutSufix("_MM"), mRestoreTrash(1), mTPImSz1(500), mTPImSz2(1000) { mDir="./"; ElInitArgMain ( argc,argv, LArgMain() << EAMC(mDir,"Working Directory", eSAM_IsDir) , LArgMain() << EAM(mOutSufix,"Suf",true, "resulting ply suffix , default result is Directory+'_MM'.ply .") << EAM(DoMEC,"DoMEC",true, "Perform dense matching, def false .") << EAM(DoOri,"DoOri",true, "Perform orientation, def true.") << EAM(Purge,"Purge",true, "Purge intermediate results, def true.") << EAM(mF,"F",true, "overwrite results, def false.") << EAM(mRestoreTrash,"Restore",true, "Restore images that are in the Poubelle folder prior to run the photogrammetric pipeline, def true.") << EAM(mTPImSz1,"TPImSz1",true, "Size of image to compute tie point at first iteration (prior to filter images), def=500") << EAM(mTPImSz2,"TPImSz2",true, "Size of image to compute tie point at second iteration (prior to compute orientation), def=1000") ); if (!MMVisualMode) { #if (ELISE_unix) // apericloud export mOut=mDir+mOutSufix+"_aero.ply"; // pims2ply (Dense Cloud) export std::string mDC=mDir+mOutSufix+".ply"; std::cout << "I will process data " << mDir << "\n"; // martini ne fonctionne que si on est dans le directory grrr std::string aPat("'.*.(jpg|JPG)'"); std::string aCom(""); if (mRestoreTrash) Restore(); // if no MTD, give fake ones testMTD(); //if (DoOri) SortImBlurred(); mICNM = cInterfChantierNameManipulateur::BasicAlloc(mDir); if ( chdir(mDir.c_str())) {} // Warning retunr value if (DoOri){ if(ELISE_fp::IsDirectory("Ori-C1") && mF==0){ std::cout << "Orientation exist, use F=1 to overwrite it\n" ; } else { ELISE_fp::PurgeDirRecursif("Ori-C1"); aCom=MMBinFile(MM3DStr)+" Tapioca All "+ aPat + " " + ToString(mTPImSz1) + " Detect=Digeo"; std::cout << aCom << "\n"; system_call(aCom.c_str()); aCom=MMBinFile(MM3DStr)+" Schnaps "+ aPat + " NbWin=200 MoveBadImgs=1 minPercentCoverage=60 VeryStrict=0 " ; std::cout << aCom << "\n"; // iteratif for (int i(0) ; i<3 ; i++) {system_call(aCom.c_str());} aCom=MMBinFile(MM3DStr)+" Tapioca All "+ aPat + " " + ToString(mTPImSz2) + " Detect=Digeo"; std::cout << aCom << "\n"; system_call(aCom.c_str()); aCom=MMBinFile(MM3DStr)+" Schnaps "+ aPat + " NbWin=200 MoveBadImgs=1 minPercentCoverage=60 VeryStrict=1 " ; std::cout << aCom << "\n"; // iteratif for (int i(0) ; i<3 ; i++) {system_call(aCom.c_str());} aCom=MMBinFile(MM3DStr)+" Tapas RadialExtended "+ aPat + " Out=1 SH=_mini" ; std::cout << aCom << "\n"; system_call(aCom.c_str()); std::cout << aCom << "\n"; //system_call(aCom.c_str()); //aCom=MMBinFile(MM3DStr)+" AperiCloud "+ aPat + " C1 SH=-Ratafia Out=../cloud_" + mOut ; aCom=MMBinFile(MM3DStr)+" AperiCloud "+ aPat + " 1 Out=../" + mOut ; std::cout << aCom << "\n"; system_call(aCom.c_str()); } } if (DoMEC){ if( ELISE_fp::IsDirectory("Ori-1")){ aCom=MMBinFile(MM3DStr)+" PIMs BigMac " + aPat + " 1 ZoomF=8"; std::cout << aCom << "\n"; system_call(aCom.c_str()); aCom=MMBinFile(MM3DStr)+" PIMs2Ply BigMac Out=" + mDC; std::cout << aCom << "\n"; system_call(aCom.c_str()); } } if (Purge) { std::list<std::string> aLDir; aLDir.push_back("Tmp-MM-Dir"); aLDir.push_back("Pyram"); aLDir.push_back("Pastis"); aLDir.push_back("NewOriTmpQuick"); aLDir.push_back("Tmp-ReducTieP"); aLDir.push_back("Ori-RadialBasic"); //aLDir.push_back("Ori-Martini"); aLDir.push_back("Ori-InterneScan"); aLDir.push_back("Homol_mini"); for (auto & dir : aLDir){ if(ELISE_fp::IsDirectory(dir)) { std::cout << "Purge and remove directory " << dir << "\n"; ELISE_fp::PurgeDirRecursif(dir); ELISE_fp::RmDir(dir); } } } #endif } } void cOneLionPaw::SortImBlurred(){ vector<Pt2dr> aVPair; for (auto & imName : mIms){ Im2D_REAL4 aIm=Im2D_REAL4::FromFileStd(imName.second); double aVar = VarLap(&aIm); Pt2dr aPair(imName.first, aVar); aVPair.push_back(aPair); } // choose the best image sortDescendPt2drY(aVPair); int imCt(0); for (auto & pair : aVPair){ if (imCt<25) std::cout << imCt << ": image " << mIms[round(pair.x)] << " i keep it \n"; if (imCt>=25) {std::cout << imCt << ": image " << mIms[round(pair.x)] << " i remove it \n"; std::string aCom("mv " + mIms[round(pair.x)] + " " + mIms[round(pair.x)] + "_bu" ); std::cout << aCom << "\n"; system_call(aCom.c_str()); } imCt++; } } void cOneLionPaw::Restore(){ std::string aCom("mv "+ mDir + "/Poubelle/* "+ mDir + "/" ); system_call(aCom.c_str()); } void cOneLionPaw::testMTD(){ // il ne faut pas qu'il y en aie dans le répertroire "repetition1" std::cout << "Test Metadata \n"; ELISE_fp::RmFileIfExist(mDir+"/MicMac-LocalChantierDescripteur.xml"); mICNM = cInterfChantierNameManipulateur::BasicAlloc("./"); std::string aPat(mDir+"/.*.(jpg|JPG)"); // get first image of im list mImName = mICNM->StdGetListOfFile(aPat); int imCt(0); for (auto & Name : mImName){ mIms[imCt]=Name; imCt++; } cMetaDataPhoto aMTD = cMetaDataPhoto::CreateExiv2(mIms[0]); if (aMTD.Foc35(true)<0){ std::cout << "No metadata, I give some that are fake \n\n\n"; std::string aCall("cp ../MicMac-LocalChantierDescripteur.xml "+mDir+"/"); system_call(aCall.c_str()); } else { std::cout << "Metadata found for image " << mIms[0]<< "\n\n"; } } // survey of a concrete wall, orientation very distorded, we export every tie point as GCP with a Z fixed by the user, in order to use them in campari class cTPM2GCPwithConstantZ{ public: cTPM2GCPwithConstantZ(int argc,char ** argv); private: cInterfChantierNameManipulateur * mICNM; bool mExpTxt,mDebug; double mZ; std::string mDir,mOriPat,mOut3D,mOut2D,mFileSH; std::list<std::string> mOriFL;// OriFileList cSetTiePMul * mTPM; std::vector<std::string> mImName; std::map<int, CamStenope*> mCams; }; cTPM2GCPwithConstantZ::cTPM2GCPwithConstantZ(int argc,char ** argv) { mOut2D="FakeGCP-2D.xml"; mOut3D="FakeGCP-3D.xml"; mDebug=0; mDir="./"; mZ=0; ElInitArgMain ( argc,argv, LArgMain() << EAMC(mDir,"Working Directory", eSAM_IsDir) << EAMC(mOriPat,"Orientation (xml) list of file", eSAM_IsPatFile) << EAMC(mFileSH,"File of new set of homol format (PMulMachin).",eSAM_IsExistFile ) , LArgMain() << EAM(mZ,"Z",true, "Altitude to set for all tie points" ) << EAM(mOut2D,"Out2D",true, "Name of resulting image measures file, def FakeGCP-2D.xml" ) << EAM(mOut3D,"Out3D",true, "Name of resulting ground measures file, def FakeGCP-3D.xml" ) << EAM(mDebug,"Debug",true, "Print message in terminal to help debugging." ) ); if (!MMVisualMode) { mICNM = cInterfChantierNameManipulateur::BasicAlloc(mDir); // load Tie point mTPM = new cSetTiePMul(0); mTPM->AddFile(mFileSH); // load orientations mOriFL = mICNM->StdGetListOfFile(mOriPat); std::string aKey= "NKS-Assoc-Ori2ImGen" ; std::string aTmp1, aNameOri; for (auto &aOri : mOriFL){ // retrieve name of image from name of orientation xml SplitDirAndFile(aTmp1,aNameOri,aOri); std::string NameIm = mICNM->Assoc1To1(aKey,aNameOri,true); mImName.push_back(NameIm); // retrieve IdIm cCelImTPM * ImTPM=mTPM->CelFromName(NameIm); if (ImTPM) { // map of Camera is indexed by the Id of Image (cSetTiePMul) mCams[ImTPM->Id()]=CamOrientGenFromFile(aOri,mICNM); } else { std::cout << "No tie points found for image " << NameIm << ".\n"; } } // initialize dicco appui and mesureappui // 2D cSetOfMesureAppuisFlottants MAF; // 3D cDicoAppuisFlottant DAF; // loop on every config of TPM of the set of TPM int label(0); for (auto & aCnf : mTPM->VPMul()) { // retrieve 3D position in model geometry std::vector<Pt3dr> aPts=aCnf->IntersectBundle(mCams); // add the points int aKp(0); for (auto & Pt: aPts){ // position 3D fake Pt3dr PosXYZ(Pt.x,Pt.y,mZ); cOneAppuisDAF GCP; GCP.Pt()=PosXYZ; GCP.NamePt()=std::string(to_string(label)); GCP.Incertitude()=Pt3dr(1.0,1.0,1.0); DAF.OneAppuisDAF().push_back(GCP); // position 2D for (int nIm(0); nIm<aCnf->NbIm();nIm++) { int IdIm=aCnf->VIdIm().at(nIm); cMesureAppuiFlottant1Im aMark; aMark.NameIm()=mTPM->NameFromId(IdIm); cOneMesureAF1I currentMAF; currentMAF.NamePt()=std::string(to_string(label)); currentMAF.PtIm()= aCnf->GetPtByImgId(aKp,IdIm); aMark.OneMesureAF1I().push_back(currentMAF); MAF.MesureAppuiFlottant1Im().push_back(aMark); } label++; // total count of pt aKp++; // count of pt in config } } MakeFileXML(MAF,mOut2D); MakeFileXML(DAF,mOut3D); } } // we wish to improve coregistration between 2 orthos class cCoreg2Ortho { public: std::string mDir; cCoreg2Ortho(int argc,char ** argv); private: cImGeo * mO1; cImGeo * mO2; Im2D_REAL4 mO1clip,mO2clip; std::string mNameO1, mNameO2, mNameMapOut; Box2dr mBoxOverlapTerrain; }; // vocation de test divers cCoreg2Ortho::cCoreg2Ortho(int argc,char ** argv) { ElInitArgMain ( argc,argv, LArgMain() << EAMC(mNameO1,"Name Ortho master", eSAM_IsExistFile) << EAMC(mNameO2,"Name Ortho slave",eSAM_IsExistFile), LArgMain() << EAM(mNameMapOut,"Out",true, "Name of resulting map") ); if (!MMVisualMode) { mDir="./"; mNameMapOut=mNameO2 +"2"+ mNameO1; //cInterfChantierNameManipulateur * aICNM = cInterfChantierNameManipulateur::BasicAlloc(mDir); if (ELISE_fp::exist_file(mNameO1) & ELISE_fp::exist_file(mNameO2)) { // Initialise les 2 orthos mO1 = new cImGeo(mDir+mNameO1); mO2 = new cImGeo(mDir+mNameO2); // Dijkstra's single source shortest path algorithm mBoxOverlapTerrain=mO1->overlapBox(mO2); // clip les 2 orthos sur cette box terrain Im2D_REAL4 o1 = mO1->clipImTer(mBoxOverlapTerrain); Im2D_REAL4 o2 = mO2->clipImTer(mBoxOverlapTerrain); // determiner debut et fin de la ligne d'estompage Im2D_U_INT1 over(o1.sz().x,o2.sz().y,0); // carte des coût, varie de 0 à 1 Im2D_REAL4 cost(o1.sz().x,o2.sz().y,1.0); // pixels d'overlap sont noté 1, pixel sans overlap sont noté 0 ELISE_COPY(select(over.all_pts(), o1.in()!=0 && o2.in()!=0), 1, over.out()); Tiff_Im::CreateFromIm(over,"Tmp_overlap.tif"); } else { std::cout << "cannot find ortho 1 and 2, please check file names\n";} } } // appliquer une translation à une orientation class cOriTran_Appli { public: cOriTran_Appli(int argc,char ** argv); private: std::string mDir; std::string mFullDir; std::string mPat; std::string mOriIn, mOriOut; Pt3dr mTr; }; cOriTran_Appli::cOriTran_Appli(int argc,char ** argv) { ElInitArgMain ( argc,argv, LArgMain() << EAMC(mFullDir,"image pattern", eSAM_IsPatFile) << EAMC(mOriIn,"Orientation Directory", eSAM_IsExistDirOri ) << EAMC(mTr,"Translation vector" ) << EAMC(mOriOut,"Orientation Out" ) ,LArgMain() ); if (!MMVisualMode) { SplitDirAndFile(mDir,mPat,mFullDir); cInterfChantierNameManipulateur * aICNM = cInterfChantierNameManipulateur::BasicAlloc(mDir); StdCorrecNameOrient(mOriIn,mDir); const std::vector<std::string> aSetIm = *(aICNM->Get(mPat)); // the bad way to do this, because I cannot find how to change the optical center of a camera with micmac classes std::string aNameTmp("Tmp-OriTrans.txt"); std::string aCom = MMDir() + std::string("bin/mm3d") + " OriExport Ori-" + mOriIn + std::string("/Orientation-") + mPat + std::string(".xml") + std::string(" ") + aNameTmp; std::cout << aCom << "\n"; system_call(aCom.c_str()); aCom= MMDir() + std::string("bin/mm3d OriConvert '#F=N_X_Y_Z_W_P_K' ") + aNameTmp + std::string(" ") + std::string("OriTrans") + std::string(" OffsetXYZ=") + ToString(mTr); std::cout << aCom << "\n"; system_call(aCom.c_str()); // je fais une bascule la dessus // je vérifie également avec un oriexport que l'offset fonctionnne aCom="cp Ori-"+mOriIn +"/AutoCal* Ori-"+mOriOut+"/"; system_call(aCom.c_str()); /* aCom= MMDir() + std::string("bin/mm3d GCP '#F=N_X_Y_Z_S_S_S' ") + aNameTmp + std::string(" ") + std::string(mOriOut) + std::string(" OffsetXYZ=") + ToString(mTr); std::cout << aCom << "\n"; system_call(aCom.c_str()); */ } } // Applique une homographie à l'ensemble des images thermiques pour les mettres dans la géométrie des images visibles prises simultanément class cTIR2VIS_Appli; class cTIR2VIS_Appli { public: void ReechThermicIm(std::vector<std::string> aPatImgs, std::string aHomog); void CopyOriVis(std::vector<std::string> aPatImgs, std::string aOri); cTIR2VIS_Appli(int argc,char ** argv); string T2V_imName(string tirName); string T2Reech_imName(string tirName); void changeImSize(std::vector<std::string> aLIm); //list image void changeImRadiom(std::vector<std::string> aLIm); //list image std::string mDir; private: std::string mFullDir; std::string mPat; std::string mHomog; std::string mOri; std::string mPrefixReech; bool mOverwrite; Pt2di mImSzOut;// si je veux découper mes images output, ex: homography between 2 sensors of different shape and size (TIR 2 VIS) but I want to have the same dimension as output Pt2di mRadiomRange;// If I want to change radiometry value, mainly to convert 16 bits to 8 bits }; cTIR2VIS_Appli::cTIR2VIS_Appli(int argc,char ** argv) : mFullDir ("img.*.tif"), mHomog ("homography.xml"), mOri ("RTL"), mPrefixReech("Reech"), mOverwrite (false) { ElInitArgMain ( argc,argv, LArgMain() << EAMC(mFullDir,"image pattern", eSAM_IsPatFile) << EAMC(mHomog,"homography XML file", eSAM_IsExistFile ), LArgMain() << EAM(mOri,"Ori",true, "ori name of VIS images", eSAM_IsExistDirOri ) << EAM(mOverwrite,"F",true, "Overwrite previous resampled images, def false") << EAM(mImSzOut,"ImSzOut",true, "Size of output images") << EAM(mRadiomRange,"RadiomRange",true, "range of radiometry of input images, if given, output will be 8 bits images") ); if (!MMVisualMode) { SplitDirAndFile(mDir,mPat,mFullDir); cInterfChantierNameManipulateur * aICNM = cInterfChantierNameManipulateur::BasicAlloc(mDir); const std::vector<std::string> aSetIm = *(aICNM->Get(mPat)); ReechThermicIm(aSetIm,mHomog); if (EAMIsInit(&mOri)) { StdCorrecNameOrient(mOri,mDir); mOri="Ori-"+mOri+"/"; std::cout << "Copy orientation file." << std::endl; CopyOriVis(aSetIm,mOri); } // changer la taille des images out if (EAMIsInit(&mImSzOut)) { //open first reech image just to read the dimension in order to print a message Tiff_Im mTif=Tiff_Im::StdConvGen(T2Reech_imName(aSetIm.at(0)),1,true); std::cout << "Change size of output images from " << mTif.sz() << " to " << mImSzOut << "\n"; changeImSize(aSetIm); } // change the image radiometry if (EAMIsInit(&mRadiomRange)) { std::cout << "Change images dynamic from range " << mRadiomRange << " to [0, 255] \n"; changeImRadiom(aSetIm); } } } void cTIR2VIS_Appli::ReechThermicIm( std::vector<std::string> _SetIm, std::string aHomog ) { std::list<std::string> aLCom; for(unsigned int aK=0; aK<_SetIm.size(); aK++) { string aNameOut = "Reech_" + NameWithoutDir(StdPrefix(_SetIm.at(aK))) + ".tif";// le nom default donnée par ReechImMap std::string aCom = MMDir() + std::string("bin/mm3d") + std::string(" ") + "ReechImMap" + std::string(" ") + _SetIm.at(aK) + std::string(" ") + aHomog; if (EAMIsInit(&mPrefixReech)) { aCom += " PrefixOut=" + T2Reech_imName(_SetIm.at(aK)) ; } //+ " Win=[3,3]";// taille de fenetre pour le rééchantillonnage, par défaut 5x5 bool Exist= ELISE_fp::exist_file(T2Reech_imName(_SetIm.at(aK))); if(!Exist || mOverwrite) { std::cout << "aCom = " << aCom << std::endl; //system_call(aCom.c_str()); aLCom.push_back(aCom); } else { std::cout << "Reech image " << T2Reech_imName(_SetIm.at(aK)) << " exist, use F=1 to overwrite \n"; } } cEl_GPAO::DoComInParal(aLCom); } // dupliquer l'orientation des images visibles de la variocam pour les images thermiques accociées void cTIR2VIS_Appli::CopyOriVis( std::vector<std::string> _SetIm, std::string aOri ) { for(auto & imTIR: _SetIm) { //cInterfChantierNameManipulateur * aICNM = cInterfChantierNameManipulateur::BasicAlloc(mDir); std::string aOriFileName(aOri+"Orientation-"+T2V_imName(imTIR)+".xml"); if (ELISE_fp::exist_file(aOriFileName)) { std::string aCom="cp " + aOriFileName + " "+ aOri+"Orientation-" + T2Reech_imName(imTIR) +".xml"; std::cout << "aCom = " << aCom << std::endl; system_call(aCom.c_str()); } else { std::cout << "Can not copy orientation " << aOriFileName << " because file not found." << std::endl; } } } string cTIR2VIS_Appli::T2V_imName(string tirName) { std::string visName=tirName; visName[0]='V'; visName[2]='S'; return visName; } string cTIR2VIS_Appli::T2Reech_imName(string tirName) { return mPrefixReech+ "_" + tirName; } int T2V_main(int argc,char ** argv) { cTIR2VIS_Appli aT2V(argc,argv); return EXIT_SUCCESS; } void cTIR2VIS_Appli::changeImSize(std::vector<std::string> aLIm) { for(auto & imTIR: aLIm) { // load reech images Tiff_Im mTifIn=Tiff_Im::StdConvGen(T2Reech_imName(imTIR),1,true); // create RAM image Im2D_REAL4 im(mImSzOut.x,mImSzOut.y); // y sauver l'image ELISE_COPY(mTifIn.all_pts(),mTifIn.in(),im.out()); // juste clipper Tiff_Im aTifOut ( T2Reech_imName(imTIR).c_str(), im.sz(), GenIm::real4, Tiff_Im::No_Compr, Tiff_Im::BlackIsZero ); // on écrase le fichier tif ELISE_COPY(im.all_pts(),im.in(),aTifOut.out()); } } void cTIR2VIS_Appli::changeImRadiom(std::vector<std::string> aLIm) { for(auto & imTIR: aLIm) { int minRad(mRadiomRange.x), rangeRad(mRadiomRange.y-mRadiomRange.x); // load reech images Tiff_Im mTifIn=Tiff_Im::StdConvGen(T2Reech_imName(imTIR),1,true); // create empty RAM image for imput image Im2D_REAL4 imIn(mTifIn.sz().x,mTifIn.sz().y); // create empty RAM image for output image Im2D_U_INT1 imOut(mTifIn.sz().x,mTifIn.sz().y); // fill it with tiff image value ELISE_COPY( mTifIn.all_pts(), mTifIn.in(), imIn.out() ); // change radiometry for (int v(0); v<imIn.sz().y;v++) { for (int u(0); u<imIn.sz().x;u++) { Pt2di pt(u,v); double aVal = imIn.GetR(pt); unsigned int v(0); if(aVal!=0){ if (aVal>minRad && aVal <minRad+rangeRad) { v=255.0*(aVal-minRad)/rangeRad; } } imOut.SetR(pt,v); //std::cout << "aVal a la position " << pt << " vaut " << aVal << ", transfo en " << v <<"\n"; } } // remove file to be sure of result //ELISE_fp::RmFile(T2Reech_imName(imTIR)); Tiff_Im aTifOut ( T2Reech_imName(imTIR).c_str(), imOut.sz(), GenIm::u_int1, Tiff_Im::No_Compr, Tiff_Im::BlackIsZero ); // on écrase le fichier tif ELISE_COPY(imOut.all_pts(),imOut.in(),aTifOut.out()); } } /* comparaise des orthos thermiques pour déterminer un éventuel facteur de calibration spectrale entre 2 frame successif, expliquer pouquoi tant de variabilité spectrale est présente (mosaique moche) */ // à priori ce n'est pas ça du tout, déjà mauvaise registration TIR --> vis du coup les ortho TIR ne se superposent pas , du coup correction metrique ne peut pas fonctionner. int CmpOrthosTir_main(int argc,char ** argv) { std::string aDir, aPat="Ort_.*.tif", aPrefix="ratio"; int aScale = 1; bool Test=true; std::list<std::string> mLFile; std::vector<cImGeo> mLIm; ElInitArgMain ( argc,argv, LArgMain() << EAMC(aDir,"Ortho's Directory", eSAM_IsExistFile), LArgMain() << EAM(aPat,"Pat",false,"Ortho's image pattern, def='Ort_.*'",eSAM_IsPatFile) << EAM(aScale,"Scale",false,"Scale factor for both Orthoimages ; Def=1") << EAM(Test,"T",false, "Test filtre des bords") << EAM(aPrefix,"Prefix", false,"Prefix pour les ratio, default = ratio") ); cInterfChantierNameManipulateur * aICNM = cInterfChantierNameManipulateur::BasicAlloc(aDir); // create the list of images starting from the regular expression (Pattern) mLFile = aICNM->StdGetListOfFile(aPat); for (auto & imName : mLFile){ //read Ortho cImGeo aIm(imName); std::cout << "nom image " << aIm.Name() << "\n"; mLIm.push_back(aIm); } std::cout << mLFile.size() << " Ortho chargées.\n"; // tester si l'overlap est suffisant int i(0); for (auto aCurrentImGeo: mLIm) { i++; for (unsigned int j=i ; j<mLFile.size(); j++) { if (mLIm.at(j).Name()!=aCurrentImGeo.Name() && mLIm.at(j).overlap(&aCurrentImGeo,70)) { Pt2di aTr=aCurrentImGeo.computeTrans(&mLIm.at(j)); //std::string aName="ratio"+std::to_string(j)+"on"+std::to_string(j+1)+".tif"; std::string aName=aPrefix+aCurrentImGeo.Name()+"on"+mLIm.at(j).Name()+".tif"; // copie sur disque de l'image // pas très pertinent, je devrais plutot faire tout les calcul en ram puis sauver l'image à la fin avec un constructeur de cImGeo qui utilise une image RAM et les info du georef cImGeo aImGeo(& aCurrentImGeo, aName); aImGeo.applyTrans(aTr); Im2D_REAL4 aIm=aImGeo.toRAM(); Im2D_REAL4 aIm2(aIm.sz().x, aIm.sz().y); Im2D_REAL4 aImEmpty(aIm.sz().x, aIm.sz().y); Im2D_REAL4 aIm3=mLIm.at(j).toRAM(); // l'image 1 n'as pas la meme taille, on la copie dans une image de meme dimension que l'im 0 ELISE_COPY ( aIm3.all_pts(), aIm3.in(),// l'image 1 n'as pas la meme taille, on la copie dans une image de meme dimension que l'im 0n(), aIm2.oclip() ); // division de im 0 par im 1 ELISE_COPY ( select(aIm.all_pts(),aIm2.in()>0), (aIm.in())/(aIm2.in()), aImEmpty.oclip() ); if (Test){ // etape de dilation, effet de bord non désiré int it(0); do{ Neighbourhood V8 = Neighbourhood::v8(); Liste_Pts_INT2 l2(2); ELISE_COPY ( dilate ( select(aImEmpty.all_pts(),aImEmpty.in()==0), sel_func(V8,aImEmpty.in_proj()>0) ), 1000,// je me fous de la valeur c'est pour créer un flux de points surtout aImEmpty.out() | l2 // il faut écrire et dans la liste de point, et dans l'image, sinon il va repecher plusieur fois le meme point ); // j'enleve l'effet de bord , valleurs nulles ELISE_COPY ( l2.all_pts(), 0, aImEmpty.out() ); it++; } while (it<3); } // je sauve mon image RAM dans mon image tif file aImGeo.updateTiffIm(&aImEmpty); // je calcule la moyenne du ratio int nbVal(0); double somme(0); for(int aI=0; aI<aImEmpty.sz().x; aI++) { for(int aJ=0; aJ<aImEmpty.sz().y; aJ++) { Pt2di aCoor(aI,aJ); double aValue = aImEmpty.GetR(aCoor); if (aValue!=0) { somme +=aValue; nbVal++; //std::cout <<"Valeur:"<<aValue<< "\n"; } } //fprintf(aFP,"\n"); } somme/=nbVal; std::cout << "Ratio de l'image " << aCurrentImGeo.Name() << " sur l'image " << mLIm.at(j).Name() << " caclulé, moyenne de "<< somme << " ------------\n"; // end if } // end boucle 1 } // end boucle 2 } return EXIT_SUCCESS; } int ComputeStat_main(int argc,char ** argv) { double NoData(0); std::string aPat("Ree*.tif"); std::list<std::string> mLFile; ElInitArgMain ( argc,argv, LArgMain() << EAMC(aPat,"Image pattern",eSAM_IsPatFile), LArgMain() << EAM(NoData,"ND", "no data value, default 0") ); std::cout <<" Debut\n"; cInterfChantierNameManipulateur * aICNM = cInterfChantierNameManipulateur::BasicAlloc("./"); // create the list of images starting from the regular expression (Pattern) mLFile = aICNM->StdGetListOfFile(aPat); std::cout << mLFile.size() << " images\n"; double aMax(0), aMin(0); for (auto & aName : mLFile){ Tiff_Im mTif=Tiff_Im::StdConvGen(aName,1,true); Im2D_REAL4 aImRAM(mTif.sz().x, mTif.sz().y); ELISE_COPY ( mTif.all_pts(), mTif.in(), aImRAM.out() ); // je calcule la moyenne du ratio int nbVal(0); bool firstVal=1; double somme(0),min(1e30) /* MPD Warn uninit*/ ,max(0); for(int aI=0; aI<aImRAM.sz().x; aI++) { for(int aJ=0; aJ<aImRAM.sz().y; aJ++) { Pt2di aCoor(aI,aJ); double aValue = aImRAM.GetR(aCoor); if (aValue!=NoData) { if (firstVal) { min=aValue; firstVal=0; } if (aValue<min) min=aValue; if (aValue>max) max=aValue; somme +=aValue; nbVal++; } } } somme/=nbVal; std::cout <<"Statistique Image "<<aName<< "\n"; std::cout << "Nb value !=" << NoData << " :" << nbVal << "\n"; std::cout << "Mean :" << somme <<"\n"; std::cout << "Max :" << max <<"\n"; std::cout << "Min :" << min <<"\n"; std::cout << "Dynamique (max-min) :" << max-min <<"\n"; // stat sur toutes les images if (mLFile.front()==aName) { aMin=min; aMax=max; } if (max>aMax) aMax=max; if (min<aMin) aMin=min; } std::cout << "Max de toutes les images :" << aMax <<"\n"; std::cout << "Min de toutes les iamges :" << aMin <<"\n"; std::cout << "Dynamique (max-min) :" << aMax-aMin <<"\n"; return EXIT_SUCCESS; } // j'ai utilisé saisieAppui pour saisir des points homologues sur plusieurs couples d'images TIR VIS orienté // je dois manipuler le résulat pour le tranformer en set de points homologues pour un unique couple d'images // de plus, la saisie sur les im TIR est effectué sur des images rééchantillonnées, il faut appliquer une homographie inverse au points saisi int TransfoMesureAppuisVario2TP_main(int argc,char ** argv) { std::string a2DMesFileName, aOutputFile1, aOutputFile2,aImName("AK100419.tif"), aNameMap, aDirHomol("Homol-Man"); ElInitArgMain ( argc,argv, //mandatory arguments LArgMain() << EAMC(a2DMesFileName, "Input mes2D file", eSAM_IsExistFile) << EAMC(aNameMap, "Input homography to apply to TIR images measurements", eSAM_IsExistFile), LArgMain() << EAM(aImName,"ImName", true, "Name of Image for output files", eSAM_IsOutputFile) << EAM(aOutputFile1,"Out1", true, "Output TP file 1, def Homol-Man/PastisTIR_ImName/VIS_ImName.txt", eSAM_IsOutputFile) << EAM(aOutputFile2,"Out2", true, "Output TP file 2, def Homol-Man/PastisVIS_ImName/TIR_ImName.txt", eSAM_IsOutputFile) ); if (!EAMIsInit(&aOutputFile1)) { aOutputFile1=aDirHomol + "/PastisTIR_" + aImName + "/VIS_" + aImName + ".txt"; if(!ELISE_fp::IsDirectory(aDirHomol)) ELISE_fp::MkDir(aDirHomol); if(!ELISE_fp::IsDirectory(aDirHomol + "/PastisTIR_" + aImName)) ELISE_fp::MkDir(aDirHomol + "/PastisTIR_" + aImName); } if (!EAMIsInit(&aOutputFile2)) { aOutputFile2=aDirHomol + "/PastisVIS_" + aImName + "/TIR_" + aImName + ".txt"; if(!ELISE_fp::IsDirectory(aDirHomol)) ELISE_fp::MkDir(aDirHomol); if(!ELISE_fp::IsDirectory(aDirHomol + "/PastisVIS_" + aImName)) ELISE_fp::MkDir(aDirHomol + "/PastisVIS_" + aImName); } // lecture de la map 2D cElMap2D * aMap = cElMap2D::FromFile(aNameMap); // conversion de la map 2D en homographie; map 2D: plus de paramètres que l'homographie //1) grille de pt sur le capteur thermique auquel on applique la map2D ElPackHomologue aPackHomMap2Homogr; for (int y=0 ; y<720; y +=10) { for (int x=0 ; x<1200; x +=10) { Pt2dr aPt(x,y); Pt2dr aPt2 = (*aMap)(aPt); ElCplePtsHomologues Homol(aPt,aPt2); aPackHomMap2Homogr.Cple_Add(Homol); } } // convert Map2D to homography cElHomographie H(aPackHomMap2Homogr,true); //H = cElHomographie::RobustInit(qual,aPackHomImTer,bool Ok(1),1, 1.0,4); // initialiser le pack de points homologues ElPackHomologue aPackHom; cSetOfMesureAppuisFlottants aSetOfMesureAppuisFlottants=StdGetFromPCP(a2DMesFileName,SetOfMesureAppuisFlottants); int count=0; for( std::list< cMesureAppuiFlottant1Im >::const_iterator iTmes1Im=aSetOfMesureAppuisFlottants.MesureAppuiFlottant1Im().begin(); iTmes1Im!=aSetOfMesureAppuisFlottants.MesureAppuiFlottant1Im().end(); iTmes1Im++ ) { cMesureAppuiFlottant1Im anImTIR=*iTmes1Im; //std::cout<<anImTIR.NameIm().substr(0,5)<<" \n"; // pour chacune des images thermique rééchantillonnée, recherche l'image visible associée if (anImTIR.NameIm().substr(0,5)=="Reech") { //std::cout<<anImTIR.NameIm()<<" \n"; for (auto anImVIS : aSetOfMesureAppuisFlottants.MesureAppuiFlottant1Im()) { // ne fonctionne que pour la convention de préfixe Reech_TIR_ et VIS_ if(anImTIR.NameIm().substr(10,anImTIR.NameIm().size()) == anImVIS.NameIm().substr(4,anImVIS.NameIm().size())) { // j'ai un couple d'image. //std::cout << "Couple d'images " << anImTIR.NameIm() << " et " <<anImVIS.NameIm() << "\n"; for (auto & appuiTIR : anImTIR.OneMesureAF1I()) { // for (auto & appuiVIS : anImVIS.OneMesureAF1I()) { if (appuiTIR.NamePt()==appuiVIS.NamePt()) { // j'ai 2 mesures pour ce point // std::cout << "Pt " << appuiTIR.NamePt() << ", " <<appuiTIR.PtIm() << " --> " << appuiVIS.PtIm() << "\n"; // J'ajoute ce point au set de points homol ElCplePtsHomologues Homol(appuiTIR.PtIm(),appuiVIS.PtIm()); aPackHom.Cple_Add(Homol); count++; break; } } } break; } } } // fin iter sur les mesures appuis flottant } std::cout << "Total : " << count << " tie points read \n" ; if (!EAMIsInit(&aOutputFile1) && !EAMIsInit(&aOutputFile2)) { if(!ELISE_fp::IsDirectory(aDirHomol + "/PastisReech_TIR_" + aImName)) ELISE_fp::MkDir(aDirHomol + "/PastisReech_TIR_" + aImName); std::cout << "Homol pack saved in : " << aDirHomol + "/PastisReech_TIR_" + aImName + "/VIS_" + aImName + ".txt" << " \n" ; aPackHom.StdPutInFile(aDirHomol + "/PastisReech_TIR_" + aImName + "/VIS_" + aImName + ".txt"); aPackHom.SelfSwap(); std::cout << "Homol pack saved in : " << aDirHomol + "/PastisVIS_" + aImName + "/Reech_TIR_" + aImName + ".txt" << " \n" ; aPackHom.StdPutInFile(aDirHomol + "/PastisVIS_" + aImName + "/Reech_TIR_" + aImName + ".txt"); } // appliquer l'homographie //aPackHom.ApplyHomographies(H.Inverse(),H.Id()); aPackHom.ApplyHomographies(H,H.Id()); // maintenant on sauve ce pack de points homologues std::cout << "Homol pack saved in : " << aOutputFile1 << " \n" ; aPackHom.StdPutInFile(aOutputFile1); aPackHom.SelfSwap(); std::cout << "Homol pack saved in : " << aOutputFile2 << " \n" ; aPackHom.StdPutInFile(aOutputFile2); return EXIT_SUCCESS; } /* j'ai saisi des points d'appuis sur un vol 2 altitudes thermiques, j'aimerai voir si cette radiance est corrélée à -Distance entre sensor et object -->NON -angle --> PAS TESTE moins probable mais je teste quand même: -position sur capteur --> NON -temps écoulé depuis début du vol PAS TESTE */ int statRadianceVarioCam_main(int argc,char ** argv) { std::string a2DMesFileName, a3DMesFileName, aOutputFile, aOri; ElInitArgMain ( argc,argv, //mandatory arguments LArgMain() << EAMC(a2DMesFileName, "Input mes2D file", eSAM_IsExistFile) << EAMC(a3DMesFileName, "Input mes3D file", eSAM_IsExistFile) << EAMC(aOri, "Orientation", eSAM_IsExistDirOri), LArgMain() << EAM(aOutputFile,"Out", true, "Output .txt file with radiance observation for statistic", eSAM_IsOutputFile) ); cInterfChantierNameManipulateur * aICNM = cInterfChantierNameManipulateur::BasicAlloc("./"); // open 2D measures cSetOfMesureAppuisFlottants aSetOfMesureAppuisFlottants=StdGetFromPCP(a2DMesFileName,SetOfMesureAppuisFlottants); // open 3D measures cDicoAppuisFlottant DAF= StdGetFromPCP(a3DMesFileName,DicoAppuisFlottant); std::list<cOneAppuisDAF> & aLGCP = DAF.OneAppuisDAF(); // create a map of GCP and position std::map<std::string, Pt3dr> aGCPmap; for (auto & GCP : aLGCP) { aGCPmap[GCP.NamePt()]=Pt3dr(GCP.Pt().x,GCP.Pt().y,GCP.Pt().z); } std::cout << "Image GCP U V rayon Radiance GroundDist \n" ; for( std::list< cMesureAppuiFlottant1Im >::const_iterator iTmes1Im=aSetOfMesureAppuisFlottants.MesureAppuiFlottant1Im().begin(); iTmes1Im!=aSetOfMesureAppuisFlottants.MesureAppuiFlottant1Im().end(); iTmes1Im++ ) { cMesureAppuiFlottant1Im anImTIR=*iTmes1Im; // open the image if (ELISE_fp::exist_file(anImTIR.NameIm())) { Tiff_Im mTifIn=Tiff_Im::StdConvGen(anImTIR.NameIm(),1,true); // create empty RAM image Im2D_REAL4 im(mTifIn.sz().x,mTifIn.sz().y); // fill it with tiff image value ELISE_COPY( mTifIn.all_pts(), mTifIn.in(), im.out() ); // open the CamStenope std::string aNameOri=aICNM->Assoc1To1("NKS-Assoc-Im2Orient@-"+aOri+"@",anImTIR.NameIm(), true); CamStenope * aCam(CamOrientGenFromFile(aNameOri,aICNM)); //std::cout << "Optical center Cam" << aCam->PseudoOpticalCenter() << "\n"; // loop on the for (auto & appuiTIR : anImTIR.OneMesureAF1I()) { // je garde uniquement les GCP dont le nom commence par L if (appuiTIR.NamePt().substr(0,1)=="L") { Pt3dr pt = aGCPmap[appuiTIR.NamePt()]; // std::cout << " Image " << anImTIR.NameIm() << " GCP " << appuiTIR.NamePt() << " ground position " << pt << " Image position " << appuiTIR.PtIm() << " \n"; double aRadiance(0); int aNb(0); Pt2di UV(appuiTIR.PtIm()); Pt2di sz(1,1); ELISE_COPY( rectangle(UV-sz,UV+Pt2di(2,2)*sz),// not sure how it work Virgule(im.in(),1), Virgule(sigma(aRadiance),sigma(aNb)) ); aRadiance/=aNb; std::cout << " Radiance on windows of " << aNb << " px " << aRadiance << " \n"; aRadiance=aRadiance-27315; // now determine incid and distance from camera to GCP double aDist(0); Pt3dr vDist=aCam->PseudoOpticalCenter()-pt; aDist=euclid(vDist); double aDistUV=euclid(appuiTIR.PtIm()-aCam->PP()); std::cout << anImTIR.NameIm() << " " << appuiTIR.NamePt() << " " << appuiTIR.PtIm().x << " " << appuiTIR.PtIm().y << " " << aDistUV << " " << aRadiance << " " << aDist << " \n"; } } } // fin iter sur les mesures appuis flottant } return EXIT_SUCCESS; } int MasqTIR_main(int argc,char ** argv) { std::string aDir, aPat="Ort_.*.tif"; std::list<std::string> mLFile; std::vector<cImGeo> mLIm; ElInitArgMain ( argc,argv, LArgMain() << EAMC(aDir,"Ortho's Directory", eSAM_IsExistFile), LArgMain() << EAM(aPat,"Pat",false,"Ortho's image pattern, def='Ort_.*'",eSAM_IsPatFile) ); cInterfChantierNameManipulateur * aICNM = cInterfChantierNameManipulateur::BasicAlloc(aDir); // create the list of images starting from the regular expression (Pattern) mLFile = aICNM->StdGetListOfFile(aPat); for (auto & aName : mLFile) { Tiff_Im im=Tiff_Im::StdConvGen("../OrthoTIR025/"+aName,1,true); std::string filenamePC= "PC"+aName.substr(3, aName.size()) ; /* //255: masqué. 0: ok Im2D_U_INT1 out(im.sz().x,im.sz().y); Im2D_REAL4 tmp(im.sz().x,im.sz().y); int minRad(27540), rangeRad(2546.0); ELISE_COPY ( im.all_pts(), im.in(), tmp.out() ); ELISE_COPY ( select(tmp.all_pts(), tmp.in()>minRad && tmp.in()<minRad+rangeRad && tmp.in()!=0), 255*(tmp.in()-minRad)/rangeRad, out.out() ); ELISE_COPY ( select(tmp.all_pts(), tmp.in()==0), 0, out.out() ); for (int v(0); v<tmp.sz().y;v++) { for (int u(0); u<tmp.sz().x;u++) { Pt2di pt(u,v); double aVal = tmp.GetR(pt); unsigned int v(0); if(aVal!=0){ if (aVal>minRad && aVal <minRad+rangeRad) { v=255.0*(aVal-minRad)/rangeRad; } } out.SetR(pt,v); //std::cout << "aVal a la position " << pt << " vaut " << aVal << ", transfo en " << v <<"\n"; } } std::cout << "je sauve l'image " << aName << "\n"; ELISE_COPY ( out.all_pts(), out.in(0), Tiff_Im( aName.c_str(), out.sz(), GenIm::u_int1, Tiff_Im::No_Compr, Tiff_Im::BlackIsZero ).out() ); */ Im2D_REAL4 masq(im.sz().x,im.sz().y); ELISE_COPY ( im.all_pts(), im.in(0), masq.oclip() ); std::cout << "détecte le bord pour image " << filenamePC << "\n"; int it(0); do{ Neighbourhood V8 = Neighbourhood::v8(); Liste_Pts_INT2 l2(2); ELISE_COPY ( dilate ( select(masq.all_pts(),masq.in()==0), sel_func(V8,masq.in_proj()>0) ), 1000,// je me fous de la valeur c'est pour créer un flux de points surtout masq.oclip() | l2 // il faut écrire et dans la liste de point, et dans l'image, sinon il va repecher plusieur fois le meme point ); // j'enleve l'effet de bord , valleurs nulles ELISE_COPY ( l2.all_pts(), 0, masq.oclip() ); it++; } while (it<3); /* // attention, écrase le ficher existant, pas propre ça std::cout << "je sauve l'image avec correction radiométrique " << aName << "\n"; ELISE_COPY ( masq.all_pts(), masq.in(0), Tiff_Im( aName.c_str(), masq.sz(), GenIm::int1, Tiff_Im::No_Compr, Tiff_Im::BlackIsZero ).out() ); */ ELISE_COPY ( select(masq.all_pts(),masq.in()==0), 255, masq.oclip() ); ELISE_COPY ( select(masq.all_pts(),masq.in()!=255), 0, masq.oclip() ); std::cout << "je sauve l'image les parties cachées " << filenamePC << "\n"; ELISE_COPY ( masq.all_pts(), masq.in(0), Tiff_Im( filenamePC.c_str(), masq.sz(), GenIm::u_int1, Tiff_Im::No_Compr, Tiff_Im::BlackIsZero ).out() ); } return EXIT_SUCCESS; } int main_test2(int argc,char ** argv) { //cORT_Appli anAppli(argc,argv); //CmpOrthosTir_main(argc,argv); //ComputeStat_main(argc,argv); //RegTIRVIS_main(argc,argv); //MasqTIR_main(argc,argv); //statRadianceVarioCam_main(argc,argv); //cTPM2GCPwithConstantZ(argc,argv); return EXIT_SUCCESS; } // launch all photogrammetric pipeline on a list of directory int main_AllPipeline(int argc,char ** argv) { cLionPaw(argc,argv); return EXIT_SUCCESS; } // launch a complete workflow on one image block int main_OneLionPaw(int argc,char ** argv) { cOneLionPaw(argc,argv); return EXIT_SUCCESS; } int main_testold(int argc,char ** argv) { // manipulate the ofstream fout("/home/lisein/data/DIDRO/lp17/GPS_RGP/GNSS_pos/test.obs"); ifstream fin("/home/lisein/data/DIDRO/lp17/GPS_RGP/GNSS_pos/tmp.txt"); string line; std::string add(" 40.000 40.000\n"); add="\t40.000\t40.000\n"; if (fin.is_open()) { unsigned int i(0); while ( getline(fin,line) ) { i++; if (i==17){ i=0; fout << line << add; } else { if (i%2==1 && i>2) { fout << line << add; } else { fout << line <<"\n";} } } } else { std::cout << "cannot open file in\n";} fin.close(); fout.close(); return EXIT_SUCCESS; } /* * // useless, Giang l'a codé en bien plus propre. * template <class T,class TB> double VarLapl(Im2D<T,TB> * aIm,int aSzW); //burriness is computed as variance of Laplacian with a mean filter prior to reduce noise //https://www.pyimagesearch.com/2015/09/07/blur-detection-with-opencv/ template <class T,class TB> double VarLapl(Im2D<T,TB> * aIm,int aSzW) { Im2D_REAL4 aRes(aIm->sz().x,aIm->sz().y); Fonc_Num aF = aIm->in_proj(); int aNbVois = ElSquare(1+2*aSzW); aF = rect_som(aF,aSzW) /aNbVois; double min,max;// afin de pouvoir mettre le range de valeur entre 0 et 255 ELISE_COPY(aIm->all_pts() ,aF ,aRes.out()); double mean; int nb; ELISE_COPY(aRes.all_pts() ,Virgule(Laplacien(aRes.in_proj()) ,1) ,Virgule(aRes.out()|sigma(mean) ,sigma(nb))); std::cout << "mean of laplacian : " << mean << "\n"; mean=mean/nb; std::cout << "nb of value: " << nb << "\n"; // variance of laplacian Fonc_Num aFVar = ElSquare((aRes.in()-mean)); double meanVarLap; ELISE_COPY(aRes.all_pts() ,aFVar ,sigma(meanVarLap)); // mean of variance meanVarLap/=nb; return meanVarLap; } */ /*Footer-MicMac-eLiSe-25/06/2007 Ce logiciel est un programme informatique servant à la mise en correspondances d'images pour la reconstruction du relief. Ce logiciel est régi par la licence CeCILL-B soumise au droit français et respectant les principes de diffusion des logiciels libres. Vous pouvez utiliser, modifier et/ou redistribuer ce programme sous les conditions de la licence CeCILL-B telle que diffusée par le CEA, le CNRS et l'INRIA sur le site "http://www.cecill.info". En contrepartie de l'accessibilité au code source et des droits de copie, de modification et de redistribution accordés par cette licence, il n'est offert aux utilisateurs qu'une garantie limitée. Pour les mêmes raisons, seule une responsabilité restreinte pèse sur l'auteur du programme, le titulaire des droits patrimoniaux et les concédants successifs. A cet égard l'attention de l'ucApplitilisateur est attirée sur les risques associés au chargement, à l'utilisation, à la modification et/ou au développement et à la reproduction du logiciel par l'utilisateur étant donné sa spécificité de logiciel libre, qui peut le rendre complexe à manipuler et qui le réserve donc à des développeurs et des professionnels avertis possédant des connaissances informatiques approfondies. Les utilisateurs sont donc invités à charger et tester l'adéquation du logiciel à leurs besoins dans des conditions permettant d'assurer la sécurité de leurs systèmes et ou de leurs données et, plus généralement, à l'utiliser et l'exploiter dans les mêmes conditions de sécurité. Le fait que vous puissiez accéder à cet en-tête signifie que vous avez pris connaissance de la licence CeCILL-B, et que vous en avez accepté les termes. Footer-MicMac-eLiSe-25/06/2007*/
32.662195
216
0.562148
[ "geometry", "object", "shape", "vector", "model", "3d" ]
1b958c36b5447628ac864189bb0b466dfa22ab9a
13,955
cpp
C++
plugins/protein/src/SolPathDataSource.cpp
masrice/megamol
d48fc4889f500528609053a5445202a9c0f6e5fb
[ "BSD-3-Clause" ]
49
2017-08-23T13:24:24.000Z
2022-03-16T09:10:58.000Z
plugins/protein/src/SolPathDataSource.cpp
masrice/megamol
d48fc4889f500528609053a5445202a9c0f6e5fb
[ "BSD-3-Clause" ]
200
2018-07-20T15:18:26.000Z
2022-03-31T11:01:44.000Z
plugins/protein/src/SolPathDataSource.cpp
masrice/megamol
d48fc4889f500528609053a5445202a9c0f6e5fb
[ "BSD-3-Clause" ]
31
2017-07-31T16:19:29.000Z
2022-02-14T23:41:03.000Z
/* * SolPathRenderer.cpp * * Copyright (C) 2010 by VISUS (University of Stuttgart) * Alle Rechte vorbehalten. */ #include "stdafx.h" #define _USE_MATH_DEFINES 1 #include "SolPathDataSource.h" #include "mmcore/param/BoolParam.h" #include "mmcore/param/FilePathParam.h" #include "mmcore/param/FloatParam.h" #include "mmcore/utility/log/Log.h" #include "mmcore/utility/sys/MemmappedFile.h" #include "vislib/SingleLinkedList.h" #include "vislib/String.h" #include "vislib/math/ShallowPoint.h" #include "vislib/math/ShallowVector.h" #include "vislib/math/Vector.h" #include <cfloat> #include <climits> #include <cmath> #include "mmcore/BoundingBoxes_2.h" using namespace megamol::core; using namespace megamol::protein; /* * SolPathDataSource::SolPathDataSource */ SolPathDataSource::SolPathDataSource(void) : core::Module() , getdataslot("getdata", "Publishes the data for other modules") , filenameslot("filename", "The path of the solpath file to load") , smoothSlot("smooth", "Flag whether or not to smooth the data") , smoothValueSlot("smoothValue", "Value for the smooth filter") , smoothExpSlot("smoothExp", "The smoothing filter function exponent") , speedOfSmoothedSlot( "speedOfSmoothed", "Flag whether or not to use the smoothed data for the speed calculation") , clusterOfSmoothedSlot("clusterOfSmoothed", "Flag to cluster the smoothed or unsmoothed data") { this->getdataslot.SetCallback(SolPathDataCall::ClassName(), "GetData", &SolPathDataSource::getData); this->getdataslot.SetCallback(SolPathDataCall::ClassName(), "GetExtent", &SolPathDataSource::getExtent); this->MakeSlotAvailable(&this->getdataslot); this->filenameslot << new param::FilePathParam(""); this->MakeSlotAvailable(&this->filenameslot); this->smoothSlot << new param::BoolParam(true); this->MakeSlotAvailable(&this->smoothSlot); this->smoothValueSlot << new param::FloatParam(10.0f, 0.0f, 100.0f); this->MakeSlotAvailable(&this->smoothValueSlot); this->smoothExpSlot << new param::FloatParam(3.0f, 2.0f); this->MakeSlotAvailable(&this->smoothExpSlot); this->speedOfSmoothedSlot << new param::BoolParam(true); this->MakeSlotAvailable(&this->speedOfSmoothedSlot); this->clusterOfSmoothedSlot << new param::BoolParam(true); this->MakeSlotAvailable(&this->clusterOfSmoothedSlot); } /* * SolPathDataSource::~SolPathDataSource */ SolPathDataSource::~SolPathDataSource(void) { this->Release(); this->clear(); } /* * SolPathDataSource::create */ bool SolPathDataSource::create(void) { if (this->anyParamslotDirty()) { this->loadData(); } return true; } /* * SolPathDataSource::release */ void SolPathDataSource::release(void) { this->clear(); } /* * SolPathDataSource::getData */ bool SolPathDataSource::getData(megamol::core::Call& call) { SolPathDataCall* spdc = dynamic_cast<SolPathDataCall*>(&call); if (spdc == NULL) return false; if (this->anyParamslotDirty()) { this->loadData(); } spdc->Set(static_cast<unsigned int>(this->pathlines.Count()), this->pathlines.PeekElements(), this->minTime, this->maxTime, this->minSpeed, this->maxSpeed); return true; } /* * SolPathDataSource::getExtent */ bool SolPathDataSource::getExtent(megamol::core::Call& call) { SolPathDataCall* spdc = dynamic_cast<SolPathDataCall*>(&call); if (spdc == NULL) return false; if (this->anyParamslotDirty()) { this->loadData(); } spdc->AccessBoundingBoxes().SetObjectSpaceBBox(this->bbox); return false; } /* * SolPathDataSource::clear */ void SolPathDataSource::clear(void) { this->bbox.Set(-1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 1.0f); this->minTime = 0.0f; this->maxTime = 0.0f; this->minSpeed = 0.0f; this->maxSpeed = 0.0f; this->vertices.Clear(); this->pathlines.Clear(); } /* * SolPathDataSource::loadData */ void SolPathDataSource::loadData(void) { using megamol::core::utility::log::Log; using vislib::sys::File; vislib::sys::MemmappedFile file; this->filenameslot.ResetDirty(); this->smoothSlot.ResetDirty(); this->smoothValueSlot.ResetDirty(); this->smoothExpSlot.ResetDirty(); this->speedOfSmoothedSlot.ResetDirty(); this->clusterOfSmoothedSlot.ResetDirty(); this->clear(); if (file.Open(this->filenameslot.Param<param::FilePathParam>()->Value().native().c_str(), File::READ_ONLY, File::SHARE_READ, File::OPEN_ONLY) == false) { Log::DefaultLog.WriteMsg(Log::LEVEL_ERROR, "Unable to open data file %s", this->filenameslot.Param<param::FilePathParam>()->Value().generic_u8string().c_str()); return; } vislib::StringA headerID; if (file.Read(headerID.AllocateBuffer(7), 7) != 7) { Log::DefaultLog.WriteMsg(Log::LEVEL_ERROR, "Unable to read data file %s", this->filenameslot.Param<param::FilePathParam>()->Value().generic_u8string().c_str()); return; } vislib::SingleLinkedList<fileBlockInfo> fileStruct; fileBlockInfo* blockInfo = NULL; if (headerID.Equals("SolPath")) { unsigned int version; if (file.Read(&version, 4) != 4) { Log::DefaultLog.WriteMsg(Log::LEVEL_ERROR, "Unable to read data file %s", this->filenameslot.Param<param::FilePathParam>()->Value().generic_u8string().c_str()); return; } if (version > 1) { Log::DefaultLog.WriteMsg(Log::LEVEL_ERROR, "Data file %s uses unsupported version %u", this->filenameslot.Param<param::FilePathParam>()->Value().generic_u8string().c_str(), version); return; } fileBlockInfo info; while (!file.IsEOF()) { if (file.Read(&info.id, 4) != 4) break; if (file.Read(&info.size, 8) != 8) break; info.start = file.Tell(); file.Seek(info.size, vislib::sys::File::CURRENT); fileStruct.Add(info); } } else { // legacy file support fileBlockInfo info; info.id = 0; // <= pathline data info.start = 0; // <= start of file info.size = file.GetSize(); // <= whole file fileStruct.Add(info); } // search for pathline data block vislib::SingleLinkedList<fileBlockInfo>::Iterator iter = fileStruct.GetIterator(); while (iter.HasNext()) { fileBlockInfo& info = iter.Next(); if (info.id == 0) { blockInfo = &info; break; } } if (blockInfo == NULL) { Log::DefaultLog.WriteMsg(Log::LEVEL_ERROR, "File %s does not contain a path line data block", this->filenameslot.Param<param::FilePathParam>()->Value().generic_u8string().c_str()); return; } file.Seek(blockInfo->start, File::BEGIN); // load data unsigned int atomCount; file.Read(&atomCount, 4); this->pathlines.AssertCapacity(atomCount); for (SIZE_T a = 0; a < atomCount; a++) { unsigned int tmp, framesCount; SolPathDataCall::Vertex vertex; SolPathDataCall::Pathline path; vertex.speed = 0.0f; // will be set later vertex.clusterID = 0; vertex.time = -2.0f; path.length = 0; path.data = NULL; // will be set later file.Read(&tmp, 4); path.id = tmp; file.Read(&framesCount, 4); this->vertices.AssertCapacity(this->vertices.Count() + framesCount); for (SIZE_T e = 0; e < framesCount; e++) { file.Read(&tmp, 4); file.Read(&vertex.x, 12); if (tmp != static_cast<unsigned int>(vertex.time) + 1) { // start a new path if (path.length > 0) { this->pathlines.Add(path); } path.length = 1; } else { // continue path path.length++; } vertex.time = static_cast<float>(tmp); this->vertices.Add(vertex); } if (path.length > 0) { this->pathlines.Add(path); } } Log::DefaultLog.WriteMsg(Log::LEVEL_INFO + 1000, "Finished solpath file IO"); // calculate pointers, bounding data, and speed values SIZE_T off = 0; for (SIZE_T p = 0; p < this->pathlines.Count(); p++) { off += this->pathlines[p].length; } if (off < this->vertices.Count()) { Log::DefaultLog.WriteMsg(Log::LEVEL_WARN, "Path data inconsistent: too many vertices"); } else if (off > this->vertices.Count()) { Log::DefaultLog.WriteMsg(Log::LEVEL_ERROR, "Path data inconsistent: too few vertices"); this->clear(); return; } if (off <= 0) { // data is empty! return; } off = 0; this->maxTime = 0.0f; this->minTime = FLT_MAX; this->maxSpeed = -FLT_MAX; this->minSpeed = FLT_MAX; this->bbox.Set(FLT_MAX, FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX, -FLT_MAX); for (SIZE_T p = 0; p < this->pathlines.Count(); p++) { this->pathlines[p].data = this->vertices.PeekElements() + off; for (SIZE_T v = 0; v < this->pathlines[p].length; v++) { SolPathDataCall::Vertex& v1 = this->vertices[off + v]; if (v > 0) { v1.speed = vislib::math::ShallowPoint<float, 3>(&v1.x).Distance( vislib::math::ShallowPoint<float, 3>(&this->vertices[off + v - 1].x)); } if (v1.time > this->maxTime) this->maxTime = v1.time; if (v1.time < this->minTime) this->minTime = v1.time; if (v1.speed > 0.01f) { if (v1.speed > this->maxSpeed) this->maxSpeed = v1.speed; if (v1.speed < this->minSpeed) this->minSpeed = v1.speed; } if (this->bbox.Left() > v1.x) this->bbox.SetLeft(v1.x); if (this->bbox.Right() < v1.x) this->bbox.SetRight(v1.x); if (this->bbox.Bottom() > v1.y) this->bbox.SetBottom(v1.y); if (this->bbox.Top() < v1.y) this->bbox.SetTop(v1.y); if (this->bbox.Back() > v1.z) this->bbox.SetBack(v1.z); if (this->bbox.Front() < v1.z) this->bbox.SetFront(v1.z); } if (this->pathlines[p].length > 2) { this->vertices[off].speed = this->vertices[off + 1].speed; } off += this->pathlines[p].length; } this->bbox.EnforcePositiveSize(); if (!this->smoothSlot.Param<param::BoolParam>()->Value() || !this->clusterOfSmoothedSlot.Param<param::BoolParam>()->Value()) { // TODO: calculate clusters here } if (this->smoothSlot.Param<param::BoolParam>()->Value()) { // smooth float smoothValue = this->smoothValueSlot.Param<param::FloatParam>()->Value(); vislib::Array<float> filter(1 + static_cast<unsigned int>(::ceil(smoothValue)), 0.0f); filter[0] = 1.0f; if (smoothValue > 0.00001f) { float exp = this->smoothExpSlot.Param<param::FloatParam>()->Value(); for (SIZE_T i = 1; i < filter.Count(); i++) { filter[i] = ::pow(::cos(static_cast<float>(M_PI) * static_cast<float>(i) / (1.0f + smoothValue)), exp); filter[i] *= filter[i]; } } off = 0; for (SIZE_T p = 0; p < this->pathlines.Count(); p++) { for (SIZE_T v = 0; v < this->pathlines[p].length; v++) { float fac = 1.0f; vislib::math::ShallowVector<float, 3> pos(&this->vertices[off + v].x); for (SIZE_T f = 1; f < filter.Count(); f++) { if (f <= v) { pos += vislib::math::ShallowVector<float, 3>(&this->vertices[off + v - f].x) * filter[f]; fac += filter[f]; } if (f + v < this->pathlines[p].length) { pos += vislib::math::ShallowVector<float, 3>(&this->vertices[off + v + f].x) * filter[f]; fac += filter[f]; } } pos /= fac; } off += this->pathlines[p].length; } // Note: smoothing does change the positions, but will never leave the // original bounding box. Since everything is just an approximation we // keep the old bounding box. if (this->speedOfSmoothedSlot.Param<param::BoolParam>()->Value()) { // recalculate speed off = 0; this->maxSpeed = -FLT_MAX; this->minSpeed = FLT_MAX; for (SIZE_T p = 0; p < this->pathlines.Count(); p++) { for (SIZE_T v = 1; v < this->pathlines[p].length; v++) { SolPathDataCall::Vertex& v1 = this->vertices[off + v]; v1.speed = vislib::math::ShallowPoint<float, 3>(&v1.x).Distance( vislib::math::ShallowPoint<float, 3>(&this->vertices[off + v - 1].x)); if (v1.speed > 0.01f) { if (v1.speed > this->maxSpeed) this->maxSpeed = v1.speed; if (v1.speed < this->minSpeed) this->minSpeed = v1.speed; } } if (this->pathlines[p].length > 2) { this->vertices[off].speed = this->vertices[off + 1].speed; } off += this->pathlines[p].length; } } if (this->clusterOfSmoothedSlot.Param<param::BoolParam>()->Value()) { // TODO: calculate clusters here } } }
33.305489
119
0.564815
[ "vector" ]
1b9607e0783072eb2f24919364d48f8092e350d6
7,539
hpp
C++
physics/oblate_body_body.hpp
madman2003/Principia
c757f840f5278ca3480799cee297238697868283
[ "MIT" ]
null
null
null
physics/oblate_body_body.hpp
madman2003/Principia
c757f840f5278ca3480799cee297238697868283
[ "MIT" ]
null
null
null
physics/oblate_body_body.hpp
madman2003/Principia
c757f840f5278ca3480799cee297238697868283
[ "MIT" ]
null
null
null
 #pragma once #include "physics/oblate_body.hpp" #include <algorithm> #include <set> #include <vector> #include "astronomy/epoch.hpp" #include "numerics/legendre_normalization_factor.mathematica.h" #include "quantities/constants.hpp" #include "quantities/quantities.hpp" #include "quantities/si.hpp" namespace principia { namespace physics { namespace internal_oblate_body { using astronomy::J2000; using geometry::AngularVelocity; using geometry::Instant; using numerics::LegendreNormalizationFactor; using quantities::Angle; using quantities::SIUnit; using quantities::si::Radian; using quantities::si::Second; template<typename Frame> OblateBody<Frame>::Parameters::Parameters(double const j2, Length const& reference_radius) : reference_radius_(reference_radius), j2_(j2), j2_over_μ_(j2 * reference_radius * reference_radius), cos_(typename OblateBody<Frame>::GeopotentialCoefficients()), sin_(typename OblateBody<Frame>::GeopotentialCoefficients()), degree_(2), is_zonal_(true) { CHECK_LT(0.0, j2) << "Oblate body must have positive j2"; cos_[2][0] = -j2 / LegendreNormalizationFactor[2][0]; } template<typename Frame> OblateBody<Frame>::Parameters::Parameters(Length const& reference_radius) : reference_radius_(reference_radius), cos_(typename OblateBody<Frame>::GeopotentialCoefficients()), sin_(typename OblateBody<Frame>::GeopotentialCoefficients()), degree_(0), is_zonal_(false) {} template<typename Frame> typename OblateBody<Frame>::Parameters OblateBody<Frame>::Parameters::ReadFromMessage( serialization::OblateBody::Geopotential const& message, Length const& reference_radius) { Parameters parameters(reference_radius); std::set<int> degrees_seen; for (auto const& row : message.row()) { const int n = row.degree(); CHECK_LE(n, OblateBody<Frame>::max_geopotential_degree); CHECK(degrees_seen.insert(n).second) << "Degree " << n << " specified multiple times"; CHECK_LE(row.column_size(), n + 1) << "Degree " << n << " has " << row.column_size() << " coefficients"; std::set<int> orders_seen; for (auto const& column : row.column()) { const int m = column.order(); CHECK_LE(m, n); CHECK(orders_seen.insert(m).second) << "Degree " << n << " order " << m << " specified multiple times"; parameters.cos_[n][m] = column.cos(); parameters.sin_[n][m] = column.sin(); } } parameters.degree_ = *degrees_seen.crbegin(); // Unnormalization. parameters.j2_ = -parameters.cos_[2][0] * LegendreNormalizationFactor[2][0]; parameters.j2_over_μ_ = -parameters.cos_[2][0] * LegendreNormalizationFactor[2][0] * reference_radius * reference_radius; // Zonalness. parameters.is_zonal_ = true; for (int n = 0; n <= parameters.degree_; ++n) { for (int m = 1; m <= n; ++m) { if (parameters.cos_[n][m] != 0 || parameters.sin_[n][m] != 0) { parameters.is_zonal_ = false; break; } } } return parameters; } template<typename Frame> void OblateBody<Frame>::Parameters::WriteToMessage( not_null<serialization::OblateBody::Geopotential*> const message) const { for (int n = 0; n <= degree_; ++n) { auto const row = message->add_row(); row->set_degree(n); for (int m = 0; m <= n; ++m) { auto const column = row->add_column(); column->set_order(m); column->set_cos(cos_[n][m]); column->set_sin(sin_[n][m]); } } } template<typename Frame> OblateBody<Frame>::OblateBody( MassiveBody::Parameters const& massive_body_parameters, typename RotatingBody<Frame>::Parameters const& rotating_body_parameters, Parameters const& parameters) : RotatingBody<Frame>(massive_body_parameters, rotating_body_parameters), parameters_(parameters) {} template<typename Frame> double OblateBody<Frame>::j2() const { return parameters_.j2_; } template<typename Frame> Quotient<Degree2SphericalHarmonicCoefficient, GravitationalParameter> const& OblateBody<Frame>::j2_over_μ() const { return parameters_.j2_over_μ_; } template<typename Frame> typename OblateBody<Frame>::GeopotentialCoefficients const& OblateBody<Frame>::cos() const { return parameters_.cos_; } template<typename Frame> typename OblateBody<Frame>::GeopotentialCoefficients const& OblateBody<Frame>::sin() const { return parameters_.sin_; } template<typename Frame> int OblateBody<Frame>::geopotential_degree() const { return parameters_.degree_; } template<typename Frame> bool OblateBody<Frame>::is_zonal() const { return parameters_.is_zonal_; } template<typename Frame> Length const& OblateBody<Frame>::reference_radius() const { return parameters_.reference_radius_; } template<typename Frame> bool OblateBody<Frame>::is_massless() const { return false; } template<typename Frame> bool OblateBody<Frame>::is_oblate() const { return true; } template<typename Frame> void OblateBody<Frame>::WriteToMessage( not_null<serialization::Body*> const message) const { WriteToMessage(message->mutable_massive_body()); } template<typename Frame> void OblateBody<Frame>::WriteToMessage( not_null<serialization::MassiveBody*> const message) const { RotatingBody<Frame>::WriteToMessage(message); not_null<serialization::OblateBody*> const oblate_body = message->MutableExtension(serialization::RotatingBody::extension)-> MutableExtension(serialization::OblateBody::extension); parameters_.reference_radius_.WriteToMessage( oblate_body->mutable_reference_radius()); parameters_.WriteToMessage(oblate_body->mutable_geopotential()); } template<typename Frame> not_null<std::unique_ptr<OblateBody<Frame>>> OblateBody<Frame>::ReadFromMessage( serialization::OblateBody const& message, MassiveBody::Parameters const& massive_body_parameters, typename RotatingBody<Frame>::Parameters const& rotating_body_parameters) { std::unique_ptr<Parameters> parameters; switch (message.oblateness_case()) { case serialization::OblateBody::OblatenessCase::kPreDiophantosJ2: { // In the legacy case we didn't record the reference radius, so we use a // dummy value to achieve the right effect. CHECK(!message.has_reference_radius()) << message.DebugString(); Length const reference_radius = SIUnit<Length>(); parameters = std::make_unique<Parameters>( Degree2SphericalHarmonicCoefficient::ReadFromMessage( message.pre_diophantos_j2()) / (massive_body_parameters.gravitational_parameter() * reference_radius * reference_radius), reference_radius); break; } case serialization::OblateBody::OblatenessCase::kGeopotential: CHECK(message.has_reference_radius()) << message.DebugString(); parameters = std::make_unique<Parameters>(Parameters::ReadFromMessage( message.geopotential(), Length::ReadFromMessage(message.reference_radius()))); break; case serialization::OblateBody::OblatenessCase::OBLATENESS_NOT_SET: LOG(FATAL) << message.DebugString(); base::noreturn(); } return std::make_unique<OblateBody<Frame>>(massive_body_parameters, rotating_body_parameters, *parameters); } } // namespace internal_oblate_body } // namespace physics } // namespace principia
33.506667
80
0.698899
[ "geometry", "vector" ]
1b980e95635b665985d3fa146bc424c1664dda75
36,695
cpp
C++
src/lapack_like/perm/DistPermutation.cpp
jeffhammond/Elemental
a9e6236ce9d92dd56c7d3cd5ffd52f796a35cd0c
[ "Apache-2.0" ]
null
null
null
src/lapack_like/perm/DistPermutation.cpp
jeffhammond/Elemental
a9e6236ce9d92dd56c7d3cd5ffd52f796a35cd0c
[ "Apache-2.0" ]
null
null
null
src/lapack_like/perm/DistPermutation.cpp
jeffhammond/Elemental
a9e6236ce9d92dd56c7d3cd5ffd52f796a35cd0c
[ "Apache-2.0" ]
null
null
null
/* Copyright (c) 2009-2016, Jack Poulson All rights reserved. This file is part of Elemental and is under the BSD 2-Clause License, which can be found in the LICENSE file in the root directory, or at http://opensource.org/licenses/BSD-2-Clause */ #include <El.hpp> namespace El { namespace { template<typename T> void PermuteCols ( AbstractDistMatrix<T>& A, const PermutationMeta& oldMeta, bool inverse=false ) { DEBUG_CSE DEBUG_ONLY( if( A.RowComm() != oldMeta.comm ) LogicError("Invalid communicator in metadata"); if( A.RowAlign() != oldMeta.align ) LogicError("Invalid alignment in metadata"); ) if( A.Height() == 0 || A.Width() == 0 || !A.Participating() ) return; T* ABuf = A.Buffer(); const Int ALDim = A.LDim(); const Int localHeight = A.LocalHeight(); PermutationMeta meta = oldMeta; meta.ScaleUp( localHeight ); if( inverse ) { // Fill vectors with the send data auto offsets = meta.recvDispls; const int totalSend = meta.TotalRecv(); vector<T> sendData; FastResize( sendData, mpi::Pad(totalSend) ); const int numSends = meta.recvIdx.size(); for( int send=0; send<numSends; ++send ) { const int jLoc = meta.recvIdx[send]; const int rank = meta.recvRanks[send]; MemCopy( &sendData[offsets[rank]], &ABuf[jLoc*ALDim], localHeight ); offsets[rank] += localHeight; } // Communicate all pivot rows const int totalRecv = meta.TotalSend(); vector<T> recvData; FastResize( recvData, mpi::Pad(totalRecv) ); mpi::AllToAll ( sendData.data(), meta.recvCounts.data(), meta.recvDispls.data(), recvData.data(), meta.sendCounts.data(), meta.sendDispls.data(), meta.comm ); // Unpack the recv data offsets = meta.sendDispls; const int numRecvs = meta.sendIdx.size(); for( int recv=0; recv<numRecvs; ++recv ) { const int jLoc = meta.sendIdx[recv]; const int rank = meta.sendRanks[recv]; MemCopy( &ABuf[jLoc*ALDim], &recvData[offsets[rank]], localHeight ); offsets[rank] += localHeight; } } else { // Fill vectors with the send data auto offsets = meta.sendDispls; const int totalSend = meta.TotalSend(); vector<T> sendData; FastResize( sendData, mpi::Pad(totalSend) ); const int numSends = meta.sendIdx.size(); for( int send=0; send<numSends; ++send ) { const int jLoc = meta.sendIdx[send]; const int rank = meta.sendRanks[send]; MemCopy( &sendData[offsets[rank]], &ABuf[jLoc*ALDim], localHeight ); offsets[rank] += localHeight; } // Communicate all pivot rows const int totalRecv = meta.TotalRecv(); vector<T> recvData; FastResize( recvData, mpi::Pad(totalRecv) ); mpi::AllToAll ( sendData.data(), meta.sendCounts.data(), meta.sendDispls.data(), recvData.data(), meta.recvCounts.data(), meta.recvDispls.data(), meta.comm ); // Unpack the recv data offsets = meta.recvDispls; const int numRecvs = meta.recvIdx.size(); for( int recv=0; recv<numRecvs; ++recv ) { const int jLoc = meta.recvIdx[recv]; const int rank = meta.recvRanks[recv]; MemCopy( &ABuf[jLoc*ALDim], &recvData[offsets[rank]], localHeight ); offsets[rank] += localHeight; } } } template<typename T> void PermuteRows ( AbstractDistMatrix<T>& A, const PermutationMeta& oldMeta, bool inverse=false ) { DEBUG_CSE DEBUG_ONLY( if( A.ColComm() != oldMeta.comm ) LogicError("Invalid communicator in metadata"); if( A.ColAlign() != oldMeta.align ) LogicError("Invalid alignment in metadata"); ) if( A.Height() == 0 || A.Width() == 0 || !A.Participating() ) return; T* ABuf = A.Buffer(); const Int ALDim = A.LDim(); const Int localWidth = A.LocalWidth(); PermutationMeta meta = oldMeta; meta.ScaleUp( localWidth ); if( inverse ) { // Fill vectors with the send data auto offsets = meta.recvDispls; const int totalSend = meta.TotalRecv(); vector<T> sendData; FastResize( sendData, mpi::Pad(totalSend) ); const int numSends = meta.recvIdx.size(); for( int send=0; send<numSends; ++send ) { const int iLoc = meta.recvIdx[send]; const int rank = meta.recvRanks[send]; StridedMemCopy ( &sendData[offsets[rank]], 1, &ABuf[iLoc], ALDim, localWidth ); offsets[rank] += localWidth; } // Communicate all pivot rows const int totalRecv = meta.TotalSend(); vector<T> recvData; FastResize( recvData, mpi::Pad(totalRecv) ); mpi::AllToAll ( sendData.data(), meta.recvCounts.data(), meta.recvDispls.data(), recvData.data(), meta.sendCounts.data(), meta.sendDispls.data(), meta.comm ); // Unpack the recv data offsets = meta.sendDispls; const int numRecvs = meta.sendIdx.size(); for( int recv=0; recv<numRecvs; ++recv ) { const int iLoc = meta.sendIdx[recv]; const int rank = meta.sendRanks[recv]; StridedMemCopy ( &ABuf[iLoc], ALDim, &recvData[offsets[rank]], 1,localWidth ); offsets[rank] += localWidth; } } else { // Fill vectors with the send data auto offsets = meta.sendDispls; const int totalSend = meta.TotalSend(); vector<T> sendData; FastResize( sendData, mpi::Pad(totalSend) ); const int numSends = meta.sendIdx.size(); for( int send=0; send<numSends; ++send ) { const int iLoc = meta.sendIdx[send]; const int rank = meta.sendRanks[send]; StridedMemCopy ( &sendData[offsets[rank]], 1, &ABuf[iLoc], ALDim, localWidth ); offsets[rank] += localWidth; } // Communicate all pivot rows const int totalRecv = meta.TotalRecv(); vector<T> recvData; FastResize( recvData, mpi::Pad(totalRecv) ); mpi::AllToAll ( sendData.data(), meta.sendCounts.data(), meta.sendDispls.data(), recvData.data(), meta.recvCounts.data(), meta.recvDispls.data(), meta.comm ); // Unpack the recv data offsets = meta.recvDispls; const int numRecvs = meta.recvIdx.size(); for( int recv=0; recv<numRecvs; ++recv ) { const int iLoc = meta.recvIdx[recv]; const int rank = meta.recvRanks[recv]; StridedMemCopy ( &ABuf[iLoc], ALDim, &recvData[offsets[rank]], 1,localWidth ); offsets[rank] += localWidth; } } } void InvertPermutation ( const AbstractDistMatrix<Int>& pPre, AbstractDistMatrix<Int>& pInvPre ) { DEBUG_CSE DEBUG_ONLY( if( pPre.Width() != 1 ) LogicError("p must be a column vector"); ) const Int n = pPre.Height(); pInvPre.Resize( n, 1 ); if( n == 0 ) return; DistMatrixReadProxy<Int,Int,VC,STAR> pProx( pPre ); DistMatrixWriteProxy<Int,Int,VC,STAR> pInvProx( pInvPre ); auto& p = pProx.GetLocked(); auto& pInv = pInvProx.Get(); auto& pLoc = p.LockedMatrix(); auto& pInvLoc = pInv.Matrix(); DEBUG_ONLY( // This is obviously necessary but not sufficient for 'p' to contain // a reordering of (0,1,...,n-1). const Int range = MaxNorm( p ) + 1; if( range != n ) LogicError("Invalid permutation range"); ) // Compute the send counts const mpi::Comm colComm = p.ColComm(); const Int commSize = mpi::Size( colComm ); vector<int> sendSizes(commSize,0), recvSizes(commSize,0); for( Int iLoc=0; iLoc<p.LocalHeight(); ++iLoc ) { const Int iDest = pLoc(iLoc); const int owner = pInv.RowOwner(iDest); sendSizes[owner] += 2; // we'll send the global index and the value } // Perform a small AllToAll to get the receive counts mpi::AllToAll( sendSizes.data(), 1, recvSizes.data(), 1, colComm ); vector<int> sendOffs, recvOffs; const int sendTotal = Scan( sendSizes, sendOffs ); const int recvTotal = Scan( recvSizes, recvOffs ); // Pack the send data vector<Int> sendBuf(sendTotal); auto offsets = sendOffs; for( Int iLoc=0; iLoc<p.LocalHeight(); ++iLoc ) { const Int i = p.GlobalRow(iLoc); const Int iDest = pLoc(iLoc); const int owner = pInv.RowOwner(iDest); sendBuf[offsets[owner]++] = iDest; sendBuf[offsets[owner]++] = i; } // Perform the actual exchange vector<Int> recvBuf(recvTotal); mpi::AllToAll ( sendBuf.data(), sendSizes.data(), sendOffs.data(), recvBuf.data(), recvSizes.data(), recvOffs.data(), colComm ); SwapClear( sendBuf ); SwapClear( sendSizes ); SwapClear( sendOffs ); // Unpack the received data for( Int k=0; k<recvTotal/2; ++k ) { const Int iDest = recvBuf[2*k+0]; const Int i = recvBuf[2*k+1]; const Int iDestLoc = pInv.LocalRow(iDest); pInvLoc(iDestLoc) = i; } } } // anonymous namespace DistPermutation::DistPermutation( const Grid& g ) : grid_(g) { DEBUG_CSE swapDests_.SetGrid( g ); swapOrigins_.SetGrid( g ); perm_.SetGrid( g ); invPerm_.SetGrid( g ); } void DistPermutation::SetGrid( const Grid& g ) { DEBUG_CSE Empty(); swapDests_.SetGrid( g ); swapOrigins_.SetGrid( g ); perm_.SetGrid( g ); invPerm_.SetGrid( g ); } void DistPermutation::Empty() { DEBUG_CSE size_ = 0; parity_ = false; staleParity_ = false; swapSequence_ = true; // Only used if swapSequence_ = true // --------------------------------- numSwaps_ = 0; implicitSwapOrigins_ = true; swapDests_.Empty(); swapOrigins_.Empty(); // Only used if swapSequence_ = false // ---------------------------------- perm_.Empty(); invPerm_.Empty(); staleInverse_ = false; rowMeta_.clear(); colMeta_.clear(); staleMeta_ = false; } void DistPermutation::MakeIdentity( Int size ) { DEBUG_CSE if( !swapSequence_ ) { Empty(); size_ = size; return; } // Carefully ensure that a previous swap reservation is not blocked // if the permutation is still in swap mode size_ = size; parity_ = false; staleParity_ = false; numSwaps_ = 0; implicitSwapOrigins_ = true; } void DistPermutation::ReserveSwaps( Int maxSwaps ) { DEBUG_CSE // Arbitrary permutations can trivially support arbitrarily many swaps if( !swapSequence_ ) return; if( maxSwaps > swapDests_.Height() ) { MakeIdentity( size_ ); swapDests_.Resize( maxSwaps, 1 ); return; } } void DistPermutation::Swap( Int origin, Int dest ) { DEBUG_CSE DEBUG_ONLY( if( origin < 0 || origin >= size_ || dest < 0 || dest >= size_ ) LogicError ("Attempted swap (",origin,",",dest,") for perm. of size ",size_); ) if( origin != dest ) parity_ = !parity_; if( swapSequence_ && numSwaps_ == swapDests_.Height() ) MakeArbitrary(); if( !swapSequence_ ) { El::RowSwap( perm_, origin, dest ); staleInverse_ = true; staleMeta_ = true; return; } if( !implicitSwapOrigins_ ) { swapOrigins_.Set( numSwaps_, 0, origin ); swapDests_.Set( numSwaps_, 0, dest ); ++numSwaps_; return; } if( origin == numSwaps_ ) { swapDests_.Set( numSwaps_, 0, dest ); ++numSwaps_; } else { implicitSwapOrigins_ = false; const Int maxSwaps = swapDests_.Height(); swapOrigins_.SetGrid( grid_ ); swapOrigins_.Resize( maxSwaps, 1 ); auto swapOriginsActive = swapOrigins_(IR(0,numSwaps_),ALL); const Int localHeight = swapOriginsActive.LocalHeight(); for( Int iLoc=0; iLoc<localHeight; ++iLoc ) swapOriginsActive.SetLocal ( iLoc, 0, swapOriginsActive.GlobalRow(iLoc) ); swapOrigins_.Set( numSwaps_, 0, origin ); swapDests_.Set( numSwaps_, 0, dest ); ++numSwaps_; } } void DistPermutation::SwapSequence( const DistPermutation& P, Int offset ) { DEBUG_CSE if( P.swapSequence_ ) { const Int numSwapAppends = P.numSwaps_; auto activeInd = IR(0,numSwapAppends); DistMatrix<Int,STAR,STAR> swapDests_STAR_STAR = P.swapDests_(activeInd,ALL); auto& swapDestsLoc = swapDests_STAR_STAR.Matrix(); if( P.implicitSwapOrigins_ ) { for( Int j=0; j<numSwapAppends; ++j ) Swap( j+offset, swapDestsLoc(j)+offset ); } else { DistMatrix<Int,STAR,STAR> swapOrigins_STAR_STAR = P.swapOrigins_(activeInd,ALL); auto& swapOriginsLoc = swapOrigins_STAR_STAR.Matrix(); for( Int j=0; j<numSwapAppends; ++j ) Swap( swapOriginsLoc(j)+offset, swapDestsLoc(j)+offset ); } } else { MakeArbitrary(); P.PermuteRows( perm_, offset ); invPerm_.Empty(); staleParity_ = true; staleInverse_ = true; staleMeta_ = true; } } void DistPermutation::SwapSequence ( const ElementalMatrix<Int>& swapOriginsPre, const ElementalMatrix<Int>& swapDestsPre, Int offset ) { DEBUG_CSE DistMatrixReadProxy<Int,Int,STAR,STAR> swapOriginsProx( swapOriginsPre ), swapDestsProx( swapDestsPre ); auto& swapOrigins = swapOriginsProx.GetLocked(); auto& swapDests = swapDestsProx.GetLocked(); auto& swapOriginsLoc = swapOrigins.LockedMatrix(); auto& swapDestsLoc = swapDests.LockedMatrix(); // TODO: Assert swapOrigins and swapDests are column vectors of same size const Int numSwaps = swapDests.Height(); for( Int k=0; k<numSwaps; ++k ) Swap( swapOriginsLoc(k)+offset, swapDestsLoc(k)+offset ); } void DistPermutation::ImplicitSwapSequence ( const ElementalMatrix<Int>& swapDestsPre, Int offset ) { DEBUG_CSE DistMatrixReadProxy<Int,Int,STAR,STAR> swapDestsProx( swapDestsPre ); auto& swapDests = swapDestsProx.GetLocked(); auto& swapDestsLoc = swapDests.LockedMatrix(); const Int numPrevSwaps = numSwaps_; // TODO: Assert swapOrigins and swapDests are column vectors of same size const Int numSwaps = swapDests.Height(); for( Int k=0; k<numSwaps; ++k ) Swap( numPrevSwaps+k, swapDestsLoc(k)+offset ); } Int DistPermutation::LocalImage( Int localOrigin ) const { DEBUG_CSE if( swapSequence_ ) LogicError("Cannot query the local image of a swap sequence"); if( staleInverse_ ) LogicError("Cannot query the local image when the inverse is stale"); return invPerm_.GetLocal( localOrigin, 0 ); } Int DistPermutation::LocalPreimage( Int localDest ) const { DEBUG_CSE if( swapSequence_ ) LogicError("Cannot query the local preimage of a swap sequence"); return perm_.GetLocal( localDest, 0 ); } Int DistPermutation::Image( Int origin ) const { DEBUG_CSE MakeArbitrary(); if( staleInverse_ ) { El::InvertPermutation( perm_, invPerm_ ); staleInverse_ = false; } return invPerm_.Get( origin, 0 ); } Int DistPermutation::Preimage( Int dest ) const { DEBUG_CSE MakeArbitrary(); return perm_.Get( dest, 0 ); } void DistPermutation::SetImage( Int origin, Int dest ) { DEBUG_CSE MakeArbitrary(); perm_.Set( dest, 0, origin ); invPerm_.Set( origin, 0, dest ); staleParity_ = true; staleMeta_ = true; } void DistPermutation::MakeArbitrary() const { DEBUG_CSE if( !swapSequence_ ) return; // Compose the swaps into an explicit permutation vector // ----------------------------------------------------- perm_.Resize( size_, 1 ); auto& permLoc = perm_.Matrix(); const Int localHeight = perm_.LocalHeight(); for( Int iLoc=0; iLoc<localHeight; ++iLoc ) permLoc(iLoc) = perm_.GlobalRow(iLoc); PermuteRows( perm_ ); invPerm_.Resize( size_, 1 ); staleInverse_ = true; staleMeta_ = true; // Clear the swap information // -------------------------- swapSequence_ = false; numSwaps_ = 0; implicitSwapOrigins_ = true; swapDests_.Empty(); swapOrigins_.Empty(); } const DistPermutation& DistPermutation::operator=( const Permutation& P ) { DEBUG_CSE if( grid_.Size() != 1 ) LogicError("Invalid grid size for sequential copy"); size_ = P.size_; swapSequence_ = P.swapSequence_; numSwaps_ = P.numSwaps_; implicitSwapOrigins_ = P.implicitSwapOrigins_; swapDests_.Resize( P.swapDests_.Height(), P.swapDests_.Width() ); Copy( P.swapDests_, swapDests_.Matrix() ); swapOrigins_.Resize( P.swapOrigins_.Height(), P.swapOrigins_.Width() ); Copy( P.swapOrigins_, swapOrigins_.Matrix() ); perm_.Resize( P.perm_.Height(), P.perm_.Width() ); Copy( P.perm_, perm_.Matrix() ); invPerm_.Resize( P.invPerm_.Height(), P.invPerm_.Width() ); Copy( P.invPerm_, invPerm_.Matrix() ); parity_ = P.parity_; staleParity_ = P.staleParity_; staleInverse_ = P.staleInverse_; staleMeta_ = true; return *this; } const DistPermutation& DistPermutation::operator=( const DistPermutation& P ) { DEBUG_CSE SetGrid( P.grid_ ); size_ = P.size_; swapSequence_ = P.swapSequence_; numSwaps_ = P.numSwaps_; implicitSwapOrigins_ = P.implicitSwapOrigins_; swapDests_ = P.swapDests_; swapOrigins_ = P.swapOrigins_; perm_ = P.perm_; invPerm_ = P.invPerm_; parity_ = P.parity_; staleParity_ = P.staleParity_; staleInverse_ = P.staleInverse_; colMeta_ = P.colMeta_; rowMeta_ = P.rowMeta_; staleMeta_ = P.staleMeta_; return *this; } bool DistPermutation::Parity() const { DEBUG_CSE if( staleParity_ ) { if( swapSequence_ ) LogicError("Unexpected stale parity for a swap sequence"); // Walking through the process of LU factorization with partial // pivoting for a permutation matrix, which never requires a // Schur-complement update, yields an algorithm for expressing the // inverse of a permutation in terms of a sequence of transpositions in // linear time. Note that performing the swaps requires access to the // inverse permutation, which can be formed in linear time. if( staleInverse_ ) { El::InvertPermutation( perm_, invPerm_ ); staleInverse_ = false; } DistMatrix<Int,STAR,STAR> permCopy(perm_), invPermCopy(invPerm_); auto& permCopyLoc = permCopy.Matrix(); auto& invPermCopyLoc = invPermCopy.Matrix(); parity_ = false; for( Int k=0; k<size_; ++k ) { const Int permVal = permCopyLoc(k); if( permVal != k ) { parity_ = !parity_; const Int invPermVal = invPermCopyLoc(k); // We only need to perform half of the swaps // perm[k] <-> perm[invPerm[k]] // invPerm[k] <-> invPerm[perk[k]] // since we will not need to access perm[k] and invPerm[k] again permCopyLoc(invPermVal) = permVal; invPermCopyLoc(permVal) = invPermVal; } } staleParity_ = false; } return parity_; } Int DistPermutation::Height() const { return size_; } Int DistPermutation::Width() const { return size_; } bool DistPermutation::IsSwapSequence() const { return swapSequence_; } bool DistPermutation::IsImplicitSwapSequence() const { return implicitSwapOrigins_; } const DistMatrix<Int,VC,STAR> DistPermutation::SwapOrigins() const { DEBUG_CSE if( !swapSequence_ || !implicitSwapOrigins_ ) LogicError("Swap origins are not explicitly stored"); return swapOrigins_(IR(0,numSwaps_),ALL); } const DistMatrix<Int,VC,STAR> DistPermutation::SwapDestinations() const { DEBUG_CSE if( !swapSequence_ ) LogicError("Swap destinations are not explicitly stored"); return swapDests_(IR(0,numSwaps_),ALL); } template<typename T> void DistPermutation::PermuteCols( AbstractDistMatrix<T>& A, Int offset ) const { DEBUG_CSE // TODO: Use an (MC,MR) proxy for A? if( swapSequence_ ) { const Int height = A.Height(); const Int width = A.Width(); if( height == 0 || width == 0 ) return; auto activeInd = IR(0,numSwaps_); // TODO: Introduce an std::map for caching the pivots this process // needs to care about to avoid redundant [STAR,STAR] formations // TODO: Decide on the data structure; an std::vector of pivot origins // and destinations? DistMatrix<Int,STAR,STAR> dests_STAR_STAR( swapDests_(activeInd,ALL) ); auto& destsLoc = dests_STAR_STAR.Matrix(); if( implicitSwapOrigins_ ) { for( Int j=0; j<numSwaps_; ++j ) { const Int origin = j+offset; const Int dest = destsLoc(j)+offset; ColSwap( A, origin, dest ); } } else { DistMatrix<Int,STAR,STAR> origins_STAR_STAR = swapOrigins_(activeInd,ALL); auto& originsLoc = origins_STAR_STAR.Matrix(); for( Int j=0; j<numSwaps_; ++j ) { const Int origin = originsLoc(j)+offset; const Int dest = destsLoc(j)+offset; ColSwap( A, origin, dest ); } } } else { if( offset != 0 ) LogicError ("General permutations are not supported with nonzero offsets"); if( staleMeta_ ) { rowMeta_.clear(); colMeta_.clear(); staleMeta_ = false; } // TODO: Move El::InversePermutation into this class if( staleInverse_ ) { InvertPermutation( perm_, invPerm_ ); staleInverse_ = false; } // TODO: Query/maintain the unordered_map const Int align = A.RowAlign(); mpi::Comm comm = A.RowComm(); keyType_ key = std::pair<Int,mpi::Comm>(align,comm); auto data = colMeta_.find( key ); if( data == colMeta_.end() ) { // TODO: Enable this branch; it apparently is not possible with GCC 4.7.1 #ifdef EL_HAVE_STD_EMPLACE colMeta_.emplace ( std::piecewise_construct, std::forward_as_tuple(key), std::forward_as_tuple(perm_,invPerm_,align,comm) ); #else auto newPair = std::make_pair(key,PermutationMeta(perm_,invPerm_,align,comm)); colMeta_.insert( newPair ); #endif data = colMeta_.find( key ); } // TODO: Move El::PermuteCols into this class El::PermuteCols( A, data->second ); } } template<typename T> void DistPermutation::InversePermuteCols ( AbstractDistMatrix<T>& A, Int offset ) const { DEBUG_CSE // TODO: Use an (MC,MR) proxy for A? if( swapSequence_ ) { const Int height = A.Height(); const Int width = A.Width(); if( height == 0 || width == 0 ) return; auto activeInd = IR(0,numSwaps_); DistMatrix<Int,STAR,STAR> dests_STAR_STAR( swapDests_(activeInd,ALL) ); auto& destsLoc = dests_STAR_STAR.Matrix(); if( implicitSwapOrigins_ ) { for( Int j=numSwaps_-1; j>=0; --j ) { const Int origin = j+offset; const Int dest = destsLoc(j)+offset; ColSwap( A, origin, dest ); } } else { DistMatrix<Int,STAR,STAR> origins_STAR_STAR = swapOrigins_(activeInd,ALL); auto& originsLoc = origins_STAR_STAR.Matrix(); for( Int j=numSwaps_-1; j>=0; --j ) { const Int origin = originsLoc(j)+offset; const Int dest = destsLoc(j)+offset; ColSwap( A, origin, dest ); } } } else { if( offset != 0 ) LogicError ("General permutations are not supported with nonzero offsets"); if( staleMeta_ ) { rowMeta_.clear(); colMeta_.clear(); staleMeta_ = false; } // TODO: Move El::InversePermutation into this class if( staleInverse_ ) { InvertPermutation( perm_, invPerm_ ); staleInverse_ = false; } // TODO: Query/maintain the unordered_map const Int align = A.RowAlign(); mpi::Comm comm = A.RowComm(); keyType_ key = std::pair<Int,mpi::Comm>(align,comm); auto data = colMeta_.find( key ); if( data == colMeta_.end() ) { // TODO: Enable this branch; it apparently is not possible with GCC 4.7.1 #ifdef EL_HAVE_STD_EMPLACE colMeta_.emplace ( std::piecewise_construct, std::forward_as_tuple(key), std::forward_as_tuple(perm_,invPerm_,align,comm) ); #else auto newPair = std::make_pair(key,PermutationMeta(perm_,invPerm_,align,comm)); colMeta_.insert( newPair ); #endif data = colMeta_.find( key ); } // TODO: Move El::PermuteCols into this class El::PermuteCols( A, data->second, true ); } } template<typename T> void DistPermutation::PermuteRows( AbstractDistMatrix<T>& A, Int offset ) const { DEBUG_CSE // TODO: Use an (MC,MR) proxy for A? if( swapSequence_ ) { const Int height = A.Height(); const Int width = A.Width(); if( height == 0 || width == 0 ) return; auto activeInd = IR(0,numSwaps_); DistMatrix<Int,STAR,STAR> dests_STAR_STAR = swapDests_(activeInd,ALL); auto& destsLoc = dests_STAR_STAR.Matrix(); if( implicitSwapOrigins_ ) { for( Int j=0; j<numSwaps_; ++j ) { const Int origin = j+offset; const Int dest = destsLoc(j)+offset; El::RowSwap( A, origin, dest ); } } else { DistMatrix<Int,STAR,STAR> origins_STAR_STAR = swapOrigins_(activeInd,ALL); auto& originsLoc = origins_STAR_STAR.Matrix(); for( Int j=0; j<numSwaps_; ++j ) { const Int origin = originsLoc(j)+offset; const Int dest = destsLoc(j)+offset; El::RowSwap( A, origin, dest ); } } } else { if( offset != 0 ) LogicError ("General permutations are not supported with nonzero offsets"); if( staleMeta_ ) { rowMeta_.clear(); colMeta_.clear(); staleMeta_ = false; } // TODO: Move El::InversePermutation into this class if( staleInverse_ ) { InvertPermutation( perm_, invPerm_ ); staleInverse_ = false; } // TODO: Query/maintain the unordered_map const Int align = A.ColAlign(); mpi::Comm comm = A.ColComm(); keyType_ key = std::pair<Int,mpi::Comm>(align,comm); auto data = rowMeta_.find( key ); if( data == rowMeta_.end() ) { // TODO: Enable this branch; it apparently is not possible with GCC 4.7.1 #ifdef EL_HAVE_STD_EMPLACE rowMeta_.emplace ( std::piecewise_construct, std::forward_as_tuple(key), std::forward_as_tuple(perm_,invPerm_,align,comm) ); #else auto newPair = std::make_pair(key,PermutationMeta(perm_,invPerm_,align,comm)); rowMeta_.insert( newPair ); #endif data = rowMeta_.find( key ); } // TODO: Move El::PermuteRows into this class El::PermuteRows( A, data->second ); } } template<typename T> void DistPermutation::InversePermuteRows ( AbstractDistMatrix<T>& A, Int offset ) const { DEBUG_CSE // TODO: Use an (MC,MR) proxy for A? if( swapSequence_ ) { const Int height = A.Height(); const Int width = A.Width(); if( height == 0 || width == 0 ) return; auto activeInd = IR(0,numSwaps_); DistMatrix<Int,STAR,STAR> dests_STAR_STAR = swapDests_(activeInd,ALL); auto& destsLoc = dests_STAR_STAR.Matrix(); if( implicitSwapOrigins_ ) { for( Int j=numSwaps_-1; j>=0; --j ) { const Int origin = j+offset; const Int dest = destsLoc(j)+offset; El::RowSwap( A, origin, dest ); } } else { DistMatrix<Int,STAR,STAR> origins_STAR_STAR = swapOrigins_(activeInd,ALL); auto& originsLoc = origins_STAR_STAR.Matrix(); for( Int j=numSwaps_-1; j>=0; --j ) { const Int origin = originsLoc(j)+offset; const Int dest = destsLoc(j)+offset; El::RowSwap( A, origin, dest ); } } } else { if( offset != 0 ) LogicError ("General permutations are not supported with nonzero offsets"); if( staleMeta_ ) { rowMeta_.clear(); colMeta_.clear(); staleMeta_ = false; } // TODO: Move El::InversePermutation into this class if( staleInverse_ ) { InvertPermutation( perm_, invPerm_ ); staleInverse_ = false; } // TODO: Query/maintain the unordered_map const Int align = A.ColAlign(); mpi::Comm comm = A.ColComm(); keyType_ key = std::pair<Int,mpi::Comm>(align,comm); auto data = rowMeta_.find( key ); if( data == rowMeta_.end() ) { // TODO: Enable this branch; it apparently is not possible with GCC 4.7.1 #ifdef EL_HAVE_STD_EMPLACE rowMeta_.emplace ( std::piecewise_construct, std::forward_as_tuple(key), std::forward_as_tuple(perm_,invPerm_,align,comm) ); #else auto newPair = std::make_pair(key,PermutationMeta(perm_,invPerm_,align,comm)); rowMeta_.insert( newPair ); #endif data = rowMeta_.find( key ); } // TODO: Move El::PermuteRows into this class El::PermuteRows( A, data->second, true ); } } template<typename T> void DistPermutation::PermuteSymmetrically ( UpperOrLower uplo, AbstractDistMatrix<T>& A, bool conjugate, Int offset ) const { DEBUG_CSE // TODO: Use an (MC,MR) proxy for A? if( swapSequence_ ) { const Int height = A.Height(); const Int width = A.Width(); if( height == 0 || width == 0 ) return; auto activeInd = IR(0,numSwaps_); DistMatrix<Int,STAR,STAR> dests_STAR_STAR = swapDests_(activeInd,ALL); auto& destsLoc = dests_STAR_STAR.Matrix(); if( implicitSwapOrigins_ ) { for( Int j=0; j<numSwaps_; ++j ) { const Int origin = j+offset; const Int dest = destsLoc(j)+offset; SymmetricSwap( uplo, A, origin, dest, conjugate ); } } else { DistMatrix<Int,STAR,STAR> origins_STAR_STAR = swapOrigins_(activeInd,ALL); auto& originsLoc = origins_STAR_STAR.Matrix(); for( Int j=0; j<numSwaps_; ++j ) { const Int origin = originsLoc(j)+offset; const Int dest = destsLoc(j)+offset; SymmetricSwap( uplo, A, origin, dest, conjugate ); } } } else { if( offset != 0 ) LogicError ("General permutations are not supported with nonzero offsets"); if( staleMeta_ ) { rowMeta_.clear(); colMeta_.clear(); staleMeta_ = false; } // TODO: Move El::InversePermutation into this class if( staleInverse_ ) { InvertPermutation( perm_, invPerm_ ); staleInverse_ = false; } LogicError("General symmetric permutations are not yet supported"); } } template<typename T> void DistPermutation::InversePermuteSymmetrically ( UpperOrLower uplo, AbstractDistMatrix<T>& A, bool conjugate, Int offset ) const { DEBUG_CSE // TODO: Use an (MC,MR) proxy for A? if( swapSequence_ ) { const Int height = A.Height(); const Int width = A.Width(); if( height == 0 || width == 0 ) return; auto activeInd = IR(0,numSwaps_); DistMatrix<Int,STAR,STAR> dests_STAR_STAR = swapDests_(activeInd,ALL); auto& destsLoc = dests_STAR_STAR.Matrix(); if( implicitSwapOrigins_ ) { for( Int j=numSwaps_-1; j>=0; --j ) { const Int origin = j+offset; const Int dest = destsLoc(j)+offset; SymmetricSwap( uplo, A, origin, dest, conjugate ); } } else { DistMatrix<Int,STAR,STAR> origins_STAR_STAR = swapOrigins_(activeInd,ALL); auto& originsLoc = origins_STAR_STAR.Matrix(); for( Int j=numSwaps_-1; j>=0; --j ) { const Int origin = originsLoc(j)+offset; const Int dest = destsLoc(j)+offset; SymmetricSwap( uplo, A, origin, dest, conjugate ); } } } else { if( offset != 0 ) LogicError ("General permutations are not supported with nonzero offsets"); if( staleMeta_ ) { rowMeta_.clear(); colMeta_.clear(); staleMeta_ = false; } // TODO: Move El::InversePermutation into this class if( staleInverse_ ) { InvertPermutation( perm_, invPerm_ ); staleInverse_ = false; } LogicError("General symmetric permutations are not yet supported"); } } void DistPermutation::ExplicitVector( AbstractDistMatrix<Int>& p ) const { DEBUG_CSE p.SetGrid( grid_ ); if( swapSequence_ ) { p.Resize( size_, 1 ); auto& pLoc = p.Matrix(); const Int localHeight = p.LocalHeight(); for( Int iLoc=0; iLoc<localHeight; ++iLoc ) pLoc(iLoc) = p.GlobalRow(iLoc); PermuteRows( p ); } else { Copy( perm_, p ); } } void DistPermutation::ExplicitMatrix( AbstractDistMatrix<Int>& P ) const { DEBUG_CSE P.SetGrid( grid_ ); DistMatrix<Int,VC,STAR> p_VC_STAR(grid_); ExplicitVector( p_VC_STAR ); DistMatrix<Int,STAR,STAR> p( p_VC_STAR ); auto& pLoc = p.LockedMatrix(); Zeros( P, size_, size_ ); for( Int i=0; i<size_; ++i ) P.Set( i, pLoc(i), 1 ); } #define PROTO(T) \ template void DistPermutation::PermuteCols \ ( AbstractDistMatrix<T>& A, \ Int offset ) const; \ template void DistPermutation::InversePermuteCols \ ( AbstractDistMatrix<T>& A, \ Int offset ) const; \ template void DistPermutation::PermuteRows \ ( AbstractDistMatrix<T>& A, \ Int offset ) const; \ template void DistPermutation::InversePermuteRows \ ( AbstractDistMatrix<T>& A, \ Int offset ) const; \ template void DistPermutation::PermuteSymmetrically \ ( UpperOrLower uplo, \ AbstractDistMatrix<T>& A, \ bool conjugate, \ Int offset ) const; \ template void DistPermutation::InversePermuteSymmetrically \ ( UpperOrLower uplo, \ AbstractDistMatrix<T>& A, \ bool conjugate, \ Int offset ) const; #define EL_ENABLE_DOUBLEDOUBLE #define EL_ENABLE_QUADDOUBLE #define EL_ENABLE_QUAD #define EL_ENABLE_BIGINT #define EL_ENABLE_BIGFLOAT #include <El/macros/Instantiate.h> } // namespace El
29.26236
80
0.576373
[ "vector" ]
1b9ad00da23dfb15e6ab05ad62344e9ddff78bbe
1,700
cpp
C++
tests/map_impl/move.cpp
sugawaray/filemanager
3dcb908d4c1e0c36de0c60e1b2e1291eec986cb1
[ "MIT" ]
null
null
null
tests/map_impl/move.cpp
sugawaray/filemanager
3dcb908d4c1e0c36de0c60e1b2e1291eec986cb1
[ "MIT" ]
null
null
null
tests/map_impl/move.cpp
sugawaray/filemanager
3dcb908d4c1e0c36de0c60e1b2e1291eec986cb1
[ "MIT" ]
null
null
null
#include <algorithm> #include <iterator> #include <string> #include <vector> #include "fixture/move_copy.h" #include "move.h" #include <map_impl.h> #include <tests/fixture/db.h> using namespace ml; using std::function; using std::string; using ::test::Db_fixture; using map_impl::test::Move_copy_fixture; namespace { function<void (Map_impl&, const string&, const string&)> get_delegate() { using namespace std::placeholders; return std::bind(&Map_impl::move, _1, _2, _3); } } // unnamed using namespace std; START_TEST(should_not_add_destination_without_entry_for_source) { Move_copy_fixture f(get_delegate()); f.test_should_not_add_destination_without_entry(); } END_TEST START_TEST(should_change_destination_without_entry_for_source) { Move_copy_fixture f(get_delegate()); f.test_should_change_destination_without_entry(); } END_TEST START_TEST(should_change_destination) { Move_copy_fixture f(get_delegate()); f.test_should_change_destination(); } END_TEST START_TEST(should_remove_source) { Move_copy_fixture f(get_delegate()); f.test_source_removal(true); } END_TEST START_TEST(should_create_destination) { Move_copy_fixture f(get_delegate()); f.test_should_create_destination(); } END_TEST namespace ml { namespace test { namespace map_impl { TCase* create_tcase_for_move() { TCase* tcase = tcase_create("move"); tcase_add_test(tcase, should_not_add_destination_without_entry_for_source); tcase_add_test(tcase, should_change_destination_without_entry_for_source); tcase_add_test(tcase, should_change_destination); tcase_add_test(tcase, should_remove_source); tcase_add_test(tcase, should_create_destination); return tcase; } } // map_impl } // test } // ml
20.238095
63
0.793529
[ "vector" ]
1b9ae230f7f3b2483703822478db3ad7739e6116
12,429
cpp
C++
esphome/components/max7219digit/max7219digit.cpp
OttoWinter/esphomeyaml
6a85259e4d6d1b0a0f819688b8e555efcb99ecb0
[ "MIT" ]
249
2018-04-07T12:04:11.000Z
2019-01-25T01:11:34.000Z
esphome/components/max7219digit/max7219digit.cpp
OttoWinter/esphomeyaml
6a85259e4d6d1b0a0f819688b8e555efcb99ecb0
[ "MIT" ]
243
2018-04-11T16:37:11.000Z
2019-01-25T16:50:37.000Z
esphome/components/max7219digit/max7219digit.cpp
OttoWinter/esphomeyaml
6a85259e4d6d1b0a0f819688b8e555efcb99ecb0
[ "MIT" ]
40
2018-04-10T05:50:14.000Z
2019-01-25T15:20:36.000Z
#include "max7219digit.h" #include "esphome/core/log.h" #include "esphome/core/helpers.h" #include "esphome/core/hal.h" #include "max7219font.h" namespace esphome { namespace max7219digit { static const char *const TAG = "max7219DIGIT"; static const uint8_t MAX7219_REGISTER_NOOP = 0x00; static const uint8_t MAX7219_REGISTER_DECODE_MODE = 0x09; static const uint8_t MAX7219_REGISTER_INTENSITY = 0x0A; static const uint8_t MAX7219_REGISTER_SCAN_LIMIT = 0x0B; static const uint8_t MAX7219_REGISTER_SHUTDOWN = 0x0C; static const uint8_t MAX7219_REGISTER_DISPLAY_TEST = 0x0F; constexpr uint8_t MAX7219_NO_SHUTDOWN = 0x00; constexpr uint8_t MAX7219_SHUTDOWN = 0x01; constexpr uint8_t MAX7219_NO_DISPLAY_TEST = 0x00; constexpr uint8_t MAX7219_DISPLAY_TEST = 0x01; float MAX7219Component::get_setup_priority() const { return setup_priority::PROCESSOR; } void MAX7219Component::setup() { ESP_LOGCONFIG(TAG, "Setting up MAX7219_DIGITS..."); this->spi_setup(); this->stepsleft_ = 0; for (int chip_line = 0; chip_line < this->num_chip_lines_; chip_line++) { std::vector<uint8_t> vec(1); this->max_displaybuffer_.push_back(vec); // Initialize buffer with 0 for display so all non written pixels are blank this->max_displaybuffer_[chip_line].resize(get_width_internal(), 0); } // let's assume the user has all 8 digits connected, only important in daisy chained setups anyway this->send_to_all_(MAX7219_REGISTER_SCAN_LIMIT, 7); // let's use our own ASCII -> led pattern encoding this->send_to_all_(MAX7219_REGISTER_DECODE_MODE, 0); // No display test with all the pixels on this->send_to_all_(MAX7219_REGISTER_DISPLAY_TEST, MAX7219_NO_DISPLAY_TEST); // SET Intsity of display this->send_to_all_(MAX7219_REGISTER_INTENSITY, this->intensity_); // this->send_to_all_(MAX7219_REGISTER_INTENSITY, 1); this->display(); // power up this->send_to_all_(MAX7219_REGISTER_SHUTDOWN, 1); } void MAX7219Component::dump_config() { ESP_LOGCONFIG(TAG, "MAX7219DIGIT:"); ESP_LOGCONFIG(TAG, " Number of Chips: %u", this->num_chips_); ESP_LOGCONFIG(TAG, " Number of Chips Lines: %u", this->num_chip_lines_); ESP_LOGCONFIG(TAG, " Chips Lines Style : %u", this->chip_lines_style_); ESP_LOGCONFIG(TAG, " Intensity: %u", this->intensity_); ESP_LOGCONFIG(TAG, " Scroll Mode: %u", this->scroll_mode_); ESP_LOGCONFIG(TAG, " Scroll Speed: %u", this->scroll_speed_); ESP_LOGCONFIG(TAG, " Scroll Dwell: %u", this->scroll_dwell_); ESP_LOGCONFIG(TAG, " Scroll Delay: %u", this->scroll_delay_); LOG_PIN(" CS Pin: ", this->cs_); LOG_UPDATE_INTERVAL(this); } void MAX7219Component::loop() { uint32_t now = millis(); // check if the buffer has shrunk past the current position since last update if ((this->max_displaybuffer_[0].size() >= this->old_buffer_size_ + 3) || (this->max_displaybuffer_[0].size() <= this->old_buffer_size_ - 3)) { this->stepsleft_ = 0; this->display(); this->old_buffer_size_ = this->max_displaybuffer_[0].size(); } // Reset the counter back to 0 when full string has been displayed. if (this->stepsleft_ > this->max_displaybuffer_[0].size()) this->stepsleft_ = 0; // Return if there is no need to scroll or scroll is off if (!this->scroll_ || (this->max_displaybuffer_[0].size() <= (size_t) get_width_internal())) { this->display(); return; } if ((this->stepsleft_ == 0) && (now - this->last_scroll_ < this->scroll_delay_)) { this->display(); return; } // Dwell time at end of string in case of stop at end if (this->scroll_mode_ == ScrollMode::STOP) { if (this->stepsleft_ >= this->max_displaybuffer_[0].size() - (size_t) get_width_internal() + 1) { if (now - this->last_scroll_ >= this->scroll_dwell_) { this->stepsleft_ = 0; this->last_scroll_ = now; this->display(); } return; } } // Actual call to scroll left action if (now - this->last_scroll_ >= this->scroll_speed_) { this->last_scroll_ = now; this->scroll_left(); this->display(); } } void MAX7219Component::display() { uint8_t pixels[8]; // Run this loop for every MAX CHIP (GRID OF 64 leds) // Run this routine for the rows of every chip 8x row 0 top to 7 bottom // Fill the pixel parameter with display data // Send the data to the chip for (uint8_t chip = 0; chip < this->num_chips_ / this->num_chip_lines_; chip++) { for (uint8_t chip_line = 0; chip_line < this->num_chip_lines_; chip_line++) { for (uint8_t j = 0; j < 8; j++) { bool reverse = chip_line % 2 != 0 && this->chip_lines_style_ == ChipLinesStyle::SNAKE ? !this->reverse_ : this->reverse_; if (reverse) { pixels[j] = this->max_displaybuffer_[chip_line][(this->num_chips_ / this->num_chip_lines_ - chip - 1) * 8 + j]; } else { pixels[j] = this->max_displaybuffer_[chip_line][chip * 8 + j]; } } if (chip_line % 2 != 0 && this->chip_lines_style_ == ChipLinesStyle::SNAKE) this->orientation_ = orientation_180_(); this->send64pixels(chip_line * this->num_chips_ / this->num_chip_lines_ + chip, pixels); if (chip_line % 2 != 0 && this->chip_lines_style_ == ChipLinesStyle::SNAKE) this->orientation_ = orientation_180_(); } } } uint8_t MAX7219Component::orientation_180_() { switch (this->orientation_) { case 0: return 2; case 1: return 3; case 2: return 0; case 3: return 1; default: return 0; } } int MAX7219Component::get_height_internal() { return 8 * this->num_chip_lines_; // TO BE DONE -> CREATE Virtual size of screen and scroll } int MAX7219Component::get_width_internal() { return this->num_chips_ / this->num_chip_lines_ * 8; } void HOT MAX7219Component::draw_absolute_pixel_internal(int x, int y, Color color) { if (x + 1 > (int) this->max_displaybuffer_[0].size()) { // Extend the display buffer in case required for (int chip_line = 0; chip_line < this->num_chip_lines_; chip_line++) { this->max_displaybuffer_[chip_line].resize(x + 1, this->bckgrnd_); } } if ((y >= this->get_height_internal()) || (y < 0) || (x < 0)) // If pixel is outside display then dont draw return; uint16_t pos = x; // X is starting at 0 top left uint8_t subpos = y; // Y is starting at 0 top left if (color.is_on()) { this->max_displaybuffer_[subpos / 8][pos] |= (1 << subpos % 8); } else { this->max_displaybuffer_[subpos / 8][pos] &= ~(1 << subpos % 8); } } void MAX7219Component::send_byte_(uint8_t a_register, uint8_t data) { this->write_byte(a_register); // Write register value to MAX this->write_byte(data); // Followed by actual data } void MAX7219Component::send_to_all_(uint8_t a_register, uint8_t data) { this->enable(); // Enable SPI for (uint8_t i = 0; i < this->num_chips_; i++) // Run the loop for every MAX chip in the stack this->send_byte_(a_register, data); // Send the data to the chips this->disable(); // Disable SPI } void MAX7219Component::update() { this->update_ = true; for (int chip_line = 0; chip_line < this->num_chip_lines_; chip_line++) { this->max_displaybuffer_[chip_line].clear(); this->max_displaybuffer_[chip_line].resize(get_width_internal(), this->bckgrnd_); } if (this->writer_local_.has_value()) // insert Labda function if available (*this->writer_local_)(*this); } void MAX7219Component::invert_on_off(bool on_off) { this->invert_ = on_off; }; void MAX7219Component::invert_on_off() { this->invert_ = !this->invert_; }; void MAX7219Component::turn_on_off(bool on_off) { if (on_off) { this->send_to_all_(MAX7219_REGISTER_SHUTDOWN, 1); } else { this->send_to_all_(MAX7219_REGISTER_SHUTDOWN, 0); } } void MAX7219Component::scroll(bool on_off, ScrollMode mode, uint16_t speed, uint16_t delay, uint16_t dwell) { this->set_scroll(on_off); this->set_scroll_mode(mode); this->set_scroll_speed(speed); this->set_scroll_dwell(dwell); this->set_scroll_delay(delay); } void MAX7219Component::scroll(bool on_off, ScrollMode mode) { this->set_scroll(on_off); this->set_scroll_mode(mode); } void MAX7219Component::intensity(uint8_t intensity) { this->intensity_ = intensity; this->send_to_all_(MAX7219_REGISTER_INTENSITY, this->intensity_); } void MAX7219Component::scroll(bool on_off) { this->set_scroll(on_off); } void MAX7219Component::scroll_left() { for (int chip_line = 0; chip_line < this->num_chip_lines_; chip_line++) { if (this->update_) { this->max_displaybuffer_[chip_line].push_back(this->bckgrnd_); for (uint16_t i = 0; i < this->stepsleft_; i++) { this->max_displaybuffer_[chip_line].push_back(this->max_displaybuffer_[chip_line].front()); this->max_displaybuffer_[chip_line].erase(this->max_displaybuffer_[chip_line].begin()); } } else { this->max_displaybuffer_[chip_line].push_back(this->max_displaybuffer_[chip_line].front()); this->max_displaybuffer_[chip_line].erase(this->max_displaybuffer_[chip_line].begin()); } } this->update_ = false; this->stepsleft_++; } void MAX7219Component::send_char(uint8_t chip, uint8_t data) { // get this character from PROGMEM for (uint8_t i = 0; i < 8; i++) this->max_displaybuffer_[0][chip * 8 + i] = progmem_read_byte(&MAX7219_DOT_MATRIX_FONT[data][i]); } // end of send_char // send one character (data) to position (chip) void MAX7219Component::send64pixels(uint8_t chip, const uint8_t pixels[8]) { for (uint8_t col = 0; col < 8; col++) { // RUN THIS LOOP 8 times until column is 7 this->enable(); // start sending by enabling SPI for (uint8_t i = 0; i < chip; i++) { // send extra NOPs to push the pixels out to extra displays this->send_byte_(MAX7219_REGISTER_NOOP, MAX7219_REGISTER_NOOP); // run this loop unit the matching chip is reached } uint8_t b = 0; // rotate pixels 90 degrees -- set byte to 0 if (this->orientation_ == 0) { for (uint8_t i = 0; i < 8; i++) { // run this loop 8 times for all the pixels[8] received b |= ((pixels[i] >> col) & 1) << (7 - i); // change the column bits into row bits } } else if (this->orientation_ == 1) { b = pixels[col]; } else if (this->orientation_ == 2) { for (uint8_t i = 0; i < 8; i++) { b |= ((pixels[i] >> (7 - col)) & 1) << i; } } else { b = pixels[7 - col]; } // send this byte to display at selected chip if (this->invert_) { this->send_byte_(col + 1, ~b); } else { this->send_byte_(col + 1, b); } for (int i = 0; i < this->num_chips_ - chip - 1; i++) // end with enough NOPs so later chips don't update this->send_byte_(MAX7219_REGISTER_NOOP, MAX7219_REGISTER_NOOP); this->disable(); // all done disable SPI } // end of for each column } // end of send64pixels uint8_t MAX7219Component::printdigit(const char *str) { return this->printdigit(0, str); } uint8_t MAX7219Component::printdigit(uint8_t start_pos, const char *s) { uint8_t chip = start_pos; for (; chip < this->num_chips_ && *s; chip++) send_char(chip, *s++); // space out rest while (chip < (this->num_chips_)) send_char(chip++, ' '); return 0; } // end of sendString uint8_t MAX7219Component::printdigitf(uint8_t pos, const char *format, ...) { va_list arg; va_start(arg, format); char buffer[64]; int ret = vsnprintf(buffer, sizeof(buffer), format, arg); va_end(arg); if (ret > 0) return this->printdigit(pos, buffer); return 0; } uint8_t MAX7219Component::printdigitf(const char *format, ...) { va_list arg; va_start(arg, format); char buffer[64]; int ret = vsnprintf(buffer, sizeof(buffer), format, arg); va_end(arg); if (ret > 0) return this->printdigit(buffer); return 0; } #ifdef USE_TIME uint8_t MAX7219Component::strftimedigit(uint8_t pos, const char *format, time::ESPTime time) { char buffer[64]; size_t ret = time.strftime(buffer, sizeof(buffer), format); if (ret > 0) return this->printdigit(pos, buffer); return 0; } uint8_t MAX7219Component::strftimedigit(const char *format, time::ESPTime time) { return this->strftimedigit(0, format, time); } #endif } // namespace max7219digit } // namespace esphome
37.101493
118
0.669965
[ "vector" ]
1ba96d199a9825a5a668599bbe0de601dd4bc6d5
898
cpp
C++
207.cpp
zhangchbin/LeetRecord
7f377b1a61e8f2a6fd86d028911c2722c1d03650
[ "MIT" ]
1
2020-09-12T07:38:23.000Z
2020-09-12T07:38:23.000Z
207.cpp
zhangchbin/LeetRecord
7f377b1a61e8f2a6fd86d028911c2722c1d03650
[ "MIT" ]
1
2020-09-12T07:38:27.000Z
2020-09-12T07:40:26.000Z
207.cpp
zhangchbin/LeetRecord
7f377b1a61e8f2a6fd86d028911c2722c1d03650
[ "MIT" ]
null
null
null
class Solution { public: bool canFinish(int numCourses, vector<vector<int>>& prerequisites) { int inside[numCourses]; memset(inside, 0, sizeof(inside)); vector<vector<int> > vec; for(int i = 0; i< numCourses; i++) vec.push_back(vector<int>{}); for(int i = 0; i < prerequisites.size(); i++){ vec[prerequisites[i][1]].push_back(prerequisites[i][0]); inside[prerequisites[i][0]]++; } queue<int>q; for(int i=0;i<numCourses;i++) if(inside[i] == 0) q.push(i); while(!q.empty()){ int u = q.front(); q.pop(); for(auto o: vec[u]){ inside[o]--; if(inside[o] == 0) q.push(o); } } for(int i=0;i<numCourses;i++){ if(inside[i]) return false; } return true; } };
28.967742
72
0.46882
[ "vector" ]
1babbdb93bc2703ed8e773f1d9b1cabe4e1f972f
27,021
hpp
C++
include/TGUI/Components.hpp
texus/TGUI
87042f5dfafe9421d8a916b23ce7575d16f06d4c
[ "Zlib" ]
543
2015-01-03T22:53:59.000Z
2022-03-25T08:55:45.000Z
include/TGUI/Components.hpp
texus/TGUI
87042f5dfafe9421d8a916b23ce7575d16f06d4c
[ "Zlib" ]
118
2015-01-21T12:22:58.000Z
2022-03-31T17:05:33.000Z
include/TGUI/Components.hpp
texus/TGUI
87042f5dfafe9421d8a916b23ce7575d16f06d4c
[ "Zlib" ]
111
2015-02-02T13:22:13.000Z
2022-03-31T08:09:40.000Z
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // TGUI - Texus' Graphical User Interface // Copyright (C) 2012-2021 Bruno Van de Velde (vdv_b@tgui.eu) // // This software is provided 'as-is', without any express or implied warranty. // In no event will the authors be held liable for any damages arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it freely, // subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; // you must not claim that you wrote the original software. // If you use this software in a product, an acknowledgment // in the product documentation would be appreciated but is not required. // // 2. Altered source versions must be plainly marked as such, // and must not be misrepresented as being the original software. // // 3. This notice may not be removed or altered from any source distribution. // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #ifndef TGUI_COMPONENTS_HPP #define TGUI_COMPONENTS_HPP #include <TGUI/Text.hpp> #include <TGUI/Sprite.hpp> #include <TGUI/Texture.hpp> #include <TGUI/Outline.hpp> #include <unordered_map> #include <memory> #include <set> ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// namespace tgui { class BackendRenderTarget; namespace priv { namespace dev { ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// State of a widget or a component inside it enum class ComponentState : std::uint8_t { Normal = 0, //!< Default state Hover = 1, //!< Mouse hover Active = 2, //!< Pressed/checked/selected ActiveHover = 3, //!< Pressed/checked/selected with mouse hover Focused = 4, //!< Has focused FocusedHover = 5, //!< Has focused with mouse hover FocusedActive = 6, //!< Has focused while pressed/checked/selected FocusedActiveHover = 7, //!< Has focused while pressed/checked/selected with mouse hover Disabled = 8, //!< Is disabled DisabledActive = 10 //!< Is disabled while pressed/checked/selected }; ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// Layout alignment for automatically setting the position and (part of) the size of a component enum class AlignLayout { None, //!< Position and size need to be manually set. This is the default. Top, //!< Places the component on on the top and sets its width to the area between Leftmost and Rightmost aligned components. Height needs to be manually set. Left, //!< Places the component on the left side and sets its height to the area between Top and Bottom aligned components. Width needs to be manually set. Right, //!< Places the component on the right side and sets its height to the area between Top and Bottom aligned components. Width needs to be manually set. Bottom, //!< Places the component on on the bottom and sets its width to the area between Leftmost and Rightmost aligned components. Height needs to be manually set. Leftmost, //!< Places the component on the left side and sets height to 100%. Width needs to be manually set. Same as Left alignment if no component uses Top or Bottom alignment. Rightmost, //!< Places the component on the right side and sets height to 100%. Width needs to be manually set. Same as Left alignment if no component uses Top or Bottom alignment. Fill //!< Sets the position to (0,0) and size to (100%,100%). }; ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// Position alignment of a component within its parent enum class PositionAlignment { None, //!< Place the component at the manually set position. This is the default. TopLeft, //!< Place the component in the upper left corner of its parent Top, //!< Place the component at the upper side of its parent (horizontally centered) TopRight, //!< Place the component in the upper right corner of its parent Right, //!< Place the component at the right side of its parent (vertically centered) BottomRight, //!< Place the component in the bottom right corner of its parent Bottom, //!< Place the component at the bottom of its parent (horizontally centered) BottomLeft, //!< Place the component in the bottom left corner of its parent Left, //!< Place the component at the left side of its parent (vertically centered) Center //!< Center the component in its parent }; ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class TGUI_API MessageBroker { public: static std::uint64_t createTopic(); static void destroyTopic(std::uint64_t topicId); static std::uint64_t subscribe(std::uint64_t topicId, std::function<void()> func); static void unsubscribe(std::uint64_t callbackId); static void sendEvent(std::uint64_t topicId); private: static std::unordered_map<std::uint64_t, std::set<std::uint64_t>> m_topicIdToCallbackIds; static std::unordered_map<std::uint64_t, std::uint64_t> m_callbackIdToTopicId; static std::unordered_map<std::uint64_t, std::function<void()>> m_listeners; // CallbackId -> Func // All topic and callback ids are unique and non-overlapping static std::uint64_t m_lastId; }; ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class TGUI_API StylePropertyBase { public: virtual ~StylePropertyBase() = default; }; ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// template <typename ValueType> class TGUI_API StyleProperty : public StylePropertyBase { public: StyleProperty() : m_defaultValue {}, m_propertyData {0}, m_messageTopicId{MessageBroker::createTopic()} { } explicit StyleProperty(const ValueType& defaultValue) : m_defaultValue {defaultValue}, m_propertyData {0}, m_messageTopicId{MessageBroker::createTopic()} { } StyleProperty(const StyleProperty& other) : m_defaultValue {other.m_defaultValue}, m_propertyData {0}, m_messageTopicId{MessageBroker::createTopic()}, m_globalValues {other.m_globalValues} { unsetValue(); const std::uint64_t baseIndex = m_propertyData & 0xFFFFFFFFFFFF0000; const std::uint64_t oldBaseIndex = other.m_propertyData & 0xFFFFFFFFFFFF0000; const std::uint16_t oldStoredStates = static_cast<std::uint16_t>(other.m_propertyData & 0xFFFF); std::uint16_t total = 0; std::uint8_t bitIndex = 0; while (total < oldStoredStates) { if (oldStoredStates & (1 << bitIndex)) { m_globalValues[baseIndex + bitIndex] = m_globalValues[oldBaseIndex + bitIndex]; total += (1 << bitIndex); } ++bitIndex; } m_propertyData = baseIndex | oldStoredStates; } StyleProperty(StyleProperty&& other) : m_defaultValue {std::move(other.m_defaultValue)}, m_propertyData {std::move(other.m_propertyData)}, m_messageTopicId{std::move(other.m_messageTopicId)}, m_globalValues {std::move(other.m_globalValues)} { other.m_messageTopicId = 0; } ~StyleProperty() { if (m_messageTopicId) // Can be 0 on moved object MessageBroker::destroyTopic(m_messageTopicId); unsetValueImpl(); } StyleProperty& operator=(const StyleProperty& other) { if (&other != this) { StyleProperty temp(other); std::swap(m_defaultValue, temp.m_defaultValue); std::swap(m_propertyData, temp.m_propertyData); std::swap(m_messageTopicId, temp.m_messageTopicId); std::swap(m_globalValues, temp.m_globalValues); } return *this; } StyleProperty& operator=(StyleProperty&& other) { if (&other != this) { m_defaultValue = std::move(other.m_defaultValue); m_propertyData = std::move(other.m_propertyData); m_messageTopicId = std::move(other.m_messageTopicId); m_globalValues = std::move(other.m_globalValues); other.m_messageTopicId = 0; } return *this; } StyleProperty& operator=(const ValueType& value) { unsetValueImpl(); setValue(value, ComponentState::Normal); return *this; } void setValue(const ValueType& value, ComponentState state = ComponentState::Normal) { const std::uint64_t baseIndex = m_propertyData & 0xFFFFFFFFFFFF0000; m_propertyData |= static_cast<std::uint64_t>(1) << static_cast<std::uint8_t>(state); m_globalValues[baseIndex + static_cast<std::uint8_t>(state)] = value; MessageBroker::sendEvent(m_messageTopicId); } void unsetValue(ComponentState state) { const std::uint64_t baseIndex = m_propertyData & 0xFFFFFFFFFFFF0000; m_propertyData &= ~(1 << static_cast<std::uint8_t>(state)); m_globalValues.erase(baseIndex + static_cast<std::uint8_t>(state)); MessageBroker::sendEvent(m_messageTopicId); } void unsetValue() { unsetValueImpl(); MessageBroker::sendEvent(m_messageTopicId); } const ValueType& getValue(ComponentState state = ComponentState::Normal) const { const std::uint64_t baseIndex = m_propertyData & 0xFFFFFFFFFFFF0000; const std::uint16_t storedStates = static_cast<std::uint16_t>(m_propertyData & 0xFFFF); // If we don't have a value for any state then we can just return the default value if (storedStates == 0) return m_defaultValue; // If we only have a value for the Normal state then always use this value if (storedStates == 1) return m_globalValues.at(baseIndex); if (static_cast<std::uint8_t>(state) & static_cast<std::uint8_t>(ComponentState::Disabled)) { if ((static_cast<std::uint8_t>(state) & static_cast<std::uint8_t>(ComponentState::Active)) && (storedStates & (1 << static_cast<std::uint8_t>(ComponentState::DisabledActive)))) return m_globalValues.at(baseIndex + static_cast<std::uint8_t>(ComponentState::DisabledActive)); if (storedStates & (1 << static_cast<std::uint8_t>(ComponentState::Disabled))) return m_globalValues.at(baseIndex + static_cast<std::uint8_t>(ComponentState::Disabled)); } if (static_cast<std::uint8_t>(state) & static_cast<std::uint8_t>(ComponentState::Active)) { if (static_cast<std::uint8_t>(state) & static_cast<std::uint8_t>(ComponentState::Hover)) { if ((static_cast<std::uint8_t>(state) & static_cast<std::uint8_t>(ComponentState::Focused)) && (storedStates & (1 << static_cast<std::uint8_t>(ComponentState::FocusedActiveHover)))) return m_globalValues.at(baseIndex + static_cast<std::uint8_t>(ComponentState::FocusedActiveHover)); if (storedStates & (1 << static_cast<std::uint8_t>(ComponentState::ActiveHover))) return m_globalValues.at(baseIndex + static_cast<std::uint8_t>(ComponentState::ActiveHover)); } if ((static_cast<std::uint8_t>(state) & static_cast<std::uint8_t>(ComponentState::Focused)) && (storedStates & (1 << static_cast<std::uint8_t>(ComponentState::FocusedActive)))) return m_globalValues.at(baseIndex + static_cast<std::uint8_t>(ComponentState::FocusedActive)); if (storedStates & (1 << static_cast<std::uint8_t>(ComponentState::Active))) return m_globalValues.at(baseIndex + static_cast<std::uint8_t>(ComponentState::Active)); } if (static_cast<std::uint8_t>(state) & static_cast<std::uint8_t>(ComponentState::Hover)) { if ((static_cast<std::uint8_t>(state) & static_cast<std::uint8_t>(ComponentState::Focused)) && (storedStates & (1 << static_cast<std::uint8_t>(ComponentState::FocusedHover)))) return m_globalValues.at(baseIndex + static_cast<std::uint8_t>(ComponentState::FocusedHover)); if (storedStates & (1 << static_cast<std::uint8_t>(ComponentState::Hover))) return m_globalValues.at(baseIndex + static_cast<std::uint8_t>(ComponentState::Hover)); } if (static_cast<std::uint8_t>(state) & static_cast<std::uint8_t>(ComponentState::Focused)) { if (storedStates & (1 << static_cast<std::uint8_t>(ComponentState::Focused))) return m_globalValues.at(baseIndex + static_cast<std::uint8_t>(ComponentState::Focused)); } if (storedStates & 1) { // We have a value for the Normal state, so return it. It is possible to pass here while storedStates != 1 when there // is e.g. a value for both Normal and Disabled state and the widget is enabled. return m_globalValues.at(baseIndex + static_cast<std::uint8_t>(ComponentState::Normal)); } else { // We don't have any relevant values, so return the default value. It is possible to pass here while storedStates > 0 when // there is e.g. only a value for the Disabled state and the widget is enabled. return m_defaultValue; } } std::uint64_t connectCallback(std::function<void()> func) { return MessageBroker::subscribe(m_messageTopicId, std::move(func)); } void disconnectCallback(std::uint64_t id) { return MessageBroker::unsubscribe(id); } private: void unsetValueImpl() { const std::uint64_t baseIndex = m_propertyData & 0xFFFFFFFFFFFF0000; const std::uint16_t storedStates = static_cast<std::uint16_t>(m_propertyData & 0xFFFF); std::uint16_t total = 0; std::uint8_t bitIndex = 0; while (total < storedStates) { if (storedStates & (1 << bitIndex)) { m_globalValues.erase(baseIndex + bitIndex); total += (1 << bitIndex); } ++bitIndex; } m_propertyData = baseIndex; // Forget about the states that were stored } private: ValueType m_defaultValue; // The highest 48 bits store the index in a static map of values (see below). // The next 16 bits are used to indicate the set of states that are present for this property. std::uint64_t m_propertyData = 0; // Index of the event that we publish to when the property changes. std::uint64_t m_messageTopicId = 0; // All values are stored in a static map, which can be seen as a very large sparse list. // Each instance holds a unique 48-bit id that can be seen as the high bits of the index in the list. // The lowest 4 bits of the index contain the widget state. The remaining 12 bits inbetween are always 0. ///static std::unordered_map<std::uint64_t, ValueType> m_globalValues; ///static std::uint64_t m_nextGlobalValueIndex; /// TODO: The system with global values caused way too many implementation and platform-specific problems. /// For now we just store the values in the StyleProperty itself. std::unordered_map<std::uint64_t, ValueType> m_globalValues; }; ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// struct TGUI_API StylePropertyBackground { StyleProperty<Color> borderColor{Color::Black}; StyleProperty<Color> color{Color::White}; StyleProperty<Texture> texture; StyleProperty<Outline> borders; StyleProperty<Outline> padding; float roundedBorderRadius = 0; }; ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// struct TGUI_API StylePropertyText { StyleProperty<Color> color{Color::Black}; StyleProperty<TextStyles> style; }; ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class GroupComponent; class TGUI_API Component { public: Component(const Component&); Component& operator=(const Component&); Component(Component&&) = default; Component& operator=(Component&&) = default; void setPosition(Vector2f position); Vector2f getPosition() const; Vector2f getSize() const; void setPositionAlignment(PositionAlignment alignment); void setVisible(bool visible); bool isVisible() const; void setParent(GroupComponent* parent); virtual void draw(BackendRenderTarget& target, RenderStates states) const = 0; virtual void updateLayout(); virtual std::shared_ptr<Component> clone() const = 0; protected: Component() = default; virtual ~Component() = default; friend void swap(Component& first, Component& second); protected: ComponentState m_state = ComponentState::Normal; PositionAlignment m_positionAlignment = PositionAlignment::None; Vector2f m_position; Vector2f m_size; bool m_visible = true; float m_opacity = 1; GroupComponent* m_parent = nullptr; }; class TGUI_API GroupComponent : public Component { public: GroupComponent(const GroupComponent&); GroupComponent& operator=(const GroupComponent&); GroupComponent(GroupComponent&&) = default; GroupComponent& operator=(GroupComponent&&) = default; Vector2f getClientSize() const; void addComponent(const std::shared_ptr<Component>& component); const std::vector<std::shared_ptr<Component>>& getComponents() const; void draw(BackendRenderTarget& target, RenderStates states) const override; void updateLayout() override; std::shared_ptr<Component> clone() const override; friend void swap(GroupComponent& first, GroupComponent& second); protected: GroupComponent() = default; protected: std::vector<std::shared_ptr<Component>> m_children; Vector2f m_clientSize; }; ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class TGUI_API BackgroundComponent : public GroupComponent { public: BackgroundComponent(StylePropertyBackground* backgroundStyle); ~BackgroundComponent(); BackgroundComponent(const BackgroundComponent& other, StylePropertyBackground* backgroundStyle = nullptr); BackgroundComponent& operator=(const BackgroundComponent& other); void init(); void setSize(Vector2f size); void setBorders(const Outline& border); const Outline& getBorders() const; void setPadding(const Outline& padding); const Outline& getPadding() const; void setOpacity(float opacity); void setComponentState(ComponentState state); bool isTransparentPixel(Vector2f pos, bool transparentTexture) const; void draw(BackendRenderTarget& target, RenderStates states) const override; Vector2f getSizeWithoutBorders() const; void updateLayout() override; std::shared_ptr<Component> clone() const override; private: struct ColorRect { Color color; FloatRect rect; }; StylePropertyBackground* m_backgroundStyle; ColorRect m_background{Color::White, {}}; Color m_borderColor = Color::Black; Sprite m_sprite; Outline m_borders; Outline m_padding; std::uint64_t m_borderColorCallbackId = 0; std::uint64_t m_backgroundColorCallbackId = 0; std::uint64_t m_textureCallbackId = 0; std::uint64_t m_bordersCallbackId = 0; std::uint64_t m_paddingCallbackId = 0; }; ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class TGUI_API TextComponent : public Component { public: TextComponent(StylePropertyText* textStyle); ~TextComponent(); TextComponent(const TextComponent& other, StylePropertyText* textStyle = nullptr); TextComponent& operator=(const TextComponent& other); void init(); void setString(const String& caption); const String& getString() const; void setCharacterSize(unsigned int size); unsigned int getCharacterSize() const; void setFont(Font font); Font getFont() const; void setOutlineColor(Color color); Color getOutlineColor() const; void setOutlineThickness(float thickness); float getOutlineThickness() const; float getLineHeight() const; void setOpacity(float opacity); void updateLayout() override; void setComponentState(ComponentState state); void draw(BackendRenderTarget& target, RenderStates states) const override; std::shared_ptr<Component> clone() const override; private: Text m_text; StylePropertyText* m_textStyle; Color m_color = Color::Black; TextStyles m_style = TextStyle::Regular; std::uint64_t m_colorCallbackId = 0; std::uint64_t m_styleCallbackId = 0; }; ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class TGUI_API ImageComponent : public Component { public: ImageComponent(StyleProperty<Texture>* textureStyle); ~ImageComponent(); ImageComponent(const ImageComponent& other, StyleProperty<Texture>* textureStyle = nullptr); ImageComponent& operator=(const ImageComponent& other); void init(); void setSize(Vector2f size); void setOpacity(float opacity); void setComponentState(ComponentState state); bool isTransparentPixel(Vector2f pos, bool transparentTexture) const; void draw(BackendRenderTarget& target, RenderStates states) const override; std::shared_ptr<Component> clone() const override; private: StyleProperty<Texture>* m_textureStyle; Sprite m_sprite; std::uint64_t m_textureCallbackId = 0; }; ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// inline ComponentState getStateFromFlags(bool hover, bool active, bool focused = false, bool enabled = true) { if (!enabled) { if (active) return ComponentState::DisabledActive; else return ComponentState::Disabled; } else if (focused) { if (active) { if (hover) return ComponentState::FocusedActiveHover; else return ComponentState::FocusedActive; } else if (hover) return ComponentState::FocusedHover; else return ComponentState::Focused; } else if (active) { if (hover) return ComponentState::ActiveHover; else return ComponentState::Active; } else if (hover) return ComponentState::Hover; else return ComponentState::Normal; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// inline void setOptionalPropertyValue(StyleProperty<Color>& property, const Color& color, ComponentState state) { if (color.isSet()) property.setValue(color, state); else property.unsetValue(state); } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// inline void setOptionalPropertyValue(StyleProperty<TextStyles>& property, const TextStyles& style, ComponentState state) { if (style.isSet()) property.setValue(style, state); else property.unsetValue(state); } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// inline void setOptionalPropertyValue(StyleProperty<Texture>& property, const Texture& texture, ComponentState state) { if (texture.getData()) property.setValue(texture, state); else property.unsetValue(state); } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// } // namespace dev } // namespace priv } // namespace tgui ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #endif // TGUI_COMPONENTS_HPP
37.950843
201
0.56197
[ "object", "vector" ]
1bae6431d55c2513b9cfa4c5bcb134f31b56210c
10,391
cpp
C++
sort_timing.cpp
dion-w-pieterse/cpsc-335-algorithm-engineering-cf-vs-ec
2f3fab2b4522bfb8e525ed49712c76986760b874
[ "MIT" ]
null
null
null
sort_timing.cpp
dion-w-pieterse/cpsc-335-algorithm-engineering-cf-vs-ec
2f3fab2b4522bfb8e525ed49712c76986760b874
[ "MIT" ]
null
null
null
sort_timing.cpp
dion-w-pieterse/cpsc-335-algorithm-engineering-cf-vs-ec
2f3fab2b4522bfb8e525ed49712c76986760b874
[ "MIT" ]
null
null
null
/////////////////////////////////////////////////////////////////////////////// // sort_timing.cpp // // Example code showing how to run each algorithm while measuring // elapsed times precisely. You should modify this program to gather // all of your experimental data. // /////////////////////////////////////////////////////////////////////////////// #include <algorithm> #include <cassert> #include <iostream> #include <vector> #include "sort_comparison.hpp" #include "timer.hpp" using namespace std; void print_bar() { cout << string(79, '-') << endl; } int main() { ofstream small_n_results; small_n_results.open("small_value_n_170_results.txt"); const int MAX_SELECTION_SORT_SIZE = 20*1000; const int MAX_SELECTION_SORT_SIZE_MEDIUM = 50000; auto all_words = load_json_string_array("warandpeace.json"); assert( all_words ); double elapsed; Timer timer; //*** n = 2 -> n = 100 //start of loop to generate values for(unsigned long long n = 1; n < 170; n++) { assert( n <= all_words->size() ); const StringVector word_vector(all_words->begin(), all_words->begin() + n); assert( word_vector.size() == n ); const StringList word_list(word_vector.begin(), word_vector.end()); assert( word_list.size() == n ); print_bar(); cout << "n=" << n << endl << endl; StringVector selection_sort_solution; bool do_selection_sort = (n <= MAX_SELECTION_SORT_SIZE); if (!do_selection_sort) { cout << "(n too large for selection sort)" << endl; } else { selection_sort_solution = word_vector; timer.reset(); selection_sort(selection_sort_solution); elapsed = timer.elapsed(); cout << "selection sort elapsed time=" << elapsed << " seconds" << endl; small_n_results << "sel.sort: " << "\t" << elapsed << "\t"; } timer.reset(); auto merge_sort_list_solution = merge_sort_list(word_list); elapsed = timer.elapsed(); cout << "merge sort list elapsed time=" << elapsed << " seconds" << endl; small_n_results << "merge sort list: " << "\t" << elapsed << "\t"; timer.reset(); auto merge_sort_vector_solution = merge_sort_vector(word_vector); elapsed = timer.elapsed(); cout << "merge sort vector elapsed time=" << elapsed << " seconds" << endl; small_n_results << "merge sort vector: " << "\t" << elapsed << "\t"; StringVector builtin_sort_solution = word_vector; timer.reset(); builtin_sort(builtin_sort_solution); elapsed = timer.elapsed(); cout << "builtin sort elapsed time=" << elapsed << " seconds" << endl; small_n_results << "builtin sort: " << "\t" << elapsed << "\t"; small_n_results << "\n"; if (do_selection_sort) { assert(std::equal(builtin_sort_solution.begin(), builtin_sort_solution.end(), selection_sort_solution.begin())); } assert(std::equal(builtin_sort_solution.begin(), builtin_sort_solution.end(), merge_sort_list_solution->begin())); assert(std::equal(builtin_sort_solution.begin(), builtin_sort_solution.end(), merge_sort_vector_solution->begin())); if (n >= 10) { print_bar(); cout << "first 10 words alphabetically:" << endl; for (int i = 0; i < 10; ++i) { cout << builtin_sort_solution[i] << ' '; } cout << endl; } print_bar(); }//end for loop to collect small input n = 2 -> n = 99 small_n_results.close(); //*** Medium values of n = 1000 -> 50 000 ofstream medium_n_results; medium_n_results.open("medium_value_n_results.txt"); //start of loop to generate values for(unsigned long long n = 1000; n < 50000; n+=1000) { assert( n <= all_words->size() ); const StringVector word_vector(all_words->begin(), all_words->begin() + n); assert( word_vector.size() == n ); const StringList word_list(word_vector.begin(), word_vector.end()); assert( word_list.size() == n ); print_bar(); cout << "n=" << n << endl << endl; StringVector selection_sort_solution; bool do_selection_sort = (n <= MAX_SELECTION_SORT_SIZE_MEDIUM); if (!do_selection_sort) { cout << "(n too large for selection sort)" << endl; } else { selection_sort_solution = word_vector; timer.reset(); selection_sort(selection_sort_solution); elapsed = timer.elapsed(); cout << "selection sort elapsed time=" << elapsed << " seconds" << endl; medium_n_results << "sel.sort: " << "\t" << elapsed << "\t"; } timer.reset(); auto merge_sort_list_solution = merge_sort_list(word_list); elapsed = timer.elapsed(); cout << "merge sort list elapsed time=" << elapsed << " seconds" << endl; medium_n_results << "merge sort list: " << "\t" << elapsed << "\t"; timer.reset(); auto merge_sort_vector_solution = merge_sort_vector(word_vector); elapsed = timer.elapsed(); cout << "merge sort vector elapsed time=" << elapsed << " seconds" << endl; medium_n_results << "merge sort vector: " << "\t" << elapsed << "\t"; StringVector builtin_sort_solution = word_vector; timer.reset(); builtin_sort(builtin_sort_solution); elapsed = timer.elapsed(); cout << "builtin sort elapsed time=" << elapsed << " seconds" << endl; medium_n_results << "builtin sort: " << "\t" << elapsed << "\t"; medium_n_results << "\n"; if (do_selection_sort) { assert(std::equal(builtin_sort_solution.begin(), builtin_sort_solution.end(), selection_sort_solution.begin())); } assert(std::equal(builtin_sort_solution.begin(), builtin_sort_solution.end(), merge_sort_list_solution->begin())); assert(std::equal(builtin_sort_solution.begin(), builtin_sort_solution.end(), merge_sort_vector_solution->begin())); if (n >= 10) { print_bar(); cout << "first 10 words alphabetically:" << endl; for (int i = 0; i < 10; ++i) { cout << builtin_sort_solution[i] << ' '; } cout << endl; } print_bar(); }//end for loop to collect medium input n = 1000 -> n = 50 000 medium_n_results.close();//close the file. //*** Larger values of n = 25000 -> 550 000 ofstream large_n_results; large_n_results.open("large_value_n_results.txt"); //start of loop to generate values for(unsigned long long n = 25000; n < 560000; n+=25000) { assert( n <= all_words->size() ); const StringVector word_vector(all_words->begin(), all_words->begin() + n); assert( word_vector.size() == n ); const StringList word_list(word_vector.begin(), word_vector.end()); assert( word_list.size() == n ); print_bar(); cout << "n=" << n << endl << endl; StringVector selection_sort_solution; bool do_selection_sort = (n <= MAX_SELECTION_SORT_SIZE); if (!do_selection_sort) { cout << "(n too large for selection sort)" << endl; } else { selection_sort_solution = word_vector; timer.reset(); selection_sort(selection_sort_solution); elapsed = timer.elapsed(); cout << "selection sort elapsed time=" << elapsed << " seconds" << endl; large_n_results << "sel.sort: " << "\t" << elapsed << "\t"; } timer.reset(); auto merge_sort_list_solution = merge_sort_list(word_list); elapsed = timer.elapsed(); cout << "merge sort list elapsed time=" << elapsed << " seconds" << endl; large_n_results << "merge sort list: " << "\t" << elapsed << "\t"; timer.reset(); auto merge_sort_vector_solution = merge_sort_vector(word_vector); elapsed = timer.elapsed(); cout << "merge sort vector elapsed time=" << elapsed << " seconds" << endl; large_n_results << "merge sort vector: " << "\t" << elapsed << "\t"; StringVector builtin_sort_solution = word_vector; timer.reset(); builtin_sort(builtin_sort_solution); elapsed = timer.elapsed(); cout << "builtin sort elapsed time=" << elapsed << " seconds" << endl; large_n_results << "builtin sort: " << "\t" << elapsed << "\t"; large_n_results << "\n"; if (do_selection_sort) { assert(std::equal(builtin_sort_solution.begin(), builtin_sort_solution.end(), selection_sort_solution.begin())); } assert(std::equal(builtin_sort_solution.begin(), builtin_sort_solution.end(), merge_sort_list_solution->begin())); assert(std::equal(builtin_sort_solution.begin(), builtin_sort_solution.end(), merge_sort_vector_solution->begin())); if (n >= 10) { print_bar(); cout << "first 10 words alphabetically:" << endl; for (int i = 0; i < 10; ++i) { cout << builtin_sort_solution[i] << ' '; } cout << endl; } print_bar(); }//end for loop to collect large input n = 10000 -> n = 550000 large_n_results.close();//close the file. return 0; }
36.332168
84
0.527187
[ "vector" ]
1baffbfaeeaf307ee16051debcae4822af6ecadc
5,007
cpp
C++
src/qoiconv.cpp
wx257osn2/qoixx
ef734e0d21fc34d148e4a24b1b4e5d72a0f26e5d
[ "MIT" ]
3
2022-02-22T16:26:43.000Z
2022-03-29T01:12:25.000Z
src/qoiconv.cpp
wx257osn2/qoixx
ef734e0d21fc34d148e4a24b1b4e5d72a0f26e5d
[ "MIT" ]
1
2022-02-20T15:42:39.000Z
2022-02-20T15:42:39.000Z
src/qoiconv.cpp
wx257osn2/qoixx
ef734e0d21fc34d148e4a24b1b4e5d72a0f26e5d
[ "MIT" ]
null
null
null
#if defined(__GNUC__) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wmissing-field-initializers" #elif defined(_MSC_VER) #define _CRT_SECURE_NO_WARNINGS #pragma warning(push) #pragma warning(disable: 4820 4365 4505) #endif #define STB_IMAGE_IMPLEMENTATION #define STBI_ONLY_PNG #define STBI_NO_LINEAR #include"stb_image.h" #define STB_IMAGE_WRITE_IMPLEMENTATION #include"stb_image_write.h" #if defined(__GNUC__) #pragma GCC diagnostic pop #elif defined(_MSC_VER) #pragma warning(pop) #endif #include"qoixx.hpp" #include<filesystem> #include<vector> #include<cstddef> #include<fstream> #include<iostream> #include<cstdlib> #include<memory> #include<variant> #include<string> #include<string_view> static inline std::vector<std::byte> load_file(const std::filesystem::path& path){ std::vector<std::byte> bytes(std::filesystem::file_size(path)); std::ifstream ifs{path}; ifs.read(reinterpret_cast<char*>(bytes.data()), bytes.size()); return bytes; } static inline void save_file(const std::filesystem::path& path, const std::vector<std::byte>& bytes){ std::ofstream ofs{path}; ofs.write(reinterpret_cast<const char*>(bytes.data()), bytes.size()); } struct stbi_png{ std::unique_ptr<::stbi_uc[], decltype(&::stbi_image_free)> pixels; int width; int height; int channels; }; using image = std::variant<stbi_png, std::pair<std::vector<std::byte>, qoixx::qoi::desc>>; static inline stbi_png read_png(const std::filesystem::path& file_path){ int w, h, c; if(!::stbi_info(file_path.string().c_str(), &w, &h, &c)) throw std::runtime_error("decode_png: Couldn't read header " + file_path.string()); if(c != 3) c = 4; auto loaded = ::stbi_load(file_path.string().c_str(), &w, &h, nullptr, c); if(loaded == nullptr) throw std::runtime_error("decode_png: Couldn't load/decode " + file_path.string()); auto pixels = std::unique_ptr<::stbi_uc[], decltype(&::stbi_image_free)>{loaded, &::stbi_image_free}; return {std::move(pixels), w, h, c}; } static inline std::pair<std::vector<std::byte>, qoixx::qoi::desc> read_qoi(const std::filesystem::path& file_path){ const auto qoi = load_file(file_path); return qoixx::qoi::decode<std::vector<std::byte>>(qoi); } template<typename... Fs> struct overloaded : Fs...{ using Fs::operator()...; }; template<typename... Fs> overloaded(Fs...) -> overloaded<Fs...>; static inline void write_png(const std::filesystem::path& file_path, const image& image){ auto [ptr, w, h, c] = std::visit(overloaded( [](const stbi_png& image){ return std::make_tuple(reinterpret_cast<const void*>(image.pixels.get()), image.width, image.height, image.channels); }, [](const std::pair<std::vector<std::byte>, qoixx::qoi::desc>& image){ return std::make_tuple( reinterpret_cast<const void*>(image.first.data()), static_cast<int>(image.second.width), static_cast<int>(image.second.height), static_cast<int>(image.second.channels) ); } ), image); if(!::stbi_write_png(file_path.string().c_str(), w, h, c, ptr, 0)) throw std::runtime_error("write_png: Couldn't write/encode " + file_path.string()); } static inline void write_qoi(const std::filesystem::path& file_path, const image& image){ auto [ptr, size, desc] = std::visit(overloaded( [](const stbi_png& image){ return std::make_tuple( reinterpret_cast<const std::byte*>(image.pixels.get()), static_cast<std::size_t>(image.width) * image.height * image.channels, qoixx::qoi::desc{ .width = static_cast<std::uint32_t>(image.width), .height = static_cast<std::uint32_t>(image.height), .channels = static_cast<std::uint8_t>(image.channels), .colorspace = qoixx::qoi::colorspace::srgb } ); }, [](const std::pair<std::vector<std::byte>, qoixx::qoi::desc>& image){ return std::make_tuple(image.first.data(), image.first.size(), image.second); } ), image); const auto encoded = qoixx::qoi::encode<std::vector<std::byte>>(ptr, size, desc); save_file(file_path, encoded); } int main(int argc, char **argv)try{ if(argc < 3){ std::cout << "Usage: " << argv[0] << " <infile> <outfile>\n" "Examples:\n" " " << argv[0] << " input.png output.qoi\n" " " << argv[0] << " input.qoi output.png" << std::endl; return EXIT_FAILURE; } const std::string_view in{argv[1]}, out{argv[2]}; const auto im = [&in]()->image{ if(in.ends_with(".png")) return read_png(in); else if(in.ends_with(".qoi")) return read_qoi(in); else throw std::runtime_error("infile " + std::string{in} + " is not png/qoi file"); }(); if(out.ends_with(".png")) write_png(out, im); else if(out.ends_with(".qoi")) write_qoi(out, im); else throw std::runtime_error("outfile " + std::string{out} + " is not png/qoi file name"); }catch(std::exception& e){ std::cerr << e.what() << std::endl; return EXIT_FAILURE; }
33.15894
123
0.660875
[ "vector" ]
1bbdd28f2cc658105b09cd8fba8059b15974e33e
11,955
cc
C++
src/modular/bin/sessionmgr/puppet_master/story_puppet_master_impl.cc
opensource-assist/fuschia
66646c55b3d0b36aae90a4b6706b87f1a6261935
[ "BSD-3-Clause" ]
3
2020-08-02T04:46:18.000Z
2020-08-07T10:10:53.000Z
src/modular/bin/sessionmgr/puppet_master/story_puppet_master_impl.cc
opensource-assist/fuschia
66646c55b3d0b36aae90a4b6706b87f1a6261935
[ "BSD-3-Clause" ]
null
null
null
src/modular/bin/sessionmgr/puppet_master/story_puppet_master_impl.cc
opensource-assist/fuschia
66646c55b3d0b36aae90a4b6706b87f1a6261935
[ "BSD-3-Clause" ]
1
2020-08-07T10:11:49.000Z
2020-08-07T10:11:49.000Z
// Copyright 2018 The Fuchsia 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/modular/bin/sessionmgr/puppet_master/story_puppet_master_impl.h" #include <utility> #include "src/lib/fsl/types/type_converters.h" #include "src/lib/fxl/logging.h" #include "src/modular/bin/sessionmgr/annotations.h" #include "src/modular/bin/sessionmgr/puppet_master/story_command_executor.h" #include "src/modular/bin/sessionmgr/storage/session_storage.h" namespace modular { namespace { class ExecuteOperation : public Operation<fuchsia::modular::ExecuteResult> { public: ExecuteOperation(SessionStorage* const session_storage, StoryCommandExecutor* const executor, std::string story_name, std::vector<fuchsia::modular::StoryCommand> commands, ResultCall done) : Operation("StoryPuppetMasterImpl.ExecuteOperation", std::move(done)), session_storage_(session_storage), executor_(executor), story_name_(std::move(story_name)), commands_(std::move(commands)) {} private: void Run() override { session_storage_->GetStoryData(story_name_) ->WeakThen(GetWeakPtr(), [this](fuchsia::modular::internal::StoryDataPtr data) { if (data) { story_id_ = data->story_info().id(); ExecuteCommands(); return; } CreateStory(); }); } void CreateStory() { session_storage_->CreateStory(story_name_, /*annotations=*/{}) ->WeakThen(GetWeakPtr(), [this](fidl::StringPtr story_id, auto /* ignored */) { story_id_ = std::move(story_id); ExecuteCommands(); }); } void ExecuteCommands() { executor_->ExecuteCommands( story_id_, std::move(commands_), [weak_ptr = GetWeakPtr(), this](fuchsia::modular::ExecuteResult result) { Done(std::move(result)); }); } SessionStorage* const session_storage_; StoryCommandExecutor* const executor_; std::string story_name_; std::vector<fuchsia::modular::StoryCommand> commands_; fidl::StringPtr story_id_; }; class AnnotateOperation : public Operation<fuchsia::modular::StoryPuppetMaster_Annotate_Result> { public: AnnotateOperation(SessionStorage* const session_storage, std::string story_name, std::vector<fuchsia::modular::Annotation> annotations, ResultCall done) : Operation("StoryPuppetMasterImpl.AnnotateOperation", std::move(done)), session_storage_(session_storage), story_name_(std::move(story_name)), annotations_(std::move(annotations)) {} private: void Run() override { for (auto const& annotation : annotations_) { if (annotation.value && annotation.value->is_buffer() && annotation.value->buffer().size > fuchsia::modular::MAX_ANNOTATION_VALUE_BUFFER_LENGTH_BYTES) { fuchsia::modular::StoryPuppetMaster_Annotate_Result result{}; result.set_err(fuchsia::modular::AnnotationError::VALUE_TOO_BIG); Done(std::move(result)); return; } } session_storage_->GetStoryData(story_name_) ->WeakThen(GetWeakPtr(), [this](fuchsia::modular::internal::StoryDataPtr data) { if (data) { Annotate(std::move(data)); } else { CreateStory(); } }); } void CreateStory() { if (annotations_.size() > fuchsia::modular::MAX_ANNOTATIONS_PER_STORY) { fuchsia::modular::StoryPuppetMaster_Annotate_Result result{}; result.set_err(fuchsia::modular::AnnotationError::TOO_MANY_ANNOTATIONS); Done(std::move(result)); return; } session_storage_->CreateStory(story_name_, std::move(annotations_)) ->WeakThen(GetWeakPtr(), [this](fidl::StringPtr story_id, auto /* ignored */) { fuchsia::modular::StoryPuppetMaster_Annotate_Result result{}; result.set_response({}); Done(std::move(result)); }); } void Annotate(fuchsia::modular::internal::StoryDataPtr story_data) { // Merge the annotations provided to the operation into any existing ones in `story_data`. auto new_annotations = story_data->story_info().has_annotations() ? annotations::Merge( std::move(*story_data->mutable_story_info()->mutable_annotations()), std::move(annotations_)) : std::move(annotations_); if (new_annotations.size() > fuchsia::modular::MAX_ANNOTATIONS_PER_STORY) { fuchsia::modular::StoryPuppetMaster_Annotate_Result result{}; result.set_err(fuchsia::modular::AnnotationError::TOO_MANY_ANNOTATIONS); Done(std::move(result)); return; } session_storage_->UpdateStoryAnnotations(story_name_, std::move(new_annotations)) ->WeakThen(GetWeakPtr(), [this]() { fuchsia::modular::StoryPuppetMaster_Annotate_Result result{}; result.set_response({}); Done(std::move(result)); }); } SessionStorage* const session_storage_; std::string story_name_; std::vector<fuchsia::modular::Annotation> annotations_; }; class AnnotateModuleOperation : public Operation<fuchsia::modular::StoryPuppetMaster_AnnotateModule_Result> { public: AnnotateModuleOperation(SessionStorage* const session_storage, std::string story_name, std::string module_id, std::vector<fuchsia::modular::Annotation> annotations, ResultCall done) : Operation("StoryPuppetMasterImpl.AnnotateModuleOperation", std::move(done)), session_storage_(session_storage), story_name_(std::move(story_name)), module_id_(std::move(module_id)), annotations_(std::move(annotations)) {} private: void Run() override { for (auto const& annotation : annotations_) { if (annotation.value && annotation.value->is_buffer() && annotation.value->buffer().size > fuchsia::modular::MAX_ANNOTATION_VALUE_BUFFER_LENGTH_BYTES) { fuchsia::modular::StoryPuppetMaster_AnnotateModule_Result result{}; result.set_err(fuchsia::modular::AnnotationError::VALUE_TOO_BIG); Done(std::move(result)); return; } } session_storage_->GetStoryStorage(story_name_) ->WeakAsyncMap( GetWeakPtr(), [this](std::unique_ptr<StoryStorage> story_storage) { if (story_storage == nullptr) { // Since Modules are created by an external component, and the external component // would only be able to add a Module to a Story that it managed, it isn't possible // for AnnotateModule() to create it's own StoryStorage, if not found. So this is // an error. fuchsia::modular::StoryPuppetMaster_AnnotateModule_Result result{}; result.set_err(fuchsia::modular::AnnotationError::NOT_FOUND); Done(std::move(result)); return static_cast<FuturePtr<fuchsia::modular::ModuleDataPtr>>(nullptr); } story_storage_ = std::move(story_storage); // Add a callback on module_data updates before attempting ReadModuleData, // then try to ReadModuleData(), if it exists in |StoryStorage|. // If the module_data is not found, the callback will be called if and // when the ModuleData is stored, later. story_storage_->set_on_module_data_updated( [&](fuchsia::modular::ModuleData new_module_data) { if (new_module_data.module_path().back() == module_id_) { AnnotateModuleIfFirstAttempt(std::make_unique<fuchsia::modular::ModuleData>( std::move(new_module_data))); } }); return story_storage_->ReadModuleData({module_id_}) ->WeakMap(GetWeakPtr(), [](fuchsia::modular::ModuleDataPtr module_data) mutable { return module_data; }); }) ->WeakThen(GetWeakPtr(), [this](fuchsia::modular::ModuleDataPtr module_data) mutable { if (module_data != nullptr) { AnnotateModuleIfFirstAttempt(std::move(module_data)); } }); } void AnnotateModuleIfFirstAttempt(fuchsia::modular::ModuleDataPtr module_data) { if (attempted) return; attempted = true; // Merge the annotations provided to the operation into any existing ones in `module_data`. auto new_annotations = module_data->has_annotations() ? annotations::Merge(std::move(*module_data->mutable_annotations()), std::move(annotations_)) : std::move(annotations_); if (new_annotations.size() > fuchsia::modular::MAX_ANNOTATIONS_PER_MODULE) { fuchsia::modular::StoryPuppetMaster_AnnotateModule_Result result{}; result.set_err(fuchsia::modular::AnnotationError::TOO_MANY_ANNOTATIONS); Done(std::move(result)); return; } // Save the new version of module_data with annotations added. module_data->set_annotations(std::move(new_annotations)); story_storage_->WriteModuleData(std::move(*module_data))->Then([this]() mutable { fuchsia::modular::StoryPuppetMaster_AnnotateModule_Result result{}; result.set_response({}); Done(std::move(result)); }); } SessionStorage* const session_storage_; std::unique_ptr<StoryStorage> story_storage_; std::string story_name_; std::string module_id_; std::vector<fuchsia::modular::Annotation> annotations_; bool attempted = false; }; } // namespace StoryPuppetMasterImpl::StoryPuppetMasterImpl(std::string story_name, OperationContainer* const operations, SessionStorage* const session_storage, StoryCommandExecutor* const executor) : story_name_(std::move(story_name)), session_storage_(session_storage), executor_(executor), operations_(operations), weak_ptr_factory_(this) { FXL_DCHECK(session_storage != nullptr); FXL_DCHECK(executor != nullptr); } StoryPuppetMasterImpl::~StoryPuppetMasterImpl() = default; void StoryPuppetMasterImpl::Enqueue(std::vector<fuchsia::modular::StoryCommand> commands) { enqueued_commands_.insert(enqueued_commands_.end(), make_move_iterator(commands.begin()), make_move_iterator(commands.end())); } void StoryPuppetMasterImpl::Execute(ExecuteCallback done) { operations_->Add(std::make_unique<ExecuteOperation>( session_storage_, executor_, story_name_, std::move(enqueued_commands_), std::move(done))); } void StoryPuppetMasterImpl::SetStoryInfoExtra( std::vector<fuchsia::modular::StoryInfoExtraEntry> story_info_extra, SetStoryInfoExtraCallback callback) { // This method is a no-op. fuchsia::modular::StoryPuppetMaster_SetStoryInfoExtra_Result result{}; result.set_response({}); callback(std::move(result)); } void StoryPuppetMasterImpl::Annotate(std::vector<fuchsia::modular::Annotation> annotations, AnnotateCallback callback) { operations_->Add(std::make_unique<AnnotateOperation>( session_storage_, story_name_, std::move(annotations), std::move(callback))); } void StoryPuppetMasterImpl::AnnotateModule(std::string module_id, std::vector<fuchsia::modular::Annotation> annotations, AnnotateModuleCallback callback) { operations_->Add(std::make_unique<AnnotateModuleOperation>( session_storage_, story_name_, module_id, std::move(annotations), std::move(callback))); } } // namespace modular
40.941781
99
0.654203
[ "vector" ]
1bbe310194f76ce2abd3c47a0fa0e18b97eff31b
920
hpp
C++
include/pacman/GhostModeTimer.hpp
197708156EQUJ5/pacman
8cfc42feaf741c33e65bbf36c7e9888ef625d1fc
[ "MIT" ]
1
2021-10-31T18:23:06.000Z
2021-10-31T18:23:06.000Z
include/pacman/GhostModeTimer.hpp
197708156EQUJ5/pacman
8cfc42feaf741c33e65bbf36c7e9888ef625d1fc
[ "MIT" ]
10
2020-12-14T22:04:27.000Z
2020-12-17T22:50:32.000Z
include/pacman/GhostModeTimer.hpp
197708156EQUJ5/pacman
8cfc42feaf741c33e65bbf36c7e9888ef625d1fc
[ "MIT" ]
null
null
null
#pragma once #include "pacman/GhostMode.hpp" #include <atomic> #include <chrono> #include <cstdint> #include <functional> #include <utility> #include <vector> namespace pacman { class GhostModeTimer { public: GhostModeTimer(std::vector<std::pair<int, GhostMode>> transitionDelays, std::function<void(GhostMode)> transitionGhostMode); ~GhostModeTimer(); void run(); void startTimer(); void pause(); void reset(); void stop(); private: std::atomic<bool> isRunning; std::atomic<bool> isTimerRunning; std::chrono::steady_clock::time_point startTime; std::chrono::steady_clock::time_point pauseStartTime; std::chrono::steady_clock::time_point pauseEndTime; std::chrono::seconds transitionDelay; std::function<void(GhostMode)> transitionGhostMode; std::vector<std::pair<int, GhostMode>> transitionDelays; int transitionIndex; }; } // namespace pacman
20.909091
128
0.713043
[ "vector" ]
1bc110bacc669674c1aabda282051934a25355d6
3,562
cxx
C++
src/io/UringOpenStat.cxx
CM4all/beng-proxy
ce5a81f7969bc5cb6c5985cdc98f61ef8b5c6159
[ "BSD-2-Clause" ]
35
2017-08-16T06:52:26.000Z
2022-03-27T21:49:01.000Z
src/io/UringOpenStat.cxx
nn6n/beng-proxy
2cf351da656de6fbace3048ee90a8a6a72f6165c
[ "BSD-2-Clause" ]
2
2017-12-22T15:34:23.000Z
2022-03-08T04:15:23.000Z
src/io/UringOpenStat.cxx
nn6n/beng-proxy
2cf351da656de6fbace3048ee90a8a6a72f6165c
[ "BSD-2-Clause" ]
8
2017-12-22T15:11:47.000Z
2022-03-15T22:54:04.000Z
/* * Copyright 2007-2021 CM4all GmbH * All rights reserved. * * author: Max Kellermann <mk@cm4all.com> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * FOUNDATION 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 "UringOpenStat.hxx" #include "io/uring/OpenStat.hxx" #include "io/uring/Handler.hxx" #include "util/Cancellable.hxx" #include "AllocatorPtr.hxx" #include <memory> #include <fcntl.h> class UringOpenStatOperation final : Cancellable, Uring::OpenStatHandler { std::unique_ptr<Uring::OpenStat> open_stat; Uring::OpenStatHandler &handler; public: UringOpenStatOperation(Uring::Queue &uring, FileDescriptor directory, const char *path, Uring::OpenStatHandler &_handler, CancellablePointer &cancel_ptr) noexcept :open_stat(new Uring::OpenStat(uring, *this)), handler(_handler) { cancel_ptr = *this; if (directory.IsDefined() && directory != FileDescriptor(AT_FDCWD)) open_stat->StartOpenStatReadOnlyBeneath(directory, path); else open_stat->StartOpenStatReadOnly(directory, path); } private: void Destroy() noexcept { this->~UringOpenStatOperation(); } /* virtual methods from class Cancellable */ void Cancel() noexcept override { /* keep the Uring::OpenStat allocated until the kernel finishes the operation, or else the kernel may overwrite the memory when something else occupies it; also, the canceled object will take care for closing the new file descriptor */ open_stat->Cancel(); open_stat.release(); Destroy(); } /* virtual methods from class Uring::OpenStatHandler */ void OnOpenStat(UniqueFileDescriptor fd, struct statx &st) noexcept override { auto &_handler = handler; /* delay destruction, because this object owns the memory pointed to by "st" */ const auto operation = std::move(open_stat); Destroy(); _handler.OnOpenStat(std::move(fd), st); } void OnOpenStatError(std::exception_ptr e) noexcept override { auto &_handler = handler; Destroy(); _handler.OnOpenStatError(std::move(e)); } }; void UringOpenStat(Uring::Queue &uring, AllocatorPtr alloc, FileDescriptor directory, const char *path, Uring::OpenStatHandler &handler, CancellablePointer &cancel_ptr) noexcept { alloc.New<UringOpenStatOperation>(uring, directory, path, handler, cancel_ptr); }
31.522124
74
0.735542
[ "object" ]
1bc66474d0dce92dda6bdc09297da855b4558711
1,555
cpp
C++
three/extras/geometries/impl/octahedron_geometries.cpp
Graphics-Physics-Libraries/three-cpp-works-imported
9df305135187c5db9247a44537290e181350e26c
[ "MIT" ]
4
2016-08-09T21:56:43.000Z
2020-10-16T16:39:53.000Z
three/extras/geometries/impl/octahedron_geometries.cpp
Graphics-Physics-Libraries/three-cpp-works-imported
9df305135187c5db9247a44537290e181350e26c
[ "MIT" ]
null
null
null
three/extras/geometries/impl/octahedron_geometries.cpp
Graphics-Physics-Libraries/three-cpp-works-imported
9df305135187c5db9247a44537290e181350e26c
[ "MIT" ]
1
2019-09-07T06:45:35.000Z
2019-09-07T06:45:35.000Z
#ifndef THREE_EXTRA_OCTAHEDRON_GEOMETRY_CPP #define THREE_EXTRA_OCTAHEDRON_GEOMETRY_CPP #include <three/core/geometry.h> #include <three/extras/geometries/octahedron_geometry.h> #include <three/extras/geometries/polyhedron_geometry.h> #include <three/utils/conversion.h> namespace three { OctahedronGeometry::Ptr OctahedronGeometry::create( float radius, int detail ) { return make_shared<OctahedronGeometry>( radius, detail ); } OctahedronGeometry::OctahedronGeometry( float radius, int detail ) : PolyhedronGeometry( radius, detail ) { // wtb vs2012 initializer list initialization :-( std::vector<std::array<float, 3>> vertices; vertices.push_back( toArray<float>( 1, 0, 0 ) ); vertices.push_back( toArray<float>( -1, 0, 0 ) ); vertices.push_back( toArray<float>( 0, 1, 0 ) ); vertices.push_back( toArray<float>( 0, -1, 0 ) ); vertices.push_back( toArray<float>( 0, 0, 1 ) ); vertices.push_back( toArray<float>( 0, 0, -1 ) ); std::vector<std::array<float, 3>> faces; faces.push_back( toArray<float>( 0, 2, 4 ) ); faces.push_back( toArray<float>( 0, 4, 3 ) ); faces.push_back( toArray<float>( 0, 3, 5 ) ); faces.push_back( toArray<float>( 0, 5, 2 ) ); faces.push_back( toArray<float>( 1, 2, 5 ) ); faces.push_back( toArray<float>( 1, 5, 3 ) ); faces.push_back( toArray<float>( 1, 3, 4 ) ); faces.push_back( toArray<float>( 1, 4, 2 ) ); this->initialize( std::move( vertices ), std::move( faces ), radius, detail ); } } // end namespace three #endif // THREE_EXTRA_OCTAHEDRON_GEOMETRY_CPP
34.555556
80
0.690675
[ "geometry", "vector" ]
1bc99efc6a17815eca41d717c34dab6948f8488b
26,050
cc
C++
garnet/lib/system_monitor/dockyard/dockyard.cc
bootingman/fuchsia2
04012f0aa1edd1d4108a2ac647a65e59730fc4c2
[ "BSD-3-Clause" ]
1
2019-10-09T10:50:57.000Z
2019-10-09T10:50:57.000Z
garnet/lib/system_monitor/dockyard/dockyard.cc
bootingman/fuchsia2
04012f0aa1edd1d4108a2ac647a65e59730fc4c2
[ "BSD-3-Clause" ]
null
null
null
garnet/lib/system_monitor/dockyard/dockyard.cc
bootingman/fuchsia2
04012f0aa1edd1d4108a2ac647a65e59730fc4c2
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2018 The Fuchsia 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 "garnet/lib/system_monitor/dockyard/dockyard.h" #include <grpc++/grpc++.h> #include <chrono> #include <iostream> #include <memory> #include <string> #include "garnet/lib/system_monitor/protos/dockyard.grpc.pb.h" #include "src/lib/fxl/logging.h" namespace dockyard { namespace { // This is an arbitrary default port. constexpr char DEFAULT_SERVER_ADDRESS[] = "0.0.0.0:50051"; // To calculate the slope, a range of time is needed. |prior_time| and |time| // define that range. The very first |prior_time| is one stride prior to the // requested start time. SampleValue calculate_slope(SampleValue value, SampleValue* prior_value, SampleTimeNs time, SampleTimeNs* prior_time) { if (value < *prior_value) { // A lower value will produce a negative slope, which is not currently // supported. As a workaround the value is pulled up to |prior_value| to // create a convex surface. value = *prior_value; } assert(time >= *prior_time); SampleValue delta_value = value - *prior_value; SampleTimeNs delta_time = time - *prior_time; SampleValue result = delta_time ? delta_value * SLOPE_LIMIT / delta_time : 0ULL; *prior_value = value; *prior_time = time; return result; } // Logic and data behind the server's behavior. class DockyardServiceImpl final : public dockyard_proto::Dockyard::Service { public: void SetDockyard(Dockyard* dockyard) { dockyard_ = dockyard; } private: Dockyard* dockyard_; grpc::Status Init(grpc::ServerContext* context, const dockyard_proto::InitRequest* request, dockyard_proto::InitReply* reply) override { auto now = std::chrono::system_clock::now(); auto nanoseconds = std::chrono::duration_cast<std::chrono::nanoseconds>( now.time_since_epoch()) .count(); dockyard_->SetDeviceTimeDeltaNs(nanoseconds - request->device_time_ns()); if (request->version() != DOCKYARD_VERSION) { return grpc::Status::CANCELLED; } reply->set_version(DOCKYARD_VERSION); dockyard_->OnConnection(); return grpc::Status::OK; } grpc::Status SendInspectJson( grpc::ServerContext* context, grpc::ServerReaderWriter<dockyard_proto::EmptyMessage, dockyard_proto::InspectJson>* stream) override { dockyard_proto::InspectJson inspect; while (stream->Read(&inspect)) { FXL_LOG(INFO) << "Received inspect at " << inspect.time() << ", key " << inspect.dockyard_id() << ": " << inspect.json(); // TODO(smbug.com/43): interpret the data. } return grpc::Status::OK; } // This is the handler for the client sending a `SendSample` message. A better // name would be `ReceiveSample` but then it wouldn't match the message // name. grpc::Status SendSample( grpc::ServerContext* context, grpc::ServerReaderWriter<dockyard_proto::EmptyMessage, dockyard_proto::RawSample>* stream) override { dockyard_proto::RawSample sample; while (stream->Read(&sample)) { FXL_LOG(INFO) << "Received sample at " << sample.time() << ", key " << sample.sample().key() << ": " << sample.sample().value(); dockyard_->AddSample(sample.sample().key(), Sample(sample.time(), sample.sample().value())); } return grpc::Status::OK; } // Handler for the Harvester calling `SendSamples()`. grpc::Status SendSamples( grpc::ServerContext* context, grpc::ServerReaderWriter<dockyard_proto::EmptyMessage, dockyard_proto::RawSamples>* stream) override { dockyard_proto::RawSamples samples; while (stream->Read(&samples)) { int limit = samples.sample_size(); for (int i = 0; i < limit; ++i) { auto sample = samples.sample(i); dockyard_->AddSample(sample.key(), Sample(samples.time(), sample.value())); } } return grpc::Status::OK; } grpc::Status GetDockyardIdsForPaths( grpc::ServerContext* context, const dockyard_proto::DockyardPaths* request, dockyard_proto::DockyardIds* reply) override { for (int i = 0; i < request->path_size(); ++i) { DockyardId id = dockyard_->GetDockyardId(request->path(i)); reply->add_id(id); #ifdef VERBOSE_OUTPUT FXL_LOG(INFO) << "Received DockyardIds " << ": " << request->path(i) << ", id " << id; #endif // VERBOSE_OUTPUT } return grpc::Status::OK; } }; // Listen for Harvester connections from the Fuchsia device. void RunGrpcServer(const char* listen_at, Dockyard* dockyard) { std::string server_address(listen_at); DockyardServiceImpl service; service.SetDockyard(dockyard); grpc::ServerBuilder builder; // Listen on the given address without any authentication mechanism. builder.AddListeningPort(server_address, grpc::InsecureServerCredentials()); // Register "service" as the instance through which we'll communicate with // clients. In this case it corresponds to a *synchronous* service. builder.RegisterService(&service); // Finally assemble the server. std::unique_ptr<grpc::Server> server(builder.BuildAndStart()); FXL_LOG(INFO) << "Server listening on " << server_address; // Wait for the server to shutdown. Note that some other thread must be // responsible for shutting down the server for this call to ever return. server->Wait(); } // Calculates the (edge) time for each column of the result data. SampleTimeNs CalcTimeForStride(const StreamSetsRequest& request, ssize_t index) { // These need to be signed to support a signed |index|. int64_t delta = (request.end_time_ns - request.start_time_ns); int64_t count = int64_t(request.sample_count); return request.start_time_ns + (delta * index / count); } } // namespace bool StreamSetsRequest::HasFlag(StreamSetsRequestFlags flag) const { return (flags & flag) != 0; } std::ostream& operator<<(std::ostream& out, const StreamSetsRequest& request) { out << "StreamSetsRequest {" << std::endl; out << " request_id: " << request.request_id << std::endl; out << " start_time_ns: " << request.start_time_ns << std::endl; out << " end_time_ns: " << request.end_time_ns << std::endl; out << " delta time in seconds: " << double(request.end_time_ns - request.start_time_ns) / kNanosecondsPerSecond << std::endl; out << " sample_count: " << request.sample_count << std::endl; out << " min: " << request.min; out << " max: " << request.max; out << " reserved: " << request.reserved << std::endl; out << " render_style: " << request.render_style; out << " flags: " << request.flags << std::endl; out << " ids (" << request.dockyard_ids.size() << "): ["; for (auto iter = request.dockyard_ids.begin(); iter != request.dockyard_ids.end(); ++iter) { out << " " << *iter; } out << " ]" << std::endl; out << "}" << std::endl; return out; } std::ostream& operator<<(std::ostream& out, const StreamSetsResponse& response) { out << "StreamSetsResponse {" << std::endl; out << " request_id: " << response.request_id << std::endl; out << " lowest_value: " << response.lowest_value << std::endl; out << " highest_value: " << response.highest_value << std::endl; out << " data_sets (" << response.data_sets.size() << "): ["; for (auto list = response.data_sets.begin(); list != response.data_sets.end(); ++list) { out << " data_set: {"; for (auto data = list->begin(); data != list->end(); ++data) { if (*data == NO_DATA) { out << " NO_DATA"; } else { out << " " << *data; } } out << " }, " << std::endl; } out << "]" << std::endl; out << "}" << std::endl; return out; } Dockyard::Dockyard() : device_time_delta_ns_(0ULL), latest_sample_time_ns_(0ULL), on_connection_handler_(nullptr), on_paths_handler_(nullptr), on_stream_sets_handler_(nullptr), next_context_id_(0ULL) {} Dockyard::~Dockyard() { std::lock_guard<std::mutex> guard(mutex_); #ifdef VERBOSE_OUTPUT FXL_LOG(INFO) << "Stopping dockyard server"; #endif // VERBOSE_OUTPUT if (server_thread_.joinable()) { server_thread_.join(); } for (SampleStreamMap::iterator i = sample_streams_.begin(); i != sample_streams_.end(); ++i) { delete i->second; } } SampleTimeNs Dockyard::DeviceDeltaTimeNs() const { return device_time_delta_ns_; } void Dockyard::SetDeviceTimeDeltaNs(SampleTimeNs delta_ns) { device_time_delta_ns_ = delta_ns; } SampleTimeNs Dockyard::LatestSampleTimeNs() const { return latest_sample_time_ns_; } void Dockyard::AddSample(DockyardId dockyard_id, Sample sample) { std::lock_guard<std::mutex> guard(mutex_); // Find or create a sample_stream for this dockyard_id. SampleStream* sample_stream; auto search = sample_streams_.find(dockyard_id); if (search == sample_streams_.end()) { sample_stream = new SampleStream(); sample_streams_.emplace(dockyard_id, sample_stream); } else { sample_stream = search->second; } latest_sample_time_ns_ = sample.time; sample_stream->emplace(sample.time, sample.value); // Track the overall lowest and highest values encountered. sample_stream_low_high_.try_emplace(dockyard_id, std::make_pair(SAMPLE_MAX_VALUE, 0ULL)); auto low_high = sample_stream_low_high_.find(dockyard_id); SampleValue lowest = low_high->second.first; SampleValue highest = low_high->second.second; bool change = false; if (lowest > sample.value) { lowest = sample.value; change = true; } if (highest < sample.value) { highest = sample.value; change = true; } if (change) { sample_stream_low_high_[dockyard_id] = std::make_pair(lowest, highest); } } void Dockyard::AddSamples(DockyardId dockyard_id, std::vector<Sample> samples) { std::lock_guard<std::mutex> guard(mutex_); // Find or create a sample_stream for this dockyard_id. SampleStream* sample_stream; auto search = sample_streams_.find(dockyard_id); if (search == sample_streams_.end()) { sample_stream = new SampleStream(); sample_streams_.emplace(dockyard_id, sample_stream); } else { sample_stream = search->second; } // Track the overall lowest and highest values encountered. sample_stream_low_high_.try_emplace(dockyard_id, std::make_pair(SAMPLE_MAX_VALUE, 0ULL)); auto low_high = sample_stream_low_high_.find(dockyard_id); SampleValue lowest = low_high->second.first; SampleValue highest = low_high->second.second; for (auto i = samples.begin(); i != samples.end(); ++i) { if (lowest > i->value) { lowest = i->value; } if (highest < i->value) { highest = i->value; } sample_stream->emplace(i->time, i->value); } sample_stream_low_high_[dockyard_id] = std::make_pair(lowest, highest); } DockyardId Dockyard::GetDockyardId(const std::string& dockyard_path) { std::lock_guard<std::mutex> guard(mutex_); auto search = dockyard_path_to_id_.find(dockyard_path); if (search != dockyard_path_to_id_.end()) { return search->second; } DockyardId id = dockyard_path_to_id_.size(); dockyard_path_to_id_.emplace(dockyard_path, id); dockyard_id_to_path_.emplace(id, dockyard_path); #ifdef VERBOSE_OUTPUT FXL_LOG(INFO) << "Path " << dockyard_path << ": ID " << id; #endif // VERBOSE_OUTPUT assert(dockyard_path_to_id_.find(dockyard_path) != dockyard_path_to_id_.end()); return id; } bool Dockyard::GetDockyardPath(DockyardId dockyard_id, std::string* dockyard_path) const { std::lock_guard<std::mutex> guard(mutex_); auto search = dockyard_id_to_path_.find(dockyard_id); if (search != dockyard_id_to_path_.end()) { *dockyard_path = search->second; return true; } return false; } uint64_t Dockyard::GetStreamSets(StreamSetsRequest* request) { std::lock_guard<std::mutex> guard(mutex_); request->request_id = next_context_id_; pending_requests_.push_back(request); ++next_context_id_; return request->request_id; } void Dockyard::OnConnection() { if (on_connection_handler_ != nullptr) { on_connection_handler_(""); } } void Dockyard::StartCollectingFrom(const std::string& device) { Initialize(); FXL_LOG(INFO) << "Starting collecting from " << device; // TODO(smbug.com/39): Connect to the device and start the harvester. } void Dockyard::StopCollectingFrom(const std::string& device) { FXL_LOG(INFO) << "Stop collecting from " << device; // TODO(smbug.com/40): Stop the harvester. } bool Dockyard::Initialize() { if (server_thread_.joinable()) { return true; } FXL_LOG(INFO) << "Starting dockyard server"; server_thread_ = std::thread([this] { RunGrpcServer(DEFAULT_SERVER_ADDRESS, this); }); return server_thread_.joinable(); } OnConnectionCallback Dockyard::SetConnectionHandler( OnConnectionCallback callback) { assert(!server_thread_.joinable()); auto old_handler = on_connection_handler_; on_connection_handler_ = callback; return old_handler; } OnPathsCallback Dockyard::SetDockyardPathsHandler(OnPathsCallback callback) { assert(!server_thread_.joinable()); auto old_handler = on_paths_handler_; on_paths_handler_ = callback; return old_handler; } OnStreamSetsCallback Dockyard::SetStreamSetsHandler( OnStreamSetsCallback callback) { auto old_handler = on_stream_sets_handler_; on_stream_sets_handler_ = callback; return old_handler; } void Dockyard::ProcessSingleRequest(const StreamSetsRequest& request, StreamSetsResponse* response) const { std::lock_guard<std::mutex> guard(mutex_); FXL_LOG(INFO) << "ProcessSingleRequest request " << request; response->request_id = request.request_id; for (auto dockyard_id = request.dockyard_ids.begin(); dockyard_id != request.dockyard_ids.end(); ++dockyard_id) { std::vector<SampleValue> samples; auto search = sample_streams_.find(*dockyard_id); if (search == sample_streams_.end()) { samples.push_back(NO_STREAM); } else { auto sample_stream = *search->second; switch (request.render_style) { case StreamSetsRequest::SCULPTING: ComputeSculpted(*dockyard_id, sample_stream, request, &samples); break; case StreamSetsRequest::WIDE_SMOOTHING: ComputeSmoothed(*dockyard_id, sample_stream, request, &samples); break; case StreamSetsRequest::LOWEST_PER_COLUMN: ComputeLowestPerColumn(*dockyard_id, sample_stream, request, &samples); break; case StreamSetsRequest::HIGHEST_PER_COLUMN: ComputeHighestPerColumn(*dockyard_id, sample_stream, request, &samples); break; case StreamSetsRequest::AVERAGE_PER_COLUMN: ComputeAveragePerColumn(*dockyard_id, sample_stream, request, &samples); break; default: break; } if (request.HasFlag(StreamSetsRequest::NORMALIZE)) { NormalizeResponse(*dockyard_id, sample_stream, request, &samples); } } response->data_sets.push_back(samples); } ComputeLowestHighestForRequest(request, response); } void Dockyard::ComputeAveragePerColumn( DockyardId dockyard_id, const SampleStream& sample_stream, const StreamSetsRequest& request, std::vector<SampleValue>* samples) const { // To calculate the slope, a range of time is needed. |prior_time| and // |start_time| define that range. The very first |prior_time| is one stride // prior to the requested start time. SampleTimeNs prior_time = CalcTimeForStride(request, -1); SampleValue prior_value = 0ULL; const int64_t limit = request.sample_count; for (int64_t sample_n = -1; sample_n < limit; ++sample_n) { SampleTimeNs start_time = CalcTimeForStride(request, sample_n); SampleTimeNs end_time = CalcTimeForStride(request, sample_n + 1); auto begin = sample_stream.lower_bound(start_time); if (begin == sample_stream.end()) { if (sample_n >= 0) { samples->push_back(NO_DATA); } continue; } auto end = sample_stream.lower_bound(end_time); SampleValue accumulator = 0ULL; uint_fast32_t count = 0ULL; for (auto i = begin; i != end; ++i) { accumulator += i->second; ++count; } SampleValue result = NO_DATA; if (count) { if (request.HasFlag(StreamSetsRequest::SLOPE)) { result = calculate_slope(accumulator / count, &prior_value, start_time, &prior_time); } else { result = accumulator / count; } } if (sample_n >= 0) { samples->push_back(result); } } } void Dockyard::ComputeHighestPerColumn( DockyardId dockyard_id, const SampleStream& sample_stream, const StreamSetsRequest& request, std::vector<SampleValue>* samples) const { // To calculate the slope, a range of time is needed. |prior_time| and // |start_time| define that range. The very first |prior_time| is one stride // prior to the requested start time. SampleTimeNs prior_time = CalcTimeForStride(request, -1); SampleValue prior_value = 0ULL; const int64_t limit = request.sample_count; for (int64_t sample_n = -1; sample_n < limit; ++sample_n) { SampleTimeNs start_time = CalcTimeForStride(request, sample_n); SampleTimeNs end_time = CalcTimeForStride(request, sample_n + 1); auto begin = sample_stream.lower_bound(start_time); if (begin == sample_stream.end()) { if (sample_n >= 0) { samples->push_back(NO_DATA); } continue; } auto end = sample_stream.lower_bound(end_time); SampleTimeNs high_time = request.start_time_ns; SampleValue highest = 0ULL; uint_fast32_t count = 0ULL; for (auto i = begin; i != end; ++i) { if (highest < i->second) { high_time = i->first; highest = i->second; } ++count; } SampleValue result = NO_DATA; if (count) { if (request.HasFlag(StreamSetsRequest::SLOPE)) { result = calculate_slope(highest, &prior_value, high_time, &prior_time); } else { result = highest; } } if (sample_n >= 0) { samples->push_back(result); } } } void Dockyard::ComputeLowestPerColumn(DockyardId dockyard_id, const SampleStream& sample_stream, const StreamSetsRequest& request, std::vector<SampleValue>* samples) const { // To calculate the slope, a range of time is needed. |prior_time| and // |start_time| define that range. The very first |prior_time| is one stride // prior to the requested start time. SampleTimeNs prior_time = CalcTimeForStride(request, -1); SampleValue prior_value = 0ULL; const int64_t limit = request.sample_count; for (int64_t sample_n = -1; sample_n < limit; ++sample_n) { SampleTimeNs start_time = CalcTimeForStride(request, sample_n); auto begin = sample_stream.lower_bound(start_time); if (begin == sample_stream.end()) { if (sample_n >= 0) { samples->push_back(NO_DATA); } continue; } SampleTimeNs end_time = CalcTimeForStride(request, sample_n + 1); auto end = sample_stream.lower_bound(end_time); SampleTimeNs low_time = request.start_time_ns; SampleValue lowest = SAMPLE_MAX_VALUE; uint_fast32_t count = 0ULL; for (auto i = begin; i != end; ++i) { if (lowest > i->second) { low_time = i->first; lowest = i->second; } ++count; } SampleValue result = NO_DATA; if (count) { if (request.HasFlag(StreamSetsRequest::SLOPE)) { result = calculate_slope(lowest, &prior_value, low_time, &prior_time); } else { result = lowest; } } if (sample_n >= 0) { samples->push_back(result); } } } void Dockyard::NormalizeResponse(DockyardId dockyard_id, const SampleStream& sample_stream, const StreamSetsRequest& request, std::vector<SampleValue>* samples) const { auto low_high = sample_stream_low_high_.find(dockyard_id); SampleValue lowest = low_high->second.first; SampleValue highest = low_high->second.second; SampleValue value_range = highest - lowest; if (value_range == 0) { // If there is no range, then all the values drop to zero. // Also avoid divide by zero in the code below. std::fill(samples->begin(), samples->end(), 0); return; } for (std::vector<SampleValue>::iterator i = samples->begin(); i != samples->end(); ++i) { *i = (*i - lowest) * NORMALIZATION_RANGE / value_range; } } void Dockyard::ComputeSculpted(DockyardId dockyard_id, const SampleStream& sample_stream, const StreamSetsRequest& request, std::vector<SampleValue>* samples) const { // To calculate the slope, a range of time is needed. |prior_time| and // |start_time| define that range. The very first |prior_time| is one stride // prior to the requested start time. SampleTimeNs prior_time = CalcTimeForStride(request, -1); SampleValue prior_value = 0ULL; auto overall_average = OverallAverageForStream(dockyard_id); const int64_t limit = request.sample_count; for (int64_t sample_n = -1; sample_n < limit; ++sample_n) { SampleTimeNs start_time = CalcTimeForStride(request, sample_n); auto begin = sample_stream.lower_bound(start_time); if (begin == sample_stream.end()) { if (sample_n >= 0) { samples->push_back(NO_DATA); } continue; } SampleTimeNs end_time = CalcTimeForStride(request, sample_n + 1); auto end = sample_stream.lower_bound(end_time); SampleValue accumulator = 0ULL; SampleValue highest = 0ULL; SampleValue lowest = SAMPLE_MAX_VALUE; uint_fast32_t count = 0ULL; for (auto i = begin; i != end; ++i) { auto value = i->second; accumulator += value; if (highest < value) { highest = value; } if (lowest > value) { lowest = value; } ++count; } SampleValue result = NO_DATA; if (count) { auto average = accumulator / count; auto final = average >= overall_average ? highest : lowest; if (request.HasFlag(StreamSetsRequest::SLOPE)) { result = calculate_slope(final, &prior_value, end_time, &prior_time); } else { result = final; } } if (sample_n >= 0) { samples->push_back(result); } } } void Dockyard::ComputeSmoothed(DockyardId dockyard_id, const SampleStream& sample_stream, const StreamSetsRequest& request, std::vector<SampleValue>* samples) const { SampleTimeNs prior_time = CalcTimeForStride(request, -1); SampleValue prior_value = 0ULL; const int64_t limit = request.sample_count; for (int64_t sample_n = -1; sample_n < limit; ++sample_n) { SampleTimeNs start_time = CalcTimeForStride(request, sample_n - 1); auto begin = sample_stream.lower_bound(start_time); if (begin == sample_stream.end()) { if (sample_n >= 0) { samples->push_back(NO_DATA); } continue; } SampleTimeNs end_time = CalcTimeForStride(request, sample_n + 2); auto end = sample_stream.lower_bound(end_time); SampleValue accumulator = 0ULL; uint_fast32_t count = 0ULL; for (auto i = begin; i != end; ++i) { accumulator += i->second; ++count; } SampleValue result = NO_DATA; if (count) { result = accumulator / count; if (request.HasFlag(StreamSetsRequest::SLOPE)) { result = calculate_slope(result, &prior_value, end_time, &prior_time); } } if (sample_n >= 0) { samples->push_back(result); } } } SampleValue Dockyard::OverallAverageForStream(DockyardId dockyard_id) const { auto low_high = sample_stream_low_high_.find(dockyard_id); if (low_high == sample_stream_low_high_.end()) { return NO_DATA; } return (low_high->second.first + low_high->second.second) / 2; } void Dockyard::ComputeLowestHighestForRequest( const StreamSetsRequest& request, StreamSetsResponse* response) const { if (request.HasFlag(StreamSetsRequest::SLOPE)) { // Slope responses have fixed low/high values. response->lowest_value = 0ULL; response->highest_value = SLOPE_LIMIT; return; } // Gather the overall lowest and highest values encountered. SampleValue lowest = SAMPLE_MAX_VALUE; SampleValue highest = 0ULL; for (auto dockyard_id = request.dockyard_ids.begin(); dockyard_id != request.dockyard_ids.end(); ++dockyard_id) { auto low_high = sample_stream_low_high_.find(*dockyard_id); if (low_high == sample_stream_low_high_.end()) { continue; } if (lowest > low_high->second.first) { lowest = low_high->second.first; } if (highest < low_high->second.second) { highest = low_high->second.second; } } response->lowest_value = lowest; response->highest_value = highest; } void Dockyard::ProcessRequests() { if (on_stream_sets_handler_ != nullptr) { StreamSetsResponse response; for (auto i = pending_requests_.begin(); i != pending_requests_.end(); ++i) { ProcessSingleRequest(**i, &response); on_stream_sets_handler_(response); } } pending_requests_.clear(); } } // namespace dockyard
35.298103
80
0.655969
[ "vector" ]
1bca2baa0c3d41a35f23332f04ebf9c3bf8c1ad6
2,464
cc
C++
Filters/src/BunchIntensityFilter_module.cc
NamithaChitrazee/Offline-1
bcb6c74954f95dd48433d79a69d3ef3bdb99022e
[ "Apache-2.0" ]
null
null
null
Filters/src/BunchIntensityFilter_module.cc
NamithaChitrazee/Offline-1
bcb6c74954f95dd48433d79a69d3ef3bdb99022e
[ "Apache-2.0" ]
null
null
null
Filters/src/BunchIntensityFilter_module.cc
NamithaChitrazee/Offline-1
bcb6c74954f95dd48433d79a69d3ef3bdb99022e
[ "Apache-2.0" ]
null
null
null
// // Filter for selecting events with a mu-bunch intensity above a given threshold // Original author: G. Pezzullo // // framework #include "art/Framework/Core/EDFilter.h" #include "art/Framework/Principal/Event.h" #include "art/Framework/Principal/Handle.h" #include "Offline/RecoDataProducts/inc/TrkFitFlag.hh" #include "Offline/RecoDataProducts/inc/TriggerInfo.hh" #include "fhiclcpp/ParameterSet.h" #include "Offline/BFieldGeom/inc/BFieldManager.hh" #include "Offline/GeometryService/inc/GeomHandle.hh" #include "Offline/GeometryService/inc/DetectorSystem.hh" // data #include "Offline/MCDataProducts/inc/ProtonBunchIntensity.hh" using namespace CLHEP; // c++ #include <string> #include <vector> #include <iostream> #include <memory> using namespace std; namespace mu2e { class BunchIntensityFilter : public art::EDFilter { public: explicit BunchIntensityFilter(fhicl::ParameterSet const& pset); virtual bool filter (art::Event& event) override; virtual bool beginRun(art::Run& run ); virtual bool endRun ( art::Run& run ) override; private: art::InputTag _pbiTag; double _minIntensity; int _debug; // counters unsigned _nevt, _npass; }; BunchIntensityFilter::BunchIntensityFilter(fhicl::ParameterSet const& pset) : art::EDFilter{pset}, _pbiTag (pset.get<art::InputTag>("protonBunchIntensityTag","protonBunchIntensity")), _minIntensity (pset.get<double> ("minIntensity", 3.5e7)), _debug (pset.get<int> ("debugLevel",0)), _nevt(0), _npass(0){} bool BunchIntensityFilter::beginRun(art::Run & run){ return true; } bool BunchIntensityFilter::filter(art::Event& evt){ // create output unique_ptr<TriggerInfo> triginfo(new TriggerInfo); ++_nevt; bool retval(false); // preset to fail // find the collection auto pbiH = evt.getValidHandle<ProtonBunchIntensity>(_pbiTag); const ProtonBunchIntensity* pbi = pbiH.product(); if (pbi->intensity() >= _minIntensity) { retval = true; ++_npass; } return retval; } bool BunchIntensityFilter::endRun( art::Run& run ) { if(_debug > 0 && _nevt > 0){ cout << moduleDescription().moduleLabel() << " paassed " << _npass << " events out of " << _nevt << " for a ratio of " << float(_npass)/float(_nevt) << endl; } return true; } } using mu2e::BunchIntensityFilter; DEFINE_ART_MODULE(BunchIntensityFilter);
30.04878
164
0.6875
[ "vector" ]
1bcd92f7af69159db34501c735674b9025f18127
822
cpp
C++
Dataset/Leetcode/test/66/243.cpp
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
Dataset/Leetcode/test/66/243.cpp
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
Dataset/Leetcode/test/66/243.cpp
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
class Solution { public: vector<int> XXX(vector<int>& digits) { bool add=0;//进位数据 int i=digits.size()-1;//遍历数组的下标 if(digits[i]==9){//如果遍历到9,就变成0且进位数据为1 digits[i--]=0; add=1; }else digits[i]++;//如果不是就末尾加一 while(i>-1&&add){//如果进位为1且数组下标没有越界,下标往前遍历 if(digits[i]==9){//如果是9,继续往前遍历 digits[i--]=0; add=1; }else{//如果不是9,加一且退出循环 add=0; digits[i]++; } } if(add){//如果下标越界且进位信息为1,将头位信息改为1,在添一位0 digits[0]=1; digits.push_back(0); } return digits; } }; undefined for (i = 0; i < document.getElementsByTagName("code").length; i++) { console.log(document.getElementsByTagName("code")[i].innerText); }
26.516129
139
0.489051
[ "vector" ]
1bcd9c408dfbb140550b12fa871a6e82d198e73b
1,787
cpp
C++
random/permutations.cpp
ChaoticCooties/cses
afe785306a9bd546aee9f46dd8649cfe2666fc4c
[ "MIT" ]
null
null
null
random/permutations.cpp
ChaoticCooties/cses
afe785306a9bd546aee9f46dd8649cfe2666fc4c
[ "MIT" ]
null
null
null
random/permutations.cpp
ChaoticCooties/cses
afe785306a9bd546aee9f46dd8649cfe2666fc4c
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #define ll long long #define pb push_back #define mp make_pair #define endl '\n' #define fast ios_base::sync_with_stdio(false), cin.tie(0), cout.tie(0); #define MOD 1000000007 using namespace std; void fastscan(int &number) { // variable to indicate sign of input number bool negative = false; int c; number = 0; // extract current character from buffer c = getchar(); if (c == '-') { // number is negative negative = true; // extract the next character from the buffer c = getchar(); } // Keep on extracting characters if they are integers // i.e ASCII Value lies from '0'(48) to '9' (57) for (; (c > 47 && c < 58); c = getchar()) number = number * 10 + c - 48; // if scanned input has a negative sign, negate the // value of the input number if (negative) number *= -1; } void generatePermutations(vector<int> &permutations, vector<int> elements, vector<bool> positions) { // Base case if (permutations.size() == elements.size()) { // Print for (auto i : permutations) { cout << i; } cout << endl; } else { for (int i = 0; i < elements.size(); i++) { // Taken if (positions[i]) { continue; } // Permutate positions[i] = true; permutations.pb(elements[i]); generatePermutations(permutations, elements, positions); // Reverse operation positions[i] = false; permutations.pop_back(); } } } int main() { fast int n; fastscan(n); vector<int> permutations; vector<int> elements; vector<bool> positions(n, false); for (int i = 0; i < n; i++) { elements.pb(i); } generatePermutations(permutations, elements, positions); return 0; }
20.77907
74
0.603805
[ "vector" ]
1bd89f59df0db6c2c40b2162bf4763954e16c440
742
hpp
C++
mia/medium/medium.hpp
CasualPokePlayer/ares
58690cd5fc7bb6566c22935c5b80504a158cca29
[ "BSD-3-Clause" ]
153
2020-07-25T17:55:29.000Z
2021-10-01T23:45:01.000Z
mia/medium/medium.hpp
CasualPokePlayer/ares
58690cd5fc7bb6566c22935c5b80504a158cca29
[ "BSD-3-Clause" ]
176
2020-07-25T19:11:23.000Z
2021-10-04T17:11:32.000Z
mia/medium/medium.hpp
CasualPokePlayer/ares
58690cd5fc7bb6566c22935c5b80504a158cca29
[ "BSD-3-Clause" ]
44
2020-07-25T08:51:55.000Z
2021-09-25T16:09:01.000Z
struct Database { string name; Markup::Node list; }; struct Medium : Pak { static auto create(string name) -> shared_pointer<Pak>; auto manifestDatabase(string sha256) -> string; string sha256; }; struct Cartridge : Medium { auto type() -> string override { return "Cartridge"; } }; struct CompactDisc : Medium { auto type() -> string override { return "Compact Disc"; } auto extensions() -> vector<string> override { return {"cue"}; } auto manifestAudio(string location) -> string; auto readDataSectorBCD(string filename, u32 sectorID) -> vector<u8>; auto readDataSectorCUE(string filename, u32 sectorID) -> vector<u8>; }; struct FloppyDisk : Medium { auto type() -> string override { return "Floppy Disk"; } };
26.5
70
0.692722
[ "vector" ]
1bd9baee898f918f4be2d5489e8efb78f7355c02
2,757
cc
C++
src/WorkerSession.cc
IMCG/RamCloud
dad96cf34d330608acb43b009d12949ed2d938f4
[ "0BSD" ]
1
2021-12-06T01:24:22.000Z
2021-12-06T01:24:22.000Z
src/WorkerSession.cc
behnamm/cs244b_project
957e8b3979e4ca24814edd73254cc4c69ea14126
[ "0BSD" ]
null
null
null
src/WorkerSession.cc
behnamm/cs244b_project
957e8b3979e4ca24814edd73254cc4c69ea14126
[ "0BSD" ]
1
2021-12-06T01:24:22.000Z
2021-12-06T01:24:22.000Z
/* Copyright (c) 2012 Stanford University * * Permission to use, copy, modify, and distribute this software for any purpose * with or without fee is hereby granted, provided that the above copyright * notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR ANY * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "Logger.h" #include "WorkerSession.h" namespace RAMCloud { /** * Construct a WorkerSession. * * \param context * Overall information about the RAMCloud server. * \param wrapped * Another Session object, to which #sendRequest and other methods * will be forwarded. */ WorkerSession::WorkerSession(Context* context, Transport::SessionRef wrapped) : context(context) , wrapped(wrapped) { setServiceLocator(wrapped->getServiceLocator()); RAMCLOUD_TEST_LOG("created"); } /** * Destructor for WorkerSessions. */ WorkerSession::~WorkerSession() { // Make sure that the underlying session is released while the // dispatch thread is locked. Dispatch::Lock lock(context->dispatch); wrapped = NULL; } /// \copydoc Transport::Session::abort void WorkerSession::abort() { // Must make sure that the dispatch thread isn't running when we // invoke the real abort. Dispatch::Lock lock(context->dispatch); return wrapped->abort(); } /// \copydoc Transport::Session::cancelRequest void WorkerSession::cancelRequest(Transport::RpcNotifier* notifier) { // Must make sure that the dispatch thread isn't running when we // invoke the real cancelRequest. Dispatch::Lock lock(context->dispatch); return wrapped->cancelRequest(notifier); } /// \copydoc Transport::Session::getRpcInfo string WorkerSession::getRpcInfo() { // Must make sure that the dispatch thread isn't running when we // invoke the real getRpcInfo. Dispatch::Lock lock(context->dispatch); return wrapped->getRpcInfo(); } /// \copydoc Transport::Session::sendRequest void WorkerSession::sendRequest(Buffer* request, Buffer* response, Transport::RpcNotifier* notifier) { // Must make sure that the dispatch thread isn't running when we // invoke the real sendRequest. Dispatch::Lock lock(context->dispatch); wrapped->sendRequest(request, response, notifier); } } // namespace RAMCloud
29.967391
80
0.725426
[ "object" ]