hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
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
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
77k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
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
7
1.05M
avg_line_length
float64
1.21
653k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
1
9e6696f57287cb809f6261bae1f749e86b51c56f
484
cpp
C++
228. Summary Ranges/solution.cpp
zlsun/leetcode
438d0020a701d7aa6a82eee0e46e5b11305abfda
[ "MIT" ]
null
null
null
228. Summary Ranges/solution.cpp
zlsun/leetcode
438d0020a701d7aa6a82eee0e46e5b11305abfda
[ "MIT" ]
null
null
null
228. Summary Ranges/solution.cpp
zlsun/leetcode
438d0020a701d7aa6a82eee0e46e5b11305abfda
[ "MIT" ]
null
null
null
/** 228. Summary Ranges Given a sorted integer array without duplicates, return the summary of its ranges. For example, given [0,1,2,4,5,7], return ["0->2","4->5","7"]. Credits:Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases. **/ #include <iostream> #include "../utils.h" using namespace std; class Solution { public: vector<string> summaryRanges(vector<int>& nums) { } }; int main() { Solution s; return 0; }
19.36
99
0.667355
9e67cbfbd174db0408f4e99477194e09d737b4f8
4,357
cpp
C++
ShopListManager/ShopPackage.cpp
0x4d696e68/InGameShop
405e01defb59bd1cf22a5a5d245fdf2475b1ca36
[ "MIT" ]
5
2021-08-31T19:18:24.000Z
2021-11-11T08:58:20.000Z
ShopListManager/ShopPackage.cpp
0x4d696e68/InGameShop
405e01defb59bd1cf22a5a5d245fdf2475b1ca36
[ "MIT" ]
null
null
null
ShopListManager/ShopPackage.cpp
0x4d696e68/InGameShop
405e01defb59bd1cf22a5a5d245fdf2475b1ca36
[ "MIT" ]
2
2021-08-31T18:39:50.000Z
2021-09-16T22:37:06.000Z
//************************************************************************ // // Decompiled by @myheart, @synth3r // <https://forum.ragezone.com/members/2000236254.html> // // // FILE: ShopPackage.cpp // // #include "stdafx.h" #if(DECOMPILE_INGAMESHOP==1) #include "ShopPackage.h" #include "StringToken.h" #include "StringMethod.h" CShopPackage::CShopPackage() // OK { this->LeftCount = -1; this->ProductSeqList.clear(); this->PriceSeqList.clear(); } CShopPackage::~CShopPackage() // OK { } bool CShopPackage::SetPackage(std::string strdata) // OK { if(strdata.empty()) return 0; CStringToken token(strdata,"@"); if(token.hasMoreTokens()==0) return 0; this->ProductDisplaySeq = atoi(token.nextToken().c_str()); this->ViewOrder = atoi(token.nextToken().c_str()); this->PackageProductSeq = atoi(token.nextToken().c_str()); StringCchCopy(this->PackageProductName,sizeof(this->PackageProductName),token.nextToken().c_str()); this->PackageProductType = atoi(token.nextToken().c_str()); this->Price = atoi(token.nextToken().c_str()); StringCchCopy(this->Description,sizeof(this->Description),token.nextToken().c_str()); StringCchCopy(this->Caution,sizeof(this->Caution),token.nextToken().c_str()); this->SalesFlag = atoi(token.nextToken().c_str()); this->GiftFlag = atoi(token.nextToken().c_str()); CStringMethod::ConvertStringToDateTime(this->StartDate,token.nextToken()); CStringMethod::ConvertStringToDateTime(this->EndDate,token.nextToken()); this->CapsuleFlag = atoi(token.nextToken().c_str()); this->CapsuleCount = atoi(token.nextToken().c_str()); StringCchCopy(this->ProductCashName,sizeof(this->ProductCashName),token.nextToken().c_str()); StringCchCopy(this->PricUnitName,sizeof(this->PricUnitName),token.nextToken().c_str()); this->DeleteFlag = atoi(token.nextToken().c_str()); this->EventFlag = atoi(token.nextToken().c_str()); this->ProductAmount = atoi(token.nextToken().c_str()); this->SetProductSeqList(token.nextToken()); StringCchCopy(this->InGamePackageID,sizeof(this->InGamePackageID),token.nextToken().c_str()); this->ProductCashSeq = atoi(token.nextToken().c_str()); this->PriceCount = atoi(token.nextToken().c_str()); this->SetPriceSeqList(token.nextToken()); this->DeductMileageFlag = atoi(token.nextToken().c_str())!=0; this->CashType = atoi(token.nextToken().c_str()); this->CashTypeFlag = atoi(token.nextToken().c_str()); return 1; } void CShopPackage::SetLeftCount(int nCount) // OK { this->LeftCount = nCount; } int CShopPackage::GetProductCount() // OK { return static_cast<int>(this->ProductSeqList.size()); } void CShopPackage::SetProductSeqFirst() // OK { this->ProductSeqIter = this->ProductSeqList.begin(); } bool CShopPackage::GetProductSeqFirst(int& ProductSeq) // OK { this->ProductSeqIter = this->ProductSeqList.begin(); if(this->ProductSeqIter==this->ProductSeqList.end()) return 0; ProductSeq = (*this->ProductSeqIter); this->ProductSeqIter++; return 1; } bool CShopPackage::GetProductSeqNext(int& ProductSeq) // OK { if(this->ProductSeqIter==this->ProductSeqList.end()) return 0; ProductSeq = (*this->ProductSeqIter); this->ProductSeqIter++; return 1; } int CShopPackage::GetPriceCount() { return static_cast<int>(this->PriceSeqList.size()); } void CShopPackage::SetPriceSeqFirst() { this->PriceSeqIter = this->PriceSeqList.begin(); } bool CShopPackage::GetPriceSeqFirst(int& PriceSeq) // OK { this->PriceSeqIter = this->PriceSeqList.begin(); if(this->PriceSeqIter==this->PriceSeqList.end()) return 0; PriceSeq = (*this->PriceSeqIter); this->PriceSeqIter++; return 1; } bool CShopPackage::GetPriceSeqNext(int& PriceSeq) // OK { if(this->PriceSeqIter==this->PriceSeqList.end()) return 0; PriceSeq = (*this->PriceSeqIter); this->PriceSeqIter++; return 1; } void CShopPackage::SetProductSeqList(std::string strdata) // OK { CStringToken token(strdata,"|"); while(true) { if(token.hasMoreTokens()==0) break; std::string data = token.nextToken(); if(data.empty()) break; this->ProductSeqList.push_back(atoi(data.c_str())); } } void CShopPackage::SetPriceSeqList(std::string strdata) // OK { CStringToken token(strdata,"|"); while(true) { if(token.hasMoreTokens()==0) break; std::string data = token.nextToken(); if(data.empty()) break; this->PriceSeqList.push_back(atoi(data.c_str())); } } #endif
25.934524
100
0.706679
9e67f3cc68150c8beadda59b2c30b05adaf5e682
761
cpp
C++
Jeu/Src/ComponentsManagement/ProjectileSystem/Projectiles/Fireball.cpp
abastienIIT/Roguelike
f31935e45c968fbe608e57d0137d71251d1afc10
[ "Apache-2.0" ]
2
2021-02-07T16:07:10.000Z
2021-02-07T23:18:43.000Z
Jeu/Src/ComponentsManagement/ProjectileSystem/Projectiles/Fireball.cpp
abastienIIT/Roguelike
f31935e45c968fbe608e57d0137d71251d1afc10
[ "Apache-2.0" ]
49
2021-02-06T19:08:07.000Z
2021-09-14T16:43:27.000Z
Jeu/Src/ComponentsManagement/ProjectileSystem/Projectiles/Fireball.cpp
abastienIIT/Roguelike
f31935e45c968fbe608e57d0137d71251d1afc10
[ "Apache-2.0" ]
null
null
null
#include "Fireball.h" #include "../../Components.h" #include "../../../Common/Globalbilboulga.h" void Fireball::init(Entity* projectile, std::vector<Entity*>* targets) { ProjectileBase::init(projectile, targets); transform->velocity = velocity; sprite->setAsset("Fireball"); sprite->setCurrentTexture(0); collider->tag = "Fireball"; collider->setCollider(SDL_Rect({ 0,0,32,32 })); } void Fireball::update() { distance += velocity.x; if (distance > range || distance < range * -1 || transform->position.x < 0 || transform->position.y < 0 || transform->position.x > Globalbilboulga::getInstance()->getCurrentRoomSize().x || transform->position.y > Globalbilboulga::getInstance()->getCurrentRoomSize().y) { projectile->destroy(); } }
23.060606
83
0.683311
9e695c2c6e58847974dc3e0b07949c777725ce7d
788
cpp
C++
C++/add-bold-tag-in-string.cpp
cmhuang0328/Leetcode
f1b8e4b8f0e2ca74d4315d55ad17b7c2be1cb253
[ "MIT" ]
5
2017-11-14T09:32:33.000Z
2020-05-11T05:15:41.000Z
C++/add-bold-tag-in-string.cpp
Ikhideifidon/LeetCode
414e70bc0181207d49877abc025fb62d03b93b85
[ "MIT" ]
null
null
null
C++/add-bold-tag-in-string.cpp
Ikhideifidon/LeetCode
414e70bc0181207d49877abc025fb62d03b93b85
[ "MIT" ]
3
2019-05-14T02:49:34.000Z
2020-05-19T08:45:39.000Z
// Time: O(s * d * l), l is the average string length // Space: O(s) class Solution { public: string addBoldTag(string s, vector<string>& dict) { vector<bool> bold(s.length()); for (const auto& d: dict) { auto pos = -1; while ((pos = s.find(d, pos + 1)) != string::npos) { fill(bold.begin() + pos, bold.begin() + pos + d.length(), true); } } string result; bool prev = false; for (int i = 0; i < s.length(); ++i) { if (prev != bold[i]) { result += prev ? "</b>" : "<b>"; prev = bold[i]; } result.push_back(s[i]); } if (prev) { result += "</b>"; } return result; } };
28.142857
80
0.414975
9e69f8a3a3c40561449fcf2c1b6021ca3b2f5dca
5,954
cc
C++
src/c++/apps/echo/httpops.cc
isaac-ped/demikernel
6f372569e3599d8bf9083df6c25490c42af74c0d
[ "MIT" ]
null
null
null
src/c++/apps/echo/httpops.cc
isaac-ped/demikernel
6f372569e3599d8bf9083df6c25490c42af74c0d
[ "MIT" ]
null
null
null
src/c++/apps/echo/httpops.cc
isaac-ped/demikernel
6f372569e3599d8bf9083df6c25490c42af74c0d
[ "MIT" ]
null
null
null
#include <string.h> #include <stdio.h> #include <stdint.h> #include "httpops.hh" int regex_html(char *to_match, char *htmlDoc, size_t length) { const char *pcreErrorStr; int errOffset; pcre * reCompiled = pcre_compile(EVIL_REGEX, 0, &pcreErrorStr, &errOffset, NULL); if (reCompiled == NULL) { fprintf(stderr, "Error compiling regex"); } pcre_extra pcreExtra; pcreExtra.match_limit = -1; pcreExtra.match_limit_recursion = -1; pcreExtra.flags = PCRE_EXTRA_MATCH_LIMIT | PCRE_EXTRA_MATCH_LIMIT_RECURSION; int len = strlen(to_match); int x[1]; int ret = pcre_exec(reCompiled, &pcreExtra, to_match, len, 0, 0, x, 1); char resp[5]; if (ret < 0){ sprintf(resp, "%s", "NO"); } else { sprintf(resp, "%s", "YES"); } snprintf(htmlDoc, length, HTML, to_match, EVIL_REGEX, resp); pcre_free(reCompiled); return 0; } void replace_special(char *url) { for (u_int16_t i=0; i<strlen(url); i++) { if (url[i] == '%') { char hex[3]; hex[0] = url[i+1]; hex[1] = url[i+2]; hex[2] = '\0'; char sub = (char)strtol(hex, NULL, 16); url[i] = sub; for (u_int16_t j=i+1; j<strlen(url) - 1; j++) { url[j] = url[j+2]; } } } } int url_to_path(char *url, const char *dir, char *path, int capacity) { int len = 0; for (char *c=url; *c!='\0' && *c!='?'; c++, len++); int dir_len = strlen(dir); int dir_slash = (dir[dir_len - 1] == '/'); int url_slash = (url[0] == '/'); dir_len -= (dir_slash && url_slash); int both_missing_slash = (!dir_slash && !url_slash); if (dir_len + len + both_missing_slash >= capacity) { fprintf(stderr, "Path from url (%s) too large for buffer (%d)", url, capacity); return -1; } char *dest = path; strncpy(dest, dir, dir_len); if (both_missing_slash) { dest[dir_len] = '/'; } strncpy(&dest[dir_len + both_missing_slash], url, len + 1); dest[dir_len + both_missing_slash + len] = '\0'; replace_special(dest); return dir_len + len; } void path_to_mime_type(char *path, char buf[], int capacity) { char *extension = &path[strlen(path) - 1]; for (; extension != path && *extension != '.' && *extension != '/'; extension--); if (*extension != '.') strncpy(buf, DEFAULT_MIME_TYPE, capacity); extension++; // Advance past the dot // TODO: Necessary to replace this by loading /etc/mime.types into hashmap? if (strcasecmp(extension, "html") == 0 || strcasecmp(extension, "htm") == 0 || strcasecmp(extension, "txt") == 0) { strncpy(buf, "text/html", capacity); } else if (strcasecmp(extension, "png") == 0) { strncpy(buf, "image/png", capacity); } else if (strcasecmp(extension, "jpg") == 0 || strcasecmp(extension, "jpeg") == 0) { strncpy(buf, "image/jpeg", capacity); } else if (strcasecmp(extension, "gif") == 0) { strncpy(buf, "image/gif", capacity); } else { strncpy(buf, DEFAULT_MIME_TYPE, capacity); } } int generate_header(char **dest, int code, int body_len, char *mime_type) { if (code == 200) { char header_buf[MAX_HEADER_LEN]; size_t alloc_size = snprintf(header_buf, 0, BASE_HTTP_HEADER, code, mime_type, body_len) + 1; *dest = reinterpret_cast<char *>(malloc(alloc_size)); return snprintf(*dest, alloc_size, BASE_HTTP_HEADER, code, mime_type, body_len); } else if (code == 404) { size_t alloc_size = strlen(NOT_FOUND_HEADER) + 1; *dest = reinterpret_cast<char *>(malloc(alloc_size)); return snprintf(*dest, alloc_size, NOT_FOUND_HEADER); } else if (code == 501) { size_t alloc_size = strlen(INT_ERROR_HEADER) + 1; *dest = reinterpret_cast<char *>(malloc(alloc_size)); return snprintf(*dest, alloc_size, INT_ERROR_HEADER); } else { size_t alloc_size = strlen(NOT_IMPLEMENTED_HEADER) + 1; *dest = reinterpret_cast<char *>(malloc(alloc_size)); return snprintf(*dest, alloc_size, NOT_IMPLEMENTED_HEADER); } } int get_regex_value(char *url, char *regex) { char *regex_start = strstr(url, REGEX_KEY); if (regex_start == NULL) return -1; regex_start += strlen(REGEX_KEY); int start_i = (regex_start - url); for (int i=start_i; (i-start_i)<MAX_REGEX_VALUE_LEN; i++) { switch (url[i]) { case '?': case '&': case '\0': case ' ': strncpy(regex, &url[start_i], i - start_i); regex[i-start_i] = '\0'; return 0; default: continue; } } fprintf(stderr, "Requested regex value (%s) too long\n", regex_start); return -1; } enum http_req_type get_request_type(char *url) { if (strstr(url, REGEX_KEY) != NULL) { return REGEX_REQ; } return FILE_REQ; } void generate_response(char **response, char *header, char *body, int header_len, int body_len, int *response_len, uint32_t req_id) { *response = reinterpret_cast<char *>(malloc( (size_t) body_len + header_len + 2 + sizeof(uint32_t) )); memcpy(*response, (const int *) &req_id, sizeof(uint32_t)); *response_len = sizeof(uint32_t); *response_len += snprintf(*response + *response_len, header_len + 1, "%s", header); if (*response_len > (header_len + (int) sizeof(uint32_t))) { fprintf(stderr, "response_len > header_len: header was truncated!"); } if (body) { *response_len += snprintf(*response + *response_len, body_len + 1, "%s", body); free(body); } if (*response_len > (body_len + header_len + (int) sizeof(uint32_t))) { fprintf(stderr, "response_len > header_len+body_len: body was truncated!"); } free(header); }
33.638418
101
0.584649
9e6b96d69508e8a7e4d2467a1b5af222443a5a6f
2,712
cpp
C++
tests/picross_shell/test_cross_command.cpp
deqyra/Picross-
0c81172faa8121c58bc2a88122d1cdbe661cc17e
[ "MIT" ]
null
null
null
tests/picross_shell/test_cross_command.cpp
deqyra/Picross-
0c81172faa8121c58bc2a88122d1cdbe661cc17e
[ "MIT" ]
1
2020-05-16T14:01:08.000Z
2020-06-11T21:12:02.000Z
tests/picross_shell/test_cross_command.cpp
deqyra/PicrossEngine
0c81172faa8121c58bc2a88122d1cdbe661cc17e
[ "MIT" ]
null
null
null
#include "../../lib/catch2/catch2.hpp" #include <sstream> #include "../../tools/cli/cli_streams.hpp" #include "../../tools/micro_shell/micro_shell_codes.hpp" #include "../../picross_shell/picross_shell_state.hpp" #include "../../picross_shell/shell_cross_command.hpp" #include "../../core/grid.hpp" #include "../../core/cell_t.hpp" #include "../../io/xml_grid_serializer.hpp" #define TAGS "[shell][shell_command]" namespace Picross { TEST_CASE("ShellCrossCommand end-to-end", TAGS) { std::stringstream ss; CLIStreams s = CLIStreams(ss, ss, ss); PicrossShellState state = PicrossShellState(); Grid g = Grid(10, 10); Grid modifiedG = g; state.mainGrid() = g; state.workingGrid() = modifiedG; ShellCrossCommand command = ShellCrossCommand(); SECTION("Bad arguments") { REQUIRE(command.processInput("cross aze", state, s) == SHELL_COMMAND_BAD_ARGUMENTS); REQUIRE(command.processInput("cross aze rty", state, s) == SHELL_COMMAND_BAD_ARGUMENTS); REQUIRE(command.processInput("cross 3 rty", state, s) == SHELL_COMMAND_BAD_ARGUMENTS); REQUIRE(state.mainGrid() == g); REQUIRE(state.workingGrid() == modifiedG); std::string expected = StringTools::readFileIntoString("resources/tests/picross_shell/cross_invalid_output.txt"); REQUIRE(ss.str() == expected); } SECTION("Cross single cell") { REQUIRE(command.processInput("cross 3 5", state, s) == SHELL_COMMAND_SUCCESS); modifiedG.crossCell(3, 5); } SECTION("Cross row or column range") { REQUIRE(command.processInput("cross 3 5:8", state, s) == SHELL_COMMAND_SUCCESS); REQUIRE(command.processInput("cross 1:4 2", state, s) == SHELL_COMMAND_SUCCESS); modifiedG.setCellRange(3, 3, 5, 8, CELL_CROSSED); modifiedG.setCellRange(1, 4, 2, 2, CELL_CROSSED); } SECTION("Cross row or column range (reversed ranges)") { REQUIRE(command.processInput("cross 3 8:5", state, s) == SHELL_COMMAND_SUCCESS); REQUIRE(command.processInput("cross 4:1 2", state, s) == SHELL_COMMAND_SUCCESS); modifiedG.setCellRange(3, 3, 5, 8, CELL_CROSSED); modifiedG.setCellRange(1, 4, 2, 2, CELL_CROSSED); } SECTION("Cross area range") { REQUIRE(command.processInput("cross 3:7 5:8", state, s) == SHELL_COMMAND_SUCCESS); modifiedG.setCellRange(3, 7, 5, 8, CELL_CROSSED); } REQUIRE(state.mainGrid() == g); REQUIRE(state.workingGrid() == modifiedG); } }
35.220779
125
0.614307
9e6ea7609f559d3f5fa9d7c2b9f4b53b1c3d43e2
478
cpp
C++
layer2/ethernetHelper.cpp
zetwhite/SimpleEtherCATMaster
f17b04c96385d13e0cf1cdc664e4821058280273
[ "MIT" ]
2
2021-03-04T08:50:02.000Z
2021-04-05T14:59:57.000Z
layer2/ethernetHelper.cpp
zetwhite/SimpleEtherCATMaster
f17b04c96385d13e0cf1cdc664e4821058280273
[ "MIT" ]
null
null
null
layer2/ethernetHelper.cpp
zetwhite/SimpleEtherCATMaster
f17b04c96385d13e0cf1cdc664e4821058280273
[ "MIT" ]
null
null
null
#include "ethernetHelper.hpp" const int EthernetHelper::size = 14; EthernetHelper::EthernetHelper (uint8_t srcMac[6], uint8_t destMac[6], uint16_t type){ ptr = new struct ethhdr; memcpy(ptr->h_dest, destMac, 6); memcpy(ptr->h_source, srcMac, 6); ptr->h_proto = htons(type); } unsigned char* EthernetHelper::toArray(){ return reinterpret_cast<unsigned char*>(ptr); } void EthernetHelper::setType(uint16_t type){ ptr->h_proto = htons(type); }
26.555556
86
0.692469
9e70c3b369f80da0cad65b595b841c051f7251eb
41,980
cpp
C++
engine/navigation/navigation_manager.cpp
AugustoMoura/GritEnginePR
0f8303df7f70972036d9b555dffe08cadb473926
[ "MIT" ]
null
null
null
engine/navigation/navigation_manager.cpp
AugustoMoura/GritEnginePR
0f8303df7f70972036d9b555dffe08cadb473926
[ "MIT" ]
null
null
null
engine/navigation/navigation_manager.cpp
AugustoMoura/GritEnginePR
0f8303df7f70972036d9b555dffe08cadb473926
[ "MIT" ]
null
null
null
// // Copyright (c) 2009-2010 Mikko Mononen memon@inside.org // // 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. // // This is a modified version of Sample_TempObstacles.cpp from Recast Demo #define _USE_MATH_DEFINES #include <math.h> #include <stdio.h> #include <string.h> #include <float.h> #include <new> #include "input_geom.h" #include "navigation_manager.h" #include "Recast.h" #include "RecastDebugDraw.h" #include "DetourAssert.h" #include "DetourNavMesh.h" #include "DetourNavMeshBuilder.h" #include "DetourDebugDraw.h" #include "DetourCommon.h" #include "DetourTileCache.h" #include "crowd_manager.h" #include "RecastAlloc.h" #include "RecastAssert.h" #include "fastlz.h" #include "DetourNavMeshQuery.h" #include "DetourCrowd.h" #ifdef WIN32 # define snprintf _snprintf #endif #include"navigation_system.h" // This value specifies how many layers (or "floors") each navmesh tile is expected to have. static const int EXPECTED_LAYERS_PER_TILE = 4; static bool isectSegAABB(const float* sp, const float* sq, const float* amin, const float* amax, float& tmin, float& tmax) { static const float EPS = 1e-6f; float d[3]; rcVsub(d, sq, sp); tmin = 0; // set to -FLT_MAX to get first hit on line tmax = FLT_MAX; // set to max distance ray can travel (for segment) // For all three slabs for (int i = 0; i < 3; i++) { if (fabsf(d[i]) < EPS) { // Ray is parallel to slab. No hit if origin not within slab if (sp[i] < amin[i] || sp[i] > amax[i]) return false; } else { // Compute intersection t value of ray with near and far plane of slab const float ood = 1.0f / d[i]; float t1 = (amin[i] - sp[i]) * ood; float t2 = (amax[i] - sp[i]) * ood; // Make t1 be intersection with near plane, t2 with far plane if (t1 > t2) rcSwap(t1, t2); // Compute the intersection of slab intersections intervals if (t1 > tmin) tmin = t1; if (t2 < tmax) tmax = t2; // Exit with no collision as soon as slab intersection becomes empty if (tmin > tmax) return false; } } return true; } static int calcLayerBufferSize(const int gridWidth, const int gridHeight) { const int headerSize = dtAlign4(sizeof(dtTileCacheLayerHeader)); const int gridSize = gridWidth * gridHeight; return headerSize + gridSize*4; } struct FastLZCompressor : public dtTileCacheCompressor { virtual int maxCompressedSize(const int bufferSize) { return (int)(bufferSize* 1.05f); } virtual dtStatus compress(const unsigned char* buffer, const int bufferSize, unsigned char* compressed, const int /*maxCompressedSize*/, int* compressedSize) { *compressedSize = fastlz_compress((const void *const)buffer, bufferSize, compressed); return DT_SUCCESS; } virtual dtStatus decompress(const unsigned char* compressed, const int compressedSize, unsigned char* buffer, const int maxBufferSize, int* bufferSize) { *bufferSize = fastlz_decompress(compressed, compressedSize, buffer, maxBufferSize); return *bufferSize < 0 ? DT_FAILURE : DT_SUCCESS; } }; struct LinearAllocator : public dtTileCacheAlloc { unsigned char* buffer; size_t capacity; size_t top; size_t high; LinearAllocator(const size_t cap) : buffer(0), capacity(0), top(0), high(0) { resize(cap); } ~LinearAllocator() { dtFree(buffer); } void resize(const size_t cap) { if (buffer) dtFree(buffer); buffer = (unsigned char*)dtAlloc(cap, DT_ALLOC_PERM); capacity = cap; } virtual void reset() { high = dtMax(high, top); top = 0; } virtual void* alloc(const size_t size) { if (!buffer) return 0; if (top+size > capacity) return 0; unsigned char* mem = &buffer[top]; top += size; return mem; } virtual void free(void* /*ptr*/) { // Empty } }; struct MeshProcess : public dtTileCacheMeshProcess { InputGeom* m_geom; inline MeshProcess() : m_geom(0) { } inline void init(InputGeom* geom) { m_geom = geom; } virtual void process(struct dtNavMeshCreateParams* params, unsigned char* polyAreas, unsigned short* polyFlags) { // Update poly flags from areas. for (int i = 0; i < params->polyCount; ++i) { if (polyAreas[i] == DT_TILECACHE_WALKABLE_AREA) polyAreas[i] = SAMPLE_POLYAREA_GROUND; if (polyAreas[i] == SAMPLE_POLYAREA_GROUND || polyAreas[i] == SAMPLE_POLYAREA_GRASS || polyAreas[i] == SAMPLE_POLYAREA_ROAD) { polyFlags[i] = SAMPLE_POLYFLAGS_WALK; } else if (polyAreas[i] == SAMPLE_POLYAREA_WATER) { polyFlags[i] = SAMPLE_POLYFLAGS_SWIM; } else if (polyAreas[i] == SAMPLE_POLYAREA_DOOR) { polyFlags[i] = SAMPLE_POLYFLAGS_WALK | SAMPLE_POLYFLAGS_DOOR; } } // Pass in off-mesh connections. if (m_geom) { params->offMeshConVerts = m_geom->getOffMeshConnectionVerts(); params->offMeshConRad = m_geom->getOffMeshConnectionRads(); params->offMeshConDir = m_geom->getOffMeshConnectionDirs(); params->offMeshConAreas = m_geom->getOffMeshConnectionAreas(); params->offMeshConFlags = m_geom->getOffMeshConnectionFlags(); params->offMeshConUserID = m_geom->getOffMeshConnectionId(); params->offMeshConCount = m_geom->getOffMeshConnectionCount(); } } }; static const int MAX_LAYERS = 32; struct TileCacheData { unsigned char* data; int dataSize; }; struct RasterizationContext { RasterizationContext() : solid(0), triareas(0), lset(0), chf(0), ntiles(0) { memset(tiles, 0, sizeof(TileCacheData)*MAX_LAYERS); } ~RasterizationContext() { rcFreeHeightField(solid); delete [] triareas; rcFreeHeightfieldLayerSet(lset); rcFreeCompactHeightfield(chf); for (int i = 0; i < MAX_LAYERS; ++i) { dtFree(tiles[i].data); tiles[i].data = 0; } } rcHeightfield* solid; unsigned char* triareas; rcHeightfieldLayerSet* lset; rcCompactHeightfield* chf; TileCacheData tiles[MAX_LAYERS]; int ntiles; }; static int rasterizeTileLayers(BuildContext* ctx, InputGeom* geom, const int tx, const int ty, const rcConfig& cfg, TileCacheData* tiles, const int maxTiles) { if (!geom || !geom->getMesh() || !geom->getChunkyMesh()) { ctx->log(RC_LOG_ERROR, "buildTile: Input mesh is not specified."); return 0; } FastLZCompressor comp; RasterizationContext rc; const float* verts = geom->getMesh()->getVerts(); const int nverts = geom->getMesh()->getVertCount(); const rcChunkyTriMesh* chunkyMesh = geom->getChunkyMesh(); // Tile bounds. const float tcs = cfg.tileSize * cfg.cs; rcConfig tcfg; memcpy(&tcfg, &cfg, sizeof(tcfg)); tcfg.bmin[0] = cfg.bmin[0] + tx*tcs; tcfg.bmin[1] = cfg.bmin[1]; tcfg.bmin[2] = cfg.bmin[2] + ty*tcs; tcfg.bmax[0] = cfg.bmin[0] + (tx+1)*tcs; tcfg.bmax[1] = cfg.bmax[1]; tcfg.bmax[2] = cfg.bmin[2] + (ty+1)*tcs; tcfg.bmin[0] -= tcfg.borderSize*tcfg.cs; tcfg.bmin[2] -= tcfg.borderSize*tcfg.cs; tcfg.bmax[0] += tcfg.borderSize*tcfg.cs; tcfg.bmax[2] += tcfg.borderSize*tcfg.cs; // Allocate voxel heightfield where we rasterize our input data to. rc.solid = rcAllocHeightfield(); if (!rc.solid) { ctx->log(RC_LOG_ERROR, "buildNavigation: Out of memory 'solid'."); return 0; } if (!rcCreateHeightfield(ctx, *rc.solid, tcfg.width, tcfg.height, tcfg.bmin, tcfg.bmax, tcfg.cs, tcfg.ch)) { ctx->log(RC_LOG_ERROR, "buildNavigation: Could not create solid heightfield."); return 0; } // Allocate array that can hold triangle flags. // If you have multiple meshes you need to process, allocate // and array which can hold the max number of triangles you need to process. rc.triareas = new unsigned char[chunkyMesh->maxTrisPerChunk]; if (!rc.triareas) { ctx->log(RC_LOG_ERROR, "buildNavigation: Out of memory 'm_triareas' (%d).", chunkyMesh->maxTrisPerChunk); return 0; } float tbmin[2], tbmax[2]; tbmin[0] = tcfg.bmin[0]; tbmin[1] = tcfg.bmin[2]; tbmax[0] = tcfg.bmax[0]; tbmax[1] = tcfg.bmax[2]; int cid[512];// TODO: Make grow when returning too many items. const int ncid = rcGetChunksOverlappingRect(chunkyMesh, tbmin, tbmax, cid, 512); if (!ncid) { return 0; // empty } for (int i = 0; i < ncid; ++i) { const rcChunkyTriMeshNode& node = chunkyMesh->nodes[cid[i]]; const int* tris = &chunkyMesh->tris[node.i*3]; const int ntris = node.n; memset(rc.triareas, 0, ntris*sizeof(unsigned char)); rcMarkWalkableTriangles(ctx, tcfg.walkableSlopeAngle, verts, nverts, tris, ntris, rc.triareas); if (!rcRasterizeTriangles(ctx, verts, nverts, tris, rc.triareas, ntris, *rc.solid, tcfg.walkableClimb)) return 0; } // Once all geometry is rasterized, we do initial pass of filtering to // remove unwanted overhangs caused by the conservative rasterization // as well as filter spans where the character cannot possibly stand. rcFilterLowHangingWalkableObstacles(ctx, tcfg.walkableClimb, *rc.solid); rcFilterLedgeSpans(ctx, tcfg.walkableHeight, tcfg.walkableClimb, *rc.solid); rcFilterWalkableLowHeightSpans(ctx, tcfg.walkableHeight, *rc.solid); rc.chf = rcAllocCompactHeightfield(); if (!rc.chf) { ctx->log(RC_LOG_ERROR, "buildNavigation: Out of memory 'chf'."); return 0; } if (!rcBuildCompactHeightfield(ctx, tcfg.walkableHeight, tcfg.walkableClimb, *rc.solid, *rc.chf)) { ctx->log(RC_LOG_ERROR, "buildNavigation: Could not build compact data."); return 0; } // Erode the walkable area by agent radius. if (!rcErodeWalkableArea(ctx, tcfg.walkableRadius, *rc.chf)) { ctx->log(RC_LOG_ERROR, "buildNavigation: Could not erode."); return 0; } // (Optional) Mark areas. const ConvexVolume* vols = geom->getConvexVolumes(); for (int i = 0; i < geom->getConvexVolumeCount(); ++i) { rcMarkConvexPolyArea(ctx, vols[i].verts, vols[i].nverts, vols[i].hmin, vols[i].hmax, (unsigned char)vols[i].area, *rc.chf); } rc.lset = rcAllocHeightfieldLayerSet(); if (!rc.lset) { ctx->log(RC_LOG_ERROR, "buildNavigation: Out of memory 'lset'."); return 0; } if (!rcBuildHeightfieldLayers(ctx, *rc.chf, tcfg.borderSize, tcfg.walkableHeight, *rc.lset)) { ctx->log(RC_LOG_ERROR, "buildNavigation: Could not build heighfield layers."); return 0; } rc.ntiles = 0; for (int i = 0; i < rcMin(rc.lset->nlayers, MAX_LAYERS); ++i) { TileCacheData* tile = &rc.tiles[rc.ntiles++]; const rcHeightfieldLayer* layer = &rc.lset->layers[i]; // Store header dtTileCacheLayerHeader header; header.magic = DT_TILECACHE_MAGIC; header.version = DT_TILECACHE_VERSION; // Tile layer location in the navmesh. header.tx = tx; header.ty = ty; header.tlayer = i; dtVcopy(header.bmin, layer->bmin); dtVcopy(header.bmax, layer->bmax); // Tile info. header.width = (unsigned char)layer->width; header.height = (unsigned char)layer->height; header.minx = (unsigned char)layer->minx; header.maxx = (unsigned char)layer->maxx; header.miny = (unsigned char)layer->miny; header.maxy = (unsigned char)layer->maxy; header.hmin = (unsigned short)layer->hmin; header.hmax = (unsigned short)layer->hmax; dtStatus status = dtBuildTileCacheLayer(&comp, &header, layer->heights, layer->areas, layer->cons, &tile->data, &tile->dataSize); if (dtStatusFailed(status)) { return 0; } } // Transfer ownsership of tile data from build context to the caller. int n = 0; for (int i = 0; i < rcMin(rc.ntiles, maxTiles); ++i) { tiles[n++] = rc.tiles[i]; rc.tiles[i].data = 0; rc.tiles[i].dataSize = 0; } return n; } void drawTiles(duDebugDraw* dd, dtTileCache* tc) { unsigned int fcol[6]; float bmin[3], bmax[3]; for (int i = 0; i < tc->getTileCount(); ++i) { const dtCompressedTile* tile = tc->getTile(i); if (!tile->header) continue; tc->calcTightTileBounds(tile->header, bmin, bmax); const unsigned int col = duIntToCol(i,64); duCalcBoxColors(fcol, col, col); duDebugDrawBox(dd, bmin[0],bmin[1],bmin[2], bmax[0],bmax[1],bmax[2], fcol); } for (int i = 0; i < tc->getTileCount(); ++i) { const dtCompressedTile* tile = tc->getTile(i); if (!tile->header) continue; tc->calcTightTileBounds(tile->header, bmin, bmax); const unsigned int col = duIntToCol(i,255); const float pad = tc->getParams()->cs * 0.1f; duDebugDrawBoxWire(dd, bmin[0]-pad,bmin[1]-pad,bmin[2]-pad, bmax[0]+pad,bmax[1]+pad,bmax[2]+pad, col, 2.0f); } } enum DrawDetailType { DRAWDETAIL_AREAS, DRAWDETAIL_REGIONS, DRAWDETAIL_CONTOURS, DRAWDETAIL_MESH, }; void drawDetail(duDebugDraw* dd, dtTileCache* tc, const int tx, const int ty, int type) { struct TileCacheBuildContext { inline TileCacheBuildContext(struct dtTileCacheAlloc* a) : layer(0), lcset(0), lmesh(0), alloc(a) {} inline ~TileCacheBuildContext() { purge(); } void purge() { dtFreeTileCacheLayer(alloc, layer); layer = 0; dtFreeTileCacheContourSet(alloc, lcset); lcset = 0; dtFreeTileCachePolyMesh(alloc, lmesh); lmesh = 0; } struct dtTileCacheLayer* layer; struct dtTileCacheContourSet* lcset; struct dtTileCachePolyMesh* lmesh; struct dtTileCacheAlloc* alloc; }; dtCompressedTileRef tiles[MAX_LAYERS]; const int ntiles = tc->getTilesAt(tx,ty,tiles,MAX_LAYERS); dtTileCacheAlloc* talloc = tc->getAlloc(); dtTileCacheCompressor* tcomp = tc->getCompressor(); const dtTileCacheParams* params = tc->getParams(); for (int i = 0; i < ntiles; ++i) { const dtCompressedTile* tile = tc->getTileByRef(tiles[i]); talloc->reset(); TileCacheBuildContext bc(talloc); const int walkableClimbVx = (int)(params->walkableClimb / params->ch); dtStatus status; // Decompress tile layer data. status = dtDecompressTileCacheLayer(talloc, tcomp, tile->data, tile->dataSize, &bc.layer); if (dtStatusFailed(status)) return; if (type == DRAWDETAIL_AREAS) { duDebugDrawTileCacheLayerAreas(dd, *bc.layer, params->cs, params->ch); continue; } // Build navmesh status = dtBuildTileCacheRegions(talloc, *bc.layer, walkableClimbVx); if (dtStatusFailed(status)) return; if (type == DRAWDETAIL_REGIONS) { duDebugDrawTileCacheLayerRegions(dd, *bc.layer, params->cs, params->ch); continue; } bc.lcset = dtAllocTileCacheContourSet(talloc); if (!bc.lcset) return; status = dtBuildTileCacheContours(talloc, *bc.layer, walkableClimbVx, params->maxSimplificationError, *bc.lcset); if (dtStatusFailed(status)) return; if (type == DRAWDETAIL_CONTOURS) { duDebugDrawTileCacheContours(dd, *bc.lcset, tile->header->bmin, params->cs, params->ch); continue; } bc.lmesh = dtAllocTileCachePolyMesh(talloc); if (!bc.lmesh) return; status = dtBuildTileCachePolyMesh(talloc, *bc.lcset, *bc.lmesh); if (dtStatusFailed(status)) return; if (type == DRAWDETAIL_MESH) { duDebugDrawTileCachePolyMesh(dd, *bc.lmesh, tile->header->bmin, params->cs, params->ch); continue; } } } void drawDetailOverlay(const dtTileCache* tc, const int tx, const int ty, double* proj, double* model, int* view) { dtCompressedTileRef tiles[MAX_LAYERS]; const int ntiles = tc->getTilesAt(tx,ty,tiles,MAX_LAYERS); if (!ntiles) return; (void) model; (void) view; (void) proj; //const int rawSize = calcLayerBufferSize(tc->getParams()->width, tc->getParams()->height); //char text[128]; for (int i = 0; i < ntiles; ++i) { const dtCompressedTile* tile = tc->getTileByRef(tiles[i]); float pos[3]; pos[0] = (tile->header->bmin[0]+tile->header->bmax[0])/2.0f; pos[1] = tile->header->bmin[1]; pos[2] = (tile->header->bmin[2]+tile->header->bmax[2])/2.0f; (void) pos; //-- TODO: replace this using Ogre "MoveableTextOverlay" //GLdouble x, y, z; //if (gluProject((GLdouble)pos[0], (GLdouble)pos[1], (GLdouble)pos[2], // model, proj, view, &x, &y, &z)) //{ // snprintf(text,128,"(%d,%d)/%d", tile->header->tx,tile->header->ty,tile->header->tlayer); // imguiDrawText((int)x, (int)y-25, IMGUI_ALIGN_CENTER, text, imguiRGBA(0,0,0,220)); // snprintf(text,128,"Compressed: %.1f kB", tile->dataSize/1024.0f); // imguiDrawText((int)x, (int)y-45, IMGUI_ALIGN_CENTER, text, imguiRGBA(0,0,0,128)); // snprintf(text,128,"Raw:%.1fkB", rawSize/1024.0f); // imguiDrawText((int)x, (int)y-65, IMGUI_ALIGN_CENTER, text, imguiRGBA(0,0,0,128)); //} } } dtObstacleRef hitTestObstacle(const dtTileCache* tc, const float* sp, const float* sq) { float tmin = FLT_MAX; const dtTileCacheObstacle* obmin = 0; for (int i = 0; i < tc->getObstacleCount(); ++i) { const dtTileCacheObstacle* ob = tc->getObstacle(i); if (ob->state == DT_OBSTACLE_EMPTY) continue; float bmin[3], bmax[3], t0,t1; tc->getObstacleBounds(ob, bmin,bmax); if (isectSegAABB(sp,sq, bmin,bmax, t0,t1)) { if (t0 < tmin) { tmin = t0; obmin = ob; } } } return tc->getObstacleRef(obmin); } void drawObstacles(duDebugDraw* dd, const dtTileCache* tc) { // Draw obstacles for (int i = 0; i < tc->getObstacleCount(); ++i) { const dtTileCacheObstacle* ob = tc->getObstacle(i); if (ob->state == DT_OBSTACLE_EMPTY) continue; float bmin[3], bmax[3]; tc->getObstacleBounds(ob, bmin,bmax); unsigned int col = 0; if (ob->state == DT_OBSTACLE_PROCESSING) col = duRGBA(255,255,0,128); else if (ob->state == DT_OBSTACLE_PROCESSED) col = duRGBA(255,192,0,192); else if (ob->state == DT_OBSTACLE_REMOVING) col = duRGBA(220,0,0,128); duDebugDrawCylinder(dd, bmin[0],bmin[1],bmin[2], bmax[0],bmax[1],bmax[2], col); duDebugDrawCylinderWire(dd, bmin[0],bmin[1],bmin[2], bmax[0],bmax[1],bmax[2], duDarkenCol(col), 2); } } NavigationManager::NavigationManager() : m_geom(nullptr), m_navMesh(nullptr), m_navMeshDrawFlags(DU_DRAWNAVMESH_OFFMESHCONS | DU_DRAWNAVMESH_CLOSEDLIST), m_ctx(nullptr), m_keepInterResults(false), m_tileCache(0), m_cacheBuildTimeMs(0), m_cacheCompressedSize(0), m_cacheRawSize(0), m_cacheLayerCount(0), m_cacheBuildMemUsage(0), m_drawMode(DRAWMODE_NAVMESH), m_maxTiles(0), m_maxPolysPerTile(0), m_tileSize(48) { m_navQuery = dtAllocNavMeshQuery(); m_crowd = dtAllocCrowd(); resetCommonSettings(); m_talloc = new LinearAllocator(32000); m_tcomp = new FastLZCompressor; m_tmproc = new MeshProcess; m_crowdTool = new CrowdTool(); } NavigationManager::~NavigationManager() { dtFreeNavMeshQuery(m_navQuery); dtFreeNavMesh(m_navMesh); dtFreeCrowd(m_crowd); m_navMesh = 0; dtFreeTileCache(m_tileCache); } void NavigationManager::updateMaxTiles() { if (m_geom) { const float* bmin = m_geom->getNavMeshBoundsMin(); const float* bmax = m_geom->getNavMeshBoundsMax(); // char text[64]; int gw = 0, gh = 0; rcCalcGridSize(bmin, bmax, m_cellSize, &gw, &gh); const int ts = (int)m_tileSize; const int tw = (gw + ts-1) / ts; const int th = (gh + ts-1) / ts; // Max tiles and max polys affect how the tile IDs are caculated. // There are 22 bits available for identifying a tile and a polygon. int tileBits = rcMin((int)dtIlog2(dtNextPow2(tw*th*EXPECTED_LAYERS_PER_TILE)), 14); if (tileBits > 14) tileBits = 14; int polyBits = 22 - tileBits; m_maxTiles = 1 << tileBits; m_maxPolysPerTile = 1 << polyBits; } else { m_maxTiles = 0; m_maxPolysPerTile = 0; } } // this is a modified function of Recast Debug Draw // removed tile bounds and points static void drawMeshTilex(duDebugDraw* dd, const dtNavMesh& mesh, const dtNavMeshQuery* query, const dtMeshTile* tile, unsigned char flags) { dtPolyRef base = mesh.getPolyRefBase(tile); int tileNum = mesh.decodePolyIdTile(base); dd->depthMask(false); dd->begin(DU_DRAW_TRIS); for (int i = 0; i < tile->header->polyCount; ++i) { const dtPoly* p = &tile->polys[i]; if (p->getType() == DT_POLYTYPE_OFFMESH_CONNECTION) // Skip off-mesh links. continue; const dtPolyDetail* pd = &tile->detailMeshes[i]; unsigned int col; if (query && query->isInClosedList(base | (dtPolyRef)i)) col = duRGBA(255, 196, 0, 64); else { if (flags & DU_DRAWNAVMESH_COLOR_TILES) { col = duIntToCol(tileNum, 128); } else { if (p->getArea() == 0) // Treat zero area type as default. col = duRGBA(0, 192, 255, 64); else col = duIntToCol(p->getArea(), 64); } } for (int j = 0; j < pd->triCount; ++j) { const unsigned char* t = &tile->detailTris[(pd->triBase + j) * 4]; for (int k = 0; k < 3; ++k) { if (t[k] < p->vertCount) dd->vertex(&tile->verts[p->verts[t[k]] * 3], col); else dd->vertex(&tile->detailVerts[(pd->vertBase + t[k] - p->vertCount) * 3], col); } } } dd->end(); if (flags & DU_DRAWNAVMESH_OFFMESHCONS) { dd->begin(DU_DRAW_LINES, 2.0f); for (int i = 0; i < tile->header->polyCount; ++i) { const dtPoly* p = &tile->polys[i]; if (p->getType() != DT_POLYTYPE_OFFMESH_CONNECTION) // Skip regular polys. continue; unsigned int col, col2; if (query && query->isInClosedList(base | (dtPolyRef)i)) col = duRGBA(255, 196, 0, 220); else col = duDarkenCol(duIntToCol(p->getArea(), 220)); const dtOffMeshConnection* con = &tile->offMeshCons[i - tile->header->offMeshBase]; const float* va = &tile->verts[p->verts[0] * 3]; const float* vb = &tile->verts[p->verts[1] * 3]; // Check to see if start and end end-points have links. bool startSet = false; bool endSet = false; for (unsigned int k = p->firstLink; k != DT_NULL_LINK; k = tile->links[k].next) { if (tile->links[k].edge == 0) startSet = true; if (tile->links[k].edge == 1) endSet = true; } // End points and their on-mesh locations. dd->vertex(va[0], va[1], va[2], col); dd->vertex(con->pos[0], con->pos[1], con->pos[2], col); col2 = startSet ? col : duRGBA(220, 32, 16, 196); duAppendCircle(dd, con->pos[0], con->pos[1] + 0.1f, con->pos[2], con->rad, col2); dd->vertex(vb[0], vb[1], vb[2], col); dd->vertex(con->pos[3], con->pos[4], con->pos[5], col); col2 = endSet ? col : duRGBA(220, 32, 16, 196); duAppendCircle(dd, con->pos[3], con->pos[4] + 0.1f, con->pos[5], con->rad, col2); // End point vertices. dd->vertex(con->pos[0], con->pos[1], con->pos[2], duRGBA(0, 48, 64, 196)); dd->vertex(con->pos[0], con->pos[1] + 0.2f, con->pos[2], duRGBA(0, 48, 64, 196)); dd->vertex(con->pos[3], con->pos[4], con->pos[5], duRGBA(0, 48, 64, 196)); dd->vertex(con->pos[3], con->pos[4] + 0.2f, con->pos[5], duRGBA(0, 48, 64, 196)); // Connection arc. duAppendArc(dd, con->pos[0], con->pos[1], con->pos[2], con->pos[3], con->pos[4], con->pos[5], 0.25f, (con->flags & 1) ? 0.6f : 0, 0.6f, col); } dd->end(); } dd->depthMask(true); } void duDebugDrawNavMeshx(duDebugDraw* dd, const dtNavMesh& mesh, unsigned char flags) { if (!dd) return; for (int i = 0; i < mesh.getMaxTiles(); ++i) { const dtMeshTile* tile = mesh.getTile(i); if (!tile->header) continue; drawMeshTilex(dd, mesh, 0, tile, flags); } } void NavigationManager::render() { // when loading from a navmesh file, no m_geom is loaded bool navmesh_from_disk = false; if (!m_geom || !m_geom->getMesh()) { navmesh_from_disk = true; //return; } DebugDrawGL dd; // const float texScale = 1.0f / (m_cellSize * 10.0f); if (!navmesh_from_disk) { if (m_drawMode != DRAWMODE_NAVMESH_TRANS && NavSysDebug::ShowOffmeshConnections && NavSysDebug::RedrawOffmeshConnections) { NavSysDebug::DebugObject = NavSysDebug::OffmeshConectionsObject; NavSysDebug::DebugObject->clear(); m_geom->drawOffMeshConnections(&dd); NavSysDebug::RedrawOffmeshConnections = false; } // Draw bounds const float* bmin = m_geom->getNavMeshBoundsMin(); const float* bmax = m_geom->getNavMeshBoundsMax(); if (NavSysDebug::ShowBounds && NavSysDebug::RedrawBounds) { NavSysDebug::DebugObject = NavSysDebug::BoundsObject; NavSysDebug::DebugObject->clear(); duDebugDrawBoxWire(&dd, bmin[0], bmin[1], bmin[2], bmax[0], bmax[1], bmax[2], duRGBA(255, 255, 255, 128), 1.0f); NavSysDebug::RedrawBounds = false; } if (NavSysDebug::ShowTilingGrid && NavSysDebug::RedrawTilingGrid) { // Tiling grid. int gw = 0, gh = 0; rcCalcGridSize(bmin, bmax, m_cellSize, &gw, &gh); const int tw = (gw + (int)m_tileSize - 1) / (int)m_tileSize; const int th = (gh + (int)m_tileSize - 1) / (int)m_tileSize; const float s = m_tileSize*m_cellSize; NavSysDebug::DebugObject = NavSysDebug::TilingGridObject; NavSysDebug::DebugObject->clear(); duDebugDrawGridXZ(&dd, bmin[0], bmin[1], bmin[2], tw, th, s, duRGBA(0, 0, 0, 64), 1.0f); } // TODO if (NavSysDebug::ShowConvexVolumes && NavSysDebug::RedrawConvexVolumes) { NavSysDebug::DebugObject = NavSysDebug::ConvexVolumeObjects; NavSysDebug::DebugObject->clear(); m_geom->drawConvexVolumes(&dd); // temporary convex volume drawConvexVolume(&dd); NavSysDebug::RedrawConvexVolumes = false; } m_crowdTool->render(); } //if (m_tileCache && m_drawMode == DRAWMODE_CACHE_BOUNDS) // drawTiles(&dd, m_tileCache); if (m_tileCache && NavSysDebug::ShowObstacles && NavSysDebug::RedrawObstacles) { NavSysDebug::DebugObject = NavSysDebug::ObstaclesObject; NavSysDebug::DebugObject->clear(); drawObstacles(&dd, m_tileCache); NavSysDebug::RedrawObstacles = false; } if (NavSysDebug::ShowNavmesh && NavSysDebug::RedrawNavmesh) { NavSysDebug::DebugObject = NavSysDebug::NavmeshObject; NavSysDebug::DebugObject->clear(); if (m_navMesh && m_navQuery && (m_drawMode == DRAWMODE_NAVMESH || m_drawMode == DRAWMODE_NAVMESH_TRANS || m_drawMode == DRAWMODE_NAVMESH_BVTREE || m_drawMode == DRAWMODE_NAVMESH_NODES || m_drawMode == DRAWMODE_NAVMESH_PORTALS || m_drawMode == DRAWMODE_NAVMESH_INVIS)) { if (m_drawMode != DRAWMODE_NAVMESH_INVIS) //--duDebugDrawNavMeshWithClosedList(&dd, *m_navMesh, *m_navQuery, m_navMeshDrawFlags|DU_DRAWNAVMESH_COLOR_TILES); //++ duDebugDrawNavMeshx(&dd, *m_navMesh, m_navMeshDrawFlags | DU_DRAWNAVMESH_COLOR_TILES); /* if (m_drawMode == DRAWMODE_NAVMESH_BVTREE) duDebugDrawNavMeshBVTree(&dd, *m_navMesh); if (m_drawMode == DRAWMODE_NAVMESH_PORTALS) duDebugDrawNavMeshPortals(&dd, *m_navMesh); if (m_drawMode == DRAWMODE_NAVMESH_NODES) duDebugDrawNavMeshNodes(&dd, *m_navQuery); */ //duDebugDrawNavMeshPolysWithFlags(&dd, *m_navMesh, SAMPLE_POLYFLAGS_DISABLED, duRGBA(0,0,0,128)); } NavSysDebug::RedrawNavmesh = false; } } void NavigationManager::renderCachedTile(const int tx, const int ty, const int type) { DebugDrawGL dd; if (m_tileCache) drawDetail(&dd,m_tileCache,tx,ty,type); } void NavigationManager::renderCachedTileOverlay(const int tx, const int ty, double* proj, double* model, int* view) { if (m_tileCache) drawDetailOverlay(m_tileCache, tx, ty, proj, model, view); } void NavigationManager::changeMesh(class InputGeom* geom) { m_geom = geom; dtFreeTileCache(m_tileCache); m_tileCache = 0; dtFreeNavMesh(m_navMesh); m_navMesh = 0; } void NavigationManager::addTempObstacle(const float* pos) { if (!m_tileCache) return; float p[3]; dtVcopy(p, pos); p[1] -= 0.5f; m_tileCache->addObstacle(p, 1.0f, 2.0f, 0); } void NavigationManager::removeTempObstacle(const float* sp, const float* sq) { if (!m_tileCache) return; dtObstacleRef ref = hitTestObstacle(m_tileCache, sp, sq); m_tileCache->removeObstacle(ref); } void NavigationManager::clearAllTempObstacles() { if (!m_tileCache) return; for (int i = 0; i < m_tileCache->getObstacleCount(); ++i) { const dtTileCacheObstacle* ob = m_tileCache->getObstacle(i); if (ob->state == DT_OBSTACLE_EMPTY) continue; m_tileCache->removeObstacle(m_tileCache->getObstacleRef(ob)); } } bool NavigationManager::build() { dtStatus status; if (!m_geom || !m_geom->getMesh()) { m_ctx->log(RC_LOG_ERROR, "buildTiledNavigation: No vertices and triangles."); return false; } m_tmproc->init(m_geom); // Init cache const float* bmin = m_geom->getNavMeshBoundsMin(); const float* bmax = m_geom->getNavMeshBoundsMax(); int gw = 0, gh = 0; rcCalcGridSize(bmin, bmax, m_cellSize, &gw, &gh); const int ts = (int)m_tileSize; const int tw = (gw + ts-1) / ts; const int th = (gh + ts-1) / ts; // Generation params. rcConfig cfg; memset(&cfg, 0, sizeof(cfg)); cfg.cs = m_cellSize; cfg.ch = m_cellHeight; cfg.walkableSlopeAngle = m_agentMaxSlope; cfg.walkableHeight = (int)ceilf(m_agentHeight / cfg.ch); cfg.walkableClimb = (int)floorf(m_agentMaxClimb / cfg.ch); cfg.walkableRadius = (int)ceilf(m_agentRadius / cfg.cs); cfg.maxEdgeLen = (int)(m_edgeMaxLen / m_cellSize); cfg.maxSimplificationError = m_edgeMaxError; cfg.minRegionArea = (int)rcSqr(m_regionMinSize); // Note: area = size*size cfg.mergeRegionArea = (int)rcSqr(m_regionMergeSize); // Note: area = size*size cfg.maxVertsPerPoly = (int)m_vertsPerPoly; cfg.tileSize = (int)m_tileSize; cfg.borderSize = cfg.walkableRadius + 3; // Reserve enough padding. cfg.width = cfg.tileSize + cfg.borderSize*2; cfg.height = cfg.tileSize + cfg.borderSize*2; cfg.detailSampleDist = m_detailSampleDist < 0.9f ? 0 : m_cellSize * m_detailSampleDist; cfg.detailSampleMaxError = m_cellHeight * m_detailSampleMaxError; rcVcopy(cfg.bmin, bmin); rcVcopy(cfg.bmax, bmax); // Tile cache params. dtTileCacheParams tcparams; memset(&tcparams, 0, sizeof(tcparams)); rcVcopy(tcparams.orig, bmin); tcparams.cs = m_cellSize; tcparams.ch = m_cellHeight; tcparams.width = (int)m_tileSize; tcparams.height = (int)m_tileSize; tcparams.walkableHeight = m_agentHeight; tcparams.walkableRadius = m_agentRadius; tcparams.walkableClimb = m_agentMaxClimb; tcparams.maxSimplificationError = m_edgeMaxError; tcparams.maxTiles = tw*th*EXPECTED_LAYERS_PER_TILE; tcparams.maxObstacles = 128; dtFreeTileCache(m_tileCache); m_tileCache = dtAllocTileCache(); if (!m_tileCache) { m_ctx->log(RC_LOG_ERROR, "buildTiledNavigation: Could not allocate tile cache."); return false; } status = m_tileCache->init(&tcparams, m_talloc, m_tcomp, m_tmproc); if (dtStatusFailed(status)) { m_ctx->log(RC_LOG_ERROR, "buildTiledNavigation: Could not init tile cache."); return false; } dtFreeNavMesh(m_navMesh); m_navMesh = dtAllocNavMesh(); if (!m_navMesh) { m_ctx->log(RC_LOG_ERROR, "buildTiledNavigation: Could not allocate navmesh."); return false; } dtNavMeshParams params; memset(&params, 0, sizeof(params)); rcVcopy(params.orig, bmin); params.tileWidth = m_tileSize*m_cellSize; params.tileHeight = m_tileSize*m_cellSize; params.maxTiles = m_maxTiles; params.maxPolys = m_maxPolysPerTile; status = m_navMesh->init(&params); if (dtStatusFailed(status)) { m_ctx->log(RC_LOG_ERROR, "buildTiledNavigation: Could not init navmesh."); return false; } status = m_navQuery->init(m_navMesh, 2048); if (dtStatusFailed(status)) { m_ctx->log(RC_LOG_ERROR, "buildTiledNavigation: Could not init Detour navmesh query"); return false; } // Preprocess tiles. m_ctx->resetTimers(); m_cacheLayerCount = 0; m_cacheCompressedSize = 0; m_cacheRawSize = 0; for (int y = 0; y < th; ++y) { for (int x = 0; x < tw; ++x) { TileCacheData tiles[MAX_LAYERS]; memset(tiles, 0, sizeof(tiles)); int ntiles = rasterizeTileLayers(m_ctx, m_geom, x, y, cfg, tiles, MAX_LAYERS); for (int i = 0; i < ntiles; ++i) { TileCacheData* tile = &tiles[i]; status = m_tileCache->addTile(tile->data, tile->dataSize, DT_COMPRESSEDTILE_FREE_DATA, 0); if (dtStatusFailed(status)) { dtFree(tile->data); tile->data = 0; continue; } m_cacheLayerCount++; m_cacheCompressedSize += tile->dataSize; m_cacheRawSize += calcLayerBufferSize(tcparams.width, tcparams.height); } } } // Build initial meshes m_ctx->startTimer(RC_TIMER_TOTAL); for (int y = 0; y < th; ++y) for (int x = 0; x < tw; ++x) m_tileCache->buildNavMeshTilesAt(x,y, m_navMesh); m_ctx->stopTimer(RC_TIMER_TOTAL); m_cacheBuildTimeMs = m_ctx->getAccumulatedTime(RC_TIMER_TOTAL)/1000.0f; m_cacheBuildMemUsage = m_talloc->high; //-- /* const dtNavMesh* nav = m_navMesh; int navmeshMemUsage = 0; for (int i = 0; i < nav->getMaxTiles(); ++i) { const dtMeshTile* tile = nav->getTile(i); if (tile->header) navmeshMemUsage += tile->dataSize; } printf("navmeshMemUsage = %.1f kB", navmeshMemUsage/1024.0f); */ m_crowdTool->init(this); return true; } void NavigationManager::update(const float dt) { m_crowdTool->update(dt); if (!m_navMesh) return; if (!m_tileCache) return; m_tileCache->update(dt, m_navMesh); } void NavigationManager::getTilePos(const float* pos, int& tx, int& ty) { if (!m_geom) return; const float* bmin = m_geom->getNavMeshBoundsMin(); const float ts = m_tileSize*m_cellSize; tx = (int)((pos[0] - bmin[0]) / ts); ty = (int)((pos[2] - bmin[2]) / ts); } static const int TILECACHESET_MAGIC = 'T'<<24 | 'S'<<16 | 'E'<<8 | 'T'; //'TSET'; static const int TILECACHESET_VERSION = 1; struct TileCacheSetHeader { int magic; int version; int numTiles; dtNavMeshParams meshParams; dtTileCacheParams cacheParams; }; struct TileCacheTileHeader { dtCompressedTileRef tileRef; int dataSize; }; bool NavigationManager::saveAll(const char* path) { if (!m_tileCache) return false; FILE* fp = fopen(path, "wb"); if (!fp) return false; // Store header. TileCacheSetHeader header; header.magic = TILECACHESET_MAGIC; header.version = TILECACHESET_VERSION; header.numTiles = 0; for (int i = 0; i < m_tileCache->getTileCount(); ++i) { const dtCompressedTile* tile = m_tileCache->getTile(i); if (!tile || !tile->header || !tile->dataSize) continue; header.numTiles++; } memcpy(&header.cacheParams, m_tileCache->getParams(), sizeof(dtTileCacheParams)); memcpy(&header.meshParams, m_navMesh->getParams(), sizeof(dtNavMeshParams)); fwrite(&header, sizeof(TileCacheSetHeader), 1, fp); // Store tiles. for (int i = 0; i < m_tileCache->getTileCount(); ++i) { const dtCompressedTile* tile = m_tileCache->getTile(i); if (!tile || !tile->header || !tile->dataSize) continue; TileCacheTileHeader tileHeader; tileHeader.tileRef = m_tileCache->getTileRef(tile); tileHeader.dataSize = tile->dataSize; fwrite(&tileHeader, sizeof(tileHeader), 1, fp); fwrite(tile->data, tile->dataSize, 1, fp); } fclose(fp); return true; } bool NavigationManager::loadAll(const char* path) { FILE* fp = fopen(path, "rb"); if (!fp) return false; // Read header. TileCacheSetHeader header; size_t bytes = fread(&header, sizeof(TileCacheSetHeader), 1, fp); APP_ASSERT(bytes != sizeof(TileCacheSetHeader)); if (header.magic != TILECACHESET_MAGIC) { fclose(fp); return false; } if (header.version != TILECACHESET_VERSION) { fclose(fp); return false; } m_navMesh = dtAllocNavMesh(); if (!m_navMesh) { fclose(fp); return false; } dtStatus status = m_navMesh->init(&header.meshParams); if (dtStatusFailed(status)) { fclose(fp); return false; } m_tileCache = dtAllocTileCache(); if (!m_tileCache) { fclose(fp); return false; } status = m_tileCache->init(&header.cacheParams, m_talloc, m_tcomp, m_tmproc); if (dtStatusFailed(status)) { fclose(fp); return false; } // Read tiles. for (int i = 0; i < header.numTiles; ++i) { TileCacheTileHeader tileHeader; bytes = fread(&tileHeader, sizeof(tileHeader), 1, fp); APP_ASSERT(bytes != sizeof(tileHeader)); if (!tileHeader.tileRef || !tileHeader.dataSize) break; unsigned char* data = (unsigned char*)dtAlloc(tileHeader.dataSize, DT_ALLOC_PERM); if (!data) break; memset(data, 0, tileHeader.dataSize); bytes = fread(data, tileHeader.dataSize, 1, fp); APP_ASSERT((long long)(bytes) != tileHeader.dataSize); dtCompressedTileRef tile = 0; m_tileCache->addTile(data, tileHeader.dataSize, DT_COMPRESSEDTILE_FREE_DATA, &tile); if (tile) m_tileCache->buildNavMeshTile(tile, m_navMesh); } fclose(fp); return true; } void NavigationManager::resetCommonSettings() { m_cellSize = 0.3f; m_cellHeight = 0.2f; m_agentHeight = 2.0f; m_agentRadius = 0.6f; m_agentMaxClimb = 0.9f; m_agentMaxSlope = 45.0f; m_regionMinSize = 8; m_regionMergeSize = 20; m_edgeMaxLen = 12.0f; m_edgeMaxError = 1.3f; m_vertsPerPoly = 6.0f; m_detailSampleDist = 6.0f; m_detailSampleMaxError = 1.0f; m_partitionType = SAMPLE_PARTITION_WATERSHED; } const float* NavigationManager::getBoundsMin() { if (!m_geom) return 0; return m_geom->getNavMeshBoundsMin(); } const float* NavigationManager::getBoundsMax() { if (!m_geom) return 0; return m_geom->getNavMeshBoundsMax(); } void NavigationManager::step() { } bool NavigationManager::load(const char* path) { updateMaxTiles(); dtFreeNavMesh(m_navMesh); dtFreeTileCache(m_tileCache); bool result = loadAll(path); m_navQuery->init(m_navMesh, 2048); m_crowdTool->init(this); return result; } void NavigationManager::freeNavmesh() { dtFreeTileCache(m_tileCache); m_tileCache = 0; dtFreeNavMesh(m_navMesh); m_navMesh = 0; } // CONVEX VOLUMES: (from Convex Volume Tool) // Returns true if 'c' is left of line 'a'-'b'. inline bool left(const float* a, const float* b, const float* c) { const float u1 = b[0] - a[0]; const float v1 = b[2] - a[2]; const float u2 = c[0] - a[0]; const float v2 = c[2] - a[2]; return u1 * v2 - v1 * u2 < 0; } // Returns true if 'a' is more lower-left than 'b'. inline bool cmppt(const float* a, const float* b) { if (a[0] < b[0]) return true; if (a[0] > b[0]) return false; if (a[2] < b[2]) return true; if (a[2] > b[2]) return false; return false; } // Calculates convex hull on xz-plane of points on 'pts', // stores the indices of the resulting hull in 'out' and // returns number of points on hull. static int convexhull(const float* pts, int npts, int* out) { // Find lower-leftmost point. int hull = 0; for (int i = 1; i < npts; ++i) if (cmppt(&pts[i * 3], &pts[hull * 3])) hull = i; // Gift wrap hull. int endpt = 0; int i = 0; do { out[i++] = hull; endpt = 0; for (int j = 1; j < npts; ++j) if (hull == endpt || left(&pts[hull * 3], &pts[endpt * 3], &pts[j * 3])) endpt = j; hull = endpt; } while (endpt != out[0]); return i; } static int pointInPoly(int nvert, const float* verts, const float* p) { int i, j, c = 0; for (i = 0, j = nvert - 1; i < nvert; j = i++) { const float* vi = &verts[i * 3]; const float* vj = &verts[j * 3]; if (((vi[2] > p[2]) != (vj[2] > p[2])) && (p[0] < (vj[0] - vi[0]) * (p[2] - vi[2]) / (vj[2] - vi[2]) + vi[0])) c = !c; } return c; } void NavigationManager::removeConvexVolume(float* p) { if (!m_geom || !m_geom->getMesh()) { return; } int nearestIndex = -1; const ConvexVolume* vols = m_geom->getConvexVolumes(); for (int i = 0; i < m_geom->getConvexVolumeCount(); ++i) { if (pointInPoly(vols[i].nverts, vols[i].verts, p) && p[1] >= vols[i].hmin && p[1] <= vols[i].hmax) { nearestIndex = i; } } // If end point close enough, delete it. if (nearestIndex != -1) { m_geom->deleteConvexVolume(nearestIndex); } } void NavigationManager::createConvexVolume(float* p) { if (!m_geom || !m_geom->getMesh()) { return; } // If clicked on that last pt, create the shape. if (m_npts && rcVdistSqr(p, &m_pts[(m_npts - 1) * 3]) < rcSqr(0.2f)) { if (m_nhull > 2) { // Create shape. float verts[MAX_PTS * 3]; for (int i = 0; i < m_nhull; ++i) rcVcopy(&verts[i * 3], &m_pts[m_hull[i] * 3]); float minh = FLT_MAX, maxh = 0; for (int i = 0; i < m_nhull; ++i) minh = rcMin(minh, verts[i * 3 + 1]); minh -= m_boxDescent; maxh = minh + m_boxHeight; if (m_polyOffset > 0.01f) { float offset[MAX_PTS * 2 * 3]; int noffset = rcOffsetPoly(verts, m_nhull, m_polyOffset, offset, MAX_PTS * 2); if (noffset > 0) m_geom->addConvexVolume(offset, noffset, minh, maxh, (unsigned char)m_areaType); } else { m_geom->addConvexVolume(verts, m_nhull, minh, maxh, (unsigned char)m_areaType); } } m_npts = 0; m_nhull = 0; } else { // Add new point if (m_npts < MAX_PTS) { rcVcopy(&m_pts[m_npts * 3], p); m_npts++; // Update hull. if (m_npts > 1) m_nhull = convexhull(m_pts, m_npts, m_hull); else m_nhull = 0; } } } // Temporary convex volume void NavigationManager::drawConvexVolume(DebugDrawGL* dd) { // Find height extents of the shape. float minh = FLT_MAX, maxh = 0; for (int i = 0; i < m_npts; ++i) minh = rcMin(minh, m_pts[i * 3 + 1]); minh -= m_boxDescent; maxh = minh + m_boxHeight; dd->begin(DU_DRAW_POINTS, 4.0f); for (int i = 0; i < m_npts; ++i) { unsigned int col = duRGBA(255, 255, 255, 255); if (i == m_npts - 1) col = duRGBA(240, 32, 16, 255); dd->vertex(m_pts[i * 3 + 0], m_pts[i * 3 + 1] + 0.1f, m_pts[i * 3 + 2], col); } dd->end(); dd->begin(DU_DRAW_LINES, 2.0f); for (int i = 0, j = m_nhull - 1; i < m_nhull; j = i++) { const float* vi = &m_pts[m_hull[j] * 3]; const float* vj = &m_pts[m_hull[i] * 3]; dd->vertex(vj[0], minh, vj[2], duRGBA(255, 255, 255, 64)); dd->vertex(vi[0], minh, vi[2], duRGBA(255, 255, 255, 64)); dd->vertex(vj[0], maxh, vj[2], duRGBA(255, 255, 255, 64)); dd->vertex(vi[0], maxh, vi[2], duRGBA(255, 255, 255, 64)); dd->vertex(vj[0], minh, vj[2], duRGBA(255, 255, 255, 64)); dd->vertex(vj[0], maxh, vj[2], duRGBA(255, 255, 255, 64)); } dd->end(); }
26.910256
118
0.676941
9e716ed1b82e835dbbed3a6fa2d870d54d83a0f6
21,662
cpp
C++
src/ui/ui.cpp
EnthDev/dedicatedslave
d8c097082d9e1ae11740cd917a9e9d449be457d2
[ "MIT" ]
7
2018-03-05T02:58:13.000Z
2019-01-06T13:11:50.000Z
src/ui/ui.cpp
EnthDev/dedicatedslave
d8c097082d9e1ae11740cd917a9e9d449be457d2
[ "MIT" ]
3
2017-12-21T00:29:38.000Z
2019-04-24T01:05:12.000Z
src/ui/ui.cpp
EnthDev/dedicatedslave
d8c097082d9e1ae11740cd917a9e9d449be457d2
[ "MIT" ]
1
2019-03-07T11:41:55.000Z
2019-03-07T11:41:55.000Z
// Includes #include <QtWidgets> #include "ui.h" DedicatedSlaveUi::DedicatedSlaveUi(const QString &dir, QWidget *parent) : QWidget(parent), app_slcInstPos(new int[2]) { app_slcInstPos[0] = -1; parentWin = qobject_cast<QMainWindow*>(parent); if(parentWin != 0 ) { // After casting parent widget QMainWindow, need to check if is not null (Async) // Core qInfo() << "(CLASS)\tInitializing 'DedicatedSlaveApp' class..."; ds_app = new DedicatedSlaveApp(dir, this); qInfo() << "(CLASS)\t'DedicatedSlaveApp' initialized."; //QObject::connect(&ds_app, SIGNAL(signal_verifyComplete(int)), this); // Variables app_dir = dir; // Actions initActions(); qInfo() << "\tActions initialized."; // Main Components // Instance List ui_instanceTable = new QTableWidget; ui_instanceTable->setRowCount(0); ui_instanceTable->setColumnCount(3); QStringList header; header << "Name" << "Game" << "Status"; ui_instanceTable->setHorizontalHeaderLabels(header); connect(ui_instanceTable, SIGNAL(cellClicked(int,int)), this, SLOT(slot_instanceSelect(int, int))); // Text Edit ui_textEdit = new QTextEdit(this); ui_textEdit->setAlignment(Qt::AlignCenter); // Info Label ui_infoLabel = new QLabel(tr("<i>Welcome to DedicatedSlave, this is the information label</i>")); ui_infoLabel->setFrameStyle(QFrame::StyledPanel | QFrame::Sunken); ui_infoLabel->setAlignment(Qt::AlignCenter); // Options Dock dockOptions = new UiDockOptions("Instance Options", parentWin); // Filesystem Dock dockFileSystem = new UiDockFileSystem("Workspace File System", parentWin); qInfo() << "\tMain Components initialized."; // Toolbar QToolBar *fileToolBar = parentWin->addToolBar(tr("File Toolbar")); fileToolBar->addAction(actNewInst); fileToolBar->addAction(actRemoveInst); fileToolBar->addAction(actRunInst); fileToolBar->addAction(actVerifyInst); QToolBar *editToolBar = parentWin->addToolBar(tr("Edit Toolbar")); editToolBar->addAction(actUndo); qInfo() << "\tToolbar initialized."; // Menus initMenus(); qInfo() << "\tMenus initialized."; // Toggle View Menus menuView->addAction(dockOptions->toggleViewAction()); menuView->addAction(dockFileSystem->toggleViewAction()); menuView->addAction(fileToolBar->toggleViewAction()); menuView->addAction(editToolBar->toggleViewAction()); // Main QVBoxLayout *layout = new QVBoxLayout; QWidget *topFiller = new QWidget; topFiller->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Maximum); QWidget *bottomFiller = new QWidget; bottomFiller->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Maximum); layout->setMargin(5); layout->addWidget(topFiller); layout->addWidget(ui_textEdit); layout->addWidget(ui_instanceTable); layout->addWidget(ui_infoLabel); /* TODO: Causing segfault ** #0 0x00007ffff74c5040 in QLayout::addChildWidget(QWidget*) () from libQt5Widgets.so.5 ** #1 0x00007ffff74bcb8c in QBoxLayout::insertWidget(int, QWidget*, int, QFlags<Qt::AlignmentFlag>) () from libQt5Widgets.so.5 ** #2 0x000055555556fcf5 in DedicatedSlaveUi::DedicatedSlaveUi (this=0x555555861320, dir=..., parent=<optimized out>) at src/ui/ui.cpp:81 ** #3 0x0000555555566d82 in MainWindow::MainWindow (this=0x7fffffffd900, dir=..., parent=<optimized out>, flags=...) at src/ui/mainwindow.cpp:7 ** #4 0x000055555556639e in main (argc=<optimized out>, argv=<optimized out>) at src/ui/main.cpp:84 */ //layout->addWidget(ui_progressBar); layout->addWidget(bottomFiller); setLayout(layout); // Parent properties ui_progressBar = new QProgressBar(this); QLabel *a = new QLabel(this); parentWin->statusBar()->addPermanentWidget(ui_progressBar); parentWin->statusBar()->addPermanentWidget(a); ui_progressBar->setValue(75); parentWin->statusBar()->showMessage(tr("A context menu is available by right-clicking")); parentWin->addDockWidget(Qt::RightDockWidgetArea, dockOptions); parentWin->addDockWidget(Qt::RightDockWidgetArea, dockFileSystem); parentWin->setCentralWidget(this); qInfo() << "\tParent properties has been set."; // Populate updateModelInstTable(); updateEdit(); // ????? remove } } void DedicatedSlaveUi::contextMenuEvent(QContextMenuEvent *event){ this->getContextMenu()->exec(event->globalPos()); } QMenu* DedicatedSlaveUi::getContextMenu(){ QMenu *menu = new QMenu(this); menu->addAction(actCut); menu->addAction(actCopy); menu->addAction(actPaste); return menu; } void DedicatedSlaveUi::updateModelInstTable(){ while (ui_instanceTable->rowCount() > 0){ ui_instanceTable->removeRow(0); } QHashIterator<QString, GameInstance*> i = ds_app->listInst(); i.toFront(); while (i.hasNext()) { i.next(); if(!i.key().isEmpty()){ ui_instanceTable->insertRow(ui_instanceTable->rowCount()); QTableWidgetItem *item0 = new QTableWidgetItem(i.key()); QTableWidgetItem *item1 = new QTableWidgetItem(i.value()->getGameId()); QTableWidgetItem *item2 = new QTableWidgetItem(QString::number(i.value()->getStatus())); ui_instanceTable->setItem(ui_instanceTable->rowCount()-1, 0, item0); ui_instanceTable->setItem(ui_instanceTable->rowCount()-1, 1, item1); ui_instanceTable->setItem(ui_instanceTable->rowCount()-1, 2, item2); } } } void DedicatedSlaveUi::updateProgressBar(int value){ ui_progressBar->setValue(value); } void DedicatedSlaveUi::resetProgressBar(){ ui_progressBar->reset(); } void DedicatedSlaveUi::updateEdit(){ ui_textEdit->clear(); QTextCursor cursor(ui_textEdit->textCursor()); cursor.movePosition(QTextCursor::Start); QTextFrame *topFrame = cursor.currentFrame(); QTextFrameFormat topFrameFormat = topFrame->frameFormat(); topFrameFormat.setPadding(16); topFrame->setFrameFormat(topFrameFormat); QTextCharFormat textFormat; QTextCharFormat boldFormat; boldFormat.setFontWeight(QFont::Bold); QTextCharFormat italicFormat; italicFormat.setFontItalic(true); QTextTableFormat tableFormat; tableFormat.setBorder(1); tableFormat.setCellPadding(16); tableFormat.setAlignment(Qt::AlignRight); cursor.insertTable(1, 1, tableFormat); cursor.insertText("The Firm", boldFormat); cursor.insertBlock(); cursor.insertText("321 City Street", textFormat); cursor.insertBlock(); cursor.insertText("Industry Park"); cursor.insertBlock(); cursor.insertText("Some Country"); cursor.setPosition(topFrame->lastPosition()); cursor.insertText(QDate::currentDate().toString("d MMMM yyyy"), textFormat); cursor.insertBlock(); cursor.insertBlock(); cursor.insertText("Dear ", textFormat); cursor.insertText("NAME", italicFormat); cursor.insertText(",", textFormat); for (int i = 0; i < 3; ++i) cursor.insertBlock(); cursor.insertText(tr("Yours sincerely,"), textFormat); for (int i = 0; i < 3; ++i) cursor.insertBlock(); cursor.insertText("The Boss", textFormat); cursor.insertBlock(); cursor.insertText("ADDRESS", italicFormat); updateEdit1("BLABLABLA 1"); updateEdit2("BLABLABLA 2"); } void DedicatedSlaveUi::updateEdit1(const QString &customer){ if (customer.isEmpty()) return; QStringList customerList = customer.split(", "); QTextDocument *document = ui_textEdit->document(); QTextCursor cursor = document->find("NAME"); if (!cursor.isNull()) { cursor.beginEditBlock(); cursor.insertText(customerList.at(0)); QTextCursor oldcursor = cursor; cursor = document->find("ADDRESS"); if (!cursor.isNull()) { for (int i = 1; i < customerList.size(); ++i) { cursor.insertBlock(); cursor.insertText(customerList.at(i)); } cursor.endEditBlock(); } else { oldcursor.endEditBlock(); } } } void DedicatedSlaveUi::updateEdit2(const QString &paragraph){ if (paragraph.isEmpty()) return; QTextDocument *document = ui_textEdit->document(); QTextCursor cursor = document->find(tr("Yours sincerely,")); if (cursor.isNull()) return; cursor.beginEditBlock(); cursor.movePosition(QTextCursor::PreviousBlock, QTextCursor::MoveAnchor, 2); cursor.insertBlock(); cursor.insertText(paragraph); cursor.insertBlock(); cursor.endEditBlock(); } void DedicatedSlaveUi::initActions(){ // https://specifications.freedesktop.org/icon-naming-spec/icon-naming-spec-latest.html // New Instance const QIcon newIcon = QIcon::fromTheme("list-add", QIcon(":/images/new.png")); actNewInst = new QAction(newIcon, tr("&New"), this); actNewInst->setShortcuts(QKeySequence::New); actNewInst->setStatusTip(tr("Add a new instance")); connect(actNewInst, &QAction::triggered, this, &DedicatedSlaveUi::conn_actionNewInstDialog); // Remove Instance const QIcon removeIcon = QIcon::fromTheme("list-remove", QIcon(":/images/new.png")); actRemoveInst = new QAction(removeIcon, tr("&Remove"), this); actRemoveInst->setShortcuts(QKeySequence::New); actRemoveInst->setStatusTip(tr("Remove a new instance")); connect(actRemoveInst, &QAction::triggered, this, &DedicatedSlaveUi::conn_actionRemoveInst); // Verify Instance const QIcon verifyIcon = QIcon::fromTheme("emblem-downloads", QIcon(":/images/new.png")); actVerifyInst = new QAction(verifyIcon, tr("&Verify"), this); actVerifyInst->setStatusTip(tr("Verify a instance")); connect(actVerifyInst, &QAction::triggered, this, &DedicatedSlaveUi::conn_actionVerifyInst); // Run Instance const QIcon runIcon = QIcon::fromTheme("go-next", QIcon(":/images/new.png")); actRunInst = new QAction(runIcon, tr("&Run"), this); actRunInst->setStatusTip(tr("Run a new instance")); connect(actRunInst, &QAction::triggered, this, &DedicatedSlaveUi::conn_actionRunInst); // Backup actBackupInst = new QAction(tr("&Backup"), this); actBackupInst->setStatusTip(tr("Backup the selected instance to disk")); connect(actBackupInst, &QAction::triggered, this, &DedicatedSlaveUi::conn_actionBackup); // Restore actRestoreInst = new QAction(tr("&Restore"), this); actRestoreInst->setStatusTip(tr("Restore the selected instance to disk")); connect(actRestoreInst, &QAction::triggered, this, &DedicatedSlaveUi::conn_actionRestore); // Exit/Close actExit = new QAction(tr("E&xit"), this); actExit->setShortcuts(QKeySequence::Quit); actExit->setStatusTip(tr("Exit the application")); connect(actExit, &QAction::triggered, this, &QWidget::close); // Undo const QIcon undoIcon = QIcon::fromTheme("edit-undo", QIcon(":/images/undo.png")); actUndo = new QAction(undoIcon, tr("&Undo"), this); actUndo->setShortcuts(QKeySequence::Undo); actUndo->setStatusTip(tr("Undo the last operation")); connect(actUndo, &QAction::triggered, this, &DedicatedSlaveUi::conn_actionUndo); // Redo actRedo = new QAction(tr("&Redo"), this); actRedo->setShortcuts(QKeySequence::Redo); actRedo->setStatusTip(tr("Redo the last operation")); connect(actRedo, &QAction::triggered, this, &DedicatedSlaveUi::conn_actionRedo); // Cut actCut = new QAction(tr("Cu&t"), this); actCut->setShortcuts(QKeySequence::Cut); actCut->setStatusTip(tr("Cut the current selection's contents to the clipboard")); connect(actCut, &QAction::triggered, this, &DedicatedSlaveUi::conn_actionCut); // Copy actCopy = new QAction(tr("&Copy"), this); actCopy->setShortcuts(QKeySequence::Copy); actCopy->setStatusTip(tr("Copy the current selection's contents to the clipboard")); connect(actCopy, &QAction::triggered, this, &DedicatedSlaveUi::conn_actionCopy); // Paste actPaste = new QAction(tr("&Paste"), this); actPaste->setShortcuts(QKeySequence::Paste); actPaste->setStatusTip(tr("Paste the clipboard's contents into the current selection")); connect(actPaste, &QAction::triggered, this, &DedicatedSlaveUi::conn_actionPaste); // Options actOptions = new QAction(tr("&Options..."), this); QList<QKeySequence> optionsShortcuts; optionsShortcuts.append(QKeySequence(Qt::CTRL + Qt::Key_F)); optionsShortcuts.append(QKeySequence(Qt::CTRL + Qt::Key_P)); actOptions->setShortcuts(optionsShortcuts); actOptions->setStatusTip(tr("Open the config options dialog")); connect(actOptions, &QAction::triggered, this, &DedicatedSlaveUi::conn_actionOptions); // Help actHelp = new QAction(tr("&Help"), this); actHelp->setStatusTip(tr("Getting started with DedicatedSlave")); connect(actHelp, &QAction::triggered, this, &DedicatedSlaveUi::conn_actionHelp); // Check Updates actCheckUpdates = new QAction(tr("&Check Updates"), this); actCheckUpdates->setStatusTip(tr("Check if exists new updates")); connect(actCheckUpdates, &QAction::triggered, this, &DedicatedSlaveUi::conn_actionCheckUpdates); // About actAbout = new QAction(tr("&About"), this); actAbout->setStatusTip(tr("Show the application's About box")); connect(actAbout, &QAction::triggered, this, &DedicatedSlaveUi::conn_actionAbout); // About Qt actAboutQt = new QAction(tr("About &Qt"), this); actAboutQt->setStatusTip(tr("Show the Qt library's About box")); connect(actAboutQt, &QAction::triggered, qApp, &QApplication::aboutQt); connect(actAboutQt, &QAction::triggered, this, &DedicatedSlaveUi::conn_actionAboutQt); } /*! * \brief Function that initializate menus */ void DedicatedSlaveUi::initMenus(){ // File Menu // if(parentWin != 0) { //qDebug() << "\tQ_FUNC_INFO" << Q_FUNC_INFO; // qInfo() << "Q_FUNC_INFO:" << Q_FUNC_INFO; // QMenuBar *menu = parentWin->menuBar(); menuFile = parentWin->menuBar()->addMenu(tr("&File")); menuFile->addAction(actNewInst); menuFile->addAction(actRemoveInst); menuFile->addAction(actRunInst); menuFile->addAction(actVerifyInst); menuFile->addAction(actBackupInst); menuFile->addAction(actRestoreInst); menuFile->addSeparator(); menuFile->addAction(actExit); // Edit Menu menuEdit = parentWin->menuBar()->addMenu(tr("&Edit")); menuEdit->addAction(actUndo); menuEdit->addAction(actRedo); menuEdit->addSeparator(); menuEdit->addAction(actCut); menuEdit->addAction(actCopy); menuEdit->addAction(actPaste); menuEdit->addSeparator(); // View Menu menuView = parentWin->menuBar()->addMenu(tr("&View")); // Tools Menu menuTools = parentWin->menuBar()->addMenu(tr("&Tools")); menuTools->addSeparator(); menuTools->addAction(actOptions); // Help Menu menuHelp = parentWin->menuBar()->addMenu(tr("&Help")); menuHelp->addAction(actHelp); menuHelp->addAction(actCheckUpdates); menuHelp->addSeparator(); menuHelp->addAction(actAbout); menuHelp->addAction(actAboutQt); } void DedicatedSlaveUi::conn_actionHelp(){ QDesktopServices::openUrl(QUrl("https://enthdev.github.io/dedicatedslave/user-guide/gettingstarted/")); ui_infoLabel->setText(tr("Invoked <b>Help|Help</b>")); } void DedicatedSlaveUi::conn_actionCheckUpdates(){ ui_infoLabel->setText(tr("Invoked <b>Help|CheckUpdates</b>")); } void DedicatedSlaveUi::conn_actionAbout(){ ui_infoLabel->setText(tr("Invoked <b>Help|About</b>")); QMessageBox::about(this, tr("About Dedicated Slave"), tr("The <b>Dedicated Slave</b> is a cross platform desktop app " "tool to manage steam dedicated game servers with SteamCMD." "<p><a href='https://github.com/EnthDev/dedicatedslave'>Github Repository</a>" "<p><a href='https://enthdev.github.io/dedicatedslave/'>Website</a>" "<p><a href='https://enthdev.github.io/dedicatedslave/user-guide/gettingstarted/'>Website - Getting Started</a>")); } void DedicatedSlaveUi::conn_actionAboutQt(){ ui_infoLabel->setText(tr("Invoked <b>Help|About Qt</b>")); } void DedicatedSlaveUi::conn_actionVerifyInst(){ if(app_slcInstPos[0] != -1 && app_slcInstPos[1] != -1){ QString instName = ui_instanceTable->item(app_slcInstPos[0], 0)->text(); if(ds_app->hasInst(instName)){ ds_app->verifyInstProgress(ui_instanceTable->item(app_slcInstPos[0], 0)->text()); updateModelInstTable(); }else{ ui_infoLabel->setText(QString("Error: Instance '%1' does not exist").arg(instName)); } } } void DedicatedSlaveUi::conn_actionRunInst(){ if(app_slcInstPos[0] != -1 && app_slcInstPos[1] != -1){ QString instName = ui_instanceTable->item(app_slcInstPos[0], 0)->text(); if(ds_app->hasInst(instName)){ if(ds_app->hasReadyInst(instName)){ ds_app->runInst(instName); updateModelInstTable(); }else{ ui_infoLabel->setText(QString("Error: Instance '%1' is not ready to run").arg(instName)); } }else{ ui_infoLabel->setText(QString("Error: Instance '%1' does not exist").arg(instName)); } } } void DedicatedSlaveUi::conn_actionNewInstDialog(){ ui_newInstGroup = new QGroupBox; QLabel *labeltest = new QLabel(tr("Instance Game:")); // QRadioButton *radio = new QRadioButton(tr("Add Instance")); QVBoxLayout *vbox = new QVBoxLayout; QComboBox *comboGamesList = new QComboBox; connect(comboGamesList, SIGNAL(activated(int)), this, SLOT(slot_addInstanceCombo(int))); QPushButton *addButton = new QPushButton("OK"); connect(addButton, &QAbstractButton::clicked, this, &DedicatedSlaveUi::conn_actionNewInst); QLineEdit *instNameLineEdit = new QLineEdit; QLineEdit *instDirLineEdit = new QLineEdit("etcinstances"); connect(instNameLineEdit, SIGNAL(textEdited(QString)), this, SLOT(slot_addInstNameEdit(QString))); connect(instDirLineEdit, SIGNAL(textEdited(QString)), this, SLOT(slot_addInstDirEdit(QString))); // Unlike textChanged(), this signal is not emitted when the text is changed programmatically, for example, by calling setText(). comboGamesList->addItem("-"); comboGamesList->addItem("Counter-Strike: Global Offensive"); // 1 comboGamesList->addItem("Rust"); // 2 // vbox->addWidget(radio); vbox->addWidget(labeltest); vbox->addWidget(comboGamesList); vbox->addWidget(addButton); vbox->addWidget(instNameLineEdit); vbox->addWidget(instDirLineEdit); ui_newInstGroup->setLayout(vbox); ui_newInstGroup->show(); ui_infoLabel->setText(tr("Invoked <b>File|New</b>")); } void DedicatedSlaveUi::conn_actionRemoveInst(){ if(app_slcInstPos[0] != -1 && app_slcInstPos[1] != -1){ QMessageBox::StandardButton removeReply; removeReply = QMessageBox::question(this, "Remove Instace", QString("Do you really want to remove instance '%1'").arg(ui_instanceTable->item(app_slcInstPos[0], 0)->text()), QMessageBox::Yes|QMessageBox::No); if(removeReply == QMessageBox::Yes){ QMessageBox::StandardButton removeFileReply; removeFileReply = QMessageBox::question(this, "Remove Instace", "Do you want to remove all instance files?", QMessageBox::Yes|QMessageBox::No); if(removeFileReply == QMessageBox::Yes) ds_app->removeInst(ui_instanceTable->item(app_slcInstPos[0], 0)->text(), true); else ds_app->removeInst(ui_instanceTable->item(app_slcInstPos[0], 0)->text(), false); updateModelInstTable(); } } } void DedicatedSlaveUi::conn_actionNewInst(){ ui_newInstGroup->hide(); if(!app_newIntsName.isEmpty()){ if(!ds_app->hasInst(app_newIntsName)){ ds_app->addInst(app_newIntsName, app_newInstGame); updateModelInstTable(); app_newInstGame = ""; ui_infoLabel->setText(QString("Invoked New Instance <b>%1</b> (<b>%2</b>) - <b>%3</b>").arg(app_newIntsName).arg(ui_instanceTable->rowCount()-1).arg(app_newInstGame)); }else{ ui_infoLabel->setText(QString("Error: New Instance name already exist (<b>%1</b>)").arg(app_newIntsName)); } }else{ ui_infoLabel->setText("Error: New Instance name cannot be empty."); } } void DedicatedSlaveUi::conn_actionRestore(){ ui_infoLabel->setText(tr("Invoked <b>File|Restore</b>")); } void DedicatedSlaveUi::conn_actionBackup(){ ui_infoLabel->setText(tr("Invoked <b>File|Save</b>")); QMimeDatabase mimeDatabase; QString fileName = QFileDialog::getSaveFileName(this, tr("Choose a file name"), ".", mimeDatabase.mimeTypeForName("text/html").filterString()); if (fileName.isEmpty()) return; QFile file(fileName); if (!file.open(QFile::WriteOnly | QFile::Text)) { QMessageBox::warning(this, tr("Dock Widgets"), tr("Cannot write file %1:\n%2.") .arg(QDir::toNativeSeparators(fileName), file.errorString())); return; } QTextStream out(&file); QApplication::setOverrideCursor(Qt::WaitCursor); out << ui_textEdit->toHtml(); QApplication::restoreOverrideCursor(); parentWin->statusBar()->showMessage(tr("Saved '%1'").arg(fileName), 2000); } void DedicatedSlaveUi::conn_actionUndo(){ ui_infoLabel->setText(tr("Invoked <b>Edit|Undo</b>")); ui_textEdit->document()->undo(); } void DedicatedSlaveUi::conn_actionRedo(){ ui_infoLabel->setText(tr("Invoked <b>Edit|Redo</b>")); } void DedicatedSlaveUi::conn_actionCut(){ ui_infoLabel->setText(tr("Invoked <b>Edit|Cut</b>")); } void DedicatedSlaveUi::conn_actionCopy(){ ui_infoLabel->setText(tr("Invoked <b>Edit|Copy</b>")); } void DedicatedSlaveUi::conn_actionPaste(){ ui_infoLabel->setText(tr("Invoked <b>Edit|Paste</b>")); } void DedicatedSlaveUi::conn_actionOptions(){ ui_infoLabel->setText(tr("Invoked <b>Tools|Options...</b>")); ui_dialogConfig = new ConfigDialog(ds_app); ui_dialogConfig->show(); } void DedicatedSlaveUi::slot_addInstanceCombo(int index){ switch (index) { case 1: app_newInstGame = "csgo"; break; case 2: app_newInstGame = "rust"; break; } } void DedicatedSlaveUi::slot_addInstNameEdit(QString instanceName){ app_newIntsName = instanceName; } void DedicatedSlaveUi::slot_addInstDirEdit(QString instanceDir){ app_newInstDir = instanceDir; } void DedicatedSlaveUi::slot_instanceSelect(int row, int column){ app_slcInstPos[0] = row; app_slcInstPos[1] = column; QHashIterator<QString, GameInstance*> i = ds_app->listInst(); while(i.hasNext()){ i.next(); if(i.key() == ui_instanceTable->item(app_slcInstPos[0], 0)->text()){ GameInstance *gi = i.value(); dockOptions->updateModelInst(i.key(), gi->getServerName(), gi->getNumPlayers()); } } ui_infoLabel->setText(QString("Selected Inst <b>%1</b>:<b>%2</b>").arg(row).arg(column)); }
36.591216
170
0.728188
9e72f674499a8b8ec62adb88341d59099f91252e
8,949
cpp
C++
SimSpark/rcssserver3d/plugin/soccer/hmdp_effector/hmdpeffector.cpp
IllyasvielEin/Robocup3dInstaller
12e91d9372dd08a92feebf98e916c98bc2242ff4
[ "MIT" ]
null
null
null
SimSpark/rcssserver3d/plugin/soccer/hmdp_effector/hmdpeffector.cpp
IllyasvielEin/Robocup3dInstaller
12e91d9372dd08a92feebf98e916c98bc2242ff4
[ "MIT" ]
null
null
null
SimSpark/rcssserver3d/plugin/soccer/hmdp_effector/hmdpeffector.cpp
IllyasvielEin/Robocup3dInstaller
12e91d9372dd08a92feebf98e916c98bc2242ff4
[ "MIT" ]
null
null
null
/* -*- mode: c++; c-basic-offset: 4; indent-tabs-mode: nil -*- this file is part of rcssserver3D Copyright (C) 2002,2003 Koblenz University Copyright (C) 2003 RoboCup Soccer Server 3D Maintenance Group Copyright (C) 2008 N. Michael Mayer, email: nmmayer@gmail.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "hmdpeffector.h" #include "hmdpperceptor.h" #include "hmdpaction.h" #include <zeitgeist/logserver/logserver.h> #include <oxygen/gamecontrolserver/actionobject.h> #include <oxygen/agentaspect/jointeffector.h> #include <oxygen/physicsserver/hingejoint.h> using namespace boost; using namespace oxygen; using namespace salt; using namespace HMDP; //! Handler for HMDP Effector and Perceptor back and forward HMDPPerceptor *hmdpPerceptorHandle = NULL; HMDPEffector *hmdpEffectorHandle = NULL; namespace HMDP { extern "C" { using namespace HMDP; int lock; extern Hmdl *hmdl; extern Base_data *base_data; extern int readChar; void disableIRQ(); //! mimicks IRQ functionality void enableIRQ(); } } HMDPEffector::HMDPEffector(): oxygen::Effector() { ifActive = false; } HMDPEffector::~HMDPEffector() { HMDP::lock = 0; } void HMDPEffector::PrePhysicsUpdateInternal(float deltaTime) { if (iter == 0) { ReadOutJointList(); InitHMDP(); } iter++; if (!ifActive) GetLog()->Normal() << "MAIN LOOP NOT ACTIVE THOUGH!!!" << std::endl; mainLoop(); if (mAction.get() == 0 || mBody.get() == 0) { return; } boost::shared_ptr<HMDPAction> hMDPAction = dynamic_pointer_cast<HMDPAction>(mAction); mAction.reset(); if (hMDPAction.get() == 0) { GetLog()->Error() << "ERROR: (HMDPEffector) cannot realize an unknown ActionObject\n"; return; } } boost::shared_ptr<ActionObject> HMDPEffector::GetActionObject(const Predicate& predicate) { //std::cout << " GetActionObject called " << std::endl; if (predicate.name != GetPredicate()) { GetLog()->Error() << "ERROR: (HMDPEffector) invalid predicate" << predicate.name << "\n"; return boost::shared_ptr<ActionObject>(); } std::string message; if (!predicate.GetValue(predicate.begin(), message)) { GetLog()->Error() << "ERROR: (HMDPEffector) Some Problem while receiving the HMDP Message\n"; return boost::shared_ptr<ActionObject>(); }; inMessage = inMessage + message + "\r\n"; //std::cout << inMessage << std::endl; return boost::shared_ptr<ActionObject>(new HMDPAction(GetPredicate(), inMessage)); } void HMDPEffector::OnLink() { hmdpEffectorHandle = this; perceptor = hmdpPerceptorHandle; std::cout << "Perceptor points to " << perceptor << std::endl; std::cout << "in OnLink " << std::endl; ifActive = true; iter = 0; // just to do the right things on iter = 0 in pre physics routine boost::shared_ptr<Node> parent = GetParent().lock(); if (parent.get() == 0) { GetLog()->Error() << "ERROR: (HMDPEffector) parent node is not derived from BaseNode\n"; return; } // parent should be a transform, or some other node, which has a // Body-child mBody = dynamic_pointer_cast<RigidBody>(parent->GetChildOfClass("RigidBody")); if (mBody.get() == 0) { GetLog()->Error() << "ERROR: (HMDPEffector) parent node has no Body child;" "cannot apply HMDP\n"; return; } inMessage = ""; //! initialize the incoming messages stored in this string } void HMDPEffector::OnUnlink() { mBody.reset(); HMDP::lock = 0; ifActive = false; } /**************************************************************************************************** SPECIAL HMDP RELATED METHODS of the Effecotr Class ****************************************************************************************************/ float HMDPEffector::zeroPosServo(int id) //! this is to define a standard position for HMDP ( some kind of standing straight with arms diagonal down ) { return nao.zeroPosition(id); //! NAO related function inside the plugin } //! it is important for the parser to go the beginning of the new line -- no matter if the p void HMDPEffector::searchForNextLinestartInMessage() { int state = 0; while (state < 3) { char a = inMessage[0]; if ((a == 13) && (state == 0)) state = 1; if (((a != 13) || (a != 10)) && (state == 1)) state = 2; inMessage = inMessage.substr(1, inMessage.size() - 1); if (state == 2) state = 3; } } void HMDPEffector::sendMessage(std::string message) { //std::cout << "message in effector "<< message << std::endl; perceptor->sendMessage(message); // goes into perceptor part -- this is the only part where the perceptor is needed } void HMDPEffector::ReadOutJointList() { boost::shared_ptr<Node> parent = GetParent().lock(); boost::shared_ptr<Node> grandparent = parent->GetParent().lock(); grandparent->ListChildrenSupportingClass<HingeJoint>(jointList, true); // This vectors describe the state of each joint and thus there need to be an entry for each joint servo_target_pos.resize(jointList.size()); servo_gain.resize(jointList.size()); servo_angle.resize(jointList.size()); int i = 0; for (TLeafList::iterator j_it = jointList.begin(); j_it != jointList.end(); j_it++) { // set all to yzero (necessary ?) servo_target_pos[i] = 0.; servo_gain[i] = 0.05; servo_angle[i] = 0; boost::shared_ptr<Leaf> join = *j_it; boost::shared_ptr<BaseNode> jparent = dynamic_pointer_cast<BaseNode>(join->GetParent().lock()); std::cout << i << " " << jparent->GetName() << std::endl; i++; } } bool HMDPEffector::checkIfServoIDExists(int ID) //! checks if a joint with ID ID exists { if ((ID >= 0) && (ID < jointList.size())) return true; return false; } void HMDPEffector::mainLoop() // HMDP update method { prepareUsage(); int watchdog = 0; hmdpEffectorHandle = this; // just to make sure you have the right one set -- in the case of several agents while ((inMessage.size() > 0) && (watchdog < 100)) { watchdog++; inMessage = inMessage; //if (inMessage.size()>10) std::cout << "GOT LARGE MESS " << this << std::endl; HMDP::parse_one_line(); // HMDP parser reads one line in one call } HMDP::lock = 0; if (ifIRQ) HMDP::inter_routine_base(); // real time functionality (!) now in the loop controlPosServo(); // servo update loop } void HMDPEffector::controlPosServo() // for controlling servos { int i = 0; for (TLeafList::iterator j_it = jointList.begin(); j_it != jointList.end(); j_it++) { boost::shared_ptr<HingeJoint> joint = static_pointer_cast<HingeJoint> (*j_it); servo_angle[i] = joint->GetAngle() - zeroPosServo(i); double tpos = servo_target_pos[i]; float err = servo_gain[i] * (tpos - servo_angle[i]); joint->SetParameter(2 /*dParamVel*/, err); if (abs(err) > 0.00001) { boost::shared_ptr<RigidBody> body = joint->GetBody(Joint::BI_FIRST); if (body && !body->IsEnabled()) { body->Enable(); } } i++; } } void HMDPEffector::prepareUsage() { while (lock) { //std::cout <<" waiting in lock "<<std::endl; }; hmdl = &local_hmdl; base_data = &local_base; lock = 1; } void HMDPEffector::InitHMDP() //! startup of HMDP { prepareUsage(); HMDP::init_base(); //! boot the base part HMDP::init_hmdl(); //! boot the hmdp part HMDP::enableIRQ(); /* start the IRQ */ for (int i = 0; i < 64; i++) { local_base.zero_pos_inits_feed[i] = 32* 64 ; if (checkIfServoIDExists(i)) { std::cout << nao.getJointName(i) << std::endl; for (int j=0; j<6;j++) HMDP::jointnames[i][j] = nao.getJointName(i).c_str()[j]; HMDP::jointnames[i][7]=0; //! stop signal for c-string } } local_base.zero_pos_inits = &(local_base.zero_pos_inits_feed[0]); HMDP::lock=0; }
28.5
150
0.608224
9e76384bb659a7ad64d1a252793929ad59cfc345
508
cpp
C++
Classwork/25.02.19/rectangle.cpp
5ko99/FMI-Semester-2
a7e7f2cc1ae7b3198728197c8b70d14156eb0996
[ "MIT" ]
null
null
null
Classwork/25.02.19/rectangle.cpp
5ko99/FMI-Semester-2
a7e7f2cc1ae7b3198728197c8b70d14156eb0996
[ "MIT" ]
null
null
null
Classwork/25.02.19/rectangle.cpp
5ko99/FMI-Semester-2
a7e7f2cc1ae7b3198728197c8b70d14156eb0996
[ "MIT" ]
null
null
null
#include<iostream>; using namespace std; struct Rectangle{ double width; double height; }; void printRec(Rectangle r){ cout<<"Width:"<<r.width<<endl; cout<<"Height:"<<r.height<<endl; } void initRec(Rectangle* r){ cin>>(*r).width; cin>>(*r).height; } Rectangle initRec(){ Rectangle r; cin>>r.width; cin>>r.height; return r; } int main(){ Rectangle r; initRec(&(r)); printRec(r); r=initRec(); printRec(r); return 0; }
17.517241
37
0.555118
9e76a925bb00ef7ec3d318043a012adeaaf8e42c
5,445
hpp
C++
src/batteries/radix_queue.hpp
tonyastolfi/batteries
67349930e54785f44eab84f1e56da6c78c66a5f9
[ "Apache-2.0" ]
1
2022-01-04T20:28:17.000Z
2022-01-04T20:28:17.000Z
src/batteries/radix_queue.hpp
mihir-thakkar/batteries
67349930e54785f44eab84f1e56da6c78c66a5f9
[ "Apache-2.0" ]
2
2020-06-04T14:02:24.000Z
2020-06-04T14:03:18.000Z
src/batteries/radix_queue.hpp
mihir-thakkar/batteries
67349930e54785f44eab84f1e56da6c78c66a5f9
[ "Apache-2.0" ]
1
2022-01-03T20:24:31.000Z
2022-01-03T20:24:31.000Z
// Copyright 2021 Anthony Paul Astolfi // #pragma once #ifndef BATTERIES_RADIX_QUEUE_HPP #define BATTERIES_RADIX_QUEUE_HPP #include <batteries/assert.hpp> #include <batteries/int_types.hpp> #include <boost/functional/hash.hpp> #include <array> #include <limits> #include <type_traits> namespace batt { template <usize kCapacityInBits> class RadixQueue; template <usize N_> std::ostream& operator<<(std::ostream& out, const RadixQueue<N_>& t); // A fixed-capacity FIFO queue of integers with variable radix per integer. This is used to store sequences // of events. // template <usize kCapacityInBits> class RadixQueue { public: static constexpr usize kQueueSize = kCapacityInBits / 64; //==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - using index_type = std::conditional_t< (kCapacityInBits <= std::numeric_limits<u16>::max()), std::conditional_t<(kCapacityInBits <= std::numeric_limits<u8>::max()), u8, u16>, std::conditional_t<(kCapacityInBits <= std::numeric_limits<u32>::max()), u32, u64>>; // The queue is stored in segments of 64 bits each. // struct Segment { u64 radix = 1; u64 value = 0; friend inline std::ostream& operator<<(std::ostream& out, const Segment& t) { return out << "{.value=" << t.value << ", .radix=" << t.radix << "}"; } }; // Default hash function. // struct Hash { using value_type = usize; usize operator()(const RadixQueue& r) const { usize seed = r.queue_size(); for (usize i = 0; i < r.queue_size(); ++i) { usize j = (r.front_ + i) % kQueueSize; boost::hash_combine(seed, r.queue[j].radix); boost::hash_combine(seed, r.queue[j].value); } return seed; } }; //==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - RadixQueue() = default; // Returns true when there are no items in the queue. // bool empty() const { return this->queue_size() == 1 && this->front().radix == 1; } // Returns true when the queue has reached its maximum capacity. // bool full() const { return this->front_ == (this->back_ + 1) % kQueueSize; } // Discards the contents of the queue, resetting it to default state. // void clear() { this->front_ = 0; this->back_ = 0; this->queue_[0] = Segment{}; } // Insert the given value with the given radix at the back of the queue. // void push(u64 radix, u64 value) { BATT_CHECK_GT(radix, value) << "value must not exceed the supplied radix"; const bool would_overflow = std::numeric_limits<u64>::max() / this->back().radix < radix; if (would_overflow) { this->push_back(); } Segment& s = this->back(); s.value += value * s.radix; s.radix *= radix; } // Extract the next value out of the queue. The passed radix must match the radix used when inserting // the item originally; otherwise behavior is undefined. // u64 pop(u64 radix) { Segment& s = this->front(); BATT_CHECK_LE(radix, s.radix) << "the supplied radix is too large"; const u64 value = s.value % radix; s.radix /= radix; s.value /= radix; BATT_CHECK_LT(s.value, s.radix); if (s.radix == 1 && this->queue_size() > 1) { this->pop_front(); } return value; } template <usize N_> friend std::ostream& operator<<(std::ostream& out, const RadixQueue<N_>& t); private: static void advance_index(index_type* i) { *i = (*i + 1) % kQueueSize; } usize queue_size() const { const usize upper_bound = [&]() -> usize { if (this->front_ <= this->back_) { return this->back_ + 1; } return kQueueSize + this->back_ + 1; }(); BATT_CHECK_LT(this->front_, upper_bound); return upper_bound - this->front_; } Segment& front() { return this->queue_[this->front_]; } const Segment& front() const { return this->queue_[this->front_]; } Segment& back() { return this->queue_[this->back_]; } const Segment& back() const { return this->queue_[this->back_]; } void pop_front() { BATT_CHECK_NE(this->front_, this->back_) << "pull failed; the RadixQueue is empty"; advance_index(&this->front_); } void push_back() { BATT_CHECK(!this->full()) << "push failed; the RadixQueue is full"; advance_index(&this->back_); this->queue_[this->back_] = Segment{}; } //==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - index_type front_ = 0; index_type back_ = 0; std::array<Segment, kQueueSize> queue_; }; template <usize N_> inline std::ostream& operator<<(std::ostream& out, const RadixQueue<N_>& t) { usize end = (t.front_ <= t.back_) ? (t.back_ + 1) : (t.back_ + 1 + t.queue_.size()); out << "{"; for (usize i = t.front_; i < end; ++i) { const auto& s = t.queue_[i % t.queue_.size()]; out << s.value << "/" << s.radix << ","; } return out << "}"; } } // namespace batt #endif // BATTERIES_RADIX_QUEUE_HPP
26.052632
108
0.547658
9e7a1c6c684d37995423a925a87f05e1ff12801a
13,114
cpp
C++
groups/bdl/bdlde/bdlde_quotedprintableencoder.cpp
seanbaxter/bde-1
149176ebc2ae49c3b563895a7332fe638a760782
[ "Apache-2.0" ]
1
2021-11-10T16:53:42.000Z
2021-11-10T16:53:42.000Z
groups/bdl/bdlde/bdlde_quotedprintableencoder.cpp
seanbaxter/bde-1
149176ebc2ae49c3b563895a7332fe638a760782
[ "Apache-2.0" ]
2
2020-11-05T15:20:55.000Z
2021-01-05T19:38:43.000Z
groups/bdl/bdlde/bdlde_quotedprintableencoder.cpp
seanbaxter/bde-1
149176ebc2ae49c3b563895a7332fe638a760782
[ "Apache-2.0" ]
2
2020-01-16T17:58:12.000Z
2020-08-11T20:59:30.000Z
// bdlde_quotedprintableencoder.cpp -*-C++-*- // ---------------------------------------------------------------------------- // NOTICE // // This component is not up to date with current BDE coding standards, and // should not be used as an example for new development. // ---------------------------------------------------------------------------- #include <bdlde_quotedprintableencoder.h> #include <bsls_ident.h> BSLS_IDENT_RCSID(bdlde_quotedprintableencoder_cpp,"$Id$ $CSID$") #include <bslma_default.h> #include <bsls_assert.h> #include <bsl_cstring.h> // 'strlen' // ====================== // FILE-SCOPE STATIC DATA // ====================== namespace { typedef BloombergLP::bdlde::QuotedPrintableEncoder QuotedPrintableEncoder; } // close unnamed namespace static const char PC = QuotedPrintableEncoder::e_PC; static const char CC = QuotedPrintableEncoder::e_CC; static const char CR = QuotedPrintableEncoder::e_CR; static const char LF = QuotedPrintableEncoder::e_LF; static const char WS = QuotedPrintableEncoder::e_WS; static const char *bdeHex = "0123456789ABCDEF"; // The following table is a map of an 8-bit index value to the corresponding // equivalence class. static const char equivalenceClassMap[] = { // 0 1 2 3 4 5 6 7 CC, CC, CC, CC, CC, CC, CC, CC, // 000 CC, WS, LF, CC, CC, CR, CC, CC, // 010 '\t', '\n', '\r' CC, CC, CC, CC, CC, CC, CC, CC, // 020 CC, CC, CC, CC, CC, CC, CC, CC, // 030 WS, PC, PC, PC, PC, PC, PC, PC, // 040 ' ', '!' is first PC PC, PC, PC, PC, PC, PC, PC, PC, // 050 PC, PC, PC, PC, PC, PC, PC, PC, // 060 PC, PC, PC, PC, PC, CC, PC, PC, // 070 '=' PC, PC, PC, PC, PC, PC, PC, PC, // 100 PC, PC, PC, PC, PC, PC, PC, PC, // 110 PC, PC, PC, PC, PC, PC, PC, PC, // 120 PC, PC, PC, PC, PC, PC, PC, PC, // 130 PC, PC, PC, PC, PC, PC, PC, PC, // 140 PC, PC, PC, PC, PC, PC, PC, PC, // 150 PC, PC, PC, PC, PC, PC, PC, PC, // 160 PC, PC, PC, PC, PC, PC, PC, CC, // 170 '~' is last PC CC, CC, CC, CC, CC, CC, CC, CC, // 200 CC, CC, CC, CC, CC, CC, CC, CC, // 210 CC, CC, CC, CC, CC, CC, CC, CC, // 220 CC, CC, CC, CC, CC, CC, CC, CC, // 230 CC, CC, CC, CC, CC, CC, CC, CC, // 240 CC, CC, CC, CC, CC, CC, CC, CC, // 250 CC, CC, CC, CC, CC, CC, CC, CC, // 260 CC, CC, CC, CC, CC, CC, CC, CC, // 270 CC, CC, CC, CC, CC, CC, CC, CC, // 300 CC, CC, CC, CC, CC, CC, CC, CC, // 310 CC, CC, CC, CC, CC, CC, CC, CC, // 320 CC, CC, CC, CC, CC, CC, CC, CC, // 330 CC, CC, CC, CC, CC, CC, CC, CC, // 340 CC, CC, CC, CC, CC, CC, CC, CC, // 350 CC, CC, CC, CC, CC, CC, CC, CC, // 360 CC, CC, CC, CC, CC, CC, CC, CC // 370 }; // The following table stores the names for the line break modes so that on // query, users can tell the mode of the encoder without having to search the // header file for the corresponding enum value. namespace BloombergLP { namespace bdlde { const char* QuotedPrintableEncoder::s_lineBreakModeName[] = { "CRLF mode", "LF mode", "Mixed mode" }; const char *QuotedPrintableEncoder::s_defaultEquivClass_p = equivalenceClassMap; // PRIVATE MANIPULATORS void QuotedPrintableEncoder::appendSoftLineBreak(char *out) { *out = '='; ++d_outputLength; d_buffer[d_bufferLength++] = '\n'; d_buffer[d_bufferLength++] = '\r'; d_lineStart = d_outputLength + 2; d_lastWasWS = false; BSLS_ASSERT(5 >= d_bufferLength); } void QuotedPrintableEncoder::appendHardLineBreak(char *out) { if (d_lastWasWS) { *out = '='; ++d_outputLength; d_buffer[d_bufferLength++] = '\n'; d_buffer[d_bufferLength++] = '\r'; d_buffer[d_bufferLength++] = '\n'; d_buffer[d_bufferLength++] = '\r'; d_lineStart = d_outputLength + 4; } else { *out = '\r'; ++d_outputLength; d_buffer[d_bufferLength++] = '\n'; d_lineStart = d_outputLength + 1; } d_lastWasWS = false; BSLS_ASSERT(5 >= d_bufferLength); } void QuotedPrintableEncoder::appendPrintable(char *out, char ch) { BSLS_ASSERT(0 == d_bufferLength); if (d_outputLength - d_lineStart >= d_maxLineLength - 1) { d_buffer[d_bufferLength++] = ch; appendSoftLineBreak(out); } else { *out = ch; ++d_outputLength; } d_lastWasWS = (WS == d_equivClass_p[static_cast<unsigned char>(ch)]); BSLS_ASSERT(5 >= d_bufferLength); } void QuotedPrintableEncoder::appendAsHex(char *out, char ch, bool isFinal) { BSLS_ASSERT(0 == d_bufferLength); d_buffer[d_bufferLength++] = bdeHex[ch & 0xf]; d_buffer[d_bufferLength++] = bdeHex[(ch >> 4) & 0xf]; if (d_outputLength - d_lineStart >= d_maxLineLength - (isFinal ? 2 : 3)) { d_buffer[d_bufferLength++] = '='; appendSoftLineBreak(out); } else { *out = '='; ++d_outputLength; } d_lastWasWS = false; BSLS_ASSERT(5 >= d_bufferLength); } // CREATORS QuotedPrintableEncoder::QuotedPrintableEncoder( QuotedPrintableEncoder::LineBreakMode lineBreakMode, int maxLineLength, bslma::Allocator *basicAllocator) : d_lineBreakMode(lineBreakMode) , d_maxLineLength(maxLineLength) , d_outputLength(0) , d_lineLength(0) , d_equivClass_p(const_cast<char *>(s_defaultEquivClass_p)) , d_state(e_INITIAL_STATE) , d_bufferLength(0) , d_lineStart(0) , d_deffered(0) , d_lastWasWS(false) , d_allocator_p(bslma::Default::allocator(basicAllocator)) { BSLS_ASSERT(4 <= d_maxLineLength); BSLS_ASSERT( d_maxLineLength <= 76); if (e_CRLF_MODE != d_lineBreakMode && e_MIXED_MODE != d_lineBreakMode) { int len = sizeof(equivalenceClassMap); d_equivClass_p = static_cast<char *>(d_allocator_p->allocate(len)); bsl::memcpy(d_equivClass_p, s_defaultEquivClass_p, len); d_equivClass_p['\r'] = CC; if (e_BINARY_MODE == d_lineBreakMode) { d_equivClass_p['\n'] = CC; } } } QuotedPrintableEncoder::QuotedPrintableEncoder( const char *extraCharsToEncode, QuotedPrintableEncoder::LineBreakMode lineBreakMode, int maxLineLength, bslma::Allocator *basicAllocator) : d_lineBreakMode(lineBreakMode) , d_maxLineLength(maxLineLength) , d_outputLength(0) , d_lineLength(0) , d_equivClass_p(const_cast<char *>(s_defaultEquivClass_p)) , d_state(e_INITIAL_STATE) , d_bufferLength(0) , d_lineStart(0) , d_deffered(0) , d_lastWasWS(false) , d_allocator_p(bslma::Default::allocator(basicAllocator)) { BSLS_ASSERT(4 <= d_maxLineLength); BSLS_ASSERT( d_maxLineLength <= 76); // First copy the default mapping table to data member. int len = sizeof(equivalenceClassMap); d_equivClass_p = static_cast<char *>(d_allocator_p->allocate(len)); bsl::memcpy(d_equivClass_p, s_defaultEquivClass_p, len); // Now change the specified individual elements. if (extraCharsToEncode) { len = static_cast<int>(bsl::strlen(extraCharsToEncode)); for (int i = 0; i < len; ++i) { int index = static_cast<unsigned char>(extraCharsToEncode[i]); if (PC == d_equivClass_p[index] || WS == d_equivClass_p[index]) { d_equivClass_p[index] = CC; } } } if (e_CRLF_MODE == d_lineBreakMode || e_MIXED_MODE == d_lineBreakMode) { d_equivClass_p['\r'] = CR; d_equivClass_p['\n'] = LF; } else if (e_LF_MODE == d_lineBreakMode) { d_equivClass_p['\r'] = CC; d_equivClass_p['\n'] = LF; } else { d_equivClass_p['\r'] = CC; d_equivClass_p['\n'] = CC; } } QuotedPrintableEncoder::~QuotedPrintableEncoder() { if (d_equivClass_p != s_defaultEquivClass_p) { d_allocator_p->deallocate(d_equivClass_p); } } // MANIPULATORS int QuotedPrintableEncoder::convert(char *out, int *numOut, int *numIn, const char *begin, const char *end, int maxNumOut) { BSLS_ASSERT(out); BSLS_ASSERT(numOut); BSLS_ASSERT(numIn); BSLS_ASSERT(begin); BSLS_ASSERT(end); if (e_ERROR_STATE == d_state || e_DONE_STATE == d_state) { d_state = e_ERROR_STATE; *numOut = 0; *numIn = 0; return -1; // RETURN } if (0 == maxNumOut) { *numOut = 0; *numIn = 0; return numOutputPending(); // RETURN } if (begin < end) { d_state = e_INPUT_STATE; } const int originalOutputLength = d_outputLength; const char *originalBegin = begin; int maxOutLen = d_outputLength + maxNumOut; while ( d_outputLength != maxOutLen && (begin < end || d_bufferLength)) { while (d_bufferLength && d_outputLength != maxOutLen) { *out++ = d_buffer[--d_bufferLength]; ++d_outputLength; } if (d_deffered && d_outputLength != maxOutLen && begin < end) { if (d_deffered == '\r') { if (LF == d_equivClass_p[static_cast<unsigned char>(*begin)]) { appendHardLineBreak(out++); ++begin; } else { appendAsHex(out++, d_deffered); } } else { if (LF == d_equivClass_p[static_cast<unsigned char>(*begin)] || CR == d_equivClass_p[static_cast<unsigned char>(*begin)]) { appendAsHex(out++, d_deffered); } else { appendPrintable(out++, d_deffered); } } d_deffered = 0; } while ( d_outputLength != maxOutLen && begin < end && 0 == d_deffered && 0 == d_bufferLength) { switch (d_equivClass_p[static_cast<unsigned char>(*begin)]) { case PC: { appendPrintable(out++, *begin++); } break; case CC: { appendAsHex(out++, *begin++); } break; case WS: { d_deffered = *begin++; } break; case CR: { d_deffered = *begin++; } break; case LF: { if ( e_LF_MODE == d_lineBreakMode || e_MIXED_MODE == d_lineBreakMode) { appendHardLineBreak(out++); ++begin; } else { appendAsHex(out++, *begin++); } } break; } } } *numOut = d_outputLength - originalOutputLength; *numIn = static_cast<int>(begin - originalBegin); return numOutputPending(); } int QuotedPrintableEncoder::endConvert(char *out, int *numOut, int maxNumOut) { enum { e_ERROR = -1 }; if (d_state == e_ERROR_STATE || isDone()) { d_state = e_ERROR_STATE; *numOut = 0; return e_ERROR; // RETURN } d_state = e_DONE_STATE; const int originalOutputLength = d_outputLength; int maxOutLen = d_outputLength + maxNumOut; if (d_deffered && d_outputLength != maxOutLen) { appendAsHex(out++, d_deffered, true); d_deffered = 0; } while (d_bufferLength && d_outputLength != maxOutLen) { *out++ = d_buffer[--d_bufferLength]; ++d_outputLength; } *numOut = d_outputLength - originalOutputLength; return numOutputPending(); } } // close package namespace } // close enterprise namespace // ---------------------------------------------------------------------------- // Copyright 2016 Bloomberg Finance L.P. // // 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. // ----------------------------- END-OF-FILE ----------------------------------
31.830097
79
0.538356
9e7c6bad8dc38dc8cd43fbe739f5ef56c9044bff
200
hpp
C++
Algorithm.hpp
NagiSenbon/Algorithm
e8044820a2cdd6a26d58097fd84512f3231d8dd6
[ "Apache-2.0" ]
2
2019-10-07T01:48:53.000Z
2019-10-13T08:24:22.000Z
Algorithm.hpp
NagiSenbon/Algorithm
e8044820a2cdd6a26d58097fd84512f3231d8dd6
[ "Apache-2.0" ]
null
null
null
Algorithm.hpp
NagiSenbon/Algorithm
e8044820a2cdd6a26d58097fd84512f3231d8dd6
[ "Apache-2.0" ]
null
null
null
#pragma once #include "src/Headers.hpp" #include "src/Heap.hpp" #include "src/Math.hpp" #include "src/Meta.hpp" #include "src/Queue.hpp" #include "src/Sort.hpp" // #include "src/Tensor.hpp"
20
29
0.675
9e7fb447028b2423a142d6d793883c71cb0ceb47
350
cp
C++
CocosBuilder/CCBFileRunDelay/CCBFileRunDelay.cp
chipsCode/cocosbuilder3
96bfe3089b87e52964c88e11e8fe1678d446b905
[ "MIT", "BSD-2-Clause", "BSD-3-Clause" ]
2
2015-01-04T01:07:04.000Z
2015-07-25T02:34:56.000Z
CocosBuilder/CCBFileRunDelay/CCBFileRunDelay.cp
chipsCode/cocosbuilder3
96bfe3089b87e52964c88e11e8fe1678d446b905
[ "MIT", "BSD-2-Clause", "BSD-3-Clause" ]
null
null
null
CocosBuilder/CCBFileRunDelay/CCBFileRunDelay.cp
chipsCode/cocosbuilder3
96bfe3089b87e52964c88e11e8fe1678d446b905
[ "MIT", "BSD-2-Clause", "BSD-3-Clause" ]
null
null
null
/* * CCBFileRunDelay.cp * CCBFileRunDelay * * Created by Qidea on 11/13/13. * * */ #include "CCBFileRunDelay.h" #include "CCBFileRunDelayPriv.h" CFStringRef CCBFileRunDelayUUID(void) { CCCBFileRunDelay* theObj = new CCCBFileRunDelay; return theObj->UUID(); } CFStringRef CCCBFileRunDelay::UUID() { return CFSTR("0001020304050607"); }
15.217391
49
0.722857
9e8113d1fca423b20b9a8299dc50a8aa10fd200d
11,716
cpp
C++
kcfi/llvm-kcfi/lib/CodeGen/CFI.cpp
IntelSTORM/Projects
b983417a5ca22c7679da5a1144b348863bea5698
[ "Intel" ]
1
2022-01-11T11:12:00.000Z
2022-01-11T11:12:00.000Z
kcfi/llvm-kcfi/lib/CodeGen/CFI.cpp
IntelSTORMteam/Jurassic-Projects
b983417a5ca22c7679da5a1144b348863bea5698
[ "Intel" ]
null
null
null
kcfi/llvm-kcfi/lib/CodeGen/CFI.cpp
IntelSTORMteam/Jurassic-Projects
b983417a5ca22c7679da5a1144b348863bea5698
[ "Intel" ]
null
null
null
//===---- CFI.cpp - kCFI LLVM IR analyzes and transformation --------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // LLVM IR analyzes / transformations to enable kCFI backend instrumentation // //===----------------------------------------------------------------------===// #include <iostream> #include <sstream> #include <fstream> #include <list> #include "llvm/ADT/IndexedMap.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/SetVector.h" #include "llvm/ADT/SmallSet.h" #include "llvm/ADT/Statistic.h" #include "llvm/CodeGen/CFGforCFI.h" #include "llvm/CodeGen/MachineDominators.h" #include "llvm/CodeGen/MachineFrameInfo.h" #include "llvm/CodeGen/MachineFunction.h" #include "llvm/CodeGen/MachineInstr.h" #include "llvm/CodeGen/MachineLoopInfo.h" #include "llvm/CodeGen/MachineModuleInfo.h" #include "llvm/CodeGen/MachineRegisterInfo.h" #include "llvm/CodeGen/Passes.h" #include "llvm/CodeGen/RegisterScavenging.h" #include "llvm/CodeGen/StackProtector.h" #include "llvm/CodeGen/WinEHFuncInfo.h" #include "llvm/IR/DiagnosticInfo.h" #include "llvm/IR/InlineAsm.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/ValueMap.h" #include "llvm/Transforms/IPO.h" #include "llvm/ADT/Statistic.h" #include "llvm/IR/CFG.h" #include "llvm/IR/Dominators.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/Module.h" #include "llvm/Pass.h" #include "llvm/Transforms/Utils/Cloning.h" #include "llvm/Transforms/Utils/CodeExtractor.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/Debug.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Target/TargetFrameLowering.h" #include "llvm/Target/TargetInstrInfo.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Target/TargetRegisterInfo.h" #include "llvm/Target/TargetSubtargetInfo.h" #include "llvm/Transforms/Utils/BasicBlockUtils.h" #include <climits> using namespace llvm; #define DEBUG_TYPE "cfi" extern cl::opt<bool> CFICoarse; extern CFICFG cfi; extern cl::opt<bool> CFIBuildCFG; extern cl::opt<bool> CFIv; extern cl::opt<bool> CFIvv; extern cl::opt<bool> CFICGD; extern cl::opt<bool> CFIMapDecls; static CFIUtils u; namespace { class CFI : public ModulePass { public: static char ID; CFI() : ModulePass(ID) { initializeCFIPass(*PassRegistry::getPassRegistry()); } bool runOnModule(Module &M) override; bool shouldCGD(Function *F); void dumpAliases(Module &M); void computeCalls(Module &M); void computeFunctions(Module &M); int tagCalls(Module &M); void CGD(Module &M); int tagFunctions(Module &M); void computeAndTag(Module &M); }; } char CFI::ID = 0; char &llvm::CFIID = CFI::ID; INITIALIZE_PASS_BEGIN(CFI, "CFITagger", "CFI Function Tag Placer", false, false) INITIALIZE_PASS_END(CFI, "CFITagger", "CFI Function Tag Placer", false, false) bool CFI::runOnModule(Module &M) { // Templates generated using LLVM's C++ backend. // TODO: Improve variables/types/function declarations below if(CFIBuildCFG){ GlobalVariable* CFIGlobalVar = M.getGlobalVariable("global_signature"); if(!CFIGlobalVar){ CFIGlobalVar = new GlobalVariable(M, Type::getInt32Ty(M.getContext()), false, GlobalValue::LinkOnceODRLinkage, 0, "global_signature"); CFIGlobalVar->setAlignment(1); CFIGlobalVar->setThreadLocal(false); } ConstantInt* type = ConstantInt::get(M.getContext(), APInt(32, StringRef("0"), 10)); CFIGlobalVar->setInitializer(type); } std::vector<Type*>args; args.push_back(IntegerType::get(M.getContext(), 32)); args.push_back(IntegerType::get(M.getContext(), 32)); FunctionType* func_type = FunctionType::get(Type::getVoidTy(M.getContext()), args, false); Function* cvh = M.getFunction("call_violation_handler"); if (!cvh) { cvh = Function::Create(func_type, GlobalValue::ExternalLinkage, "call_violation_handler", &M); } cvh->setCallingConv(CallingConv::PreserveMost); Function* rvh = M.getFunction("ret_violation_handler"); if (!rvh) { rvh = Function::Create(func_type, GlobalValue::ExternalLinkage, "ret_violation_handler", &M); } rvh->setCallingConv(CallingConv::PreserveMost); AttributeSet cvh_PAL; { SmallVector<AttributeSet, 4> Attrs; AttributeSet PAS; { AttrBuilder B; B.addAttribute(Attribute::NoUnwind); B.addAttribute(Attribute::UWTable); PAS = AttributeSet::get(M.getContext(), ~0U, B); } Attrs.push_back(PAS); cvh_PAL = AttributeSet::get(M.getContext(), Attrs); } cvh->setAttributes(cvh_PAL); AttributeSet rvh_PAL; { SmallVector<AttributeSet, 4> Attrs; AttributeSet PAS; { AttrBuilder B; B.addAttribute(Attribute::NoUnwind); B.addAttribute(Attribute::UWTable); PAS = AttributeSet::get(M.getContext(), ~0U, B); } Attrs.push_back(PAS); rvh_PAL = AttributeSet::get(M.getContext(), Attrs); } rvh->setAttributes(cvh_PAL); // CFI required symbols created above, now start the analysis computeAndTag(M); return true; } bool CFI::shouldCGD(Function *F){ bool v = true; StringRef handle = "_kcfi"; if(F->getName().endswith(handle)) v = false; handle = "call_violation_handler"; if(F->getName().equals_lower(handle)) v = false; handle = "ret_violation_handler"; if(F->getName().equals_lower(handle)) v = false; handle = "__brk_reservation_fn_"; if(F->getName().startswith(handle)) v = false; if(!v) return false; if(cfi.differentEdgesToStrongerNode(F)){ u.warn("Found weak linkage replacement that should be cloned\n"); return true; } if(cfi.differentEdgesToNode(F)) return true; return false; } void CFI::CGD(Module &M){ std::stringstream fname; for(Module::iterator m = M.begin(), me = M.end(); m != me; ++m){ Function *Original = m, *Clone, *HackF; if(!shouldCGD(Original)){ // if do not clone this f; check if it is an alias if it is an alias, // materialize the aliasee and then check if it should be cloned. std::string aliasee = cfi.checkWeakAlias(Original); if(aliasee.length() > 0){ fname.str(std::string()); fname.clear(); fname << aliasee; Function *a; a = M.getFunction(fname.str()); if(!a){ a = Function::Create(Original->getFunctionType(), GlobalValue::ExternalLinkage, fname.str(), &M); } a->setCallingConv(CallingConv::C); if(!shouldCGD(a)){ a->removeFromParent(); } } continue; } fname.str(std::string()); fname.clear(); fname << Original->getName().str() << "_kcfi"; if(Original->isDeclaration()){ Function* c = Function::Create(Original->getFunctionType(), GlobalValue::ExternalLinkage, fname.str(), &M); c->setCallingConv(CallingConv::C); } else { ValueToValueMapTy VMap; Clone = CloneFunction(Original, VMap, false); M.getFunctionList().push_back(Clone); CFINode n = cfi.getNode(Original, true); Clone->setCFINode(n); HackF = M.getFunction(fname.str()); if(HackF){ fprintf(stderr, "** into clone %s\n", fname.str().c_str()); HackF->replaceAllUsesWith(Clone); HackF->eraseFromParent(); } Clone->setName(fname.str()); } } } void CFI::dumpAliases(Module &M){ for(GlobalAlias &GA : M.aliases()){ if(cfi.getAlias(GA.getName()).length() > 0){ if(strcmp(cfi.getAlias(GA.getName()).c_str(), GA.getAliasee()->stripPointerCasts()->getName().str() .c_str())!=0){ fprintf(stderr, "Clashing aliases:\n Alias/value: "); GA.dump(); fprintf(stderr, "%s\n Aliasee/value:", GA.getName().str().c_str()); GA.getAliasee()->dump(); fprintf(stderr, "%s", GA.getAliasee()->stripPointerCasts()->getName() .str().c_str()); } else { continue; } } cfi.setAlias(GA.getName(), GA.getAliasee()->stripPointerCasts()->getName() .str().c_str()); } cfi.storeAliases(); } void CFI::computeAndTag(Module &M){ if(CFICoarse) return; if(CFIBuildCFG){ computeFunctions(M); computeCalls(M); cfi.storeCFG(); if(CFIMapDecls) cfi.storeDecls(); dumpAliases(M); } else { tagFunctions(M); if(CFICGD) CGD(M); tagCalls(M); } } int CFI::tagCalls(Module &M){ int n = 0; CFICluster c; for(Module::iterator m = M.begin(), me = M.end(); m != me; ++m){ Function &Fn = *m; for(Function::iterator bb = Fn.begin(), bbe = Fn.end(); bb != bbe; ++bb){ BasicBlock &b = *bb; for(BasicBlock::iterator i = b.begin(), ie = b.end(); i != ie; ++i){ CallInst *CI = dyn_cast_or_null<CallInst>(i); if(CI && u.isICall(CI)){ c = cfi.getCluster(CI->getFunctionType()); if(!c.id){ cfi_er << "Unable to get cluster " << Fn.getName().str(); u.error(true); } CI->setCFITag(c.id); n++; if(CFIvv) fprintf(stderr, "CFIMsg: tagged icall: Tag ID %x %s to %s\n", c.id, Fn.getName().str().c_str(), c.proto); } } } } return n; } void CFI::computeCalls(Module &M){ CFIEdge e; std::string t; for(Module::iterator m = M.begin(), me = M.end(); m != me; ++m){ Function &Fn = *m; for(Function::iterator bb = Fn.begin(), bbe = Fn.end(); bb != bbe; ++bb){ BasicBlock &b = *bb; for(BasicBlock::iterator i = b.begin(), ie = b.end(); i != ie; ++i){ CallInst *CI = dyn_cast_or_null<CallInst>(i); if(CI){ if(u.isICall(CI)){ CallInst *CI = dyn_cast<CallInst>(i); Type *proto = CI->getFunctionType(); e = cfi.createEdge(m, proto); if(!e.id) u.error("Unable to create edge", true); } else if(u.isDCall(CI)){ CallInst *CI = dyn_cast<CallInst>(i); Function *F = CI->getCalledFunction(); if(F){ std::stringstream s; if(F->getName().startswith("llvm.")) continue; } } } } } } } void CFI::computeFunctions(Module &M){ CFINode n; std::string t; for(Module::iterator m = M.begin(), me = M.end(); m != me; ++m){ Function &Fn = *m; if(Fn.isDeclaration()){ if(Fn.getName().startswith("llvm.")) continue; if(CFIMapDecls) cfi.createDecl(&Fn); continue; } n = cfi.createNode(&Fn); if(!n.id) u.error("Unable to create node", true); if(CFIv){ cfi_msg << "Tags created for " << Fn.getName().str() << "\n"; u.msg(); } Fn.setCFINode(n); } } int CFI::tagFunctions(Module &M){ CFINode n; CFICluster c; std::string t; int i = 0; for(Module::iterator m = M.begin(), me = M.end(); m != me; ++m){ Function &Fn = *m; if(Fn.isDeclaration()) continue; n = cfi.getNode(m, true); c = cfi.getCluster(Fn.getFunctionType()); if(!n.id){ cfi.dumpCFG(); Fn.dump(); cfi_er << "Unable to get node" << Fn.getName().str() << "\n"; u.error(true); } Fn.setCFINode(n); Fn.setCFICluster(c); i++; } return i; }
29.964194
80
0.597986
9e877c98b23dfe47cefd55199d26bc9eba31bba1
1,689
cpp
C++
cpp/leetcode/LongestStringChain.cpp
danyfang/SourceCode
8168f6058648f2a330a7354daf3a73a4d8a4e730
[ "MIT" ]
null
null
null
cpp/leetcode/LongestStringChain.cpp
danyfang/SourceCode
8168f6058648f2a330a7354daf3a73a4d8a4e730
[ "MIT" ]
null
null
null
cpp/leetcode/LongestStringChain.cpp
danyfang/SourceCode
8168f6058648f2a330a7354daf3a73a4d8a4e730
[ "MIT" ]
null
null
null
//Leetcode Problem No 1048. Longest String Chain //Solution written by Xuqiang Fang on 18 May, 2019 #include <iostream> #include <vector> #include <string> #include <algorithm> #include <unordered_map> #include <unordered_set> #include <stack> #include <queue> using namespace std; class Solution{ public: int longestStrChain(vector<string>& words) { sort(words.begin(), words.end(), [](string& a , string& b){ return a.size() < b.size(); }); const int n = words.size(); ans = 0; vector<vector<int>> graph(n, vector<int>(n, 0)); for(int i=0; i<n; ++i){ for(int j=i+1; j<n; ++j){ if(ischain(words[i], words[j])){ graph[i][j] = 1; } } } for(int i=0; i<n; ++i){ for(int j=0; j<n; ++j){ cout << graph[i][j] << " "; } cout << endl; } for(int i=0; i<n; ++i){ dfs(graph, n, i, 1); } return ans; } private: int ans; void dfs(vector<vector<int>>& graph, const int n, int i, int level){ ans = max(ans, level); for(int j=i+1; j<n; ++j){ if(graph[i][j] == 1){ dfs(graph, n, j, level+1); } } } bool ischain(string& a, string& b){ if(b.size()-a.size() != 1 ){ return false; } int num[26] = {0}; for(auto& x : a){ num[x-'a']++; } for(auto& x : b){ num[x-'a']--; } int count = 0; for(auto i : num){ if(i == 0){ count++; } } return count == 25; } }; int main(){ Solution s; vector<string> words{"a","b","ba","bca","bda","bdca"}; cout << s.longestStrChain(words) << endl; return 0; }
21.653846
72
0.487863
9e8c11d9faa94fe11338d41a60378b8707f4955e
2,876
cpp
C++
src/window/preferences/init_chilren.cpp
LibreTextus/LibreTextus
a142c0bed2237b1b252e1ff5dcfdbe82bd4439d3
[ "CC0-1.0" ]
3
2020-08-26T06:18:42.000Z
2021-01-16T17:22:29.000Z
src/window/preferences/init_chilren.cpp
LibreTextus/LibreTextus
a142c0bed2237b1b252e1ff5dcfdbe82bd4439d3
[ "CC0-1.0" ]
null
null
null
src/window/preferences/init_chilren.cpp
LibreTextus/LibreTextus
a142c0bed2237b1b252e1ff5dcfdbe82bd4439d3
[ "CC0-1.0" ]
null
null
null
#include "preferences.hpp" void Libre::PreferencesWindow::add_themes_to_themes_combo() { std::vector<std::string> v = this->settings.get_children("themes", "name"); for (std::vector<std::string>::iterator i = v.begin(); i != v.end(); i++) { this->ui_pane.get_theme()->get_element()->append(*i); if (*i == this->settings.get_attribute("themes", "active")) { this->ui_pane.get_theme()->get_element()->set_active_text(*i); } } } void Libre::PreferencesWindow::add_locales_to_locales_combo() { this->ui_pane.get_locale()->get_element()->append(_("System default")); for (auto & i : std::experimental::filesystem::directory_iterator(DATA("../locale"))) { this->ui_pane.get_locale()->get_element()->append(i.path().filename().string()); } this->ui_pane.get_locale()->get_element()->set_active_text( (this->settings.get_attribute("locale", "locale").empty() ? _("System default") : this->settings.get_attribute("locale", "locale")) ); } void Libre::PreferencesWindow::set_font_size_adjustment() { this->ui_pane.get_font_size()->get_element()->set_adjustment( Gtk::Adjustment::create(std::stoi(this->settings.get_attribute("font", "size")), 0, 100) ); } void Libre::PreferencesWindow::create_css_context() { Glib::RefPtr<Gdk::Screen> screen = Gdk::Screen::get_default(); this->theme_css_provider = Gtk::CssProvider::create(); this->font_size_css_provider = Gtk::CssProvider::create(); this->get_style_context()->add_provider_for_screen(screen, this->theme_css_provider, GTK_STYLE_PROVIDER_PRIORITY_APPLICATION); this->get_style_context()->add_provider_for_screen(screen, this->font_size_css_provider, GTK_STYLE_PROVIDER_PRIORITY_APPLICATION); this->theme_css_provider->load_from_path(DATA(this->settings.get_attribute("themes", "active") + ".css")); this->font_size_css_provider->load_from_data( "#text_view { font-size: " + this->settings.get_attribute("font", "size") + "px;}" ); } void Libre::PreferencesWindow::set_package_manager(Libre::PackageManager * pm) { this->package_manager = pm; std::vector<std::string> v = this->package_manager->get_sources(); for (std::vector<std::string>::const_iterator i = v.begin(); i != v.end(); i++) { this->book_manager_pane.get_book_list()->append(*i); this->book_manager_pane.get_book_list()->get_items()->back()->set_active( this->package_manager->is_enabled(*i) ); this->book_manager_pane.get_default_source()->get_element()->append(*i); this->book_manager_pane.get_book_list()->get_items()->back()->signal_clicked().connect( sigc::bind<Gtk::CheckButton *>( sigc::mem_fun(this, &Libre::PreferencesWindow::enable_changed), this->book_manager_pane.get_book_list()->get_items()->back() ) ); } this->book_manager_pane.get_default_source()->get_element()->set_active_text(this->settings.get_attribute("startupfile", "file")); }
37.350649
131
0.714882
9e8dc554686bf44921293885bf7ce947bc2e370e
1,291
cpp
C++
src/thumbnailholder.cpp
digitalsurgeon/EasyWallpapers
86f62ad6453ed079f9b889d6adc910f0d89092c1
[ "MIT" ]
null
null
null
src/thumbnailholder.cpp
digitalsurgeon/EasyWallpapers
86f62ad6453ed079f9b889d6adc910f0d89092c1
[ "MIT" ]
null
null
null
src/thumbnailholder.cpp
digitalsurgeon/EasyWallpapers
86f62ad6453ed079f9b889d6adc910f0d89092c1
[ "MIT" ]
null
null
null
#include "thumbnailholder.h" #if defined(Q_OS_SYMBIAN) #include <e32std.h> #include <touchfeedback.h> #endif ThumbnailHolder::ThumbnailHolder() : iPixmap(NULL) { setFlag(QGraphicsItem::ItemClipsToShape); } ThumbnailHolder::~ThumbnailHolder() { delete iPixmap; } QRectF ThumbnailHolder::boundingRect() const { if (!iPixmap) return QRectF(0,0,420,420); return QRectF(QPointF(0,0), iPixmap->size()); } void ThumbnailHolder::paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *) { if(iPixmap) { const QRect br = boundingRect().toRect(); painter->drawPixmap(br, *iPixmap); } } void ThumbnailHolder::mousePressEvent(QGraphicsSceneMouseEvent *) { #if defined(Q_OS_SYMBIAN) MTouchFeedback* feedBack = MTouchFeedback::Instance(); if (feedBack) { feedBack->InstantFeedback(ETouchFeedbackBasic); } #endif emit thmbnailTapped(); } void ThumbnailHolder::setPixmap(const QPixmap &pixmap) { delete iPixmap; prepareGeometryChange(); iPixmap = new QPixmap(pixmap); } void ThumbnailHolder::setImageUrl ( const QString& aUrl) { iImageUrl = aUrl; } QString ThumbnailHolder::imageUrl() const { return iImageUrl; }
18.985294
80
0.660728
9e8ecb5a2f10b5b2c0fae200a98321ecacf7a626
3,623
cxx
C++
source/opengl/ui_renderer.cxx
bjadamson/BoomHS
60b5d8ddc2490ec57e8f530ba7ce3135221e2ec4
[ "MIT" ]
2
2016-07-22T10:09:21.000Z
2017-09-16T06:50:01.000Z
source/opengl/ui_renderer.cxx
bjadamson/BoomHS
60b5d8ddc2490ec57e8f530ba7ce3135221e2ec4
[ "MIT" ]
14
2016-08-13T22:45:56.000Z
2018-12-16T03:56:36.000Z
source/opengl/ui_renderer.cxx
bjadamson/BoomHS
60b5d8ddc2490ec57e8f530ba7ce3135221e2ec4
[ "MIT" ]
null
null
null
#include <opengl/ui_renderer.hpp> #include <opengl/bind.hpp> #include <opengl/draw_info.hpp> #include <opengl/gpu.hpp> #include <opengl/renderer.hpp> #include <opengl/shader.hpp> #include <boomhs/camera.hpp> #include <boomhs/math.hpp> #include <boomhs/rectangle.hpp> #include <boomhs/shape.hpp> using namespace boomhs; using namespace boomhs::math; namespace opengl { UiRenderer::UiRenderer(static_shaders::BasicMvWithUniformColor&& sp2d, Viewport const& vp) : sp2d_(MOVE(sp2d)) { resize(vp); } void UiRenderer::resize(Viewport const& vp) { int constexpr NEAR_PM = -1.0; int constexpr FAR_PM = 1.0f; Frustum const fr{ vp.left(), vp.right(), vp.bottom(), vp.top(), NEAR_PM, FAR_PM }; auto constexpr ZOOM = glm::ivec2{0}; pm_ = CameraORTHO::compute_pm(fr, vp.size(), constants::ZERO, ZOOM); } void UiRenderer::draw_rect_impl(common::Logger& logger, ModelViewMatrix const& mv, DrawInfo& di, Color const& color, GLenum const dm, ShaderProgram& sp, DrawState& ds) { BIND_UNTIL_END_OF_SCOPE(logger, sp); shader::set_uniform(logger, sp, "u_mv", mv); shader::set_uniform(logger, sp, "u_color", color); BIND_UNTIL_END_OF_SCOPE(logger, di); OR::draw_2delements(logger, dm, sp, di.num_indices(), ds); } void UiRenderer::draw_rect(common::Logger& logger, DrawInfo& di, Color const& color, GLenum const dm, DrawState& ds) { auto const& mv = pm_; draw_rect_impl(logger, mv, di, color, dm, sp2d_.sp(), ds); } void UiRenderer::draw_rect(common::Logger& logger, ModelMatrix const& mmatrix, DrawInfo& di, Color const& color, GLenum const dm, DrawState& ds) { auto const mv = pm_ * mmatrix; draw_rect_impl(logger, mv, di, color, dm, sp2d_.sp(), ds); } //////////////////////////////////////////////////////////////////////////////////////////////////// // static_shaders::BasicMvWithUniformColor static_shaders::BasicMvWithUniformColor static_shaders::BasicMvWithUniformColor::create(common::Logger& logger) { constexpr auto vert_source = GLSL_SOURCE(R"GLSL( in vec3 a_position; uniform mat4 u_mv; uniform vec4 u_color; out vec4 v_color; void main() { gl_Position = u_mv * vec4(a_position, 1.0); v_color = u_color; } )GLSL"); static auto frag_source = GLSL_SOURCE(R"GLSL( in vec4 v_color; out vec4 fragment_color; void main() { fragment_color = v_color; } )GLSL"); auto api = AttributePointerInfo{0, GL_FLOAT, AttributeType::POSITION, 3}; auto sp = make_shaderprogram_expect(logger, vert_source, frag_source, MOVE(api)); return static_shaders::BasicMvWithUniformColor{MOVE(sp)}; } /////////////////////////////////////////////////////////////////////////////////////////////// // ProgramAndDrawInfo ProgramAndDrawInfo::ProgramAndDrawInfo(static_shaders::BasicMvWithUniformColor&& p, DrawInfo&& di) : program(MOVE(p)) , dinfo(MOVE(di)) { } ProgramAndDrawInfo ProgramAndDrawInfo::create_rect(common::Logger& logger, RectFloat const& rect, static_shaders::BasicMvWithUniformColor&& program, GLenum const dm) { auto builder = RectBuilder{rect}; builder.draw_mode = dm; auto const& va = program.sp().va(); auto dinfo = OG::copy_rectangle(logger, va, builder.build()); return ProgramAndDrawInfo{MOVE(program), MOVE(dinfo)}; } ProgramAndDrawInfo ProgramAndDrawInfo::create_rect(common::Logger& logger, RectFloat const& rect, GLenum const dm) { auto program = static_shaders::BasicMvWithUniformColor::create(logger); return create_rect(logger, rect, MOVE(program), dm); } } // namespace opengl
26.837037
111
0.665471
9e9062b2ab3c13a91fb34a48dc732c589d6af198
1,136
cpp
C++
Sid's Contests/LeetCode contests/May Challenge/Non Decreasing Array.cpp
Tiger-Team-01/DSA-A-Z-Practice
e08284ffdb1409c08158dd4e90dc75dc3a3c5b18
[ "MIT" ]
14
2021-08-22T18:21:14.000Z
2022-03-08T12:04:23.000Z
Sid's Contests/LeetCode contests/May Challenge/Non Decreasing Array.cpp
Tiger-Team-01/DSA-A-Z-Practice
e08284ffdb1409c08158dd4e90dc75dc3a3c5b18
[ "MIT" ]
1
2021-10-17T18:47:17.000Z
2021-10-17T18:47:17.000Z
Sid's Contests/LeetCode contests/May Challenge/Non Decreasing Array.cpp
Tiger-Team-01/DSA-A-Z-Practice
e08284ffdb1409c08158dd4e90dc75dc3a3c5b18
[ "MIT" ]
5
2021-09-01T08:21:12.000Z
2022-03-09T12:13:39.000Z
class Solution { public: bool isSorted(vector<int> nums) { vector<int> res; for(int i = 0; i < nums.size(); i++) res.push_back(nums[i]); sort(res.begin(), res.end()); for(int i = 0; i < res.size(); i++) if(res[i] != nums[i]) return false; return true; } bool checkPossibility(vector<int>& nums) { //OM GAN GANAPATHAYE NAMO NAMAH //JAI SHRI RAM //JAI BAJRANGBALI //AMME NARAYANA, DEVI NARAYANA, LAKSHMI NARAYANA, BHADRE NARAYANA vector<int> res; for(int i = 0; i < nums.size(); i++) res.push_back(nums[i]); for(int i = 0; i < nums.size()-1; i++) { if(nums[i] > nums[i+1]) { nums[i+1] = nums[i]; break; } } bool x = isSorted(nums); for(int i = 0; i < res.size()-1; i++) { if(res[i] > res[i+1]) { res[i] = res[i+1]; break; } } bool y = isSorted(res); return x|y; } };
26.418605
73
0.415493
9e90a644d3f786772ec655721f087a69972ab44f
59
cpp
C++
C++/Algorytmy dla zabawy/Quiz/start.cpp
Kwandes/highschool-code
ffaf7aea78236cec709ec7c70886df5427005332
[ "MIT" ]
null
null
null
C++/Algorytmy dla zabawy/Quiz/start.cpp
Kwandes/highschool-code
ffaf7aea78236cec709ec7c70886df5427005332
[ "MIT" ]
null
null
null
C++/Algorytmy dla zabawy/Quiz/start.cpp
Kwandes/highschool-code
ffaf7aea78236cec709ec7c70886df5427005332
[ "MIT" ]
null
null
null
#include <iostream> #include "quiz.h" using namespace std;
14.75
20
0.745763
9e91d353b7c868acdb6e2efdcbe5bcf792310ffd
96
cpp
C++
src/widgets/Library/ProgramLibraryController.cpp
javedlingasur/CompileOne
646da061ea9a8c427a533490cb612f5858de3f09
[ "MIT" ]
null
null
null
src/widgets/Library/ProgramLibraryController.cpp
javedlingasur/CompileOne
646da061ea9a8c427a533490cb612f5858de3f09
[ "MIT" ]
null
null
null
src/widgets/Library/ProgramLibraryController.cpp
javedlingasur/CompileOne
646da061ea9a8c427a533490cb612f5858de3f09
[ "MIT" ]
null
null
null
#include "ProgramLibraryController.h" ProgramLibraryController::ProgramLibraryController() { }
16
52
0.833333
9e9928d6d8f93fef0c661d8e2b30a0046d429f03
4,688
cpp
C++
src/c-API/cTracer.cpp
mensinda/tracer
874d859a1ac98f296610c8d634eb557e5bc9c515
[ "BSD-3-Clause" ]
11
2017-07-04T11:23:19.000Z
2021-08-24T05:20:01.000Z
src/c-API/cTracer.cpp
mensinda/tracer
874d859a1ac98f296610c8d634eb557e5bc9c515
[ "BSD-3-Clause" ]
null
null
null
src/c-API/cTracer.cpp
mensinda/tracer
874d859a1ac98f296610c8d634eb557e5bc9c515
[ "BSD-3-Clause" ]
4
2017-07-07T19:36:16.000Z
2022-01-05T15:30:08.000Z
/* Copyright (c) 2017, Daniel Mensinger * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Daniel Mensinger 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 Daniel Mensinger BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ //! \file cTracer.cpp #include "tracer.h" #include "tracerDef.hpp" #include "tracerInternal.hpp" #include <limits> #include <stddef.h> #include <string.h> using namespace tracer; using namespace std; extern "C" { //! \brief Wrapper for tracer::Tracer::Tracer tr_Tracer_t *tr_getTracer() { tr_Tracer_t *t = new tr_Tracer_t; t->tPTR = &t->tracer; return t; } //! \brief Wrapper for tracer::Tracer::Tracer(TraceerEngines, DebuggerEngines) tr_Tracer_t *tr_getTracerWithParam(TR_TraceerEngines_t tracer, TR_DebuggerEngines_t debugInfo) { tr_Tracer_t *t = new tr_Tracer_t(static_cast<TraceerEngines>(tracer), static_cast<DebuggerEngines>(debugInfo)); t->tPTR = &t->tracer; return t; } //! \brief Creates the priavet C struct form a void pointer to the C++ Tracer object tr_Tracer_t *tr_getTracerFromVoid(void *tVoid) { tr_Tracer_t *t = new tr_Tracer_t; t->tPTR = reinterpret_cast<Tracer *>(tVoid); return t; } //! \brief Wrapper for tracer::Tracer::trace void tr_Tracer__trace(tr_Tracer_t *tracer) { if (!tracer) return; tracer->tPTR->trace(); } /*! * \brief (Indirect) Wrapper for tracer::Tracer::getFrames * \sa tr_Tracer__getFrame */ size_t tr_Tracer__getNumFrames(tr_Tracer_t *tracer) { if (!tracer) return numeric_limits<size_t>::max(); return tracer->tPTR->getFrames()->size(); } /*! * \brief (Indirect) Wrapper for tracer::Tracer::getFrames * \sa tr_Tracer__getNumFrames */ tr_Frame_t tr_Tracer__getFrame(tr_Tracer_t *tracer, size_t frameNum) { tr_Frame_t frame; memset(&frame, 0, sizeof(frame)); if (!tracer) return frame; auto *frames = tracer->tPTR->getFrames(); if (frameNum >= frames->size()) return frame; auto &f = frames->at(frameNum); frame.frameAddr = f.frameAddr; frame.funcName = f.funcName.c_str(); frame.moduleName = f.moduleName.c_str(); frame.fileName = f.fileName.c_str(); frame.line = f.line; frame.column = f.column; if ((f.flags & FrameFlags::HAS_FUNC_NAME) != FrameFlags::HAS_FUNC_NAME) frame.funcName = nullptr; if ((f.flags & FrameFlags::HAS_MODULE_INFO) != FrameFlags::HAS_MODULE_INFO) frame.moduleName = nullptr; if ((f.flags & FrameFlags::HAS_LINE_INFO) != FrameFlags::HAS_LINE_INFO) frame.fileName = nullptr; return frame; } /*! * \brief (Indirect) Wrapper for tracer::Tracer::getAvailableEngines and tracer::Tracer::getAvailableDebuggers */ tr_Tracer_AvailableEngines_t tr_Tracer__getAvailableEngines() { tr_Tracer_AvailableEngines_t result; memset(&result, 0, sizeof(result)); int c = 0; for (auto i : tracer::Tracer::getAvailableEngines()) { result.tracer[c++] = static_cast<TR_TraceerEngines_t>(i); if (c >= 8) break; } c = 0; for (auto i : tracer::Tracer::getAvailableDebuggers()) { result.debuggers[c++] = static_cast<TR_DebuggerEngines_t>(i); if (c >= 8) break; } return result; } //! \brief Destroyes the private C object and the Tracer C++ object UNLESS tr_getTracerFromVoid was used void tr_freeTracer(tr_Tracer_t *tracer) { if (tracer) delete tracer; } }
31.675676
113
0.715657
9e9a7a21b244e330a0fe45bffa695183c9e364d8
2,281
cpp
C++
src/argparse.cpp
The-Compiler/herbstluftwm
a4f13aa299a760841ee204ddb180944bad6ceb2d
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
src/argparse.cpp
The-Compiler/herbstluftwm
a4f13aa299a760841ee204ddb180944bad6ceb2d
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
src/argparse.cpp
The-Compiler/herbstluftwm
a4f13aa299a760841ee204ddb180944bad6ceb2d
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
#include "argparse.h" #include <iostream> using std::string; /** * @brief try to parse the arguments * @param input * @param output * @return return whether there has been an error (true = error, false = no error) */ bool ArgParse::parsingFails(Input& input, Output& output) { size_t mandatoryArguments = 0; size_t optionalArguments = 0; for (const auto& arg : arguments_) { if (arg.optional_) { optionalArguments++; } else { mandatoryArguments++; } } if (input.size() < mandatoryArguments) { output << input.command() << ": Expected "; if (optionalArguments) { output << "between " << mandatoryArguments << " and " << (optionalArguments + mandatoryArguments) << " arguments"; } else if (mandatoryArguments == 1) { output << "one argument"; } else { output << mandatoryArguments << " arguments"; } output << ", but got only " << input.size() << " arguments."; errorCode_ = HERBST_NEED_MORE_ARGS; return true; } // the number of optional arguments that are provided by 'input': size_t optionalArgumentsRemaining = input.size() - mandatoryArguments; for (const auto& arg : arguments_) { if (arg.optional_) { if (optionalArgumentsRemaining) { optionalArgumentsRemaining--; } else { // skip this argument if it's optional and there // are not more optional arguments in the input continue; } } string valueString; // the following can't fail because we checked input.size() before input >> valueString; try { arg.tryParse_(valueString); } catch (std::exception& e) { output << input.command() << ": Cannot parse argument \"" << valueString << "\": " << e.what() << "\n"; errorCode_ = HERBST_INVALID_ARGUMENT; return true; } } // if all arguments were parsed, then we report that there were // no errors. It's ok if there are remaining elements in 'input' that // have not been parsed. return false; }
33.544118
82
0.55765
9e9a9292f67c90512d6916416204819b1fb0ae5b
2,837
cpp
C++
Source/AliveLibAO/RollingBallShaker.cpp
THEONLYDarkShadow/alive_reversing
680d87088023f2d5f2a40c42d6543809281374fb
[ "MIT" ]
1
2021-04-11T23:44:43.000Z
2021-04-11T23:44:43.000Z
Source/AliveLibAO/RollingBallShaker.cpp
THEONLYDarkShadow/alive_reversing
680d87088023f2d5f2a40c42d6543809281374fb
[ "MIT" ]
null
null
null
Source/AliveLibAO/RollingBallShaker.cpp
THEONLYDarkShadow/alive_reversing
680d87088023f2d5f2a40c42d6543809281374fb
[ "MIT" ]
null
null
null
#include "stdafx_ao.h" #include "RollingBallShaker.hpp" #include "Function.hpp" #include "Game.hpp" #include "stdlib.hpp" #include "PsxDisplay.hpp" #include "ScreenManager.hpp" #include "Primitives.hpp" void RollingBallShaker_ForceLink() {} namespace AO { const static PSX_Pos16 sRollingBallShakerScreenOffsets_4BB740[18] = { { 1, 0 }, { 0, 0 }, { -1, 1 }, { 0, 0 }, { -1, -1 }, { 0, 0 }, { 1, -1 }, { 0, 0 }, { 0, 1 }, { 0, 0 }, { 1, 0 }, { 0, 0 }, { 1, 1 }, { 0, 0 }, { -1, -1 }, { 0, 0 }, { 0, -1 }, { 0, 0 } }; RollingBallShaker* RollingBallShaker::ctor_4361A0() { ctor_487E10(1); field_6_flags.Set(Options::eDrawable_Bit4); SetVTable(this, 0x4BB788); field_4_typeId = Types::eRollingBallStopperShaker_58; field_30_shake_table_idx = 0; field_32_bKillMe = 0; // Set externally gObjList_drawables_504618->Push_Back(this); return this; } BaseGameObject* RollingBallShaker::dtor_436200() { SetVTable(this, 0x4BB788); gObjList_drawables_504618->Remove_Item(this); return dtor_487DF0(); } void RollingBallShaker::VUpdate_436260() { field_30_shake_table_idx++; if (field_30_shake_table_idx >= ALIVE_COUNTOF(sRollingBallShakerScreenOffsets_4BB740)) { field_30_shake_table_idx = 0; } } void RollingBallShaker::VRender_436280(PrimHeader** ppOt) { Prim_ScreenOffset* pPrim = &field_10_prim_screen_offset[gPsxDisplay_504C78.field_A_buffer_index + 1]; if (field_32_bKillMe != 0) { // Unshake the screen PSX_Pos16 screenOff = {}; if (gPsxDisplay_504C78.field_A_buffer_index) { screenOff.y = gPsxDisplay_504C78.field_2_height; } InitType_ScreenOffset_496000(pPrim, &screenOff); OrderingTable_Add_498A80(OtLayer(ppOt, Layer::eLayer_0), &pPrim->mBase); // Kill yourself field_6_flags.Set(Options::eDead_Bit3); } else { PSX_Pos16 screenOff = sRollingBallShakerScreenOffsets_4BB740[field_30_shake_table_idx]; if (gPsxDisplay_504C78.field_A_buffer_index) { screenOff.y += gPsxDisplay_504C78.field_2_height; } InitType_ScreenOffset_496000(pPrim, &screenOff); OrderingTable_Add_498A80(OtLayer(ppOt, Layer::eLayer_0), &pPrim->mBase); } pScreenManager_4FF7C8->InvalidateRect_406CC0(0, 0, 640, gPsxDisplay_504C78.field_2_height); } BaseGameObject* RollingBallShaker::VDestructor(signed int flags) { return Vdtor_436350(flags); } void RollingBallShaker::VUpdate() { return VUpdate_436260(); } void RollingBallShaker::VRender(PrimHeader** ppOt) { VRender_436280(ppOt); } RollingBallShaker* RollingBallShaker::Vdtor_436350(signed int flags) { dtor_436200(); if (flags & 1) { ao_delete_free_447540(this); } return this; } }
22.696
105
0.670427
9e9bb1d1c9542e659e86698919f1538459c57b57
337
cpp
C++
CodeForces/Complete/700-799/714A-MeetingOldFriends.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
36
2019-12-27T08:23:08.000Z
2022-01-24T20:35:47.000Z
CodeForces/Complete/700-799/714A-MeetingOldFriends.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
10
2019-11-13T02:55:18.000Z
2021-10-13T23:28:09.000Z
CodeForces/Complete/700-799/714A-MeetingOldFriends.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
53
2020-08-15T11:08:40.000Z
2021-10-09T15:51:38.000Z
#include <cstdio> int main(){ long long l1, r1, l2, r2, k; scanf("%lld %lld %lld %lld %lld", &l1, &r1, &l2, &r2, &k); long long l = (l1 > l2) ? l1 : l2; long long r = (r1 < r2) ? r1 : r2; long long res = r - l + 1; if(l <= k && k <= r){--res;} if(res <= 0){res = 0;} printf("%lld\n", res); return 0; }
22.466667
91
0.454006
9e9de3e0c55836644fa4ad9692f6e2948e3c5f59
5,983
cpp
C++
lib/Dialect/TPU/Interpreter/core/csc.cpp
sophgo/tpu_compiler
6299ea0a3adae1e5c206bcb9bedf225d16e636db
[ "Apache-2.0" ]
3
2022-03-14T11:47:20.000Z
2022-03-16T01:45:37.000Z
lib/Dialect/TPU/Interpreter/core/csc.cpp
sophgo/tpu_compiler
6299ea0a3adae1e5c206bcb9bedf225d16e636db
[ "Apache-2.0" ]
null
null
null
lib/Dialect/TPU/Interpreter/core/csc.cpp
sophgo/tpu_compiler
6299ea0a3adae1e5c206bcb9bedf225d16e636db
[ "Apache-2.0" ]
null
null
null
#include "tpuc/Interpreter/cpu/csc.hpp" #include "internal.hpp" #include "tpuc/Dialect/TPU/TPUDialect.h" #include "tpuc/MlirModuleInterpreter.h" static inline int align_up(int x, int n) { if (n == 0 || n == 1) { return x; } return ((x + n - 1) / n) * n; } static inline float UINT8(float data) { return static_cast<float>(F32ToUint8(data, 0)); } namespace mlir { // pixel_type 1--i420 2--nv12 3--nv21 void CscOpKernel::yuv_csc(float *input, float *output, int n, int c, int h, int w, std::vector<int> &order, int quant_type, YuvType pixel_type) { int y_w_aligned = align_up(w, y_align); int uv_w_aligned = 0; int y_offset = 0; int u_offset = 0; int v_offset = 0; if (pixel_type == YUV420_PLANAR) { uv_w_aligned = align_up(w / 2, w_align); u_offset = align_up(h * y_w_aligned, channel_align); v_offset = align_up(u_offset + h / 2 * uv_w_aligned, channel_align); } else { uv_w_aligned = align_up(w, w_align); u_offset = align_up(h * y_w_aligned, channel_align); v_offset = u_offset; } int n_stride = align_up(v_offset + h / 2 * uv_w_aligned, channel_align); for (int idx_n = 0; idx_n < n; idx_n++) { for (int idx_h = 0; idx_h < h; idx_h++) { for (int idx_w = 0; idx_w < w; idx_w++) { int y_idx = y_offset + idx_n * n_stride + idx_h * y_w_aligned + idx_w; int u_idx = 0; int v_idx = 0; if (pixel_type == YUV420_PLANAR) { // i420 u_idx = u_offset + idx_n * n_stride + idx_h / 2 * uv_w_aligned + idx_w / 2; v_idx = v_offset + idx_n * n_stride + idx_h / 2 * uv_w_aligned + idx_w / 2; } else if (pixel_type == YUV_NV12) { //nv12 u_idx = u_offset + idx_n * n_stride + idx_h / 2 * uv_w_aligned + idx_w / 2 * 2; v_idx = v_offset + idx_n * n_stride + idx_h / 2 * uv_w_aligned + idx_w / 2 * 2 + 1; } else { //nv21 u_idx = u_offset + idx_n * n_stride + idx_h / 2 * uv_w_aligned + idx_w / 2 * 2 + 1; v_idx = v_offset + idx_n * n_stride + idx_h / 2 * uv_w_aligned + idx_w / 2 * 2; } float y = input[y_idx]; float u = input[u_idx]; float v = input[v_idx]; float r, g, b; if (quant_type == 0) { y = 1.164 * (y - 16.0f); u -= 128; v -= 128; // float: r = y + 1.596 * v; g = y - 0.813 * v - 0.391 * u; b = y + 2.018 * u; } else { // u8 or bf16 y = (float)(uint8_t)y; u = (float)(uint8_t)u; v = (float)(uint8_t)v; y = BF16(BF16(1.164) * (y - 16.0f)); u -= 128.0f; v -= 128.0f; r = BF16(y + BF16(1.596f) * v); g = BF16(BF16(y + BF16(-0.813f) * v) + BF16(-0.391f) * u); b = BF16(y + BF16(2.018f) * u); } r = UINT8(r); g = UINT8(g); b = UINT8(b); float color[3] = {b, g, r}; int c0_idx = idx_n * 3 * h * w + idx_h * w + idx_w; int c1_idx = c0_idx + h * w; int c2_idx = c1_idx + h * w; output[c0_idx] = color[order[0]]; output[c1_idx] = color[order[1]]; output[c2_idx] = color[order[2]]; } } } } CscOpKernel::CscOpKernel(Operation &op, value_map_t &valueMapping, weight_map_t &weightMapping) : CPUOpKernel(op, valueMapping, weightMapping) { auto cscOp = cast<tpu::CscOp>(op); auto input_type = cscOp.input().getType().template cast<TensorType>(); this->input_shape = input_type.getShape(); this->pixel_format = cscOp.pixel_format().str(); this->aligned = cscOp.aligned(); // get tensors input_data = this->opdTensors[0]; output_data = this->resTensor; w_align = cscOp.w_align(); y_align = cscOp.y_align(); channel_align = cscOp.channel_align(); } void CscOpKernel::invoke() { if (shape.size() < 4 || input_shape.size() < 4) { dump(); llvm_unreachable("wrong shape size"); } int on = shape[0]; int oc = shape[1]; int oh = shape[2]; int ow = shape[3]; int ic = input_shape[1]; int ih = input_shape[2]; if (pixel_format == "YUV420_PLANAR") { std::vector<int> orders{0, 1, 2}; yuv_csc(input_data->data(), output_data->data(), on, oc, oh, ow, orders, datatype == DataType::FP32 ? 0 : 1, YUV420_PLANAR); } else if (pixel_format == "YUV_NV12") { std::vector<int> orders{0, 1, 2}; yuv_csc(input_data->data(), output_data->data(), on, oc, oh, ow, orders, datatype == DataType::FP32 ? 0 : 1, YUV_NV12); } else if (pixel_format == "YUV_NV21") { std::vector<int> orders{0, 1, 2}; yuv_csc(input_data->data(), output_data->data(), on, oc, oh, ow, orders, datatype == DataType::FP32 ? 0 : 1, YUV_NV21); } else if (aligned) { if (pixel_format == "RGB_PLANAR" || pixel_format == "BGR_PLANAR" || pixel_format == "RGBA_PLANAR") { // do stride copy to make data unaligned std::vector<int> indices(4, 0); int iw = align_up(shape[3], w_align); int ic_stride = align_up(iw * shape[2], channel_align); int in_stride = ic_stride * ic; std::vector<int32_t> input_stride = {in_stride, ic_stride, iw, 1}; std::vector<int32_t> output_stride = {ow * oh * oc, ow * oh, ow, 1}; stride_copy(input_data->data(), output_data->data(), shape.data(), input_stride.data(), output_stride.data(), 0, indices.data()); } else { // do crop to make data unaligned std::vector<int64_t> crop_shape(input_shape.begin(), input_shape.end()); crop_shape[3] = (int)(oc * oh * ow / (ic * ih)); std::vector<int> crop_offset{0, 0, 0, 0}; std::vector<int> indices(4, 0); crop(input_data->data(), output_data->data(), input_shape.data(), crop_shape.data(), 0, crop_offset.data(), indices.data()); } } else { output_data->assign(input_data->begin(), input_data->end()); } } } // namespace mlir
36.705521
98
0.563263
9e9f8638d6bf5ad630ae93ca7924219572182f61
1,053
cpp
C++
comb_SWEEP_D1_main.cpp
imrehg/bloch
d4920b325b685a0e8842e305f7f9613b6a0fbf42
[ "MIT" ]
2
2016-08-08T12:33:37.000Z
2017-09-15T08:38:55.000Z
comb_SWEEP_D1_main.cpp
imrehg/bloch
d4920b325b685a0e8842e305f7f9613b6a0fbf42
[ "MIT" ]
null
null
null
comb_SWEEP_D1_main.cpp
imrehg/bloch
d4920b325b685a0e8842e305f7f9613b6a0fbf42
[ "MIT" ]
null
null
null
#include "comb.h" int main() { for(int i=0;i<11;i+=1) sweep(30,1000000,10*pow(2,i),1/pow(10,4),0,10,12,10,600,15,0); //sweep steps, total steps, power(uW/cm2),convergence condition,convergence threshold,convergency steps,ADM order,n1 interval,n2 interval,Matrix self multiplication,laser detune //fstream file; //stringstream strstream; //string filename; // //for(int j=2;j<3;j++){ // //filename.clear(); //strstream.clear(); //strstream<<"CenterSweep_"<<j*100000<<"uW.txt"; //strstream>>filename; //cout<<filename.c_str()<<endl; //file.open(filename.c_str(),ios::out | ios::trunc); // // for(int i=-200;i<201;i+=1){ // file<<setiosflags(ios::left)<<setw(30)<<0.0002*i; // file<<setiosflags(ios::left)<<setw(30)<<sweep_single(10.87827848197104833208,100000*j,1/pow(10,4),0,10,12,10,600,15,0.0002*2*pi*i)<<endl; // } // //period, power(uW/cm2),convergence condition,convergence threshold,convergency steps,ADM order,n1 interval,n2 interval,Matrix self multiplication,laser detune //file.close(); // //} return 0; }
29.25
183
0.678063
9ea3996cf5e814c82439232dbd0eeee8ca4018f4
199
cpp
C++
Sandbox/src/SandboxApp.cpp
thiagofsm36/HazelTM
033a0d733183a076ba849026d80a6cf647ad3173
[ "MIT" ]
null
null
null
Sandbox/src/SandboxApp.cpp
thiagofsm36/HazelTM
033a0d733183a076ba849026d80a6cf647ad3173
[ "MIT" ]
null
null
null
Sandbox/src/SandboxApp.cpp
thiagofsm36/HazelTM
033a0d733183a076ba849026d80a6cf647ad3173
[ "MIT" ]
null
null
null
#include <HazelTM.h> class Sandbox: public HazelTM::Application { public: Sandbox() { } ~Sandbox() { } }; HazelTM::Application* HazelTM::CreateApplication() { return new Sandbox(); }
9.045455
52
0.648241
9ea4b8ad82da2c9b3a9535d29b2e02d53215371c
2,723
cpp
C++
Github-Arduino/libraries/ideawu_RTC/base/packet.cpp
famley-richards/Documents-KTibow
b5d2be03ea2f6687cd9d854d9f43ef839a37e275
[ "MIT" ]
null
null
null
Github-Arduino/libraries/ideawu_RTC/base/packet.cpp
famley-richards/Documents-KTibow
b5d2be03ea2f6687cd9d854d9f43ef839a37e275
[ "MIT" ]
null
null
null
Github-Arduino/libraries/ideawu_RTC/base/packet.cpp
famley-richards/Documents-KTibow
b5d2be03ea2f6687cd9d854d9f43ef839a37e275
[ "MIT" ]
null
null
null
#include <stdlib.h> #include "log.h" #include "packet.h" int Packet::parse(){ parsed = true; this->params_.clear(); if(this->len < HEADER_LEN){ return -1; } int size = this->size(); char *head = (char *)this->data(); while(size > 0){ if(head[0] == ' ' || head[0] == '\r'){ head ++; size --; continue; }else if(head[0] == '\n'){ break; } char *body = (char *)memchr(head, ' ', size); if(body == NULL){ return -1; } body ++; int head_len = body - head; if(head[0] < '0' || head[0] > '9'){ log_warn("bad format"); return -1; } char head_str[20]; if(head_len > (int)sizeof(head_str) - 1){ return -1; } memcpy(head_str, head, head_len - 1); // no '\n' head_str[head_len - 1] = '\0'; int body_len = atoi(head_str); if(body_len < 0){ log_warn("bad format"); return -1; } //log_debug("size: %d, head_len: %d, body_len: %d", size, head_len, body_len); size -= head_len + body_len; if(size < 0){ return -1; } this->params_.push_back(Bytes(body, body_len)); head += head_len + body_len; //if(parsed > MAX_PACKET_SIZE){ // log_warn("fd: %d, exceed max packet size, parsed: %d", this->sock, parsed); // return -1; //} } return 1; } int Packet::append(const Bytes &b){ #define MAX_BLOCK_SIZE 10000 #define MAX_BLOCK_SIZE_STR_LEN 5 if(MAX_BLOCK_SIZE_STR_LEN + 2 + b.size() + this->len > MAX_DATA_LEN){ return -1; } char *p = this->buf() + this->len; int size_str_len = sprintf(p, " %d ", b.size()); if(size_str_len < 0){ return -1; } p += size_str_len; memcpy(p, b.data(), b.size()); p += b.size(); int ret = size_str_len + b.size(); this->len += ret; return ret; } int Packet::set_params(const Bytes &b1){ this->len = HEADER_LEN; int ret = 0; int tmp; tmp = this->append(b1); if(tmp == -1){ return -1; } ret += tmp; // add a '\n' to let the packet print-friendly this->buf()[this->len++] = '\n'; return ret; } int Packet::set_params(const Bytes &b1, const Bytes &b2){ this->len = HEADER_LEN; int ret = 0; int tmp; tmp = this->append(b1); if(tmp == -1){ return -1; } ret += tmp; tmp = this->append(b2); if(tmp == -1){ return -1; } ret += tmp; // add a '\n' to let the packet print-friendly this->buf()[this->len++] = '\n'; return ret; } int Packet::set_params(const Bytes &b1, const Bytes &b2, const Bytes &b3){ this->len = HEADER_LEN; int ret = 0; int tmp; tmp = this->append(b1); if(tmp == -1){ return -1; } ret += tmp; tmp = this->append(b2); if(tmp == -1){ return -1; } ret += tmp; tmp = this->append(b3); if(tmp == -1){ return -1; } ret += tmp; // add a '\n' to let the packet print-friendly this->buf()[this->len++] = '\n'; return ret; }
18.909722
81
0.573265
9ea812a3010535aa59762748ff0aa6ef36e1d939
1,554
cpp
C++
src/factory/font.cpp
equal-games/equal
acaf0d456d7b996dd2a6bc23150cd45ddf618296
[ "BSD-2-Clause", "Apache-2.0" ]
7
2019-08-07T21:27:27.000Z
2020-11-27T16:33:16.000Z
src/factory/font.cpp
equal-games/equal
acaf0d456d7b996dd2a6bc23150cd45ddf618296
[ "BSD-2-Clause", "Apache-2.0" ]
null
null
null
src/factory/font.cpp
equal-games/equal
acaf0d456d7b996dd2a6bc23150cd45ddf618296
[ "BSD-2-Clause", "Apache-2.0" ]
null
null
null
/* * Copyright 2019 Equal Games * 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 <equal/core/logger.hpp> #include <equal/factory/dat.hpp> #include <equal/factory/font.hpp> #include <equal/helper/error.hpp> #include <equal/helper/string.hpp> #include <equal/helper/system.hpp> #ifdef EQ_SDL #include <SDL2/SDL_ttf.h> #endif namespace eq { std::unordered_map<std::string, Font *> LoadFontFromDAT() { std::unordered_map<std::string, Font *> fonts; ResourceDAT res; ReadDAT<ResourceDAT>("resources", res); for (auto &font_dat : res.fonts) { Font *font = new Font(); font->name = fmt::format("{0}_{1}", font_dat.name, 16); #ifdef EQ_SDL TTF_Font *sdl_font = TTF_OpenFontRW(SDL_RWFromMem(font_dat.buffer.data(), font_dat.buffer.size()), 1, 16); if (!sdl_font) { TTF_CloseFont(sdl_font); EQ_THROW("Can't load font({}): {}", font->name, TTF_GetError()); } font->data = static_cast<void *>(sdl_font); #endif fonts.try_emplace(font->name, font); } return fonts; } } // namespace eq
28.254545
110
0.698198
9ea8d3c8220c1d7b5590f4de0745222909c735b4
5,155
cpp
C++
Qt_GUI/DisplayPanelWidget.cpp
SDUBigDataCourse/RecursiveSubdivision-basedSampling
a187eabe37e64312b326461d29800f1aff25371c
[ "MIT" ]
5
2020-10-26T09:42:16.000Z
2022-02-16T10:36:24.000Z
Qt_GUI/DisplayPanelWidget.cpp
Ideas-Laboratory/RecursiveSubdivision-basedSampling
2b8cbae9cb72a05089ace5ccee4745d33121d60f
[ "MIT" ]
null
null
null
Qt_GUI/DisplayPanelWidget.cpp
Ideas-Laboratory/RecursiveSubdivision-basedSampling
2b8cbae9cb72a05089ace5ccee4745d33121d60f
[ "MIT" ]
2
2019-09-09T08:01:37.000Z
2019-12-01T03:36:47.000Z
#include "DisplayPanelWidget.h" using namespace std; DisplayPanelWidget::DisplayPanelWidget(SamplingProcessViewer *spv, unordered_map<uint, string> *c2l_mapping, QWidget * parent) : QWidget(parent), viewer(spv), class2label(c2l_mapping) { setFixedWidth(440); container = dynamic_cast<QScrollArea*>(parent); QVBoxLayout *layout = new QVBoxLayout(this); layout->setAlignment(Qt::AlignTop); setLayout(layout); addClassToColorMappingTable(); connect(spv, &SamplingProcessViewer::inputImageChanged, [this]() { clearAllChildren(); addClassToColorMappingTable(); }); connect(spv, &SamplingProcessViewer::areaCreated, [this](IndividualSampleArea* area) { addAreaInfo("r", area->getTotalInfo(), area->getSampleInfo()); }); connect(spv, &SamplingProcessViewer::areaCounted, [this](StatisticalInfo* total_info, StatisticalInfo* sample_info) { addAreaInfo("o", total_info, sample_info); }); connect(spv, &SamplingProcessViewer::adjustmentStart, [this]() { removeSpecifiedChildren([](QWidget* w) { return w->objectName() == "o"; }); }); connect(spv, &SamplingProcessViewer::sampleStart, [this]() { removeSpecifiedChildren([](QWidget* w) { return !w->objectName().isEmpty(); }); }); connect(spv, &SamplingProcessViewer::redrawStart, [this]() { removeSpecifiedChildren([](QWidget* w) { return !w->objectName().isEmpty(); }); }); //connect(spv, &SamplingProcessViewer::pointSelected, [this](uint index, uint class_) { // qDebug() << index << ',' << QString(this->class2label->at(class_).c_str()); //}); } void DisplayPanelWidget::resizeEvent(QResizeEvent * e) { QWidget::resizeEvent(e); container->verticalScrollBar()->setValue(height()); } void DisplayPanelWidget::addClassToColorMappingTable() { QGroupBox *mapping_box = new QGroupBox("Class to Color mapping:", this); QVBoxLayout *box_layout = new QVBoxLayout(mapping_box); mapping_box->setLayout(box_layout); QTableWidget *tw = new QTableWidget(this); tw->setShowGrid(false); tw->setEditTriggers(QAbstractItemView::NoEditTriggers); tw->verticalHeader()->setVisible(false); tw->setRowCount(class2label->size()); tw->setColumnCount(2); tw->setHorizontalHeaderLabels(QStringList{ "Class", "Color" }); tw->setColumnWidth(0, 300); tw->setColumnWidth(1, 70); int rows = 0; for (auto &pr : *class2label) { QTableWidgetItem *newItem = new QTableWidgetItem(tr(pr.second.c_str())); tw->setItem(rows, 0, newItem); newItem = new QTableWidgetItem(); newItem->setBackground(this->viewer->getColorBrushes()[pr.first]); tw->setItem(rows, 1, newItem); ++rows; } tw->setRowCount(rows); box_layout->addWidget(tw); mapping_box->setFixedHeight(tw->horizontalHeader()->height() + 60 + tw->rowHeight(0)*rows); this->layout()->addWidget(mapping_box); } void DisplayPanelWidget::addAreaInfo(const QString& name, StatisticalInfo * total_info, StatisticalInfo * sample_info) { if (total_info->total_num > 0) { QTableWidget *tw = new QTableWidget(this); tw->setObjectName(name); tw->setEditTriggers(QAbstractItemView::NoEditTriggers); tw->verticalHeader()->setVisible(false); tw->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); tw->setRowCount(total_info->class_point_num.size() + 1); tw->setColumnCount(4); tw->setHorizontalHeaderLabels(QStringList{ "", "Actual", "Sample", "Ratio" }); tw->setColumnWidth(0, 70); auto &map_t = total_info->class_point_num, &map_s = sample_info->class_point_num; int rows = 0; for (int i = 0, sz = selected_class_order.size(); i < sz; ++i) { int class_index = selected_class_order[i]; if (map_t.find(class_index) != map_t.end()) { QTableWidgetItem *newItem = new QTableWidgetItem(); newItem->setBackground(this->viewer->getColorBrushes()[class_index]); tw->setItem(rows, 0, newItem); newItem = new QTableWidgetItem(QString::number(map_t[class_index])); tw->setItem(rows, 1, newItem); uint sample_num = map_s.find(class_index) != map_s.end() ? map_s[class_index] : 0; newItem = new QTableWidgetItem(QString::number(sample_num)); tw->setItem(rows, 2, newItem); newItem = new QTableWidgetItem(QString::number(100.0*sample_num/map_t[class_index], 'f', 2) + "%"); tw->setItem(rows, 3, newItem); ++rows; } } tw->setItem(rows, 0, new QTableWidgetItem(tr("Sum:"))); tw->setItem(rows, 1, new QTableWidgetItem(QString::number(total_info->total_num))); tw->setItem(rows, 2, new QTableWidgetItem(QString::number(sample_info->total_num))); tw->setItem(rows, 3, new QTableWidgetItem(QString::number(100.0*sample_info->total_num/total_info->total_num, 'f', 2) + "%")); tw->setRowCount(++rows); tw->setFixedHeight(tw->horizontalHeader()->height() + 4 + tw->rowHeight(0)*rows); this->layout()->addWidget(tw); } delete total_info; delete sample_info; } void DisplayPanelWidget::removeSpecifiedChildren(std::function<bool(QWidget*)> pred) { for (int i = this->layout()->count() - 1; i > -1; --i) { QWidget *w = this->layout()->itemAt(i)->widget(); if (pred(w)) { this->layout()->removeWidget(w); w->close(); } } } void DisplayPanelWidget::clearAllChildren() { removeSpecifiedChildren([](QWidget* w) { return true; }); }
37.627737
183
0.711542
9ea910c3b6479e86e3bac33e8e3cb5d3b2af02b2
2,015
cpp
C++
JayEngine/Jay_Engine/UI_Hierarchy.cpp
Josef212/JayEngine
437faf3c81eb9c13bb99a104338c7de4434323c6
[ "MIT" ]
null
null
null
JayEngine/Jay_Engine/UI_Hierarchy.cpp
Josef212/JayEngine
437faf3c81eb9c13bb99a104338c7de4434323c6
[ "MIT" ]
2
2016-09-27T09:29:06.000Z
2016-11-02T09:42:13.000Z
JayEngine/Jay_Engine/UI_Hierarchy.cpp
Josef212/JayEngine
437faf3c81eb9c13bb99a104338c7de4434323c6
[ "MIT" ]
null
null
null
#include "Application.h" #include "UI_Hierarchy.h" #include "ModuleGOManager.h" #include "GameObject.h" #include "Component.h" #include "Transform.h" #include "Mesh.h" #include "Material.h" #include "ModuleWindow.h" UI_Hierarchy::UI_Hierarchy(bool startEnalbed) : UI_Panel(startEnalbed) { } UI_Hierarchy::~UI_Hierarchy() { } void UI_Hierarchy::Draw() { int w = app->window->GetWidth(); int h = app->window->GetHeight(); //ImGui::SetNextWindowPos(ImVec2(0, 20)); //ImGui::SetNextWindowSize(ImVec2(360, 560)); ImGui::SetNextWindowPos(ImVec2(0, 20)); ImGui::SetNextWindowSize(ImVec2(w*0.2, (h -20)*0.5)); ImGui::Begin("Hierarchy", &active); { GameObject* root = app->goManager->GetSceneroot(); GameObject* selected = app->goManager->GetSelected(); ImGuiTreeNodeFlags nodeFlags = ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick; if (!selected) nodeFlags |= ImGuiTreeNodeFlags_Selected; if (ImGui::TreeNodeEx("Scene", nodeFlags)) { ImGui::PushStyleVar(ImGuiStyleVar_IndentSpacing, ImGui::GetFontSize() * 3); // Increase spacing to differentiate leaves from expanded contents. if (ImGui::IsItemClicked()) app->goManager->Select(nullptr); if (root) { for (uint i = 0; i < root->childs.size(); ++i) HierarchyRecursive(root->childs[i], selected); } ImGui::PopStyleVar(); ImGui::TreePop(); } ImGui::End(); } } void UI_Hierarchy::HierarchyRecursive(GameObject* node, GameObject* selected) { ImGuiTreeNodeFlags nodeFlags = 0; if (node == selected) nodeFlags |= ImGuiTreeNodeFlags_Selected; if (node->childs.size() > 0) { nodeFlags |= ImGuiTreeNodeFlags_OpenOnArrow; nodeFlags |= ImGuiTreeNodeFlags_OpenOnDoubleClick; } else nodeFlags |= ImGuiTreeNodeFlags_Leaf; if (ImGui::TreeNodeEx(node->GetName(), nodeFlags)) { if (ImGui::IsItemClicked()) app->goManager->Select(node); for (uint i = 0; i < node->childs.size(); ++i) { HierarchyRecursive(node->childs[i], selected); } ImGui::TreePop(); } }
23.430233
146
0.701241
9ea93736a1011d8434627a70580108e9b05f012d
270
hpp
C++
include/RED4ext/Scripting/Natives/Generated/quest/QuickItemsSet.hpp
jackhumbert/RED4ext.SDK
2c55eccb83beabbbe02abae7945af8efce638fca
[ "MIT" ]
42
2020-12-25T08:33:00.000Z
2022-03-22T14:47:07.000Z
include/RED4ext/Scripting/Natives/Generated/quest/QuickItemsSet.hpp
jackhumbert/RED4ext.SDK
2c55eccb83beabbbe02abae7945af8efce638fca
[ "MIT" ]
38
2020-12-28T22:36:06.000Z
2022-02-16T11:25:47.000Z
include/RED4ext/Scripting/Natives/Generated/quest/QuickItemsSet.hpp
jackhumbert/RED4ext.SDK
2c55eccb83beabbbe02abae7945af8efce638fca
[ "MIT" ]
20
2020-12-28T22:17:38.000Z
2022-03-22T17:19:01.000Z
#pragma once // This file is generated from the Game's Reflection data #include <cstdint> namespace RED4ext { namespace quest { enum class QuickItemsSet : uint32_t { Q001_Kereznikov_Heal_Phone = 0, Q003_All = 1, }; } // namespace quest } // namespace RED4ext
16.875
57
0.722222
9eab0549271f5337d77b1c6db8edfc6e879c9a72
1,184
cpp
C++
workbench/src/audiostream.cpp
MasterQ32/cg-workbench
3d6229b961192689e6dbd0a09ec4b61041ecb155
[ "MIT" ]
5
2017-12-27T12:57:36.000Z
2021-10-02T03:21:40.000Z
workbench/src/audiostream.cpp
MasterQ32/cg-workbench
3d6229b961192689e6dbd0a09ec4b61041ecb155
[ "MIT" ]
9
2020-09-29T22:40:49.000Z
2020-10-17T20:05:05.000Z
workbench/src/audiostream.cpp
MasterQ32/cg-workbench
3d6229b961192689e6dbd0a09ec4b61041ecb155
[ "MIT" ]
null
null
null
#include "audiostream.hpp" #include <cstring> #include <cassert> // Implement stb_vorbis here! #undef STB_VORBIS_HEADER_ONLY #include <stb_vorbis.h> uint32_t audio_samplerate; uint32_t audio_buffersize; uint32_t audio_channels; AudioStream::AudioStream(int channels) : samples(audio_buffersize * channels), channels(channels) { this->Clear(); } AudioStream::AudioStream(AudioStream const &other) : samples(other.samples), channels(other.channels) { } AudioStream::AudioStream(AudioStream && other) : samples(std::move(other.samples)), channels(other.channels) { } AudioStream::~AudioStream() { } void AudioStream::Clear() { memset(this->samples.data(), 0, sizeof(sample_t) * this->samples.size()); } void AudioStream::SetFormatForStream(AudioStream const & other) { this->SetChannels(other.GetChannels()); } void AudioStream::SetChannels(uint32_t chans) { assert(chans >= 1); if(this->channels == chans) return; this->channels = chans; this->samples.resize(audio_buffersize * this->channels); this->Clear(); } void AudioStream::CopyTo(AudioStream & target) const { target.channels = this->channels; target.samples = this->samples; }
17.939394
74
0.728041
9eacbcac940dcbd9bdf58f9fe934da294c7b8e8b
499
cpp
C++
test/src/bextr_test.cpp
MatsuTaku/libbo
e139e1bd81898f22a903a7d43018c93ae2722601
[ "Unlicense" ]
null
null
null
test/src/bextr_test.cpp
MatsuTaku/libbo
e139e1bd81898f22a903a7d43018c93ae2722601
[ "Unlicense" ]
null
null
null
test/src/bextr_test.cpp
MatsuTaku/libbo
e139e1bd81898f22a903a7d43018c93ae2722601
[ "Unlicense" ]
null
null
null
// // Created by 松本拓真 on 2019/11/06. // #include "gtest/gtest.h" #include "bo/bextr.hpp" namespace { constexpr int N = 1<<16; uint64_t rand64() { return uint64_t(random()) | (uint64_t(random()) << 32); } } TEST(Bextr, 64) { for (int i = 0; i < N; i++) { auto val = rand64(); int s = random() % 64; int l = random() % (64 - s) + 1; uint64_t bar = (l < 64) ? (1ull<<l)-1 : -1; uint64_t mask = bar << s; EXPECT_EQ(bo::bextr_u64(val, s, l), (val & mask) >> s); } }
16.633333
59
0.529058
9eb0b41af51f4d54c4f306c07f27818893871ed7
185
hpp
C++
Extensions/Includes.hpp
CodeRedRL/CodeRed-Universal
d6dd12fea9d4a583a99666d7cf75b7e0e3db896a
[ "MIT" ]
6
2021-04-22T01:50:35.000Z
2021-07-16T21:06:46.000Z
Extensions/Includes.hpp
CodeRedRL/CodeRed-Universal
d6dd12fea9d4a583a99666d7cf75b7e0e3db896a
[ "MIT" ]
2
2021-04-24T23:15:32.000Z
2021-05-26T02:22:43.000Z
Extensions/Includes.hpp
CodeRedRL/CodeRed-Universal
d6dd12fea9d4a583a99666d7cf75b7e0e3db896a
[ "MIT" ]
4
2021-04-23T18:26:08.000Z
2021-06-02T09:41:14.000Z
#pragma once #include "Extensions/Colors.hpp" #include "Extensions/Formatting.hpp" #include "Extensions/Math.hpp" #include "Extensions/Memory.hpp" #include "Extensions/UnrealMemory.hpp"
30.833333
38
0.8
9eb8c75d4134e31fb7cd5a15e831fff7c1bc2abb
1,173
cpp
C++
icpc/2019-9-24/I.cpp
Riteme/test
b511d6616a25f4ae8c3861e2029789b8ee4dcb8d
[ "BSD-Source-Code" ]
3
2018-08-30T09:43:20.000Z
2019-12-03T04:53:43.000Z
icpc/2019-9-24/I.cpp
Riteme/test
b511d6616a25f4ae8c3861e2029789b8ee4dcb8d
[ "BSD-Source-Code" ]
null
null
null
icpc/2019-9-24/I.cpp
Riteme/test
b511d6616a25f4ae8c3861e2029789b8ee4dcb8d
[ "BSD-Source-Code" ]
null
null
null
#include <cstdio> #include <algorithm> using namespace std; #define NMAX 50 typedef unsigned char u8; static int n, m, _, cnt; static int u[NMAX], v[NMAX]; static u8 s[NMAX]; void dfs(int i) { if (i == m) cnt++; else if (s[u[i]] < s[v[i]]) { dfs(i + 1); swap(s[u[i]], s[v[i]]); dfs(i + 1); swap(s[u[i]], s[v[i]]); } } inline void reset(int len) { for (int i = 0; i < len; i++) s[i] = i + 1; } int solve() { cnt = 0; reset(n); dfs(0); for (int i = 0; i < n; i++) { reset(n); for (int j = i - 1; j >= 0; j--) { swap(s[j], s[j + 1]); if (j + 1 != i) dfs(0); } reset(n); for (int j = i + 1; j < n; j++) { swap(s[j], s[j - 1]); dfs(0); } } return cnt; } int main() { int T; scanf("%d", &T); while (T--) { scanf("%d%d%d", &n, &m, &_); for (int i = 0; i < m; i++) { scanf("%d%d", u + i, v + i); u[i]--; v[i]--; } reverse(u, u + m); reverse(v, v + m); printf("%d\n", solve()); } return 0; }
17.772727
42
0.369991
9ebdc49e6fbdfe07a2d77199fde267c9bbbadfb1
1,283
cpp
C++
tests/TestTiming/TestStopWatch.cpp
cvilas/grape-old
d8e9b184fff396982be8d230214a1f66a7a8fcc9
[ "BSD-3-Clause" ]
null
null
null
tests/TestTiming/TestStopWatch.cpp
cvilas/grape-old
d8e9b184fff396982be8d230214a1f66a7a8fcc9
[ "BSD-3-Clause" ]
4
2018-06-04T08:18:21.000Z
2018-07-13T14:36:03.000Z
tests/TestTiming/TestStopWatch.cpp
cvilas/grape-old
d8e9b184fff396982be8d230214a1f66a7a8fcc9
[ "BSD-3-Clause" ]
null
null
null
#include "TestStopWatch.h" //============================================================================= TestStopWatch::TestStopWatch() //============================================================================= { } //----------------------------------------------------------------------------- void TestStopWatch::resolution() //----------------------------------------------------------------------------- { grape::StopWatch watch; long long int resolution = watch.getResolutionNanoseconds(); qDebug() << " Watch resolution is " << resolution << "nanoseconds"; QVERIFY(resolution > 0); } //----------------------------------------------------------------------------- void TestStopWatch::period() //----------------------------------------------------------------------------- { grape::StopWatch watch; unsigned long long sleepNs = 1234567890ULL; unsigned long long errNsLimit = 1000000; // 1 millisecond watch.start(); grape::StopWatch::nanoSleep(sleepNs); watch.stop(); unsigned long long ns = watch.getAccumulatedNanoseconds(); unsigned long long errNs = ((ns > sleepNs)?(ns - sleepNs):(sleepNs - ns)); qDebug() << "Elapsed Time: " << ns << " ns. (error: " << errNs << " ns)"; QVERIFY(errNs < errNsLimit); }
33.763158
79
0.411535
9ebf9a324cc53593fa7691c79e70243ea47b5141
835
cpp
C++
EB_GUIDE_GTF/concepts/TraceOutputExample/src/CustomTraceOutputExport.cpp
pethipet/eb-guide-examples
1c14fdb6eebdd8b164d99b519161160ecc5a29cf
[ "MIT" ]
11
2020-02-12T16:35:59.000Z
2022-03-26T14:36:28.000Z
EB_GUIDE_GTF/concepts/TraceOutputExample/src/CustomTraceOutputExport.cpp
pethipet/eb-guide-examples
1c14fdb6eebdd8b164d99b519161160ecc5a29cf
[ "MIT" ]
1
2020-02-12T16:49:56.000Z
2020-03-20T15:22:58.000Z
EB_GUIDE_GTF/concepts/TraceOutputExample/src/CustomTraceOutputExport.cpp
pethipet/eb-guide-examples
1c14fdb6eebdd8b164d99b519161160ecc5a29cf
[ "MIT" ]
4
2020-02-12T16:36:07.000Z
2022-03-26T14:36:22.000Z
//////////////////////////////////////////////////////////////////////////////// // Copyright (c) Elektrobit Automotive GmbH // Alle Rechte vorbehalten. All Rights Reserved. // // Information contained herein is subject to change without notice. // Elektrobit retains ownership and all other rights in the software and each // component thereof. // Any reproduction of the software or components thereof without the prior // written permission of Elektrobit is prohibited. //////////////////////////////////////////////////////////////////////////////// #include "CustomTraceOutput.h" #include <gtf/pluginloader/PluginSymbols.h> using namespace gtf::tracing; extern "C" GTF_PLUGIN_SO_SYMBOL TraceOutput* TRACE_OUTPUT_FACTORY_FUNCTION_CALL(void) { static traceoutputexample::CustomTraceOutput s_fileOut; return &s_fileOut; }
37.954545
85
0.641916
9ec11020b2fdba5457ef32048e476e371db4e26d
1,411
cpp
C++
Gear/Math/Matrix.cpp
Alpha255/Rockcat
f04124b17911fb6148512dd8fb260bd84702ffc1
[ "MIT" ]
null
null
null
Gear/Math/Matrix.cpp
Alpha255/Rockcat
f04124b17911fb6148512dd8fb260bd84702ffc1
[ "MIT" ]
null
null
null
Gear/Math/Matrix.cpp
Alpha255/Rockcat
f04124b17911fb6148512dd8fb260bd84702ffc1
[ "MIT" ]
null
null
null
#include "Gear/Math/Matrix.h" NAMESPACE_START(Gear) NAMESPACE_START(Math) #if !defined(USE_SSE) void Matrix::gaussJordanInverse() { /// Gauss-Jordan method Matrix copy(*this); int32_t i, j, k; /// Forward elimination for (i = 0; i < 3; ++i) { int32_t pivot = i; float32_t pivotSize = copy.m[i][i]; pivotSize = pivotSize < 0.0f ? -pivotSize : pivotSize; for (j = i + 1; j < 4; ++j) { float32_t temp = copy.m[j][i]; temp = temp < 0.0f ? -temp : temp; if (temp > pivotSize) { pivot = j; pivotSize = temp; } } /// singular Matrix assert(pivotSize != 0.0f); if (pivot != i) { for (j = 0; j < 4; ++j) { std::swap(copy.m[i][j], copy.m[pivot][j]); std::swap(m[i][j], m[pivot][j]); } } for (j = i + 1; j < 4; ++j) { float32_t factor = copy.m[j][i] / copy.m[i][i]; for (k = 0; k < 4; ++k) { copy.m[j][k] -= factor * copy.m[i][k]; m[j][k] -= factor * m[i][k]; } } } /// Backward substitution for (i = 3; i >= 0; --i) { float32_t factor = copy.m[i][i]; /// singular Matrix assert(factor != 0.0f); for (j = 0; j < 4; ++j) { copy.m[i][j] /= factor; m[i][j] /= factor; } for (j = 0; j < i; ++j) { factor = copy.m[j][i]; for (k = 0; k < 4; ++k) { copy.m[j][k] -= factor * copy.m[i][k]; m[j][k] -= factor * m[i][k]; } } } } #endif NAMESPACE_END(Math) NAMESPACE_END(Gear)
16.6
56
0.501063
9ec490b05858d9d942213feb29bce4d98c8adbf7
379
cpp
C++
0027. Remove Element/Solution.cpp
Solitudez/leetcode
a47bad8f0796d08e5996e55d38735295f8135703
[ "MIT" ]
1
2022-03-04T16:25:57.000Z
2022-03-04T16:25:57.000Z
0027. Remove Element/Solution.cpp
Solitudez/leetcode
a47bad8f0796d08e5996e55d38735295f8135703
[ "MIT" ]
null
null
null
0027. Remove Element/Solution.cpp
Solitudez/leetcode
a47bad8f0796d08e5996e55d38735295f8135703
[ "MIT" ]
null
null
null
#include <vector> using std::vector; class Solution { public: int removeElement_1(vector<int>& nums, int val) { int l = 0, r = nums.size(); while(l < r) { if (nums[l] == val) { nums[l] = nums[r - 1]; r--; } else l++; } return r; } };
18.047619
53
0.364116
9eca7a702c29987590b725fd14f12a0f7580d2bf
1,166
hpp
C++
include/timer/timer.hpp
lkskstlr/mc-mpi
fc197f4bdf8f3dc3692fc24019bfd7f3c12d6442
[ "MIT" ]
null
null
null
include/timer/timer.hpp
lkskstlr/mc-mpi
fc197f4bdf8f3dc3692fc24019bfd7f3c12d6442
[ "MIT" ]
1
2019-03-05T09:05:10.000Z
2019-03-05T09:05:10.000Z
include/timer/timer.hpp
lkskstlr/mc-mpi
fc197f4bdf8f3dc3692fc24019bfd7f3c12d6442
[ "MIT" ]
null
null
null
#ifndef TIMER_HPP #define TIMER_HPP // I use the fact that structs with methods are still POD in memory which is // guranteed by the standard. See: // https://stackoverflow.com/questions/422830/structure-of-a-c-object-in-memory-vs-a-struct #include <iostream> #include <mpi.h> #include <stdio.h> class Timer { public: typedef int id_t; enum Tag : id_t { Computation = 0, Send, Recv, Idle, STATE_COUNT }; typedef struct timestamp_tag { Tag tag; double time; } Timestamp; typedef struct state_tag { double cumm_times[Tag::STATE_COUNT] = {0.0}; double starttime = 0.0; double endtime = 0.0; int sprintf(char *str); static int sprintf_header(char *str); static int sprintf_max_len(); static MPI_Datatype mpi_t(); } State; Timer(); Timestamp start(Tag tag); State restart(Timestamp &timestamp, Tag tag); void change(Timestamp &timestamp, Tag tag); State stop(Timestamp timestamp); void reset(); double tick() const; double time() const; double starttime() const; friend std::ostream &operator<<(std::ostream &stream, const Timer &timer); private: State state; const double offset; }; #endif
23.795918
91
0.696398
19b02a9ffe3cd60793242ec6536fb3844d69c274
3,993
cpp
C++
IfcPlusPlus/src/ifcpp/IFC4/IfcConnectionVolumeGeometry.cpp
linsipese/ifcppstudy
e09f05d276b5e129fcb6be65800472979cd4c800
[ "MIT" ]
1
2018-10-23T09:43:07.000Z
2018-10-23T09:43:07.000Z
IfcPlusPlus/src/ifcpp/IFC4/IfcConnectionVolumeGeometry.cpp
linsipese/ifcppstudy
e09f05d276b5e129fcb6be65800472979cd4c800
[ "MIT" ]
null
null
null
IfcPlusPlus/src/ifcpp/IFC4/IfcConnectionVolumeGeometry.cpp
linsipese/ifcppstudy
e09f05d276b5e129fcb6be65800472979cd4c800
[ "MIT" ]
null
null
null
/* -*-c++-*- IfcPlusPlus - www.ifcplusplus.com - Copyright (C) 2011 Fabian Gerold * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * 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 * OpenSceneGraph Public License for more details. */ #include <sstream> #include <limits> #include "ifcpp/model/IfcPPException.h" #include "ifcpp/model/IfcPPAttributeObject.h" #include "ifcpp/model/IfcPPGuid.h" #include "ifcpp/reader/ReaderUtil.h" #include "ifcpp/writer/WriterUtil.h" #include "ifcpp/IfcPPEntityEnums.h" #include "include/IfcConnectionVolumeGeometry.h" #include "include/IfcSolidOrShell.h" // ENTITY IfcConnectionVolumeGeometry IfcConnectionVolumeGeometry::IfcConnectionVolumeGeometry() { m_entity_enum = IFCCONNECTIONVOLUMEGEOMETRY; } IfcConnectionVolumeGeometry::IfcConnectionVolumeGeometry( int id ) { m_id = id; m_entity_enum = IFCCONNECTIONVOLUMEGEOMETRY; } IfcConnectionVolumeGeometry::~IfcConnectionVolumeGeometry() {} shared_ptr<IfcPPObject> IfcConnectionVolumeGeometry::getDeepCopy( IfcPPCopyOptions& options ) { shared_ptr<IfcConnectionVolumeGeometry> copy_self( new IfcConnectionVolumeGeometry() ); if( m_VolumeOnRelatingElement ) { copy_self->m_VolumeOnRelatingElement = dynamic_pointer_cast<IfcSolidOrShell>( m_VolumeOnRelatingElement->getDeepCopy(options) ); } if( m_VolumeOnRelatedElement ) { copy_self->m_VolumeOnRelatedElement = dynamic_pointer_cast<IfcSolidOrShell>( m_VolumeOnRelatedElement->getDeepCopy(options) ); } return copy_self; } void IfcConnectionVolumeGeometry::getStepLine( std::stringstream& stream ) const { stream << "#" << m_id << "= IFCCONNECTIONVOLUMEGEOMETRY" << "("; if( m_VolumeOnRelatingElement ) { m_VolumeOnRelatingElement->getStepParameter( stream, true ); } else { stream << "$" ; } stream << ","; if( m_VolumeOnRelatedElement ) { m_VolumeOnRelatedElement->getStepParameter( stream, true ); } else { stream << "$" ; } stream << ");"; } void IfcConnectionVolumeGeometry::getStepParameter( std::stringstream& stream, bool ) const { stream << "#" << m_id; } void IfcConnectionVolumeGeometry::readStepArguments( const std::vector<std::wstring>& args, const boost::unordered_map<int,shared_ptr<IfcPPEntity> >& map ) { const int num_args = (int)args.size(); if( num_args != 2 ){ std::stringstream err; err << "Wrong parameter count for entity IfcConnectionVolumeGeometry, expecting 2, having " << num_args << ". Entity ID: " << m_id << std::endl; throw IfcPPException( err.str().c_str() ); } m_VolumeOnRelatingElement = IfcSolidOrShell::createObjectFromSTEP( args[0], map ); m_VolumeOnRelatedElement = IfcSolidOrShell::createObjectFromSTEP( args[1], map ); } void IfcConnectionVolumeGeometry::getAttributes( std::vector<std::pair<std::string, shared_ptr<IfcPPObject> > >& vec_attributes ) { IfcConnectionGeometry::getAttributes( vec_attributes ); vec_attributes.push_back( std::make_pair( "VolumeOnRelatingElement", m_VolumeOnRelatingElement ) ); vec_attributes.push_back( std::make_pair( "VolumeOnRelatedElement", m_VolumeOnRelatedElement ) ); } void IfcConnectionVolumeGeometry::getAttributesInverse( std::vector<std::pair<std::string, shared_ptr<IfcPPObject> > >& vec_attributes_inverse ) { IfcConnectionGeometry::getAttributesInverse( vec_attributes_inverse ); } void IfcConnectionVolumeGeometry::setInverseCounterparts( shared_ptr<IfcPPEntity> ptr_self_entity ) { IfcConnectionGeometry::setInverseCounterparts( ptr_self_entity ); } void IfcConnectionVolumeGeometry::unlinkFromInverseCounterparts() { IfcConnectionGeometry::unlinkFromInverseCounterparts(); }
57.042857
235
0.771851
19b36115b0c392143e7461c8ca9b6eb61a4b9f70
338
hpp
C++
src/core/menu.hpp
dynilath/cqcppsdk
8f14c2ed85b6d2917ad7aef149acdfb89512937f
[ "MIT" ]
154
2020-01-03T02:51:51.000Z
2020-08-03T19:44:53.000Z
src/core/menu.hpp
dynilath/cqcppsdk
8f14c2ed85b6d2917ad7aef149acdfb89512937f
[ "MIT" ]
22
2020-01-26T04:18:28.000Z
2020-07-04T06:38:28.000Z
src/core/menu.hpp
dynilath/cqcppsdk
8f14c2ed85b6d2917ad7aef149acdfb89512937f
[ "MIT" ]
40
2020-01-06T11:17:25.000Z
2020-08-07T08:26:32.000Z
#pragma once #include "event_export_def.hpp" #define CQ_MENU(FuncName) \ static void __cq_menu_##FuncName(); \ _CQ_EVENT(int32_t, FuncName, 0)() { \ __cq_menu_##FuncName(); \ return 0; \ } \ static void __cq_menu_##FuncName()
28.166667
41
0.482249
19b471af1eb0ed5c4eeb8ad92b4e5bd7b27dd3ac
10,075
inl
C++
src/bad/math/f32x4_calc/f32x4_calc_no_simd.inl
Bad-Sam/bad
a16717bd39c1607a042c673494e9c4a695905868
[ "MIT" ]
null
null
null
src/bad/math/f32x4_calc/f32x4_calc_no_simd.inl
Bad-Sam/bad
a16717bd39c1607a042c673494e9c4a695905868
[ "MIT" ]
null
null
null
src/bad/math/f32x4_calc/f32x4_calc_no_simd.inl
Bad-Sam/bad
a16717bd39c1607a042c673494e9c4a695905868
[ "MIT" ]
null
null
null
// ==== Arithmetic & math functions === static bad_forceinline f32x4 f32x4_add(f32x4 a, f32x4 b) { f32x4 res; res.x = a.x + b.x; res.y = a.y + b.y; res.z = a.z + b.z; res.w = a.w + b.w; return res; } static bad_forceinline f32x4 f32x4_sub(f32x4 a, f32x4 b) { f32x4 res; res.x = a.x - b.x; res.y = a.y - b.y; res.z = a.z - b.z; res.w = a.w - b.w; return res; } static bad_forceinline f32x4 f32x4_mul(f32x4 a, f32x4 b) { f32x4 res; res.x = a.x * b.x; res.y = a.y * b.y; res.z = a.z * b.z; res.w = a.w * b.w; return res; } static bad_forceinline f32x4 f32x4_div(f32x4 a, f32x4 b) { f32x4 res; res.x = a.x / b.x; res.y = a.y / b.y; res.z = a.z / b.z; res.w = a.w / b.w; return res; } static bad_forceinline f32x4 f32x4_hadd3(f32x4 a) { return (f32x4) { f32x4_sum3(a), a.y, a.z, a.w }; } static bad_forceinline f32x4 f32x4_hadd4(f32x4 a) { return (f32x4) { f32x4_sum4(a), a.y, a.z, a.w }; } static bad_forceinline f32 f32x4_sum3(f32x4 a) { return a.x + a.y + a.z; } static bad_forceinline f32 f32x4_sum4(f32x4 a) { return a.x + a.y + a.z + a.w; } static bad_forceinline f32x4 f32x4_rcp(f32x4 a) { f32x4 res; res.x = 1.f / a.x; res.y = 1.f / a.y; res.z = 1.f / a.z; res.w = 1.f / a.w; return res; } static bad_forceinline f32x4 f32x4_sqrt(f32x4 a) { return f32x4_sqrt(a); } static bad_forceinline f32x4 f32x4_rsqrt(f32x4 a) { return f32_rcp(f32x4_sqrt(a)); } static bad_forceinline f32x4 f32x4_min(f32x4 a, f32x4 b) { f32x4 res; res.x = f32x_min(a, b); res.y = f32x_min(a, b); res.z = f32x_min(a, b); res.w = f32x_min(a, b); return res; } static bad_forceinline f32x4 f32x4_max(f32x4 a, f32x4 b) { f32x4 res; res.x = f32x_max(a, b); res.y = f32x_max(a, b); res.z = f32x_max(a, b); res.w = f32x_max(a, b); return res; } static bad_forceinline f32x4 f32x4_abs(f32x4 a) { const u32 value_mask = 0x7FFFFFFF; mask128 a_mask = f32x4_as_mask128(a); a_mask.x &= value_mask; a_mask.y &= value_mask; a_mask.z &= value_mask; a_mask.w &= value_mask; return mask128_as_f32x4(a_mask); } static bad_forceinline f32x4 f32x4_sign(f32x4 a) { const u32 sign_mask = 0x80000000; const u32 one_mask = 0x3F800000; mask128 a_mask = f32x4_as_mask128(a); a_mask.x = (a_mask.x & sign_mask) | one_mask; a_mask.y = (a_mask.y & sign_mask) | one_mask; a_mask.z = (a_mask.z & sign_mask) | one_mask; a_mask.w = (a_mask.w & sign_mask) | one_mask; return mask128_as_f32x4(a_mask); } static bad_forceinline f32x4 f32x4_neg(f32x4 a) { const u32 sign_mask = 0x80000000; mask128 a_mask = f32x4_as_mask128(a); a_mask.x ^= sign_mask; a_mask.y ^= sign_mask; a_mask.z ^= sign_mask; a_mask.w ^= sign_mask; return mask128_as_f32x4(a_mask); } static bad_forceinline f32x4 bad_veccall f32x4_frac(f32x4 a) { return f32x4_sub(a, f32x4_trunc(a)); } static bad_forceinline f32x4 f32x4_mod(f32x4 a, f32x4 b) { a.x = f32_mod(a.x, b.x); a.y = f32_mod(a.y, b.y); a.z = f32_mod(a.z, b.z); a.w = f32_mod(a.w, b.w); return a; } static bad_forceinline f32x4 f32x4_trunc(f32x4 a) { f32x4 res; res.x = f32_trunc(a.x); res.y = f32_trunc(a.y); res.z = f32_trunc(a.z); res.w = f32_trunc(a.w); return res; } static bad_forceinline f32x4 f32x4_round(f32x4 a) { f32x4 sign_a = f32x4_sign(a); f32x4 trunc_a = f32x4_trunc(a); f32x4 offset = f32x4_mul(sign_a, f32x4_sub(a, trunc_a)); offset.x = (offset.x > .5f) ? 1.f : .0f; offset.y = (offset.y > .5f) ? 1.f : .0f; offset.z = (offset.z > .5f) ? 1.f : .0f; offset.w = (offset.w > .5f) ? 1.f : .0f; return f32x4_mul_add(sign_a, offset, trunc_a); } static bad_forceinline f32x4 f32x4_floor(f32x4 a) { a.x = f32_floor(a.x); a.y = f32_floor(a.y); a.z = f32_floor(a.z); a.w = f32_floor(a.w); return a; } static bad_forceinline f32x4 f32x4_ceil(f32x4 a) { a.x = f32_ceil(a.x); a.y = f32_ceil(a.y); a.z = f32_ceil(a.z); a.w = f32_ceil(a.w); return a; } static bad_forceinline f32x4 f32x4_clamp(f32x4 a, f32x4 min, f32x4 max) { return f32x4_min(f32x4_max(a, min), max); } static bad_forceinline f32x4 f32x4_lerp(f32x4 a, f32x4 b, f32x4 t) { f32x4 one_min_t = f32x4_sub(f32x4_one(), t); return f32x4_mul_add(a, one_min_t, f32x4_mul(b, t)); } static bad_forceinline f32x4 bad_veccall f32x4_copysign(f32x4 a, f32x4 reference_sign) { mask128 res; mask128 a_mask = f32x4_as_mask128(a); mask128 sign_mask = f32x4_as_mask128(reference_sign); res.x = (a_mask.x & 0x7FFFFFFF) | (sign_mask.x & 0x80000000); res.y = (a_mask.y & 0x7FFFFFFF) | (sign_mask.y & 0x80000000); res.z = (a_mask.z & 0x7FFFFFFF) | (sign_mask.z & 0x80000000); res.w = (a_mask.w & 0x7FFFFFFF) | (sign_mask.w & 0x80000000); return mask128_as_f32x4(res); } static bad_forceinline f32x4 f32x4_mul_by_sign(f32x4 a, f32x4 reference_sign) { mask128 res; mask128 a_bits = f32x4_as_mask128(a); mask128 sign_bits = f32x4_as_mask128(reference_sign); res.x = a_bits.x ^ (sign_bits.x & 0x80000000); res.y = a_bits.y ^ (sign_bits.y & 0x80000000); res.z = a_bits.z ^ (sign_bits.z & 0x80000000); res.w = a_bits.w ^ (sign_bits.w & 0x80000000); return mask128_as_f32x4(res); } // ========== Trigonometry =========== static bad_forceinline f32x4 bad_veccall f32x4_cos(f32x4 a) { return (f32x4) { f32_cos(x.x), f32_cos(x.y), f32_cos(x.z), f32_cos(x.w) }; } static bad_forceinline f32x4 bad_veccall f32x4_sin(f32x4 a) { return (f32x4) { f32_sin(x.x), f32_sin(x.y), f32_sin(x.z), f32_sin(x.w) }; } static bad_forceinline f32x4 bad_veccall f32x4_tan(f32x4 a) { return (f32x4) { f32_tan(x.x), f32_tan(x.y), f32_tan(x.z), f32_tan(x.w) }; } // Expects inputs in [-1; 1] // Max error: ~1.5974045e-5 // Max relative error: ~0.0005% static bad_forceinline f32x4 bad_veccall f32x4_acos(f32x4 x) { return (f32x4) { f32_acos(x.x), f32_acos(x.y), f32_acos(x.z), f32_acos(x.w) }; } // ======== Fused operations ======== static bad_forceinline f32x4 f32x4_mul_add(f32x4 a, f32x4 b, f32x4 c) { return f32x4_add(f32x4_mul(a, b), c); } static bad_forceinline f32x4 f32x4_mul_sub(f32x4 a, f32x4 b, f32x4 c) { return f32x4_sub(f32x4_mul(a, b), c); } static bad_forceinline f32x4 f32x4_nmul_add(f32x4 a, f32x4 b, f32x4 c) { return f32x4_neg(f32x4_mul_sub(a, b, c)); } static bad_forceinline f32x4 f32x4_nmul_sub(f32x4 a, f32x4 b, f32x4 c) { return f32x4_neg(f32x4_mul_add(a, b, c)); } // ============ Comparison ============ static bad_forceinline mask128 f32x4_neq(f32x4 a, f32x4 b) { mask128 res; res.x = (a.x != b.x) * 0xFFFFFFFF; res.y = (a.y != b.y) * 0xFFFFFFFF; res.z = (a.z != b.z) * 0xFFFFFFFF; res.w = (a.w != b.w) * 0xFFFFFFFF; return res; } static bad_forceinline mask128 f32x4_eq(f32x4 a, f32x4 b) { mask128 res; res.x = (a.x == b.x) * 0xFFFFFFFF; res.y = (a.y == b.y) * 0xFFFFFFFF; res.z = (a.z == b.z) * 0xFFFFFFFF; res.w = (a.w == b.w) * 0xFFFFFFFF; return res; } static bad_forceinline mask128 f32x4_ge(f32x4 a, f32x4 b) { mask128 res; res.x = (a.x >= b.x) * 0xFFFFFFFF; res.y = (a.y >= b.y) * 0xFFFFFFFF; res.z = (a.z >= b.z) * 0xFFFFFFFF; res.w = (a.w >= b.w) * 0xFFFFFFFF; return res; } static bad_forceinline mask128 f32x4_gt(f32x4 a, f32x4 b) { mask128 res; res.x = (a.x > b.x) * 0xFFFFFFFF; res.y = (a.y > b.y) * 0xFFFFFFFF; res.z = (a.z > b.z) * 0xFFFFFFFF; res.w = (a.w > b.w) * 0xFFFFFFFF; return res; } static bad_forceinline mask128 f32x4_le(f32x4 a, f32x4 b) { mask128 res; res.x = (a.x <= b.x) * 0xFFFFFFFF; res.y = (a.y <= b.y) * 0xFFFFFFFF; res.z = (a.z <= b.z) * 0xFFFFFFFF; res.w = (a.w <= b.w) * 0xFFFFFFFF; return res; } static bad_forceinline mask128 f32x4_lt(f32x4 a, f32x4 b) { mask128 res; res.x = (a.x < b.x) * 0xFFFFFFFF; res.y = (a.y < b.y) * 0xFFFFFFFF; res.z = (a.z < b.z) * 0xFFFFFFFF; res.w = (a.w < b.w) * 0xFFFFFFFF; return res; } // ======= Selection & tests ======== static bad_forceinline mask128 f32x4_is_positive(f32x4 a) { mask128 res; res.x = (a.x >= .0f) * 0xFFFFFFFF; res.y = (a.y >= .0f) * 0xFFFFFFFF; res.z = (a.z >= .0f) * 0xFFFFFFFF; res.w = (a.w >= .0f) * 0xFFFFFFFF; return res; } static bad_forceinline mask128 f32x4_is_negative(f32x4 a) { mask128 res; res.x = (a.x < .0f) * 0xFFFFFFFF; res.y = (a.y < .0f) * 0xFFFFFFFF; res.z = (a.z < .0f) * 0xFFFFFFFF; res.w = (a.w < .0f) * 0xFFFFFFFF; return res; } static bad_forceinline mask128 f32x4_is_nan(f32x4 a) { return f32x4_neq(a, a); } static bad_forceinline mask128 f32x4_is_infinite(f32x4 a) { const u32 value_mask = 0x7FFFFFFF; const u32 inf_mask = 0x7F800000; mask128 a_mask = f32x4_as_mask128(a); a_mask.x &= value_mask; a_mask.y &= value_mask; a_mask.z &= value_mask; a_mask.w &= value_mask; a_mask.x = (a_mask.x == inf_mask); a_mask.y = (a_mask.y == inf_mask); a_mask.z = (a_mask.z == inf_mask); a_mask.w = (a_mask.w == inf_mask); return a_mask; } static bad_forceinline mask128 f32x4_is_finite(f32x4 a) { const u32 expo_mask = 0x7F800000; mask128 a_mask = f32x4_as_mask128(a); a_mask.x &= expo_mask; a_mask.y &= expo_mask; a_mask.z &= expo_mask; a_mask.w &= expo_mask; a_mask.x = (a_mask.x != expo_mask); a_mask.y = (a_mask.y != expo_mask); a_mask.z = (a_mask.z != expo_mask); a_mask.w = (a_mask.w != expo_mask); return a_mask; }
19.300766
86
0.596824
19b5803a8cfd16435200eee8f5c0fa004b281350
1,317
hpp
C++
source/AsioExpress/ClientServer/ClientEventHandler.hpp
suhao/asioexpress
2f3453465934afdcdf4a575a2d933d86929b23c7
[ "BSL-1.0" ]
null
null
null
source/AsioExpress/ClientServer/ClientEventHandler.hpp
suhao/asioexpress
2f3453465934afdcdf4a575a2d933d86929b23c7
[ "BSL-1.0" ]
null
null
null
source/AsioExpress/ClientServer/ClientEventHandler.hpp
suhao/asioexpress
2f3453465934afdcdf4a575a2d933d86929b23c7
[ "BSL-1.0" ]
null
null
null
// Copyright Ross MacGregor 2013 // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #pragma once #include "AsioExpress/Error.hpp" #include "AsioExpress/CompletionHandler.hpp" #include "AsioExpress/ClientServer/ClientMessage.hpp" #include "AsioExpress/ClientServer/ClientConnection.hpp" namespace AsioExpress { namespace MessagePort { class ClientEventHandler { public: virtual ~ClientEventHandler() {}; virtual void ClientConnected( AsioExpress::MessagePort::ClientConnection) = 0; virtual void ClientDisconnected( AsioExpress::MessagePort::ClientConnection connection, AsioExpress::Error error) = 0; virtual void AsyncProcessMessage( AsioExpress::MessagePort::ClientMessage message) = 0; virtual AsioExpress::Error ConnectionError( AsioExpress::MessagePort::ClientConnection connection, AsioExpress::Error error) = 0; virtual AsioExpress::Error MessageError( AsioExpress::MessagePort::ClientMessage message, AsioExpress::Error error) = 0; }; typedef boost::shared_ptr<ClientEventHandler> ClientEventHandlerPointer; } // namespace MessagePort } // namespace AsioExpress
29.931818
73
0.725892
19b6d2ecf6c5083c17df38b8f6498e6d484e2696
139
cpp
C++
base/win32/fusion/tools/idlxml/cpp.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
base/win32/fusion/tools/idlxml/cpp.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
base/win32/fusion/tools/idlxml/cpp.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
// Copyright (c) Microsoft Corporation #define SORTPP_PASS #define GUID_DEFINED #define IN __in #define OUT __out #include "h.h"
15.444444
39
0.719424
19b81538e09ab959ef0690421b96ee0eb115adc6
1,038
cpp
C++
src/lib/vector3.cpp
abainbridge/trex-warrior
fac95802ce7efd8dc9c50f915ce8d5891f545640
[ "BSD-2-Clause" ]
null
null
null
src/lib/vector3.cpp
abainbridge/trex-warrior
fac95802ce7efd8dc9c50f915ce8d5891f545640
[ "BSD-2-Clause" ]
null
null
null
src/lib/vector3.cpp
abainbridge/trex-warrior
fac95802ce7efd8dc9c50f915ce8d5891f545640
[ "BSD-2-Clause" ]
null
null
null
#include "lib/universal_include.h" #include <math.h> #include <float.h> #include "lib/vector2.h" #include "lib/vector3.h" Vector3 const g_upVector(0.0f, 1.0f, 0.0f); Vector3 const g_zeroVector(0.0f, 0.0f, 0.0f); void Vector3::RotateAroundX(float angle) { FastRotateAround(Vector3(1,0,0), angle); } void Vector3::RotateAroundY(float angle) { FastRotateAround(g_upVector, angle); } void Vector3::RotateAroundZ(float angle) { FastRotateAround(Vector3(0,0,1), angle); } // ASSUMES that _norm is normalized void Vector3::FastRotateAround(Vector3 const &norm, float angle) { float dot = (*this) * norm; Vector3 a = norm * dot; Vector3 n1 = *this - a; Vector3 n2 = norm.CrossProduct(n1); float s = sinf(angle); float c = cosf(angle); *this = a + c*n1 + s*n2; } void Vector3::RotateAround(Vector3 const &axis) { float angle = axis.LenSquared(); if (angle < 1e-8) return; angle = sqrtf(angle); Vector3 norm(axis / angle); FastRotateAround(norm, angle); }
19.222222
65
0.656069
19c14f19b5a65412d1f04fe10f48be8ce004e7e8
669
cpp
C++
SPOJ/MATGAME.cpp
TISparta/competitive-programming-solutions
31987d4e67bb874bf15653565c6418b5605a20a8
[ "MIT" ]
1
2018-01-30T13:21:30.000Z
2018-01-30T13:21:30.000Z
SPOJ/MATGAME.cpp
TISparta/competitive-programming-solutions
31987d4e67bb874bf15653565c6418b5605a20a8
[ "MIT" ]
null
null
null
SPOJ/MATGAME.cpp
TISparta/competitive-programming-solutions
31987d4e67bb874bf15653565c6418b5605a20a8
[ "MIT" ]
1
2018-08-29T13:26:50.000Z
2018-08-29T13:26:50.000Z
/** * > Author : TISparta * > Date : 11-08-18 * > Tags : Game Theory * > Difficulty : 4 / 10 */ #include <bits/stdc++.h> using namespace std; const int MAX_M = 50; int T, N, M, pile[MAX_M + 1], nim_sum, SGV; int main() { scanf("%d", &T); while (T--) { nim_sum = 0; scanf("%d %d", &N, &M); for (int row = 0; row < N; row++) { for (int col = 0; col < M; col++) scanf("%d", &pile[col]); SGV = pile[M - 1]; for (int col = M - 2; col >= 0; col--) SGV = pile[col] - (pile[col] <= SGV); nim_sum ^= SGV; } puts(nim_sum == 0 ? "SECOND" : "FIRST"); } return (0); }
21.580645
88
0.442451
19c4476cfd25ef06185acc5fc28c0a2a364af5a6
13,112
cpp
C++
src/mame/drivers/btoads.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
26
2015-03-31T06:25:51.000Z
2021-12-14T09:29:04.000Z
src/mame/drivers/btoads.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
null
null
null
src/mame/drivers/btoads.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
10
2015-03-27T05:45:51.000Z
2022-02-04T06:57:36.000Z
// license:BSD-3-Clause // copyright-holders:Aaron Giles /************************************************************************* BattleToads driver by Aaron Giles **************************************************************************/ #include "emu.h" #include "includes/btoads.h" #include "speaker.h" #define CPU_CLOCK XTAL(64'000'000) #define VIDEO_CLOCK XTAL(20'000'000) #define SOUND_CLOCK XTAL(24'000'000) /************************************* * * Machine init * *************************************/ void btoads_state::machine_start() { m_nvram_data = std::make_unique<uint8_t[]>(0x2000); subdevice<nvram_device>("nvram")->set_base(m_nvram_data.get(), 0x2000); save_item(NAME(m_main_to_sound_data)); save_item(NAME(m_main_to_sound_ready)); save_item(NAME(m_sound_to_main_data)); save_item(NAME(m_sound_to_main_ready)); save_item(NAME(m_sound_int_state)); save_pointer(NAME(m_nvram_data), 0x2000); } /************************************* * * NVRAM * *************************************/ void btoads_state::nvram_w(offs_t offset, uint8_t data) { m_nvram_data[offset] = data; } uint8_t btoads_state::nvram_r(offs_t offset) { return m_nvram_data[offset]; } /************************************* * * Main -> sound CPU communication * *************************************/ void btoads_state::device_timer(emu_timer &timer, device_timer_id id, int param, void *ptr) { switch (id) { case TIMER_ID_DELAYED_SOUND: m_main_to_sound_data = param; m_main_to_sound_ready = 1; m_audiocpu->signal_interrupt_trigger(); // use a timer to make long transfers faster timer_set(attotime::from_usec(50), TIMER_ID_NOP); break; } } void btoads_state::main_sound_w(offs_t offset, uint16_t data, uint16_t mem_mask) { if (ACCESSING_BITS_0_7) synchronize(TIMER_ID_DELAYED_SOUND, data & 0xff); } uint16_t btoads_state::main_sound_r() { m_sound_to_main_ready = 0; return m_sound_to_main_data; } READ_LINE_MEMBER( btoads_state::main_to_sound_r ) { return m_main_to_sound_ready; } READ_LINE_MEMBER( btoads_state::sound_to_main_r ) { return m_sound_to_main_ready; } /************************************* * * Sound -> main CPU communication * *************************************/ void btoads_state::sound_data_w(uint8_t data) { m_sound_to_main_data = data; m_sound_to_main_ready = 1; } uint8_t btoads_state::sound_data_r() { m_main_to_sound_ready = 0; return m_main_to_sound_data; } uint8_t btoads_state::sound_ready_to_send_r() { return m_sound_to_main_ready ? 0x00 : 0x80; } uint8_t btoads_state::sound_data_ready_r() { if (m_audiocpu->pc() == 0xd50 && !m_main_to_sound_ready) m_audiocpu->spin_until_interrupt(); return m_main_to_sound_ready ? 0x00 : 0x80; } /************************************* * * Sound CPU interrupt generation * *************************************/ void btoads_state::sound_int_state_w(uint8_t data) { /* top bit controls BSMT2000 reset */ if (!(m_sound_int_state & 0x80) && (data & 0x80)) m_bsmt->reset(); /* also clears interrupts */ m_audiocpu->set_input_line(0, CLEAR_LINE); m_sound_int_state = data; } /************************************* * * Sound CPU BSMT2000 communication * *************************************/ uint8_t btoads_state::bsmt_ready_r() { return m_bsmt->read_status() << 7; } void btoads_state::bsmt2000_port_w(offs_t offset, uint8_t data) { m_bsmt->write_reg(offset >> 8); m_bsmt->write_data(((offset & 0xff) << 8) | data); } /************************************* * * Main CPU memory map * *************************************/ void btoads_state::main_map(address_map &map) { map(0x00000000, 0x003fffff).ram(); map(0x20000000, 0x2000007f).portr("P1"); map(0x20000080, 0x200000ff).portr("P2"); map(0x20000100, 0x2000017f).portr("P3"); map(0x20000180, 0x200001ff).portr("UNK"); map(0x20000200, 0x2000027f).portr("SPECIAL"); map(0x20000280, 0x200002ff).portr("SW1"); map(0x20000000, 0x200000ff).writeonly().share("sprite_scale"); map(0x20000100, 0x2000017f).writeonly().share("sprite_control"); map(0x20000180, 0x200001ff).w(FUNC(btoads_state::display_control_w)); map(0x20000200, 0x2000027f).w(FUNC(btoads_state::scroll0_w)); map(0x20000280, 0x200002ff).w(FUNC(btoads_state::scroll1_w)); map(0x20000300, 0x2000037f).rw(m_tlc34076, FUNC(tlc34076_device::read), FUNC(tlc34076_device::write)).umask32(0x000000ff); map(0x20000380, 0x200003ff).rw(FUNC(btoads_state::main_sound_r), FUNC(btoads_state::main_sound_w)); map(0x20000400, 0x2000047f).w(FUNC(btoads_state::misc_control_w)); map(0x40000000, 0x4000001f).nopw(); /* watchdog? */ map(0x60000000, 0x6003ffff).rw(FUNC(btoads_state::nvram_r), FUNC(btoads_state::nvram_w)).umask32(0x000000ff); map(0xa0000000, 0xa03fffff).rw(FUNC(btoads_state::vram_fg_display_r), FUNC(btoads_state::vram_fg_display_w)); map(0xa4000000, 0xa43fffff).rw(FUNC(btoads_state::vram_fg_draw_r), FUNC(btoads_state::vram_fg_draw_w)); map(0xa8000000, 0xa87fffff).ram().share("vram_fg_data"); map(0xa8800000, 0xa8ffffff).nopw(); map(0xb0000000, 0xb03fffff).rw(FUNC(btoads_state::vram_bg0_r), FUNC(btoads_state::vram_bg0_w)); map(0xb4000000, 0xb43fffff).rw(FUNC(btoads_state::vram_bg1_r), FUNC(btoads_state::vram_bg1_w)); map(0xfc000000, 0xffffffff).rom().region("user1", 0); } /************************************* * * Sound CPU memory map * *************************************/ void btoads_state::sound_map(address_map &map) { map(0x0000, 0x7fff).rom(); map(0x8000, 0xffff).ram(); } void btoads_state::sound_io_map(address_map &map) { map(0x0000, 0x7fff).w(FUNC(btoads_state::bsmt2000_port_w)); map(0x8000, 0x8000).rw(FUNC(btoads_state::sound_data_r), FUNC(btoads_state::sound_data_w)); map(0x8002, 0x8002).w(FUNC(btoads_state::sound_int_state_w)); map(0x8004, 0x8004).r(FUNC(btoads_state::sound_data_ready_r)); map(0x8005, 0x8005).r(FUNC(btoads_state::sound_ready_to_send_r)); map(0x8006, 0x8006).r(FUNC(btoads_state::bsmt_ready_r)); } /************************************* * * Input ports * *************************************/ static INPUT_PORTS_START( btoads ) PORT_START("P1") PORT_BIT( 0x00000001, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_PLAYER(1) PORT_BIT( 0x00000002, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_PLAYER(1) PORT_BIT( 0x00000004, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_PLAYER(1) PORT_BIT( 0x00000008, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_PLAYER(1) PORT_BIT( 0x00000010, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_PLAYER(1) PORT_BIT( 0x00000020, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_PLAYER(1) PORT_BIT( 0x00000040, IP_ACTIVE_LOW, IPT_COIN1 ) PORT_IMPULSE(2) PORT_BIT( 0x00000080, IP_ACTIVE_LOW, IPT_START1 ) PORT_BIT( 0xffffff00, IP_ACTIVE_LOW, IPT_UNUSED ) PORT_START("P2") PORT_BIT( 0x00000001, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_PLAYER(2) PORT_BIT( 0x00000002, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_PLAYER(2) PORT_BIT( 0x00000004, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_PLAYER(2) PORT_BIT( 0x00000008, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_PLAYER(2) PORT_BIT( 0x00000010, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_PLAYER(2) PORT_BIT( 0x00000020, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_PLAYER(2) PORT_BIT( 0x00000040, IP_ACTIVE_LOW, IPT_COIN2 ) PORT_IMPULSE(2) PORT_BIT( 0x00000080, IP_ACTIVE_LOW, IPT_START2 ) PORT_BIT( 0xffffff00, IP_ACTIVE_LOW, IPT_UNUSED ) PORT_START("P3") PORT_BIT( 0x00000001, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_PLAYER(3) PORT_BIT( 0x00000002, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_PLAYER(3) PORT_BIT( 0x00000004, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_PLAYER(3) PORT_BIT( 0x00000008, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_PLAYER(3) PORT_BIT( 0x00000010, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_PLAYER(3) PORT_BIT( 0x00000020, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_PLAYER(3) PORT_BIT( 0x00000040, IP_ACTIVE_LOW, IPT_COIN3 ) PORT_IMPULSE(2) PORT_BIT( 0x00000080, IP_ACTIVE_LOW, IPT_START3 ) PORT_BIT( 0xffffff00, IP_ACTIVE_LOW, IPT_UNUSED ) PORT_START("UNK") PORT_BIT( 0xffffffff, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_START("SPECIAL") PORT_BIT( 0x00000001, IP_ACTIVE_HIGH, IPT_CUSTOM ) PORT_READ_LINE_MEMBER(btoads_state, sound_to_main_r) PORT_SERVICE_NO_TOGGLE( 0x0002, IP_ACTIVE_LOW ) PORT_BIT( 0x00000080, IP_ACTIVE_HIGH, IPT_CUSTOM ) PORT_READ_LINE_MEMBER(btoads_state, main_to_sound_r) PORT_BIT( 0xffffff7c, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_START("SW1") PORT_DIPNAME( 0x0001, 0x0000, DEF_STR( Demo_Sounds )) PORT_DIPLOCATION("SW1:1") PORT_DIPSETTING( 0x0001, DEF_STR( Off )) PORT_DIPSETTING( 0x0000, DEF_STR( On )) PORT_DIPNAME( 0x0002, 0x0000, DEF_STR( Stereo )) PORT_DIPLOCATION("SW1:2") PORT_DIPSETTING( 0x0002, DEF_STR( Off )) PORT_DIPSETTING( 0x0000, DEF_STR( On )) PORT_DIPNAME( 0x0004, 0x0000, "Common Coin Mech") PORT_DIPLOCATION("SW1:3") PORT_DIPSETTING( 0x0004, DEF_STR( Off )) PORT_DIPSETTING( 0x0000, DEF_STR( On )) PORT_DIPNAME( 0x0008, 0x0008, "Three Players") PORT_DIPLOCATION("SW1:4") PORT_DIPSETTING( 0x0008, DEF_STR( Off )) PORT_DIPSETTING( 0x0000, DEF_STR( On )) PORT_DIPNAME( 0x0010, 0x0010, DEF_STR( Free_Play )) PORT_DIPLOCATION("SW1:5") PORT_DIPSETTING( 0x0010, DEF_STR( Off )) PORT_DIPSETTING( 0x0000, DEF_STR( On )) PORT_DIPNAME( 0x0020, 0x0020, "Blood Free Mode") PORT_DIPLOCATION("SW1:6") PORT_DIPSETTING( 0x0020, DEF_STR( Off )) PORT_DIPSETTING( 0x0000, DEF_STR( On )) PORT_DIPNAME( 0x0040, 0x0040, "Credit Retention") PORT_DIPLOCATION("SW1:7") PORT_DIPSETTING( 0x0040, DEF_STR( Off )) PORT_DIPSETTING( 0x0000, DEF_STR( On )) PORT_DIPUNKNOWN_DIPLOC(0x0080, 0x0080, "SW1:8") PORT_BIT( 0xffffff00, IP_ACTIVE_LOW, IPT_UNUSED ) INPUT_PORTS_END /************************************* * * Machine drivers * *************************************/ void btoads_state::btoads(machine_config &config) { TMS34020(config, m_maincpu, CPU_CLOCK/2); m_maincpu->set_addrmap(AS_PROGRAM, &btoads_state::main_map); m_maincpu->set_halt_on_reset(false); m_maincpu->set_pixel_clock(VIDEO_CLOCK/2); m_maincpu->set_pixels_per_clock(1); m_maincpu->set_scanline_rgb32_callback(FUNC(btoads_state::scanline_update)); m_maincpu->set_shiftreg_in_callback(FUNC(btoads_state::to_shiftreg)); m_maincpu->set_shiftreg_out_callback(FUNC(btoads_state::from_shiftreg)); Z80(config, m_audiocpu, SOUND_CLOCK/4); m_audiocpu->set_addrmap(AS_PROGRAM, &btoads_state::sound_map); m_audiocpu->set_addrmap(AS_IO, &btoads_state::sound_io_map); m_audiocpu->set_periodic_int(FUNC(btoads_state::irq0_line_assert), attotime::from_hz(SOUND_CLOCK/4/32768)); NVRAM(config, "nvram", nvram_device::DEFAULT_ALL_1); /* video hardware */ TLC34076(config, m_tlc34076, tlc34076_device::TLC34076_6_BIT); SCREEN(config, m_screen, SCREEN_TYPE_RASTER); m_screen->set_raw(VIDEO_CLOCK/2, 640, 0, 512, 257, 0, 224); m_screen->set_screen_update("maincpu", FUNC(tms34020_device::tms340x0_rgb32)); /* sound hardware */ SPEAKER(config, "lspeaker").front_left(); SPEAKER(config, "rspeaker").front_right(); BSMT2000(config, m_bsmt, SOUND_CLOCK); m_bsmt->add_route(0, "lspeaker", 1.0); m_bsmt->add_route(1, "rspeaker", 1.0); } /************************************* * * ROM definitions * *************************************/ ROM_START( btoads ) ROM_REGION( 0x10000, "audiocpu", 0 ) /* sound program, M27C256B rom */ ROM_LOAD( "bt.u102", 0x0000, 0x8000, CRC(a90b911a) SHA1(6ec25161e68df1c9870d48cc2b1f85cd1a49aba9) ) ROM_REGION32_LE( 0x800000, "user1", 0 ) /* 34020 code, M27C322 roms */ ROM_LOAD32_WORD( "btc0-p0.u120", 0x000000, 0x400000, CRC(0dfd1e35) SHA1(733a0a4235bebd598c600f187ed2628f28cf9bd0) ) ROM_LOAD32_WORD( "btc0-p1.u121", 0x000002, 0x400000, CRC(df7487e1) SHA1(67151b900767bb2653b5261a98c81ff8827222c3) ) ROM_REGION( 0x1000000, "bsmt", 0 ) /* BSMT data, M27C160 rom */ ROM_LOAD( "btc0-s.u109", 0x00000, 0x200000, CRC(d9612ddb) SHA1(f186dfb013e81abf81ba8ac5dc7eb731c1ad82b6) ) ROM_REGION( 0x080a, "plds", 0 ) ROM_LOAD( "u10.bin", 0x0000, 0x0157, CRC(b1144178) SHA1(15fb047adee4125e9fcf04171e0a502655e0a3d8) ) /* GAL20V8A-15LP Located at U10. */ ROM_LOAD( "u11.bin", 0x0000, 0x0157, CRC(7c6beb96) SHA1(2f19d21889dd765b344ad7d257ea7c244baebec2) ) /* GAL20V8A-15LP Located at U11. */ ROM_LOAD( "u57.bin", 0x0000, 0x0157, CRC(be355a56) SHA1(975238bb1ea8fef14458d6f264a82aa77ecf865d) ) /* GAL20V8A-15LP Located at U57. */ ROM_LOAD( "u58.bin", 0x0000, 0x0157, CRC(41ed339c) SHA1(5853c805a902e6d12c979958d878d1cefd6908cc) ) /* GAL20V8A-15LP Located at U58. */ ROM_LOAD( "u90.bin", 0x0000, 0x0157, CRC(a0d0c3f1) SHA1(47464c2ef9fadbba933df27767f377e0c29158aa) ) /* GAL20V8A-15LP Located at U90. */ ROM_LOAD( "u144.bin", 0x0000, 0x0157, CRC(8597017f) SHA1(003d7b5de57e48f831ab211e2783fff338ce2f32) ) /* GAL20V8A-15LP Located at U144. */ ROM_END /************************************* * * Game drivers * *************************************/ GAME( 1994, btoads, 0, btoads, btoads, btoads_state, empty_init, ROT0, "Rare / Electronic Arts", "Battletoads", MACHINE_SUPPORTS_SAVE )
32.862155
138
0.690589
19c621d95652303b64be9e504254602d2c3dc7f6
470
cpp
C++
ZeXo/src/Core/Logger.cpp
Ciridev/ZeXoEngine
1c825e7aab915ea58c14db323123632e71c0a1bd
[ "Apache-2.0" ]
6
2020-12-25T15:35:42.000Z
2021-07-26T21:31:57.000Z
ZeXo/src/Core/Logger.cpp
Ciridev/ZeXoEngine
1c825e7aab915ea58c14db323123632e71c0a1bd
[ "Apache-2.0" ]
null
null
null
ZeXo/src/Core/Logger.cpp
Ciridev/ZeXoEngine
1c825e7aab915ea58c14db323123632e71c0a1bd
[ "Apache-2.0" ]
null
null
null
#include "zxpch.h" #include "Logger.h" namespace ZeXo { Shared<spdlog::logger> Logger::s_CoreLogger; Shared<spdlog::logger> Logger::s_ClientLogger; void Logger::Init() { spdlog::set_pattern("%^[%T] { %n } %v%$"); s_CoreLogger = spdlog::stdout_color_mt("ZeXo Engine"); s_ClientLogger = spdlog::stdout_color_mt("ZeXo Client"); s_CoreLogger->set_level(spdlog::level::level_enum::trace); s_ClientLogger->set_level(spdlog::level::level_enum::trace); } }
22.380952
62
0.706383
19c69b52917fbebe98a96eda954ba83ae41f50ef
1,016
cpp
C++
spoj/Diehard/diehard.cpp
Abhinavlamba/competitive-programming
fdf26f55e5559cde32651ef91f1927b1137442f9
[ "MIT" ]
1
2020-05-12T04:28:55.000Z
2020-05-12T04:28:55.000Z
spoj/Diehard/diehard.cpp
devkant/competitive-programming
fdf26f55e5559cde32651ef91f1927b1137442f9
[ "MIT" ]
null
null
null
spoj/Diehard/diehard.cpp
devkant/competitive-programming
fdf26f55e5559cde32651ef91f1927b1137442f9
[ "MIT" ]
5
2017-10-22T06:04:17.000Z
2020-08-04T11:08:47.000Z
#include <bits/stdc++.h> using namespace std; int dp[1007][1007][1]; int diehard(int h,int a,int air){ if(h<=0 || a<=0){ return 0; } if(dp[h][a][air]!=-1){ return dp[h][a][air]; } if(air){ dp[h][a][air]=1+diehard(h+3,a+2,0); return dp[h][a][air]; }else{ int maxi=max(diehard(h-20,a+5,1), diehard(h-5,a-10,1)); if(maxi==0){ dp[h][a][air]=0; return dp[h][a][air]; }else{ dp[h][a][air]=1+maxi; return dp[h][a][air]; } } } int main() { int t; scanf("%d",&t); for(int j=0;j<=1006;j++){ for(int k=0;k<=1006;k++){ if(j==0 || k==0){ dp[j][k][0]=0; dp[j][k][1]=0; }else{ dp[j][k][0]=-1; dp[j][k][1]=-1; } } } while(t--){ int h,a; scanf("%d%d",&h,&a); printf("%d\n",diehard(h,a,1)); } return 0; }
18.142857
63
0.36122
19c88b00bae7f0ed1e3b3f2bcda0667632890368
630
cpp
C++
src/ui/ui_frame_buffers.cpp
astrellon/simple-space
20e98d4f562a78b1efeaedb0a0012f3c9306ac7e
[ "MIT" ]
1
2020-09-23T11:17:35.000Z
2020-09-23T11:17:35.000Z
src/ui/ui_frame_buffers.cpp
astrellon/simple-space
20e98d4f562a78b1efeaedb0a0012f3c9306ac7e
[ "MIT" ]
null
null
null
src/ui/ui_frame_buffers.cpp
astrellon/simple-space
20e98d4f562a78b1efeaedb0a0012f3c9306ac7e
[ "MIT" ]
null
null
null
#include "ui_frame_buffers.hpp" #include <sstream> #include "../imgui/imgui-SFML.h" #include "../engine.hpp" namespace space { UIFrameBuffers::UIFrameBuffers() : UIWindow("FrameBuffers") { } void UIFrameBuffers::doDraw(Engine &engine) { auto &renderCameras = engine.renderCameras(); ImGui::Text("Frame Buffers: %i", (int)renderCameras.objects().size()); for (auto &renderCamera : renderCameras.objects()) { ImGui::Text("- %s", renderCamera->camera().debugName.c_str()); ImGui::Image(renderCamera->texture().getTexture()); } } } // space
24.230769
78
0.612698
19cabdd0e228af0ec12b2a070e143a05b4998947
1,994
cpp
C++
testtool/common.cpp
obono/TinyJoypadWorks
e9f5403fc435b7fece1b6d488dcef3a6699e6194
[ "MIT" ]
3
2020-12-28T20:22:44.000Z
2022-02-22T08:33:14.000Z
testtool/common.cpp
obono/TinyJoypadWorks
e9f5403fc435b7fece1b6d488dcef3a6699e6194
[ "MIT" ]
null
null
null
testtool/common.cpp
obono/TinyJoypadWorks
e9f5403fc435b7fece1b6d488dcef3a6699e6194
[ "MIT" ]
null
null
null
#include "common.h" /* Defines */ #define NUMBER_DIGITS 3 #define DPAD_BUTTONS (LEFT_BUTTON | RIGHT_BUTTON | DOWN_BUTTON | UP_BUTTON) /* Global Variables */ RECORD_T record; char stringBuffer[STRING_BUFFERS][STRING_BUFFER_SIZE]; int8_t dpadX, dpadY; /* Local Variables */ static PROGMEM const uint8_t imgButtons[] = { // 6x6 x5 0x04, 0x04, 0x0E, 0x0E, 0x1F, 0x00, // left 0x1F, 0x0E, 0x0E, 0x04, 0x04, 0x00, // right 0x01, 0x07, 0x1F, 0x07, 0x01, 0x00, // down 0x10, 0x1C, 0x1F, 0x1C, 0x10, 0x00, // up 0x0E, 0x1F, 0x1F, 0x1F, 0x0E, 0x00, // A }; static uint8_t dpadCounter; /*---------------------------------------------------------------------------*/ void setDpadSprite(uint8_t idx, DPAD_SPRITE_T type, int8_t x, int8_t y) { const uint8_t *p = imgButtons; uint8_t w = 12; switch (type) { case DPAD_SPRITE_ALL: w = 30; break; case DPAD_SPRITE_X_AXIS: break; case DPAD_SPRITE_Y_AXIS: p += 12; break; case DPAD_SPRITE_BUTTON: p += 24; w = 6; break; } setSprite(idx, x, y, p, w, 8, WHITE); } char *(setStringBuffer)(uint8_t idx, const __FlashStringHelper *pFlashString) { uint8_t len = strlen_P((const char *)pFlashString); char *p = stringBuffer[idx]; memcpy_P(p, pFlashString, len + 1); return p; } void printNumber(uint8_t idx, uint8_t offset, uint16_t number, uint8_t radix) { char *p = &stringBuffer[idx][offset]; for (int8_t i = 0; i < NUMBER_DIGITS; i++) { uint8_t c = number % radix; *p-- = (number || i == 0) ? c + ((c < 10) ? '0' : 'A' - 10) : ' '; number /= radix; } } void handleDpad(void) { dpadX = isButtonPressed(RIGHT_BUTTON) - isButtonPressed(LEFT_BUTTON); dpadY = isButtonPressed(DOWN_BUTTON) - isButtonPressed(UP_BUTTON); if (isButtonPressed(DPAD_BUTTONS)) { if (dpadCounter < DPAD_REPEAT_DELAY && dpadCounter++ > 0) dpadX = dpadY = 0; } else { dpadCounter = 0; } }
28.898551
84
0.599799
19cb35df39f98f047e984076450eebeaa84167f1
5,535
cpp
C++
test/test_session.cpp
dvetutnev/tomsksoft
39741046e1355ac36775189b4e8970af3a7861cd
[ "MIT" ]
null
null
null
test/test_session.cpp
dvetutnev/tomsksoft
39741046e1355ac36775189b4e8970af3a7861cd
[ "MIT" ]
null
null
null
test/test_session.cpp
dvetutnev/tomsksoft
39741046e1355ac36775189b4e8970af3a7861cd
[ "MIT" ]
null
null
null
#include "session.h" #include "mocks.h" #include "create_packet.h" #include <algorithm> using ::testing::SaveArg; using ::testing::InSequence; using ::testing::StrictMock; using ::testing::NiceMock; using ::testing::AtLeast; TEST(Session, timeout) { MockServer server; StrictMock<MockWriter> writer; auto client = std::make_shared<NiceMock<MockSocket>>(); MockHandle::THandler<uvw::DataEvent> handlerDataEvent; EXPECT_CALL(*client, saveDataHandler).WillOnce(SaveArg<0>(&handlerDataEvent)); { InSequence _; EXPECT_CALL(*client, read).Times(1); EXPECT_CALL(*client, stop).Times(1); EXPECT_CALL(*client, close).Times(1); } auto timer = std::make_shared<StrictMock<MockTimer>>(); MockHandle::THandler<uvw::TimerEvent> handlerTimerEvent; EXPECT_CALL(*timer, saveHandler).WillOnce(SaveArg<0>(&handlerTimerEvent)); { InSequence _; EXPECT_CALL(*timer, start).Times(1); EXPECT_CALL(*timer, stop).Times(1); EXPECT_CALL(*timer, close).Times(1); } Session<MockServer, MockWriter, MockSocket, MockTimer> session{server, writer, client, timer}; EXPECT_CALL(server, remove(&session)).Times(1); uvw::DataEvent dataEvent{std::make_unique<char[]>(3), 3};; handlerDataEvent(dataEvent, *client); handlerTimerEvent(uvw::TimerEvent{}, *timer); } TEST(Session, networkError) { MockServer server; StrictMock<MockWriter> writer; auto client = std::make_shared<NiceMock<MockSocket>>(); MockHandle::THandler<uvw::DataEvent> handlerDataEvent; EXPECT_CALL(*client, saveDataHandler).WillOnce(SaveArg<0>(&handlerDataEvent)); MockHandle::THandler<uvw::ErrorEvent> handlerErrorEvent; EXPECT_CALL(*client, saveErrorHandler).WillOnce(SaveArg<0>(&handlerErrorEvent)); { InSequence _; EXPECT_CALL(*client, read).Times(1); EXPECT_CALL(*client, stop).Times(1); EXPECT_CALL(*client, close).Times(1); } auto timer = std::make_shared<NiceMock<MockTimer>>(); { InSequence _; EXPECT_CALL(*timer, start).Times(1); EXPECT_CALL(*timer, stop).Times(1); EXPECT_CALL(*timer, close).Times(1); } Session<MockServer, MockWriter, MockSocket, MockTimer> session{server, writer, client, timer}; EXPECT_CALL(server, remove(&session)).Times(1); uvw::DataEvent dataEvent{std::make_unique<char[]>(3), 3};; handlerDataEvent(dataEvent, *client); handlerErrorEvent(uvw::ErrorEvent{static_cast<std::underlying_type_t<uv_errno_t>>(UV_EFAULT)}, *client); } TEST(Session, normal) { StrictMock<MockServer> server; MockWriter writer; auto client = std::make_shared<NiceMock<MockSocket>>(); MockHandle::THandler<uvw::DataEvent> handlerDataEvent; EXPECT_CALL(*client, saveDataHandler).WillOnce(SaveArg<0>(&handlerDataEvent)); EXPECT_CALL(*client, read).Times(1); auto timer = std::make_shared<NiceMock<MockTimer>>(); EXPECT_CALL(*timer, start).Times(1); Session<MockServer, MockWriter, MockSocket, MockTimer> session{server, writer, client, timer}; EXPECT_CALL(writer, push("abcdef")).Times(1); auto dataEvent = createPacket("abcdef"); handlerDataEvent(dataEvent, *client); } TEST(Session, repeat) { StrictMock<MockServer> server; MockWriter writer; auto client = std::make_shared<NiceMock<MockSocket>>(); MockHandle::THandler<uvw::DataEvent> handlerDataEvent; EXPECT_CALL(*client, saveDataHandler).WillOnce(SaveArg<0>(&handlerDataEvent)); EXPECT_CALL(*client, read).Times(1); auto timer = std::make_shared<NiceMock<MockTimer>>(); EXPECT_CALL(*timer, start).Times(1); EXPECT_CALL(*timer, again).Times(AtLeast(1)); Session<MockServer, MockWriter, MockSocket, MockTimer> session{server, writer, client, timer}; const std::string data1 = "abcdefqwert"; auto packet1 = createPacket(data1); const std::string data2 = "42abcdefqwert"; auto packet2 = createPacket(data2); { InSequence _; EXPECT_CALL(writer, push(data1)).Times(1); EXPECT_CALL(writer, push(data2)).Times(1); } handlerDataEvent(packet1, *client); handlerDataEvent(packet2, *client); } TEST(Session, disconnect) { StrictMock<MockServer> server; NiceMock<MockWriter> writer; auto client = std::make_shared<NiceMock<MockSocket>>(); MockHandle::THandler<uvw::DataEvent> handlerDataEvent; EXPECT_CALL(*client, saveDataHandler).WillOnce(SaveArg<0>(&handlerDataEvent)); MockHandle::THandler<uvw::EndEvent> handlerEndEvent; EXPECT_CALL(*client, saveEndHandler).WillOnce(SaveArg<0>(&handlerEndEvent)); EXPECT_CALL(*client, read).Times(1); auto timer = std::make_shared<NiceMock<MockTimer>>(); Session<MockServer, MockWriter, MockSocket, MockTimer> session{server, writer, client, timer}; auto createPacket = [](const std::string& data) -> uvw::DataEvent { std::uint32_t header = ::htonl(data.size()); std::size_t packetLength = sizeof(header) + data.size(); uvw::DataEvent packet{std::make_unique<char[]>(packetLength), packetLength};; std::copy_n(reinterpret_cast<const char*>(&header), sizeof(header), packet.data.get()); std::copy_n(data.data(), data.size(), packet.data.get() + sizeof(header)); return packet; }; EXPECT_CALL(server, remove(&session)).Times(1); auto packet = createPacket("abcdefqwert"); handlerDataEvent(packet, *client); handlerEndEvent(uvw::EndEvent{}, *client); }
31.810345
108
0.687263
19ccba639c5c8bf915f7d90b82f0c588b272885b
11,754
cpp
C++
src/linux_parser.cpp
george-DLJ/CppND-System-Monitor
41b33b2937626361ec0fa4bf8d6489f8a2920d83
[ "MIT" ]
null
null
null
src/linux_parser.cpp
george-DLJ/CppND-System-Monitor
41b33b2937626361ec0fa4bf8d6489f8a2920d83
[ "MIT" ]
null
null
null
src/linux_parser.cpp
george-DLJ/CppND-System-Monitor
41b33b2937626361ec0fa4bf8d6489f8a2920d83
[ "MIT" ]
null
null
null
#include <dirent.h> #include <unistd.h> #include <string> #include <vector> #include "linux_parser.h" using std::stof; using std::string; using std::to_string; using std::vector; // An example of how to read data from the filesystem string LinuxParser::OperatingSystem() { string line; string key; string value; std::ifstream filestream(kOSPath); if (filestream.is_open()) { while (std::getline(filestream, line)) { std::replace(line.begin(), line.end(), ' ', '_'); std::replace(line.begin(), line.end(), '=', ' '); std::replace(line.begin(), line.end(), '"', ' '); std::istringstream linestream(line); while (linestream >> key >> value) { if (key == "PRETTY_NAME") { std::replace(value.begin(), value.end(), '_', ' '); return value; } } } } return value; } // An example of how to read data from the filesystem string LinuxParser::Kernel() { string os, version, kernel; string line; std::ifstream stream(kProcDirectory + kVersionFilename); if (stream.is_open()) { std::getline(stream, line); std::istringstream linestream(line); linestream >> os >> version >> kernel; } return kernel; } // BONUS: Update this to use std::filesystem // (!) requires update gcc to c++17 vector<int> LinuxParser::Pids() { vector<int> pids; DIR* directory = opendir(kProcDirectory.c_str()); struct dirent* file; while ((file = readdir(directory)) != nullptr) { if (file->d_type == DT_DIR) { string filename(file->d_name); if (std::all_of(filename.begin(), filename.end(), isdigit)) { int pid = stoi(filename); pids.push_back(pid); } } } closedir(directory); return pids; } /** * Helper function to read the tokens on files. */ inline string readToken(const string tokenName, const string &line ) { string key; string value; std::istringstream linestream(line); linestream >> key >> value; // >> units; (kB) if (key == tokenName) { return value; } return ""; } /** * Retrieves the system memory utilization. * * This function uses /proc/meminfo to calculate the memory utilization. The * calculation is done using just MemTotal and Memfree parameters; * * NOTE: Unused memory fields: memavailable , buffers; */ float LinuxParser::MemoryUtilization() { float memtotal = 0.0, memfree = 0.0 ; string line; string key; string value; std::ifstream stream(kProcDirectory + kMeminfoFilename); if (stream.is_open()) { { // 1st line expected MemTotal value. std::getline(stream, line); std::istringstream linestream(line); linestream >> key >> value; // >> units; (kB) if (key == "MemTotal:") { memtotal = stof(value); } // Alternative: use a helper function. // It works but crashes when token is not found on line (or line is empty). // string tokenValue = readToken("MemTotal:", line ); // memtotal = stof(tokenValue); } { // 2nd line expected MemFree value. std::getline(stream, line); std::istringstream linestream(line); linestream >> key >> value; // >> units; (kB) if (key == "MemFree:") { memfree = stof(value); } } } return (memtotal - memfree) / memtotal; } /** * Read and return the system uptime * * The information is gathered from /proc/uptime file which contains two values: * - the uptime of the system (including time spent in suspend) and * - the amount of time spent in the idle process * This file contains a single line. */ long int LinuxParser::UpTime() { long int uptimeValue = 0; string line; string uptimeStr; std::ifstream stream(kProcDirectory + kUptimeFilename); if (stream.is_open()) { std::getline(stream, line); std::istringstream linestream(line); linestream >> uptimeStr; uptimeValue = stol(uptimeStr); return uptimeValue; } return uptimeValue; } /** * Read and return the number of jiffies for the system * I'm confused because the linux man says there are not * jiffies any more since Kernel 2.6 but clock tics * NOTE: I asume (system cpu) jiffies value is the sum of all values but guest. * jiffies: user + nice + system + idle + io * from cpu line in /proc/stat file. * see: https://man7.org/linux/man-pages/man5/proc.5.html */ long LinuxParser::Jiffies() { return LinuxParser::ActiveJiffies() + LinuxParser::IdleJiffies(); } /** * (?): Read and return the number of active jiffies for a PID * It is not clear if I should use just utime+ stime or als * add the children nodes (cutime + cstime) */ long LinuxParser::ActiveJiffies(int pid) { string line; string key; string token; std::ifstream stream(kProcDirectory + to_string(pid) + kStatFilename); if (stream.is_open()) { long utime{0}; long stime{0}; long cutime{0}; long cstime{0}; std::getline(stream, line); std::istringstream linestream(line); int i = 1; while (linestream >> token){ //return the nth token. switch(i) { case LinuxParser::PidStat::kutime: utime = stol(token); break; case LinuxParser::PidStat::kstime: stime = stol(token); break; case LinuxParser::PidStat::kcutime: cutime = stol(token); break; case LinuxParser::PidStat::kcstime: //this is the token with higher index: add to sum and return; cstime = stol(token); return utime + stime + cutime + cstime; } i++; } } return 0; } /** * Read and return the number of active jiffies for the system * * NOTE: It is not clear on the project description und neither on linux man * but I asume it is the cpu non-idle time from file /proc/stat: * Jiffies = user + nice + system + irq + softirq + steal */ long LinuxParser::ActiveJiffies() { vector<string> cpuUtilization = LinuxParser::CpuUtilization(); if (cpuUtilization.size() > CPUStates::kSteal_){ //NOTE: kSteal_: last used cpu state index. return stol(cpuUtilization[kUser_]) + stol(cpuUtilization[kNice_]) + stol(cpuUtilization[kSystem_]) + stol(cpuUtilization[kIRQ_]) + stol(cpuUtilization[kSoftIRQ_]) + stol(cpuUtilization[kSteal_]); } return 0; } /** * Read and return the number of idle jiffies for the system * * NOTE: It is not clear on the project description und neither on linux man * how is this value calculated. I asume it is the cpu idle time from * file /proc/stat: * IdleJiffies = idle + iowait */ long LinuxParser::IdleJiffies() { vector<string> cpuUtilization = LinuxParser::CpuUtilization(); if (cpuUtilization.size() > CPUStates::kSteal_){ //NOTE: kSteal_: last used cpu state index. return stol(cpuUtilization[kIdle_]) + stol(cpuUtilization[kIOwait_]); } return 0; } /** * Read and return CPU utilization */ vector<string> LinuxParser::CpuUtilization() { string line; string cpuKey; string cpuStat; std::ifstream stream(kProcDirectory + kStatFilename); if (stream.is_open()) { while (std::getline(stream, line)) { std::istringstream linestream(line); linestream >> cpuKey; if (cpuKey == "cpu") { vector<string> cpuUtilization {}; while (linestream >> cpuStat){ cpuUtilization.push_back(cpuStat); } return cpuUtilization; } } } return {}; } /** * Read and return the total number of processes * * This information can be found on /proc/stat file * under the token 'processes' * * This file contains multiple lines of information. */ int LinuxParser::TotalProcesses() { string line; string key; string value; string uptime; std::ifstream stream(kProcDirectory + kStatFilename); if (stream.is_open()) { while (std::getline(stream, line)) { std::istringstream linestream(line); linestream >> key >> value; if (key == "processes") { return stoi(value); } } } return 0; } /** * Read and return the number of running processes. * * This information is stored on /proc/stat * */ int LinuxParser::RunningProcesses() { string line; string key; string value; std::ifstream stream(kProcDirectory + kStatFilename); if (stream.is_open()) { while (std::getline(stream, line)) { std::istringstream linestream(line); linestream >> key >> value; if (key == "procs_running") { return stoi(value); } } } return 0; } /** * Read and return the command associated with a process * * file contains a single line; return all of it. */ string LinuxParser::Command(int pid) { std::ifstream stream(kProcDirectory + to_string(pid) + kCmdlineFilename); string line; if (stream.is_open()) { std::getline(stream, line); return line; } return string(); } /** * Read and return the memory used by a process * * NOTE: this function returns the source Values that are in kB. * * @return memory used by a process in kB. */ string LinuxParser::Ram(int pid) { string line; string key; string value; std::ifstream stream(kProcDirectory + to_string(pid) + kStatusFilename); if (stream.is_open()) { while (std::getline(stream, line)) { std::istringstream linestream(line); linestream >> key >> value; if (key == "VmSize:") { return value; //unit: kB } } } return string(); } /** * Read and return the user ID associated with a process */ string LinuxParser::Uid(int pid) { string line; string key; string value; std::ifstream stream(kProcDirectory + to_string(pid) + kStatusFilename); if (stream.is_open()) { while (std::getline(stream, line)) { std::istringstream linestream(line); linestream >> key >> value; if (key == "Uid:") { return value; } } } return string(); } /** * Read and return the user associated with a process */ string LinuxParser::User(int pid) { return UserName(Uid(pid)); } /** * Read and return the pid 'starttime' of a process in clocktics. * from file /proc/[PID]/stat * * TODO: consider rename the functiontion to starttime * @return [pid] uptime in raw units (e.g. clock_tics) */ long LinuxParser::UpTime(int pid) { string line; string key; string token; std::ifstream stream(kProcDirectory + to_string(pid) + kStatFilename); if (stream.is_open()) { // data is in a single line: std::getline(stream, line); std::istringstream linestream(line); int i = 1; while (linestream >> token){ //return the nth token. if (i == LinuxParser::PidStat::kstartime){ return stol(token); } i++; } } return 0; } /** * Helper Function. Reads the username that belongs to a given Uid * /etc/passwd contains following format (where ':' is separator): * username:pwd:uid:gid:UserIdInfo:home/dir:command/shell * NOTE: some elements may contain spaces. */ string LinuxParser::UserName(std::string userId){ string line; std::ifstream stream(kPasswordPath); if (stream.is_open()) { string username, pwd, uid; while (std::getline(stream, line)) { std::replace(line.begin(), line.end(), ' ', '_'); // Replace empty spaces with underscores std::replace(line.begin(), line.end(), ':', ' '); // (!) separator is ':' replace it with empty space std::istringstream linestream(line); linestream >> username >> pwd >> uid; if (uid == userId){ return username; } } } return userId; }
27.271462
107
0.627786
19cecee5716dda019d8e0e84c8d54cf348fb1878
4,027
cpp
C++
src/macro.cpp
reveluxlabs/Tilton
d8ff1a58366023422e1a83178fd8d7370081477e
[ "MIT" ]
null
null
null
src/macro.cpp
reveluxlabs/Tilton
d8ff1a58366023422e1a83178fd8d7370081477e
[ "MIT" ]
1
2019-10-17T12:58:18.000Z
2019-10-17T12:58:18.000Z
src/macro.cpp
reveluxlabs/Tilton
d8ff1a58366023422e1a83178fd8d7370081477e
[ "MIT" ]
2
2019-10-16T12:45:50.000Z
2019-10-17T12:08:10.000Z
// Copyright (c) 2011 Revelux Labs, LLC. All rights reserved. // Use of this source code is governed by a MIT-style license that can be // found in the LICENSE file. #include "macro.h" #include <string> #include <stdio.h> #include <stdlib.h> #include "tilton.h" Macro::Macro() { InitializeMacro(NULL, 0); } Macro::Macro(int len) { InitializeMacro(NULL, len); } Macro::Macro(const char* s) { InitializeMacro(s, static_cast<int>(strlen(s))); } Macro::Macro(Text* t) { if (t) { InitializeMacro(t->string_, t->length_); } else { InitializeMacro(NULL, 0); } } Macro::~Macro() { delete this->definition_; delete this->name_; } void Macro::AddToString(const char* s, int len) { if (s && len) { CheckLengthAndIncrease(len); memmove(&definition_[length_], s, len); length_ += len; my_hash_ = 0; } } void Macro::AddToString(Text* t) { if (t) { AddToString(t->string_, t->length_); } } void Macro::CheckLengthAndIncrease(int len) { int newMaxLength; int req = length_ + len; if (max_length_ < req) { newMaxLength = max_length_ * 2; if (newMaxLength < req) { newMaxLength = req; } char* newString = new char[newMaxLength]; memmove(newString, definition_, max_length_); delete definition_; definition_ = newString; max_length_ = newMaxLength; } } void Macro::PrintMacroList() { Macro* t = this; while (t) { fwrite(t->name_, sizeof(char), t->name_length_, stderr); if (t->length_) { fputc('~', stderr); fwrite(t->definition_, sizeof(char), t->length_, stderr); } fprintf(stderr, "\n"); t = t->link_; } } int Macro::FindFirstSubstring(Text *t) { int len = t->length_; char* s = t->string_; if (len) { bool b; int d = length_ - len; int i; int r; for (r = 0; r <= d; r += 1) { b = true; for (i = 0; i < len; i += 1) { if (definition_[r + i] != s[i]) { b = false; break; } } if (b) { return r; } }; } return -1; } void Macro::InitializeMacro(const char* s, int len) { name_ = NULL; link_ = NULL; length_ = name_length_ = 0; my_hash_ = 0; max_length_ = len; if (len == 0) { definition_ = NULL; } else { definition_ = new char[len]; if (s) { memmove(definition_, s, len); length_ = len; } } } bool Macro::IsNameEqual(Text* t) { if (name_length_ != t->length_) { return false; } for (int i = 0; i < name_length_; i += 1) { if (name_[i] != t->string_[i]) { return false; } } return true; } int Macro::FindLastSubstring(Text *t) { int len = t->length_; char* s = t->string_; if (len) { bool b; int d = length_ - len; for (int r = d; r >= 0; r -= 1) { b = true; for (int i = 0; i < len; i += 1) { if (definition_[r + i] != s[i]) { b = false; break; } } if (b) { return r; } } } return -1; } void Macro::set_string(Text* t) { my_hash_ = 0; if (t && t->length_) { length_ = t->length_; if (length_ > max_length_) { delete definition_; definition_ = new char[length_]; max_length_ = length_; } memmove(definition_, t->string_, length_); } else { length_ = 0; } } void Macro::set_name(const char* s) { set_name(s, static_cast<int>(strlen(s))); } void Macro::set_name(const char* s, int len) { delete name_; name_length_ = len; name_ = new char[name_length_]; memmove(name_, s, name_length_); } void Macro::set_name(Text* t) { set_name(t->string_, t->length_); } void Macro::ReplaceDefWithSubstring(int start, int len) { memmove(definition_, &definition_[start], len); length_ = len; }
21.08377
73
0.532158
19d1ae34118cdbad622550dcb7b215a3ac151442
395
cpp
C++
C or C++/poinTer.cpp
amitShindeGit/Miscellaneous-Programs
11aa892628f44b51a8723d5f282d64f867b01be2
[ "MIT" ]
3
2020-11-01T05:48:04.000Z
2021-04-25T05:33:47.000Z
C or C++/poinTer.cpp
amitShindeGit/Miscellaneous-Programs
11aa892628f44b51a8723d5f282d64f867b01be2
[ "MIT" ]
null
null
null
C or C++/poinTer.cpp
amitShindeGit/Miscellaneous-Programs
11aa892628f44b51a8723d5f282d64f867b01be2
[ "MIT" ]
3
2020-10-31T05:29:55.000Z
2021-06-19T09:33:53.000Z
#include <iostream> #include <new> #include <cstdlib> #include <map> #include <string> #include <vector> #include <cmath> using namespace std; int main() { int a = 90; int b = 100; cout << "Address = " << (long)&a << " " << (long)&b << endl; int *p = &a; cout << "p = " << *p << " " << endl; p++; cout << "p after increment = " << *p << " " << endl; return 0; }
18.809524
64
0.496203
19d23aa18ab8775f38678c4dc264a93cdadc54c5
6,979
hpp
C++
include/conduit/mixin/promise_parts.hpp
jantonioperez/conduit
1366d710fb3afac5dbc3b71f8285c62c03bdf201
[ "MIT" ]
6
2021-09-18T07:49:46.000Z
2022-02-03T12:21:16.000Z
include/conduit/mixin/promise_parts.hpp
functionalperez/conduit
1366d710fb3afac5dbc3b71f8285c62c03bdf201
[ "MIT" ]
1
2021-08-05T22:48:51.000Z
2021-08-05T23:27:30.000Z
include/conduit/mixin/promise_parts.hpp
codeinred/conduit
1366d710fb3afac5dbc3b71f8285c62c03bdf201
[ "MIT" ]
null
null
null
#pragma once #include <conduit/async/callback.hpp> #include <conduit/async/immediate_value.hpp> #include <conduit/mem/allocator.hpp> #include <conduit/mixin/awaitable_parts.hpp> #include <conduit/util/tag_types.hpp> #include <exception> namespace conduit::mixin { enum suspend : bool { always = true, never = false }; #if CONDUIT_USE_GCC_EXCEPTION_WORKAROUND namespace detail { using remuse_coro_t = void (*)(); using destroy_coro_t = void (*)(); struct frame_header_t { remuse_coro_t resume_coro; destroy_coro_t destroy_coro; }; } // namespace detail template <bool suspend> struct InitialSuspend { // If CONDUIT_USE_GCC_EXCEPTION_WORKAROUND is defined, then we need to keep // track of this value in order to destroy the frame manually. This value is // recorded inside initial_suspend_t detail::destroy_coro_t destroy_coro = nullptr; struct initial_suspend_t { detail::destroy_coro_t& destroy_coro_ref; inline constexpr bool await_ready() { return false; } inline bool await_suspend(std::coroutine_handle<> h) { destroy_coro_ref = ((detail::frame_header_t*)h.address()) ->destroy_coro; return suspend; // The coroutine is resumed if suspend is false } inline constexpr void await_resume() noexcept {} }; inline constexpr auto initial_suspend() noexcept { return initial_suspend_t {destroy_coro}; } }; #else template <bool suspend> struct InitialSuspend { inline constexpr auto initial_suspend() noexcept { if constexpr (suspend) { return std::suspend_always {}; } else { return std::suspend_never {}; } } }; #endif template <bool suspend> struct FinalSuspend { inline constexpr auto final_suspend() noexcept { if constexpr (suspend) { return std::suspend_always {}; } else { return std::suspend_never {}; } } }; struct ReturnVoid { inline constexpr void return_void() noexcept {} }; template <class DerivedPromise> struct UnhandledException { void unhandled_exception() { // NB: for some reason, GCC doesn't destroy the coroutine frame if // there's an exception raised inside the coroutine. As a result, if // we're on GCC, we need to destroy it manually. #ifdef CONDUIT_USE_GCC_EXCEPTION_WORKAROUND DerivedPromise& promise = static_cast<DerivedPromise&>(*this); auto coro_frame = static_cast<detail::frame_header_t*>( std::coroutine_handle<DerivedPromise>::from_promise(promise) .address()); coro_frame->destroy_coro = promise.destroy_coro; std::coroutine_handle<>::from_address(coro_frame).destroy(); #endif std::rethrow_exception(std::current_exception()); } }; template <class Promise, bool IsNoexcept = true> struct GetReturnObject; template <class Promise> struct GetReturnObject<Promise, false> { using handle_type = std::coroutine_handle<Promise>; // Used by the compiler to produce the return_object when starting the // coroutine handle_type get_return_object() noexcept { return get_handle(); } // Allows you access to the promise object from within a coroutine via // auto& promise = co_yield get_promise; // await_ready() always returns true inline auto yield_value(tags::get_promise_t) noexcept { return async::immediate_value {static_cast<Promise*>(this)}; } inline auto yield_value(tags::get_handle_t) noexcept { return async::immediate_value {get_handle()}; } inline handle_type get_handle() noexcept { return handle_type::from_promise(static_cast<Promise&>(*this)); } }; template <class Promise> struct GetReturnObject<Promise, true> : GetReturnObject<Promise, false> { using super = GetReturnObject<Promise, false>; using super::get_handle; using super::get_return_object; using super::yield_value; using handle_type = typename super::handle_type; // If there's an allocation failure, returns a null coroutine handle static handle_type get_return_object_on_allocation_failure() noexcept { return nullptr; } }; template <class Alloc> struct NewAndDelete { template <class... T> static void* operator new(size_t size, Alloc& alloc, T&&...) { return alloc.alloc(size); } template <class... T> static void* operator new(size_t size, Alloc* alloc, T&&...) { return alloc->alloc(size); } static void operator delete(void* pointer, size_t size) { std::decay_t<Alloc>::dealloc(pointer, size); } }; class HasOwnerAndCallback : public mixin::InitialSuspend<true> { protected: std::coroutine_handle<>* owner = nullptr; async::callback callback; public: template <class T> inline void set_owner(std::coroutine_handle<T>* owner) noexcept { this->owner = reinterpret_cast<std::coroutine_handle<>*>(owner); } inline void set_callback(std::coroutine_handle<> handle) noexcept { callback.emplace(handle); } inline auto final_suspend() noexcept { return callback.release(); } ~HasOwnerAndCallback() noexcept { if (owner) { *owner = nullptr; } } }; class ExceptionHandler { std::exception_ptr exception_ptr; constexpr static bool unhandled_noexcept = std:: is_nothrow_copy_assignable_v<std::exception_ptr>; public: void unhandled_exception() noexcept(unhandled_noexcept) { exception_ptr = std::current_exception(); } void rethrow_if_exception() const { if (exception_ptr) { std::rethrow_exception(exception_ptr); } } void clear_and_rethrow_if_exception() { if (exception_ptr) { auto hold = exception_ptr; exception_ptr = nullptr; std::rethrow_exception(hold); } } }; template <class T> class YieldValue { public: using value_type = std::remove_reference_t<T>; using reference_type = std:: conditional_t<std::is_reference_v<T>, T, T const&>; using pointer_type = std::remove_reference_t<reference_type>*; private: pointer_type value_ptr = nullptr; protected: void clear() noexcept { value_ptr = nullptr; } public: constexpr bool has_value() const noexcept { return value_ptr; } constexpr auto yield_value(reference_type value) noexcept -> std::suspend_always { value_ptr = std::addressof(value); return {}; } constexpr auto get_pointer() const noexcept -> pointer_type { return value_ptr; } constexpr auto value() const noexcept -> reference_type { return *value_ptr; } }; // Protects incorrect co_await operations by deleting await_transform struct DisableCoAwait { template <typename U> std::suspend_never await_transform(U&& value) = delete; }; } // namespace conduit::mixin
31.017778
80
0.674882
19d280bfd3df9525e25a7dcb89e6102afb006dac
970
cpp
C++
vdslib/src/tests/distribution/randombucket.cpp
kennyeric/vespa
f69f960d5ae48d246f56a60e6e46c90a58f836ba
[ "Apache-2.0" ]
1
2018-12-30T05:42:18.000Z
2018-12-30T05:42:18.000Z
vdslib/src/tests/distribution/randombucket.cpp
kennyeric/vespa
f69f960d5ae48d246f56a60e6e46c90a58f836ba
[ "Apache-2.0" ]
1
2021-03-31T22:27:25.000Z
2021-03-31T22:27:25.000Z
vdslib/src/tests/distribution/randombucket.cpp
kennyeric/vespa
f69f960d5ae48d246f56a60e6e46c90a58f836ba
[ "Apache-2.0" ]
1
2020-02-01T07:21:28.000Z
2020-02-01T07:21:28.000Z
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "randombucket.h" #include <vespa/vdslib/state/random.h> namespace RandomBucket{ uint64_t _num_users; uint64_t _locationbits; bool _scheme = false; storage::lib::RandomGen rg; void setUserDocScheme(uint64_t num_users, uint64_t locationbits) { _scheme = true; _num_users = num_users; _locationbits = locationbits; } void setDocScheme() { _scheme = false; } uint64_t get() { uint64_t u = rg.nextUint64(); if(_scheme){ // userdoc uint64_t shift = 8 * sizeof(uint64_t) - _locationbits; uint64_t lsb = u << shift; lsb >>= shift; lsb %= _num_users; u >>= _locationbits; u <<= _locationbits; u |= lsb; } return u; } void setSeed(int seed) { if(seed == -1){ rg = storage::lib::RandomGen(); } else{ rg.setSeed(seed); } } }
19.019608
118
0.627835
19d59469611a8e400bce05b775c6c90b3652d6d0
4,617
cpp
C++
lammps-master/lib/poems/virtualmatrix.cpp
rajkubp020/helloword
4bd22691de24b30a0f5b73821c35a7ac0666b034
[ "MIT" ]
null
null
null
lammps-master/lib/poems/virtualmatrix.cpp
rajkubp020/helloword
4bd22691de24b30a0f5b73821c35a7ac0666b034
[ "MIT" ]
null
null
null
lammps-master/lib/poems/virtualmatrix.cpp
rajkubp020/helloword
4bd22691de24b30a0f5b73821c35a7ac0666b034
[ "MIT" ]
null
null
null
/* *_________________________________________________________________________* * POEMS: PARALLELIZABLE OPEN SOURCE EFFICIENT MULTIBODY SOFTWARE * * DESCRIPTION: SEE READ-ME * * FILE NAME: virtualmatrix.cpp * * AUTHORS: See Author List * * GRANTS: See Grants List * * COPYRIGHT: (C) 2005 by Authors as listed in Author's List * * LICENSE: Please see License Agreement * * DOWNLOAD: Free at www.rpi.edu/~anderk5 * * ADMINISTRATOR: Prof. Kurt Anderson * * Computational Dynamics Lab * * Rensselaer Polytechnic Institute * * 110 8th St. Troy NY 12180 * * CONTACT: anderk5@rpi.edu * *_________________________________________________________________________*/ #include "virtualmatrix.h" #include "matrixfun.h" #include <cstdlib> using namespace std; VirtualMatrix::VirtualMatrix(){ numrows = numcols = 0; } VirtualMatrix::~VirtualMatrix(){ } int VirtualMatrix::GetNumRows() const { return numrows; } int VirtualMatrix::GetNumCols() const { return numcols; } double& VirtualMatrix::operator() (int i, int j){ // array access return operator_2int(i,j); } double VirtualMatrix::Get(int i, int j) const{ return Get_2int(i,j); } void VirtualMatrix::Set(int i, int j, double value){ Set_2int(i,j,value); } double VirtualMatrix::BasicGet(int i, int j) const{ return BasicGet_2int(i,j); } void VirtualMatrix::BasicSet(int i, int j, double value){ BasicSet_2int(i,j,value); } void VirtualMatrix::BasicIncrement(int i, int j, double value){ BasicIncrement_2int(i,j,value); } double& VirtualMatrix::operator() (int i){ return operator_1int(i); } double VirtualMatrix::Get(int i) const{ return Get_1int(i); } void VirtualMatrix::Set(int i, double value){ Set_1int(i, value); } double VirtualMatrix::BasicGet(int i) const{ return BasicGet_1int(i); } void VirtualMatrix::BasicSet(int i, double value){ BasicSet_1int(i, value); } void VirtualMatrix::BasicIncrement(int i, double value){ BasicIncrement_1int(i, value); } double& VirtualMatrix::operator_1int (int i) { cerr << "Error: single dimensional access is not defined for matrices of type " << GetType() << endl; exit(0); return *(new double); } double VirtualMatrix::Get_1int(int i) const { cerr << "Error: single dimensional access is not defined for matrices of type " << GetType() << endl; exit(0); return 0.0; } void VirtualMatrix::Set_1int(int i, double value){ cerr << "Error: single dimensional access is not defined for matrices of type " << GetType() << endl; exit(0); } double VirtualMatrix::BasicGet_1int(int i) const { cerr << "Error: single dimensional access is not defined for matrices of type " << GetType() << endl; exit(0); return 0.0; } void VirtualMatrix::BasicSet_1int(int i, double value) { cerr << "Error: single dimensional access is not defined for matrices of type " << GetType() << endl; exit(0); } void VirtualMatrix::BasicIncrement_1int(int i, double value){ cerr << "Error: single dimensional access is not defined for matrices of type " << GetType() << endl; exit(0); } void VirtualMatrix::Zeros(){ Const(0.0); } void VirtualMatrix::Ones(){ Const(1.0); } ostream& VirtualMatrix::WriteData(ostream& c) const { cerr << "Error: no output definition for matrices of type " << GetType() << endl; exit(0); } istream& VirtualMatrix::ReadData(istream& c){ cerr << "Error: no input definition for matrices of type " << GetType() << endl; exit(0); } // // operators and functions // ostream& operator<< (ostream& c, const VirtualMatrix& A){ //output c << A.GetType() << ' '; A.WriteData(c); c << endl; return c; } istream& operator>> (istream& c, VirtualMatrix& A){ //input VirtualMatrix* vm; int matrixtype; c >> matrixtype; if( MatrixType(matrixtype) == A.GetType() ) A.ReadData(c); else{ // issue a warning? cerr << "Warning: During matrix read expected type " << A.GetType() << " and got type " << matrixtype << endl; vm = NewMatrix(matrixtype); if(!vm){ cerr << "Error: unable to instantiate matrix of type " << matrixtype << endl; exit(0); } vm->ReadData(c); A.AssignVM(*vm); delete vm; } return c; }
26.843023
114
0.621183
19d6905fcc00e21a5f9c27f212201722b919eeb1
176
cpp
C++
src/basic/src/listener_node.cpp
sgermanserrano/gitlab_ci_test
df415655757d9674a31ca704bef6bb7c456e7c09
[ "Apache-2.0" ]
null
null
null
src/basic/src/listener_node.cpp
sgermanserrano/gitlab_ci_test
df415655757d9674a31ca704bef6bb7c456e7c09
[ "Apache-2.0" ]
null
null
null
src/basic/src/listener_node.cpp
sgermanserrano/gitlab_ci_test
df415655757d9674a31ca704bef6bb7c456e7c09
[ "Apache-2.0" ]
1
2019-03-05T16:33:21.000Z
2019-03-05T16:33:21.000Z
#include "basic/listener.h" int main(int argc, char **argv) { ros::init(argc, argv, "listener_node"); Listener listener_node; listener_node.spin(); return 0; }
11
41
0.659091
19d6d426f1ac47a9e74c87895d7b3ba67e038bc4
3,527
cpp
C++
esm/Util.cpp
kstemp/TESviewer
2905367f0e30c586633831e0312a7902fb645b4e
[ "MIT" ]
null
null
null
esm/Util.cpp
kstemp/TESviewer
2905367f0e30c586633831e0312a7902fb645b4e
[ "MIT" ]
null
null
null
esm/Util.cpp
kstemp/TESviewer
2905367f0e30c586633831e0312a7902fb645b4e
[ "MIT" ]
null
null
null
#include "Util.h" #include "records\CELL.h" ESM::Record* ESM::getBaseFromREFR(const ESM::Record* refr, ESM::File& file) { return file.findByFormID(refr->fieldOr<uint32_t>("NAME")); } std::vector<ESM::Group>* ESM::findCellChildrenTopLevel(const ESM::Record* cell, ESM::File& file) { int block = getCellBlock(cell); int subBlock = getCellSubBlock(cell); std::vector<ESM::Group>* cellChildrenTop = (cell->fieldOr<uint16_t>("DATA") & ESM::CellFlags::Interior) ? &file.groups[57].subgroups[block].subgroups[subBlock].subgroups : &file.groups[58].subgroups[0].subgroups[0].subgroups;//.subgroups[2].subgroups; return cellChildrenTop; } ESM::Group* ESM::findCellChildren(ESM::Record* cell, std::vector<ESM::Group>* cellChildrenTop) { auto cellChildren = std::find_if( cellChildrenTop->begin(), cellChildrenTop->end(), [&](const auto& g) { const uint32_t groupParentFormID = g.labelAsFormID(); return g.type == ESM::GroupType::CellChildren && groupParentFormID == cell->formID; }); return &(*cellChildren); } ESM::Group* ESM::findCellTemporaryChildren(ESM::Record* cell, ESM::Group* cellChildren) { auto cellTemporaryChildren = std::find_if( cellChildren->subgroups.begin(), cellChildren->subgroups.end(), [](const auto& g) { return g.type == ESM::GroupType::CellTemporaryChildren; }); return &(*cellTemporaryChildren); } int ESM::getCellBlock(const ESM::Record* cell) { if (cell->fieldOr<uint16_t>("DATA") & ESM::CellFlags::Interior) // last digit of formID in decimal return cell->formID % 10; else return 0; } int ESM::getCellSubBlock(const ESM::Record* cell) { if (cell->fieldOr<uint16_t>("DATA") & ESM::CellFlags::Interior) // penultimate digit of formID in decimal return ((cell->formID / 10) % 10); else return 0; } QString ESM::getRecordFullName(const std::string& name) { if (name == "CELL") return "Cell"; else if (name == "TES4") return "TES Header"; else if (name == "WRLD") return "Worldspace"; else if (name == "STAT") return "Static"; else if (name == "FURN") return "Furniture"; else if (name == "CONT") return "Container"; else if (name == "DOOR") return "Door"; else if (name == "LIGH") return "Light"; else if (name == "MISC") return "Miscellanous Object"; else if (name == "ALCH") return "Potion"; else if (name == "FLOR") return "Flora"; else if (name == "MATO") return "Material Object"; else if (name == "TREE") return "Tree"; else if (name == "NAVM") return "Navigation Mesh"; return QString::fromStdString(name); } QString ESM::getGroupCaption(const ESM::Group& group) { switch (group.type) { case ESM::GroupType::Top: return getRecordFullName(group.label); break; case ESM::GroupType::WorldChildren: return "World Children"; break; case ESM::GroupType::InteriorCellBlock: return "Block " + QString::number(*(int32_t*)(&group.label[0])); break; case ESM::GroupType::InteriorCellSubBlock: return "Sub-Block " + QString::number(*(int32_t*)(&group.label[0])); break; case ESM::GroupType::ExteriorCellBlock: return "Block"; break; case ESM::GroupType::ExteriorCellSubBlock: return "Sub-Block"; break; case ESM::GroupType::CellChildren: return "Cell children"; break; case ESM::GroupType::TopicChildren: return "Topic children"; break; case ESM::GroupType::CellPersistentChildren: return "Persistent"; break; case ESM::GroupType::CellTemporaryChildren: return "Temporary"; break; default: return "Group"; // TODO should not happen? break; } }
26.719697
106
0.68727
19d984e9b5562b1f89838d17a1e10c164a8a6b78
1,360
cpp
C++
D01/ex00/main.cpp
amoinier/piscine-cpp
43d4806d993eb712f49a32e54646d8c058a569ea
[ "MIT" ]
null
null
null
D01/ex00/main.cpp
amoinier/piscine-cpp
43d4806d993eb712f49a32e54646d8c058a569ea
[ "MIT" ]
null
null
null
D01/ex00/main.cpp
amoinier/piscine-cpp
43d4806d993eb712f49a32e54646d8c058a569ea
[ "MIT" ]
null
null
null
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* main.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: amoinier <amoinier@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/10/03 09:09:58 by amoinier #+# #+# */ /* Updated: 2017/10/04 17:39:41 by amoinier ### ########.fr */ /* */ /* ************************************************************************** */ #include "Pony.hpp" static void ponyOnTheHeap(void) { Pony* ponyHeap = new Pony("Petit_Tonerre"); std::cout << ponyHeap->getName() << " attacks you !" << std::endl; delete ponyHeap; return ; } static void ponyOnTheStack(void) { Pony ponyStack = Pony("Chocolat"); std::cout << ponyStack.getName() << " attacks you !" << std::endl; return ; } int main() { ponyOnTheHeap(); ponyOnTheStack(); std::cout << "Where are ponies ?" << std::endl; return 0; }
32.380952
80
0.294118
19dcb470546b54f68991f8e4df94417ed86b88d1
1,201
cpp
C++
app/main.cpp
frachop/ezWebSockify
a35ff5aa7867830b0b51d9d7dfedc44e55f27eab
[ "MIT" ]
null
null
null
app/main.cpp
frachop/ezWebSockify
a35ff5aa7867830b0b51d9d7dfedc44e55f27eab
[ "MIT" ]
null
null
null
app/main.cpp
frachop/ezWebSockify
a35ff5aa7867830b0b51d9d7dfedc44e55f27eab
[ "MIT" ]
null
null
null
// // main.cpp // ezWebSockify // // Created by Franck on 22/07/2020. // Copyright © 2020 Frachop. All rights reserved. // #include <ezWebSockifyLib/ezWebSockifyLib.hpp> #include <iostream> #include <limits> #include <csignal> #include <thread> namespace { volatile std::sig_atomic_t gSignalStatus; } void signal_handler(int signal) { std::cout << "handling ctrl-c signal" << std::endl; gSignalStatus = signal; ezWebSockify::stop(); } int main(int argc, const char * argv[]) { if (argc != 4) { std::cerr << "ezWebSockify version " << ezWebSockify::getVersionString() << std::endl; std::cerr << "Usage: ezWebSockify <wsPort> <tcpHost> <tcpPort>" << std::endl; return 1; } auto const wsPort{ std::atoi(argv[1]) }; auto const tcpHost{ argv[2] }; auto const tcpPort{ std::atoi(argv[3]) }; if ((wsPort <= 0) || (tcpPort <= 0) || (wsPort > std::numeric_limits<uint16_t>::max()) || (tcpPort > std::numeric_limits<uint16_t>::max())) { std::cerr << "port out of range" << std::endl; return 1; } // Install a signal handler std::signal(SIGINT, signal_handler); ezWebSockify::start(wsPort, tcpHost, tcpPort); ezWebSockify::wait(); ezWebSockify::cleanup(); return 0; }
21.446429
140
0.661948
19de5723db8d917abd9a56bffc906ebfb0b90aec
542
cpp
C++
3rdParty/B-Human/Tools/Streams/InOut.cpp
h3ndrk/CompiledNN
8ed33a8d976367bfe7a62f506ba6215256a5b26c
[ "MIT" ]
null
null
null
3rdParty/B-Human/Tools/Streams/InOut.cpp
h3ndrk/CompiledNN
8ed33a8d976367bfe7a62f506ba6215256a5b26c
[ "MIT" ]
null
null
null
3rdParty/B-Human/Tools/Streams/InOut.cpp
h3ndrk/CompiledNN
8ed33a8d976367bfe7a62f506ba6215256a5b26c
[ "MIT" ]
null
null
null
/** * @file Tools/Streams/InOut.cpp * * Implementation of the streamable function endl. * * @author <a href="mailto:oberlies@sim.tu-darmstadt.de">Tobias Oberlies</a> */ #include "InOut.h" #include <cstring> Out& endl(Out& out) { out.outEndL(); return out; } In& endl(In& in) { in.inEndL(); return in; } namespace Streaming { void trimName(const char*& name) { if(name) { const char* p = name + strlen(name) - 1; while(p >= name && *p != ')' && *p != ' ') --p; name = p + 1; } } }
14.648649
76
0.551661
19e483c8ad2f6650868557d6c731d793e94a8c5b
437
hpp
C++
server/api/include/irods/rsFileRead.hpp
aghsmith/irods
31d48a47a4942df688da94b30aa8a5b5210261bb
[ "BSD-3-Clause" ]
1
2022-03-08T13:00:56.000Z
2022-03-08T13:00:56.000Z
server/api/include/irods/rsFileRead.hpp
selroc/irods
d232c7f3e0154cacc3a115aa50e366a98617b126
[ "BSD-3-Clause" ]
null
null
null
server/api/include/irods/rsFileRead.hpp
selroc/irods
d232c7f3e0154cacc3a115aa50e366a98617b126
[ "BSD-3-Clause" ]
null
null
null
#ifndef RS_FILE_READ_HPP #define RS_FILE_READ_HPP #include "irods/rodsConnect.h" #include "irods/fileRead.h" int rsFileRead( rsComm_t *rsComm, fileReadInp_t *fileReadInp, bytesBuf_t *fileReadOutBBuf ); int _rsFileRead( rsComm_t *rsComm, fileReadInp_t *fileReadInp, bytesBuf_t *fileReadOutBBuf ); int remoteFileRead( rsComm_t *rsComm, fileReadInp_t *fileReadInp, bytesBuf_t *fileReadOutBBuf, rodsServerHost_t *rodsServerHost ); #endif
36.416667
130
0.816934
19e5207ad65c5f2f519ab2a797b1c27220dabaab
2,048
cpp
C++
tests/test_asm/main.cpp
SgAkErRu/labs
9cf71e131513beb3c54ad3599f2a1e085bff6947
[ "BSD-3-Clause" ]
null
null
null
tests/test_asm/main.cpp
SgAkErRu/labs
9cf71e131513beb3c54ad3599f2a1e085bff6947
[ "BSD-3-Clause" ]
null
null
null
tests/test_asm/main.cpp
SgAkErRu/labs
9cf71e131513beb3c54ad3599f2a1e085bff6947
[ "BSD-3-Clause" ]
null
null
null
// Ассемблерные вставки на GCC с флагом -masm=intel в .pro для синтаксиса Intel // (тоже самое можно и через команды .intel_syntax noprefix в начале asm вставки (и после кода, но внутри вставки, надо было вкл обратно AT&T .att_syntax noprefix) // использовать либо глобальные переменные, или локальные объявлять согласно AT&T syntax (или это GAS ассемблер, не знаю точно) после кода через : выходные операнды, .., .., : входные, .., .. // в квадратных скобках можно указать имя операнда входного / выходного // m - ограничитель, означает, что операнд передается через память, а всякие ir, r и так далее - это РОН // во 2 функции показал, как можно без \n обойтись #include <stdio.h> #include <iostream> inline int cmp_asm(int a, int b, int c){ asm( //ассемблерная функция "mov edx, %[a]\n" // помещение в регистр еdх значения переменной а "cmp edx, %[b]\n" // сравнение содержимого регистра edx и переменной b "ja m1\n" // условный переход "mov edx, %[b]\n" // помещение в регистр еdх значения переменной b "m1: cmp edx, %[c]\n" // сравнение содержимого регистра edx и переменной c "jna m2\n" // условный переход "mov %[c], edx\n" // помещение в переменную c содержимого регистра еdх "m2:\n" : [c] "+m" (c) : [a] "m" (a), [b] "m" (b) ); return c; } inline int cmp_asm_2(int a, int b, int c){ asm ( R"( mov edx, %[a] # коммент cmp edx, %[b] ja m1 mov edx, %[b] m1: cmp edx, %[c] jna m2 mov %[c], edx m2: )" : [c] "+m" (c) : [a] "m" (a), [b] "m" (b) ); return c; } int main() { int k, m, n; //инициализация целочисленных переменных printf("Compare\n"); printf("Please, input 1st number\n"); scanf("%d", &k); printf("Please, input 2nd number\n"); scanf("%d", &m); printf("Please, input 2nd number\n"); scanf("%d", &n); std::cout << cmp_asm(k, m, n); scanf("%d", &n); return 0; }
29.681159
192
0.581055
19e87cf737beb7be0f14c977cf595772b345c4d6
166
hpp
C++
modules/anti_nd/functions/CfgFunctions.hpp
goosko/Olsen-Framework-Arma-3
bb77aa28195bb04cc3b94ec768901308162e555c
[ "MIT" ]
4
2020-05-04T18:03:59.000Z
2020-05-06T19:40:27.000Z
modules/anti_nd/functions/CfgFunctions.hpp
goosko/Olsen-Framework-Arma-3
bb77aa28195bb04cc3b94ec768901308162e555c
[ "MIT" ]
64
2020-09-13T23:26:04.000Z
2022-03-19T07:27:54.000Z
modules/anti_nd/functions/CfgFunctions.hpp
goosko/Olsen-Framework-Arma-3
bb77aa28195bb04cc3b94ec768901308162e555c
[ "MIT" ]
5
2020-12-07T20:37:05.000Z
2022-02-03T21:03:49.000Z
#include "..\script_component.hpp" class COMPONENT { tag = COMPONENT; class ANTI_ND { file = "modules\anti_nd\functions\anti_nd"; class Init {}; }; };
18.444444
46
0.644578
19e89de6247e69bf0bb45872c22c40fc10280620
1,551
cpp
C++
test/spMatspMat_test.cpp
pnnl/NWGraph
bd9e091d2eed4e655c109347c3ec734bf399ff70
[ "BSD-4-Clause-UC" ]
null
null
null
test/spMatspMat_test.cpp
pnnl/NWGraph
bd9e091d2eed4e655c109347c3ec734bf399ff70
[ "BSD-4-Clause-UC" ]
null
null
null
test/spMatspMat_test.cpp
pnnl/NWGraph
bd9e091d2eed4e655c109347c3ec734bf399ff70
[ "BSD-4-Clause-UC" ]
null
null
null
/** * @file spMatspMat_test.cpp * * @copyright SPDX-FileCopyrightText: 2022 Battelle Memorial Institute * @copyright SPDX-FileCopyrightText: 2022 University of Washington * * SPDX-License-Identifier: BSD-3-Clause * * @authors * Andrew Lumsdaine * */ #include <tuple> #include <vector> #include "nwgraph/graph_concepts.hpp" #include "nwgraph/adaptors/edge_range.hpp" #include "common/test_header.hpp" #include "nwgraph/algorithms/spMatspMat.hpp" TEST_CASE("Row times Row", "[row-row") { // Create A, B and known correct answer // By hand // Generate random A, B compute C with known, slow, approach // (e.g., convert A, B to dense // Compute C = A * B with spMatspMat // Compare C with known correct answer /* [ 3, 1, 4 ] [ 8, 6, 7 ] [ 65, 21, 57 ] [ 1, 5, 9 ] [ 5, 3, 0 ] = [ 114, 21, 88 ] [ 2, 6, 7 ] [ 9, 0, 9 ] [ 109, 30, 77 ] */ using SparseMatrix = std::vector<std::vector<std::tuple<int, double>>>; SparseMatrix A { { { 0, 3 }, { 1, 1 }, { 2, 4 } }, { { 0, 1 }, { 1, 5 }, { 2, 9 } }, { { 0, 2 }, { 1, 6 }, { 2, 7 } }, }; SparseMatrix B { { { 0, 8 }, { 1, 6 }, { 2, 7 } }, { { 0, 5 }, { 1, 3 }, { 2, 0 } }, { { 0, 9 }, { 1, 0 }, { 2, 9 } }, }; SparseMatrix C { { { 0, 65 }, { 1, 21 }, { 2, 57 } }, { { 0, 114 }, { 1, 21 }, { 2, 88 } }, { { 0, 109 }, { 1, 30 }, { 2, 77 } }, }; auto d = nw::graph::spMatspMat<double>(A, B); REQUIRE(std::equal(begin(d), end(d), begin(nw::graph::make_edge_range<0>(C)))); }
25.42623
81
0.516441
19e98193d98bf64799596d2ad3257aebf61f771e
1,224
hpp
C++
include/c9/time.hpp
stormbrew/channel9
626b42c208ce1eb54fff09ebd9f9e9fd0311935d
[ "MIT" ]
1
2015-02-13T02:03:29.000Z
2015-02-13T02:03:29.000Z
include/c9/time.hpp
stormbrew/channel9
626b42c208ce1eb54fff09ebd9f9e9fd0311935d
[ "MIT" ]
null
null
null
include/c9/time.hpp
stormbrew/channel9
626b42c208ce1eb54fff09ebd9f9e9fd0311935d
[ "MIT" ]
null
null
null
#pragma once #include <time.h> #include <sys/time.h> class Time { double t; public: Time(){ struct timeval time; gettimeofday(&time, NULL); t = time.tv_sec + (double)time.tv_usec/1000000; } Time(double a) : t(a) { } Time(const struct timeval & time){ t = time.tv_sec + (double)time.tv_usec/1000000; } int to_i() const { return (int)t; } long long in_msec() const { return (long long)(t*1000); } long long in_usec() const { return (long long)(t*1000000); } double to_f() const { return t; } Time operator + (double a) const { return Time(t+a); } Time & operator += (double a) { t += a; return *this; } double operator - (const Time & a) const { return t - a.t; } Time operator - (double a) const { return Time(t-a); } Time & operator -= (double a) { t -= a; return *this; } bool operator < (const Time & a) const { return t < a.t; } bool operator <= (const Time & a) const { return t <= a.t; } bool operator > (const Time & a) const { return t > a.t; } bool operator >= (const Time & a) const { return t >= a.t; } bool operator == (const Time & a) const { return t == a.t; } bool operator != (const Time & a) const { return t != a.t; } };
31.384615
68
0.589869
19ea691d62f5de4780a604b7cda878648f87c921
35,453
cpp
C++
src/Layers/xrRender/xrRender_console.cpp
clayne/xray-16
32ebf81a252c7179e2824b2874f911a91e822ad1
[ "OML", "Linux-OpenIB" ]
2
2015-02-23T10:43:02.000Z
2015-06-11T14:45:08.000Z
src/Layers/xrRender/xrRender_console.cpp
clayne/xray-16
32ebf81a252c7179e2824b2874f911a91e822ad1
[ "OML", "Linux-OpenIB" ]
17
2022-01-25T08:58:23.000Z
2022-03-28T17:18:28.000Z
src/Layers/xrRender/xrRender_console.cpp
clayne/xray-16
32ebf81a252c7179e2824b2874f911a91e822ad1
[ "OML", "Linux-OpenIB" ]
1
2015-06-05T20:04:00.000Z
2015-06-05T20:04:00.000Z
#include "stdafx.h" #pragma hdrstop #include "xrRender_console.h" #include "xrCore/xr_token.h" #include "xrCore/Animation/SkeletonMotions.hpp" u32 ps_Preset = 2; const xr_token qpreset_token[] = {{"Minimum", 0}, {"Low", 1}, {"Default", 2}, {"High", 3}, {"Extreme", 4}, {nullptr, 0}}; u32 ps_r2_smapsize = 2048; const xr_token qsmapsize_token[] = { #if !defined(MASTER_GOLD) || RENDER == R_R1 { "256", 256 }, // Too bad for R2+ { "512", 512 }, // But works #endif { "1024", 1024 }, { "1032", 1032 }, { "1536", 1536 }, { "2048", 2048 }, { "2560", 2560 }, { "3072", 3072 }, { "3584", 3584 }, { "4096", 4096 }, #if defined(USE_DX11) || defined(USE_OGL) // XXX: check if values more than 8192 are supported on OpenGL { "5120", 5120 }, { "6144", 6144 }, { "7168", 7168 }, { "8192", 8192 }, { "9216", 9216 }, { "10240", 10240 }, { "11264", 11264 }, { "12288", 12288 }, { "13312", 13312 }, { "14336", 14336 }, { "15360", 15360 }, { "16384", 16384 }, #endif // !USE_DX9 { nullptr, 0 } }; u32 ps_r_ssao_mode = 2; const xr_token qssao_mode_token[] = {{"disabled", 0}, {"default", 1}, {"hdao", 2}, {"hbao", 3}, {nullptr, 0}}; u32 ps_r_sun_shafts = 2; const xr_token qsun_shafts_token[] = {{"st_opt_off", 0}, {"st_opt_low", 1}, {"st_opt_medium", 2}, {"st_opt_high", 3}, {nullptr, 0}}; u32 ps_r_ssao = 3; const xr_token qssao_token[] = {{"st_opt_off", 0}, {"st_opt_low", 1}, {"st_opt_medium", 2}, {"st_opt_high", 3}, #if defined(USE_DX11) || defined(USE_OGL) {"st_opt_ultra", 4}, #endif {nullptr, 0}}; u32 ps_r_sun_quality = 1; // = 0; const xr_token qsun_quality_token[] = {{"st_opt_low", 0}, {"st_opt_medium", 1}, {"st_opt_high", 2}, #if defined(USE_DX11) // TODO: OGL: fix ultra and extreme settings {"st_opt_ultra", 3}, {"st_opt_extreme", 4}, #endif // !USE_DX9 {nullptr, 0}}; u32 ps_r_water_reflection = 3; const xr_token qwater_reflection_quality_token[] = { { "st_opt_off", 0 }, { "st_opt_low", 1 }, { "st_opt_medium", 2 }, { "st_opt_high", 3 }, { "st_opt_ultra", 4 }, { nullptr, -1 } }; u32 ps_r3_msaa = 0; // = 0; const xr_token qmsaa_token[] = {{"st_opt_off", 0}, {"2x", 1}, {"4x", 2}, {"8x", 3}, {nullptr, 0}}; u32 ps_r3_msaa_atest = 0; // = 0; const xr_token qmsaa__atest_token[] = { {"st_opt_off", 0}, {"st_opt_atest_msaa_dx10_0", 1}, {"st_opt_atest_msaa_dx10_1", 2}, {nullptr, 0}}; u32 ps_r3_minmax_sm = 3; // = 0; const xr_token qminmax_sm_token[] = {{"off", 0}, {"on", 1}, {"auto", 2}, {"autodetect", 3}, {nullptr, 0}}; // “Off” // “DX10.0 style [Standard]” // “DX10.1 style [Higher quality]” // Common extern int psSkeletonUpdate; extern float r__dtex_range; Flags32 ps_r__common_flags = { RFLAG_ACTOR_SHADOW | RFLAG_NO_RAM_TEXTURES }; // All renders //int ps_r__Supersample = 1; int ps_r__LightSleepFrames = 10; float ps_r__Detail_l_ambient = 0.9f; float ps_r__Detail_l_aniso = 0.25f; float ps_r__Detail_density = 0.3f; float ps_r__Detail_height = 1.f; float ps_r__Detail_rainbow_hemi = 0.75f; float ps_r__Tree_w_rot = 10.0f; float ps_r__Tree_w_speed = 1.00f; float ps_r__Tree_w_amp = 0.005f; Fvector ps_r__Tree_Wave = {.1f, .01f, .11f}; float ps_r__Tree_SBC = 1.5f; // scale bias correct float ps_r__WallmarkTTL = 50.f; float ps_r__WallmarkSHIFT = 0.0001f; float ps_r__WallmarkSHIFT_V = 0.0001f; float ps_r__GLOD_ssa_start = 256.f; float ps_r__GLOD_ssa_end = 64.f; float ps_r__LOD = 0.75f; //float ps_r__LOD_Power = 1.5f; float ps_r__ssaDISCARD = 3.5f; // RO float ps_r__ssaDONTSORT = 32.f; // RO float ps_r__ssaHZBvsTEX = 96.f; // RO int ps_r__tf_Anisotropic = 8; float ps_r__tf_Mipbias = 0.0f; // R1 float ps_r1_ssaLOD_A = 64.f; float ps_r1_ssaLOD_B = 48.f; Flags32 ps_r1_flags = {R1FLAG_DLIGHTS}; // r1-only float ps_r1_lmodel_lerp = 0.1f; float ps_r1_dlights_clip = 40.f; float ps_r1_pps_u = 0.f; float ps_r1_pps_v = 0.f; int ps_r1_force_geomx = 0; // R1-specific int ps_r1_GlowsPerFrame = 16; // r1-only float ps_r1_fog_luminance = 1.1f; // r1-only int ps_r1_SoftwareSkinning = 0; // r1-only // R2 bool ps_r2_sun_static = false; bool ps_r2_advanced_pp = true; // advanced post process and effects float ps_r2_ssaLOD_A = 64.f; float ps_r2_ssaLOD_B = 48.f; // R2-specific Flags32 ps_r2_ls_flags = {R2FLAG_SUN //| R2FLAG_SUN_IGNORE_PORTALS | R2FLAG_EXP_DONT_TEST_UNSHADOWED | R2FLAG_USE_NVSTENCIL | R2FLAG_EXP_SPLIT_SCENE | R2FLAG_EXP_MT_CALC | R3FLAG_DYN_WET_SURF | R3FLAG_VOLUMETRIC_SMOKE //| R3FLAG_MSAA //| R3FLAG_MSAA_OPT | R3FLAG_GBUFFER_OPT | R2FLAG_DETAIL_BUMP | R2FLAG_DOF | R2FLAG_SOFT_PARTICLES | R2FLAG_SOFT_WATER | R2FLAG_STEEP_PARALLAX | R2FLAG_SUN_FOCUS | R2FLAG_SUN_TSM | R2FLAG_TONEMAP | R2FLAG_VOLUMETRIC_LIGHTS}; // r2-only Flags32 ps_r2_ls_flags_ext = { /*R2FLAGEXT_SSAO_OPT_DATA |*/ R2FLAGEXT_SSAO_HALF_DATA | R2FLAGEXT_ENABLE_TESSELLATION | R3FLAGEXT_SSR_HALF_DEPTH | R3FLAGEXT_SSR_JITTER}; float ps_r2_df_parallax_h = 0.02f; float ps_r2_df_parallax_range = 75.f; float ps_r2_tonemap_middlegray = 1.f; // r2-only float ps_r2_tonemap_adaptation = 1.f; // r2-only float ps_r2_tonemap_low_lum = 0.0001f; // r2-only float ps_r2_tonemap_amount = 0.7f; // r2-only float ps_r2_ls_bloom_kernel_g = 3.f; // r2-only float ps_r2_ls_bloom_kernel_b = .7f; // r2-only float ps_r2_ls_bloom_speed = 100.f; // r2-only float ps_r2_ls_bloom_kernel_scale = .7f; // r2-only // gauss float ps_r2_ls_dsm_kernel = .7f; // r2-only float ps_r2_ls_psm_kernel = .7f; // r2-only float ps_r2_ls_ssm_kernel = .7f; // r2-only float ps_r2_ls_bloom_threshold = .00001f; // r2-only Fvector ps_r2_aa_barier = {.8f, .1f, 0}; // r2-only Fvector ps_r2_aa_weight = {.25f, .25f, 0}; // r2-only float ps_r2_aa_kernel = .5f; // r2-only float ps_r2_mblur = .0f; // .5f int ps_r2_GI_depth = 1; // 1..5 int ps_r2_GI_photons = 16; // 8..64 float ps_r2_GI_clip = EPS_L; // EPS float ps_r2_GI_refl = .9f; // .9f float ps_r2_ls_depth_scale = 1.00001f; // 1.00001f float ps_r2_ls_depth_bias = -0.0003f; // -0.0001f float ps_r2_ls_squality = 1.0f; // 1.00f float ps_r2_sun_tsm_projection = 0.3f; // 0.18f float ps_r2_sun_tsm_bias = -0.01f; // float ps_r2_sun_near = 20.f; // 12.0f extern float OLES_SUN_LIMIT_27_01_07; // actually sun_far float ps_r2_sun_near_border = 0.75f; // 1.0f float ps_r2_sun_depth_far_scale = 1.00000f; // 1.00001f float ps_r2_sun_depth_far_bias = -0.00002f; // -0.0000f float ps_r2_sun_depth_near_scale = 1.0000f; // 1.00001f float ps_r2_sun_depth_near_bias = 0.00001f; // -0.00005f float ps_r2_sun_lumscale = 1.0f; // 1.0f float ps_r2_sun_lumscale_hemi = 1.0f; // 1.0f float ps_r2_sun_lumscale_amb = 1.0f; float ps_r2_gmaterial = 2.2f; // float ps_r2_zfill = 0.25f; // .1f float ps_r2_dhemi_sky_scale = 0.08f; // 1.5f float ps_r2_dhemi_light_scale = 0.2f; float ps_r2_dhemi_light_flow = 0.1f; int ps_r2_dhemi_count = 5; // 5 int ps_r2_wait_sleep = 0; int ps_r2_wait_timeout = 500; float ps_r2_lt_smooth = 1.f; // 1.f float ps_r2_slight_fade = 0.5f; // 1.f // x - min (0), y - focus (1.4), z - max (100) Fvector3 ps_r2_dof = Fvector3().set(-1.25f, 1.4f, 600.f); float ps_r2_dof_sky = 30; // distance to sky float ps_r2_dof_kernel_size = 5.0f; // 7.0f float ps_r3_dyn_wet_surf_near = 5.f; // 10.0f float ps_r3_dyn_wet_surf_far = 20.f; // 30.0f int ps_r3_dyn_wet_surf_sm_res = 256; // 256 u32 ps_steep_parallax = 0; int ps_r__detail_radius = 49; u32 dm_size = 24; u32 dm_cache1_line = 12; //dm_size*2/dm_cache1_count u32 dm_cache_line = 49; //dm_size+1+dm_size u32 dm_cache_size = 2401; //dm_cache_line*dm_cache_line float dm_fade = 47.5; //float(2*dm_size)-.5f; u32 dm_current_size = 24; u32 dm_current_cache1_line = 12; //dm_current_size*2/dm_cache1_count u32 dm_current_cache_line = 49; //dm_current_size+1+dm_current_size u32 dm_current_cache_size = 2401; //dm_current_cache_line*dm_current_cache_line float dm_current_fade = 47.5; //float(2*dm_current_size)-.5f; float ps_current_detail_density = 0.6f; float ps_current_detail_height = 1.f; xr_token ext_quality_token[] = {{"qt_off", 0}, {"qt_low", 1}, {"qt_medium", 2}, {"qt_high", 3}, {"qt_extreme", 4}, {nullptr, 0}}; //-AVO //- Mad Max float ps_r2_gloss_factor = 4.0f; //- Mad Max #ifndef _EDITOR #include "xrEngine/XR_IOConsole.h" #include "xrEngine/xr_ioc_cmd.h" #if defined(USE_DX11) #include "Layers/xrRenderDX10/StateManager/dx10SamplerStateCache.h" #endif //----------------------------------------------------------------------- //AVO: detail draw radius class CCC_detail_radius : public CCC_Integer { public: void apply() { dm_current_size = iFloor((float)ps_r__detail_radius / 4) * 2; dm_current_cache1_line = dm_current_size * 2 / 4; // assuming cache1_count = 4 dm_current_cache_line = dm_current_size + 1 + dm_current_size; dm_current_cache_size = dm_current_cache_line * dm_current_cache_line; dm_current_fade = float(2 * dm_current_size) - .5f; } CCC_detail_radius(LPCSTR N, int* V, int _min = 0, int _max = 999) : CCC_Integer(N, V, _min, _max) {}; void Execute(LPCSTR args) override { CCC_Integer::Execute(args); apply(); } void GetStatus(TStatus& S) override { CCC_Integer::GetStatus(S); } }; //-AVO class CCC_tf_Aniso : public CCC_Integer { public: void apply() { #if defined(USE_DX9) || defined(USE_DX11) if (nullptr == HW.pDevice) return; #endif int val = *value; clamp(val, 1, 16); #if defined(USE_DX9) for (u32 i = 0; i < HW.Caps.raster.dwStages; i++) CHK_DX(HW.pDevice->SetSamplerState(i, D3DSAMP_MAXANISOTROPY, val)); #elif defined(USE_DX11) SSManager.SetMaxAnisotropy(val); #elif defined(USE_OGL) // OGL: don't set aniso here because it will be updated after vid restart #else # error No graphics API selected or enabled! #endif } CCC_tf_Aniso(LPCSTR N, int* v) : CCC_Integer(N, v, 1, 16){}; virtual void Execute(LPCSTR args) { CCC_Integer::Execute(args); apply(); } virtual void GetStatus(TStatus& S) { CCC_Integer::GetStatus(S); apply(); } }; class CCC_tf_MipBias : public CCC_Float { public: void apply() { #if defined(USE_DX9) || defined(USE_DX11) if (nullptr == HW.pDevice) return; #endif #if defined(USE_DX9) for (u32 i = 0; i < HW.Caps.raster.dwStages; i++) CHK_DX(HW.pDevice->SetSamplerState(i, D3DSAMP_MIPMAPLODBIAS, *((u32*)value))); #elif defined(USE_DX11) SSManager.SetMipLODBias(*value); #endif } CCC_tf_MipBias(LPCSTR N, float* v) : CCC_Float(N, v, -3.f, +3.f) {} virtual void Execute(LPCSTR args) { CCC_Float::Execute(args); apply(); } virtual void GetStatus(TStatus& S) { CCC_Float::GetStatus(S); apply(); } }; class CCC_R2GM : public CCC_Float { public: CCC_R2GM(LPCSTR N, float* v) : CCC_Float(N, v, 0.f, 4.f) { *v = 0; }; virtual void Execute(LPCSTR args) { if (0 == xr_strcmp(args, "on")) { ps_r2_ls_flags.set(R2FLAG_GLOBALMATERIAL, TRUE); } else if (0 == xr_strcmp(args, "off")) { ps_r2_ls_flags.set(R2FLAG_GLOBALMATERIAL, FALSE); } else { CCC_Float::Execute(args); if (ps_r2_ls_flags.test(R2FLAG_GLOBALMATERIAL)) { static LPCSTR name[4] = {"oren", "blin", "phong", "metal"}; float mid = *value; int m0 = iFloor(mid) % 4; int m1 = (m0 + 1) % 4; float frc = mid - float(iFloor(mid)); Msg("* material set to [%s]-[%s], with lerp of [%f]", name[m0], name[m1], frc); } } } }; class CCC_Screenshot : public IConsole_Command { public: CCC_Screenshot(LPCSTR N) : IConsole_Command(N){}; virtual void Execute(LPCSTR args) { if (GEnv.isDedicatedServer) return; string_path name; name[0] = 0; sscanf(args, "%s", name); LPCSTR image = xr_strlen(name) ? name : 0; GEnv.Render->Screenshot(IRender::SM_NORMAL, image); } }; class CCC_ModelPoolStat : public IConsole_Command { public: CCC_ModelPoolStat(LPCSTR N) : IConsole_Command(N) { bEmptyArgsHandled = TRUE; }; virtual void Execute(LPCSTR /*args*/) { RImplementation.Models->dump(); } }; class CCC_SSAO_Mode : public CCC_Token { public: CCC_SSAO_Mode(LPCSTR N, u32* V, const xr_token* T) : CCC_Token(N, V, T){}; virtual void Execute(LPCSTR args) { CCC_Token::Execute(args); switch (*value) { case 0: { ps_r_ssao = 0; ps_r2_ls_flags_ext.set(R2FLAGEXT_SSAO_HBAO, 0); ps_r2_ls_flags_ext.set(R2FLAGEXT_SSAO_HDAO, 0); break; } case 1: { if (ps_r_ssao == 0) { ps_r_ssao = 1; } ps_r2_ls_flags_ext.set(R2FLAGEXT_SSAO_HBAO, 0); ps_r2_ls_flags_ext.set(R2FLAGEXT_SSAO_HDAO, 0); ps_r2_ls_flags_ext.set(R2FLAGEXT_SSAO_HALF_DATA, 0); break; } case 2: { if (ps_r_ssao == 0) { ps_r_ssao = 1; } ps_r2_ls_flags_ext.set(R2FLAGEXT_SSAO_HBAO, 0); ps_r2_ls_flags_ext.set(R2FLAGEXT_SSAO_HDAO, 1); ps_r2_ls_flags_ext.set(R2FLAGEXT_SSAO_OPT_DATA, 0); ps_r2_ls_flags_ext.set(R2FLAGEXT_SSAO_HALF_DATA, 0); break; } case 3: { if (ps_r_ssao == 0) { ps_r_ssao = 1; } ps_r2_ls_flags_ext.set(R2FLAGEXT_SSAO_HBAO, 1); ps_r2_ls_flags_ext.set(R2FLAGEXT_SSAO_HDAO, 0); ps_r2_ls_flags_ext.set(R2FLAGEXT_SSAO_OPT_DATA, 1); break; } } } }; //----------------------------------------------------------------------- class CCC_Preset : public CCC_Token { public: CCC_Preset(LPCSTR N, u32* V, const xr_token* T) : CCC_Token(N, V, T){}; virtual void Execute(LPCSTR args) { CCC_Token::Execute(args); string_path _cfg; string_path cmd; switch (*value) { case 0: xr_strcpy(_cfg, "rspec_minimum.ltx"); break; case 1: xr_strcpy(_cfg, "rspec_low.ltx"); break; case 2: xr_strcpy(_cfg, "rspec_default.ltx"); break; case 3: xr_strcpy(_cfg, "rspec_high.ltx"); break; case 4: xr_strcpy(_cfg, "rspec_extreme.ltx"); break; } FS.update_path(_cfg, "$game_config$", _cfg); strconcat(sizeof(cmd), cmd, "cfg_load", " ", _cfg); Console->Execute(cmd); } }; class CCC_memory_stats : public IConsole_Command { public: CCC_memory_stats(LPCSTR N) : IConsole_Command(N) { bEmptyArgsHandled = true; }; virtual void Execute(LPCSTR /*args*/) { // TODO: OGL: Implement memory usage statistics. #if defined(USE_DX9) || defined(USE_DX11) u32 m_base = 0; u32 c_base = 0; u32 m_lmaps = 0; u32 c_lmaps = 0; RImplementation.ResourcesGetMemoryUsage(m_base, c_base, m_lmaps, c_lmaps); Msg("memory usage mb \t \t video \t managed \t system \n"); const float MiB = 1024*1024; // XXX: use it as common enum value (like in X-Ray 2.0) const u32* mem_usage = HW.stats_manager.memory_usage_summary[enum_stats_buffer_type_vertex]; float vb_video = mem_usage[D3DPOOL_DEFAULT] / MiB; float vb_managed = mem_usage[D3DPOOL_MANAGED] / MiB; float vb_system = mem_usage[D3DPOOL_SYSTEMMEM] / MiB; Msg("vertex buffer \t \t %f \t %f \t %f ", vb_video, vb_managed, vb_system); float ib_video = mem_usage[D3DPOOL_DEFAULT] / MiB; float ib_managed = mem_usage[D3DPOOL_MANAGED] / MiB; float ib_system = mem_usage[D3DPOOL_SYSTEMMEM] / MiB; Msg("index buffer \t \t %f \t %f \t %f ", ib_video, ib_managed, ib_system); float textures_managed = (m_base+m_lmaps)/MiB; Msg("textures \t \t %f \t %f \t %f ", 0.f, textures_managed, 0.f); mem_usage = HW.stats_manager.memory_usage_summary[enum_stats_buffer_type_rtarget]; float rt_video = mem_usage[D3DPOOL_DEFAULT] / MiB; float rt_managed = mem_usage[D3DPOOL_MANAGED] / MiB; float rt_system = mem_usage[D3DPOOL_SYSTEMMEM] / MiB; Msg("R-Targets \t \t %f \t %f \t %f ", rt_video, rt_managed, rt_system); Msg("\nTotal \t \t %f \t %f \t %f ", vb_video + ib_video + rt_video, textures_managed + vb_managed + ib_managed + rt_managed, vb_system + ib_system + rt_system); #endif // !USE_OGL } }; class CCC_DumpResources final : public IConsole_Command { public: CCC_DumpResources(pcstr name) : IConsole_Command(name) { bEmptyArgsHandled = true; } void Execute(pcstr /*args*/) override { RImplementation.Models->dump(); RImplementation.Resources->Dump(false); } }; class CCC_MotionsStat final : public IConsole_Command { public: CCC_MotionsStat(pcstr name) : IConsole_Command(name) { bEmptyArgsHandled = true; } void Execute(pcstr /*args*/) override { g_pMotionsContainer->dump(); } }; class CCC_TexturesStat final : public IConsole_Command { public: CCC_TexturesStat(pcstr name) : IConsole_Command(name) { bEmptyArgsHandled = true; } void Execute(pcstr /*args*/) override { RImplementation.Resources->_DumpMemoryUsage(); } }; #if RENDER != R_R1 #include "r__pixel_calculator.h" class CCC_BuildSSA : public IConsole_Command { public: CCC_BuildSSA(LPCSTR N) : IConsole_Command(N) { bEmptyArgsHandled = TRUE; }; virtual void Execute(LPCSTR /*args*/) { r_pixel_calculator c; c.run(); } }; #endif class CCC_DofFar : public CCC_Float { public: CCC_DofFar(LPCSTR N, float* V, float _min = 0.0f, float _max = 10000.0f) : CCC_Float(N, V, _min, _max) {} virtual void Execute(LPCSTR args) { float v = float(atof(args)); if (v < ps_r2_dof.y + 0.1f) { char pBuf[256]; _snprintf(pBuf, sizeof(pBuf) / sizeof(pBuf[0]), "float value greater or equal to r2_dof_focus+0.1"); Msg("~ Invalid syntax in call to '%s'", cName); Msg("~ Valid arguments: %s", pBuf); Console->Execute("r2_dof_focus"); } else { CCC_Float::Execute(args); if (g_pGamePersistent) g_pGamePersistent->SetBaseDof(ps_r2_dof); } } // CCC_Dof should save all data as well as load from config virtual void Save(IWriter* /*F*/) { ; } }; class CCC_DofNear : public CCC_Float { public: CCC_DofNear(LPCSTR N, float* V, float _min = 0.0f, float _max = 10000.0f) : CCC_Float(N, V, _min, _max) {} virtual void Execute(LPCSTR args) { float v = float(atof(args)); if (v > ps_r2_dof.y - 0.1f) { char pBuf[256]; _snprintf(pBuf, sizeof(pBuf) / sizeof(pBuf[0]), "float value less or equal to r2_dof_focus-0.1"); Msg("~ Invalid syntax in call to '%s'", cName); Msg("~ Valid arguments: %s", pBuf); Console->Execute("r2_dof_focus"); } else { CCC_Float::Execute(args); if (g_pGamePersistent) g_pGamePersistent->SetBaseDof(ps_r2_dof); } } // CCC_Dof should save all data as well as load from config virtual void Save(IWriter* /*F*/) { ; } }; class CCC_DofFocus : public CCC_Float { public: CCC_DofFocus(LPCSTR N, float* V, float _min = 0.0f, float _max = 10000.0f) : CCC_Float(N, V, _min, _max) {} virtual void Execute(LPCSTR args) { float v = float(atof(args)); if (v > ps_r2_dof.z - 0.1f) { char pBuf[256]; _snprintf(pBuf, sizeof(pBuf) / sizeof(pBuf[0]), "float value less or equal to r2_dof_far-0.1"); Msg("~ Invalid syntax in call to '%s'", cName); Msg("~ Valid arguments: %s", pBuf); Console->Execute("r2_dof_far"); } else if (v < ps_r2_dof.x + 0.1f) { char pBuf[256]; _snprintf(pBuf, sizeof(pBuf) / sizeof(pBuf[0]), "float value greater or equal to r2_dof_far-0.1"); Msg("~ Invalid syntax in call to '%s'", cName); Msg("~ Valid arguments: %s", pBuf); Console->Execute("r2_dof_near"); } else { CCC_Float::Execute(args); if (g_pGamePersistent) g_pGamePersistent->SetBaseDof(ps_r2_dof); } } // CCC_Dof should save all data as well as load from config virtual void Save(IWriter* /*F*/) { ; } }; class CCC_Dof : public CCC_Vector3 { public: CCC_Dof(LPCSTR N, Fvector* V, const Fvector _min, const Fvector _max) : CCC_Vector3(N, V, _min, _max) { ; } virtual void Execute(LPCSTR args) { Fvector v; if (3 != sscanf(args, "%f,%f,%f", &v.x, &v.y, &v.z)) InvalidSyntax(); else if ((v.x > v.y - 0.1f) || (v.z < v.y + 0.1f)) { InvalidSyntax(); Msg("x <= y - 0.1"); Msg("y <= z - 0.1"); } else { CCC_Vector3::Execute(args); if (g_pGamePersistent) g_pGamePersistent->SetBaseDof(ps_r2_dof); } } virtual void GetStatus(TStatus& S) { xr_sprintf(S, "%f,%f,%f", value->x, value->y, value->z); } virtual void Info(TInfo& I) { xr_sprintf(I, "vector3 in range [%f,%f,%f]-[%f,%f,%f]", min.x, min.y, min.z, max.x, max.y, max.z); } }; #ifdef DEBUG class CCC_SunshaftsIntensity : public CCC_Float { public: CCC_SunshaftsIntensity(LPCSTR N, float* V, float _min, float _max) : CCC_Float(N, V, _min, _max) {} virtual void Save(IWriter*) { ; } }; #endif // Allow real-time fog config reload #if (RENDER == R_R3) || (RENDER == R_R4) # ifndef MASTER_GOLD # include "Layers/xrRenderDX10/3DFluid/dx103DFluidManager.h" class CCC_Fog_Reload : public IConsole_Command { public: CCC_Fog_Reload(LPCSTR N) : IConsole_Command(N) { bEmptyArgsHandled = TRUE; }; virtual void Execute(LPCSTR /*args*/) { FluidManager.UpdateProfiles(); } }; # endif // MASTER_GOLD #endif // (RENDER == R_R3) || (RENDER == R_R4) //----------------------------------------------------------------------- void xrRender_initconsole() { CMD3(CCC_Preset, "_preset", &ps_Preset, qpreset_token); CMD4(CCC_Integer, "rs_skeleton_update", &psSkeletonUpdate, 2, 128); #ifndef MASTER_GOLD CMD1(CCC_DumpResources, "dump_resources"); CMD1(CCC_MotionsStat, "stat_motions"); CMD1(CCC_TexturesStat, "stat_textures"); #endif CMD4(CCC_Float, "r__dtex_range", &r__dtex_range, 5, 175); // Common CMD1(CCC_Screenshot, "screenshot"); #ifdef DEBUG #if RENDER != R_R1 CMD1(CCC_BuildSSA, "build_ssa"); #endif CMD4(CCC_Integer, "r__lsleep_frames", &ps_r__LightSleepFrames, 4, 30); CMD4(CCC_Float, "r__ssa_glod_start", &ps_r__GLOD_ssa_start, 128, 512); CMD4(CCC_Float, "r__ssa_glod_end", &ps_r__GLOD_ssa_end, 16, 96); CMD4(CCC_Float, "r__wallmark_shift_pp", &ps_r__WallmarkSHIFT, 0.0f, 1.f); CMD4(CCC_Float, "r__wallmark_shift_v", &ps_r__WallmarkSHIFT_V, 0.0f, 1.f); CMD1(CCC_ModelPoolStat, "stat_models"); #endif // DEBUG CMD4(CCC_Float, "r__wallmark_ttl", &ps_r__WallmarkTTL, 1.0f, 10.f * 60.f); CMD4(CCC_Integer, "r__supersample", &ps_r__Supersample, 1, 8); Fvector tw_min, tw_max; CMD4(CCC_Float, "r__geometry_lod", &ps_r__LOD, 0.1f, 2.f); //CMD4(CCC_Float, "r__geometry_lod_pow", &ps_r__LOD_Power, 0, 2); CMD4(CCC_Float, "r__detail_density", &ps_current_detail_density/*&ps_r__Detail_density*/, 0.1f, 0.99f); CMD4(CCC_detail_radius, "r__detail_radius", &ps_r__detail_radius, 49, 300); CMD4(CCC_Float, "r__detail_height", &ps_r__Detail_height, 1, 2); #ifdef DEBUG CMD4(CCC_Float, "r__detail_l_ambient", &ps_r__Detail_l_ambient, .5f, .95f); CMD4(CCC_Float, "r__detail_l_aniso", &ps_r__Detail_l_aniso, .1f, .5f); CMD4(CCC_Float, "r__d_tree_w_amp", &ps_r__Tree_w_amp, .001f, 1.f); CMD4(CCC_Float, "r__d_tree_w_rot", &ps_r__Tree_w_rot, .01f, 100.f); CMD4(CCC_Float, "r__d_tree_w_speed", &ps_r__Tree_w_speed, 1.0f, 10.f); tw_min.set(EPS, EPS, EPS); tw_max.set(2, 2, 2); CMD4(CCC_Vector3, "r__d_tree_wave", &ps_r__Tree_Wave, tw_min, tw_max); #endif // DEBUG CMD3(CCC_Mask, "r__no_ram_textures", &ps_r__common_flags, RFLAG_NO_RAM_TEXTURES); CMD3(CCC_Mask, "r__actor_shadow", &ps_r__common_flags, RFLAG_ACTOR_SHADOW); CMD2(CCC_tf_Aniso, "r__tf_aniso", &ps_r__tf_Anisotropic); // {1..16} CMD2(CCC_tf_MipBias, "r1_tf_mipbias", &ps_r__tf_Mipbias); // {-3 +3} CMD2(CCC_tf_MipBias, "r2_tf_mipbias", &ps_r__tf_Mipbias); // {-3 +3} // R1 CMD4(CCC_Float, "r1_ssa_lod_a", &ps_r1_ssaLOD_A, 16, 96); CMD4(CCC_Float, "r1_ssa_lod_b", &ps_r1_ssaLOD_B, 16, 64); CMD4(CCC_Float, "r1_lmodel_lerp", &ps_r1_lmodel_lerp, 0, 0.333f); CMD3(CCC_Mask, "r1_dlights", &ps_r1_flags, R1FLAG_DLIGHTS); CMD4(CCC_Float, "r1_dlights_clip", &ps_r1_dlights_clip, 10.f, 150.f); CMD4(CCC_Float, "r1_pps_u", &ps_r1_pps_u, -1.f, +1.f); CMD4(CCC_Float, "r1_pps_v", &ps_r1_pps_v, -1.f, +1.f); CMD4(CCC_Integer, "r1_force_geomx", &ps_r1_force_geomx, 0, 1); // R1-specific CMD4(CCC_Integer, "r1_glows_per_frame", &ps_r1_GlowsPerFrame, 2, 32); CMD3(CCC_Mask, "r1_detail_textures", &ps_r2_ls_flags, R1FLAG_DETAIL_TEXTURES); CMD4(CCC_Float, "r1_fog_luminance", &ps_r1_fog_luminance, 0.2f, 5.f); // Software Skinning // 0 - disabled (renderer can override) // 1 - enabled // 2 - forced hardware skinning (renderer can not override) CMD4(CCC_Integer, "r1_software_skinning", &ps_r1_SoftwareSkinning, 0, 2); // R2 CMD4(CCC_Float, "r2_ssa_lod_a", &ps_r2_ssaLOD_A, 16, 96); CMD4(CCC_Float, "r2_ssa_lod_b", &ps_r2_ssaLOD_B, 32, 64); // R2-specific CMD2(CCC_R2GM, "r2em", &ps_r2_gmaterial); CMD3(CCC_Mask, "r2_tonemap", &ps_r2_ls_flags, R2FLAG_TONEMAP); CMD4(CCC_Float, "r2_tonemap_middlegray", &ps_r2_tonemap_middlegray, 0.0f, 2.0f); CMD4(CCC_Float, "r2_tonemap_adaptation", &ps_r2_tonemap_adaptation, 0.01f, 10.0f); CMD4(CCC_Float, "r2_tonemap_lowlum", &ps_r2_tonemap_low_lum, 0.0001f, 1.0f); CMD4(CCC_Float, "r2_tonemap_amount", &ps_r2_tonemap_amount, 0.0000f, 1.0f); CMD4(CCC_Float, "r2_ls_bloom_kernel_scale", &ps_r2_ls_bloom_kernel_scale, 0.5f, 2.f); CMD4(CCC_Float, "r2_ls_bloom_kernel_g", &ps_r2_ls_bloom_kernel_g, 1.f, 7.f); CMD4(CCC_Float, "r2_ls_bloom_kernel_b", &ps_r2_ls_bloom_kernel_b, 0.01f, 1.f); CMD4(CCC_Float, "r2_ls_bloom_threshold", &ps_r2_ls_bloom_threshold, 0.f, 1.f); CMD4(CCC_Float, "r2_ls_bloom_speed", &ps_r2_ls_bloom_speed, 0.f, 100.f); CMD3(CCC_Mask, "r2_ls_bloom_fast", &ps_r2_ls_flags, R2FLAG_FASTBLOOM); CMD4(CCC_Float, "r2_ls_dsm_kernel", &ps_r2_ls_dsm_kernel, .1f, 3.f); CMD4(CCC_Float, "r2_ls_psm_kernel", &ps_r2_ls_psm_kernel, .1f, 3.f); CMD4(CCC_Float, "r2_ls_ssm_kernel", &ps_r2_ls_ssm_kernel, .1f, 3.f); CMD4(CCC_Float, "r2_ls_squality", &ps_r2_ls_squality, .5f, 1.f); CMD3(CCC_Mask, "r2_zfill", &ps_r2_ls_flags, R2FLAG_ZFILL); CMD4(CCC_Float, "r2_zfill_depth", &ps_r2_zfill, .001f, .5f); CMD3(CCC_Mask, "r2_allow_r1_lights", &ps_r2_ls_flags, R2FLAG_R1LIGHTS); //- Mad Max CMD4(CCC_Float, "r2_gloss_factor", &ps_r2_gloss_factor, .0f, 10.f); //- Mad Max #ifdef DEBUG CMD3(CCC_Mask, "r2_use_nvdbt", &ps_r2_ls_flags, R2FLAG_USE_NVDBT); CMD3(CCC_Mask, "r2_mt", &ps_r2_ls_flags, R2FLAG_EXP_MT_CALC); #endif // DEBUG CMD3(CCC_Mask, "r2_sun", &ps_r2_ls_flags, R2FLAG_SUN); CMD3(CCC_Mask, "r2_sun_details", &ps_r2_ls_flags, R2FLAG_SUN_DETAILS); CMD3(CCC_Mask, "r2_sun_focus", &ps_r2_ls_flags, R2FLAG_SUN_FOCUS); //CMD3(CCC_Mask, "r2_sun_static", &ps_r2_ls_flags, R2FLAG_SUN_STATIC); //CMD3(CCC_Mask, "r2_exp_splitscene", &ps_r2_ls_flags, R2FLAG_EXP_SPLIT_SCENE); //CMD3(CCC_Mask, "r2_exp_donttest_uns", &ps_r2_ls_flags, R2FLAG_EXP_DONT_TEST_UNSHADOWED); CMD3(CCC_Mask, "r2_exp_donttest_shad", &ps_r2_ls_flags, R2FLAG_EXP_DONT_TEST_SHADOWED); CMD3(CCC_Mask, "r2_sun_tsm", &ps_r2_ls_flags, R2FLAG_SUN_TSM); CMD4(CCC_Float, "r2_sun_tsm_proj", &ps_r2_sun_tsm_projection, .001f, 0.8f); CMD4(CCC_Float, "r2_sun_tsm_bias", &ps_r2_sun_tsm_bias, -0.5, +0.5); CMD4(CCC_Float, "r2_sun_near", &ps_r2_sun_near, 1.f, 150.f); //AVO: extended from 50.f to 150.f #if RENDER != R_R1 CMD4(CCC_Float, "r2_sun_far", &OLES_SUN_LIMIT_27_01_07, 51.f, 180.f); #endif CMD4(CCC_Float, "r2_sun_near_border", &ps_r2_sun_near_border, .5f, 1.0f); CMD4(CCC_Float, "r2_sun_depth_far_scale", &ps_r2_sun_depth_far_scale, 0.5, 1.5); CMD4(CCC_Float, "r2_sun_depth_far_bias", &ps_r2_sun_depth_far_bias, -0.5, +0.5); CMD4(CCC_Float, "r2_sun_depth_near_scale", &ps_r2_sun_depth_near_scale, 0.5, 1.5); CMD4(CCC_Float, "r2_sun_depth_near_bias", &ps_r2_sun_depth_near_bias, -0.5, +0.5); CMD4(CCC_Float, "r2_sun_lumscale", &ps_r2_sun_lumscale, -1.0, +3.0); CMD4(CCC_Float, "r2_sun_lumscale_hemi", &ps_r2_sun_lumscale_hemi, 0.0, +3.0); CMD4(CCC_Float, "r2_sun_lumscale_amb", &ps_r2_sun_lumscale_amb, 0.0, +3.0); CMD3(CCC_Mask, "r2_aa", &ps_r2_ls_flags, R2FLAG_AA); CMD4(CCC_Float, "r2_aa_kernel", &ps_r2_aa_kernel, 0.3f, 0.7f); CMD4(CCC_Float, "r2_mblur", &ps_r2_mblur, 0.0f, 1.0f); CMD3(CCC_Mask, "r2_gi", &ps_r2_ls_flags, R2FLAG_GI); CMD4(CCC_Float, "r2_gi_clip", &ps_r2_GI_clip, EPS, 0.1f); CMD4(CCC_Integer, "r2_gi_depth", &ps_r2_GI_depth, 1, 5); CMD4(CCC_Integer, "r2_gi_photons", &ps_r2_GI_photons, 8, 256); CMD4(CCC_Float, "r2_gi_refl", &ps_r2_GI_refl, EPS_L, 0.99f); CMD4(CCC_Integer, "r2_wait_sleep", &ps_r2_wait_sleep, 0, 1); CMD4(CCC_Integer, "r2_wait_timeout", &ps_r2_wait_timeout, 100, 1000); #ifndef MASTER_GOLD CMD4(CCC_Integer, "r2_dhemi_count", &ps_r2_dhemi_count, 4, 25); CMD4(CCC_Float, "r2_dhemi_sky_scale", &ps_r2_dhemi_sky_scale, 0.0f, 100.f); CMD4(CCC_Float, "r2_dhemi_light_scale", &ps_r2_dhemi_light_scale, 0, 100.f); CMD4(CCC_Float, "r2_dhemi_light_flow", &ps_r2_dhemi_light_flow, 0, 1.f); CMD4(CCC_Float, "r2_dhemi_smooth", &ps_r2_lt_smooth, 0.f, 10.f); CMD3(CCC_Mask, "rs_hom_depth_draw", &ps_r2_ls_flags_ext, R_FLAGEXT_HOM_DEPTH_DRAW); CMD3(CCC_Mask, "r2_shadow_cascede_zcul", &ps_r2_ls_flags_ext, R2FLAGEXT_SUN_ZCULLING); CMD3(CCC_Mask, "r2_shadow_cascede_old", &ps_r2_ls_flags_ext, R2FLAGEXT_SUN_OLD); #endif // DEBUG CMD4(CCC_Float, "r2_ls_depth_scale", &ps_r2_ls_depth_scale, 0.5, 1.5); CMD4(CCC_Float, "r2_ls_depth_bias", &ps_r2_ls_depth_bias, -0.5, +0.5); CMD4(CCC_Float, "r2_parallax_h", &ps_r2_df_parallax_h, .0f, .5f); // CMD4(CCC_Float, "r2_parallax_range", &ps_r2_df_parallax_range, 5.0f, 175.0f ); CMD4(CCC_Float, "r2_slight_fade", &ps_r2_slight_fade, .2f, 1.f); CMD3(CCC_Token, "r2_smap_size", &ps_r2_smapsize, qsmapsize_token); tw_min.set(0, 0, 0); tw_max.set(1, 1, 1); CMD4(CCC_Vector3, "r2_aa_break", &ps_r2_aa_barier, tw_min, tw_max); tw_min.set(0, 0, 0); tw_max.set(1, 1, 1); CMD4(CCC_Vector3, "r2_aa_weight", &ps_r2_aa_weight, tw_min, tw_max); // Igor: Depth of field tw_min.set(-10000, -10000, 0); tw_max.set(10000, 10000, 10000); CMD4(CCC_Dof, "r2_dof", &ps_r2_dof, tw_min, tw_max); CMD4(CCC_DofNear, "r2_dof_near", &ps_r2_dof.x, tw_min.x, tw_max.x); CMD4(CCC_DofFocus, "r2_dof_focus", &ps_r2_dof.y, tw_min.y, tw_max.y); CMD4(CCC_DofFar, "r2_dof_far", &ps_r2_dof.z, tw_min.z, tw_max.z); CMD4(CCC_Float, "r2_dof_kernel", &ps_r2_dof_kernel_size, .0f, 10.f); CMD4(CCC_Float, "r2_dof_sky", &ps_r2_dof_sky, -10000.f, 10000.f); CMD3(CCC_Mask, "r2_dof_enable", &ps_r2_ls_flags, R2FLAG_DOF); //float ps_r2_dof_near = 0.f; // 0.f //float ps_r2_dof_focus = 1.4f; // 1.4f #ifdef DEBUG CMD4(CCC_SunshaftsIntensity, "r__sunshafts_intensity", &SunshaftsIntensity, 0.f, 1.f); #endif CMD3(CCC_Mask, "r2_volumetric_lights", &ps_r2_ls_flags, R2FLAG_VOLUMETRIC_LIGHTS); //CMD3(CCC_Mask, "r2_sun_shafts", &ps_r2_ls_flags, R2FLAG_SUN_SHAFTS); CMD3(CCC_Token, "r2_sun_shafts", &ps_r_sun_shafts, qsun_shafts_token); CMD3(CCC_SSAO_Mode, "r2_ssao_mode", &ps_r_ssao_mode, qssao_mode_token); CMD3(CCC_Token, "r2_ssao", &ps_r_ssao, qssao_token); CMD3(CCC_Mask, "r2_ssao_blur", &ps_r2_ls_flags_ext, R2FLAGEXT_SSAO_BLUR); // Need restart CMD3(CCC_Mask, "r2_ssao_opt_data", &ps_r2_ls_flags_ext, R2FLAGEXT_SSAO_OPT_DATA); // Need restart CMD3(CCC_Mask, "r2_ssao_half_data", &ps_r2_ls_flags_ext, R2FLAGEXT_SSAO_HALF_DATA); // Need restart CMD3(CCC_Mask, "r2_ssao_hbao", &ps_r2_ls_flags_ext, R2FLAGEXT_SSAO_HBAO); // Need restart CMD3(CCC_Mask, "r2_ssao_hdao", &ps_r2_ls_flags_ext, R2FLAGEXT_SSAO_HDAO); // Need restart CMD3(CCC_Mask, "r4_enable_tessellation", &ps_r2_ls_flags_ext, R2FLAGEXT_ENABLE_TESSELLATION); // Need restart CMD3(CCC_Mask, "r4_wireframe", &ps_r2_ls_flags_ext, R2FLAGEXT_WIREFRAME); // Need restart CMD3(CCC_Mask, "r2_steep_parallax", &ps_r2_ls_flags, R2FLAG_STEEP_PARALLAX); CMD3(CCC_Mask, "r2_detail_bump", &ps_r2_ls_flags, R2FLAG_DETAIL_BUMP); CMD3(CCC_Token, "r2_sun_quality", &ps_r_sun_quality, qsun_quality_token); //Igor: need restart CMD3(CCC_Mask, "r2_soft_water", &ps_r2_ls_flags, R2FLAG_SOFT_WATER); CMD3(CCC_Mask, "r2_soft_particles", &ps_r2_ls_flags, R2FLAG_SOFT_PARTICLES); CMD3(CCC_Token, "r3_water_refl", &ps_r_water_reflection, qwater_reflection_quality_token); CMD3(CCC_Mask, "r3_water_refl_half_depth", &ps_r2_ls_flags_ext, R3FLAGEXT_SSR_HALF_DEPTH); CMD3(CCC_Mask, "r3_water_refl_jitter", &ps_r2_ls_flags_ext, R3FLAGEXT_SSR_JITTER); //CMD3(CCC_Mask, "r3_msaa", &ps_r2_ls_flags, R3FLAG_MSAA); CMD3(CCC_Token, "r3_msaa", &ps_r3_msaa, qmsaa_token); //CMD3(CCC_Mask, "r3_msaa_hybrid", &ps_r2_ls_flags, R3FLAG_MSAA_HYBRID); //CMD3(CCC_Mask, "r3_msaa_opt", &ps_r2_ls_flags, R3FLAG_MSAA_OPT); CMD3(CCC_Mask, "r3_gbuffer_opt", &ps_r2_ls_flags, R3FLAG_GBUFFER_OPT); CMD3(CCC_Mask, "r3_use_dx10_1", &ps_r2_ls_flags, (u32)R3FLAG_USE_DX10_1); //CMD3(CCC_Mask, "r3_msaa_alphatest", &ps_r2_ls_flags, (u32)R3FLAG_MSAA_ALPHATEST); CMD3(CCC_Token, "r3_msaa_alphatest", &ps_r3_msaa_atest, qmsaa__atest_token); CMD3(CCC_Token, "r3_minmax_sm", &ps_r3_minmax_sm, qminmax_sm_token); // Allow real-time fog config reload #if (RENDER == R_R3) || (RENDER == R_R4) # ifndef MASTER_GOLD CMD1(CCC_Fog_Reload, "r3_fog_reload"); # endif #endif // (RENDER == R_R3) || (RENDER == R_R4) CMD3(CCC_Mask, "r3_dynamic_wet_surfaces", &ps_r2_ls_flags, R3FLAG_DYN_WET_SURF); CMD4(CCC_Float, "r3_dynamic_wet_surfaces_near", &ps_r3_dyn_wet_surf_near, 5, 70); CMD4(CCC_Float, "r3_dynamic_wet_surfaces_far", &ps_r3_dyn_wet_surf_far, 20, 100); CMD4(CCC_Integer, "r3_dynamic_wet_surfaces_sm_res", &ps_r3_dyn_wet_surf_sm_res, 64, 2048); CMD3(CCC_Mask, "r3_volumetric_smoke", &ps_r2_ls_flags, R3FLAG_VOLUMETRIC_SMOKE); CMD1(CCC_memory_stats, "render_memory_stats"); //CMD3(CCC_Mask, "r2_sun_ignore_portals", &ps_r2_ls_flags, R2FLAG_SUN_IGNORE_PORTALS); } #endif
36.250511
132
0.657829
19eadf2988201dfb3f53987243833469d5b00a5c
544
cpp
C++
MFC MyDAQ DigitalWriter/MyDAQ.cpp
ermin-muratovic/MFC-MyDAQ-DigitalWriter
26439359ede5e42efc186793d83c9db8d5ac3ae9
[ "MIT" ]
null
null
null
MFC MyDAQ DigitalWriter/MyDAQ.cpp
ermin-muratovic/MFC-MyDAQ-DigitalWriter
26439359ede5e42efc186793d83c9db8d5ac3ae9
[ "MIT" ]
null
null
null
MFC MyDAQ DigitalWriter/MyDAQ.cpp
ermin-muratovic/MFC-MyDAQ-DigitalWriter
26439359ede5e42efc186793d83c9db8d5ac3ae9
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "MyDAQ.h" MyDAQ::MyDAQ() { } MyDAQ::~MyDAQ() { } TaskHandle MyDAQ::createWriteTask(string name) { TaskHandle Task = 0; name += "/port0/line4:7"; const char *c_str1 = name.c_str(); DAQmxCreateTask("", &Task); DAQmxCreateDOChan(Task, c_str1, "", DAQmx_Val_ChanForAllLines); return Task; } void MyDAQ::writeDO(TaskHandle Task, uInt32 input) { int32 written; DAQmxStartTask(Task); DAQmxWriteDigitalU32(Task, 1, 0, 10.0, DAQmx_Val_GroupByChannel, &input, &written, NULL); DAQmxStopTask(Task); }
17.548387
90
0.696691
19eef03109ee5a2f874e7d1472c806102736e9aa
173
cc
C++
src/Encoder/encoders/none.cc
grzegorzmatczak/PostProcessingModules
bc815541453453f58fc40bd9c00bfc03be1fa3b5
[ "MIT" ]
null
null
null
src/Encoder/encoders/none.cc
grzegorzmatczak/PostProcessingModules
bc815541453453f58fc40bd9c00bfc03be1fa3b5
[ "MIT" ]
null
null
null
src/Encoder/encoders/none.cc
grzegorzmatczak/PostProcessingModules
bc815541453453f58fc40bd9c00bfc03be1fa3b5
[ "MIT" ]
null
null
null
#include "none.h" Encoders::None::None() {} void Encoders::None::process(std::vector<_postData> &_data) {} void Encoders::None::endProcess(std::vector<_postData> &_data) {}
34.6
65
0.710983
19efac7200deaecbf0f347811fe5588f81e17813
811
cpp
C++
Advanced-Programming/Lab-Assignment-1/1-a.cpp
hstr2785/CS
d1eaec5413887c8e271f598d41ef6ccd565c5ac8
[ "MIT" ]
null
null
null
Advanced-Programming/Lab-Assignment-1/1-a.cpp
hstr2785/CS
d1eaec5413887c8e271f598d41ef6ccd565c5ac8
[ "MIT" ]
1
2020-09-25T17:04:57.000Z
2020-09-25T17:04:57.000Z
Advanced-Programming/Lab-Assignment-1/1-a.cpp
hstr2785/CS
d1eaec5413887c8e271f598d41ef6ccd565c5ac8
[ "MIT" ]
2
2020-10-01T05:01:38.000Z
2020-10-01T08:11:50.000Z
#include <iostream> using namespace std; // create a class class Room { private: double length; double breadth; double height; public: double calculateArea() { return length * breadth; } double calculateVolume() { return length * breadth * height; } void set_length() { length = 42.5; } void set_breadth() { breadth = 30.8; } void set_height() { height = 19.2; } }; int main() { // create object of Room class Room room1; // assign values to data members room1.set_length(); room1.set_breadth(); room1.set_height(); // calculate and display the area and volume of the room cout << "Area of Room = " << room1.calculateArea() << endl; cout << "Volume of Room = " << room1.calculateVolume() << endl; return 0; }
18.860465
66
0.610358
19f09c1442cbb814783fca9449d00971fcadc05f
5,300
hpp
C++
vendor/libbitcoin/include/bitcoin/bitcoin/chain/header.hpp
X9Developers/xsn-wallet
7b5aaf6de15928c8cf5b86a844e56710c301df1f
[ "MIT" ]
1
2018-08-20T11:15:45.000Z
2018-08-20T11:15:45.000Z
vendor/libbitcoin/include/bitcoin/bitcoin/chain/header.hpp
X9Developers/xsn-wallet
7b5aaf6de15928c8cf5b86a844e56710c301df1f
[ "MIT" ]
null
null
null
vendor/libbitcoin/include/bitcoin/bitcoin/chain/header.hpp
X9Developers/xsn-wallet
7b5aaf6de15928c8cf5b86a844e56710c301df1f
[ "MIT" ]
3
2018-08-30T08:35:43.000Z
2019-03-29T15:36:26.000Z
/** * Copyright (c) 2011-2017 libbitcoin developers (see AUTHORS) * * This file is part of libbitcoin. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef LIBBITCOIN_CHAIN_HEADER_HPP #define LIBBITCOIN_CHAIN_HEADER_HPP #include <cstddef> #include <cstdint> #include <istream> #include <string> #include <memory> #include <vector> #include <bitcoin/bitcoin/chain/chain_state.hpp> #include <bitcoin/bitcoin/define.hpp> #include <bitcoin/bitcoin/error.hpp> #include <bitcoin/bitcoin/math/hash.hpp> #include <bitcoin/bitcoin/utility/data.hpp> #include <bitcoin/bitcoin/utility/reader.hpp> #include <bitcoin/bitcoin/utility/thread.hpp> #include <bitcoin/bitcoin/utility/writer.hpp> namespace libbitcoin { namespace chain { class BC_API header { public: typedef std::vector<header> list; typedef std::shared_ptr<header> ptr; typedef std::shared_ptr<const header> const_ptr; typedef std::vector<ptr> ptr_list; typedef std::vector<const_ptr> const_ptr_list; // THIS IS FOR LIBRARY USE ONLY, DO NOT CREATE A DEPENDENCY ON IT. struct validation { size_t height = 0; uint32_t median_time_past = 0; }; // Constructors. //----------------------------------------------------------------------------- header(); header(header&& other); header(const header& other); header(header&& other, hash_digest&& hash); header(const header& other, const hash_digest& hash); header(uint32_t version, const hash_digest& previous_block_hash, const hash_digest& merkle, uint32_t timestamp, uint32_t bits, uint32_t nonce); header(uint32_t version, hash_digest&& previous_block_hash, hash_digest&& merkle, uint32_t timestamp, uint32_t bits, uint32_t nonce); // Operators. //----------------------------------------------------------------------------- /// This class is move and copy assignable. header& operator=(header&& other); header& operator=(const header& other); bool operator==(const header& other) const; bool operator!=(const header& other) const; // Deserialization. //----------------------------------------------------------------------------- static header factory_from_data(const data_chunk& data, bool wire=true); static header factory_from_data(std::istream& stream, bool wire=true); static header factory_from_data(reader& source, bool wire=true); bool from_data(const data_chunk& data, bool wire=true); bool from_data(std::istream& stream, bool wire=true); bool from_data(reader& source, bool wire=true); bool is_valid() const; // Serialization. //----------------------------------------------------------------------------- data_chunk to_data(bool wire=true) const; void to_data(std::ostream& stream, bool wire=true) const; void to_data(writer& sink, bool wire=true) const; // Properties (size, accessors, cache). //----------------------------------------------------------------------------- static size_t satoshi_fixed_size(); size_t serialized_size(bool wire=true) const; uint32_t version() const; void set_version(uint32_t value); // Deprecated (unsafe). hash_digest& previous_block_hash(); const hash_digest& previous_block_hash() const; void set_previous_block_hash(const hash_digest& value); void set_previous_block_hash(hash_digest&& value); // Deprecated (unsafe). hash_digest& merkle(); const hash_digest& merkle() const; void set_merkle(const hash_digest& value); void set_merkle(hash_digest&& value); uint32_t timestamp() const; void set_timestamp(uint32_t value); uint32_t bits() const; void set_bits(uint32_t value); uint32_t nonce() const; void set_nonce(uint32_t value); hash_digest hash() const; // Validation. //----------------------------------------------------------------------------- bool is_valid_timestamp() const; bool is_valid_proof_of_work(bool retarget=true) const; code check(bool retarget=false) const; code accept(const chain_state& state) const; // THIS IS FOR LIBRARY USE ONLY, DO NOT CREATE A DEPENDENCY ON IT. mutable validation validation; protected: // So that block may call reset from its own. friend class block; void reset(); void invalidate_cache() const; private: mutable upgrade_mutex mutex_; mutable std::shared_ptr<hash_digest> hash_; uint32_t version_; hash_digest previous_block_hash_; hash_digest merkle_; uint32_t timestamp_; uint32_t bits_; uint32_t nonce_; }; } // namespace chain } // namespace libbitcoin #endif
30.813953
83
0.648679
19f16206b89ed62e69a4342207b50b798aeee477
10,511
cpp
C++
src/core/features/esp.cpp
luk1337/gamesneeze
9b85e177d5af9a1bd30a296172c4d80f91966966
[ "MIT" ]
1
2021-02-10T00:33:31.000Z
2021-02-10T00:33:31.000Z
src/core/features/esp.cpp
luk1337/gamesneeze
9b85e177d5af9a1bd30a296172c4d80f91966966
[ "MIT" ]
null
null
null
src/core/features/esp.cpp
luk1337/gamesneeze
9b85e177d5af9a1bd30a296172c4d80f91966966
[ "MIT" ]
null
null
null
#include "features.hpp" #include "../../includes.hpp" #include <sstream> bool worldToScreen( const Vector& origin, Vector& screen ) { float w = Globals::worldToScreenMatrix[3][0] * origin.x + Globals::worldToScreenMatrix[3][1] * origin.y + Globals::worldToScreenMatrix[3][2] * origin.z + Globals::worldToScreenMatrix[3][3]; if ( w < 0.01f ) return false; float inverseW = 1 / w; screen.x = (Globals::screenSizeX/2) + (0.5f * ((Globals::worldToScreenMatrix[0][0] * origin.x + Globals::worldToScreenMatrix[0][1] * origin.y + Globals::worldToScreenMatrix[0][2] * origin.z + Globals::worldToScreenMatrix[0][3]) * inverseW) * Globals::screenSizeX + 0.5f); screen.y = (Globals::screenSizeY/2) - (0.5f * ((Globals::worldToScreenMatrix[1][0] * origin.x + Globals::worldToScreenMatrix[1][1] * origin.y + Globals::worldToScreenMatrix[1][2] * origin.z + Globals::worldToScreenMatrix[1][3]) * inverseW) * Globals::screenSizeY + 0.5f); return true; } static bool getBox(Entity* entity, int& x, int& y, int& x2, int& y2) { Vector vOrigin, min, max; Vector flb, brt, blb, frt, frb, brb, blt, flt; // think of these as Front-Left-Bottom/Front-Left-Top... Etc. vOrigin = entity->origin(); min = entity->collideable().OBBMins() + vOrigin; max = entity->collideable().OBBMaxs() + vOrigin; Vector points[] = { Vector( min.x, min.y, min.z ), Vector( min.x, max.y, min.z ), Vector( max.x, max.y, min.z ), Vector( max.x, min.y, min.z ), Vector( max.x, max.y, max.z ), Vector( min.x, max.y, max.z ), Vector( min.x, min.y, max.z ), Vector( max.x, min.y, max.z ) }; // Get screen positions if ( !worldToScreen( points[3], flb ) || !worldToScreen( points[5], brt ) || !worldToScreen( points[0], blb ) || !worldToScreen( points[4], frt ) || !worldToScreen( points[2], frb ) || !worldToScreen( points[1], brb ) || !worldToScreen( points[6], blt ) || !worldToScreen( points[7], flt ) ) return false; Vector arr[] = { flb, brt, blb, frt, frb, brb, blt, flt }; float left = flb.x; float top = flb.y; float right = flb.x; float bottom = flb.y; for ( int i = 1; i < 8; i++ ) { if (left > arr[i].x) left = arr[i].x; if (bottom < arr[i].y) bottom = arr[i].y; if (right < arr[i].x) right = arr[i].x; if (top > arr[i].y) top = arr[i].y; } x = (int)left; y = (int)top; x2 = (int)right; y2 = (int)bottom; return true; } void outlinedText(ImVec2 pos, ImColor color, char* text) { Globals::drawList->AddText(ImVec2(pos.x-1, pos.y), ImColor(0, 0, 0, 255), text); Globals::drawList->AddText(ImVec2(pos.x+1, pos.y), ImColor(0, 0, 0, 255), text); Globals::drawList->AddText(ImVec2(pos.x, pos.y-1), ImColor(0, 0, 0, 255), text); Globals::drawList->AddText(ImVec2(pos.x, pos.y+1), ImColor(0, 0, 0, 255), text); Globals::drawList->AddText(ImVec2(pos.x, pos.y), color, text); } void drawBox(int x, int y, int x2, int y2, bool drawBox, ImColor color, char* topText, char* rightText, int health = -1, bool dynamicHealthColor = false, ImColor defaultHealthBarColor = ImColor(0, 240, 0, 255)) { if (drawBox) { Globals::drawList->AddRect(ImVec2(x, y), ImVec2(x2, y2), color); Globals::drawList->AddRect(ImVec2(x-1, y-1), ImVec2(x2+1, y2+1), ImColor(0, 0, 0, 255)); Globals::drawList->AddRect(ImVec2(x+1, y+1), ImVec2(x2-1, y2-1), ImColor(0, 0, 0, 255)); } if (health != -1) { //border color Globals::drawList->AddRectFilled(ImVec2(x - 6, y2 - (((float) health / 100.f) * (y2 - y)) - 1), ImVec2(x - 2, y2 + 1), ImColor(0, 0, 0, 255)); //bar color ImColor healthBarColor = defaultHealthBarColor; if (dynamicHealthColor) { ImGui::ColorConvertHSVtoRGB(((float)health-20.f)/255.f, 1.f, 1.f, healthBarColor.Value.x, healthBarColor.Value.y, healthBarColor.Value.z); } Globals::drawList->AddRectFilled(ImVec2(x - 5, y2 - (((float) health / 100.f) * (y2 - y))),ImVec2(x - 3, y2), healthBarColor); } outlinedText(ImVec2(x2+1, y), ImColor(255, 255, 255, 255), rightText); outlinedText(ImVec2(x+((x2-x)/2)-(ImGui::CalcTextSize(topText).x/2), y-(ImGui::CalcTextSize(topText).y)), ImColor(255, 255, 255, 255), topText); } void drawPlayer(Player* p) { if (!p->dormant()) { if (p->health() > 0) { int x, y, x2, y2; if (getBox(p, x, y, x2, y2)) { player_info_t info; Interfaces::engine->GetPlayerInfo(p->index(), &info); if (p->team() != Globals::localPlayer->team()) { if ((Globals::localPlayer->health() == 0 && CONFIGBOOL("Visuals>Enemies>ESP>Only When Dead")) || !CONFIGBOOL("Visuals>Enemies>ESP>Only When Dead")) { std::stringstream rightText; if (CONFIGBOOL("Visuals>Enemies>ESP>Health")) rightText << p->health() << "hp\n"; if (CONFIGBOOL("Visuals>Enemies>ESP>Money")) rightText << "$" << p->money() << "\n"; drawBox(x, y, x2, y2, CONFIGBOOL("Visuals>Enemies>ESP>Box"), CONFIGCOL("Visuals>Enemies>ESP>Box Color"), CONFIGBOOL("Visuals>Enemies>ESP>Name") ? info.name : (char*)"", (char*)rightText.str().c_str(), CONFIGBOOL("Visuals>Enemies>ESP>Health Bar") ? p->health() : -1, CONFIGBOOL("Visuals>Enemies>ESP>Dynamic Color"), CONFIGCOL("Visuals>Enemies>ESP>Health Bar Color")); } } if (p->team() == Globals::localPlayer->team()) { if ((Globals::localPlayer->health() == 0 && CONFIGBOOL("Visuals>Teammates>ESP>Only When Dead")) || !CONFIGBOOL("Visuals>Teammates>ESP>Only When Dead")) { std::stringstream rightText; if (CONFIGBOOL("Visuals>Teammates>ESP>Health")) rightText << p->health() << "hp\n"; if (CONFIGBOOL("Visuals>Teammates>ESP>Money")) rightText << "$" << p->money() << "\n"; drawBox(x, y, x2, y2, CONFIGBOOL("Visuals>Teammates>ESP>Box"), CONFIGCOL("Visuals>Teammates>ESP>Box Color"), CONFIGBOOL("Visuals>Teammates>ESP>Name") ? info.name : (char*)"", (char*)rightText.str().c_str(), CONFIGBOOL("Visuals>Teammates>ESP>Health Bar") ? p->health() : -1, CONFIGBOOL("Visuals>Teammates>ESP>Dynamic Color"), CONFIGCOL("Visuals>Teammates>ESP>Health Bar Color")); } } } } } } void drawGenericEnt(Entity* ent, bool box, ImColor color, const char* label) { int x, y, x2, y2; if (getBox(ent, x, y, x2, y2)) { drawBox(x, y, x2, y2, box, color, (char*)label, (char*)"", -1); } } void Features::ESP::draw() { if (Interfaces::engine->IsInGame()) { int highest = Interfaces::entityList->GetHighestEntityIndex(); for (int i; i < highest; i++) { if (Globals::localPlayer) { if (i != Interfaces::engine->GetLocalPlayer()) { Entity* ent = (Entity*)Interfaces::entityList->GetClientEntity(i); if (ent) { ClientClass* clientClass = ent->clientClass(); /* Player ESP */ if (clientClass->m_ClassID == EClassIds::CCSPlayer) { drawPlayer((Player*)ent); } /* Weapon ESP */ if ((clientClass->m_ClassID != EClassIds::CBaseWeaponWorldModel && strstr(clientClass->m_pNetworkName, "Weapon")) || clientClass->m_ClassID == EClassIds::CDEagle || clientClass->m_ClassID == EClassIds::CC4 || clientClass->m_ClassID == EClassIds::CAK47) { if (((Weapon*)ent)->owner() == -1) { try { drawGenericEnt(ent, CONFIGBOOL("Visuals>World>Items>Weapon Box"), CONFIGCOL("Visuals>World>Items>Weapon Box Color"), CONFIGBOOL("Visuals>World>Items>Weapon Label") ? itemIndexMap.at(((Weapon*)ent)->itemIndex()) : ""); } catch(const std::exception & e) { //Log::log(WARN, "itemDefinitionIndex %d not found!", ((Weapon*)ent)->itemIndex()); } } } /* Planted C4 ESP */ if (clientClass->m_ClassID == EClassIds::CPlantedC4) { char label[32] = ""; snprintf(label, 32, "Planted C4\n%.3f", ((PlantedC4*)ent)->time() - Interfaces::globals->curtime); drawGenericEnt(ent, CONFIGBOOL("Visuals>World>Items>Planted C4 Box"), CONFIGCOL("Visuals>World>Items>Planted C4 Box Color"), CONFIGBOOL("Visuals>World>Items>Planted C4 Label") ? label : ""); } /* Chicken ESP */ if (clientClass->m_ClassID == EClassIds::CChicken) { drawGenericEnt(ent, CONFIGBOOL("Visuals>World>Items>Chicken Box"), CONFIGCOL("Visuals>World>Items>Chicken Box Color"), CONFIGBOOL("Visuals>World>Items>Chicken Label") ? "Chicken" : ""); } /* Fish ESP */ if (clientClass->m_ClassID == EClassIds::CFish) { drawGenericEnt(ent, CONFIGBOOL("Visuals>World>Items>Fish Box"), CONFIGCOL("Visuals>World>Items>Fish Box Color"), CONFIGBOOL("Visuals>World>Items>Fish Label") ? "Fish" : ""); } /* Debug ESP Everything*/ if (CONFIGBOOL("Visuals>World>Items>ESP Quite literally everything")) { char label[128] = ""; snprintf(label, 128, "%d\n%s", clientClass->m_ClassID, clientClass->m_pNetworkName); drawGenericEnt(ent, true, ImColor(255, 255, 255, 255), label); } } } } } } }
50.533654
278
0.528779
19f24e5c295c17a2db3723e94ce1d478e974b8d9
546
cpp
C++
benchmark/BM_init.cpp
priyanshujalan/Matrix
cf67137817eb63a85b9807c8b8e893d7267397aa
[ "MIT" ]
null
null
null
benchmark/BM_init.cpp
priyanshujalan/Matrix
cf67137817eb63a85b9807c8b8e893d7267397aa
[ "MIT" ]
null
null
null
benchmark/BM_init.cpp
priyanshujalan/Matrix
cf67137817eb63a85b9807c8b8e893d7267397aa
[ "MIT" ]
null
null
null
#include <Matrix.hpp> #include <benchmark/benchmark.h> static void BM_init_double(benchmark::State &state) { std::vector<double> row_d(4, 6.786); std::vector<std::vector<double>> vec_d(6, row_d); for (auto _ : state) matrix.init(vec_d); } BENCHMARK(BM_init_double); static void BM_init_string(benchmark::State &state) { std::vector<std::string> row_s(3, "10"); std::vector<std::vector<std::string>> vec_s(5, row_s); for (auto _ : state) matrix.init(vec_s); } BENCHMARK(BM_init_string); BENCHMARK_MAIN();
27.3
58
0.673993
19f40170d4c897b616e1a728cb76fe4ffb49a816
1,025
cpp
C++
src/inputwin.cpp
mastereuclid/cs494project
8131fb23e20a96c50e7d1252af2bc359e1009a52
[ "Apache-2.0" ]
null
null
null
src/inputwin.cpp
mastereuclid/cs494project
8131fb23e20a96c50e7d1252af2bc359e1009a52
[ "Apache-2.0" ]
null
null
null
src/inputwin.cpp
mastereuclid/cs494project
8131fb23e20a96c50e7d1252af2bc359e1009a52
[ "Apache-2.0" ]
null
null
null
#include "inputwin.hpp" #include <iostream> inputwin::inputwin() : nc::window(nc::points_t(getmaxy(stdscr) - 5, 0, getmaxy(stdscr), getmaxx(stdscr)), nc::border_t(false, true, false, false)) {} void inputwin::on_focus() { clear(); echo(); wmove(winptr(), 1, 0); } void inputwin::get_input(std::function<void(std::string)> pass_along) const { for (int input = wgetch(winptr()); input != nc::button_tab; input = wgetch(winptr())) { if (input == nc::button_enter) { clear(); // do something with buffer pass_along(buffer); buffer.clear(); wmove(winptr(), 1, 0); continue; } const char key = static_cast<char>(input); buffer.append(1, key); } buffer.clear(); } void inputwin::clear() const { int max_x = getmaxx(winptr()), max_y = getmaxy(winptr()); for (int y = 1; y < max_y; y++) { for (int x = 0; x < max_x; x++) { wmove(winptr(), y, x); waddch(winptr(), ' '); } } wmove(winptr(), 1, 0); wrefresh(winptr()); }
26.973684
89
0.578537
19f601a94df656254a9839f6c61047cf33f698e1
2,001
cpp
C++
opencv_1/hue.cpp
liangjisheng/computer-vision
b2f05f87334078f4a51775383aac04f2bdedae7c
[ "MIT" ]
null
null
null
opencv_1/hue.cpp
liangjisheng/computer-vision
b2f05f87334078f4a51775383aac04f2bdedae7c
[ "MIT" ]
null
null
null
opencv_1/hue.cpp
liangjisheng/computer-vision
b2f05f87334078f4a51775383aac04f2bdedae7c
[ "MIT" ]
null
null
null
#include <cv.h> #include <highgui.h> int main( int argc, char** argv ) { IplImage* src; if( argc == 2 && (src=cvLoadImage(argv[1], 1))!= 0) { IplImage* h_plane = cvCreateImage( cvGetSize(src), 8, 1 ); IplImage* s_plane = cvCreateImage( cvGetSize(src), 8, 1 ); IplImage* v_plane = cvCreateImage( cvGetSize(src), 8, 1 ); IplImage* planes[] = { h_plane, s_plane }; IplImage* hsv = cvCreateImage( cvGetSize(src), 8, 3 ); int h_bins = 30, s_bins = 32; int hist_size[] = {h_bins, s_bins}; float h_ranges[] = { 0, 180 }; /* hue varies from 0 (~0°red) to 180 (~360°red again) */ float s_ranges[] = { 0, 255 }; /* saturation varies from 0 (black-gray-white) to 255 (pure spectrum color) */ float* ranges[] = { h_ranges, s_ranges }; int scale = 10; IplImage* hist_img = cvCreateImage( cvSize(h_bins*scale,s_bins*scale), 8, 3 ); CvHistogram* hist; float max_value = 0; int h, s; cvCvtColor( src, hsv, CV_BGR2HSV ); cvCvtPixToPlane( hsv, h_plane, s_plane, v_plane, 0 ); hist = cvCreateHist( 2, hist_size, CV_HIST_ARRAY, ranges, 1 ); cvCalcHist( planes, hist, 0, 0 ); cvGetMinMaxHistValue( hist, 0, &max_value, 0, 0 ); cvZero( hist_img ); for( h = 0; h < h_bins; h++ ) { for( s = 0; s < s_bins; s++ ) { float bin_val = cvQueryHistValue_2D( hist, h, s ); int intensity = cvRound(bin_val*255/max_value); cvRectangle( hist_img, cvPoint( h*scale, s*scale ), cvPoint( (h+1)*scale - 1, (s+1)*scale - 1), CV_RGB(intensity,intensity,intensity), CV_FILLED ); } } cvNamedWindow( "Source", 1 ); cvShowImage( "Source", src ); cvNamedWindow( "H-S Histogram", 1 ); cvShowImage( "H-S Histogram", hist_img ); cvWaitKey(0); } }
39.235294
117
0.534733
19f71e32a9786be81906c094a023a4beb7db4852
548
cpp
C++
coffeeDBR/src/cml_oneMin/cml_golden.cpp
CoFFeeMaN11/CoffeeDBR
1c4fb0683263ada1a8a931cc78bb7cbe728e9d4b
[ "Apache-2.0" ]
null
null
null
coffeeDBR/src/cml_oneMin/cml_golden.cpp
CoFFeeMaN11/CoffeeDBR
1c4fb0683263ada1a8a931cc78bb7cbe728e9d4b
[ "Apache-2.0" ]
null
null
null
coffeeDBR/src/cml_oneMin/cml_golden.cpp
CoFFeeMaN11/CoffeeDBR
1c4fb0683263ada1a8a931cc78bb7cbe728e9d4b
[ "Apache-2.0" ]
null
null
null
#include "cml_golden.h" #include <cassert> #define GOLDEN_RADIO 0.6180339887498949L void GoldenSec::Iterate() { assert(func); long double fL, fR; func(xL, params, fL); func(xR, params, fR); if (fL < fR) { b = xR; xR = xL; xL = b - GOLDEN_RADIO * (b - a); } else { a = xL; xL = xR; xR = a + GOLDEN_RADIO * (b - a); } minimum = (a + b) / 2; } bool GoldenSec::InitMethod(long double xStart) { if(!IOneMin::InitMethod(xStart)) return false; xL = b - GOLDEN_RADIO * (b - a); xR = a + GOLDEN_RADIO * (b - a); return true; }
16.606061
46
0.596715
19f7bbfeb28d6d43a6dbb5892cea6fb1a84f2a27
1,352
cpp
C++
qt-view/mainwindow.cpp
Kiteva4/qt-cmake-json-analizer-with-loger
f05e276c9c7f95f2e80e42ceea6182895692c0af
[ "Apache-2.0" ]
null
null
null
qt-view/mainwindow.cpp
Kiteva4/qt-cmake-json-analizer-with-loger
f05e276c9c7f95f2e80e42ceea6182895692c0af
[ "Apache-2.0" ]
null
null
null
qt-view/mainwindow.cpp
Kiteva4/qt-cmake-json-analizer-with-loger
f05e276c9c7f95f2e80e42ceea6182895692c0af
[ "Apache-2.0" ]
null
null
null
#include "mainwindow.h" #include "ui_mainwindow.h" #include <iostream> #include <string> #include <filesystem> #include <QString> #include <QFileDialog> #include <fstream> #include <iostream> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow), file_path() { ui->setupUi(this); } MainWindow::~MainWindow() { delete ui; delete jsonAnalizer; } void MainWindow::on_selectFile_clicked() { file_path = QFileDialog::getOpenFileName(this,"Open a file", "/home/data/data_yak/config"); ui->filePath->setText(file_path); } void MainWindow::on_startAnalyze_clicked() { jsonAnalizer = new JsonAnalizer(file_path.toStdString()); on_enable_errors_stateChanged(ui->enable_errors->checkState()); on_enable_oks_stateChanged(ui->enable_oks->checkState()); jsonAnalizer->startAnalizing(); delete jsonAnalizer; QFile file("analyzer_logs.txt"); file.open(QFile::ReadOnly); QString content = QString::fromUtf8(file.readAll()); ui->plainTextEdit->setPlainText(content); file.close(); } void MainWindow::on_enable_oks_stateChanged(int arg1) { if(jsonAnalizer != nullptr) jsonAnalizer->set_print_ok(arg1); } void MainWindow::on_enable_errors_stateChanged(int arg1) { if(jsonAnalizer != nullptr) jsonAnalizer->set_print_error(arg1); }
21.460317
95
0.715976
19faf5d2f964194152886e599066c6da7721c1e3
7,764
cc
C++
third_party/blink/renderer/core/fileapi/public_url_manager.cc
zipated/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
third_party/blink/renderer/core/fileapi/public_url_manager.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
third_party/blink/renderer/core/fileapi/public_url_manager.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.000Z
/* * Copyright (C) 2012 Motorola Mobility Inc. * Copyright (C) 2013 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: * * 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 AND ITS 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 APPLE OR ITS 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 "third_party/blink/renderer/core/fileapi/public_url_manager.h" #include "third_party/blink/public/mojom/blob/blob_registry.mojom-blink.h" #include "third_party/blink/renderer/core/fileapi/url_registry.h" #include "third_party/blink/renderer/platform/blob/blob_data.h" #include "third_party/blink/renderer/platform/blob/blob_url.h" #include "third_party/blink/renderer/platform/runtime_enabled_features.h" #include "third_party/blink/renderer/platform/weborigin/kurl.h" #include "third_party/blink/renderer/platform/weborigin/security_origin.h" #include "third_party/blink/renderer/platform/weborigin/url_security_origin_map.h" #include "third_party/blink/renderer/platform/wtf/hash_map.h" #include "third_party/blink/renderer/platform/wtf/text/string_hash.h" #include "third_party/blink/renderer/platform/wtf/thread_specific.h" #include "third_party/blink/renderer/platform/wtf/vector.h" namespace blink { namespace { // When a blob URL is created in a unique origin the origin is serialized into // the URL as "null". Since that makes it impossible to parse the origin back // out and compare it against a context's origin (to check if a context is // allowed to dereference the URL) we store a map of blob URL to SecurityOrigin // instance for blob URLs with unique origins. class BlobOriginMap : public URLSecurityOriginMap { public: BlobOriginMap(); SecurityOrigin* GetOrigin(const KURL&) override; }; typedef HashMap<String, scoped_refptr<SecurityOrigin>> BlobURLOriginMap; static ThreadSpecific<BlobURLOriginMap>& OriginMap() { // We want to create the BlobOriginMap exactly once because it is shared by // all the threads. DEFINE_THREAD_SAFE_STATIC_LOCAL(BlobOriginMap, cache, ()); (void)cache; // BlobOriginMap's constructor does the interesting work. DEFINE_THREAD_SAFE_STATIC_LOCAL(ThreadSpecific<BlobURLOriginMap>, map, ()); return map; } static void SaveToOriginMap(SecurityOrigin* origin, const KURL& url) { // If the blob URL contains null origin, as in the context with unique // security origin or file URL, save the mapping between url and origin so // that the origin can be retrieved when doing security origin check. // // See the definition of the origin of a Blob URL in the File API spec. DCHECK(!url.HasFragmentIdentifier()); if (origin && BlobURL::GetOrigin(url) == "null") OriginMap()->insert(url.GetString(), origin); } static void RemoveFromOriginMap(const KURL& url) { if (BlobURL::GetOrigin(url) == "null") OriginMap()->erase(url.GetString()); } BlobOriginMap::BlobOriginMap() { SecurityOrigin::SetMap(this); } SecurityOrigin* BlobOriginMap::GetOrigin(const KURL& url) { if (url.ProtocolIs("blob")) { KURL url_without_fragment = url; url_without_fragment.RemoveFragmentIdentifier(); return OriginMap()->at(url_without_fragment.GetString()); } return nullptr; } } // namespace PublicURLManager* PublicURLManager::Create(ExecutionContext* context) { return new PublicURLManager(context); } PublicURLManager::PublicURLManager(ExecutionContext* context) : ContextLifecycleObserver(context), is_stopped_(false) {} String PublicURLManager::RegisterURL(URLRegistrable* registrable) { if (is_stopped_) return String(); SecurityOrigin* origin = GetExecutionContext()->GetMutableSecurityOrigin(); const KURL& url = BlobURL::CreatePublicURL(origin); DCHECK(!url.IsEmpty()); const String& url_string = url.GetString(); mojom::blink::BlobPtr blob; if (RuntimeEnabledFeatures::MojoBlobURLsEnabled()) blob = registrable->AsMojoBlob(); if (blob) { if (!url_store_) { BlobDataHandle::GetBlobRegistry()->URLStoreForOrigin( origin, MakeRequest(&url_store_)); } url_store_->Register(std::move(blob), url); mojo_urls_.insert(url_string); } else { URLRegistry* registry = &registrable->Registry(); registry->RegisterURL(origin, url, registrable); url_to_registry_.insert(url_string, registry); } SaveToOriginMap(origin, url); return url_string; } void PublicURLManager::Revoke(const KURL& url) { if (is_stopped_) return; // Don't bother trying to revoke URLs that can't have been registered anyway. if (!url.ProtocolIs("blob") || url.HasFragmentIdentifier()) return; // Don't support revoking cross-origin blob URLs. if (!SecurityOrigin::Create(url)->IsSameSchemeHostPort( GetExecutionContext()->GetSecurityOrigin())) return; if (RuntimeEnabledFeatures::MojoBlobURLsEnabled()) { if (!url_store_) { BlobDataHandle::GetBlobRegistry()->URLStoreForOrigin( GetExecutionContext()->GetSecurityOrigin(), MakeRequest(&url_store_)); } url_store_->Revoke(url); mojo_urls_.erase(url.GetString()); } RemoveFromOriginMap(url); auto it = url_to_registry_.find(url.GetString()); if (it == url_to_registry_.end()) return; it->value->UnregisterURL(url); url_to_registry_.erase(it); } void PublicURLManager::Resolve( const KURL& url, network::mojom::blink::URLLoaderFactoryRequest factory_request) { DCHECK(RuntimeEnabledFeatures::MojoBlobURLsEnabled()); DCHECK(url.ProtocolIs("blob")); if (!url_store_) { BlobDataHandle::GetBlobRegistry()->URLStoreForOrigin( GetExecutionContext()->GetSecurityOrigin(), MakeRequest(&url_store_)); } url_store_->ResolveAsURLLoaderFactory(url, std::move(factory_request)); } void PublicURLManager::Resolve( const KURL& url, mojom::blink::BlobURLTokenRequest token_request) { DCHECK(RuntimeEnabledFeatures::MojoBlobURLsEnabled()); DCHECK(url.ProtocolIs("blob")); if (!url_store_) { BlobDataHandle::GetBlobRegistry()->URLStoreForOrigin( GetExecutionContext()->GetSecurityOrigin(), MakeRequest(&url_store_)); } url_store_->ResolveForNavigation(url, std::move(token_request)); } void PublicURLManager::ContextDestroyed(ExecutionContext*) { if (is_stopped_) return; is_stopped_ = true; for (auto& url_registry : url_to_registry_) { url_registry.value->UnregisterURL(KURL(url_registry.key)); RemoveFromOriginMap(KURL(url_registry.key)); } for (const auto& url : mojo_urls_) RemoveFromOriginMap(KURL(url)); url_to_registry_.clear(); mojo_urls_.clear(); url_store_.reset(); } void PublicURLManager::Trace(blink::Visitor* visitor) { ContextLifecycleObserver::Trace(visitor); } } // namespace blink
36.971429
82
0.748841
19fb6c685d7ac8c20c312ac9b8f969207a4dc116
1,737
hpp
C++
src/svg/svg_parser.hpp
malasiot/xg
02bdcc208f479afb448767e4d2f2764e913e5d43
[ "MIT" ]
1
2019-09-06T01:48:15.000Z
2019-09-06T01:48:15.000Z
src/svg/svg_parser.hpp
malasiot/xg
02bdcc208f479afb448767e4d2f2764e913e5d43
[ "MIT" ]
null
null
null
src/svg/svg_parser.hpp
malasiot/xg
02bdcc208f479afb448767e4d2f2764e913e5d43
[ "MIT" ]
null
null
null
#ifndef __XG_SVG_PARSER_HPP__ #define __XG_SVG_PARSER_HPP__ #include <string> #include <xg/util/dictionary.hpp> #include <iostream> #include "svg_dom.hpp" namespace xg { class SVGLoadException ; class SVGDocument ; class SVGParser { public: SVGParser(SVGDocument &doc): document_(doc) {} void parseString(const std::string &xml) ; void parseStream(std::istream &strm, size_t buffer_sz = 1024) ; protected: template <typename T> std::shared_ptr<T> createNode(const Dictionary &a, bool is_root = false) { auto node = std::make_shared<T>() ; if ( is_root ) root_ = dynamic_cast<svg::SVGElement *>(node.get()) ; node->setDocument(&document_) ; auto ele = std::dynamic_pointer_cast<svg::Element>(node) ; if ( !nodes_.empty() ) { auto stack_node = nodes_.back() ; stack_node->addChild(ele) ; } nodes_.push_back(ele) ; node->parseAttributes(a) ; return node ; } void beginElement(const std::string &name, const Dictionary &attributes) ; void endElement() ; void characters(const std::string &name) ; private: static void start_element_handler(void *data, const char *element_name, const char **attributes) ; static void end_element_handler(void *data, const char *elelemnt_name); static void character_data_handler(void *data, const char *character_data, int length); void handleCharacterData() ; std::string processWhiteSpace(const std::string &); private: std::string text_ ; SVGDocument &document_ ; std::deque<std::shared_ptr<svg::Element>> nodes_ ; std::deque<std::string> elements_ ; svg::SVGElement *root_ = nullptr; }; } #endif
23.794521
102
0.663212
19fe25e1a06c3a0e321ce78d8fc2e4e2c5a1ba3f
514
cpp
C++
Tree/Convert BT to Doubly Linked List.cpp
Benson1198/CPP
b12494becadc9431303cfdb51c5134dc68c679c3
[ "MIT" ]
null
null
null
Tree/Convert BT to Doubly Linked List.cpp
Benson1198/CPP
b12494becadc9431303cfdb51c5134dc68c679c3
[ "MIT" ]
null
null
null
Tree/Convert BT to Doubly Linked List.cpp
Benson1198/CPP
b12494becadc9431303cfdb51c5134dc68c679c3
[ "MIT" ]
1
2020-10-06T09:17:33.000Z
2020-10-06T09:17:33.000Z
#include<bits/stdc++.h> using namespace std; struct Node{ int data; Node *left; Node *right; Node(int k){ data = k; left = NULL; right = NULL; } } Node *prev = NULL; Node *BTToDLL(Node *root){ if(root == NULL){ return root; } Node* head = BTToDLL(root->left); if(prev == NULL){ head = root; } else{ root->left = prev; prev->right = root; } prev = root; BTToDLL(root->right); return head; }
13.526316
37
0.490272
19fe8fe5fae8bf2351fae313f8ece406d47d9340
7,638
cpp
C++
indra/newview/llvowater.cpp
humbletim/archived-casviewer
3b51b1baae7e7cebf1c7dca62d9c02751709ee57
[ "Unlicense" ]
null
null
null
indra/newview/llvowater.cpp
humbletim/archived-casviewer
3b51b1baae7e7cebf1c7dca62d9c02751709ee57
[ "Unlicense" ]
null
null
null
indra/newview/llvowater.cpp
humbletim/archived-casviewer
3b51b1baae7e7cebf1c7dca62d9c02751709ee57
[ "Unlicense" ]
null
null
null
/** * @file llvowater.cpp * @brief LLVOWater class implementation * * $LicenseInfo:firstyear=2005&license=viewerlgpl$ * Second Life Viewer Source Code * Copyright (C) 2010, Linden Research, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; * version 2.1 of the License only. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA * $/LicenseInfo$ */ #include "llviewerprecompiledheaders.h" #include "llvowater.h" #include "llviewercontrol.h" #include "lldrawable.h" #include "lldrawpoolwater.h" #include "llface.h" #include "llsky.h" #include "llsurface.h" #include "llvosky.h" #include "llviewercamera.h" #include "llviewertexturelist.h" #include "llviewerregion.h" #include "llworld.h" #include "pipeline.h" #include "llspatialpartition.h" const BOOL gUseRoam = FALSE; /////////////////////////////////// template<class T> inline T LERP(T a, T b, F32 factor) { return a + (b - a) * factor; } const U32 N_RES_HALF = (N_RES >> 1); const U32 WIDTH = (N_RES * WAVE_STEP); //128.f //64 // width of wave tile, in meters const F32 WAVE_STEP_INV = (1. / WAVE_STEP); LLVOWater::LLVOWater(const LLUUID &id, const LLPCode pcode, LLViewerRegion *regionp) : LLStaticViewerObject(id, pcode, regionp), mRenderType(LLPipeline::RENDER_TYPE_WATER) { // Terrain must draw during selection passes so it can block objects behind it. mbCanSelect = FALSE; // <FS:CR> Aurora Sim //setScale(LLVector3(256.f, 256.f, 0.f)); // Hack for setting scale for bounding boxes/visibility. setScale(LLVector3(mRegionp->getWidth(), mRegionp->getWidth(), 0.f)); // </FS:CR> Aurora Sim mUseTexture = TRUE; mIsEdgePatch = FALSE; } void LLVOWater::markDead() { LLViewerObject::markDead(); } BOOL LLVOWater::isActive() const { return FALSE; } void LLVOWater::setPixelAreaAndAngle(LLAgent &agent) { mAppAngle = 50; mPixelArea = 500*500; } // virtual void LLVOWater::updateTextures() { } // Never gets called void LLVOWater::idleUpdate(LLAgent &agent, const F64 &time) { } LLDrawable *LLVOWater::createDrawable(LLPipeline *pipeline) { pipeline->allocDrawable(this); mDrawable->setLit(FALSE); mDrawable->setRenderType(mRenderType); LLDrawPoolWater *pool = (LLDrawPoolWater*) gPipeline.getPool(LLDrawPool::POOL_WATER); if (mUseTexture) { mDrawable->setNumFaces(1, pool, mRegionp->getLand().getWaterTexture()); } else { mDrawable->setNumFaces(1, pool, LLWorld::getInstance()->getDefaultWaterTexture()); } return mDrawable; } static LLTrace::BlockTimerStatHandle FTM_UPDATE_WATER("Update Water"); BOOL LLVOWater::updateGeometry(LLDrawable *drawable) { LL_RECORD_BLOCK_TIME(FTM_UPDATE_WATER); LLFace *face; if (drawable->getNumFaces() < 1) { LLDrawPoolWater *poolp = (LLDrawPoolWater*) gPipeline.getPool(LLDrawPool::POOL_WATER); drawable->addFace(poolp, NULL); } face = drawable->getFace(0); if (!face) { return TRUE; } // LLVector2 uvs[4]; // LLVector3 vtx[4]; LLStrider<LLVector3> verticesp, normalsp; LLStrider<LLVector2> texCoordsp; LLStrider<U16> indicesp; U16 index_offset; // A quad is 4 vertices and 6 indices (making 2 triangles) static const unsigned int vertices_per_quad = 4; static const unsigned int indices_per_quad = 6; const S32 size = gSavedSettings.getBOOL("RenderTransparentWater") && LLGLSLShader::sNoFixedFunction ? 16 : 1; const S32 num_quads = size * size; face->setSize(vertices_per_quad * num_quads, indices_per_quad * num_quads); LLVertexBuffer* buff = face->getVertexBuffer(); if (!buff || !buff->isWriteable()) { buff = new LLVertexBuffer(LLDrawPoolWater::VERTEX_DATA_MASK, GL_DYNAMIC_DRAW_ARB); buff->allocateBuffer(face->getGeomCount(), face->getIndicesCount(), TRUE); face->setIndicesIndex(0); face->setGeomIndex(0); face->setVertexBuffer(buff); } else { buff->resizeBuffer(face->getGeomCount(), face->getIndicesCount()); } index_offset = face->getGeometry(verticesp,normalsp,texCoordsp, indicesp); LLVector3 position_agent; position_agent = getPositionAgent(); face->mCenterAgent = position_agent; face->mCenterLocal = position_agent; S32 x, y; F32 step_x = getScale().mV[0] / size; F32 step_y = getScale().mV[1] / size; const LLVector3 up(0.f, step_y * 0.5f, 0.f); const LLVector3 right(step_x * 0.5f, 0.f, 0.f); const LLVector3 normal(0.f, 0.f, 1.f); F32 size_inv = 1.f / size; F32 z_fudge = 0.f; if (getIsEdgePatch()) { //bump edge patches down 10 cm to prevent aliasing along edges z_fudge = -0.1f; } for (y = 0; y < size; y++) { for (x = 0; x < size; x++) { S32 toffset = index_offset + 4*(y*size + x); position_agent = getPositionAgent() - getScale() * 0.5f; position_agent.mV[VX] += (x + 0.5f) * step_x; position_agent.mV[VY] += (y + 0.5f) * step_y; position_agent.mV[VZ] += z_fudge; *verticesp++ = position_agent - right + up; *verticesp++ = position_agent - right - up; *verticesp++ = position_agent + right + up; *verticesp++ = position_agent + right - up; *texCoordsp++ = LLVector2(x*size_inv, (y+1)*size_inv); *texCoordsp++ = LLVector2(x*size_inv, y*size_inv); *texCoordsp++ = LLVector2((x+1)*size_inv, (y+1)*size_inv); *texCoordsp++ = LLVector2((x+1)*size_inv, y*size_inv); *normalsp++ = normal; *normalsp++ = normal; *normalsp++ = normal; *normalsp++ = normal; *indicesp++ = toffset + 0; *indicesp++ = toffset + 1; *indicesp++ = toffset + 2; *indicesp++ = toffset + 1; *indicesp++ = toffset + 3; *indicesp++ = toffset + 2; } } buff->flush(); mDrawable->movePartition(); LLPipeline::sCompiles++; return TRUE; } void LLVOWater::initClass() { } void LLVOWater::cleanupClass() { } void setVecZ(LLVector3& v) { v.mV[VX] = 0; v.mV[VY] = 0; v.mV[VZ] = 1; } void LLVOWater::setUseTexture(const BOOL use_texture) { mUseTexture = use_texture; } void LLVOWater::setIsEdgePatch(const BOOL edge_patch) { mIsEdgePatch = edge_patch; } void LLVOWater::updateSpatialExtents(LLVector4a &newMin, LLVector4a& newMax) { LLVector4a pos; pos.load3(getPositionAgent().mV); LLVector4a scale; scale.load3(getScale().mV); scale.mul(0.5f); newMin.setSub(pos, scale); newMax.setAdd(pos, scale); pos.setAdd(newMin,newMax); pos.mul(0.5f); mDrawable->setPositionGroup(pos); } U32 LLVOWater::getPartitionType() const { if (mIsEdgePatch) { return LLViewerRegion::PARTITION_VOIDWATER; } return LLViewerRegion::PARTITION_WATER; } U32 LLVOVoidWater::getPartitionType() const { return LLViewerRegion::PARTITION_VOIDWATER; } LLWaterPartition::LLWaterPartition(LLViewerRegion* regionp) : LLSpatialPartition(0, FALSE, GL_DYNAMIC_DRAW_ARB, regionp) { mInfiniteFarClip = TRUE; mDrawableType = LLPipeline::RENDER_TYPE_WATER; mPartitionType = LLViewerRegion::PARTITION_WATER; } LLVoidWaterPartition::LLVoidWaterPartition(LLViewerRegion* regionp) : LLWaterPartition(regionp) { mOcclusionEnabled = FALSE; mDrawableType = LLPipeline::RENDER_TYPE_VOIDWATER; mPartitionType = LLViewerRegion::PARTITION_VOIDWATER; }
24.094637
110
0.707384
c20073cf03e1fac2b7f5c24b5c4e22352b84dc79
4,986
cpp
C++
code_reading/oceanbase-master/src/storage/blocksstable/ob_storage_cache_suite.cpp
wangcy6/weekly_read
3a8837ee9cd957787ee1785e4066dd623e02e13a
[ "Apache-2.0" ]
null
null
null
code_reading/oceanbase-master/src/storage/blocksstable/ob_storage_cache_suite.cpp
wangcy6/weekly_read
3a8837ee9cd957787ee1785e4066dd623e02e13a
[ "Apache-2.0" ]
null
null
null
code_reading/oceanbase-master/src/storage/blocksstable/ob_storage_cache_suite.cpp
wangcy6/weekly_read
3a8837ee9cd957787ee1785e4066dd623e02e13a
[ "Apache-2.0" ]
1
2020-10-18T12:59:31.000Z
2020-10-18T12:59:31.000Z
/** * Copyright (c) 2021 OceanBase * OceanBase CE is licensed under Mulan PubL v2. * You can use this software according to the terms and conditions of the Mulan PubL v2. * You may obtain a copy of Mulan PubL v2 at: * http://license.coscl.org.cn/MulanPubL-2.0 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PubL v2 for more details. */ #include "ob_storage_cache_suite.h" using namespace oceanbase::common; namespace oceanbase { namespace blocksstable { ObStorageCacheSuite::ObStorageCacheSuite() : block_index_cache_(), user_block_cache_(), user_row_cache_(), bf_cache_(), fuse_row_cache_(), is_inited_(false) {} ObStorageCacheSuite::~ObStorageCacheSuite() { destroy(); } ObStorageCacheSuite& ObStorageCacheSuite::get_instance() { static ObStorageCacheSuite instance_; return instance_; } int ObStorageCacheSuite::init(const int64_t index_cache_priority, const int64_t user_block_cache_priority, const int64_t user_row_cache_priority, const int64_t fuse_row_cache_priority, const int64_t bf_cache_priority, const int64_t bf_cache_miss_count_threshold) { int ret = OB_SUCCESS; if (OB_UNLIKELY(is_inited_)) { ret = OB_INIT_TWICE; STORAGE_LOG(WARN, "The cache suite has been inited, ", K(ret)); } else if (OB_FAIL(block_index_cache_.init("block_index_cache", index_cache_priority))) { STORAGE_LOG(ERROR, "init block index cache failed, ", K(ret)); } else if (OB_FAIL(user_block_cache_.init("user_block_cache", user_block_cache_priority))) { STORAGE_LOG(ERROR, "init user block cache failed, ", K(ret)); } else if (OB_FAIL(user_row_cache_.init("user_row_cache", user_row_cache_priority))) { STORAGE_LOG(ERROR, "init user sstable row cache failed, ", K(ret)); } else if (OB_FAIL(bf_cache_.init("bf_cache", bf_cache_priority))) { STORAGE_LOG(ERROR, "init bloom filter cache failed, ", K(ret)); } else if (OB_FAIL(bf_cache_.set_bf_cache_miss_count_threshold(bf_cache_miss_count_threshold))) { STORAGE_LOG(ERROR, "failed to set bf_cache_miss_count_threshold", K(ret)); } else if (OB_FAIL(fuse_row_cache_.init("fuse_row_cache", fuse_row_cache_priority))) { STORAGE_LOG(ERROR, "fail to init fuse row cache", K(ret)); } else { is_inited_ = true; } if (OB_UNLIKELY(OB_SUCCESS != ret && !is_inited_)) { destroy(); } return ret; } int ObStorageCacheSuite::reset_priority(const int64_t index_cache_priority, const int64_t user_block_cache_priority, const int64_t user_row_cache_priority, const int64_t fuse_row_cache_priority, const int64_t bf_cache_priority) { int ret = OB_SUCCESS; if (OB_UNLIKELY(!is_inited_)) { ret = OB_NOT_INIT; STORAGE_LOG(WARN, "The cache suite has not been inited, ", K(ret)); } else if (OB_FAIL(block_index_cache_.set_priority(index_cache_priority))) { STORAGE_LOG(ERROR, "set priority for block index cache failed, ", K(ret)); } else if (OB_FAIL(user_block_cache_.set_priority(user_block_cache_priority))) { STORAGE_LOG(ERROR, "set priority for user block cache failed, ", K(ret)); } else if (OB_FAIL(user_row_cache_.set_priority(user_row_cache_priority))) { STORAGE_LOG(ERROR, "set priority for user sstable row cache failed, ", K(ret)); } else if (OB_FAIL(bf_cache_.set_priority(bf_cache_priority))) { STORAGE_LOG(ERROR, "set priority for bloom filter cache failed, ", K(ret)); } else if (OB_FAIL(fuse_row_cache_.set_priority(fuse_row_cache_priority))) { STORAGE_LOG(ERROR, "fail to set priority for fuse row cache", K(ret)); } return ret; } int ObStorageCacheSuite::set_bf_cache_miss_count_threshold(const int64_t bf_cache_miss_count_threshold) { int ret = OB_SUCCESS; if (OB_FAIL(bf_cache_.set_bf_cache_miss_count_threshold(bf_cache_miss_count_threshold))) { STORAGE_LOG(WARN, "failed to set bf_cache_miss_count_threshold", K(ret), K(bf_cache_miss_count_threshold)); } return ret; } void ObStorageCacheSuite::destroy() { block_index_cache_.destroy(); user_block_cache_.destroy(); user_row_cache_.destroy(); bf_cache_.destroy(); fuse_row_cache_.destroy(); is_inited_ = false; } void ObStorageCacheContext::set(ObBlockCacheWorkingSet& block_cache_ws) { block_index_cache_ = &(OB_STORE_CACHE.block_index_cache_); block_cache_ = &(OB_STORE_CACHE.user_block_cache_); block_cache_ws_ = &block_cache_ws; bf_cache_ = &(OB_STORE_CACHE.bf_cache_); row_cache_ = &(OB_STORE_CACHE.user_row_cache_); } bool ObStorageCacheContext::is_valid() const { return NULL != block_index_cache_ && NULL != block_cache_ && NULL != block_cache_ws_ && NULL != row_cache_ && NULL != bf_cache_; } void ObStorageCacheContext::reset() { block_index_cache_ = NULL; block_cache_ = NULL; block_cache_ws_ = NULL; row_cache_ = NULL; bf_cache_ = NULL; } } // namespace blocksstable } // namespace oceanbase
38.651163
117
0.751304
c201ef5788f72bf70434e8fa03e8b42033133303
1,104
cpp
C++
WickedEngine/wiLoadingScreen.cpp
rohankumardubey/WickedEngine
2e94230c520f0921718ea531c1de9c76611c8944
[ "MIT" ]
11
2021-12-27T11:31:24.000Z
2021-12-30T08:02:57.000Z
WickedEngine/wiLoadingScreen.cpp
rohankumardubey/WickedEngine
2e94230c520f0921718ea531c1de9c76611c8944
[ "MIT" ]
null
null
null
WickedEngine/wiLoadingScreen.cpp
rohankumardubey/WickedEngine
2e94230c520f0921718ea531c1de9c76611c8944
[ "MIT" ]
3
2021-12-28T02:31:08.000Z
2021-12-31T07:32:00.000Z
#include "wiLoadingScreen.h" #include "wiApplication.h" #include <thread> namespace wi { bool LoadingScreen::isActive() { return wi::jobsystem::IsBusy(ctx); } void LoadingScreen::addLoadingFunction(std::function<void(wi::jobsystem::JobArgs)> loadingFunction) { if (loadingFunction != nullptr) { tasks.push_back(loadingFunction); } } void LoadingScreen::addLoadingComponent(RenderPath* component, Application* main, float fadeSeconds, wi::Color fadeColor) { addLoadingFunction([=](wi::jobsystem::JobArgs args) { component->Load(); }); onFinished([=] { main->ActivatePath(component, fadeSeconds, fadeColor); }); } void LoadingScreen::onFinished(std::function<void()> finishFunction) { if (finishFunction != nullptr) finish = finishFunction; } void LoadingScreen::Start() { for (auto& x : tasks) { wi::jobsystem::Execute(ctx, x); } std::thread([this]() { wi::jobsystem::Wait(ctx); finish(); }).detach(); RenderPath2D::Start(); } void LoadingScreen::Stop() { tasks.clear(); finish = nullptr; RenderPath2D::Stop(); } }
18.098361
122
0.671196
c202af40ed7454f6c723d5124d070870fc6b40e0
264
cpp
C++
src/main/algorithms/cpp/graph/clone_graph_133/graph_node.cpp
algorithmlover2016/leet_code
2eecc7971194c8a755e67719d8f66c636694e7e9
[ "Apache-2.0" ]
null
null
null
src/main/algorithms/cpp/graph/clone_graph_133/graph_node.cpp
algorithmlover2016/leet_code
2eecc7971194c8a755e67719d8f66c636694e7e9
[ "Apache-2.0" ]
null
null
null
src/main/algorithms/cpp/graph/clone_graph_133/graph_node.cpp
algorithmlover2016/leet_code
2eecc7971194c8a755e67719d8f66c636694e7e9
[ "Apache-2.0" ]
null
null
null
#include "./graph_node.h" Node::Node() : val(0), neighbors(std::vector<Node*>()) { } Node::Node(int _val) : val(_val), neighbors(std::vector<Node*>()) { } Node::Node(int _val, std::vector<Node*> const & _neighbors): val(_val), neighbors(_neighbors) { }
17.6
71
0.625
c204cf8e0458653fecc337527805f7fe2de01019
17,967
cpp
C++
src/globals/graph_types.cpp
zakimjz/GPU_graph_mining
22ba73bea97533ed6b2af613bd263ef4d869e71a
[ "Apache-2.0" ]
2
2020-05-13T09:09:50.000Z
2021-07-16T12:51:53.000Z
src/globals/graph_types.cpp
zakimjz/GPU_graph_mining
22ba73bea97533ed6b2af613bd263ef4d869e71a
[ "Apache-2.0" ]
null
null
null
src/globals/graph_types.cpp
zakimjz/GPU_graph_mining
22ba73bea97533ed6b2af613bd263ef4d869e71a
[ "Apache-2.0" ]
1
2022-03-22T01:15:33.000Z
2022-03-22T01:15:33.000Z
#include <graph_types.hpp> #include <algorithm> #include <cassert> #include <string> #include <sstream> #include <iostream> #include <iterator> #include <stdexcept> #include <logger.hpp> #include <utils.hpp> #include <cstring> namespace types { template <class T, class Iterator> void tokenize(const char *str, Iterator iterator) { std::istringstream is(std::string(str)); std::copy(std::istream_iterator <T> (is), std::istream_iterator <T> (), iterator); } Graph::Graph() : edge_size_(0), directed(false) { } Graph::Graph(bool _directed) { directed = _directed; } void Graph::buildEdge() { char buf[512]; std::map <std::string, unsigned int> tmp; unsigned int id = 0; for(int from = 0; from < (int)size(); ++from) { for(Vertex::edge_iterator it = (*this)[from].edge.begin(); it != (*this)[from].edge.end(); ++it) { if(directed || from <= it->to) std::sprintf(buf, "%d %d %d", from, it->to, it->elabel); else std::sprintf(buf, "%d %d %d", it->to, from, it->elabel); // Assign unique id's for the edges. if(tmp.find(buf) == tmp.end()) { it->id = id; tmp[buf] = id; ++id; } else { it->id = tmp[buf]; } } } edge_size_ = id; } std::istream &Graph::read(std::istream &is) { char line[1024]; std::vector<std::string> result; clear(); while(true) { unsigned int pos = is.tellg(); if(!is.getline(line, 1024)) { break; } result.clear(); utils::split(line, result); if(result.empty()) { // do nothing } else if(result[0] == "t") { if(!empty()) { // use as delimiter is.seekg(pos, std::ios_base::beg); break; } else { // y = atoi (result[3].c_str()); } } else if(result[0] == "v" && result.size() >= 3) { unsigned int id = atoi(result[1].c_str()); this->resize(id + 1); (*this)[id].label = atoi(result[2].c_str()); } else if(result[0] == "e" && result.size() >= 4) { int from = atoi(result[1].c_str()); int to = atoi(result[2].c_str()); int elabel = atoi(result[3].c_str()); if((int)size() <= from || (int)size() <= to) { std::cerr << "Format Error: define vertex lists before edges, from: " << from << "; to: " << to << "; vertex count: " << size() << std::endl; throw std::runtime_error("Format Error: define vertex lists before edges"); } (*this)[from].push(from, to, elabel); if(directed == false) (*this)[to].push(to, from, elabel); } } buildEdge(); return is; } std::istream &Graph::read_fsg(std::istream &is) { char line[1024]; std::vector<std::string> result; clear(); std::map<std::string,int > vertex_labels; std::map<std::string,int > edge_labels; int num_vertex_labels = 0, num_edge_labels = 0; while(true) { unsigned int pos = is.tellg(); if(!is.getline(line, 1024)) { break; } result.clear(); utils::split(line, result); if(result.empty()) { // do nothing } else if(result[0] == "t") { if(!empty()) { // use as delimiter is.seekg(pos, std::ios_base::beg); break; } else { // y = atoi (result[3].c_str()); } } else if(result[0] == "v" && result.size() >= 3) { unsigned int id = atoi(result[1].c_str()); this->resize(id + 1); if(vertex_labels.count(result[2]) == 0 ) vertex_labels[result[2]] = num_vertex_labels++; (*this)[id].label = vertex_labels[result[2]]; //(*this)[id].label = atoi(result[2].c_str()); } else if(result[0] == "u" && result.size() >= 4) { int from = atoi(result[1].c_str()); int to = atoi(result[2].c_str()); //int elabel = atoi(result[3].c_str()); if(edge_labels.count(result[3]) == 0 ) edge_labels[result[3]] = num_edge_labels++; int elabel = edge_labels[result[3]]; if((int)size() <= from || (int)size() <= to) { std::cerr << "Format Error: define vertex lists before edges, from: " << from << "; to: " << to << "; vertex count: " << size() << std::endl; throw std::runtime_error("Format Error: define vertex lists before edges"); } (*this)[from].push(from, to, elabel); if(directed == false) (*this)[to].push(to, from, elabel); } } buildEdge(); return is; } std::ostream &Graph::write(std::ostream &os) { char buf[512]; std::set <std::string> tmp; for(int from = 0; from < (int)size(); ++from) { os << "v " << from << " " << (*this)[from].label << std::endl; for(Vertex::edge_iterator it = (*this)[from].edge.begin(); it != (*this)[from].edge.end(); ++it) { if(directed || from <= it->to) { std::sprintf(buf, "%d %d %d", from, it->to, it->elabel); } else { std::sprintf(buf, "%d %d %d", it->to, from, it->elabel); } tmp.insert(buf); } // for it } // for from for(std::set<std::string>::iterator it = tmp.begin(); it != tmp.end(); ++it) { os << "e " << *it << std::endl; } // for it return os; } void Graph::check(void) { // Check all indices for(int from = 0; from < (int)size(); ++from) { //mexPrintf ("check vertex %d, label %d\n", from, (*this)[from].label); for(Vertex::edge_iterator it = (*this)[from].edge.begin(); it != (*this)[from].edge.end(); ++it) { //mexPrintf (" check edge from %d to %d, label %d\n", it->from, it->to, it->elabel); assert(it->from >= 0 && it->from < size()); assert(it->to >= 0 && it->to < size()); } } } std::string Edge::to_string() const { std::stringstream ss; ss << "e(" << from << "," << to << "," << elabel << ")"; return ss.str(); } std::string PDFS::to_string() const { std::stringstream ss; ss << "[" << id << "," << edge->to_string() << "]"; return ss.str(); } std::string PDFS::to_string_projection(types::graph_database_t &gdb, types::graph_database_cuda &cgdb) const { const PDFS *curr = this; std::string result; while(curr != 0) { std::stringstream ss; types::Graph &grph = gdb[curr->id]; int cuda_grph_from = cgdb.translate_to_device(curr->id, curr->edge->from); int cuda_grph_to = cgdb.translate_to_device(curr->id, curr->edge->to); ss << "(" << grph.get_vertex_label(curr->edge->from) << ") " << curr->edge->from << "/" << cuda_grph_from << " = " << curr->edge->elabel << " = " << curr->edge->to << "/" << cuda_grph_to << " (" << grph.get_vertex_label(curr->edge->to) << "); "; result = ss.str() + result; //curr->to_string(); curr = curr->prev; } return result; } std::string Projected::to_string() const { std::stringstream ss; for(int i = 0; i < size(); i++) { ss << (*this)[i].to_string() << "; "; } // for i return ss.str(); } // Projected::to_string void History::build(const Graph &graph, PDFS *e) { // first build history clear(); edge.clear(); edge.resize(graph.edge_size()); vertex.clear(); vertex.resize(graph.size()); if(e) { push_back(e->edge); edge[e->edge->id] = vertex[e->edge->from] = vertex[e->edge->to] = 1; for(PDFS *p = e->prev; p; p = p->prev) { push_back(p->edge); // this line eats 8% of overall instructions(!) edge[p->edge->id] = vertex[p->edge->from] = vertex[p->edge->to] = 1; } std::reverse(begin(), end()); } } std::string History::to_string() const { std::stringstream ss; //ostream_iterator< for(int i = 0; i < size(); i++) { ss << at(i)->to_string() << "; "; } return ss.str(); } /* Original comment: * get_forward_pure () * e1 (from1, elabel1, to1) * from から繋がる edge e2(from2, elabel2, to2) を返す. * * minlabel <= elabel2, * (elabel1 < elabel2 || * (elabel == elabel2 && tolabel1 < tolabel2) の条件をみたす. * (elabel1, to1) のほうが先に探索されるべき * また, いままで見た vertex には逝かない (backward のやくめ) * * RK comment: * ???? gets the edge that starts and extends the right-most path. * */ bool get_forward_rmpath(const Graph &graph, Edge *e, int minlabel, History& history, types::EdgeList &result) { result.clear(); assert(e->to >= 0 && e->to < graph.size()); assert(e->from >= 0 && e->from < graph.size()); int tolabel = graph[e->to].label; for(Vertex::const_edge_iterator it = graph[e->from].edge.begin(); it != graph[e->from].edge.end(); ++it) { int tolabel2 = graph[it->to].label; if(e->to == it->to || minlabel > tolabel2 || history.hasVertex(it->to)) continue; if(e->elabel < it->elabel || (e->elabel == it->elabel && tolabel <= tolabel2)) result.push_back(const_cast<Edge*>(&(*it))); } return (!result.empty()); } /* Original comment: * get_forward_pure () * e (from, elabel, to) * to から繋がる edge を返す * ただし, minlabel より大きいものにしかいかない (DFSの制約) * また, いままで見た vertex には逝かない (backward のやくめ) * * RK comment: this function takes a "pure" forward edge, that is: an * edge that extends the last node of the right-most path, i.e., the * right-most node. * */ bool get_forward_pure(const Graph &graph, Edge *e, int minlabel, History& history, types::EdgeList &result) { result.clear(); assert(e->to >= 0 && e->to < graph.size()); // Walk all edges leaving from vertex e->to. for(Vertex::const_edge_iterator it = graph[e->to].edge.begin(); it != graph[e->to].edge.end(); ++it) { // -e-> [e->to] -it-> [it->to] assert(it->to >= 0 && it->to < graph.size()); if(minlabel > graph[it->to].label || history.hasVertex(it->to)) continue; result.push_back(const_cast<Edge*>(&(*it))); } return (!result.empty()); } /* * Original comment: * graph の vertex からはえる edge を探す * ただし, fromlabel <= tolabel の性質を満たす. * * RK comment: * */ bool get_forward_root(const Graph &g, const Vertex &v, types::EdgeList &result) { result.clear(); for(Vertex::const_edge_iterator it = v.edge.begin(); it != v.edge.end(); ++it) { assert(it->to >= 0 && it->to < g.size()); if(v.label <= g[it->to].label) result.push_back(const_cast<Edge*>(&(*it))); } return (!result.empty()); } /* Original comment: * get_backward (graph, e1, e2, history); * e1 (from1, elabel1, to1) * e2 (from2, elabel2, to2) * to2 -> from1 に繋がるかどうかしらべる. * * (elabel1 < elabel2 || * (elabel == elabel2 && tolabel1 < tolabel2) の条件をみたす. (elabel1, to1) のほうが先に探索されるべき * * RK comment: gets backward edge that starts and ends at the right most path * e1 is the forward edge and the backward edge goes to e1->from */ Edge *get_backward(const Graph &graph, Edge* e1, Edge* e2, History& history) { if(e1 == e2) return 0; assert(e1->from >= 0 && e1->from < graph.size()); assert(e1->to >= 0 && e1->to < graph.size()); assert(e2->to >= 0 && e2->to < graph.size()); for(Vertex::const_edge_iterator it = graph[e2->to].edge.begin(); it != graph[e2->to].edge.end(); ++it) { if(history.hasEdge(it->id)) continue; if((it->to == e1->from) && ((e1->elabel < it->elabel) || (e1->elabel == it->elabel) && (graph[e1->to].label <= graph[e2->to].label) )) { return const_cast<Edge*>(&(*it)); } // if(...) } // for(it) return 0; } std::string Graph::to_string() const { std::stringstream ss; for(int i = 0; i < vertex_size(); i++) { const Vertex &v = at(i); for(int k = 0; k < v.edge.size(); k++) { ss << "from: " << v.edge[k].from << "; to: " << v.edge[k].to << "; (" << v.label << ", " << v.edge[k].elabel << ", " << get_vertex_label(v.edge[k].to) << ")" << std::endl; //<< get_vertex_label(v.edge[k].from) << ", " << get_vertex_label(v.edge[k].to)<< std::endl; } // for k } // for i return ss.str(); //DFSCode dfs = get_min_dfs_code(); //return dfs.to_string(); } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Serialization // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// size_t Vertex::get_serialized_size(const Vertex &vrtx) { // vertex label + 4 * #of edges * sizeof(int) + number of edges + label; return sizeof(int) + 4 * vrtx.edge.size() * sizeof(int) + sizeof(int) + sizeof(int); } size_t Vertex::get_serialized_size(char *buffer, size_t buffer_size) { int s = *((int*)buffer); return s; } size_t Vertex::serialize(const Vertex &vrtx, char *buffer, size_t buffer_size) { if(buffer_size < get_serialized_size(vrtx)) throw std::runtime_error("Buffer too small."); int pos = 0; // size of this serialized vertex in bytes. *((int*)(buffer + pos)) = get_serialized_size(vrtx); pos += sizeof(int); // store the vertex label *((int*)(buffer + pos)) = vrtx.label; pos += sizeof(int); // store number of edges *((int*)(buffer + pos)) = vrtx.edge.size(); pos += sizeof(int); for(int i = 0; i < vrtx.edge.size(); i++) { *((int*)(buffer + pos)) = vrtx.edge[i].from; pos += sizeof(int); *((int*)(buffer + pos)) = vrtx.edge[i].to; pos += sizeof(int); *((int*)(buffer + pos)) = vrtx.edge[i].elabel; pos += sizeof(int); *((int*)(buffer + pos)) = vrtx.edge[i].id; pos += sizeof(int); } // for i return pos; } // Vertex::serialize size_t Vertex::deserialize(Vertex &vrtx, char *buffer, size_t buffer_size) { // TODO: check minimum buffer size if(buffer_size < get_serialized_size(buffer, buffer_size)) throw std::runtime_error("Buffer too small."); int pos = 0; vrtx.edge.clear(); // read buffer s pos += sizeof(int); // read the vertex label vrtx.label = *((int*)(buffer + pos)); pos += sizeof(int); // read the number of edges int edge_count = *((int*)(buffer + pos)); pos += sizeof(int); for(int i = 0; i < edge_count; i++) { Edge tmp_edge; tmp_edge.from = *((int*)(buffer + pos)); pos += sizeof(int); tmp_edge.to = *((int*)(buffer + pos)); pos += sizeof(int); tmp_edge.elabel = *((int*)(buffer + pos)); pos += sizeof(int); tmp_edge.id = *((int*)(buffer + pos)); pos += sizeof(int); vrtx.edge.push_back(tmp_edge); } // for i return pos; } // Vertex::deserialize size_t Graph::get_serialized_size(const Graph &grph) { size_t s = sizeof(int) + sizeof(int) + sizeof(int) + sizeof(bool); // edge_size_ + total buffer size + number of vertices + variable directed(bool) for(int i = 0; i < grph.size(); i++) { s += Vertex::get_serialized_size(grph[i]); } // for i return s; } // Graph::get_serialized_size size_t Graph::get_serialized_size(char *buffer, size_t buffer_size) { return *((int*) buffer); } size_t Graph::serialize(const Graph &grph, char *buffer, size_t buffer_size) { if(get_serialized_size(grph) > buffer_size) throw std::runtime_error("Buffer too small."); int pos = 0; // store buffer size *((int*)(buffer + pos)) = get_serialized_size(grph); pos += sizeof(int); // store edge_size_ *((int*)(buffer + pos)) = grph.edge_size_; pos += sizeof(int); // store number of vertices *((bool*)(buffer + pos)) = grph.directed; pos += sizeof(grph.directed); // store number of vertices *((int*)(buffer + pos)) = grph.size(); pos += sizeof(int); for(int i = 0; i < grph.size(); i++) { int tmp_pos = Vertex::serialize(grph.at(i), buffer + pos, buffer_size - pos); pos += tmp_pos; } // for i return pos; } // Graph::serialize size_t Graph::deserialize(Graph &grph, char *buffer, size_t buffer_size) { if(Graph::get_serialized_size(buffer, buffer_size) > buffer_size) throw std::runtime_error("Buffer too small."); grph.clear(); int pos = 0; // store buffer size pos += sizeof(int); // store edge_size_ grph.edge_size_ = *((int*)(buffer + pos)); pos += sizeof(int); // store number of vertices grph.directed = *((bool*)(buffer + pos)); pos += sizeof(grph.directed); // store number of vertices int vert_count = *((int*)(buffer + pos)); pos += sizeof(int); for(int i = 0; i < vert_count; i++) { Vertex tmp_vert; int tmp_pos = Vertex::deserialize(tmp_vert, buffer + pos, buffer_size - pos); grph.push_back(tmp_vert); pos += tmp_pos; } // for i return pos; } // Graph::deserialize size_t Graph::get_serialized_size(const graph_database_t &grph_db) { size_t min_buff_size = 0; min_buff_size += sizeof(int) + sizeof(int); // size of the database + size of the buffer for(size_t i = 0; i < grph_db.size(); i++) { min_buff_size += get_serialized_size(grph_db[i]); } // for i return min_buff_size; } // Graph::get_serialized_size size_t Graph::get_serialized_size_db(char *buffer, size_t buffer_size) { //abort(); return *((int*) buffer); } // Graph::get_serialized_size size_t Graph::serialize(const graph_database_t &grph_db, char *buffer, size_t buffer_size) { size_t pos = 0; int min_buff_size = get_serialized_size(grph_db); if(min_buff_size > buffer_size) throw std::runtime_error("Buffer too small."); *((int*)(buffer + pos)) = min_buff_size; pos += sizeof(int); *((int*)(buffer + pos)) = grph_db.size(); pos += sizeof(int); for(int i = 0; i < grph_db.size(); i++) { size_t tmp_pos = serialize(grph_db[i], buffer + pos, buffer_size - pos); pos += tmp_pos; } return pos; } // Graph::serialize size_t Graph::deserialize(graph_database_t &grph_db, char *buffer, size_t buffer_size) { int min_buf_size = get_serialized_size_db(buffer, buffer_size); if(buffer_size < min_buf_size) throw std::runtime_error("Buffer too small."); grph_db.clear(); size_t pos = 0; // skip buffer size pos += sizeof(int); int grph_db_size = *((int*)(buffer + pos)); pos += sizeof(int); for(int i = 0; i < grph_db_size; i++) { Graph grph; size_t tmp_pos = deserialize(grph, buffer + pos, buffer_size - pos); pos += tmp_pos; grph_db.push_back(grph); } // for i return pos; } // Graph::deserialize } // namespace types
25.926407
251
0.577336
c205135c11d51528b686eccfca8179e398d42899
5,015
cpp
C++
DarkSpace/GadgetAreaWeapon.cpp
SnipeDragon/darkspace
b6a1fa0a29d3559b158156e7b96935bd0a832ee3
[ "MIT" ]
1
2016-05-22T21:28:29.000Z
2016-05-22T21:28:29.000Z
DarkSpace/GadgetAreaWeapon.cpp
SnipeDragon/darkspace
b6a1fa0a29d3559b158156e7b96935bd0a832ee3
[ "MIT" ]
null
null
null
DarkSpace/GadgetAreaWeapon.cpp
SnipeDragon/darkspace
b6a1fa0a29d3559b158156e7b96935bd0a832ee3
[ "MIT" ]
null
null
null
/* GadgetAreaWeapon.cpp (c)2000 Palestar Inc, Richard Lyle */ #include "GadgetAreaWeapon.h" #include "GameContext.h" static Constant AI_USE_AREA_WEAPON( "AI_USE_AREA_WEAPON", 0.75f ); //---------------------------------------------------------------------------- IMPLEMENT_ABSTRACT_FACTORY( GadgetAreaWeapon, NounGadget ); REGISTER_FACTORY_KEY( GadgetAreaWeapon, 4373539570291853529LL ); BEGIN_ABSTRACT_PROPERTY_LIST( GadgetAreaWeapon, NounGadget ); ADD_TRANSMIT_UPDATE_PROPERTY( m_Energy ); END_PROPERTY_LIST(); GadgetAreaWeapon::GadgetAreaWeapon() : m_Energy( 0 ), m_nEnergyTick( 0 ), m_fChargeRate( 0.0f ) {} //---------------------------------------------------------------------------- void GadgetAreaWeapon::setup() { NounGadget::setup(); // start out with full energy m_Energy = energyNeeded(); } //---------------------------------------------------------------------------- NounGadget::Type GadgetAreaWeapon::type() const { return WEAPON; } NounGadget::EnergyClass GadgetAreaWeapon::energyClass() const { return ENERGY_CLASS_WEAPONS; } dword GadgetAreaWeapon::hotkey() const { return 'V'; } CharString GadgetAreaWeapon::useTip( Noun * pTarget, bool shift ) const { CharString tip; // usage information tip += CharString().format("\nRange:<X;100>%.0fgu", range() * calculateModifier( MT_WEAPON_RANGE ) ); tip += CharString().format("\nDamage:<X;100>%.0f-%.0f", ( damageCaused() * calculateModifier( MT_WEAPON_DAMAGE ) ) * damageRolls(), ( ( damageCaused() + damageRandom() ) * calculateModifier( MT_WEAPON_DAMAGE ) ) * damageRolls() ); tip += CharString().format("\nRecharge Time:<X;100>%.1fs", energyNeeded() / ( ( ( chargeRate() * TICKS_PER_SECOND ) * damageRatioInv() ) * calculateModifier( MT_WEAPON_ENERGY ) ) ); tip += CharString().format("\nEnergy Cost:<X;100>%.1f", energyNeeded() / 1000.0f ); return tip; } //---------------------------------------------------------------------------- int GadgetAreaWeapon::usableWhen() const { return (100 - ((m_Energy * 100) / energyNeeded())); } bool GadgetAreaWeapon::usable( Noun * pTarget, bool shift ) const { if (! NounGadget::usable( pTarget, shift ) ) return false; if ( destroyed() ) return false; if ( WidgetCast<NounShip>( parent() ) && ((NounShip *)parent())->testFlags( NounShip::FLAG_CLOAKED|NounShip::FLAG_IN_SAFE_ZONE ) ) return false; if ( m_Energy < energyNeeded() ) return false; return true; } void GadgetAreaWeapon::use( dword when, Noun * pTarget, bool shift) { NounGadget::use( when, pTarget, shift ); createUseEffect( false ); m_Energy = 0; m_nEnergyTick = when; Vector3 origin( worldPosition() ); float fRange = range() * calculateModifier( MT_WEAPON_RANGE ); Array< GameContext::NounCollision > collide; if ( context()->proximityCheck( origin, fRange, collide ) ) { for(int i=0;i<collide.size();i++) { NounGame * pCollide = WidgetCast<NounGame>( collide[ i ].pNoun ); if ( pCollide != NULL && pCollide != parent() && isEnemy( pCollide ) && pCollide->canDamage( damageType() ) ) { float fDistance = collide[i].fDistance - pCollide->radius(); if ( fDistance < range() ) { float damageRatio = 1.0f - (fDistance / range()); for(int k=0;k<damageRolls();++k) { int damage = damageRatio * damageCaused(); if ( damageRandom() > 0 ) damage += rand() % damageRandom(); if ( damage > 0 ) { // send the damage verb damage *= calculateModifier( MT_WEAPON_DAMAGE ); pCollide->inflictDamage( tick() + k, parentBody(), damage, damageType(), pCollide->worldFrame() * (origin - pCollide->worldPosition()) ); } } } } } } } int GadgetAreaWeapon::useEnergy( dword nTick, int energy ) { int nElapsed = nTick - m_nEnergyTick; m_nEnergyTick = nTick; if ( m_Energy < energyNeeded() ) { float fEnergyMod = calculateModifier( MT_WEAPON_ENERGY ); float fChargeScale = damageRatioInv() * fEnergyMod; m_fChargeRate += chargeRate() * fChargeScale * nElapsed; int chargeRate = floor( m_fChargeRate ); m_fChargeRate -= chargeRate; // leave fractional amount in the float for next update.. int charge = Min( Min( energyNeeded() - m_Energy, chargeRate ), energy ); energy -= charge; m_Energy += charge; } return energy; } bool GadgetAreaWeapon::updateLogic() { if ( useActive() || usableWhen() > 0 ) return true; if ( WidgetCast<NounShip>( parent() ) ) { NounShip * pShip = (NounShip *)parent(); bool bFireWeapon = false; for(int i=0;i<pShip->contactCount() && !bFireWeapon;++i) { Noun * pContact = pShip->contact( i ); if (! pContact || !isEnemy( pContact ) ) continue; float fDistance = (pContact->worldPosition() - pShip->worldPosition()).magnitude(); if ( fDistance < (range() * AI_USE_AREA_WEAPON) ) bFireWeapon = true; } if ( bFireWeapon ) pShip->useGadget( this, NULL, false ); } return false; } //---------------------------------------------------------------------------- //EOF
27.861111
232
0.619143
c2053ff6133d4df21d6d024cadbd635fabd32763
85,297
cpp
C++
vm/compiler/Loop.cpp
HazouPH/android_dalvik
5e66532f06bbf1f43b23ff408ee64dc30c31fc9d
[ "Apache-2.0" ]
null
null
null
vm/compiler/Loop.cpp
HazouPH/android_dalvik
5e66532f06bbf1f43b23ff408ee64dc30c31fc9d
[ "Apache-2.0" ]
null
null
null
vm/compiler/Loop.cpp
HazouPH/android_dalvik
5e66532f06bbf1f43b23ff408ee64dc30c31fc9d
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2009 The Android 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 "Dalvik.h" #include "CompilerInternals.h" #include "Dataflow.h" #include "Loop.h" #include "Utility.h" #ifdef ARCH_IA32 #include "PassDriver.h" #endif #ifdef DEBUG_LOOP_ON #define DEBUG_LOOP(X) X #else #define DEBUG_LOOP(X) #endif #ifndef ARCH_IA32 /** * Find the predecessor block of a given BasicBlock: the single predecessor whichever if only one predecessor, * the entry block if there are two predecessors and the entry block is a predecessor, 0 otherwise */ static BasicBlock *findPredecessorBlock(const CompilationUnit *cUnit, const BasicBlock *bb) { int numPred = dvmCountSetBits(bb->predecessors); BitVectorIterator bvIterator; dvmBitVectorIteratorInit(bb->predecessors, &bvIterator); if (numPred == 1) { int predIdx = dvmBitVectorIteratorNext(&bvIterator); return (BasicBlock *) dvmGrowableListGetElement(&cUnit->blockList, predIdx); /* First loop block */ } else if ((numPred == 2) && dvmIsBitSet(bb->predecessors, cUnit->entryBlock->id)) { while (true) { int predIdx = dvmBitVectorIteratorNext(&bvIterator); if (predIdx == cUnit->entryBlock->id) continue; return (BasicBlock *) dvmGrowableListGetElement(&cUnit->blockList, predIdx); } /* Doesn't support other shape of control flow yet */ } else { return NULL; } } /* Used for normalized loop exit condition checks */ static Opcode negateOpcode(Opcode opcode) { switch (opcode) { /* reg/reg cmp */ case OP_IF_EQ: return OP_IF_NE; case OP_IF_NE: return OP_IF_EQ; case OP_IF_LT: return OP_IF_GE; case OP_IF_GE: return OP_IF_LT; case OP_IF_GT: return OP_IF_LE; case OP_IF_LE: return OP_IF_GT; /* reg/zero cmp */ case OP_IF_EQZ: return OP_IF_NEZ; case OP_IF_NEZ: return OP_IF_EQZ; case OP_IF_LTZ: return OP_IF_GEZ; case OP_IF_GEZ: return OP_IF_LTZ; case OP_IF_GTZ: return OP_IF_LEZ; case OP_IF_LEZ: return OP_IF_GTZ; default: ALOGE("opcode %d cannot be negated", opcode); dvmAbort(); break; } return (Opcode)-1; // unreached } /* * A loop is considered optimizable if: * 1) It has one basic induction variable. * 2) The loop back branch compares the BIV with a constant. * 3) We need to normalize the loop exit condition so that the loop is exited * via the taken path. * 4) If it is a count-up loop, the condition is GE/GT. Otherwise it is * LE/LT/LEZ/LTZ for a count-down loop. * * Return false for loops that fail the above tests. */ static bool isSimpleCountedLoop(CompilationUnit *cUnit) { unsigned int i; BasicBlock *loopBackBlock = cUnit->entryBlock->fallThrough; LoopAnalysis *loopAnalysis = cUnit->loopAnalysis; if (loopAnalysis->numBasicIV != 1) return false; for (i = 0; i < loopAnalysis->ivList->numUsed; i++) { InductionVariableInfo *ivInfo; ivInfo = GET_ELEM_N(loopAnalysis->ivList, InductionVariableInfo*, i); /* Count up or down loop? */ if (ivInfo->ssaReg == ivInfo->basicSSAReg) { /* Infinite loop */ if (ivInfo->loopIncrement == 0) { return false; } loopAnalysis->isCountUpLoop = ivInfo->loopIncrement > 0; break; } } /* Find the block that ends with a branch to exit the loop */ while (true) { loopBackBlock = findPredecessorBlock(cUnit, loopBackBlock); /* Loop structure not recognized as counted blocks */ if (loopBackBlock == NULL) { return false; } /* Unconditional goto - continue to trace up the predecessor chain */ if (loopBackBlock->taken == NULL) { continue; } break; } MIR *branch = loopBackBlock->lastMIRInsn; Opcode opcode = branch->dalvikInsn.opcode; // Remember the offset of the branch MIR in order to use it // when generating the extended MIRs loopAnalysis->loopBranchMIROffset = branch->offset; /* Last instruction is not a conditional branch - bail */ if (dexGetFlagsFromOpcode(opcode) != (kInstrCanContinue|kInstrCanBranch)) { return false; } int endSSAReg; int endDalvikReg; /* reg/reg comparison */ if (branch->ssaRep->numUses == 2) { if (branch->ssaRep->uses[0] == loopAnalysis->ssaBIV) { endSSAReg = branch->ssaRep->uses[1]; } else if (branch->ssaRep->uses[1] == loopAnalysis->ssaBIV) { endSSAReg = branch->ssaRep->uses[0]; opcode = negateOpcode(opcode); } else { return false; } endDalvikReg = dvmConvertSSARegToDalvik(cUnit, endSSAReg); /* * If the comparison is not between the BIV and a loop invariant, * return false. endDalvikReg is loop invariant if one of the * following is true: * - It is not defined in the loop (ie DECODE_SUB returns 0) * - It is reloaded with a constant */ if ((DECODE_SUB(endDalvikReg) != 0) && !dvmIsBitSet(cUnit->isConstantV, endSSAReg)) { return false; } /* Compare against zero */ } else if (branch->ssaRep->numUses == 1) { if (branch->ssaRep->uses[0] == loopAnalysis->ssaBIV) { /* Keep the compiler happy */ endDalvikReg = -1; } else { return false; } } else { return false; } /* Normalize the loop exit check as "if (iv op end) exit;" */ if (loopBackBlock->taken->blockType == kDalvikByteCode) { opcode = negateOpcode(opcode); } if (loopAnalysis->isCountUpLoop) { /* * If the normalized condition op is not > or >=, this is not an * optimization candidate. */ switch (opcode) { case OP_IF_GT: case OP_IF_GE: break; default: return false; } loopAnalysis->endConditionReg = DECODE_REG(endDalvikReg); } else { /* * If the normalized condition op is not < or <=, this is not an * optimization candidate. */ switch (opcode) { case OP_IF_LT: case OP_IF_LE: loopAnalysis->endConditionReg = DECODE_REG(endDalvikReg); break; case OP_IF_LTZ: case OP_IF_LEZ: break; default: return false; } } /* * Remember the normalized opcode, which will be used to determine the end * value used for the yanked range checks. */ loopAnalysis->loopBranchOpcode = opcode; return true; } /* * Record the upper and lower bound information for range checks for each * induction variable. If array A is accessed by index "i+5", the upper and * lower bound will be len(A)-5 and -5, respectively. */ static void updateRangeCheckInfo(CompilationUnit *cUnit, int arrayReg, int idxReg) { InductionVariableInfo *ivInfo; LoopAnalysis *loopAnalysis = cUnit->loopAnalysis; unsigned int i, j; for (i = 0; i < loopAnalysis->ivList->numUsed; i++) { ivInfo = GET_ELEM_N(loopAnalysis->ivList, InductionVariableInfo*, i); if (ivInfo->ssaReg == idxReg) { ArrayAccessInfo *arrayAccessInfo = NULL; for (j = 0; j < loopAnalysis->arrayAccessInfo->numUsed; j++) { ArrayAccessInfo *existingArrayAccessInfo = GET_ELEM_N(loopAnalysis->arrayAccessInfo, ArrayAccessInfo*, j); if (existingArrayAccessInfo->arrayReg == arrayReg) { if (ivInfo->constant > existingArrayAccessInfo->maxC) { existingArrayAccessInfo->maxC = ivInfo->constant; } if (ivInfo->constant < existingArrayAccessInfo->minC) { existingArrayAccessInfo->minC = ivInfo->constant; } arrayAccessInfo = existingArrayAccessInfo; break; } } if (arrayAccessInfo == NULL) { arrayAccessInfo = (ArrayAccessInfo *)dvmCompilerNew(sizeof(ArrayAccessInfo), false); arrayAccessInfo->ivReg = ivInfo->basicSSAReg; arrayAccessInfo->arrayReg = arrayReg; arrayAccessInfo->maxC = (ivInfo->constant > 0) ? ivInfo->constant : 0; arrayAccessInfo->minC = (ivInfo->constant < 0) ? ivInfo->constant : 0; arrayAccessInfo->loopIncrement = ivInfo->loopIncrement; dvmInsertGrowableList(loopAnalysis->arrayAccessInfo, (intptr_t) arrayAccessInfo); } break; } } } /* Returns true if the loop body cannot throw any exceptions */ static bool doLoopBodyCodeMotion(CompilationUnit *cUnit) { BasicBlock *loopBody = cUnit->entryBlock->fallThrough; MIR *mir; bool loopBodyCanThrow = false; for (mir = loopBody->firstMIRInsn; mir; mir = mir->next) { DecodedInstruction *dInsn = &mir->dalvikInsn; int dfAttributes = dvmCompilerDataFlowAttributes[mir->dalvikInsn.opcode]; /* Skip extended MIR instructions */ if ((u2) dInsn->opcode >= kNumPackedOpcodes) continue; int instrFlags = dexGetFlagsFromOpcode(dInsn->opcode); /* Instruction is clean */ if ((instrFlags & kInstrCanThrow) == 0) continue; /* * Currently we can only optimize away null and range checks. Punt on * instructions that can throw due to other exceptions. */ if (!(dfAttributes & DF_HAS_NR_CHECKS)) { loopBodyCanThrow = true; continue; } /* * This comparison is redundant now, but we will have more than one * group of flags to check soon. */ if (dfAttributes & DF_HAS_NR_CHECKS) { /* * Check if the null check is applied on a loop invariant register? * If the register's SSA id is less than the number of Dalvik * registers, then it is loop invariant. */ int refIdx; switch (dfAttributes & DF_HAS_NR_CHECKS) { case DF_NULL_N_RANGE_CHECK_0: refIdx = 0; break; case DF_NULL_N_RANGE_CHECK_1: refIdx = 1; break; case DF_NULL_N_RANGE_CHECK_2: refIdx = 2; break; default: refIdx = 0; ALOGE("Jit: bad case in doLoopBodyCodeMotion"); dvmCompilerAbort(cUnit); } int useIdx = refIdx + 1; int subNRegArray = dvmConvertSSARegToDalvik(cUnit, mir->ssaRep->uses[refIdx]); int arraySub = DECODE_SUB(subNRegArray); /* * If the register is never updated in the loop (ie subscript == 0), * it is an optimization candidate. */ if (arraySub != 0) { loopBodyCanThrow = true; continue; } /* * Then check if the range check can be hoisted out of the loop if * it is basic or dependent induction variable. */ if (dvmIsBitSet(cUnit->loopAnalysis->isIndVarV, mir->ssaRep->uses[useIdx])) { mir->OptimizationFlags |= MIR_IGNORE_RANGE_CHECK | MIR_IGNORE_NULL_CHECK; updateRangeCheckInfo(cUnit, mir->ssaRep->uses[refIdx], mir->ssaRep->uses[useIdx]); } } } return !loopBodyCanThrow; } static void genHoistedChecks(CompilationUnit *cUnit) { unsigned int i; BasicBlock *entry = cUnit->entryBlock; LoopAnalysis *loopAnalysis = cUnit->loopAnalysis; int globalMaxC = 0; int globalMinC = 0; /* Should be loop invariant */ int idxReg = 0; for (i = 0; i < loopAnalysis->arrayAccessInfo->numUsed; i++) { ArrayAccessInfo *arrayAccessInfo = GET_ELEM_N(loopAnalysis->arrayAccessInfo, ArrayAccessInfo*, i); int arrayReg = DECODE_REG( dvmConvertSSARegToDalvik(cUnit, arrayAccessInfo->arrayReg)); idxReg = DECODE_REG( dvmConvertSSARegToDalvik(cUnit, arrayAccessInfo->ivReg)); MIR *rangeCheckMIR = (MIR *)dvmCompilerNew(sizeof(MIR), true); rangeCheckMIR->dalvikInsn.opcode = (loopAnalysis->isCountUpLoop) ? (Opcode)kMirOpNullNRangeUpCheck : (Opcode)kMirOpNullNRangeDownCheck; rangeCheckMIR->dalvikInsn.vA = arrayReg; rangeCheckMIR->dalvikInsn.vB = idxReg; rangeCheckMIR->dalvikInsn.vC = loopAnalysis->endConditionReg; rangeCheckMIR->dalvikInsn.arg[0] = arrayAccessInfo->maxC; rangeCheckMIR->dalvikInsn.arg[1] = arrayAccessInfo->minC; rangeCheckMIR->dalvikInsn.arg[2] = loopAnalysis->loopBranchOpcode; rangeCheckMIR->dalvikInsn.arg[3] = arrayAccessInfo->loopIncrement; // set offset to the start offset of entry block // this will set rPC in case of bail to interpreter rangeCheckMIR->offset = entry->startOffset; dvmCompilerAppendMIR(entry, rangeCheckMIR); if (arrayAccessInfo->maxC > globalMaxC) { globalMaxC = arrayAccessInfo->maxC; } if (arrayAccessInfo->minC < globalMinC) { globalMinC = arrayAccessInfo->minC; } } if (loopAnalysis->arrayAccessInfo->numUsed != 0) { if (loopAnalysis->isCountUpLoop) { MIR *boundCheckMIR = (MIR *)dvmCompilerNew(sizeof(MIR), true); boundCheckMIR->dalvikInsn.opcode = (Opcode)kMirOpLowerBound; boundCheckMIR->dalvikInsn.vA = idxReg; boundCheckMIR->dalvikInsn.vB = globalMinC; // set offset to the start offset of entry block // this will set rPC in case of bail to interpreter boundCheckMIR->offset = entry->startOffset; dvmCompilerAppendMIR(entry, boundCheckMIR); } else { if (loopAnalysis->loopBranchOpcode == OP_IF_LT || loopAnalysis->loopBranchOpcode == OP_IF_LE) { MIR *boundCheckMIR = (MIR *)dvmCompilerNew(sizeof(MIR), true); boundCheckMIR->dalvikInsn.opcode = (Opcode)kMirOpLowerBound; boundCheckMIR->dalvikInsn.vA = loopAnalysis->endConditionReg; boundCheckMIR->dalvikInsn.vB = globalMinC; // set offset to the start offset of entry block // this will set rPC in case of bail to interpreter boundCheckMIR->offset = entry->startOffset; /* * If the end condition is ">" in the source, the check in the * Dalvik bytecode is OP_IF_LE. In this case add 1 back to the * constant field to reflect the fact that the smallest index * value is "endValue + constant + 1". */ if (loopAnalysis->loopBranchOpcode == OP_IF_LE) { boundCheckMIR->dalvikInsn.vB++; } dvmCompilerAppendMIR(entry, boundCheckMIR); } else if (loopAnalysis->loopBranchOpcode == OP_IF_LTZ) { /* Array index will fall below 0 */ if (globalMinC < 0) { MIR *boundCheckMIR = (MIR *)dvmCompilerNew(sizeof(MIR), true); boundCheckMIR->dalvikInsn.opcode = (Opcode)kMirOpPunt; // set offset to the start offset of entry block // this will set rPC in case of bail to interpreter boundCheckMIR->offset = entry->startOffset; dvmCompilerAppendMIR(entry, boundCheckMIR); } } else if (loopAnalysis->loopBranchOpcode == OP_IF_LEZ) { /* Array index will fall below 0 */ if (globalMinC < -1) { MIR *boundCheckMIR = (MIR *)dvmCompilerNew(sizeof(MIR), true); boundCheckMIR->dalvikInsn.opcode = (Opcode)kMirOpPunt; // set offset to the start offset of entry block // this will set rPC in case of bail to interpreter boundCheckMIR->offset = entry->startOffset; dvmCompilerAppendMIR(entry, boundCheckMIR); } } else { ALOGE("Jit: bad case in genHoistedChecks"); dvmCompilerAbort(cUnit); } } } } #else //IA32 /** * @brief Used to flip the condition of an "if" bytecode * @param opcode Dalvik opcode to negate * @param negatedOpcode Updated by function to contain negated * opcode. Only valid if function returns true. * @return Returns true if successfully negated. */ static bool negateOpcode(Opcode opcode, Opcode & negatedOpcode) { //Eagerly assume we will succeed bool success = true; switch (opcode) { /* reg/reg cmp */ case OP_IF_EQ: negatedOpcode = OP_IF_NE; break; case OP_IF_NE: negatedOpcode = OP_IF_EQ; break; case OP_IF_LT: negatedOpcode = OP_IF_GE; break; case OP_IF_GE: negatedOpcode = OP_IF_LT; break; case OP_IF_GT: negatedOpcode = OP_IF_LE; break; case OP_IF_LE: negatedOpcode = OP_IF_GT; break; /* reg/zero cmp */ case OP_IF_EQZ: negatedOpcode = OP_IF_NEZ; break; case OP_IF_NEZ: negatedOpcode = OP_IF_EQZ; break; case OP_IF_LTZ: negatedOpcode = OP_IF_GEZ; break; case OP_IF_GEZ: negatedOpcode = OP_IF_LTZ; break; case OP_IF_GTZ: negatedOpcode = OP_IF_LEZ; break; case OP_IF_LEZ: negatedOpcode = OP_IF_GTZ; break; default: success = false; break; } return success; } /* * A loop is considered optimizable if: * 1) It has one basic induction variable. * 2) The loop back branch compares the BIV with a constant. * 3) We need to normalize the loop exit condition so that the loop is exited * via the taken path. * 4) If it is a count-up loop, the condition is GE/GT. Otherwise it is * LE/LT/LEZ/LTZ for a count-down loop. */ /** * @brief Checks if the loops is suitable for hoisting range/null checks * @param cUnit the CompilationUnit * @param pass the Pass * @return false for loops that fail the above tests. */ //TODO: this should take a LoopInformation to be tested for inner loops static bool isSimpleCountedLoop(CompilationUnit *cUnit) { unsigned int i; BasicBlock *loopBackBlock = NULL; LoopInformation *loopInfo = cUnit->loopInformation; GrowableList* ivList = &cUnit->loopInformation->getInductionVariableList (); /* This either counted up or down loop, 2 BIVs could bring complication to detect that. Potentially we can enhance the algorithm to utilize > 1 BIV in case inc for all BIVs > 0 ( or < 0) */ if (loopInfo->getNumBasicIV(cUnit) != 1) { return false; } for (i = 0; i < ivList->numUsed; i++) { InductionVariableInfo *ivInfo; ivInfo = GET_ELEM_N(ivList, InductionVariableInfo*, i); /* Count up or down loop? */ if (ivInfo->isBasicIV () == true) { /* Infinite loop */ if (ivInfo->loopIncrement == 0) { return false; } loopInfo->setCountUpLoop(ivInfo->loopIncrement > 0); break; } } // Get Back branch bb, need to find loop exit condition // the main hypotethis is that Back branch bb is a // predecessor of a loop exit bb. BasicBlock *bb = NULL; BitVectorIterator bvIterator; BitVector *exitbbs = const_cast<BitVector *> (loopInfo->getExitLoops()); int nexitbbs = dvmCountSetBits(exitbbs); // We limit the optimization to cases where just 1 exit bb // due to unpredictable behaviour in other cases if (nexitbbs != 1) { return false; } /* Get loopBack branch bb */ // 1. Get exit bb dvmBitVectorIteratorInit (exitbbs, &bvIterator); int bIdx = dvmBitVectorIteratorNext (&bvIterator); assert (bIdx != -1); bb = (BasicBlock *) dvmGrowableListGetElement(&cUnit->blockList, bIdx); if (bb == NULL) { return false; } // 2. Get loop exit bb predecessor dvmBitVectorIteratorInit(bb->predecessors, &bvIterator); bIdx = dvmBitVectorIteratorNext(&bvIterator); assert (bIdx != -1); // 3. Finally get loopBack branch bb loopBackBlock = (BasicBlock*) (dvmGrowableListGetElement(&cUnit->blockList, bIdx)); // paranoid, didn't find loopBack bb if (loopBackBlock == NULL) { return false; } // Find exit block which contains loop exit condition MIR *branch = loopBackBlock->lastMIRInsn; if (branch == NULL) { return false; } Opcode op = branch->dalvikInsn.opcode; Opcode opcode = op; // Paranoid: Check this is not extendent MIR because // dexGetFlagsFromOpcode call is not safe then if (opcode >= kNumPackedOpcodes) { return false; } /* Last instruction is not a conditional branch - bail */ if (dexGetFlagsFromOpcode(opcode) != (kInstrCanContinue|kInstrCanBranch)) { return false; } int endSSAReg; int endDalvikReg; /* Detect end condition register As soon as we found loop back branch we can get the condition and a loop limit from it */ if (branch->ssaRep->numUses == 2) { if (branch->ssaRep->uses[0] == loopInfo->getSSABIV()) { endSSAReg = branch->ssaRep->uses[1]; } else if (branch->ssaRep->uses[1] == loopInfo->getSSABIV()) { endSSAReg = branch->ssaRep->uses[0]; negateOpcode(op, opcode); } else { return false; } endDalvikReg = dvmConvertSSARegToDalvik(cUnit, endSSAReg); /* * If the comparison is not between the BIV and a loop invariant, * return false. endDalvikReg is loop invariant if one of the * following is true: * - It is not defined in the loop (ie DECODE_SUB returns 0) * - It is reloaded with a constant */ if ((DECODE_SUB(endDalvikReg) != 0) && dvmCompilerIsRegConstant (cUnit, endSSAReg) == false) { return false; } } else { return false; } if (loopInfo->isCountUpLoop() == true) { /* * If the normalized condition op is not > or >=, this is not an * optimization candidate. */ switch (opcode) { case OP_IF_GT: case OP_IF_GE: break; default: return false; } loopInfo->setEndConditionReg(DECODE_REG(endDalvikReg)); } else { /* * If the normalized condition op is not < or <=, this is not an * optimization candidate. */ switch (opcode) { case OP_IF_LT: case OP_IF_LE: loopInfo->setEndConditionReg(DECODE_REG(endDalvikReg)); break; case OP_IF_LTZ: case OP_IF_LEZ: break; default: return false; } } /* * Remember the normalized opcode, which will be used to determine the end * value used for the yanked range checks. */ loopInfo->setLoopBranchOpcode(opcode); return true; } /** * @brief Record the upper and lower bound information for range checks for each IV * @param cUnit the CompilationUnit * @param arrayReg the array register * @param idxReg the array index register */ // If array A is accessed by index "i+5", the upper and // lower bound will be len(A)-5 and -5, respectively. static void updateRangeCheckInfo(CompilationUnit *cUnit, int arrayReg, int idxReg) { InductionVariableInfo *ivInfo; //Get the IV list GrowableList* ivList = &cUnit->loopInformation->getInductionVariableList (); LoopInformation *loopInfo = cUnit->loopInformation; assert (loopInfo != NULL); unsigned int i, j; // when the tested idxReg is found to be an IV this is an array access point. // As soon as such point is found we create array access info or update existing one. // The update means identification of maxC and minC which are the min/max of the same index. // E.g. A[i], A[i+1], ..., A[i+N] will result in maxC = N. It will be used to aggregate // several range checks into a single hoisted one. for (i = 0; i < ivList->numUsed; i++) { ivInfo = GET_ELEM_N(ivList, InductionVariableInfo*, i); if (ivInfo->ssaReg == idxReg) { ArrayAccessInfo *arrayAccessInfo = NULL; for (j = 0; j < loopInfo->getArrayAccessInfo()->numUsed; j++) { ArrayAccessInfo *existingArrayAccessInfo = GET_ELEM_N(loopInfo->getArrayAccessInfo(), ArrayAccessInfo*, j); if (existingArrayAccessInfo->arrayReg == arrayReg) { if (ivInfo->constant > existingArrayAccessInfo->maxC) { existingArrayAccessInfo->maxC = ivInfo->constant; } if (ivInfo->constant < existingArrayAccessInfo->minC) { existingArrayAccessInfo->minC = ivInfo->constant; } arrayAccessInfo = existingArrayAccessInfo; break; } } if (arrayAccessInfo == NULL) { arrayAccessInfo = (ArrayAccessInfo *)dvmCompilerNew(sizeof(ArrayAccessInfo), false); arrayAccessInfo->ivReg = ivInfo->basicSSAReg; arrayAccessInfo->arrayReg = arrayReg; arrayAccessInfo->maxC = (ivInfo->constant > 0) ? ivInfo->constant : 0; arrayAccessInfo->minC = (ivInfo->constant < 0) ? ivInfo->constant : 0; arrayAccessInfo->inc = ivInfo->loopIncrement; dvmInsertGrowableList(cUnit->loopInformation->getArrayAccessInfo(), (intptr_t) arrayAccessInfo); } break; } } } void dvmCompilerBodyCodeMotion (CompilationUnit *cUnit, Pass *currentPass) { //Get the BasicBlock vector for this loop BitVector *blocks = const_cast<BitVector *> (cUnit->loopInformation->getBasicBlocks ()); MIR *mir; //Iterate through basic blocks BitVectorIterator bvIterator; dvmBitVectorIteratorInit (blocks, &bvIterator); while (true) { //Get block index int blockIdx = dvmBitVectorIteratorNext (&bvIterator); //If done, bail if (blockIdx == -1) { break; } BasicBlock *loopBody = (BasicBlock*) (dvmGrowableListGetElement(&cUnit->blockList, blockIdx)); //Paranoid if (loopBody == 0) { break; } for (mir = loopBody->firstMIRInsn; mir; mir = mir->next) { DecodedInstruction *dInsn = &mir->dalvikInsn; long long dfAttributes = dvmCompilerDataFlowAttributes[mir->dalvikInsn.opcode]; /* Skip extended MIR instructions */ if (dInsn->opcode >= kNumPackedOpcodes) { continue; } int instrFlags = dexGetFlagsFromOpcode(dInsn->opcode); /* Instruction is clean */ if ((instrFlags & kInstrCanThrow) == 0) { continue; } /* * Currently we can only optimize away null and range checks. */ if ((dfAttributes & DF_HAS_NR_CHECKS) == 0) { continue; } /* * This comparison is redundant now, but we will have more than one * group of flags to check soon. */ if (dfAttributes & DF_HAS_NR_CHECKS) { /* * Check if the null check is applied on a loop invariant register? * If the register's SSA id is less than the number of Dalvik * registers, then it is loop invariant. */ int refIdx; switch (dfAttributes & DF_HAS_NR_CHECKS) { case DF_NULL_N_RANGE_CHECK_0: refIdx = 0; break; case DF_NULL_N_RANGE_CHECK_1: refIdx = 1; break; case DF_NULL_N_RANGE_CHECK_2: refIdx = 2; break; default: refIdx = 0; ALOGE("Jit: bad case in dvmCompilerBodyCodeMotion"); // bail - should not reach here dvmCompilerAbort(cUnit); return; } int useIdx = refIdx + 1; int subNRegArray = dvmConvertSSARegToDalvik(cUnit, mir->ssaRep->uses[refIdx]); int arraySub = DECODE_SUB(subNRegArray); /* * If the register is never updated in the loop (ie subscript == 0), * it is an optimization candidate. */ if (arraySub != 0) { continue; } /* * Then check if the range check can be hoisted out of the loop if * it is basic or dependent induction variable. */ if (cUnit->loopInformation->isAnInductionVariable(cUnit, mir->ssaRep->uses[useIdx], true)) { mir->OptimizationFlags |= MIR_IGNORE_RANGE_CHECK | MIR_IGNORE_NULL_CHECK; updateRangeCheckInfo(cUnit, mir->ssaRep->uses[refIdx], mir->ssaRep->uses[useIdx]); } } } } //Unused argument (void) currentPass; } bool dvmCompilerHoistedChecksGate(const CompilationUnit* cUnit, Pass* pass) { if (cUnit->loopInformation != NULL && isSimpleCountedLoop((CompilationUnit*)cUnit)) { return true; } //Unused argument (void) pass; return false; } /** * @brief Dump hoisted checks debugging info * @param cUnit is the CompilationUnit */ static void dvmDumpHoistedRangeCheckInfo(CompilationUnit* cUnit) { LoopInformation* loopInfo = cUnit->loopInformation; InductionVariableInfo *ivInfo; //Get the IV list GrowableList* ivList = &loopInfo->getInductionVariableList (); unsigned int i; /* dump IV info */ ALOGD("BASIC_IV_NUMBER_INFO: number of basic IV: %d", loopInfo->getNumBasicIV(cUnit)); for (i = 0; i < ivList->numUsed; i++) { ivInfo = GET_ELEM_N(ivList, InductionVariableInfo*, i); if (ivInfo->isBasicIV () == true) { /* Basic IV */ ALOGD("BASIC_IV_INFO: ssaReg: %d, basicSSAReg: %d, inc: %d, VR: %d_%dn", ivInfo->ssaReg, ivInfo->basicSSAReg, ivInfo->loopIncrement, dvmExtractSSARegister (cUnit, ivInfo->ssaReg), dvmExtractSSASubscript (cUnit, ivInfo->ssaReg)); } else { /* Dependent IV */ ALOGD("DEPENDENT_IV_INFO: ssaReg: %d, depSSAReg: %d, inc: %d, VR: %d_%d c=%d\n", ivInfo->ssaReg, ivInfo->basicSSAReg, ivInfo->loopIncrement, dvmExtractSSARegister (cUnit, ivInfo->ssaReg), dvmExtractSSASubscript (cUnit, ivInfo->ssaReg), ivInfo->constant); } } /* dump array access info */ for (i = 0; i < loopInfo->getArrayAccessInfo()->numUsed; i++) { ArrayAccessInfo *arrayAccessInfo = GET_ELEM_N(loopInfo->getArrayAccessInfo(), ArrayAccessInfo*, i); ALOGE("JIT_INFO: arrayReg: %d, idxReg: %d, endConditionReg: %d, maxC: %d, minC: %d, inc: %d", arrayAccessInfo->arrayReg, arrayAccessInfo->ivReg, loopInfo->getEndConditionReg(), arrayAccessInfo->maxC, arrayAccessInfo->minC, arrayAccessInfo->inc); } } #endif #ifdef ARCH_IA32 // The main purpose of the function is to transform internal array access info into // hoisted checks extended MIRs at start of a loop which will be transformed to // assembly using special algorithm and data from hoisted checks MIR's // Terms: e.g. for (int i=0; i<=100; i+=2) {A[i]...} // A - array, i - index, end condition reg - 100 (reg), inc - 2(i+=2) // For loop body like {A[i-1] ... a[i+N]} maxC = N, minC = -1 // loopbranch opcode - >/>=/</<=, counted up/down cycle - ?inc >0 or <0 void dvmCompilerGenHoistedChecks(CompilationUnit *cUnit, Pass* pass) { unsigned int i; if (cUnit->loopInformation == NULL) { return; } BasicBlock *entry = cUnit->entryBlock; LoopInformation* loopInfo = cUnit->loopInformation; int globalMaxC = 0; int globalMinC = 0; /* Should be loop invariant */ int idxReg = 0; //TODO The offset in entry->offset may not be correct to use. The offset for exception //must use the offset of the first instruction in block before heavy optimizations are //applied like invariant hoisting. The same applies for the parent method for these //extended MIRs. They technically have no source method but the one matching the first //instruction in loop should be assigned. This ensures that correct exit PC is set //in case these checks lead to exception. const unsigned int offsetForException = entry->startOffset; NestedMethod nesting (cUnit->method); // Go through array access elements and generate range checks // Range check in the current implemntation is the upper border of the loop // E.g. for count down loops it is lowest index // Lower border check of a loop is done using Bound checks below for (i = 0; i < loopInfo->getArrayAccessInfo()->numUsed; i++) { ArrayAccessInfo *arrayAccessInfo = GET_ELEM_N(loopInfo->getArrayAccessInfo(), ArrayAccessInfo*, i); // get reg containing array ref int arrayReg = DECODE_REG( dvmConvertSSARegToDalvik(cUnit, arrayAccessInfo->arrayReg)); // get reg containing index idxReg = DECODE_REG( dvmConvertSSARegToDalvik(cUnit, arrayAccessInfo->ivReg)); // create new mir using the array access info // see genHoistedChecks* to check with the hoisted check algorithm MIR *rangeCheckMIR = dvmCompilerNewMIR (); rangeCheckMIR->dalvikInsn.opcode = (loopInfo->isCountUpLoop()) ? (Opcode)kMirOpNullNRangeUpCheck : (Opcode)kMirOpNullNRangeDownCheck; rangeCheckMIR->dalvikInsn.vA = arrayReg; rangeCheckMIR->dalvikInsn.vB = idxReg; rangeCheckMIR->dalvikInsn.vC = loopInfo->getEndConditionReg(); rangeCheckMIR->dalvikInsn.arg[0] = arrayAccessInfo->maxC; rangeCheckMIR->dalvikInsn.arg[1] = arrayAccessInfo->minC; rangeCheckMIR->dalvikInsn.arg[2] = loopInfo->getLoopBranchOpcode(); rangeCheckMIR->dalvikInsn.arg[3] = arrayAccessInfo->inc; // set offset to the start offset of entry block // this will set rPC in case of bail to interpreter rangeCheckMIR->offset = offsetForException; rangeCheckMIR->nesting = nesting; dvmCompilerAppendMIR(entry, rangeCheckMIR); // To do bound check we need to know globalMaxC/globalMinC value // as soon as we're limited with just one BIV globalMaxC will contain // the max/min index change inside a loop body if (arrayAccessInfo->maxC > globalMaxC) { globalMaxC = arrayAccessInfo->maxC; } if (arrayAccessInfo->minC < globalMinC) { globalMinC = arrayAccessInfo->minC; } } // Insert Bound check (lower loop border check) // See the bound check algorithm in GenHoistedBoundCheck function // Bound check values should be adjusted to meet loop branch condition if (loopInfo->getArrayAccessInfo()->numUsed != 0) { if (loopInfo->isCountUpLoop()) { MIR *boundCheckMIR = dvmCompilerNewMIR (); boundCheckMIR->dalvikInsn.opcode = (Opcode)kMirOpLowerBound; boundCheckMIR->dalvikInsn.vA = idxReg; boundCheckMIR->dalvikInsn.vB = globalMinC; // set offset to the start offset of entry block // this will set rPC in case of bail to interpreter boundCheckMIR->offset = offsetForException; boundCheckMIR->nesting = nesting; dvmCompilerAppendMIR(entry, boundCheckMIR); } else { if (loopInfo->getLoopBranchOpcode() == OP_IF_LT || loopInfo->getLoopBranchOpcode() == OP_IF_LE) { MIR *boundCheckMIR = dvmCompilerNewMIR (); boundCheckMIR->dalvikInsn.opcode = (Opcode)kMirOpLowerBound; boundCheckMIR->dalvikInsn.vA = loopInfo->getEndConditionReg(); boundCheckMIR->dalvikInsn.vB = globalMinC; // set offset to the start offset of entry block // this will set rPC in case of bail to interpreter boundCheckMIR->offset = offsetForException; boundCheckMIR->nesting = nesting; /* * If the end condition is ">" in the source, the check in the * Dalvik bytecode is OP_IF_LE. In this case add 1 back to the * constant field to reflect the fact that the smallest index * value is "endValue + constant + 1". */ if (loopInfo->getLoopBranchOpcode() == OP_IF_LE) { boundCheckMIR->dalvikInsn.vB++; } dvmCompilerAppendMIR(entry, boundCheckMIR); } else if (loopInfo->getLoopBranchOpcode() == OP_IF_LTZ) { /* Array index will fall below 0 */ if (globalMinC < 0) { MIR *boundCheckMIR = dvmCompilerNewMIR (); boundCheckMIR->dalvikInsn.opcode = (Opcode)kMirOpPunt; // set offset to the start offset of entry block // this will set rPC in case of bail to interpreter boundCheckMIR->offset = offsetForException; boundCheckMIR->nesting = nesting; dvmCompilerAppendMIR(entry, boundCheckMIR); } } else if (loopInfo->getLoopBranchOpcode() == OP_IF_LEZ) { /* Array index will fall below 0 */ if (globalMinC < -1) { MIR *boundCheckMIR = dvmCompilerNewMIR (); boundCheckMIR->dalvikInsn.opcode = (Opcode)kMirOpPunt; // set offset to the start offset of entry block // this will set rPC in case of bail to interpreter boundCheckMIR->offset = offsetForException; boundCheckMIR->nesting = nesting; dvmCompilerAppendMIR(entry, boundCheckMIR); } } else { ALOGE("Jit: bad case in genHoistedChecks"); dvmCompilerAbort(cUnit); } } } if (cUnit->printPass == true) { dvmDumpHoistedRangeCheckInfo(cUnit); } (void) pass; } #endif void resetBlockEdges(BasicBlock *bb) { bb->taken = NULL; bb->fallThrough = NULL; bb->successorBlockList.blockListType = kNotUsed; } static bool clearPredecessorVector(struct CompilationUnit *cUnit, struct BasicBlock *bb) { dvmClearAllBits(bb->predecessors); return false; } /** * @brief Check if a BasicBlock has a restricted instruction for a loop * Certain opcodes cannot be included in a loop formation (in the nonFixableOpcodes array) * Certain opcodes can be "fixed" if the function handleFixableOpcode returns true and thus won't be cause to reject the loop * @param cUnit the CompilationUnit * @param bb the BasicBlock * @return whether or not we accept the BasicBlock in regards to the instructions */ static bool checkBBInstructionsForCFGLoop (CompilationUnit *cUnit, BasicBlock *bb) { //Non fixable opcodes: tested against the bb's MIR instructions //If present, there is nothing we can do about it static unsigned int nonFixableOpcodes[] = { OP_RETURN_VOID, OP_RETURN, OP_RETURN_WIDE, OP_RETURN_OBJECT, OP_MONITOR_ENTER, OP_MONITOR_EXIT, OP_NEW_INSTANCE, OP_NEW_ARRAY, OP_THROW, OP_RETURN_VOID_BARRIER, OP_BREAKPOINT, OP_THROW_VERIFICATION_ERROR, //We reject virtual/interface invokes because we have no mechanism yet for method prediction. //Thus we prefer that we get the trace which has the runtime prediction. OP_INVOKE_VIRTUAL, OP_INVOKE_VIRTUAL_RANGE, OP_INVOKE_VIRTUAL_QUICK, OP_INVOKE_VIRTUAL_QUICK_RANGE, OP_INVOKE_INTERFACE, OP_INVOKE_INTERFACE_RANGE, }; //Go through each instruction unsigned int nbr = sizeof (nonFixableOpcodes) / sizeof (nonFixableOpcodes[0]); for (MIR *mir = bb->firstMIRInsn; mir != 0; mir = mir->next) { //Go through each non supported instructions for (unsigned int i = 0; i < nbr; i++) { //If we don't support it, just quit if (mir->dalvikInsn.opcode == nonFixableOpcodes[i]) { if (cUnit->printMe == true) { ALOGD("JIT_INFO: Loop trace @ offset %04x not a loop: unsupported opcode in loop : %s", cUnit->entryBlock->startOffset, dexGetOpcodeName(mir->dalvikInsn.opcode)); } return false; } } } //If we got here we are good to go return true; } /** * @brief Accept a CFG as a loop (Helper function) * @param cUnit the CompilationUnit * @param bb the BasicBlock * @return whether or not the trace is a loop but acceptCFGLoops must still check min and max */ static bool acceptCFGLoopsHelper (CompilationUnit *cUnit, BasicBlock *bb) { //Paranoid check if (bb == 0) { return true; } //Visited check if (bb->visited == true) { return true; } //Color it now bb->visited = true; //If hidden, we stop if (bb->hidden == true) { return true; } //Check instructions: add the restrictive, we will try to inline later bool res = checkBBInstructionsForCFGLoop (cUnit, bb); //If it says no, we say no if (res == false) { return false; } //Now mark it as a BasicBlock of the loop dvmCompilerSetBit(cUnit->tempBlockV, bb->id); //Now recurse res = acceptCFGLoopsHelper (cUnit, bb->taken) && acceptCFGLoopsHelper (cUnit, bb->fallThrough); //Return it, whatever it is return res; } /** * @brief Go from the BasicBlock cur to its predecessors, up until first * @param cUnit the CompilationUnit * @param cur the current BasicBlock * @param first the start of the loop */ static void climbTheLoopHelper (CompilationUnit *cUnit, BasicBlock *cur, const BasicBlock *first) { BitVectorIterator bvIterator; //Paranoid assert (cur != 0 && cur->predecessors != 0); //Have we visited it yet: normally redundant but paranoid if (cur->visited == true) { return; } cur->visited = true; //Unhide the current block cur->hidden = false; //Are we done? if (cur == first) { return; } //Get predecessors dvmBitVectorIteratorInit(cur->predecessors, &bvIterator); while (true) { //Get the next iterator int blockIdx = dvmBitVectorIteratorNext(&bvIterator); //If it is finished, exit if (blockIdx == -1) { break; } BasicBlock *predBB = (BasicBlock*) (dvmGrowableListGetElement(&cUnit->blockList, blockIdx)); //Paranoid if (predBB == 0) { break; } //We found a trail, enable it from first if (predBB->taken == cur) { predBB->taken->hidden = false; } else { //Then it must be fallThrough assert (predBB->fallThrough == cur); predBB->fallThrough->hidden = false; } //Continue up climbTheLoopHelper (cUnit, predBB, first); } } /* * @brief Go from the BasicBlock cur downwards to bottom but bail at notLoop * @param cUnit the CompilationUnit * @param cur the current BasicBlock * @param bottom the end of the loop * @param notLoop the exit of the loop */ static void descendTheLoopHelper (CompilationUnit *cUnit, BasicBlock *cur, BasicBlock *bottom, BasicBlock *notLoop) { //If nil, or notLoop if (cur == 0 || cur == notLoop) { return; } //Have we visited it yet: normally redundant but paranoid if (cur->visited == true) { return; } cur->visited = true; //Unhide the current block cur->hidden = false; //Are we done? if (cur == bottom) { return; } //Now call children descendTheLoopHelper (cUnit, cur->taken, bottom, notLoop); descendTheLoopHelper (cUnit, cur->fallThrough, bottom, notLoop); } /** * @brief Walk the loop from its predecessors that form the loop * @param cUnit the CompilationUnit * @param bb the BasicBlock that is the start of the loop */ static bool walkTheLoop (CompilationUnit *cUnit, BasicBlock *bb) { //Get first BasicBlock of the loop BasicBlock *first = cUnit->entryBlock->fallThrough; //Is it a backward branch if (bb->loopTraversalType.walkBackward == true) { climbTheLoopHelper (cUnit, bb, first); //Now what can happen is that we have inter-twined loops, //So actually now hide again any child of bb that is not the first if (bb->taken != 0 && bb->taken != first) { bb->taken->hidden = true; } if (bb->fallThrough != 0 && bb->fallThrough != first) { bb->fallThrough->hidden = true; } } else { //Or is it a forward loop if (bb->loopTraversalType.walkForward == true) { //A BB could be both, but we reject the double case if we are walking backwards //To the first BB if (bb->loopTraversalType.walkBackward == true && (bb->taken == first || bb->fallThrough == first)) { return false; } //Find the notLoop BasicBlock *notLoop = bb->taken; if (notLoop == first) { notLoop = bb->fallThrough; } descendTheLoopHelper (cUnit, first, bb, notLoop); } } return false; } /** * @brief Clear visited and hide dispatched function * @param cUnit the CompilationUnit * @param bb the current BasicBlock * @return returns true to signal we changed the BasicBlock */ static bool clearVisitedAndHide (CompilationUnit *cUnit, BasicBlock *bb) { bb->visited = false; bb->hidden = true; return true; } /** * @brief Is the loop bottom formed? * @param cUnit the CompilationUnit * @param first the first BasicBlock of the trace * @return whether or not the loop is bottom formed */ static bool isBottomFormed (CompilationUnit *cUnit, BasicBlock *first) { //We still have work to do if it isn't topFormed BitVectorIterator bvIterator; //Paranoid assert (first->predecessors != 0); //Get predecessors dvmBitVectorIteratorInit(first->predecessors, &bvIterator); while (true) { //Get the next iterator int blockIdx = dvmBitVectorIteratorNext(&bvIterator); //If it is finished, exit if (blockIdx == -1) { break; } BasicBlock *predBB = (BasicBlock*) (dvmGrowableListGetElement(&cUnit->blockList, blockIdx)); if (predBB == 0) { continue; } //If predBB is first, we can skip it if (first == predBB) { continue; } //Is the predBB kDalvikByteCode, one child must be towards first if (predBB->blockType == kDalvikByteCode) { if (predBB->taken == first) { if (predBB->fallThrough == 0 || predBB->fallThrough->hidden == false) { return false; } } else { if (predBB->fallThrough == first) { if (predBB->taken == 0 || predBB->taken->hidden == false) { return false; } } } } } return true; } bool acceptOldLoops (CompilationUnit *cUnit) { BasicBlock *firstBB = cUnit->entryBlock->fallThrough; /* Record blocks included in the loop */ dvmClearAllBits(cUnit->tempBlockV); dvmCompilerSetBit(cUnit->tempBlockV, cUnit->entryBlock->id); dvmCompilerSetBit(cUnit->tempBlockV, firstBB->id); BasicBlock *bodyBB = firstBB; /* * First try to include the fall-through block in the loop, then the taken * block. Stop loop formation on the first backward branch that enters the * first block (ie only include the inner-most loop). */ while (true) { /* Loop formed */ if (bodyBB->taken == firstBB) { /* Check if the fallThrough edge will cause a nested loop */ if (bodyBB->fallThrough && dvmIsBitSet(cUnit->tempBlockV, bodyBB->fallThrough->id)) { return false; } /* Single loop formed */ break; } else if (bodyBB->fallThrough == firstBB) { /* Check if the taken edge will cause a nested loop */ if (bodyBB->taken && dvmIsBitSet(cUnit->tempBlockV, bodyBB->taken->id)) { return false; } /* Single loop formed */ break; } /* Inner loops formed first - quit */ if (bodyBB->fallThrough && dvmIsBitSet(cUnit->tempBlockV, bodyBB->fallThrough->id)) { return false; } if (bodyBB->taken && dvmIsBitSet(cUnit->tempBlockV, bodyBB->taken->id)) { return false; } if (bodyBB->fallThrough) { if (bodyBB->fallThrough->iDom == bodyBB) { bodyBB = bodyBB->fallThrough; dvmCompilerSetBit(cUnit->tempBlockV, bodyBB->id); /* * Loop formation to be detected at the beginning of next * iteration. */ continue; } } if (bodyBB->taken) { if (bodyBB->taken->iDom == bodyBB) { bodyBB = bodyBB->taken; dvmCompilerSetBit(cUnit->tempBlockV, bodyBB->id); /* * Loop formation to be detected at the beginning of next * iteration. */ continue; } } /* * Current block is not the immediate dominator of either fallthrough * nor taken block - bail out of loop formation. */ return false; } //Loop accepted return true; } /** * @brief Accept a CFG as a loop * @param cUnit the CompilationUnit * @return whether or not the trace is a loop */ static bool acceptCFGLoops (CompilationUnit *cUnit) { BasicBlock *first = cUnit->entryBlock->fallThrough; //Clear visiting flags dvmCompilerDataFlowAnalysisDispatcher(cUnit, clearVisitedAndHide, kAllNodes, false /* isIterative */); //We must go through the list by hand because the dispatcher looks at hidden and we set it to true GrowableListIterator iterator; dvmGrowableListIteratorInit(&cUnit->blockList, &iterator); while (true) { BasicBlock *bb = (BasicBlock *) dvmGrowableListIteratorNext(&iterator); //Paranoid if (bb == NULL) { break; } //Ok, either it is the first, or it goes towards the first if (bb != first && bb->taken != first && bb->fallThrough != first) { continue; } //Call back to walk the loop: we only care about the outer loop walkTheLoop (cUnit, bb); } //Unhide the entry cUnit->entryBlock->hidden = false; //We have a loop if first->taken or first->fallThrough are not hidden and we aren't either bool res = first->hidden; if (res == true) { if (cUnit->printMe == true) { ALOGD("JIT_INFO: Loop trace @ offset %04x not a loop: first BB hidden", cUnit->entryBlock->startOffset); } return false; } //Otherwise, look at the children res = (first->taken != 0 && first->taken->hidden == false) || (first->fallThrough != 0 && first->fallThrough->hidden == false); if (res == false) { if (cUnit->printMe == true) { ALOGD("JIT_INFO: Loop trace @ offset %04x not a loop: children of first BB hidden", cUnit->entryBlock->startOffset); } return false; } //Clear bits dvmClearAllBits (cUnit->tempBlockV); //Reset flags dvmCompilerDataFlowAnalysisDispatcher(cUnit, dvmCompilerClearVisitedFlag, kAllNodes, false); //Call the helper bool found = acceptCFGLoopsHelper (cUnit, cUnit->entryBlock); //Ok, if the acceptance returned false, we are done if (found == false) { // message logged above return false; } //Final step check if it is top formed or bottom formed bool topFormed = (first->taken != 0 && first->taken->hidden == true) || (first->fallThrough != 0 && first->fallThrough->hidden == true); if (topFormed == false) { //If it isn't top formed, it must be bottom formed bool res = isBottomFormed (cUnit, first); if (res == false && cUnit->printMe == true) { ALOGD("JIT_INFO: Loop trace @ offset %04x not a loop: not top or bottom formed", cUnit->entryBlock->startOffset); } return res; } return true; } bool dvmCompilerFilterLoopBlocks(CompilationUnit *cUnit) { BasicBlock *firstBB = cUnit->entryBlock->fallThrough; //We should only have one exit chaining cell of the loop bool normalChainingAdded = false; int numPred = dvmCountSetBits(firstBB->predecessors); /* * A loop body should have at least two incoming edges. */ if (numPred < 2) { if (cUnit->printMe == true) { ALOGD("JIT_INFO: Loop trace @ offset %04x not a loop: only one predecessor", cUnit->entryBlock->startOffset); } return false; } //Let us see if we can accept the loop //We have two loop acceptance systems: the new system and the old one, which one do we want? bool acceptIt = false; if (gDvmJit.oldLoopDetection == false) { acceptIt = acceptCFGLoops (cUnit); } else { acceptIt = acceptOldLoops (cUnit); } //If the acceptance bailed on us, we bail as well if (acceptIt == false) { return false; } /* Now mark blocks not included in the loop as hidden */ GrowableList *blockList = &cUnit->blockList; GrowableListIterator iterator; dvmGrowableListIteratorInit(blockList, &iterator); while (true) { BasicBlock *bb = (BasicBlock *) dvmGrowableListIteratorNext(&iterator); if (bb == NULL) break; if (!dvmIsBitSet(cUnit->tempBlockV, bb->id)) { bb->hidden = true; /* Clear the insn list */ bb->firstMIRInsn = bb->lastMIRInsn = NULL; resetBlockEdges(bb); } } dvmCompilerDataFlowAnalysisDispatcher(cUnit, clearPredecessorVector, kAllNodes, false /* isIterative */); dvmGrowableListIteratorInit(blockList, &iterator); while (true) { BasicBlock *bb = (BasicBlock *) dvmGrowableListIteratorNext(&iterator); if (bb == NULL) break; if (dvmIsBitSet(cUnit->tempBlockV, bb->id)) { if (bb->taken) { /* * exit block means we run into control-flow that we don't want * to handle. */ if (bb->taken == cUnit->exitBlock) { if (cUnit->printMe == true) { ALOGD("JIT_INFO: Loop trace @ offset %04x taken branch to exit block", cUnit->entryBlock->startOffset); } return false; } if (bb->taken->hidden) { //We should only be adding one loop exit if (normalChainingAdded == true) { if (cUnit->printMe == true) { ALOGD("JIT_INFO: Loop trace @ offset %04x more than one loop exit", cUnit->entryBlock->startOffset); } return false; } bb->taken->blockType = kChainingCellNormal; normalChainingAdded = true; bb->taken->hidden = false; //We unhide some BB, so we need to clear its predecessor info clearPredecessorVector (cUnit, bb->taken); } dvmCompilerSetBit(bb->taken->predecessors, bb->id); } if (bb->fallThrough) { /* * exit block means we run into control-flow that we don't want * to handle. */ if (bb->fallThrough == cUnit->exitBlock) { if (cUnit->printMe == true) { ALOGD("JIT_INFO: Loop trace @ offset %04x fallthrough to exit block", cUnit->entryBlock->startOffset); } return false; } if (bb->fallThrough->hidden) { //We should only be adding one loop exit if (normalChainingAdded == true) { if (cUnit->printMe == true) { ALOGD("JIT_INFO: Loop trace @ offset %04x fallthrough to more than one loop exit", cUnit->entryBlock->startOffset); } return false; } bb->fallThrough->blockType = kChainingCellNormal; normalChainingAdded = true; bb->fallThrough->hidden = false; //We unhide some BB, so we need to clear its predecessor info clearPredecessorVector (cUnit, bb->fallThrough); } dvmCompilerSetBit(bb->fallThrough->predecessors, bb->id); } /* Loop blocks shouldn't contain any successor blocks (yet) */ assert(bb->successorBlockList.blockListType == kNotUsed); } } return true; } #ifdef ARCH_IA32 /* * Main entry point to do loop, trace, method optimizations * Name is remaining the same as ARM for the moment... */ bool dvmCompilerLoopOpt(CompilationUnit *cUnit) { dvmCompilerLaunchPassDriver (cUnit); return true; } #else #ifdef DEBUG_LOOP_ON /* Debugging routines */ static void dumpConstants(CompilationUnit *cUnit) { int i; ALOGE("LOOP starting offset: %x", cUnit->entryBlock->startOffset); for (i = 0; i < cUnit->numSSARegs; i++) { if (dvmIsBitSet(cUnit->isConstantV, i)) { int subNReg = dvmConvertSSARegToDalvik(cUnit, i); ALOGE("CONST: s%d(v%d_%d) has %d", i, DECODE_REG(subNReg), DECODE_SUB(subNReg), (*cUnit->constantValues)[i]); } } } static void dumpIVList(CompilationUnit *cUnit) { unsigned int i; GrowableList *ivList = cUnit->loopAnalysis->ivList; for (i = 0; i < ivList->numUsed; i++) { InductionVariableInfo *ivInfo = (InductionVariableInfo *) ivList->elemList[i]; int iv = dvmConvertSSARegToDalvik(cUnit, ivInfo->ssaReg); /* Basic IV */ if (ivInfo->ssaReg == ivInfo->basicSSAReg) { ALOGE("BIV %d: s%d(v%d_%d) + %d", i, ivInfo->ssaReg, DECODE_REG(iv), DECODE_SUB(iv), ivInfo->loopIncrement); /* Dependent IV */ } else { int biv = dvmConvertSSARegToDalvik(cUnit, ivInfo->basicSSAReg); ALOGE("DIV %d: s%d(v%d_%d) = %d * s%d(v%d_%d) + %d", i, ivInfo->ssaReg, DECODE_REG(iv), DECODE_SUB(iv), ivInfo->m, ivInfo->basicSSAReg, DECODE_REG(biv), DECODE_SUB(biv), ivInfo->constant); } } } static void dumpHoistedChecks(CompilationUnit *cUnit) { LoopAnalysis *loopAnalysis = cUnit->loopAnalysis; unsigned int i; for (i = 0; i < loopAnalysis->arrayAccessInfo->numUsed; i++) { ArrayAccessInfo *arrayAccessInfo = GET_ELEM_N(loopAnalysis->arrayAccessInfo, ArrayAccessInfo*, i); int arrayReg = DECODE_REG( dvmConvertSSARegToDalvik(cUnit, arrayAccessInfo->arrayReg)); int idxReg = DECODE_REG( dvmConvertSSARegToDalvik(cUnit, arrayAccessInfo->ivReg)); ALOGE("Array access %d", i); ALOGE(" arrayReg %d", arrayReg); ALOGE(" idxReg %d", idxReg); ALOGE(" endReg %d", loopAnalysis->endConditionReg); ALOGE(" maxC %d", arrayAccessInfo->maxC); ALOGE(" minC %d", arrayAccessInfo->minC); ALOGE(" opcode %d", loopAnalysis->loopBranchOpcode); } } #endif /* * Main entry point to do loop optimization. * Return false if sanity checks for loop formation/optimization failed. */ bool dvmCompilerLoopOpt(CompilationUnit *cUnit) { LoopAnalysis *loopAnalysis = (LoopAnalysis *)dvmCompilerNew(sizeof(LoopAnalysis), true); cUnit->loopAnalysis = loopAnalysis; dvmCompilerDataFlowAnalysisDispatcher(cUnit, dvmCompilerDoConstantPropagation, kAllNodes, false /* isIterative */); DEBUG_LOOP(dumpConstants(cUnit);) /* Find induction variables - basic and dependent */ loopAnalysis->ivList = (GrowableList *)dvmCompilerNew(sizeof(GrowableList), true); dvmInitGrowableList(loopAnalysis->ivList, 4); loopAnalysis->isIndVarV = dvmCompilerAllocBitVector(cUnit->numSSARegs, false); dvmCompilerDataFlowAnalysisDispatcher(cUnit, dvmCompilerFindInductionVariables, kAllNodes, false /* isIterative */); DEBUG_LOOP(dumpIVList(cUnit);) /* Only optimize array accesses for simple counted loop for now */ if (!isSimpleCountedLoop(cUnit)) return false; loopAnalysis->arrayAccessInfo = (GrowableList *)dvmCompilerNew(sizeof(GrowableList), true); dvmInitGrowableList(loopAnalysis->arrayAccessInfo, 4); loopAnalysis->bodyIsClean = doLoopBodyCodeMotion(cUnit); DEBUG_LOOP(dumpHoistedChecks(cUnit);) /* * Convert the array access information into extended MIR code in the loop * header. */ genHoistedChecks(cUnit); return true; } /* * Select the target block of the backward branch. */ bool dvmCompilerInsertBackwardChaining(CompilationUnit *cUnit) { /* * If we are not in self-verification or profiling mode, the backward * branch can go to the entryBlock->fallThrough directly. Suspend polling * code will be generated along the backward branch to honor the suspend * requests. */ #ifndef ARCH_IA32 #if !defined(WITH_SELF_VERIFICATION) if (gDvmJit.profileMode != kTraceProfilingContinuous && gDvmJit.profileMode != kTraceProfilingPeriodicOn) { return false; } #endif #endif /* * In self-verification or profiling mode, the backward branch is altered * to go to the backward chaining cell. Without using the backward chaining * cell we won't be able to do check-pointing on the target PC, or count the * number of iterations accurately. */ BasicBlock *firstBB = cUnit->entryBlock->fallThrough; BasicBlock *backBranchBB = findPredecessorBlock(cUnit, firstBB); //Backward branching can fail if findPredecessorBlock returns 0, if it does report the failure if (backBranchBB == NULL) { return false; } if (backBranchBB->taken == firstBB) { backBranchBB->taken = cUnit->backChainBlock; } else { //Paranoid: if fallThrough is not firstBB, we have an issue: neither taken or fallthrough went to firstBB... if (backBranchBB->fallThrough != firstBB) { //Report it as a failure return false; } backBranchBB->fallThrough = cUnit->backChainBlock; } cUnit->backChainBlock->startOffset = firstBB->startOffset; //Report success return true; } #endif /** * @brief Recursive function to find the minimum offset of a loop: it is located in the BasicBlock with the smallest startOffset * @param cUnit the CompilationUnit * @param bb the current BasicBlock * @return the minimum offset BasicBlock */ static BasicBlock *findMinimumHelper (CompilationUnit *cUnit, BasicBlock *bb) { //If null, not dalvik byte code, or visited, return 0 if (bb == 0 || (bb->blockType != kDalvikByteCode) || (bb->visited == true)) { return 0; } //Mark it bb->visited = true; //Paranoid if (bb->predecessors == 0) { return 0; } //Suppose the minimum is bb BasicBlock *min = bb; //Go through the predecessors BitVectorIterator bvIterator; dvmBitVectorIteratorInit(bb->predecessors, &bvIterator); while (true) { int blockIdx = dvmBitVectorIteratorNext(&bvIterator); if (blockIdx == -1) { break; } BasicBlock *predBB = (BasicBlock *) dvmGrowableListGetElement(&cUnit->blockList, blockIdx); BasicBlock *curMin = findMinimumHelper (cUnit, predBB); if (curMin != 0 && curMin->startOffset < min->startOffset) { min = curMin; } } //Return minium return min; } /** * @brief Function to the minimum offset of a loop * @param cUnit the CompilationUnit * @return the minimum offset BasicBlock of cUnit */ static BasicBlock *findMinimum (CompilationUnit *cUnit) { //Reset flags dvmCompilerDataFlowAnalysisDispatcher(cUnit, dvmCompilerClearVisitedFlag, kAllNodes, false); //Call recursive function return findMinimumHelper (cUnit, cUnit->entryBlock->fallThrough); } /** * @brief Mark the BasicBlock in the loop cache * The loop cache is used to know if an offset is a loop head or not. It helps reduce compilation time. * The loop cache contains all the BasicBlocks that are NOT loop heads * @param cUnit the CompilationUnit * @param bb the BasicBlock * @return returns false, the function does not change the BasicBlock */ static bool markBasicBlocksInLoopCache (CompilationUnit *cUnit, BasicBlock *bb) { //Only care about dalvik byte code if (bb->blockType == kDalvikByteCode) { gDvmJit.knownNonLoopHeaderCache[cUnit->method->insns + bb->startOffset]; } //We did not change anything to bb return false; } /** * @brief Mark off any BasicBlock, which is not a loop header * @param cUnit the CompilationUnit * @param bb the BasicBlock * @return always return false, we don't change the BasicBlock */ static bool markOffNonHeadersHelper (CompilationUnit *cUnit, BasicBlock *bb) { BitVectorIterator bvIterator; //Paranoid assert (bb->predecessors != 0); //Get predecessors dvmBitVectorIteratorInit(bb->predecessors, &bvIterator); //Only mark off BasicBlocks that are dalvik code if (bb->blockType != kDalvikByteCode) { return false; } //Did we find a BasicBlock being a backward branch while (true) { //Get the next iterator int blockIdx = dvmBitVectorIteratorNext(&bvIterator); //If it is finished, exit if (blockIdx == -1) { break; } BasicBlock *predBB = (BasicBlock*) (dvmGrowableListGetElement(&cUnit->blockList, blockIdx)); //Paranoid if (predBB == 0) { break; } //If no dominator information, skip it if (predBB->dominators == 0) { continue; } //If the predecessor is dominated by this one, it is a backward branch if (dvmIsBitSet (predBB->dominators, bb->id) == true) { unsigned int entryOffset = cUnit->entryBlock->startOffset; //Now here are some assumptions: // If bb is the startOffset of cUnit->entryBlock, it is the original head if (entryOffset == bb->startOffset) { predBB->loopTraversalType.walkBackward = true; predBB->loopTraversalType.relativeTo = bb; } else { //Now the if handled top loop cases where the head of the loop is //actually the head of the trace. Sometimes it happens that the branch //into the loop is the head. Check this here //First do we have only one branch towards it: if (bb->taken != 0 && bb->fallThrough == 0 && bb->taken->startOffset == entryOffset) { bb->loopTraversalType.walkForward = true; bb->loopTraversalType.relativeTo = bb->taken; } else { //Same but the other side if (bb->fallThrough != 0 && bb->taken == 0 && bb->fallThrough->startOffset == entryOffset) { bb->loopTraversalType.walkForward = true; bb->loopTraversalType.relativeTo = bb->fallThrough; } else { //Otherwise, we have two children and that means this is exiting the loop bb->loopTraversalType.walkBackward = true; bb->loopTraversalType.relativeTo = predBB; } } } //Now mark it as a potential loop head and its children gDvmJit.knownNonLoopHeaderCache.erase (cUnit->method->insns + bb->startOffset); //Now we mark both children because we don't know which one is towards a loop //A subsequent call will handle it if (bb->taken != 0) { if (dvmIsBitSet (predBB->dominators, bb->taken->id) == true) { gDvmJit.knownNonLoopHeaderCache.erase (cUnit->method->insns + bb->taken->startOffset); } } if (bb->fallThrough != 0) { if (dvmIsBitSet (predBB->dominators, bb->fallThrough->id) == true) { gDvmJit.knownNonLoopHeaderCache.erase (cUnit->method->insns + bb->fallThrough->startOffset); } } } } //We did not change the BasicBlock return false; } /** * @brief Clear predecessor information * @param cUnit the CompilationUnit * @param bb the BasicBlock * @return returns whether we changed something in the BasicBlock or not */ static bool clearPredecessors (CompilationUnit *cUnit, BasicBlock *bb) { //We only need to set it if there is a bit set, //normally we wouldn't care about this test but the dispatcher might care if (dvmCountSetBits (bb->predecessors) != 0) { dvmClearAllBits (bb->predecessors); return true; } return false; } /** * @brief Calculate Predecessor Information Helper * @param cUnit the CompilationUnit * @param bb the BasicBlock * @return returns false, the BasicBlock is not changed */ static bool calculatePredecessorsHelper (CompilationUnit *cUnit, BasicBlock *bb) { //We only care about non hidden blocks if (bb->hidden == true) { return false; } //Create iterator for visiting children ChildBlockIterator childIter (bb); //Now iterate through the children to set the predecessor bits for (BasicBlock **childPtr = childIter.getNextChildPtr (); childPtr != 0; childPtr = childIter.getNextChildPtr ()) { BasicBlock *child = *childPtr; assert (child != 0); dvmCompilerSetBit (child->predecessors, bb->id); } //We did change something but not our own basic block return false; } /** * @brief Calculate Predecessor Information * @param cUnit the CompilationUnit */ void dvmCompilerCalculatePredecessors (CompilationUnit *cUnit) { //First job is to clear the predecessors dvmCompilerDataFlowAnalysisDispatcher (cUnit, clearPredecessors, kAllNodes, false); //Second part is to calculate them again dvmCompilerDataFlowAnalysisDispatcher (cUnit, calculatePredecessorsHelper, kAllNodes, false); } /** * @brief Mark off BasicBlocks from the loop cache * @param cUnit the CompilationUnit */ void dvmCompilerLoopMarkOffNonHeaderBlocks (CompilationUnit *cUnit) { //Recalculate the predecessors with this new formation dvmCompilerCalculatePredecessors (cUnit); //Find the minimum offset BasicBlock *minimum = findMinimum (cUnit); //Now entry should temporarily go to the minimum BasicBlock *tmpEntry = cUnit->entryBlock->fallThrough; cUnit->entryBlock->fallThrough = minimum; //Recalculate the predecessors with this new formation dvmCompilerCalculatePredecessors (cUnit); //Ok, now we can calculate dominators dvmCompilerBuildDomination (cUnit); //Clear the temporary bits dvmClearAllBits (cUnit->tempBlockV); dvmCompilerDataFlowAnalysisDispatcher(cUnit, markBasicBlocksInLoopCache, kAllNodes, false /* isIterative */); //Now we can go through the BasicBlocks and mark off those that are not loops dvmCompilerDataFlowAnalysisDispatcher(cUnit, markOffNonHeadersHelper, kAllNodes, false /* isIterative */); //Put it back as it was, and recalculate the predecessors cUnit->entryBlock->fallThrough = tmpEntry; dvmCompilerCalculatePredecessors (cUnit); //Domination is done later so no need here } #ifdef ARCH_IA32 /** * @brief Looks through backward's predecessors and inserts a new block in * between. It also ensures that new block is the taken branch and flips * condition in bytecode if needed. * @details Creates a new block and copies relevant information from backward. * @param cUnit the Compilation Unit * @param backward the backward branch chaining cell */ static void insertBlockBeforeBackwardHelper (CompilationUnit *cUnit, BasicBlock *backward) { //Checking preconditions assert(backward != 0); //Only insert prebackward if backward branch CC is involved if (backward->blockType != kChainingCellBackwardBranch) { return; } BitVector *predecessors = backward->predecessors; //Paranoid if (predecessors == 0) { return; } //Ok, there is currently no way a backward branch can have more than one predecessor //Something went terribly wrong if it did, so get out //Note that if we remove this check we need to revisit to code below, cosidering loop //over predecessors. if (dvmCountSetBits (predecessors) != 1) { PASS_LOG (ALOGD, cUnit, "JIT_INFO: Backward branch has more than one predecessor"); cUnit->quitLoopMode = true; return; } // We have only one predecessor so take it int blockIdx = dvmHighestBitSet (predecessors); //Get the predecessor block BasicBlock *predecessor = reinterpret_cast<BasicBlock *> (dvmGrowableListGetElement ( &cUnit->blockList, blockIdx)); //Paranoid assert (predecessor != 0); //Create a preBackward block BasicBlock *preBackward = dvmCompilerNewBBinCunit (cUnit, kPreBackwardBlock); //Paranoid assert(preBackward != 0); //Now we copy the relevant parts preBackward->startOffset = backward->startOffset; preBackward->firstMIRInsn = backward->firstMIRInsn; preBackward->lastMIRInsn = backward->lastMIRInsn; preBackward->containingMethod = backward->containingMethod; //We also need to make a copy of the write back requests preBackward->requestWriteBack = dvmCompilerAllocBitVector (1, true); dvmCopyBitVector (preBackward->requestWriteBack, backward->requestWriteBack); //We want the new block to be the taken branch. //So if backward used to be the fallthrough, make it the taken. if(predecessor->fallThrough == backward) { MIR *ifMir = predecessor->lastMIRInsn; //It is unexpected if we have a null MIR, so bail out if (ifMir == 0) { cUnit->quitLoopMode = true; return; } //Paranoid, we should have an if at the end assert(ifMir != 0 && ifMir->dalvikInsn.opcode >= OP_IF_EQ && ifMir->dalvikInsn.opcode <= OP_IF_LEZ); Opcode negated; bool canNegate = negateOpcode (ifMir->dalvikInsn.opcode, negated); //If we can negate the bytecode condition, then we can swap //the children if (canNegate == true) { //Update opcode ifMir->dalvikInsn.opcode = negated; //Set the fallthrough to be the old taken dvmCompilerReplaceChildBasicBlock (predecessor->taken, predecessor, kChildTypeFallthrough); //Make the backward be the new taken dvmCompilerReplaceChildBasicBlock (backward, predecessor, kChildTypeTaken); } } //Insert the preBackward block between predecessor and backward CC bool res = dvmCompilerInsertBasicBlockBetween (preBackward, predecessor, backward); //If we failed inserting, that's not good and we bail out if (res == false) { cUnit->quitLoopMode = true; return; } //Clear fields from backward backward->firstMIRInsn = 0; backward->lastMIRInsn = 0; //Update parent of the MIRs for (MIR *mir = preBackward->firstMIRInsn; mir != 0; mir = mir->next) { mir->bb = preBackward; } } /** * @brief Finds all of the backward branch chaining cells and then inserts * a block before each of them. * @param cUnit the Compilation Unit * @param info the information of Loop we are looking at * @param data required by interface (not used) * @return true to continue iteration over loops */ static bool insertBlockBeforeBackward (CompilationUnit *cUnit, LoopInformation *info, void *data = 0) { //We want to look through all of the backward chaining cells const BitVector *backwards = info->getBackwardBranches (); //Const cast due to incompatibility here BitVector *tmp = const_cast<BitVector *> (backwards); //Initialize iterator BitVectorIterator bvIterator; dvmBitVectorIteratorInit (tmp, &bvIterator); while (true) { //Get the block index int blockIdx = dvmBitVectorIteratorNext (&bvIterator); //Break if we are done if (blockIdx == -1) { break; } //Get the backward block BasicBlock *backward = reinterpret_cast<BasicBlock *> (dvmGrowableListGetElement ( &cUnit->blockList, blockIdx)); //Paranoid if (backward == 0) { continue; } insertBlockBeforeBackwardHelper (cUnit, backward); } return true; } /** * @brief Add a block before the preheader of type kFromInterpreter * @param cUnit the Compilation Unit * @param info the information of Loop we are looking at * @param data required by interface (not used) * @return true to continue iteration over loops */ static bool insertBlockFromInterpreter (CompilationUnit *cUnit, LoopInformation *info, void *data) { //Get the preheader BasicBlock *preHeader = info->getPreHeader (); //Get one of the backward blocks since we want to get offset from it int backwardIdx = dvmHighestBitSet (info->getBackwardBranches ()); BasicBlock *backward = reinterpret_cast<BasicBlock *> (dvmGrowableListGetElement (&cUnit->blockList, backwardIdx)); assert (backward != 0); if (backward == 0) { PASS_LOG (ALOGD, cUnit, "Insert_LoopHelper_Blocks: FromInterpreter cannot be properly inserting " "without offset from backward CC."); cUnit->quitLoopMode = true; return false; } if (preHeader != 0) { //Also add a from interpreter node BasicBlock *fromInterpreter = dvmCompilerNewBBinCunit (cUnit, kFromInterpreter); //Set the correct offset fromInterpreter->startOffset = backward->startOffset; //Link fromInterpreter to preHeader dvmCompilerReplaceChildBasicBlock (preHeader, fromInterpreter, kChildTypeFallthrough); } //Unused parameter (void) data; //Continue iterating return true; } /** * @brief Inserts a basic block before Backward Chaining Cell and one before the preheader. * @details The newly inserted basic blocks takes the write back requests and * MIRs from chaining cell in order to help backend which cannot handle * Backward Chaining Cell like a bytecode block. It also ensures that the * newly inserted block is the taken branch, so if the backward was fallthrough * it flips the condition. * @param cUnit the CompilationUnit * @param currentPass the Pass */ void dvmCompilerInsertLoopHelperBlocks (CompilationUnit *cUnit, Pass *currentPass) { //Now let's go through the loop information LoopInformation *info = cUnit->loopInformation; //If info is 0, there is nothing to do if (info == 0) { return; } //Actually do the work info->iterate (cUnit, insertBlockBeforeBackward); //Now do it for the from interpreter info->iterate (cUnit, insertBlockFromInterpreter); //Unused argument (void) currentPass; } #endif
34.159792
152
0.587969
c207f71a6fd127e7e6284e909bba8ab6efdf6876
283
cpp
C++
src/TextureManager.cpp
ArionasMC/Asteroids
b5a81f833af1615ede2706bfe41baa8b661fa209
[ "Apache-2.0" ]
3
2019-02-23T18:20:24.000Z
2019-02-23T18:30:18.000Z
src/TextureManager.cpp
ArionasMC/Asteroids
b5a81f833af1615ede2706bfe41baa8b661fa209
[ "Apache-2.0" ]
null
null
null
src/TextureManager.cpp
ArionasMC/Asteroids
b5a81f833af1615ede2706bfe41baa8b661fa209
[ "Apache-2.0" ]
null
null
null
#include "TextureManager.h" SDL_Texture* TextureManager::LoadTexture(const char* fileName, SDL_Renderer* ren) { SDL_Surface* tmp = IMG_Load(fileName); SDL_Texture* texture = SDL_CreateTextureFromSurface(ren, tmp); SDL_FreeSurface(tmp); return texture; }
25.727273
84
0.717314
c209b94f8e83db1255f3296bc6425698edd7cb86
976
cpp
C++
String/is_substring_hash.cpp
ShreyashRoyzada/C-plus-plus-Algorithms
9db89faf0a9b9e636aece3e7289f21ab6a1e3748
[ "MIT" ]
21
2020-10-03T03:57:19.000Z
2022-03-25T22:41:05.000Z
String/is_substring_hash.cpp
ShreyashRoyzada/C-plus-plus-Algorithms
9db89faf0a9b9e636aece3e7289f21ab6a1e3748
[ "MIT" ]
40
2020-10-02T07:02:34.000Z
2021-10-30T16:00:07.000Z
String/is_substring_hash.cpp
ShreyashRoyzada/C-plus-plus-Algorithms
9db89faf0a9b9e636aece3e7289f21ab6a1e3748
[ "MIT" ]
90
2020-10-02T07:06:22.000Z
2022-03-25T22:41:17.000Z
#include<bits/stdc++.h> using namespace std; #define ll long long ll compute_hash(string s){ const int p= 3; const int m= 1e9+9; ll hash_value= 0; ll p_pow= (ll)pow(p,s.length()-1); for(auto c:s){ hash_value= (hash_value+ (c-'a')*p_pow)%m; p_pow= p_pow/p; } return hash_value; } ll rolling_hash(ll H,string prev,char nxt) { const int p = 31; const int m = 1e9 + 9; ll Hnxt=( ( H - (prev[0]-'a')*(ll)pow(p,prev.length()-1) ) * p + (nxt-'a') ) % m; return Hnxt; } bool is_substring(string s1,string s2){ int j=0; string prev= s1.substr(j,s2.length()); j++; map<ll,int>m1,m2; ll h2= compute_hash(s2); ll h1= compute_hash(s1); m1[h1]=1; m2[h2]=1; for(int i=s2.length();i<s1.length();i++){ h1= rolling_hash(h1,prev,s1[i]); m1[h1]=1; prev=s1.substr(j,s2.length()); j++; } return m1[h2]==m2[h2]; } int main() { string s1= "iitian"; string s2= "iiti"; if(is_substring(s1,s2)) cout<<"Yes"<<endl; else cout<<"No"<<endl; }
19.918367
84
0.597336
c20b48bd40a8ae93332191ba4e3bb061a3fa2e7b
929
hpp
C++
lib/SensorNode/SHT30Node.hpp
RobAxt/SmartWeatherStation
5b756f91d6b9c8c10eab6eac1403f2362e91670c
[ "MIT" ]
null
null
null
lib/SensorNode/SHT30Node.hpp
RobAxt/SmartWeatherStation
5b756f91d6b9c8c10eab6eac1403f2362e91670c
[ "MIT" ]
null
null
null
lib/SensorNode/SHT30Node.hpp
RobAxt/SmartWeatherStation
5b756f91d6b9c8c10eab6eac1403f2362e91670c
[ "MIT" ]
null
null
null
#ifndef SHT30Node_hpp #define SHT30Node_hpp #include <Wire.h> #include <SHT3x.h> #include "SensorNode.hpp" class SHT30Node : public SensorNode { public: explicit SHT30Node(const char *id, const char *name, const int i2cAddress = 0x45); ~SHT30Node(); protected: virtual void setup() override; virtual void onReadyToOperate() override; virtual void sendMeasurement() override; virtual void takeMeasurement() override; private: const char* TMP_TOPIC = "temperature"; const char* HUM_TOPIC = "humidity"; HomieSetting<double> *_humidityFactor; HomieSetting<double> *_humidityOffset; HomieSetting<double> *_temperatureFactor; HomieSetting<double> *_temperatureOffset; SHT3x _sht30; float _temperature = NAN; float _humidity = NAN; }; #endif //SHT30Node_hpp //https://www.wemos.cc/en/latest/d1_mini_shield/sht30.html //https://github.com/Risele/SHT3x.git#master
25.805556
87
0.724435
c20c40dd4339ae0b5bff34aa20c9ac6a9d0d58dc
8,396
cpp
C++
src/Engine/Engine/Shibboleth_Image.cpp
Connway/Shibboleth
23dda9a066db8dfaf8c8d56cb1e3d9929b6ced35
[ "MIT" ]
1
2020-04-06T17:35:47.000Z
2020-04-06T17:35:47.000Z
src/Engine/Engine/Shibboleth_Image.cpp
Connway/Shibboleth
23dda9a066db8dfaf8c8d56cb1e3d9929b6ced35
[ "MIT" ]
null
null
null
src/Engine/Engine/Shibboleth_Image.cpp
Connway/Shibboleth
23dda9a066db8dfaf8c8d56cb1e3d9929b6ced35
[ "MIT" ]
null
null
null
/************************************************************************************ Copyright (C) 2021 by Nicholas LaCroix 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 "Shibboleth_Image.h" #include "Shibboleth_LogManager.h" #include "Shibboleth_Utilities.h" #include "Shibboleth_String.h" #include "Shibboleth_Vector.h" #include "Shibboleth_IApp.h" #include <Gaff_Math.h> #include <tiffio.h> #include <png.h> NS_SHIBBOLETH static ProxyAllocator g_image_allocator("Image"); static void* ImageMalloc(png_structp, png_alloc_size_t size) { return SHIB_ALLOC(size, g_image_allocator); } static void ImageFree(png_structp, void* ptr) { SHIB_FREE(ptr, g_image_allocator); } static void ImageWarning(png_structp, png_const_charp message) { LogWarningDefault("%s", message); } static void ImageError(png_structp, png_const_charp message) { LogErrorDefault("%s", message); } struct BufferData final { const void* buffer; const size_t size; size_t curr_byte_offset; }; static void PNGRead(png_structp png_ptr, png_bytep out_buffer, png_size_t out_size) { const png_voidp io_ptr = png_get_io_ptr(png_ptr); if (!io_ptr) { return; } BufferData* const buffer_data = reinterpret_cast<BufferData*>(io_ptr); const size_t read_size = Gaff::Min(buffer_data->size - buffer_data->curr_byte_offset, out_size); memcpy(out_buffer, reinterpret_cast<const int8_t*>(buffer_data->buffer) + buffer_data->curr_byte_offset, read_size); buffer_data->curr_byte_offset += read_size; } static tsize_t TIFFRead(thandle_t st, tdata_t buffer, tsize_t size) { const BufferData* const data = reinterpret_cast<const BufferData*>(st); const size_t bytes_read = Gaff::Min(static_cast<size_t>(size), data->size - data->curr_byte_offset); memcpy(buffer, data->buffer, bytes_read); return bytes_read; } static tsize_t TIFFWrite(thandle_t st, tdata_t buffer, tsize_t size) { //BufferData* const data = reinterpret_cast<BufferData*>(st); //const size_t bytes_written = Gaff::Min(static_cast<size_t>(size), data->size - data->curr_byte_offset); //memcpy(reinterpret_cast<int8_t*>(data->buffer) + data->curr_byte_offset, buffer, bytes_written); //return bytes_written; GAFF_REF(st, buffer, size); return 0; } static int TIFFClose(thandle_t) { return 0; } static toff_t TIFFSeek(thandle_t st, toff_t pos, int whence) { if (pos == 0xFFFFFFFF) { return 0xFFFFFFFF; } BufferData* const data = reinterpret_cast<BufferData*>(st); switch (whence) { case SEEK_SET: GAFF_ASSERT(pos < data->size); data->curr_byte_offset = pos; break; case SEEK_CUR: GAFF_ASSERT((data->curr_byte_offset + pos) < data->size); data->curr_byte_offset += pos; break; case SEEK_END: // Unsupported. break; } return data->curr_byte_offset; } static toff_t TIFFSize(thandle_t st) { return reinterpret_cast<const BufferData*>(st)->size; } static int TIFFMap(thandle_t st, tdata_t* buffer, toff_t* size) { BufferData* const data = reinterpret_cast<BufferData*>(st); *buffer = const_cast<void*>(data->buffer); *size = data->size; return 1; } static void TIFFError(const char* module, const char* format, va_list va) { U8String format_string; format_string.sprintf_va_list(format, va); LogErrorDefault("TIFF [%s]: %s", module, format); } static void TIFFWarning(const char* module, const char* format, va_list va) { U8String format_string; format_string.sprintf_va_list(format, va); LogWarningDefault("TIFF [%s]: %s", module, format); } static void TIFFUnmap(thandle_t, tdata_t, toff_t) { } int32_t Image::getWidth(void) const { return _width; } int32_t Image::getHeight(void) const { return _height; } int32_t Image::getBitDepth(void) const { return _bit_depth; } int32_t Image::getNumChannels(void) const { return _num_channels; } const uint8_t* Image::getBuffer(void) const { return _image.data(); } uint8_t* Image::getBuffer(void) { return _image.data(); } bool Image::load(const void* buffer, size_t size, const char* file_ext) { if (Gaff::EndsWith(file_ext, ".png")) { return loadPNG(buffer, size); } else if (Gaff::EndsWith(file_ext, ".tiff") || Gaff::EndsWith(file_ext, ".tif")) { return loadTIFF(buffer, size); } return false; } bool Image::loadTIFF(const void* buffer, size_t size) { TIFFSetWarningHandler(TIFFWarning); TIFFSetErrorHandler(TIFFError); BufferData data = { buffer, size, 0 }; TIFF* const tiff = TIFFClientOpen( "Memory", "r", &data, TIFFRead, TIFFWrite, TIFFSeek, TIFFClose, TIFFSize, TIFFMap, TIFFUnmap ); uint32_t width; uint32_t height; TIFFGetField(tiff, TIFFTAG_IMAGEWIDTH, &width); TIFFGetField(tiff, TIFFTAG_IMAGELENGTH, &height); _image.resize(static_cast<size_t>(width) * static_cast<size_t>(height) * sizeof(uint32_t)); const bool success = TIFFReadRGBAImageOriented(tiff, width, height, reinterpret_cast<uint32_t*>(_image.data()), ORIENTATION_TOPLEFT); TIFFClose(tiff); if (success) { _width = static_cast<int32_t>(width); _height = static_cast<int32_t>(height); _bit_depth = 8; _num_channels = 4; } return success; } bool Image::loadPNG(const void* buffer, size_t size) { constexpr size_t PNG_SIG_SIZE = 8; if (!png_check_sig(reinterpret_cast<png_const_bytep>(buffer), PNG_SIG_SIZE)) { return false; } png_structp png_ptr = png_create_read_struct_2(PNG_LIBPNG_VER_STRING, nullptr, ImageError, ImageWarning, nullptr, ImageMalloc, ImageFree); if (!png_ptr) { // $TODO: Log error. return false; } const png_infop info_ptr = png_create_info_struct(png_ptr); if (!info_ptr) { // $TODO: Log error. png_destroy_read_struct(&png_ptr, nullptr, nullptr); return false; } BufferData data = { buffer, size, PNG_SIG_SIZE }; png_set_read_fn(png_ptr, &data, PNGRead); // tell libpng we already read the signature png_set_sig_bytes(png_ptr, PNG_SIG_SIZE); png_read_info(png_ptr, info_ptr); png_uint_32 width = 0; png_uint_32 height = 0; int bit_depth = 0; int color_type = -1; const png_uint_32 retval = png_get_IHDR( png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, nullptr, nullptr, nullptr ); if (retval != 1) { // $TODO: Log error png_destroy_read_struct(&png_ptr, nullptr, nullptr); return false; } const png_byte num_channels = png_get_channels(png_ptr, info_ptr); const size_t bytes_per_row = png_get_rowbytes(png_ptr, info_ptr); _image.resize( static_cast<size_t>(width) * static_cast<size_t>(height) * (static_cast<size_t>(bit_depth) / 8) * static_cast<size_t>(num_channels) ); uint8_t* const start = _image.data(); for (int32_t i = 0; i < static_cast<int32_t>(height); ++i) { const size_t byte_offset = static_cast<size_t>(i) * bytes_per_row; png_read_row(png_ptr, start + byte_offset, nullptr); } png_destroy_read_struct(&png_ptr, nullptr, nullptr); _width = static_cast<int32_t>(width); _height = static_cast<int32_t>(height); _bit_depth = static_cast<int32_t>(bit_depth); _num_channels = static_cast<int32_t>(num_channels); return true; } NS_END
25.365559
140
0.699738
c20cca8b430598341fc2947ba45c9dc91f001dc4
26,399
cpp
C++
src/cpu/gemm/s8x8s32/jit_avx512_core_gemm_s8u8s32.cpp
Bil17t/mkl-dnn
8910895abc655e8e5d9d54ab91c040b26a28902d
[ "Apache-2.0" ]
6
2020-06-04T06:03:36.000Z
2022-01-27T02:41:49.000Z
src/cpu/gemm/s8x8s32/jit_avx512_core_gemm_s8u8s32.cpp
Bil17t/mkl-dnn
8910895abc655e8e5d9d54ab91c040b26a28902d
[ "Apache-2.0" ]
null
null
null
src/cpu/gemm/s8x8s32/jit_avx512_core_gemm_s8u8s32.cpp
Bil17t/mkl-dnn
8910895abc655e8e5d9d54ab91c040b26a28902d
[ "Apache-2.0" ]
3
2021-07-07T09:55:36.000Z
2022-01-12T06:59:55.000Z
/******************************************************************************* * Copyright 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 <cstdint> #include <mutex> #include "common.hpp" #include "mkldnn_types.h" #include "nstl.hpp" #include "jit_avx512_core_gemm_s8u8s32.hpp" namespace mkldnn { namespace impl { namespace cpu { enum { PARTITION_1D_ROW, PARTITION_1D_COL, PARTITION_2D_COL_MAJOR, PARTITION_2D = PARTITION_2D_COL_MAJOR, }; enum { COPY_NONE, COPY_A, }; // Alias for any dimension related variable. typedef long long int dim_t; typedef struct { // Interface arguments. int transa, transb, offsetc; dim_t m, n, k; dim_t lda, ldb, ldc; const int8_t *a; const uint8_t *b; int32_t *c; const float *alpha, *beta; int8_t ao, bo; const int32_t *co; // Kernel parameters. dim_t um, un, uk, bm, bn, bk; dim_t bn_small_k, bk_traditional, blocking_small_k; int (*copyA)(const dim_t *m, const dim_t *n, const int8_t *a, const dim_t *lda, const int8_t *alpha, int8_t *b); int (*copyB)(const dim_t *m, const dim_t *n, const uint8_t *a, const dim_t *lda, const uint8_t *alpha, uint8_t *b); int (*kernel) (const dim_t *m, const dim_t *n, const dim_t *k, const float *alpha, const int8_t *a, const uint8_t *b, int *c, const dim_t ldc); int (*kernel_b0)(const dim_t *m, const dim_t *n, const dim_t *k, const float *alpha, const int8_t *a, const uint8_t *b, int *c, const dim_t ldc); // Threading parameters. int nthrs; int nthrs_m, nthrs_n; int thread_partition; int thread_copy; } blas_t; static inline void round_to_nearest(int32_t *rounded_val, double fp_val) { if (fp_val >= 0.) { fp_val += 0.5; if (fp_val > INT32_MAX) { fp_val = INT32_MAX; } } else { fp_val -= 0.5; if (fp_val < INT32_MIN) { fp_val = INT32_MIN; } } *rounded_val = (int32_t) fp_val; } static inline void add_results(const dim_t m, const dim_t n, const dim_t k, const float alpha, const float beta, const int32_t *c_partial_sum, const dim_t ldcp, int32_t *c_data, const dim_t ldc, const int32_t *a_row_sum, const int32_t *b_col_sum, const int8_t ao, const int8_t bo, const int32_t *co, int offsetc) { for (dim_t j = 0; j < n; ++j) { for (dim_t i = 0; i < m; ++i) { int32_t ctemp = c_partial_sum[i + j * ldcp]; if (ao != 0 || bo != 0) ctemp += a_row_sum[i] * bo + b_col_sum[j] * ao + ao * bo * (int32_t) k; if (alpha == 1.0f) { if (beta == 0.0f) { c_data[i + j * ldc] = ctemp; } else { double c_float = (double) beta * (double) c_data[i + j * ldc]; c_float += (double) ctemp; round_to_nearest(&c_data[i + j * ldc], c_float); } } else if (alpha == -1.0f) { if (beta == 0.0f) { c_data[i + j * ldc] = -ctemp; } else { double c_float = (double) beta * (double) c_data[i + j * ldc]; c_float -= (double) ctemp; round_to_nearest(&c_data[i + j * ldc], c_float); } } else { if (beta == 0.0f) { double c_float = alpha * (double) ctemp; round_to_nearest(&c_data[i + j * ldc], c_float); } else { double c_float = alpha * (double) ctemp + beta * (double) c_data[i + j * ldc]; round_to_nearest(&c_data[i + j * ldc], c_float); } } if (offsetc == 0) { // Fix offset. c_data[i + j * ldc] += co[0]; } else if (offsetc == 1) { // Row offset. c_data[i + j * ldc] += co[j]; } else if (offsetc == 2) { // Col offset. c_data[i + j * ldc] += co[i]; } } } } static inline void get_a_row_sum(const int transa, const dim_t nrows, const dim_t ncols, const int8_t *a, const dim_t lda, const int8_t bo, int32_t *a_row_sum) { if (bo != 0) { dim_t strideAm = (transa == 0)? 1 : lda; dim_t strideAn = (transa != 0)? 1 : lda; for (dim_t i = 0; i < nrows; i++) { a_row_sum[i] = 0; for (dim_t j = 0; j < ncols; j++) { a_row_sum[i] += a[i * strideAm + j * strideAn]; } } } } static inline void get_b_col_sum(const int transb, const dim_t nrows, const dim_t ncols, const uint8_t *b, const dim_t ldb, const int8_t ao, int32_t *b_col_sum) { if (ao != 0) { dim_t strideBm = (transb == 0)? 1 : ldb; dim_t strideBn = (transb != 0)? 1 : ldb; for (dim_t j = 0; j < ncols; j++) { b_col_sum[j] = 0; for (dim_t i = 0; i < nrows; i++) { b_col_sum[j] += b[i * strideBm + j * strideBn]; } } } } // TODO Find a better place for those macros. #define VAL_PADD(y, x, x1) y = ((x) % (x1)) ? (((x) / (x1)) + 1) * (x1) : (x) #define LD_PADD(y,x) (y) = ((((x) + ((2048 / sizeof(int8_t)) - 1)) / (2048 / sizeof(int8_t))) * (2048 / sizeof(int8_t)) + (512 / sizeof(int8_t))); static int gemm_kernel_driver(const dim_t m, const dim_t n, const dim_t k, const int8_t *a, const uint8_t *b, int32_t *c, const int32_t *co, const blas_t *arg) { dim_t lda = arg->lda; dim_t ldb = arg->ldb; dim_t ldc = arg->ldc; int8_t ao = arg->ao; int8_t bo = arg->bo; float alpha = *arg->alpha; float beta = *arg->beta; // Padding along K dimension. dim_t k_padd = 0; if (k <= arg->bk_traditional) { VAL_PADD(k_padd, k, arg->uk); k_padd = nstl::max(128LL, k_padd); } else if (k < 2 * arg->bk) { k_padd = k / 2; VAL_PADD(k_padd, k_padd, arg->uk); } else { k_padd = arg->bk; } // Padding along M dimension. dim_t m_padd = 0; VAL_PADD(m_padd, nstl::min(nstl::max(m, arg->um), arg->bm), arg->um); // Padding along N dimension. dim_t n_padd = 0; if (k < arg->blocking_small_k) { VAL_PADD(n_padd, nstl::min(nstl::max(n, arg->un), arg->bn_small_k), arg->un); } else { VAL_PADD(n_padd, nstl::min(nstl::max(n, arg->un), arg->bn), arg->un); } // Padding for temporary buffer for C dim_t ldc_buf = m_padd; LD_PADD(ldc_buf, m_padd); dim_t strideAm = (arg->transa == 0)? 1 : lda; dim_t strideAn = (arg->transa != 0)? 1 : lda; dim_t strideBm = (arg->transb == 0)? 1 : ldb; dim_t strideBn = (arg->transb != 0)? 1 : ldb; int8_t *bufferA = (int8_t *) malloc(m_padd * k_padd * sizeof(*bufferA), PAGE_2M); if (!bufferA) { return -1; } uint8_t *bufferB = (uint8_t *) malloc(k_padd * n_padd * sizeof(*bufferB), PAGE_4K); if (!bufferB) { free(bufferA); return -1; } int32_t *bufferC = NULL; if (arg->offsetc != 0 || ao != 0 || bo != 0 || co[0] != 0 || alpha != 1.0 || (beta != 1.0 && beta != 0.0)) { bufferC = (int32_t *) malloc(ldc_buf * n_padd * sizeof(*bufferC), PAGE_4K); if (!bufferC) { free(bufferA); free(bufferB); return -1; } } int32_t *a_row_sum = (int32_t *) malloc(m_padd * sizeof(*a_row_sum), PAGE_4K); if (!a_row_sum) { free(bufferA); free(bufferB); free(bufferC); return -1; } int32_t *b_col_sum = (int32_t *) malloc(n_padd * sizeof(*b_col_sum), PAGE_4K); if (!b_col_sum) { free(bufferA); free(bufferB); free(bufferC); free(a_row_sum); return -1; } float beta_saved = beta; int a_block_copied = 0; dim_t sizeM = 0; for (dim_t Bm = 0; Bm < m; Bm += sizeM) { sizeM = m - Bm; if (sizeM > m_padd) sizeM = m_padd; dim_t sizeK = 0; for (dim_t Bk = 0; Bk < k; Bk += sizeK) { sizeK = k - Bk; if (sizeK > k_padd) sizeK = k_padd; // Scale C blocks by beta only for the first time if (Bk == 0) beta = beta_saved; else beta = 1.0f; // Apply C offset when to the last k-block of the partial sum. int offsetc = -1; if (Bk + sizeK == k) offsetc = arg->offsetc; dim_t sizeN = 0; for (dim_t Bn = 0; Bn < n; Bn += sizeN) { sizeN = n - Bn; if (sizeN > n_padd) sizeN = n_padd; const uint8_t *b_block = b + Bk * strideBm + Bn * strideBn; arg->copyB(&sizeK, &sizeN, b_block, &ldb, NULL, bufferB); get_b_col_sum(arg->transb, sizeK, sizeN, b_block, ldb, ao, b_col_sum); dim_t sizeUM = 0; for (dim_t Um = 0; Um < sizeM; Um += sizeUM) { sizeUM = sizeM - Um; if (sizeUM > arg->um) sizeUM = arg->um; const int8_t *a_block = a + (Bm + Um) * strideAm + Bk * strideAn; if (!a_block_copied) { arg->copyA(&sizeK, &sizeUM, a_block, &lda, NULL, bufferA + Um * sizeK); get_a_row_sum(arg->transa, sizeUM, sizeK, a_block, lda, bo, a_row_sum + Um); } int32_t *c_block = c + (Bm + Um) + Bn * ldc; if (bufferC) { arg->kernel_b0(&sizeUM, &sizeN, &sizeK, NULL, bufferA + Um * sizeK, bufferB, bufferC + Um, ldc_buf); // Finish the block adding the necessary alpha, beta // and offsets. dim_t co_stride = 0; if (offsetc == 0) { // Fix offset. co_stride = 0; } else if (offsetc == 1) { // Row offset. co_stride = Bn; } else if (offsetc == 2) { // Column offset. co_stride = Bm + Um; } add_results(sizeUM, sizeN, sizeK, alpha, beta, bufferC + Um, ldc_buf, c_block, ldc, a_row_sum + Um, b_col_sum, ao, bo, co + co_stride, offsetc); } else { if (beta == 0.0f) arg->kernel_b0(&sizeUM, &sizeN, &sizeK, NULL, bufferA + Um * sizeK, bufferB, c_block, ldc); else arg->kernel(&sizeUM, &sizeN, &sizeK, NULL, bufferA + Um * sizeK, bufferB, c_block, ldc); } } a_block_copied = 1; } a_block_copied = 0; } } free(bufferA); free(bufferB); free(bufferC); free(a_row_sum); free(b_col_sum); return 0; } #undef VAL_PADD #undef LD_PADD #define N2D_MAX_AVX512 384 #define M2D_MIN_AVX512 384 #define VECLEN 16 #define NCONS 1 static inline void set_thread_opts_avx512(int *p_nthrs, blas_t *arg) { int nthrs = *p_nthrs; dim_t m = arg->m; dim_t n = arg->n; int condition_2D_bsrc = -1; if ((256 * m > nthrs * n) && (nthrs * m < 256 * n)) { condition_2D_bsrc = 1; } else { condition_2D_bsrc = 0; } arg->thread_copy = COPY_NONE; // By default don't do parallel copy. if (condition_2D_bsrc == 1) { int nthrs_m = 1; int nthrs_n = nthrs; while ((nthrs_n % 2 == 0) && (n / nthrs > N2D_MAX_AVX512 || n / nthrs_n <= N2D_MAX_AVX512 / 2) && (m / nthrs_m >= 2 * M2D_MIN_AVX512) && (nthrs_m < 4)) { nthrs_m *= 2; nthrs_n /= 2; } arg->nthrs_m = nthrs_m; arg->nthrs_n = nthrs_n; arg->thread_partition = PARTITION_2D; // Reset the total number of threads that will be used. *p_nthrs = nthrs_m * nthrs_n; } else { if ((m > n) && (m / nthrs >= VECLEN || n < NCONS * nthrs)) { arg->thread_partition = PARTITION_1D_ROW; } else { arg->thread_partition = PARTITION_1D_COL; } } } #undef N2D_MAX_AVX512 #undef M2D_MIN_AVX512 #undef VECLEN #undef NCONS static inline void partition_1d(const int ithr, const int nthrs, const dim_t n, dim_t *t_offset, dim_t *t_block) { dim_t band = n / nthrs; dim_t tail = n - (nthrs - 1) * band; if (tail > (band + 1)) band++; tail = n - (nthrs - 1) * band; if (ithr < (nthrs - 1)) *t_block = band; else *t_block = tail; *t_offset = ithr * band; if (*t_offset >= n) { *t_block = 0; *t_offset = 0; } else if ((*t_offset + *t_block) > n) { *t_block = n - *t_offset; } } static inline void partition_2d(const int ithr, int *nthrs, const int ithr_i, const int ithr_j, const int nthrs_m, const int nthrs_n, const dim_t m, const dim_t n, dim_t *p_m_disp, dim_t *p_m_band, dim_t *p_n_disp, dim_t *p_n_band) { dim_t m_disp = 0, n_disp = 0; dim_t m_band = 0, n_band = 0; int mdiv = nthrs_m; int ndiv = nthrs_n; dim_t m_bandt = m / mdiv; /* size per thread */ dim_t n_bandt = n / ndiv; /* size per thread */ int firstmgroup = mdiv - 1; int firstngroup = ndiv - 1; dim_t firstmval = m_bandt; dim_t firstnval = n_bandt; int mthr_used = mdiv; if (m - (mdiv - 1) * m_bandt > m_bandt + 1) { if (m - (mdiv - 1) * m_bandt > mdiv) ++m_bandt; firstmval = m_bandt + 1; mthr_used = (int) (m / firstmval); if (mthr_used * firstmval < m) ++mthr_used; firstmgroup = mthr_used - 1; } int nthr_used = ndiv; if (n - (ndiv - 1) * n_bandt > n_bandt + 1) { firstnval = n_bandt + 1; nthr_used = (int) (n / firstnval); if (nthr_used * firstnval < n) ++nthr_used; firstngroup = nthr_used - 1; } *nthrs = mthr_used * nthr_used; if (ithr < *nthrs) { if (ithr_i < firstmgroup) { m_band = firstmval; m_disp = ithr_i * firstmval; } else if (ithr_i <= mthr_used - 2) { m_band = m_bandt; m_disp = firstmgroup * firstmval + (ithr_i - firstmgroup) * m_bandt; } else { m_disp = firstmgroup * firstmval + (mthr_used - 1 - firstmgroup) * m_bandt; m_band = nstl::max(0LL, m - m_disp); } if (ithr_j < firstngroup) { n_band = firstnval; n_disp = ithr_j * firstnval; } else if (ithr_j <= nthr_used - 2) { n_band = n_bandt; n_disp = firstngroup * firstnval + (ithr_j - firstngroup) * n_bandt; } else { n_disp = firstngroup * firstnval + (nthr_used - 1 - firstngroup) * n_bandt; n_band = nstl::max(0LL, n - n_disp); } m_disp = nstl::max(nstl::min(m_disp, m - 1), 0LL); n_disp = nstl::max(nstl::min(n_disp, n - 1), 0LL); } if (ithr < *nthrs) { *p_m_disp = m_disp; *p_n_disp = n_disp; *p_m_band = m_band; *p_n_band = n_band; } else { *p_m_disp = 0; *p_n_disp = 0; *p_m_band = 0; *p_n_band = 0; } return; } static inline void decompose_matrices(const int ithr, int *nthrs, dim_t *m, dim_t *n, dim_t *k, const int8_t **a, const uint8_t **b, int32_t **c, const int32_t **co, const blas_t *arg) { dim_t strideAm = (arg->transa == 0)? 1 : arg->lda; dim_t strideBn = (arg->transb != 0)? 1 : arg->ldb; int offsetc = arg->offsetc; switch (arg->thread_partition) { case PARTITION_1D_ROW: { dim_t offset = 0; dim_t block = 0; partition_1d(ithr, *nthrs, arg->m, &offset, &block); *m = block; *n = arg->n; *k = arg->k; // Set matrix A. *a = arg->a + offset * strideAm; // Set matrix B. *b = arg->b; // Set matrix C. *c = arg->c + offset; // Set offset vector for C matrix dim_t co_stride = 0; if (offsetc == 0) { // Fix offset. co_stride = 0; } else if (offsetc == 1) { // Row offset. co_stride = 0; } else if (offsetc == 2) { // Column offset. co_stride = offset; } *co = arg->co + co_stride; break; } case PARTITION_1D_COL: { dim_t offset = 0; dim_t block = 0; partition_1d(ithr, *nthrs, arg->n, &offset, &block); *m = arg->m; *n = block; *k = arg->k; // Set matrix A. *a = arg->a; // Set matrix B. *b = arg->b + offset * strideBn; // Set matrix C. *c = arg->c + offset * arg->ldc; // Set offset vector for C matrix dim_t co_stride = 0; if (offsetc == 0) { // Fix offset. co_stride = 0; } else if (offsetc == 1) { // Row offset. co_stride = offset; } else if (offsetc == 2) { // Column offset. co_stride = 0; } *co = arg->co + co_stride; break; } case PARTITION_2D_COL_MAJOR: { int nthrs_m = arg->nthrs_m; int nthrs_n = arg->nthrs_n; int ithr_i = ithr % nthrs_m; int ithr_j = ithr / nthrs_m; dim_t m_disp = 0; dim_t m_band = 0; dim_t n_disp = 0; dim_t n_band = 0; partition_2d(ithr, nthrs, ithr_i, ithr_j, nthrs_m, nthrs_n, arg->m, arg->n, &m_disp, &m_band, &n_disp, &n_band); *m = m_band; *n = n_band; *k = arg->k; // Set matrix A. *a = arg->a + m_disp * strideAm; // Set matrix B. *b = arg->b + n_disp * strideBn; // Set matrix C. *c = arg->c + m_disp + n_disp * arg->ldc; // Set offset vector for C matrix dim_t co_stride = 0; if (offsetc == 0) { // Fix offset. co_stride = 0; } else if (offsetc == 1) { // Row offset. co_stride = n_disp; } else if (offsetc == 2) { // Column offset. co_stride = m_disp; } *co = arg->co + co_stride; break; } } } static int gemm_threading_driver(blas_t *arg) { if ((arg->m <= 0) || (arg->n <= 0)) return mkldnn_success; const int nthr = (mkldnn_in_parallel()) ? 1 : mkldnn_get_max_threads(); /* * TODO Add a thread checker. */ if (nthr == 1) { return gemm_kernel_driver(arg->m, arg->n, arg->k, arg->a, arg->b, arg->c, arg->co, arg); } int status = 0; parallel(nthr, [&](const int ithr, const int nthr) { int nthrs = nthr; if (nthrs == 1) { status = gemm_kernel_driver(arg->m, arg->n, arg->k, arg->a, arg->b, arg->c, arg->co, arg); } else { set_thread_opts_avx512(&nthrs, arg); const int8_t *a = NULL; const uint8_t *b = NULL; int32_t *c = NULL; const int32_t *co = NULL; dim_t m = -1; dim_t n = -1; dim_t k = -1; decompose_matrices(ithr, &nthrs, &m, &n, &k, &a, &b, &c, &co, arg); if (ithr < nthrs) { int result = gemm_kernel_driver(m, n, k, a, b, c, co, arg); if (result < 0) { status = result; } } } }); return status; } static jit_avx512_core_u8_copy_an_kern *copy_an; static jit_avx512_core_u8_copy_at_kern *copy_at; static jit_avx512_core_u8_copy_bn_kern *copy_bn; static jit_avx512_core_u8_copy_bt_kern *copy_bt; static jit_avx512_core_kernel_gemm_s8u8s32_kern *kernel; static jit_avx512_core_kernel_b0_gemm_s8u8s32_kern *kernel_b0; static void jit_init(blas_t *arg) { static int (*copyAn )(const dim_t *m, const dim_t *n, const int8_t *a , const dim_t *lda, const int8_t *alpha, int8_t *b); static int (*copyAt )(const dim_t *m, const dim_t *n, const int8_t *a , const dim_t *lda, const int8_t *alpha, int8_t *b); static int (*copyBn )(const dim_t *m, const dim_t *n, const uint8_t *a, const dim_t *lda, const uint8_t *alpha, uint8_t *b); static int (*copyBt )(const dim_t *m, const dim_t *n, const uint8_t *a, const dim_t *lda, const uint8_t *alpha, uint8_t *b); static int (*kern )(const dim_t *m, const dim_t *n, const dim_t *k, const float *alpha, const int8_t *a, const uint8_t *b, int32_t *c, const dim_t ldc); static int (*kern_b0)(const dim_t *m, const dim_t *n, const dim_t *k, const float *alpha, const int8_t *a, const uint8_t *b, int32_t *c, const dim_t ldc); if (mayiuse(avx512_core_vnni)) { arg->um = AVX512_UNROLL_M; arg->un = AVX512_UNROLL_N; arg->uk = AVX512_UNROLL_K; arg->bm = AVX512_BM; arg->bn = AVX512_BN; arg->bk = AVX512_BK_VNNI; arg->bk_traditional = AVX512_BK_TRADITIONAL; arg->bn_small_k = AVX512_BN_SMALL_K; arg->blocking_small_k = AVX512_BLOCKING_SMALL_K; } else { arg->um = AVX512_UNROLL_M; arg->un = AVX512_UNROLL_N; arg->uk = AVX512_UNROLL_K; arg->bm = AVX512_BM; arg->bn = AVX512_BN; arg->bk = AVX512_BK; arg->bk_traditional = AVX512_BK_TRADITIONAL; arg->bn_small_k = AVX512_BN_SMALL_K; arg->blocking_small_k = AVX512_BLOCKING_SMALL_K; } static std::once_flag initialized; std::call_once(initialized, []{ copy_an = new jit_avx512_core_u8_copy_an_kern(); copy_at = new jit_avx512_core_u8_copy_at_kern(); copy_bn = new jit_avx512_core_u8_copy_bn_kern(); copy_bt = new jit_avx512_core_u8_copy_bt_kern(); kernel = new jit_avx512_core_kernel_gemm_s8u8s32_kern(); kernel_b0 = new jit_avx512_core_kernel_b0_gemm_s8u8s32_kern(); copyAn = copy_an -> getCode<int (*)(const dim_t *, const dim_t *, const int8_t *, const dim_t *, const int8_t *, int8_t *)>(); copyAt = copy_at -> getCode<int (*)(const dim_t *, const dim_t *, const int8_t *, const dim_t *, const int8_t *, int8_t *)>(); copyBn = copy_bn -> getCode<int (*)(const dim_t *, const dim_t *, const uint8_t *, const dim_t *, const uint8_t *, uint8_t *)>(); copyBt = copy_bt -> getCode<int (*)(const dim_t *, const dim_t *, const uint8_t *, const dim_t *, const uint8_t *, uint8_t *)>(); kern = kernel -> getCode<int (*)(const dim_t *, const dim_t *, const dim_t *, const float *, const int8_t *, const uint8_t *, int32_t *, const dim_t)>(); kern_b0 = kernel_b0 -> getCode<int (*)(const dim_t *, const dim_t *, const dim_t *, const float *, const int8_t *, const uint8_t *, int32_t *, const dim_t)>(); }); if (arg->transa == 0) { arg->copyA = copyAn; } else { arg->copyA = copyAt; } if (arg->transb == 0) { arg->copyB = copyBn; } else { arg->copyB = copyBt; } arg->kernel = kern; arg->kernel_b0 = kern_b0; } mkldnn_status_t jit_avx512_core_gemm_s8u8s32( const char *transA, const char *transB, const char *offsetC, const int *m, const int *n, const int *k, const float *alpha, const int8_t *a, const int *lda, const int8_t *oa, const uint8_t *b, const int *ldb, const int8_t *ob, const float *beta, int32_t *c, const int *ldc, const int32_t *oc) { char transa = *transA; char transb = *transB; char offsetc = *offsetC; blas_t args; // Initialize blas structure args.m = *m; args.n = *n; args.k = *k; args.alpha = alpha; args.a = a; args.lda = *lda; args.b = b; args.ldb = *ldb; args.beta = beta; args.c = c; args.ldc = *ldc; args.transa = (transa == 'N' || transa == 'n') ? 0 : 1; args.transb = (transb == 'N' || transb == 'n') ? 0 : 1; args.um = 0; args.un = 0; args.bm = 0; args.bn = 0; args.bk = 0; args.copyA = NULL; args.copyB = NULL; args.kernel = NULL; args.kernel_b0 = NULL; args.ao = *oa; args.bo = *ob; args.co = oc; if (offsetc == 'F' || offsetc == 'f') { args.offsetc = 0; } else if (offsetc == 'R' || offsetc == 'r') { args.offsetc = 1; } else { // offsetc == 'C' || offsetc == 'c' args.offsetc = 2; } jit_init(&args); int result = gemm_threading_driver(&args); return (result < 0 ) ? mkldnn_out_of_memory : mkldnn_success; } } } }
32.67203
168
0.502746
c211c8b041dfa5b8bc7afa2fda5d413fa7242ef9
20,283
hpp
C++
resources/synth/datastructures/Fixed.hpp
arturluis/spatial
4a829849231b2f9589dd9ab630657689f9a538e5
[ "MIT" ]
232
2016-09-12T23:28:11.000Z
2022-02-01T01:40:43.000Z
resources/synth/datastructures/Fixed.hpp
arturluis/spatial
4a829849231b2f9589dd9ab630657689f9a538e5
[ "MIT" ]
288
2016-09-12T16:35:34.000Z
2021-12-15T22:06:02.000Z
resources/synth/datastructures/Fixed.hpp
arturluis/spatial
4a829849231b2f9589dd9ab630657689f9a538e5
[ "MIT" ]
31
2016-10-13T04:37:00.000Z
2022-01-29T08:03:33.000Z
// From: https://github.com/eteran/cpp-utilities/blob/master/fixed/include/eteran/cpp-utilities/Fixed.h // See also: http://stackoverflow.com/questions/79677/whats-the-best-way-to-do-fixed-point-math /* * The MIT License (MIT) * * Copyright (c) 2015 Evan Teran * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #ifndef FIXED_H_ #define FIXED_H_ #if __cplusplus >= 201402L #define CONSTEXPR14 constexpr #else #define CONSTEXPR14 #endif #include <ostream> #include <exception> #include <cstddef> // for size_t #include <cstdint> #include <type_traits> namespace numeric { template <size_t I, size_t F> class Fixed; namespace detail { // helper templates to make magic with types :) // these allow us to determine resonable types from // a desired size, they also let us infer the next largest type // from a type which is nice for the division op template <size_t T> struct type_from_size { static constexpr bool is_specialized = false; }; #if defined(__GNUC__) && defined(__x86_64__) && !defined(__STRICT_ANSI__) template <> struct type_from_size<128> { static constexpr bool is_specialized = true; static constexpr size_t size = 128; using value_type = __int128; using unsigned_type = unsigned __int128; using signed_type = __int128; using next_size = type_from_size<256>; }; #endif template <> struct type_from_size<64> { static constexpr bool is_specialized = true; static constexpr size_t size = 64; using value_type = int64_t; using unsigned_type = std::make_unsigned<value_type>::type; using signed_type = std::make_signed<value_type>::type; using next_size = type_from_size<128>; }; template <> struct type_from_size<32> { static constexpr bool is_specialized = true; static constexpr size_t size = 32; using value_type = int32_t; using unsigned_type = std::make_unsigned<value_type>::type; using signed_type = std::make_signed<value_type>::type; using next_size = type_from_size<64>; }; template <> struct type_from_size<16> { static constexpr bool is_specialized = true; static constexpr size_t size = 16; using value_type = int16_t; using unsigned_type = std::make_unsigned<value_type>::type; using signed_type = std::make_signed<value_type>::type; using next_size = type_from_size<32>; }; template <> struct type_from_size<8> { static constexpr bool is_specialized = true; static constexpr size_t size = 8; using value_type = int8_t; using unsigned_type = std::make_unsigned<value_type>::type; using signed_type = std::make_signed<value_type>::type; using next_size = type_from_size<16>; }; // this is to assist in adding support for non-native base // types (for adding big-int support), this should be fine // unless your bit-int class doesn't nicely support casting template <class B, class N> constexpr B next_to_base(N rhs) { return static_cast<B>(rhs); } struct divide_by_zero : std::exception { }; template <size_t I, size_t F> CONSTEXPR14 Fixed<I,F> divide(Fixed<I, F> numerator, Fixed<I, F> denominator, Fixed<I,F> &remainder, typename std::enable_if<type_from_size<I+F>::next_size::is_specialized>::type* = nullptr) { using next_type = typename Fixed<I,F>::next_type; using base_type = typename Fixed<I,F>::base_type; constexpr size_t fractional_bits = Fixed<I,F>::fractional_bits; next_type t(numerator.to_raw()); t <<= fractional_bits; Fixed<I,F> quotient; quotient = Fixed<I,F>::from_base(next_to_base<base_type>(t / denominator.to_raw())); remainder = Fixed<I,F>::from_base(next_to_base<base_type>(t % denominator.to_raw())); return quotient; } template <size_t I, size_t F> CONSTEXPR14 Fixed<I,F> divide(Fixed<I,F> numerator, Fixed<I,F> denominator, Fixed<I,F> &remainder, typename std::enable_if<!type_from_size<I+F>::next_size::is_specialized>::type* = nullptr) { // NOTE(eteran): division is broken for large types :-( // especially when dealing with negative quantities using base_type = typename Fixed<I,F>::base_type; using unsigned_type = typename Fixed<I,F>::unsigned_type; constexpr int bits = Fixed<I,F>::total_bits; if(denominator == 0) { throw divide_by_zero(); } else { int sign = 0; Fixed<I,F> quotient; if(numerator < 0) { sign ^= 1; numerator = -numerator; } if(denominator < 0) { sign ^= 1; denominator = -denominator; } base_type n = numerator.to_raw(); base_type d = denominator.to_raw(); base_type x = 1; base_type answer = 0; // egyptian division algorithm while((n >= d) && (((d >> (bits - 1)) & 1) == 0)) { x <<= 1; d <<= 1; } while(x != 0) { if(n >= d) { n -= d; answer += x; } x >>= 1; d >>= 1; } unsigned_type l1 = n; unsigned_type l2 = denominator.to_raw(); // calculate the lower bits (needs to be unsigned) // unfortunately for many fractions this overflows the type still :-/ const unsigned_type lo = (static_cast<unsigned_type>(n) << F) / denominator.to_raw(); quotient = Fixed<I,F>::from_base((answer << F) | lo); remainder = n; if(sign) { quotient = -quotient; } return quotient; } } // this is the usual implementation of multiplication template <size_t I, size_t F> CONSTEXPR14 Fixed<I,F> multiply(Fixed<I, F> lhs, Fixed<I, F> rhs, typename std::enable_if<type_from_size<I+F>::next_size::is_specialized>::type* = nullptr) { using next_type = typename Fixed<I,F>::next_type; using base_type = typename Fixed<I,F>::base_type; constexpr size_t fractional_bits = Fixed<I,F>::fractional_bits; next_type t (static_cast<next_type>(lhs.to_raw()) * static_cast<next_type>(rhs.to_raw())); t >>= fractional_bits; return Fixed<I,F>::from_base(next_to_base<base_type>(t)); } // this is the fall back version we use when we don't have a next size // it is slightly slower, but is more robust since it doesn't // require and upgraded type template <size_t I, size_t F> CONSTEXPR14 Fixed<I,F> multiply(Fixed<I, F> lhs, Fixed<I, F> rhs, typename std::enable_if<!type_from_size<I+F>::next_size::is_specialized>::type* = nullptr) { using base_type = typename Fixed<I,F>::base_type; constexpr size_t fractional_bits = Fixed<I,F>::fractional_bits; constexpr base_type integer_mask = Fixed<I,F>::integer_mask; constexpr base_type fractional_mask = Fixed<I,F>::fractional_mask; // more costly but doesn't need a larger type constexpr base_type a_hi = (lhs.to_raw() & integer_mask) >> fractional_bits; constexpr base_type b_hi = (rhs.to_raw() & integer_mask) >> fractional_bits; constexpr base_type a_lo = (lhs.to_raw() & fractional_mask); constexpr base_type b_lo = (rhs.to_raw() & fractional_mask); constexpr base_type x1 = a_hi * b_hi; constexpr base_type x2 = a_hi * b_lo; constexpr base_type x3 = a_lo * b_hi; constexpr base_type x4 = a_lo * b_lo; return Fixed<I,F>::from_base((x1 << fractional_bits) + (x3 + x2) + (x4 >> fractional_bits)); } } template <size_t I, size_t F> class Fixed { static_assert(detail::type_from_size<I + F>::is_specialized, "invalid combination of sizes"); public: static constexpr size_t fractional_bits = F; static constexpr size_t integer_bits = I; static constexpr size_t total_bits = I + F; using base_type_info = detail::type_from_size<total_bits>; using base_type = typename base_type_info::value_type; using next_type = typename base_type_info::next_size::value_type; using unsigned_type = typename base_type_info::unsigned_type; public: #ifdef __GNUC__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Woverflow" #endif static constexpr base_type fractional_mask = ~(static_cast<unsigned_type>(~base_type(0)) << fractional_bits); static constexpr base_type integer_mask = ~fractional_mask; #ifdef __GNUC__ #pragma GCC diagnostic push #endif public: static constexpr base_type one = base_type(1) << fractional_bits; public: // constructors Fixed() = default; Fixed(const Fixed &) = default; Fixed& operator=(const Fixed &) = default; template <class Number> constexpr Fixed(Number n, typename std::enable_if<std::is_arithmetic<Number>::value>::type* = nullptr) : data_(static_cast<base_type>(n * one)) { } public: // conversion template <size_t I2, size_t F2> CONSTEXPR14 explicit Fixed(Fixed<I2, F2> other) { static_assert(I2 <= I && F2 <= F, "Scaling conversion can only upgrade types"); using T = Fixed<I2,F2>; const base_type fractional = (other.data_ & T::fractional_mask); const base_type integer = (other.data_ & T::integer_mask) >> T::fractional_bits; data_ = (integer << fractional_bits) | (fractional << (fractional_bits - T::fractional_bits)); } private: // this makes it simpler to create a fixed point object from // a native type without scaling // use "Fixed::from_base" in order to perform this. struct NoScale {}; constexpr Fixed(base_type n, const NoScale &) : data_(n) { } public: constexpr static Fixed from_base(base_type n) { return Fixed(n, NoScale()); } public: // comparison operators constexpr bool operator==(Fixed rhs) const { return data_ == rhs.data_; } constexpr bool operator!=(Fixed rhs) const { return data_ != rhs.data_; } constexpr bool operator<(Fixed rhs) const { return data_ < rhs.data_; } constexpr bool operator>(Fixed rhs) const { return data_ > rhs.data_; } constexpr bool operator<=(Fixed rhs) const { return data_ <= rhs.data_; } constexpr bool operator>=(Fixed rhs) const { return data_ >= rhs.data_; } public: // unary operators constexpr bool operator!() const { return !data_; } constexpr Fixed operator~() const { // NOTE(eteran): this will often appear to "just negate" the value // that is not an error, it is because -x == (~x+1) // and that "+1" is adding an infinitesimally small fraction to the // complimented value return Fixed::from_base(~data_); } constexpr Fixed operator-() const { return Fixed::from_base(-data_); } constexpr Fixed operator+() const { return Fixed::from_base(+data_); } CONSTEXPR14 Fixed &operator++() { data_ += one; return *this; } CONSTEXPR14 Fixed &operator--() { data_ -= one; return *this; } CONSTEXPR14 Fixed operator++(int) { Fixed tmp(*this); data_ += one; return tmp; } CONSTEXPR14 Fixed operator--(int) { Fixed tmp(*this); data_ -= one; return tmp; } public: // basic math operators CONSTEXPR14 Fixed& operator+=(Fixed n) { data_ += n.data_; return *this; } CONSTEXPR14 Fixed& operator-=(Fixed n) { data_ -= n.data_; return *this; } CONSTEXPR14 Fixed& operator*=(Fixed n) { return assign(detail::multiply(*this, n)); } CONSTEXPR14 Fixed& operator/=(Fixed n) { Fixed temp; return assign(detail::divide(*this, n, temp)); } private: CONSTEXPR14 Fixed& assign(Fixed rhs) { data_ = rhs.data_; return *this; } public: // binary math operators, effects underlying bit pattern since these // don't really typically make sense for non-integer values CONSTEXPR14 Fixed& operator&=(Fixed n) { data_ &= n.data_; return *this; } CONSTEXPR14 Fixed& operator|=(Fixed n) { data_ |= n.data_; return *this; } CONSTEXPR14 Fixed& operator^=(Fixed n) { data_ ^= n.data_; return *this; } template <class Integer, class = typename std::enable_if<std::is_integral<Integer>::value>::type> CONSTEXPR14 Fixed& operator>>=(Integer n) { data_ >>= n; return *this; } template <class Integer, class = typename std::enable_if<std::is_integral<Integer>::value>::type> CONSTEXPR14 Fixed& operator<<=(Integer n) { data_ <<= n; return *this; } public: // conversion to basic types constexpr int to_int() const { return (data_ & integer_mask) >> fractional_bits; } constexpr unsigned int to_uint() const { return (data_ & integer_mask) >> fractional_bits; } constexpr float to_float() const { return static_cast<float>(data_) / Fixed::one; } constexpr double to_double() const { return static_cast<double>(data_) / Fixed::one; } constexpr base_type to_raw() const { return data_; } public: CONSTEXPR14 void swap(Fixed &rhs) { using std::swap; swap(data_, rhs.data_); } public: base_type data_ = 0; }; // if we have the same fractional portion, but differing integer portions, we trivially upgrade the smaller type template <size_t I1, size_t I2, size_t F> CONSTEXPR14 typename std::conditional<I1 >= I2, Fixed<I1,F>, Fixed<I2,F>>::type operator+(Fixed<I1, F> lhs, Fixed<I2, F> rhs) { using T = typename std::conditional< I1 >= I2, Fixed<I1,F>, Fixed<I2,F> >::type; constexpr T l = T::from_base(lhs.to_raw()); constexpr T r = T::from_base(rhs.to_raw()); return l + r; } template <size_t I1, size_t I2, size_t F> CONSTEXPR14 typename std::conditional<I1 >= I2, Fixed<I1,F>, Fixed<I2,F>>::type operator-(Fixed<I1, F> lhs, Fixed<I2, F> rhs) { using T = typename std::conditional< I1 >= I2, Fixed<I1,F>, Fixed<I2,F> >::type; constexpr T l = T::from_base(lhs.to_raw()); constexpr T r = T::from_base(rhs.to_raw()); return l - r; } template <size_t I1, size_t I2, size_t F> CONSTEXPR14 typename std::conditional<I1 >= I2, Fixed<I1,F>, Fixed<I2,F>>::type operator*(Fixed<I1, F> lhs, Fixed<I2, F> rhs) { using T = typename std::conditional< I1 >= I2, Fixed<I1,F>, Fixed<I2,F> >::type; constexpr T l = T::from_base(lhs.to_raw()); constexpr T r = T::from_base(rhs.to_raw()); return l * r; } template <size_t I1, size_t I2, size_t F> CONSTEXPR14 typename std::conditional<I1 >= I2, Fixed<I1,F>, Fixed<I2,F>>::type operator/(Fixed<I1, F> lhs, Fixed<I2, F> rhs) { using T = typename std::conditional< I1 >= I2, Fixed<I1,F>, Fixed<I2,F> >::type; constexpr T l = T::from_base(lhs.to_raw()); constexpr T r = T::from_base(rhs.to_raw()); return l / r; } template <size_t I, size_t F> std::ostream &operator<<(std::ostream &os, Fixed<I, F> f) { os << f.to_double(); return os; } // basic math operators template <size_t I, size_t F> CONSTEXPR14 Fixed<I, F> operator+(Fixed<I, F> lhs, Fixed<I, F> rhs) { lhs += rhs; return lhs; } template <size_t I, size_t F> CONSTEXPR14 Fixed<I, F> operator-(Fixed<I, F> lhs, Fixed<I, F> rhs) { lhs -= rhs; return lhs; } template <size_t I, size_t F> CONSTEXPR14 Fixed<I, F> operator*(Fixed<I, F> lhs, Fixed<I, F> rhs) { lhs *= rhs; return lhs; } template <size_t I, size_t F> CONSTEXPR14 Fixed<I, F> operator/(Fixed<I, F> lhs, Fixed<I, F> rhs) { lhs /= rhs; return lhs; } template <size_t I, size_t F, class Number, class = typename std::enable_if<std::is_arithmetic<Number>::value>::type> CONSTEXPR14 Fixed<I, F> operator+(Fixed<I, F> lhs, Number rhs) { lhs += Fixed<I, F>(rhs); return lhs; } template <size_t I, size_t F, class Number, class = typename std::enable_if<std::is_arithmetic<Number>::value>::type> CONSTEXPR14 Fixed<I, F> operator-(Fixed<I, F> lhs, Number rhs) { lhs -= Fixed<I, F>(rhs); return lhs; } template <size_t I, size_t F, class Number, class = typename std::enable_if<std::is_arithmetic<Number>::value>::type> CONSTEXPR14 Fixed<I, F> operator*(Fixed<I, F> lhs, Number rhs) { lhs *= Fixed<I, F>(rhs); return lhs; } template <size_t I, size_t F, class Number, class = typename std::enable_if<std::is_arithmetic<Number>::value>::type> CONSTEXPR14 Fixed<I, F> operator/(Fixed<I, F> lhs, Number rhs) { lhs /= Fixed<I, F>(rhs); return lhs; } template <size_t I, size_t F, class Number, class = typename std::enable_if<std::is_arithmetic<Number>::value>::type> CONSTEXPR14 Fixed<I, F> operator+(Number lhs, Fixed<I, F> rhs) { Fixed<I, F> tmp(lhs); tmp += rhs; return tmp; } template <size_t I, size_t F, class Number, class = typename std::enable_if<std::is_arithmetic<Number>::value>::type> CONSTEXPR14 Fixed<I, F> operator-(Number lhs, Fixed<I, F> rhs) { Fixed<I, F> tmp(lhs); tmp -= rhs; return tmp; } template <size_t I, size_t F, class Number, class = typename std::enable_if<std::is_arithmetic<Number>::value>::type> CONSTEXPR14 Fixed<I, F> operator*(Number lhs, Fixed<I, F> rhs) { Fixed<I, F> tmp(lhs); tmp *= rhs; return tmp; } template <size_t I, size_t F, class Number, class = typename std::enable_if<std::is_arithmetic<Number>::value>::type> CONSTEXPR14 Fixed<I, F> operator/(Number lhs, Fixed<I, F> rhs) { Fixed<I, F> tmp(lhs); tmp /= rhs; return tmp; } // shift operators template <size_t I, size_t F, class Integer, class = typename std::enable_if<std::is_integral<Integer>::value>::type> CONSTEXPR14 Fixed<I, F> operator<<(Fixed<I, F> lhs, Integer rhs) { lhs <<= rhs; return lhs; } template <size_t I, size_t F, class Integer, class = typename std::enable_if<std::is_integral<Integer>::value>::type> CONSTEXPR14 Fixed<I, F> operator>>(Fixed<I, F> lhs, Integer rhs) { lhs >>= rhs; return lhs; } // comparison operators template <size_t I, size_t F, class Number, class = typename std::enable_if<std::is_arithmetic<Number>::value>::type> constexpr bool operator>(Fixed<I, F> lhs, Number rhs) { return lhs > Fixed<I, F>(rhs); } template <size_t I, size_t F, class Number, class = typename std::enable_if<std::is_arithmetic<Number>::value>::type> constexpr bool operator<(Fixed<I, F> lhs, Number rhs) { return lhs < Fixed<I, F>(rhs); } template <size_t I, size_t F, class Number, class = typename std::enable_if<std::is_arithmetic<Number>::value>::type> constexpr bool operator>=(Fixed<I, F> lhs, Number rhs) { return lhs >= Fixed<I, F>(rhs); } template <size_t I, size_t F, class Number, class = typename std::enable_if<std::is_arithmetic<Number>::value>::type> constexpr bool operator<=(Fixed<I, F> lhs, Number rhs) { return lhs <= Fixed<I, F>(rhs); } template <size_t I, size_t F, class Number, class = typename std::enable_if<std::is_arithmetic<Number>::value>::type> constexpr bool operator==(Fixed<I, F> lhs, Number rhs) { return lhs == Fixed<I, F>(rhs); } template <size_t I, size_t F, class Number, class = typename std::enable_if<std::is_arithmetic<Number>::value>::type> constexpr bool operator!=(Fixed<I, F> lhs, Number rhs) { return lhs != Fixed<I, F>(rhs); } template <size_t I, size_t F, class Number, class = typename std::enable_if<std::is_arithmetic<Number>::value>::type> constexpr bool operator>(Number lhs, Fixed<I, F> rhs) { return Fixed<I, F>(lhs) > rhs; } template <size_t I, size_t F, class Number, class = typename std::enable_if<std::is_arithmetic<Number>::value>::type> constexpr bool operator<(Number lhs, Fixed<I, F> rhs) { return Fixed<I, F>(lhs) < rhs; } template <size_t I, size_t F, class Number, class = typename std::enable_if<std::is_arithmetic<Number>::value>::type> constexpr bool operator>=(Number lhs, Fixed<I, F> rhs) { return Fixed<I, F>(lhs) >= rhs; } template <size_t I, size_t F, class Number, class = typename std::enable_if<std::is_arithmetic<Number>::value>::type> constexpr bool operator<=(Number lhs, Fixed<I, F> rhs) { return Fixed<I, F>(lhs) <= rhs; } template <size_t I, size_t F, class Number, class = typename std::enable_if<std::is_arithmetic<Number>::value>::type> constexpr bool operator==(Number lhs, Fixed<I, F> rhs) { return Fixed<I, F>(lhs) == rhs; } template <size_t I, size_t F, class Number, class = typename std::enable_if<std::is_arithmetic<Number>::value>::type> constexpr bool operator!=(Number lhs, Fixed<I, F> rhs) { return Fixed<I, F>(lhs) != rhs; } } #undef CONSTEXPR14 #endif
35.397906
230
0.700044