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
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
fe565512d54898ccd143d886bcc11de749329e2c
1,221
cpp
C++
Engine/Io/DictionaryReader.cpp
i0r/huisclos
930c641ab64f1deff4c15a6e1617fc596cf8118f
[ "X11" ]
null
null
null
Engine/Io/DictionaryReader.cpp
i0r/huisclos
930c641ab64f1deff4c15a6e1617fc596cf8118f
[ "X11" ]
null
null
null
Engine/Io/DictionaryReader.cpp
i0r/huisclos
930c641ab64f1deff4c15a6e1617fc596cf8118f
[ "X11" ]
null
null
null
#include "Shared.h" #include "DictionaryReader.h" #include <string> #include <fstream> namespace { void Trim( std::string &str ) { size_t charPos = str.find_first_not_of( " \n" ); if ( charPos != std::string::npos ) { str.erase( 0, charPos ); } charPos = str.find_last_not_of( " \n" ); if ( charPos != std::string::npos ) { str.erase( charPos + 1 ); } } } const int Io_ReadDictionaryFile( const char* fileName, dictionary_t& dico ) { std::ifstream fStream( fileName ); if ( fStream.is_open() ) { std::string fLine = "", dicoKey = "", dicoVal = ""; while ( fStream.good() ) { std::getline( fStream, fLine ); const size_t separator = fLine.find_first_of( ':' ); const size_t commentSep = fLine.find_first_of( ';' ); if ( commentSep != -1 ) { fLine.erase( fLine.begin() + commentSep, fLine.end() ); } if ( !fLine.empty() && separator != std::string::npos ) { dicoKey = fLine.substr( 0, separator ); dicoVal = fLine.substr( separator + 1 ); Trim( dicoKey ); Trim( dicoVal ); if ( !dicoVal.empty() ) { dico.insert( std::make_pair( dicoKey, dicoVal ) ); } } } } else { return 1; } fStream.close(); return 0; }
19.380952
75
0.5905
i0r
fe56f15dbd08cf7765305e0e75f598e4fc09eefd
412
cpp
C++
tests/Classes/main.cpp
Derik-T/CPP
adf8ecb11af5bf96d04182b83ae3fa58ca64bc72
[ "MIT" ]
1
2021-08-28T23:51:52.000Z
2021-08-28T23:51:52.000Z
tests/Classes/main.cpp
Derik-T/CPP
adf8ecb11af5bf96d04182b83ae3fa58ca64bc72
[ "MIT" ]
null
null
null
tests/Classes/main.cpp
Derik-T/CPP
adf8ecb11af5bf96d04182b83ae3fa58ca64bc72
[ "MIT" ]
null
null
null
#include "main.h" int main(){ Pessoa Joao, Cleide, Claudo; Joao.setId(1); Joao.setIdade(10); Joao.setSexo(true); Joao.setUsaOculos(false); Joao.copy(Joao); std::cout << Cleide.getId() << std::endl; std::cout << Joao.getIdade() << std::endl; Produto cadeira, ventilador, amplificador; cadeira.fill(); cadeira.setEstoque(10); cadeira.show(); return 0; }
20.6
46
0.601942
Derik-T
fe5774f1eaa8e05d8a30c89117213c3acfbe2f4f
325
cpp
C++
cpp/lab27/inheritance/base_class_content_demonstration.cpp
PeganovAnton/cs-8th-grade
843a1e228473734728949ba286e04612165a163e
[ "AFL-3.0" ]
null
null
null
cpp/lab27/inheritance/base_class_content_demonstration.cpp
PeganovAnton/cs-8th-grade
843a1e228473734728949ba286e04612165a163e
[ "AFL-3.0" ]
null
null
null
cpp/lab27/inheritance/base_class_content_demonstration.cpp
PeganovAnton/cs-8th-grade
843a1e228473734728949ba286e04612165a163e
[ "AFL-3.0" ]
null
null
null
#include <iostream> #include <stdint.h> using namespace std; class A { int32_t a; }; class B: public A { int32_t a; }; int main() { cout << "sizeof(A): " << sizeof(A) << endl; // Печатает 4. // Печатает 8, так как содержит в том числе родительские члены. cout << "sizeof(B): " << sizeof(B) << endl; }
12.037037
65
0.584615
PeganovAnton
fe5b3b007b135d6ada318d38d9b1f06c10a789cf
460
cpp
C++
source/bullet.cpp
aronlebani/math-game
86d30e6a4a89167aefc618b76848566a65ecbcab
[ "MIT" ]
null
null
null
source/bullet.cpp
aronlebani/math-game
86d30e6a4a89167aefc618b76848566a65ecbcab
[ "MIT" ]
null
null
null
source/bullet.cpp
aronlebani/math-game
86d30e6a4a89167aefc618b76848566a65ecbcab
[ "MIT" ]
null
null
null
/* bullet.cpp Aron Lebani 29 March 2016 */ #include "../include/character.h" #include "../include/bullet.h" #include "../include/tools.h" bullet::bullet() { width = 13; height = 2; } void bullet::draw() { tools::printw(getY() , getX(), " x "); tools::printw(getY()+1, getX(), " x "); } void bullet::erase() { int i, j; for (i=0; i<height; i++) { for (j=0; j<width; j++) { tools::printw(getY()+i, getX()+j, " "); } } }
13.529412
50
0.526087
aronlebani
fe5cde8ce7a2c767d2d659c44a42580ee6d1de58
843
hpp
C++
src/Cheats.hpp
soni801/SourceAutoRecord
4bd9fde988eac425f86db050354db490dd3ed69b
[ "MIT" ]
42
2021-04-27T17:03:24.000Z
2022-03-03T18:56:13.000Z
src/Cheats.hpp
soni801/SourceAutoRecord
4bd9fde988eac425f86db050354db490dd3ed69b
[ "MIT" ]
43
2021-04-27T21:20:06.000Z
2022-03-22T12:45:46.000Z
src/Cheats.hpp
soni801/SourceAutoRecord
4bd9fde988eac425f86db050354db490dd3ed69b
[ "MIT" ]
29
2021-06-11T23:52:24.000Z
2022-03-30T14:33:46.000Z
#pragma once #include "Command.hpp" #include "Variable.hpp" class Cheats { public: void Init(); void Shutdown(); }; extern Variable sar_autorecord; extern Variable sar_autojump; extern Variable sar_jumpboost; extern Variable sar_aircontrol; extern Variable sar_duckjump; extern Variable sar_disable_challenge_stats_hud; extern Variable sar_disable_steam_pause; extern Variable sar_disable_no_focus_sleep; extern Variable sar_disable_progress_bar_update; extern Variable sar_prevent_mat_snapshot_recompute; extern Variable sar_challenge_autostop; extern Variable sar_show_entinp; extern Variable sv_laser_cube_autoaim; extern Variable ui_loadingscreen_transition_time; extern Variable ui_loadingscreen_fadein_time; extern Variable ui_loadingscreen_mintransition_time; extern Variable hide_gun_when_holding; extern Command sar_togglewait;
27.193548
52
0.867141
soni801
fe5d29f8c8be4678354d4a49e522903e96401a66
6,393
cpp
C++
src/pocketdb/models/dto/User.cpp
dmaltsiniotis/pocketnet.core
d7f763259330ae3dc6a02ec30ba2525ce2f6a5d9
[ "Apache-2.0" ]
1
2022-01-09T12:22:44.000Z
2022-01-09T12:22:44.000Z
src/pocketdb/models/dto/User.cpp
dmaltsiniotis/pocketnet.core
d7f763259330ae3dc6a02ec30ba2525ce2f6a5d9
[ "Apache-2.0" ]
null
null
null
src/pocketdb/models/dto/User.cpp
dmaltsiniotis/pocketnet.core
d7f763259330ae3dc6a02ec30ba2525ce2f6a5d9
[ "Apache-2.0" ]
null
null
null
// Copyright (c) 2018-2021 Pocketnet developers // Distributed under the Apache 2.0 software license, see the accompanying // https://www.apache.org/licenses/LICENSE-2.0 #include <primitives/transaction.h> #include "pocketdb/models/dto/User.h" namespace PocketTx { User::User() : Transaction() { SetType(TxType::ACCOUNT_USER); } User::User(const std::shared_ptr<const CTransaction>& tx) : Transaction(tx) { SetType(TxType::ACCOUNT_USER); } shared_ptr <UniValue> User::Serialize() const { auto result = Transaction::Serialize(); result->pushKV("address", GetAddress() ? *GetAddress() : ""); result->pushKV("referrer", GetReferrerAddress() ? *GetReferrerAddress() : ""); result->pushKV("regdate", *GetTime()); result->pushKV("lang", (m_payload && m_payload->GetString1()) ? *m_payload->GetString1() : "en"); result->pushKV("name", (m_payload && m_payload->GetString2()) ? *m_payload->GetString2() : ""); result->pushKV("avatar", (m_payload && m_payload->GetString3()) ? *m_payload->GetString3() : ""); result->pushKV("about", (m_payload && m_payload->GetString4()) ? *m_payload->GetString4() : ""); result->pushKV("url", (m_payload && m_payload->GetString5()) ? *m_payload->GetString5() : ""); result->pushKV("pubkey", (m_payload && m_payload->GetString6()) ? *m_payload->GetString6() : ""); result->pushKV("donations", (m_payload && m_payload->GetString7()) ? *m_payload->GetString7() : ""); result->pushKV("birthday", 0); result->pushKV("gender", 0); result->pushKV("id", 0); return result; } void User::Deserialize(const UniValue& src) { Transaction::Deserialize(src); if (auto[ok, val] = TryGetStr(src, "address"); ok) SetAddress(val); if (auto[ok, val] = TryGetStr(src, "referrer"); ok) SetReferrerAddress(val); } void User::DeserializeRpc(const UniValue& src) { if (auto[ok, val] = TryGetStr(src, "r"); ok) SetReferrerAddress(val); GeneratePayload(); if (auto[ok, val] = TryGetStr(src, "l"); ok) m_payload->SetString1(val); else m_payload->SetString1("en"); if (auto[ok, val] = TryGetStr(src, "n"); ok) m_payload->SetString2(val); else m_payload->SetString2(""); if (auto[ok, val] = TryGetStr(src, "i"); ok) m_payload->SetString3(val); if (auto[ok, val] = TryGetStr(src, "a"); ok) m_payload->SetString4(val); if (auto[ok, val] = TryGetStr(src, "s"); ok) m_payload->SetString5(val); if (auto[ok, val] = TryGetStr(src, "k"); ok) m_payload->SetString6(val); if (auto[ok, val] = TryGetStr(src, "b"); ok) m_payload->SetString7(val); } shared_ptr <string> User::GetAddress() const { return m_string1; } void User::SetAddress(const string& value) { m_string1 = make_shared<string>(value); } shared_ptr <string> User::GetReferrerAddress() const { return m_string2; } void User::SetReferrerAddress(const string& value) { m_string2 = make_shared<string>(value); } // Payload getters shared_ptr <string> User::GetPayloadName() const { return GetPayload() ? GetPayload()->GetString2() : nullptr; } shared_ptr <string> User::GetPayloadAvatar() const { return GetPayload() ? GetPayload()->GetString3() : nullptr; } shared_ptr <string> User::GetPayloadUrl() const { return GetPayload() ? GetPayload()->GetString5() : nullptr; } shared_ptr <string> User::GetPayloadLang() const { return GetPayload() ? GetPayload()->GetString1() : nullptr; } shared_ptr <string> User::GetPayloadAbout() const { return GetPayload() ? GetPayload()->GetString4() : nullptr; } shared_ptr <string> User::GetPayloadDonations() const { return GetPayload() ? GetPayload()->GetString7() : nullptr; } shared_ptr <string> User::GetPayloadPubkey() const { return GetPayload() ? GetPayload()->GetString6() : nullptr; } void User::DeserializePayload(const UniValue& src) { Transaction::DeserializePayload(src); if (auto[ok, val] = TryGetStr(src, "lang"); ok) m_payload->SetString1(val); if (auto[ok, val] = TryGetStr(src, "name"); ok) m_payload->SetString2(val); else m_payload->SetString2(""); if (auto[ok, val] = TryGetStr(src, "avatar"); ok) m_payload->SetString3(val); if (auto[ok, val] = TryGetStr(src, "about"); ok) m_payload->SetString4(val); if (auto[ok, val] = TryGetStr(src, "url"); ok) m_payload->SetString5(val); if (auto[ok, val] = TryGetStr(src, "pubkey"); ok) m_payload->SetString6(val); if (auto[ok, val] = TryGetStr(src, "donations"); ok) m_payload->SetString7(val); } string User::BuildHash() { return BuildHash(true); } string User::BuildHash(bool includeReferrer) { std::string data; data += m_payload && m_payload->GetString2() ? *m_payload->GetString2() : ""; data += m_payload && m_payload->GetString5() ? *m_payload->GetString5() : ""; data += m_payload && m_payload->GetString1() ? *m_payload->GetString1() : ""; data += m_payload && m_payload->GetString4() ? *m_payload->GetString4() : ""; data += m_payload && m_payload->GetString3() ? *m_payload->GetString3() : ""; data += m_payload && m_payload->GetString7() ? *m_payload->GetString7() : ""; data += includeReferrer && GetReferrerAddress() ? *GetReferrerAddress() : ""; data += m_payload && m_payload->GetString6() ? *m_payload->GetString6() : ""; return Transaction::GenerateHash(data); } string User::PreBuildHash() { std::string data; data += m_payload && m_payload->GetString2() ? *m_payload->GetString2() : ""; data += m_payload && m_payload->GetString5() ? *m_payload->GetString5() : ""; data += m_payload && m_payload->GetString1() ? *m_payload->GetString1() : ""; data += m_payload && m_payload->GetString4() ? *m_payload->GetString4() : ""; data += m_payload && m_payload->GetString3() ? *m_payload->GetString3() : ""; data += m_payload && m_payload->GetString7() ? *m_payload->GetString7() : ""; data += GetReferrerAddress() ? *GetReferrerAddress() : ""; data += m_payload && m_payload->GetString6() ? *m_payload->GetString6() : ""; return data; } } // namespace PocketTx
45.992806
121
0.622712
dmaltsiniotis
fe5ec610ca9b45751b3be736b5e3e7e49f4bd5b0
917
cc
C++
coding/Reactor/v2/server_v2.cc
snow-tyan/learn-cpp
ecab0fae7999005ed7fdb60ff4954b4014b2c2e6
[ "MulanPSL-1.0" ]
null
null
null
coding/Reactor/v2/server_v2.cc
snow-tyan/learn-cpp
ecab0fae7999005ed7fdb60ff4954b4014b2c2e6
[ "MulanPSL-1.0" ]
null
null
null
coding/Reactor/v2/server_v2.cc
snow-tyan/learn-cpp
ecab0fae7999005ed7fdb60ff4954b4014b2c2e6
[ "MulanPSL-1.0" ]
null
null
null
#include "Acceptor.hh" #include "TCPConnection.hh" #include "EventLoop.hh" #include <iostream> #include <string> using namespace std; using namespace wd; // 普通函数版的回调函数 void onConnection(const TCPConnectionPtr &conn) { cout << conn->toString() << " has connected" << endl; conn->send("welcome to server"); } void onMessage(const TCPConnectionPtr &conn){ cout << "gets from client: " << conn->recv(); /** * 业务逻辑处理 * decode * compute * encode * **/ conn->send("wo hen shuai"); } void onClose(const TCPConnectionPtr &conn){ cout << ">> " << conn->toString() << " has disconnected" << endl; } int main() { Acceptor acceptor("172.25.40.81", 8888); acceptor.ready(); EventLoop event(acceptor); event.setConnectionCallback(onConnection); event.setMessageCallback(onMessage); event.setCloseCallback(onClose); event.loop(); return 0; }
20.840909
69
0.640131
snow-tyan
fe63bbd69243f9a5859bca41001b24b435590254
7,572
cc
C++
Source/MDEC.cc
dkoluris/pseudo
07a8d287f6b22ba70b73a012f560ff4a68dab2c3
[ "Apache-2.0" ]
40
2018-04-04T05:36:58.000Z
2021-11-15T02:03:05.000Z
Source/MDEC.cc
dkoluris/PSeudo
07a8d287f6b22ba70b73a012f560ff4a68dab2c3
[ "Apache-2.0" ]
1
2019-07-24T01:37:12.000Z
2019-09-10T07:58:12.000Z
Source/MDEC.cc
dkoluris/pseudo
07a8d287f6b22ba70b73a012f560ff4a68dab2c3
[ "Apache-2.0" ]
4
2018-09-19T10:29:44.000Z
2020-06-18T22:24:32.000Z
#include "Global.h" #define MAKERGB15(R, G, B) ((((R)>>3)<<10)|(((G)>>3)<<5)|((B)>>3)) #define ROUND(c) rtbl[(c) + 128 + 256] #define RGB15CL(N) IMAGE[N] = MAKERGB15(ROUND(GETY + R), ROUND(GETY + G), ROUND(GETY + B)); #define RGB24CL(N) IMAGE[N+ 2] = ROUND(GETY + R); IMAGE[N+ 1] = ROUND(GETY + G); IMAGE[N+ 0] = ROUND(GETY + B); #define MULR(A) (((sw)0x0000059B * (A)) >> 10) #define MULG(A) (((sw)0xFFFFFEA1 * (A)) >> 10) #define MULB(A) (((sw)0x00000716 * (A)) >> 10) #define MULF(A) (((sw)0xFFFFFD25 * (A)) >> 10) #define RUNOF(a) ((a)>>10) #define VALOF(a) ((sw)(((a)<<22)>>22)) CstrMotionDecoder mdec; void CstrMotionDecoder::reset() { rl = (uh *)&mem.ram.ptr[0x100000]; status = cmd = 0; for (sw k=0; k<256; k++) { rtbl[k+0x000] = 0; rtbl[k+0x100] = k; rtbl[k+0x200] = 255; } } void CstrMotionDecoder::write(uw addr, uw data) { switch(addr & 0xf) { case 0: cmd = data; if ((data&0xf5ff0000) == 0x30000000) { len = data&0xffff; } return; case 4: if (data & 0x80000000) { reset(); } return; } printx("/// PSeudo MDEC write: 0x%08x <- 0x%08x", addr, data); } uw CstrMotionDecoder::read(uw addr) { switch(addr & 0xf) { case 0: return cmd; case 4: return status; } printx("/// PSeudo MDEC read: 0x%08x", addr); return 0; } sw iq_y[64], iq_uv[64]; void CstrMotionDecoder::MacroBlock(sw *block, sw kh, sw sh) { for (sw k=0; k<8; k++, (sh) ? block+=8 : block++) { if((block[kh*1]| block[kh*2]| block[kh*3]| block[kh*4]| block[kh*5]| block[kh*6]| block[kh*7]) == 0) { block[kh*0]= block[kh*1]= block[kh*2]= block[kh*3]= block[kh*4]= block[kh*5]= block[kh*6]= block[kh*7]= block[kh*0]>>sh; continue; } sw z10 = block[kh*0]+block[kh*4]; sw z11 = block[kh*0]-block[kh*4]; sw z13 = block[kh*2]+block[kh*6]; sw z12 = block[kh*2]-block[kh*6]; z12 = ((z12*362)>>8)-z13; sw tmp0 = z10+z13; sw tmp3 = z10-z13; sw tmp1 = z11+z12; sw tmp2 = z11-z12; z13 = block[kh*3]+block[kh*5]; z10 = block[kh*3]-block[kh*5]; z11 = block[kh*1]+block[kh*7]; z12 = block[kh*1]-block[kh*7]; sw z5 = (((z12-z10)*473)>>8); sw tmp7 = z11+z13; sw tmp6 = (((z10)*669)>>8)+z5 -tmp7; sw tmp5 = (((z11-z13)*362)>>8)-tmp6; sw tmp4 = (((z12)*277)>>8)-z5 +tmp5; block[kh*0] = (tmp0+tmp7)>>sh; block[kh*7] = (tmp0-tmp7)>>sh; block[kh*1] = (tmp1+tmp6)>>sh; block[kh*6] = (tmp1-tmp6)>>sh; block[kh*2] = (tmp2+tmp5)>>sh; block[kh*5] = (tmp2-tmp5)>>sh; block[kh*4] = (tmp3+tmp4)>>sh; block[kh*3] = (tmp3-tmp4)>>sh; } } void CstrMotionDecoder::idct(sw *block, sw k) { if (k == 0) { sw val = block[0]>>5; for (sw i=0; i<64; i++) { block[i] = val; } return; } MacroBlock(block, 8, 0); MacroBlock(block, 1, 5); } void CstrMotionDecoder::TabInit(sw *iqtab, ub *iq_y) { for (sw i=0; i<64; i++) { iqtab[i] = iq_y[i]*aanscales[zscan[i]]>>12; } } uh *CstrMotionDecoder::rl2blk(sw *blk, uh *mdec_rl) { sw k,q_scale,rl; sw *iqtab; memset(blk, 0, 6*64*4); iqtab = iq_uv; for (sw i=0; i<6; i++) { if (i>1) iqtab = iq_y; rl = *mdec_rl++; q_scale = rl>>10; blk[0] = iqtab[0]*VALOF(rl); k = 0; for(;;) { rl = *mdec_rl++; if (rl==0xfe00) break; k += (rl>>10)+1;if (k > 63) break; blk[zscan[k]] = (iqtab[k] * q_scale * VALOF(rl)) >> 3; } idct(blk, k+1); blk+=64; } return mdec_rl; } void CstrMotionDecoder::Yuv15(sw *Block, uh *IMAGE) { sw GETY; sw CB,CR,R,G,B; sw *YYBLK = Block + 64 * 2; sw *CBBLK = Block; sw *CRBLK = Block + 64; for (sw Y=0; Y<16; Y+=2, CRBLK+=4, CBBLK+=4, YYBLK+=8, IMAGE+=24) { if (Y == 8) { YYBLK = YYBLK + 64; } for (sw X=0; X<4; X++, IMAGE+=2, CRBLK++, CBBLK++, YYBLK+=2) { CR = *CRBLK; CB = *CBBLK; R = MULR(CR); G = MULG(CB) + MULF(CR); B = MULB(CB); GETY = YYBLK[0]; RGB15CL(0x00); GETY = YYBLK[1]; RGB15CL(0x01); GETY = YYBLK[8]; RGB15CL(0x10); GETY = YYBLK[9]; RGB15CL(0x11); CR = *(CRBLK + 4); CB = *(CBBLK + 4); R = MULR(CR); G = MULG(CB) + MULF(CR); B = MULB(CB); GETY = YYBLK[64 + 0]; RGB15CL(0x08); GETY = YYBLK[64 + 1]; RGB15CL(0x09); GETY = YYBLK[64 + 8]; RGB15CL(0x18); GETY = YYBLK[64 + 9]; RGB15CL(0x19); } } } void CstrMotionDecoder::Yuv24(sw *Block, ub *IMAGE) { sw GETY; sw CB, CR, R, G, B; sw *YYBLK = Block + 64 * 2; sw *CBBLK = Block; sw *CRBLK = Block + 64; for (sw Y=0; Y<16; Y+=2, CRBLK+=4, CBBLK+=4, YYBLK+=8, IMAGE+=24*3) { if (Y == 8) { YYBLK = YYBLK + 64; } for (sw X=0; X<4; X++, IMAGE+=2*3, CRBLK++, CBBLK++, YYBLK+=2) { CR = *CRBLK; CB = *CBBLK; R = MULR(CR); G = MULG(CB) + MULF(CR); B = MULB(CB); GETY = YYBLK[0]; RGB24CL(0x00 * 3); GETY = YYBLK[1]; RGB24CL(0x01 * 3); GETY = YYBLK[8]; RGB24CL(0x10 * 3); GETY = YYBLK[9]; RGB24CL(0x11 * 3); CR = *(CRBLK + 4); CB = *(CBBLK + 4); R = MULR(CR); G = MULG(CB) + MULF(CR); B = MULB(CB); GETY = YYBLK[64 + 0]; RGB24CL(0x08 * 3); GETY = YYBLK[64 + 1]; RGB24CL(0x09 * 3); GETY = YYBLK[64 + 8]; RGB24CL(0x18 * 3); GETY = YYBLK[64 + 9]; RGB24CL(0x19 * 3); } } } void CstrMotionDecoder::executeDMA(CstrBus::castDMA *dma) { ub *p = &mem.ram.ptr[dma->madr&(mem.ram.size-1)]; sw z = (dma->bcr>>16)*(dma->bcr&0xffff); switch (dma->chcr&0xfff) { case 0x200: { sw blocksize, blk[384]; uh *im = (uh *)p; if (cmd&0x08000000) { blocksize = 256; } else { blocksize = 384; } for (; z>0; z-=blocksize/2, im+=blocksize) { rl = rl2blk(blk, rl); if (cmd&0x8000000) { Yuv15(blk, im); } else { Yuv24(blk, (ub *)im); } } break; } case 0x201: if (cmd == 0x40000001) { TabInit(iq_y, p); TabInit(iq_uv, p+64); } if ((cmd&0xf5ff0000) == 0x30000000) { rl = (uh *)p; } break; } }
26.200692
111
0.410195
dkoluris
fe646b8b115e272243b266d33377e414942eb92c
24,117
hpp
C++
SDKUsage6/VBMapViewer-SKT/VbNavKit-iOS/Classes/VbViewInfo/vbViewInfo.hpp
longxingtianxiaShuai/specialView
42fbdb1ee94fc0bd0c903e3c72c23808ec608139
[ "MIT" ]
1
2020-11-21T03:54:34.000Z
2020-11-21T03:54:34.000Z
SDKUsage6/VBMapViewer-SKT/VbNavKit-iOS/Classes/VbViewInfo/vbViewInfo.hpp
longxingtianxiaShuai/specialView
42fbdb1ee94fc0bd0c903e3c72c23808ec608139
[ "MIT" ]
null
null
null
SDKUsage6/VBMapViewer-SKT/VbNavKit-iOS/Classes/VbViewInfo/vbViewInfo.hpp
longxingtianxiaShuai/specialView
42fbdb1ee94fc0bd0c903e3c72c23808ec608139
[ "MIT" ]
3
2017-12-14T00:52:03.000Z
2019-08-08T22:25:04.000Z
#pragma once #include "Quaternion.hpp" #include "vbConfiguration.hpp" #include "vbGeometry.hpp" #include "vbCamera.hpp" #include "vbTrackCameraControl.hpp" #include "vbFPSCameraControl.hpp" #include "vbMoveOrbitZoomCameraControl.hpp" #include "vbMovingForwardCameraControl.hpp" #include "vbHorizontalPanCameraControl.hpp" #include "vbFreeCameraControl.hpp" #include "vbAnimationCameraControl.hpp" #include "vbPerspectiveProjection.hpp" #include "vbOrthogonalProjection.hpp" #include <vector> using std::vector; class vbViewInfo { public: vbViewInfo(); ~vbViewInfo(); enum ProjectionMode { PROJECTION_PERSPECTIVE=0, PROJECTION_ORTHO, PROJECTION_MODE_NONE }; enum NavigationMode { NAVIGATION_3D=0, NAVIGATION_2D, NAVIGATION_WALK, NAVIGATION_ME, NAVIGATION_2D_FIXED, //NAVIGATION_2D는 확대 축소 이동이 되지만 이것은 고정 뷰이다. NAVIGATION_ENVRN //환경맵용 고정 카메라 }; enum NavigationMode3D { NAVIGATION_3D_NONE=0, NAVIGATION_3D_ORBIT_V, NAVIGATION_3D_ORBIT_H, NAVIGATION_3D_PANZOOM, NAVIGATION_3D_ROTATEZOOM, NAVIGATION_3D_PAN, NAVIGATION_3D_ZOOM, NAVIGATION_3D_FIXED_V, //고정 상태에서 Pitch 제어(Vertical) NAVIGATION_3D_FIXED_H, //고정 상태에서 Yaw 제어 NAVIGATION_3D_ELEVATION, NAVIGATION_3D_FORWARD, NAVIGATION_3D_ZOOMHROTATION }; enum CameraAniMode { CAMERA_ANI_NONE = 0, CAMERA_ANI_JUMPPAN = 1, CAMERA_ANI_JUMPZOOM = 2, CAMERA_ANI_JUMPPANROT = 3, CAMERA_ANI_3D2WALK = 4, CAMERA_ANI_3DTO2D = 5, CAMERA_ANI_2DTO3D = 6, CAMERA_ANI_DEVICE_ROT = 7, CAMERA_ANI_FIXEDFREE = 8, CAMERA_ANI_YAW_ROTATE = 9, }; enum vbViewControlSet { vbViewControlSetDefaultLBS =0, //PISA vbViewControlSetYawPitch =1, //IIAC vbViewControlSetStandardI =2, //STD1 vbViewControlSetGongVueTypeA=3, //GongVue Type A vbViewControlSetZoneView =4, //Zone view - Yaw only vbViewControlSetPalladiON =5, //PISA default에서 수직 제어 없애고 수평 연속 회전 되도록 함. vbViewControlSetPlanar3D =6, //2touch planar rotation vbViewControlSetFixedFPS =7 //임의 좌표에서 임의 방향을 바라 볼 수 있도록 함(터치로는 제어 안됨) }; struct vbScreenControlAreaParam { /* 0 - LControl left px offset from Left 1 - LControl right px offset from Left 2 - RControl left px offset from Right 3 - RControl right px offset from 4 - BControl top px offset from bottom 5 - BControl bottom px offset from bottom 6 - TControl top px offset from top 7 - TControl bottom px offset from top */ unsigned short area_param[8]; }; enum vbViewScreenControlArea { vbViewScreenControlAreaMid = 0, vbViewScreenControlAreaTop = 1, vbViewScreenControlAreaLeft = 2, vbViewScreenControlAreaRight = 3, vbViewScreenControlAreaBottom = 4 }; protected: //vbConfiguration vbConfiguration* m_pConf; vbScreenControlAreaParam m_area_param; //GroundPlane vbPlane m_ground_plane; //Pan Valid range float m_pan_valid_ratio; //View Matrix mat4 m_view_matrix; //Projection Matrix mat4 m_prj_matrix; //view matrix X projection matrix - for Window/World conversion mat4 m_view_prj_matrix; bool m_bViewUpdated; //Projection mode ProjectionMode m_projection_mode; //Projection mode float m_min_near_clip; float m_rad_bounding_sphere; vec3 m_bounding_center; vec3 m_bound_min; vec3 m_bound_max; //Camera vbCamera m_Camera; //Move vbFPSCameraControl m_CameraFPSControl; vbMoveOrbitZoomCameraControl m_CameraZoomControl; vbHorizontalPanCameraControl m_CameraHPanControl; vbMovingForwardCameraControl m_CameraForwardControl; //Rotation vbTrackCameraControl m_CameraTrackControl; vbFreeCameraControl m_CameraFreeControl; //Animation vbAnimationCameraControl m_CameraAnimationControl; //Projection vbPerspectiveProjection m_CameraPerspective; vbOrthogonalProjection m_CameraOrthogonal; float m_cam_fMaxDistRatioBBSize; float m_cam_fMaxPanRatioToBSphereRad; bool m_cam_bJumpZoomed; //Environment sphere float m_cam_fEnvSphereRadius; //Camera animation CameraAniMode m_cam_ani_mode; float m_cam_jumpzoom_ratio; bool m_cam_jumpzoom_with_jumppan; // bool m_bBrokePan; bool m_bBrokeZoom; bool m_bBrokeRotate; //Navigation NavigationMode m_cam_navi_mode; //camera navigation mode NavigationMode m_cam_navi_mode_backup; //camera navigation mode NavigationMode3D m_cam_navi_3d_mode; // bool m_bNavigation; ivec2 m_DownPos_prev; vec3 m_cam_reference3D_first; //Reference 3d position 1 vec3 m_cam_reference3D_second; //Reference 3d position 2 //3D View camera backup Quaternion m_cam_3D_backup_rotation; vec3 m_cam_3D_backup_orbit_cntr; float m_cam_3D_backup_distance; //Turn angle float m_fDeviceAngle; vbViewDirection m_eViewDirection; //View mode vbViewControlSet m_eViewControlSet; float m_fRotateAreaRatio; //화면의 아래쪽에서 몇 %까지 수평 회전 영역에 쓸 것인지 (0~1) public: CameraAniMode GetAniMode() { return m_cam_ani_mode; }; vbMoveOrbitZoomCameraControl* GetCameraControl_OrbitZoom() { return &m_CameraZoomControl; } vbTrackCameraControl* GetCameraTrackControl() { return &m_CameraTrackControl; } //Turn vbViewDirection GetViewTurnDirection() { return m_eViewDirection; }; void SetViewTurnDirection(vbViewDirection dir, bool bAnimating=false); float GetDeviceAngle() { return m_fDeviceAngle; }; void UpdateDeviceAngleDeg(); ivec2 ConvertToRotatedDeviceCoord(ivec2 tPos); //Init void InitializeViewInfo(int width, int height, vbConfiguration* pConf); void ReloadConfiguration(); //Viewport void SetScreenSize(ivec2 screen_size); ivec2 GetScreenSize() ; ////////////////////////////////////// Projection - vbViewInfoProjection.cpp //View matrix mat4* GetViewMatrix() { return &m_view_matrix; } float const* GetViewMatrixPointer() { return m_view_matrix.Pointer(); } void SetViewMatrix(mat4 view_mat) { m_view_matrix = view_mat; } void UpdateViewMatrix(); //Projection matrix mat4* GetProjectionMatrix() { return &m_prj_matrix; } float const* GetProjectionMatrixPointer() { return m_prj_matrix.Pointer(); } void SetProjectionMatrix(mat4 view_mat) { m_prj_matrix = view_mat; } void UpdateProjectionMatrix(); ivec2 WorldToWindow(vec3 world_pt); void WindowToWorld(ivec2 win_pos, vec3& near_pt, vec3& far_pt); mat4* GetViewProjectionMatrix() { return &m_view_prj_matrix; } bool IsViewUpdated() { return m_bViewUpdated; } void SetViewUpdated(bool bUpdated) { m_bViewUpdated = bUpdated; } //Projection mode ProjectionMode GetProjectionMode() { return m_projection_mode; } void SetProjectionMode(ProjectionMode mode) { m_projection_mode = mode; } //Perspective void SetPerspectiveParameters(float* perspective_param); void SetPerspectiveParameters(float fovy, float aspect, float near, float far); const float* GetPerspectiveParameters(); void UpdateNearFarClip(); public: //Orthogonal void SetOrthogonalParameters(float left, float right, float bottom, float top, float near, float far); const float* GetOrthogonalParameters(); ////////////////////////////////////// Projection - vbViewInfoProjection.cpp ////////////////////////////////////// Navigation - vbViewInfoNavi.cpp //Fit void FitAABBtoScreen(bool bBoundMinMaxDist=false); void FitAABBtoVertices(std::vector<vec3>& target_vtx, bool bBoundMinMaxDist=false); //Ground void SetGroundPlane(vbPlane ground_plane) { m_ground_plane = ground_plane; } vbPlane GetGroundPlane() { return m_ground_plane; } float GetPanValidRatio() { return m_pan_valid_ratio; } void SetPanValidRatio(float pRatio) { m_pan_valid_ratio = pRatio; } void SetPanValidRange(vec3 min, vec3 max, float pRatio); //Orbit float GetTrackBallRatio(); void SetTrackBallRatio(float trRatio); void SetOrbitCenter(vec3 orbit_center); vec3 GetOrbitCenter(); void StartFreeRotation(ivec2 finger_pos); bool DoFreeRotation(ivec2 touchpoint); void StartRotation(ivec2 finger_pos); void StartHRotation(ivec2 finger_pos); void StartVRotation(ivec2 finger_pos); void StartYawPitchRotation(ivec2 finger_pos); bool DoOrbit(ivec2 touchpoint); //싱글터치, 초기 이동 방향에 따라 수직/수평 회전 bool DoYawRotation(ivec2 touchpoint); //수평 왕복 회전 bool DoContinuousYawRotation(ivec2 touchpoint); //수평 연속 회전 bool DoPitchRotation(ivec2 touchpoint); //수직 회전 bool DoYawPitchRotation(ivec2 touchpoint); //수직/수평 회전 bool DoLandscapeYawPitchRotation(ivec2 touchpoint); //VR용 수직,수평 회전 void EndRotation(); void JumpOrbit(ivec2 finger_pos); void SetHRotationRatio(float fVertialRatioFromBottom) { m_fRotateAreaRatio=fVertialRatioFromBottom;} float GetHRotationRatio() { return m_fRotateAreaRatio; } bool StartHRotationAnimation(float fStepYaw); bool EndHRotationAnimation(); //Panning void StartHPanning(ivec2 finger_pos); bool DoHPanning(ivec2 touchpoint); void EndHPanning(); void JumpPanning(ivec2 finger_pos); void JumpPanning(vec3 new_orbit_cntr); void JumpPanRotation(vec3 new_orbit_cntr, Quaternion new_orientation); void UpdateValidRange(vec3 bbMin, vec3 bbMax); //Zoom void StartZooming(ivec2 finger_pos); bool DoZooming(ivec2 touchpoint); void EndZooming(); void StartZooming2Pt(ivec2 finger_pos1,ivec2 finger_pos2); void StartZooming2PtEnvironment(ivec2 finger_pos1,ivec2 finger_pos2); bool DoZooming2Pt(ivec2 finger_pos1,ivec2 finger_pos2); bool DoZooming2PtEnvironment(ivec2 finger_pos1,ivec2 finger_pos2); void JumpZooming(ivec2 finger_pos); void SphereJumpZooming(ivec2 finger_pos); float GetPreviousZoomDistance(); void SetPreviousZoomDistance(float prevDist); //Pan & Zoom void StartPanZoom(ivec2 pos1, ivec2 pos2); bool DoPanZoom(ivec2 pos1, ivec2 pos2); void EndPanZoom(); //HRotate & Zoom void StartHRotateZoom(ivec2 pos1, ivec2 pos2); bool DoHRotateZoom(ivec2 pos1, ivec2 pos2); void EndHRotateZoom(); //Fixed Yaw & Pitch control void StartFixedYawPitchRotate(ivec2 pos1); void StartForwardZoom(ivec2 pos1, ivec2 pos2); void StartElevation(ivec2 pos1); bool DoFixedYawRotate(ivec2 pos1); bool DoFixedPitchRotate(ivec2 pos1); bool DoFixedYawPitchRotate(ivec2 pos1); bool DoForwardZoom(ivec2 pos1, ivec2 pos2); bool DoElevation(ivec2 pos1); void EndFixedYawPitchRotate(); void EndForwardZoom(); // void BrokeControl(bool bBrokePan, bool bBrokeZoom, bool bBrokeRotate); //Navi void InvalidateManipulation(); //2D-3D Camera void SetTopView(); void ReturnTo3DView(); //Walk float GetEyeHeight(); void SetEyeHeight(float eye_h); void InitWalk();//현재 회전 중심 위치로 내려가 걸어다닌다. void StartWalking(ivec2 finger_pos); bool DoWalking(ivec2 finger_pos); void EndWalking(); void SetWalkingCamera(vec3 pos, Quaternion dir); //FPS-Manipulation void StartFPS(); void EndFPS(); //Navigation mode bool IsNavigation() { return m_bNavigation; } void SetNavigation(bool bNavi) { m_bNavigation = bNavi; } NavigationMode GetNavigationMode() { return m_cam_navi_mode; } bool SetNavigationMode(NavigationMode nMode); void RecoverNavigationMode(); //Calculation vec3 MapToSphere(ivec2 touchpoint); vec3 GetRayFromCamera(ivec2 win_pos, vec3& fromPt); vec3 GetRayIntersectionWithGround(ivec2 ray_win_pos); //Ground = XY Plane ////////////////////////////////////// Navigation - vbViewInfoNavi.cpp ////////////////////////////////////// Camera - vbViewInfoCamera.cpp //camera position void SetCameraPosition(vec3 cam_pos); vec3 GetCameraPosition(); void UpdateCameraPositionFromOrbit();//Orbit center에서 지정된 distance에 지정 된 방향으로 위치 void UpdateCameraTargetPosition(); void UpdateOrbitCenterFromCamPosition(); void InitOrientation(bool bUpdateViewMat=true); void SetCameraPitchRatio(float pitch_ratio); float GetPitchRatio(); float GetPitchDegree(); float GetYawDegree(); void SetYawDegree(float fYaw); void SetYawDegree(vec3 dirYaw); void SetCamera(float cx, float cy, float cz, float yaw_deg_from_nZ, float pitch_deg_from_xz_plane, float fDist); //camera distance float GetCameraDistance(); void SetCameraDistance(float dist, bool bBoundMinMaxDistance=false); void SetCameraMaxDistanceRatioBBSize(float ratio) { m_cam_fMaxDistRatioBBSize = ratio; } void SetCameraMaxPanRatioBSphereRad(float ratio) { m_cam_fMaxPanRatioToBSphereRad = ratio; } void SetCameraMinMaxDistance(float fMinDistance, float fMaxDistance, bool bBoundMinMaxDist=false); //Zoom In/Out (Close to/ Far fromt Rot.Center) void MoveToRotationCenter(bool bToCenter); //Environmental map void SetEnvironmentalCamera(); //camera orientation void SetOrientation(Quaternion qtn); Quaternion GetOrientation(); //회전 쿼터니언을 반환한다. vec3 GetDirection(); //카메라의 방향 벡터 vec3 GetRight(); vec3 GetUp(); //Environment map float GetEnvironmentSphereRadius() { return m_cam_fEnvSphereRadius; } //camera fitting void FullExtendVertexVector(std::vector<vec3>& target_vtx, bool bBoundMinMaxDist=false); bool GetPerspectiveFittingCameraPosition(vec3 inputCameraDirection,/*대상을 바라보고 있을 카메라의 방향. 보통 현재 카메라의 방향*/ vec3 inputCameraUp,/*대상을 바라보고 있을 카메라의 Upvector.*/ float inputCameraFOV_Y_radian,/*카메라의 세로 방향 시야각*/ float inputCameraFOV_X_radian,/*카메라의 가로 방향 시야각*/ std::vector<vec3>& inputVts,/*Fitting 대상이 되는 점들*/ float inputFit_ratio,/* 1 : 화면에 꼭 맞게, 0.5 : 화면의 절반 크기에 맞게, 0.01 : 최소값*/ vec3& outputCameraPosition,/*카메라의 위치*/ vec3& outputOrbitCenter,//New orbit center bool& outVerticalFit,/*세로방향으로 맞췄는지 여부*/ float& outDistance, bool bBoundMinMaxDist=false);// //Orthogonal mode에서 Fitting bool GetOrthogonalFittingCameraPosition(vec3 inputCameraDirection/*대상을 바라보고 있을 카메라의 방향. 보통 현재 카메라의 방향*/, vec3 inputCameraUp/*대상을 바라보고 있을 카메라의 Upvector.*/, std::vector<vec3>& inputVts/*Fitting 대상이 되는 점들*/, float inputFit_ratio/* 1 : 화면에 꼭 맞게, 0.5 : 화면의 절반 크기에 맞게, 0.01 : 최소값*/, float inputDistance_for_ortho/*직교투영은 원근감이 없으므로, 거리에 상관없이 동일한 화면이 나오기 때문에 거리를 지정해야 한다*/, float inputViewAspectRatio/* Width/height*/, vec3& outputCameraPosition/*카메라의 위치*/, float& outputCamWidth/*카메라의 Orthogonal Width*/, float& outputCamHeight/*카메라의 Orthogonal Height*/, bool& outVerticalFit);/*세로방향으로 맞췄는지 여부*/ void UpdateCameraDistWithScreenCenter(bool bBoundMinMaxDist=false); // ////////////////////////////////////// Camera - vbViewInfoCamera.cpp //////////////////// RANGE PARAMETER const vbScreenControlAreaParam* GetScreenAreaParam() { return (const vbScreenControlAreaParam*)&m_area_param; } void SetScreenAreaParam(const vbScreenControlAreaParam* pParam); vbViewScreenControlArea IsScreenControlArea(ivec2 tPos); ////////////////////////////////////// Interaction - vbViewInfoFinger.cpp //Touch interaction bool SingleFingerUp(ivec2 tPos, int tapCount, vec3& pos3d); void SingleFingerDown(ivec2 tPos, int tapCount); bool SingleFingerMove(ivec2 tPos, int tapCount); bool DoubleFingerUp(ivec2 pos1/*pressed*/, int tapCount1,ivec2 pos2/*unpressed*/, int tapCount2); void DoubleFingerDown(ivec2 pos1, int tapCount1,ivec2 pos2, int tapCount2); bool DoubleFingerMove(ivec2 pos1, int tapCount1,ivec2 pos2, int tapCount2); vbViewControlSet GetViewControlSet() { return m_eViewControlSet; } void SetViewControlSet(vbViewControlSet viewControlSet) { m_eViewControlSet = viewControlSet; } /////////////// ViewControlSet별 이벤트 처리 함수 //////////// Default bool SingleFingerUp_Default(ivec2 tPos, int tapCount, vec3& pos3d); void SingleFingerDown_Default(ivec2 tPos, int tapCount); bool SingleFingerMove_Default(ivec2 tPos, int tapCount); bool DoubleFingerUp_Default(ivec2 pos1/*pressed*/, int tapCount1,ivec2 pos2/*unpressed*/, int tapCount2); void DoubleFingerDown_Default(ivec2 pos1, int tapCount1,ivec2 pos2, int tapCount2); bool DoubleFingerMove_Default(ivec2 pos1, int tapCount1,ivec2 pos2, int tapCount2); //////////// Yaw & Pitch bool SingleFingerUp_YawPitch(ivec2 tPos, int tapCount, vec3& pos3d); void SingleFingerDown_YawPitch(ivec2 tPos, int tapCount); bool SingleFingerMove_YawPitch(ivec2 tPos, int tapCount); bool DoubleFingerUp_YawPitch(ivec2 pos1/*pressed*/, int tapCount1,ivec2 pos2/*unpressed*/, int tapCount2); void DoubleFingerDown_YawPitch(ivec2 pos1, int tapCount1,ivec2 pos2, int tapCount2); bool DoubleFingerMove_YawPitch(ivec2 pos1, int tapCount1,ivec2 pos2, int tapCount2); //////////// STD1 bool SingleFingerUp_STD1(ivec2 tPos, int tapCount, vec3& pos3d); void SingleFingerDown_STD1(ivec2 tPos, int tapCount); bool SingleFingerMove_STD1(ivec2 tPos, int tapCount); bool DoubleFingerUp_STD1(ivec2 pos1/*pressed*/, int tapCount1,ivec2 pos2/*unpressed*/, int tapCount2); void DoubleFingerDown_STD1(ivec2 pos1, int tapCount1,ivec2 pos2, int tapCount2); bool DoubleFingerMove_STD1(ivec2 pos1, int tapCount1,ivec2 pos2, int tapCount2); //////////// GongVueA bool SingleFingerUp_GongVueA(ivec2 tPos, int tapCount, vec3& pos3d); void SingleFingerDown_GongVueA(ivec2 tPos, int tapCount); bool SingleFingerMove_GongVueA(ivec2 tPos, int tapCount); bool DoubleFingerUp_GongVueA(ivec2 pos1/*pressed*/, int tapCount1,ivec2 pos2/*unpressed*/, int tapCount2); void DoubleFingerDown_GongVueA(ivec2 pos1, int tapCount1,ivec2 pos2, int tapCount2); bool DoubleFingerMove_GongVueA(ivec2 pos1, int tapCount1,ivec2 pos2, int tapCount2); //////////// ZoneView bool SingleFingerUp_ZoneView(ivec2 tPos, int tapCount, vec3& pos3d); void SingleFingerDown_ZoneView(ivec2 tPos, int tapCount); bool SingleFingerMove_ZoneView(ivec2 tPos, int tapCount); bool DoubleFingerUp_ZoneView(ivec2 pos1/*pressed*/, int tapCount1,ivec2 pos2/*unpressed*/, int tapCount2); void DoubleFingerDown_ZoneView(ivec2 pos1, int tapCount1,ivec2 pos2, int tapCount2); bool DoubleFingerMove_ZoneView(ivec2 pos1, int tapCount1,ivec2 pos2, int tapCount2); //////////// PalladiON bool SingleFingerUp_PalladiON(ivec2 tPos, int tapCount, vec3& pos3d); void SingleFingerDown_PalladiON(ivec2 tPos, int tapCount); bool SingleFingerMove_PalladiON(ivec2 tPos, int tapCount); bool DoubleFingerUp_PalladiON(ivec2 pos1/*pressed*/, int tapCount1,ivec2 pos2/*unpressed*/, int tapCount2); void DoubleFingerDown_PalladiON(ivec2 pos1, int tapCount1,ivec2 pos2, int tapCount2); bool DoubleFingerMove_PalladiON(ivec2 pos1, int tapCount1,ivec2 pos2, int tapCount2); //////////// Planar3D bool SingleFingerUp_Planar3D(ivec2 tPos, int tapCount, vec3& pos3d); void SingleFingerDown_Planar3D(ivec2 tPos, int tapCount); bool SingleFingerMove_Planar3D(ivec2 tPos, int tapCount); bool DoubleFingerUp_Planar3D(ivec2 pos1/*pressed*/, int tapCount1,ivec2 pos2/*unpressed*/, int tapCount2); void DoubleFingerDown_Planar3D(ivec2 pos1, int tapCount1,ivec2 pos2, int tapCount2); bool DoubleFingerMove_Planar3D(ivec2 pos1, int tapCount1,ivec2 pos2, int tapCount2); ////////////////////////////////////// Interaction - vbViewInfoFinger.cpp /////////////////////////////////////// Animation - vbViewInfoAnimation.cpp void UseCameraAnimation(bool bUseCameraAnimation); bool IsCameraAnimationAvailable(); void UpdateAnimationFrame(); bool UpdateWalkingAnimation(); void InitCameraMoveAni(vec3 pos_start, vec3 pos_end, Quaternion dir_start, Quaternion dir_end, CameraAniMode aniMode); void InitDeviceRotateAni(vbViewDirection eEndDirection); void UpdateAnimatedCamera(); bool IsOnAnimating(); /////////////////////////////////////// Animation - vbViewInfoAnimation.cpp ///////// };
39.471358
149
0.605133
longxingtianxiaShuai
fe64c0925f28eda9ebd199765300661a2a2fc3f1
5,051
cc
C++
src/allocator/CrSeparableAllocator.cc
qzcx/supersim
34829411d02fd3bd3f3d7a075edef8749eb8748e
[ "Apache-2.0" ]
17
2017-05-09T07:08:41.000Z
2021-08-03T01:22:09.000Z
src/allocator/CrSeparableAllocator.cc
qzcx/supersim
34829411d02fd3bd3f3d7a075edef8749eb8748e
[ "Apache-2.0" ]
6
2016-12-02T22:07:31.000Z
2020-04-22T07:43:42.000Z
src/allocator/CrSeparableAllocator.cc
qzcx/supersim
34829411d02fd3bd3f3d7a075edef8749eb8748e
[ "Apache-2.0" ]
13
2016-12-02T22:01:04.000Z
2020-03-23T16:44:04.000Z
/* * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * See the NOTICE file distributed with this work for additional information * regarding copyright ownership. 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 "allocator/CrSeparableAllocator.h" #include <factory/ObjectFactory.h> #include <cassert> #include "arbiter/Arbiter.h" CrSeparableAllocator::CrSeparableAllocator( const std::string& _name, const Component* _parent, u32 _numClients, u32 _numResources, Json::Value _settings) : Allocator(_name, _parent, _numClients, _numResources, _settings) { // pointer arrays requests_ = new bool*[numClients_ * numResources_]; metadatas_ = new u64*[numClients_ * numResources_]; intermediates_ = new bool[numClients_ * numResources_]; grants_ = new bool*[numClients_ * numResources_]; // use vector to hold arbiter pointers clientArbiters_.resize(numClients_, nullptr); resourceArbiters_.resize(numResources_, nullptr); // instantiate the client arbiters for (u32 c = 0; c < numClients_; c++) { std::string name = "ArbiterC" + std::to_string(c); clientArbiters_[c] = Arbiter::create( name, this, numResources_, _settings["client_arbiter"]); } // instantiate the resource arbiters for (u32 r = 0; r < numResources_; r++) { std::string name = "ArbiterR" + std::to_string(r); resourceArbiters_[r] = Arbiter::create( name, this, numClients_, _settings["resource_arbiter"]); } // map intermediate request signals to arbiters for (u32 c = 0; c < numClients_; c++) { for (u32 r = 0; r < numResources_; r++) { bool* i = &intermediates_[index(c, r)]; clientArbiters_[c]->setGrant(r, i); resourceArbiters_[r]->setRequest(c, i); } } // parse settings iterations_ = _settings["iterations"].asUInt(); assert(iterations_ > 0); slipLatch_ = _settings["slip_latch"].asBool(); } CrSeparableAllocator::~CrSeparableAllocator() { for (u32 c = 0; c < numClients_; c++) { delete clientArbiters_[c]; } for (u32 r = 0; r < numResources_; r++) { delete resourceArbiters_[r]; } delete[] requests_; delete[] metadatas_; delete[] intermediates_; delete[] grants_; } void CrSeparableAllocator::setRequest(u32 _client, u32 _resource, bool* _request) { requests_[index(_client, _resource)] = _request; clientArbiters_[_client]->setRequest(_resource, _request); } void CrSeparableAllocator::setMetadata(u32 _client, u32 _resource, u64* _metadata) { metadatas_[index(_client, _resource)] = _metadata; clientArbiters_[_client]->setMetadata(_resource, _metadata); resourceArbiters_[_resource]->setMetadata(_client, _metadata); } void CrSeparableAllocator::setGrant(u32 _client, u32 _resource, bool* _grant) { grants_[index(_client, _resource)] = _grant; resourceArbiters_[_resource]->setGrant(_client, _grant); } void CrSeparableAllocator::allocate() { for (u32 remaining = iterations_; remaining > 0; remaining--) { // clear the intermediate stage for (u32 c = 0; c < numClients_; c++) { for (u32 r = 0; r < numResources_; r++) { intermediates_[index(c, r)] = false; } } // run the client arbiters for (u32 c = 0; c < numClients_; c++) { clientArbiters_[c]->arbitrate(); // perform arbiter state latching if (!slipLatch_) { // regular latch always algorithm clientArbiters_[c]->latch(); } } // run the resource arbiters for (u32 r = 0; r < numResources_; r++) { u32 winningClient = resourceArbiters_[r]->arbitrate(); if (winningClient != U32_MAX) { // remove the requests from this client for (u32 r = 0; r < numResources_; r++) { *requests_[index(winningClient, r)] = false; } // remove the requests for this resource for (u32 c = 0; c < numClients_; c++) { *requests_[index(c, r)] = false; } } // perform arbiter state latching if (slipLatch_) { // slip latching (iSLIP algorithm) if (winningClient != U32_MAX) { resourceArbiters_[r]->latch(); clientArbiters_[winningClient]->latch(); } } else { // regular latch always algorithm resourceArbiters_[r]->latch(); } } } } u64 CrSeparableAllocator::index(u64 _client, u64 _resource) const { return (numResources_ * _client) + _resource; } registerWithObjectFactory("cr_separable", Allocator, CrSeparableAllocator, ALLOCATOR_ARGS);
33.230263
79
0.659671
qzcx
fe6621bb397652b3be2692121a1c61081b7f521c
5,279
hpp
C++
include/xleaflet/xtile_layer.hpp
jtpio/xleaflet
67df1c06ef7b8bb753180bfea545e5ad38ac88b3
[ "BSD-3-Clause" ]
null
null
null
include/xleaflet/xtile_layer.hpp
jtpio/xleaflet
67df1c06ef7b8bb753180bfea545e5ad38ac88b3
[ "BSD-3-Clause" ]
null
null
null
include/xleaflet/xtile_layer.hpp
jtpio/xleaflet
67df1c06ef7b8bb753180bfea545e5ad38ac88b3
[ "BSD-3-Clause" ]
null
null
null
/****************************************************************************** * Copyright (c) 2018, Sylvain Corlay and Johan Mabille, and Wolf Vollprecht * * * * Distributed under the terms of the BSD 3-Clause License. * * * * The full license is in the file LICENSE, distributed with this software. * *******************************************************************************/ #ifndef XLEAFLET_TILE_LAYER_HPP #define XLEAFLET_TILE_LAYER_HPP #include <string> #include "xwidgets/xmaterialize.hpp" #include "xwidgets/xwidget.hpp" #include "xleaflet_config.hpp" #include "xraster_layer.hpp" namespace xlf { /************************** * tile_layer declaration * **************************/ template <class D> class xtile_layer : public xraster_layer<D> { public: using load_callback_type = std::function<void(const xeus::xjson&)>; using base_type = xraster_layer<D>; using derived_type = D; void serialize_state(xeus::xjson&, xeus::buffer_sequence&) const; void apply_patch(const xeus::xjson&, const xeus::buffer_sequence&); void on_load(load_callback_type); void handle_custom_message(const xeus::xjson&); XPROPERTY( std::string, derived_type, url, "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"); XPROPERTY(int, derived_type, min_zoom, 0); XPROPERTY(int, derived_type, max_zoom, 18); XPROPERTY(int, derived_type, tile_size, 256); XPROPERTY( std::string, derived_type, attribution, "Map data (c) <a href=\"https://openstreetmap.org\">OpenStreetMap</a> contributors"); XPROPERTY(bool, derived_type, detect_retina, false); protected: xtile_layer(); using base_type::base_type; private: void set_defaults(); std::list<load_callback_type> m_load_callbacks; }; using tile_layer = xw::xmaterialize<xtile_layer>; using tile_layer_generator = xw::xgenerator<xtile_layer>; /****************************** * xtile_layer implementation * ******************************/ template <class D> inline void xtile_layer<D>::serialize_state(xeus::xjson& state, xeus::buffer_sequence& buffers) const { base_type::serialize_state(state, buffers); using xw::set_patch_from_property; set_patch_from_property(url, state, buffers); set_patch_from_property(min_zoom, state, buffers); set_patch_from_property(max_zoom, state, buffers); set_patch_from_property(tile_size, state, buffers); set_patch_from_property(attribution, state, buffers); set_patch_from_property(detect_retina, state, buffers); } template <class D> inline void xtile_layer<D>::apply_patch(const xeus::xjson& patch, const xeus::buffer_sequence& buffers) { base_type::apply_patch(patch, buffers); using xw::set_property_from_patch; set_property_from_patch(url, patch, buffers); set_property_from_patch(min_zoom, patch, buffers); set_property_from_patch(max_zoom, patch, buffers); set_property_from_patch(tile_size, patch, buffers); set_property_from_patch(attribution, patch, buffers); set_property_from_patch(detect_retina, patch, buffers); } template <class D> inline void xtile_layer<D>::on_load(load_callback_type callback) { m_load_callbacks.emplace_back(std::move(callback)); } template <class D> inline xtile_layer<D>::xtile_layer() : base_type() { set_defaults(); } template <class D> inline void xtile_layer<D>::set_defaults() { this->_model_name() = "LeafletTileLayerModel"; this->_view_name() = "LeafletTileLayerView"; this->bottom() = true; this->options().insert( this->options().end(), { "min_zoom", "max_zoom", "tile_size", "attribution", "detect_retina" } ); } template <class D> inline void xtile_layer<D>::handle_custom_message(const xeus::xjson& content) { auto it = content.find("event"); if (it != content.end() && it.value() == "load") { for (auto it = m_load_callbacks.begin(); it != m_load_callbacks.end(); ++it) { it->operator()(content); } } } } /********************* * precompiled types * *********************/ #ifndef _WIN32 extern template class xw::xmaterialize<xlf::xtile_layer>; extern template xw::xmaterialize<xlf::xtile_layer>::xmaterialize(); extern template class xw::xtransport<xw::xmaterialize<xlf::xtile_layer>>; extern template class xw::xgenerator<xlf::xtile_layer>; extern template xw::xgenerator<xlf::xtile_layer>::xgenerator(); extern template class xw::xtransport<xw::xgenerator<xlf::xtile_layer>>; #endif #endif
31.610778
97
0.569805
jtpio
fe6714896167e506eeece31516e164508c4a440e
3,579
cpp
C++
owCore/MPQArchiveManager.cpp
adan830/OpenWow
9b6e9c248bd185b1677fe616d2a3a81a35ca8894
[ "Apache-2.0" ]
null
null
null
owCore/MPQArchiveManager.cpp
adan830/OpenWow
9b6e9c248bd185b1677fe616d2a3a81a35ca8894
[ "Apache-2.0" ]
null
null
null
owCore/MPQArchiveManager.cpp
adan830/OpenWow
9b6e9c248bd185b1677fe616d2a3a81a35ca8894
[ "Apache-2.0" ]
1
2020-05-11T13:32:49.000Z
2020-05-11T13:32:49.000Z
#include "stdafx.h" // General #include "MPQArchiveManager.h" // Additional #include "BaseManager.h" #if (VERSION == VERSION_Vanila) const char* archives = "D:/_games/World of Warcraft 1.12.1/Data/"; #elif (VERSION == VERSION_WotLK) const char* archives = "D:/_games/World of Warcraft 3.3.5a/Data/"; #endif // CMPQArchiveManager::CMPQArchiveManager() { AddManager<IMPQArchiveManager>(this); // Files 1.12 #if (VERSION == VERSION_Vanila) AddArchive(string("backup.MPQ")); AddArchive(string("base.MPQ")); AddArchive(string("dbc.MPQ")); AddArchive(string("fonts.MPQ")); AddArchive(string("interface.MPQ")); AddArchive(string("misc.MPQ")); AddArchive(string("model.MPQ")); AddArchive(string("patch.MPQ")); AddArchive(string("patch-2.MPQ")); AddArchive(string("patch-3.MPQ")); AddArchive(string("sound.MPQ")); AddArchive(string("speech.MPQ")); AddArchive(string("terrain.MPQ")); AddArchive(string("texture.MPQ")); AddArchive(string("wmo.MPQ")); //AddArchive(string("ruRU/patch-1.MPQ")); //AddArchive(string("ruRU/patch-2.MPQ")); //AddArchive(string("ruRU/patch-3.MPQ")); #elif (VERSION == VERSION_WotLK) AddArchive(string("common.MPQ")); AddArchive(string("common-2.MPQ")); AddArchive(string("expansion.MPQ")); AddArchive(string("lichking.MPQ")); AddArchive(string("patch.MPQ")); AddArchive(string("patch-2.MPQ")); AddArchive(string("patch-3.MPQ")); //AddArchive(string("patch-w.MPQ")); //AddArchive(string("patch-x.MPQ")); AddArchive(string("ruRU/locale-ruRU.MPQ")); AddArchive(string("ruRU/expansion-locale-ruRU.MPQ")); AddArchive(string("ruRU/lichking-locale-ruRU.MPQ")); AddArchive(string("ruRU/patch-ruRU.MPQ")); AddArchive(string("ruRU/patch-ruRU-2.MPQ")); AddArchive(string("ruRU/patch-ruRU-3.MPQ")); //AddArchive(string("ruRU/patch-ruRU-w.MPQ")); //AddArchive(string("ruRU/patch-ruRU-x.MPQ")); #endif } CMPQArchiveManager::~CMPQArchiveManager() { for (auto it : m_OpenArchives) { libmpq__archive_close(it); } } void CMPQArchiveManager::AddArchive(string filename) { mpq_archive_s* mpq_a; int result = libmpq__archive_open(&mpq_a, (archives + filename).c_str(), -1); Log::Info("Opening %s", filename.c_str()); if (result) { switch (result) { case LIBMPQ_ERROR_OPEN: Log::Error("Error opening archive [%s]: Does file really exist?", filename.c_str()); break; case LIBMPQ_ERROR_FORMAT: /* bad file format */ Log::Error("Error opening archive [%s]: Bad file format", filename.c_str()); break; case LIBMPQ_ERROR_SEEK: /* seeking in file failed */ Log::Error("Error opening archive [%s]: Seeking in file failed", filename.c_str()); break; case LIBMPQ_ERROR_READ: /* Read error in archive */ Log::Error("Error opening archive [%s]: Read error in archive", filename.c_str()); break; case LIBMPQ_ERROR_MALLOC: /* maybe not enough memory? :) */ Log::Error("Error opening archive [%s]: Maybe not enough memory", filename.c_str()); break; default: Log::Error("Error opening archive [%s]: Unknown error\n", filename.c_str()); break; } return; } m_OpenArchives.push_back(mpq_a); Log::Green("CMPQFile[%s]: Added!", filename.c_str()); } SMPQFileLocation CMPQArchiveManager::GetFileLocation(cstring filename) { for (auto& i = m_OpenArchives.rbegin(); i != m_OpenArchives.rend(); ++i) { mpq_archive_s* mpq_a = *i; uint32 filenum; if (libmpq__file_number(mpq_a, filename.c_str(), &filenum) == LIBMPQ_ERROR_EXIST) { continue; } return SMPQFileLocation(mpq_a, filenum); } return SMPQFileLocation(); }
26.708955
87
0.689299
adan830
fe68694ab44d19786184d2d8a3724bc0cd9ed6cf
1,666
cpp
C++
SPOJ/MB1.cpp
PiyushArora01/Coding
4f1e61317313fa3a9ea78b221b3ec03d9f256862
[ "Apache-2.0" ]
1
2016-09-01T13:57:27.000Z
2016-09-01T13:57:27.000Z
SPOJ/MB1.cpp
PiyushArora01/Coding
4f1e61317313fa3a9ea78b221b3ec03d9f256862
[ "Apache-2.0" ]
null
null
null
SPOJ/MB1.cpp
PiyushArora01/Coding
4f1e61317313fa3a9ea78b221b3ec03d9f256862
[ "Apache-2.0" ]
null
null
null
#include <iostream> using namespace std; int main() { int test; cin >> test; int PP[] = {2, 3, 5, 7, 11, 101, 131, 151, 181, 191, 313, 353, 373, 383, 727, 757, 787, 797, 919, 929, 10301, 10501, 10601, 11311, 11411, 12421, 12721, 12821, 13331, 13831, 13931, 14341, 14741, 15451, 15551, 16061, 16361, 16561, 16661, 17471, 17971, 18181, 18481, 19391, 19891, 19991, 30103, 30203, 30403, 30703, 30803, 31013, 31513, 32323, 32423, 33533, 34543, 34843, 35053, 35153, 35353, 35753, 36263, 36563, 37273, 37573, 38083, 38183, 38783, 39293, 70207, 70507, 70607, 71317, 71917, 72227, 72727, 73037, 73237, 73637, 74047, 74747, 75557, 76367, 76667, 77377, 77477, 77977, 78487, 78787, 78887, 79397, 79697, 79997, 90709, 91019, 93139, 93239, 93739, 94049, 94349, 94649, 94849, 94949, 95959, 96269, 96469, 96769, 97379, 97579, 97879, 98389, 98689}; int P[] = {3, 5, 11, 17, 2, 2, 5, 11, 19, 23, 23, 197, 307, 359, 521, 1553, 2693, 3083, 419, 953, 5, 11, 13, 5, 7, 53, 107, 131, 103, 359, 419, 223, 613, 541, 691, 151, 593, 1069, 1321, 1193, 3083, 311, 1619, 1543, 4813, 5519, 23, 61, 151, 307, 359, 23, 197, 593, 827, 2789, 5443, 9311, 1427, 1427, 5039, 13249, 4813, 13697, 6857, 19447, 4211, 4211, 38197, 12197, 521, 1553, 1931, 853, 3083, 2693, 11353, 3083, 6857, 23789, 6007, 53881, 60761, 51713, 111599, 72871, 100169, 244691, 134587, 248851, 288359, 127081, 272141, 424243, 4127, 419, 5519, 12197, 49681, 10627, 36677, 79349, 109037, 124181, 202987, 57559, 124181, 229727, 127081, 222863, 373019, 170627, 364523}; while(test--) { int n; cin >> n; cout << PP[n-1] << " " << P[n-1] << endl; } return 0; }
83.3
759
0.629652
PiyushArora01
fe71bebe3277551d644585d06fabee4d87d7ca83
20,442
cxx
C++
HLT/BASE/util/ZMQESDserver.cxx
shahor02/AliRoot
37118c83effe7965a2a24b3b868bf9012727fb7e
[ "BSD-3-Clause" ]
52
2016-12-11T13:04:01.000Z
2022-03-11T11:49:35.000Z
HLT/BASE/util/ZMQESDserver.cxx
shahor02/AliRoot
37118c83effe7965a2a24b3b868bf9012727fb7e
[ "BSD-3-Clause" ]
1,388
2016-11-01T10:27:36.000Z
2022-03-30T15:26:09.000Z
HLT/BASE/util/ZMQESDserver.cxx
shahor02/AliRoot
37118c83effe7965a2a24b3b868bf9012727fb7e
[ "BSD-3-Clause" ]
275
2016-06-21T20:24:05.000Z
2022-03-31T13:06:19.000Z
#include "AliESDEvent.h" #include "AliESDtrack.h" #include "AliHLTZMQhelpers.h" #include "AliOptionParser.h" #include "TFile.h" #include "TSystem.h" #include "TTree.h" #include "signal.h" #include "zmq.h" #include <iostream> #include <memory> #include <pthread.h> #include <string> #include <sys/time.h> #include <time.h> #include <unistd.h> using namespace AliZMQhelpers; // methods Int_t ProcessOptionString(TString arguments, Bool_t verbose = kFALSE); Int_t InitZMQ(); Int_t Run(); Int_t HandleRequest(aliZMQmsg::iterator block, void* /*socket*/ = NULL); Int_t DoSend(void* socket); Int_t HandleControlSequence(aliZMQmsg::iterator block, void* socket); void SetLastPushBackTime(); template <typename T> class o2vec; template <typename T> void alizmq_deleteArray(void* data, void*); template <typename T> int alizmq_msg_add_array(aliZMQmsg* message, o2vec<T>&& vec); // configuration vars Bool_t fVerbose = kFALSE; TString fZMQconfigOUT = "PUSH"; Int_t fZMQmaxQueueSize = 10; Int_t fZMQtimeout = -1; int fZMQlingerTime = 30000; //30s default linger std::vector<std::string> fFilesIn; std::string fInfo; // cache for the info string std::string fID; // merger ID/name long fPushbackPeriod = -1; // in seconds, -1 means never long fRequestPeriod = -1; // in seconds, -1 means never long fRequestTimeout = 10000; // default 10s aliZMQrootStreamerInfo fSchema; bool fSchemaOnRequest = false; bool fSchemaOnSend = false; int fCompression = 1; bool fgTerminationSignaled = false; bool fOnce = true; unsigned long long fLastPushBackTime = 0; unsigned long long fLastRequestTime = 0; struct timeval fCurrentTimeStruct; uint64_t fBytesOUT = 0; unsigned long fSecondsStart = 0; unsigned long fSecondsStop = 0; unsigned long long fNumberOfMessagesSent = 0; // ZMQ stuff void* fZMQcontext = NULL; // ze zmq context void* fZMQout = NULL; // the monitoring socket, here we publish a copy of the data void* fZMQresetBroadcast = NULL; bool fReconfigureZMQ = true; const char* fUSAGE = "ZMQESDserver options: \n" " -id : some string identifier\n" " -in : comma separated list of input files, e.g. AliESDs.root,../AliESDs.root\n" " -out : data out, format is zmq config string, e.g. PUSH+tcp://localhost:123123 or REP@tcp://*:123123\n" " -once : [0|1] run once, or run forever" " -ZMQlinger : [ms] - how long to wait for socket to send pending data before forcing close" " -Verbose : print some info\n"; //_______________________________________________________________________________________ void sig_handler(int signo) { if (signo == SIGINT) printf(" received SIGINT\n"); fgTerminationSignaled = true; } //_______________________________________________________________________________________ Int_t Run() { // start time (sec) gettimeofday(&fCurrentTimeStruct, NULL); fSecondsStart = fCurrentTimeStruct.tv_sec; // main loop while (!fgTerminationSignaled) { Int_t nSockets = 1; zmq_pollitem_t sockets[] = { { fZMQout, 0, ZMQ_POLLIN | ZMQ_POLLOUT, 0 }, }; Int_t rc = 0; errno = 0; Int_t outType = alizmq_socket_type(fZMQout); // poll sockets for data or conditions rc = zmq_poll(sockets, nSockets, fZMQtimeout); // poll sockets if (rc == -1 && errno == ETERM) { // this can only happen it the context was terminated, one of the sockets are // not valid or operation was interrupted Printf("zmq_poll was interrupted! rc = %i, %s", rc, zmq_strerror(errno)); break; } if (alizmq_socket_type(fZMQout) == ZMQ_REP) { // request waiting if (sockets[0].revents & ZMQ_POLLIN) { printf("request in\n"); aliZMQmsg message; alizmq_msg_recv(&message, fZMQout, 0); for (aliZMQmsg::iterator i = message.begin(); i != message.end(); ++i) { HandleRequest(i, fZMQout); } alizmq_msg_close(&message); } } // socket 0 else if (sockets[0].revents & ZMQ_POLLOUT) { DoSend(fZMQout); } } // main loop // stop time (sec) gettimeofday(&fCurrentTimeStruct, NULL); fSecondsStop = fCurrentTimeStruct.tv_sec; { printf("number of messages sent : %llu\n", fNumberOfMessagesSent); printf("out %lubytes, %.2f MB\n", fBytesOUT, (double)(fBytesOUT) / 1024. / 1024.); } return 0; } //_____________________________________________________________________ Int_t HandleControlSequence(aliZMQmsg::iterator block, void* socket) { // handle control sequences in the request if any return 0; } //_____________________________________________________________________ Int_t HandleRequest(aliZMQmsg::iterator block, void* socket) { printf("HandleRequest\n"); HandleControlSequence(block, socket); return DoSend(socket); } // struct NameHeader: public BaseDataTopic { static constexpr int nameSize{32}; char _name[nameSize]; NameHeader(char const* name, bool more = false): BaseDataTopic(sizeof(NameHeader), CharArr2uint64("NameHead"), CharArr2uint64("NONE"), more), _name{} { strncpy(_name, name, nameSize); //set padding length in last byte uint8_t* lastByte = reinterpret_cast<uint8_t*>(this) + sizeof(NameHeader) - 1; *lastByte = nameSize-strlen(name); }; }; struct Header { DataTopic dataHeader; NameHeader nameHeader; Header(char const* name, const char* id, const char* origin, uint64_t spec=0): dataHeader{id,origin,spec,CharArr2uint64("NONE"),true}, nameHeader{name} {}; }; //______________________________________________________________________________ //this is a really stupid vector, push_back has no bounds checking! //it tries to minimize reallocations and can release the underlying buffer template<typename T> class o2vec { public: o2vec(Header header, size_t capacity=0) : _buf(capacity?new T[capacity]:new T[1]), //don't want to deal with corner cases _capacity{capacity}, _end(_buf.get()), _header(header) {} o2vec(const o2vec&) = delete; o2vec& operator=(const o2vec&) = delete; T* release() { return _buf.release(); } size_t free() { return _buf.get()+_capacity-_end; } size_t size() { return _end-_buf.get(); } size_t capacity() { return _capacity; } T& back() { return *(_end-1); } T* get() const { return _buf.get(); } void push_back(T i) { *_end++=i; } void reserve(size_t elems) { if (elems>_capacity){ T* tmp = new T[elems]; memcpy(tmp,_buf.get(),size()); _end=tmp+size(); _buf.reset(tmp); _capacity=elems; }; } Header* header() {return &_header;} void reserve_free(size_t elems) { if (elems>free()){ reserve(size()+elems); }; } private: std::unique_ptr<T[]> _buf; T* _end{nullptr}; size_t _capacity{0}; Header _header; }; //______________________________________________________________________________ Int_t DoSend(void* socket) { aliZMQmsg message; o2vec<int32_t> feventID(Header{"fEVID", "TRKPAREVID","ESD"}); o2vec<float> fX(Header{"fX", "TRKPARX","ESD"}); o2vec<float> fAlpha(Header{"fAlpha", "TRKPARAlpha","ESD"}); o2vec<float> fY(Header{"fY", "TRKPARY","ESD"}); o2vec<float> fZ(Header{"fZ", "TRKPARZ","ESD"}); o2vec<float> fSnp(Header{"fSnp", "TRKPARSnp","ESD"}); o2vec<float> fTgl(Header{"fTgl", "TRKPARTgl","ESD"}); o2vec<float> fSigned1Pt(Header{"fSigned1Pt", "TRKPARSigned1Pt","ESD"}); o2vec<float> fCYY(Header{"fCYY", "TRKCOVCYY","ESD"}); o2vec<float> fCZY(Header{"fCZY", "TRKCOVCZY","ESD"}); o2vec<float> fCZZ(Header{"fCZZ", "TRKCOVCZZ","ESD"}); o2vec<float> fCSnpY(Header{"fCSnpY", "TRKCOVCSnpY","ESD"}); o2vec<float> fCSnpZ(Header{"fCSnpZ", "TRKCOVCSnpZ","ESD"}); o2vec<float> fCSnpSnp(Header{"fCSnpSnp", "TRKCOVCSnpSnp","ESD"}); o2vec<float> fCTglY(Header{"fCTglY", "TRKCOVCTglY","ESD"}); o2vec<float> fCTglZ(Header{"fCTglZ", "TRKCOVCTglZ","ESD"}); o2vec<float> fCTglSnp(Header{"fCTglSnp", "TRKCOVCTglSnp","ESD"}); o2vec<float> fCTglTgl(Header{"fCTglTgl", "TRKCOVCTglTgl","ESD"}); o2vec<float> fC1PtY(Header{"fC1PtY", "TRKCOVC1PtY","ESD"}); o2vec<float> fC1PtZ(Header{"fC1PtZ", "TRKCOVC1PtZ","ESD"}); o2vec<float> fC1PtSnp(Header{"fC1PtSnp", "TRKCOVC1PtSnp","ESD"}); o2vec<float> fC1PtTgl(Header{"fC1PtTgl", "TRKCOVC1PtTgl","ESD"}); o2vec<float> fC1Pt21Pt2(Header{"fC1Pt21Pt2", "TRKCOVC1Pt21Pt2","ESD"}); o2vec<float> fTPCinnerP(Header{"fTPCinnerP", "TRKEXTTPCinnerP","ESD"}); o2vec<float> fFlags(Header{"fFlags", "TRKEXTFlags","ESD"}); o2vec<float> fITSClusterMap(Header{"fITSClusterMap", "TRKEXTITSClsMap","ESD"}); o2vec<float> fTPCncls(Header{"fTPCncls", "TRKEXTTPCncls","ESD"}); o2vec<float> fTRDntracklets(Header{"fTRDntracklets", "TRKEXTTRDntrklts","ESD"}); o2vec<float> fITSchi2Ncl(Header{"fITSchi2Ncl", "TRKEXTITSchi2Ncl","ESD"}); o2vec<float> fTPCchi2Ncl(Header{"fTPCchi2Ncl", "TRKEXTTPCchi2Ncl","ESD"}); o2vec<float> fTRDchi2(Header{"fTRDchi2", "TRKEXTTRDchi2","ESD"}); o2vec<float> fTOFchi2(Header{"fTOFchi2", "TRKEXTTOFchi2","ESD"}); o2vec<float> fTPCsignal(Header{"fTPCsignal", "TRKEXTTPCsignal","ESD"}); o2vec<float> fTRDsignal(Header{"fTRDsignal", "TRKEXTTRDsignal","ESD"}); o2vec<float> fTOFsignal(Header{"fTOFsignal", "TRKEXTTOFsignal","ESD"}); o2vec<float> fLength(Header{"fLength", "TRKEXTLength","ESD"}); for (std::string filename: fFilesIn) { if (fVerbose) {printf("opening file %si\n",filename.c_str());} TFile file(filename.c_str()); if (file.IsOpen() == false) { printf("ERROR: cannot open %s",filename.c_str()); continue; } TTree* esdTree = (TTree*)file.Get("esdTree"); unique_ptr<AliESDEvent> esd(new AliESDEvent); esd->ReadFromTree(esdTree); size_t nev = esdTree->GetEntries(); if (fVerbose) {printf(" %lu events\n",nev);} for (size_t iev = 0; iev < nev; ++iev) { esd->Reset(); esdTree->GetEntry(iev); esd->ConnectTracks(); // Tracks information size_t ntrk = esd->GetNumberOfTracks(); if (fVerbose) {printf(" event: %lu tracks:%lu\n",iev,ntrk);} //naive preallocation scheme size_t elems = ntrk*nev*fFilesIn.size()+ntrk*nev; feventID.reserve(elems); fX.reserve(elems); fAlpha.reserve(elems); fY.reserve(elems); fZ.reserve(elems); fSnp.reserve(elems); fTgl.reserve(elems); fSigned1Pt.reserve(elems); fCYY.reserve(elems); fCZY.reserve(elems); fCZZ.reserve(elems); fCSnpY.reserve(elems); fCSnpZ.reserve(elems); fCSnpSnp.reserve(elems); fCTglY.reserve(elems); fCTglZ.reserve(elems); fCTglSnp.reserve(elems); fCTglTgl.reserve(elems); fC1PtY.reserve(elems); fC1PtZ.reserve(elems); fC1PtSnp.reserve(elems); fC1PtTgl.reserve(elems); fC1Pt21Pt2.reserve(elems); fTPCinnerP.reserve(elems); fFlags.reserve(elems); fITSClusterMap.reserve(elems); fTPCncls.reserve(elems); fTRDntracklets.reserve(elems); fITSchi2Ncl.reserve(elems); fTPCchi2Ncl.reserve(elems); fTRDchi2.reserve(elems); fTOFchi2.reserve(elems); fTPCsignal.reserve(elems); fTRDsignal.reserve(elems); fTOFsignal.reserve(elems); fLength.reserve(elems); for (size_t itrk = 0; itrk < ntrk; ++itrk) { AliESDtrack* track = esd->GetTrack(itrk); track->SetESDEvent(esd.get()); feventID.push_back(iev); fX.push_back(track->GetX()); fAlpha.push_back(track->GetAlpha()); fY.push_back(track->GetY()); fZ.push_back(track->GetZ()); fSnp.push_back(track->GetSnp()); fTgl.push_back(track->GetTgl()); fSigned1Pt.push_back(track->GetSigned1Pt()); fCYY.push_back(track->GetSigmaY2()); fCZY.push_back(track->GetSigmaZY()); fCZZ.push_back(track->GetSigmaZ2()); fCSnpY.push_back(track->GetSigmaSnpY()); fCSnpZ.push_back(track->GetSigmaSnpZ()); fCSnpSnp.push_back(track->GetSigmaSnp2()); fCTglY.push_back(track->GetSigmaTglY()); fCTglZ.push_back(track->GetSigmaTglZ()); fCTglSnp.push_back(track->GetSigmaTglSnp()); fCTglTgl.push_back(track->GetSigmaTgl2()); fC1PtY.push_back(track->GetSigma1PtY()); fC1PtZ.push_back(track->GetSigma1PtZ()); fC1PtSnp.push_back(track->GetSigma1PtSnp()); fC1PtTgl.push_back(track->GetSigma1PtTgl()); fC1Pt21Pt2.push_back(track->GetSigma1Pt2()); const AliExternalTrackParam* intp = track->GetTPCInnerParam(); fTPCinnerP.push_back(intp ? intp->GetP() : 0); fFlags.push_back(track->GetStatus()); fITSClusterMap.push_back(track->GetITSClusterMap()); fTPCncls.push_back(track->GetTPCNcls()); fTRDntracklets.push_back(track->GetTRDntracklets()); fITSchi2Ncl.push_back(track->GetITSNcls() ? track->GetITSchi2() / track->GetITSNcls() : 0); fTPCchi2Ncl.push_back(track->GetTPCNcls() ? track->GetTPCchi2() / track->GetTPCNcls() : 0); fTRDchi2.push_back(track->GetTRDchi2()); fTOFchi2.push_back(track->GetTOFchi2()); fTPCsignal.push_back(track->GetTPCsignal()); fTRDsignal.push_back(track->GetTRDsignal()); fTOFsignal.push_back(track->GetTOFsignal()); fLength.push_back(track->GetIntegratedLength()); }//track loop }//event loop }//file loop int rc{0}; rc = alizmq_msg_add_array(&message, std::move(feventID)); rc = alizmq_msg_add_array(&message, std::move(fX)); rc = alizmq_msg_add_array(&message, std::move(fAlpha)); rc = alizmq_msg_add_array(&message, std::move(fY)); rc = alizmq_msg_add_array(&message, std::move(fZ)); rc = alizmq_msg_add_array(&message, std::move(fSnp)); rc = alizmq_msg_add_array(&message, std::move(fTgl)); rc = alizmq_msg_add_array(&message, std::move(fSigned1Pt)); rc = alizmq_msg_add_array(&message, std::move(fCYY)); rc = alizmq_msg_add_array(&message, std::move(fCZY)); rc = alizmq_msg_add_array(&message, std::move(fCZZ)); rc = alizmq_msg_add_array(&message, std::move(fCSnpY)); rc = alizmq_msg_add_array(&message, std::move(fCSnpZ)); rc = alizmq_msg_add_array(&message, std::move(fCSnpSnp)); rc = alizmq_msg_add_array(&message, std::move(fCTglY)); rc = alizmq_msg_add_array(&message, std::move(fCTglZ)); rc = alizmq_msg_add_array(&message, std::move(fCTglSnp)); rc = alizmq_msg_add_array(&message, std::move(fCTglTgl)); rc = alizmq_msg_add_array(&message, std::move(fC1PtY)); rc = alizmq_msg_add_array(&message, std::move(fC1PtZ)); rc = alizmq_msg_add_array(&message, std::move(fC1PtSnp)); rc = alizmq_msg_add_array(&message, std::move(fC1PtTgl)); rc = alizmq_msg_add_array(&message, std::move(fC1Pt21Pt2)); rc = alizmq_msg_add_array(&message, std::move(fTPCinnerP)); rc = alizmq_msg_add_array(&message, std::move(fFlags)); rc = alizmq_msg_add_array(&message, std::move(fITSClusterMap)); rc = alizmq_msg_add_array(&message, std::move(fTPCncls)); rc = alizmq_msg_add_array(&message, std::move(fTRDntracklets)); rc = alizmq_msg_add_array(&message, std::move(fITSchi2Ncl)); rc = alizmq_msg_add_array(&message, std::move(fTPCchi2Ncl)); rc = alizmq_msg_add_array(&message, std::move(fTRDchi2)); rc = alizmq_msg_add_array(&message, std::move(fTOFchi2)); rc = alizmq_msg_add_array(&message, std::move(fTPCsignal)); rc = alizmq_msg_add_array(&message, std::move(fTRDsignal)); rc = alizmq_msg_add_array(&message, std::move(fTOFsignal)); rc = alizmq_msg_add_array(&message, std::move(fLength)); fBytesOUT = alizmq_msg_send(&message, socket, 0); if (fBytesOUT<=0) { printf("ERROR sending: %s\n",zmq_strerror(zmq_errno())); } fNumberOfMessagesSent++; SetLastPushBackTime(); alizmq_msg_close(&message); if (fOnce) { fgTerminationSignaled=true; } return fBytesOUT; } //______________________________________________________________________________ void SetLastPushBackTime() { gettimeofday(&fCurrentTimeStruct, NULL); fLastPushBackTime = 1000 * fCurrentTimeStruct.tv_sec + fCurrentTimeStruct.tv_usec / 1000; } //_______________________________________________________________________________________ Int_t InitZMQ() { // init or reinit stuff Int_t rc = 0; rc = alizmq_socket_init(fZMQout, fZMQcontext, fZMQconfigOUT.Data(), fZMQtimeout, fZMQmaxQueueSize, fZMQlingerTime); printf("out: (%s) %s\n", alizmq_socket_name(rc), fZMQconfigOUT.Data()); return 0; } //______________________________________________________________________________ Int_t ProcessOptionString(TString arguments, Bool_t verbose) { // process passed options Int_t nOptions = 0; std::unique_ptr<aliStringVec> options{ AliOptionParser::TokenizeOptionString(arguments) }; for (auto i : *options) { const TString& option = i.first; const TString& value = i.second; if (option.EqualTo("ZMQconfigOUT") || option.EqualTo("out")) { fZMQconfigOUT = value; fReconfigureZMQ = true; } else if (option.EqualTo("in")) { Ssiz_t from{0}; TString token{}; while (value.Tokenize(token,from,",")) { fFilesIn.emplace_back(token.Data()); } } else if (option.EqualTo("Verbose")) { fVerbose = value.EqualTo("0") ? kFALSE : kTRUE; } else if (option.EqualTo("ZMQmaxQueueSize")) { fZMQmaxQueueSize = value.Atoi(); fReconfigureZMQ = true; } else if (option.EqualTo("ZMQtimeout")) { fZMQtimeout = value.Atoi(); fReconfigureZMQ = true; } else if (option.EqualTo("id")) { fID = value.Data(); } else if (option.EqualTo("once")) { fOnce = value.Atoi(); } else if (option.EqualTo("ZMQlinger")) { fZMQlingerTime = value.Atoi(); } else { Printf("unrecognized option |%s|", option.Data()); nOptions = -1; break; } nOptions++; } if (nOptions < 1) fReconfigureZMQ = false; if (fReconfigureZMQ && (InitZMQ() < 0)) { Printf("failed ZMQ init"); return -1; } fReconfigureZMQ = false; if (fRequestTimeout < 100) printf("WARNING: setting the socket timeout to %lu ms can be dagerous,\n" " choose something more realistic or leave the default as it is\n", fRequestTimeout); return nOptions; } //_______________________________________________________________________________________ int main(Int_t argc, char** argv) { Int_t mainReturnCode = 0; // catch signals if (signal(SIGHUP, sig_handler) == SIG_ERR) printf("\ncan't catch SIGHUP\n"); if (signal(SIGINT, sig_handler) == SIG_ERR) printf("\ncan't catch SIGINT\n"); if (signal(SIGQUIT, sig_handler) == SIG_ERR) printf("\ncan't catch SIGQUIT\n"); if (signal(SIGTERM, sig_handler) == SIG_ERR) printf("\ncan't catch SIGTERM\n"); // the context fZMQcontext = alizmq_context(); if (!fZMQcontext) { printf("could not init the ZMQ context\n"); return 1; } // process args TString argString = AliOptionParser::GetFullArgString(argc, argv); if (ProcessOptionString(argString, kTRUE) <= 0) { printf("%s", fUSAGE); return 1; } Run(); // destroy ZMQ sockets zmq_close(fZMQout); zmq_ctx_destroy(fZMQcontext); return mainReturnCode; } //_______________________________________________________________________________________ template <typename T> void alizmq_deleteArray(void* data, void*) { delete [] static_cast<T*>(data); } template <typename T> int alizmq_msg_add_array(aliZMQmsg* message, o2vec<T>&& vec) { //add a frame to the mesage int rc = 0; size_t nelems = vec.size(); T* array = vec.release(); Header* topic = vec.header(); //prepare topic msg zmq_msg_t* topicMsg = new zmq_msg_t; rc = zmq_msg_init_size( topicMsg, sizeof(*topic)); if (rc<0) { zmq_msg_close(topicMsg); delete topicMsg; return -1; } memcpy(zmq_msg_data(topicMsg),topic,sizeof(*topic)); size_t size = nelems*sizeof(T); //prepare data msg zmq_msg_t* dataMsg = new zmq_msg_t; rc = zmq_msg_init_data( dataMsg, array, size, alizmq_deleteArray<T>, nullptr); if (rc<0) { zmq_msg_close(topicMsg); zmq_msg_close(dataMsg); delete topicMsg; delete dataMsg; return -1; } static_cast<DataTopic*>(zmq_msg_data(topicMsg))->SetPayloadSize(size); //add the frame to the message message->push_back(std::make_pair(topicMsg,dataMsg)); return message->size(); }
33.185065
126
0.678994
shahor02
fe72501cc5bc36b6f010dd21fd28d836cc3a160a
10,485
cpp
C++
LibFoundation/Curves/Wm4BezierCurve3.cpp
wjezxujian/WildMagic4
249a17f8c447cf57c6283408e01009039810206a
[ "BSL-1.0" ]
3
2021-08-02T04:03:03.000Z
2022-01-04T07:31:20.000Z
LibFoundation/Curves/Wm4BezierCurve3.cpp
wjezxujian/WildMagic4
249a17f8c447cf57c6283408e01009039810206a
[ "BSL-1.0" ]
null
null
null
LibFoundation/Curves/Wm4BezierCurve3.cpp
wjezxujian/WildMagic4
249a17f8c447cf57c6283408e01009039810206a
[ "BSL-1.0" ]
5
2019-10-13T02:44:19.000Z
2021-08-02T04:03:10.000Z
// Geometric Tools, Inc. // http://www.geometrictools.com // Copyright (c) 1998-2006. All Rights Reserved // // The Wild Magic Version 4 Foundation Library source code is supplied // under the terms of the license agreement // http://www.geometrictools.com/License/Wm4FoundationLicense.pdf // and may not be copied or disclosed except in accordance with the terms // of that agreement. #include "Wm4FoundationPCH.h" #include "Wm4BezierCurve3.h" namespace Wm4 { //---------------------------------------------------------------------------- template <class Real> BezierCurve3<Real>::BezierCurve3 (int iDegree, Vector3<Real>* akCtrlPoint) : SingleCurve3<Real>((Real)0.0,(Real)1.0) { assert(iDegree >= 2); int i, j; m_iDegree = iDegree; m_iNumCtrlPoints = m_iDegree + 1; m_akCtrlPoint = akCtrlPoint; // compute first-order differences m_akDer1CtrlPoint = WM4_NEW Vector3<Real>[m_iNumCtrlPoints-1]; for (i = 0; i < m_iNumCtrlPoints-1; i++) { m_akDer1CtrlPoint[i] = m_akCtrlPoint[i+1] - m_akCtrlPoint[i]; } // compute second-order differences m_akDer2CtrlPoint = WM4_NEW Vector3<Real>[m_iNumCtrlPoints-2]; for (i = 0; i < m_iNumCtrlPoints-2; i++) { m_akDer2CtrlPoint[i] = m_akDer1CtrlPoint[i+1] - m_akDer1CtrlPoint[i]; } // compute third-order differences if (iDegree >= 3) { m_akDer3CtrlPoint = WM4_NEW Vector3<Real>[m_iNumCtrlPoints-3]; for (i = 0; i < m_iNumCtrlPoints-3; i++) { m_akDer3CtrlPoint[i] = m_akDer2CtrlPoint[i+1] - m_akDer2CtrlPoint[i]; } } else { m_akDer3CtrlPoint = 0; } // Compute combinatorial values Choose(N,K), store in m_aafChoose[N][K]. // The values m_aafChoose[r][c] are invalid for r < c (use only the // entries for r >= c). m_aafChoose = WM4_NEW Real*[m_iNumCtrlPoints]; m_aafChoose[0] = WM4_NEW Real[m_iNumCtrlPoints*m_iNumCtrlPoints]; for (i = 1; i < m_iNumCtrlPoints; i++) { m_aafChoose[i] = &m_aafChoose[0][i*m_iNumCtrlPoints]; } m_aafChoose[0][0] = (Real)1.0; m_aafChoose[1][0] = (Real)1.0; m_aafChoose[1][1] = (Real)1.0; for (i = 2; i <= m_iDegree; i++) { m_aafChoose[i][0] = (Real)1.0; m_aafChoose[i][i] = (Real)1.0; for (j = 1; j < i; j++) { m_aafChoose[i][j] = m_aafChoose[i-1][j-1] + m_aafChoose[i-1][j]; } } // variation support m_iTwoDegree = 2*m_iDegree; m_iTwoDegreePlusOne = m_iTwoDegree + 1; m_afSigma = WM4_NEW Real[m_iTwoDegreePlusOne]; m_afRecip = WM4_NEW Real[m_iTwoDegreePlusOne]; for (i = 0; i <= m_iTwoDegree; i++) { m_afSigma[i] = (Real)0.0; int iHalf = (i % 2 ? (i+1)/2 : i/2); int iStart = (i <= m_iDegree ? 0 : i - m_iDegree); Real fDot, fProd; for (j = iStart; j < iHalf; j++) { fDot = m_akCtrlPoint[j].Dot(m_akCtrlPoint[i-j]); fProd = m_aafChoose[m_iDegree][j]*m_aafChoose[m_iDegree][i-j]; m_afSigma[i] += fDot*fProd; } m_afSigma[i] *= (Real)2.0; if ((i % 2) == 0) { fDot = m_akCtrlPoint[iHalf].Dot(m_akCtrlPoint[iHalf]); fProd = m_aafChoose[m_iDegree][iHalf]; fProd *= fProd; m_afSigma[i] += fDot*fProd; } m_afRecip[i] = ((Real)1.0)/Real(m_iTwoDegreePlusOne-i); } int iTDp2 = m_iTwoDegreePlusOne+1; m_afPowT0 = WM4_NEW Real[iTDp2]; m_afPowT0[0] = (Real)1.0; m_afPowT1 = WM4_NEW Real[iTDp2]; m_afPowT1[0] = (Real)1.0; m_afPowOmT0 = WM4_NEW Real[iTDp2]; m_afPowOmT0[0] = (Real)1.0; m_afPowOmT1 = WM4_NEW Real[iTDp2]; m_afPowOmT1[0] = (Real)1.0; } //---------------------------------------------------------------------------- template <class Real> BezierCurve3<Real>::~BezierCurve3 () { WM4_DELETE[] m_afPowOmT1; WM4_DELETE[] m_afPowOmT0; WM4_DELETE[] m_afPowT1; WM4_DELETE[] m_afPowT0; WM4_DELETE[] m_afSigma; WM4_DELETE[] m_afRecip; WM4_DELETE[] m_aafChoose[0]; WM4_DELETE[] m_aafChoose; WM4_DELETE[] m_akDer3CtrlPoint; WM4_DELETE[] m_akDer2CtrlPoint; WM4_DELETE[] m_akDer1CtrlPoint; WM4_DELETE[] m_akCtrlPoint; } //---------------------------------------------------------------------------- template <class Real> int BezierCurve3<Real>::GetDegree () const { return m_iDegree; } //---------------------------------------------------------------------------- template <class Real> const Vector3<Real>* BezierCurve3<Real>::GetControlPoints () const { return m_akCtrlPoint; } //---------------------------------------------------------------------------- template <class Real> Vector3<Real> BezierCurve3<Real>::GetPosition (Real fTime) const { Real fOmTime = (Real)1.0 - fTime; Real fPowTime = fTime; Vector3<Real> kResult = fOmTime*m_akCtrlPoint[0]; for (int i = 1; i < m_iDegree; i++) { Real fCoeff = m_aafChoose[m_iDegree][i]*fPowTime; kResult = (kResult+fCoeff*m_akCtrlPoint[i])*fOmTime; fPowTime *= fTime; } kResult += fPowTime*m_akCtrlPoint[m_iDegree]; return kResult; } //---------------------------------------------------------------------------- template <class Real> Vector3<Real> BezierCurve3<Real>::GetFirstDerivative (Real fTime) const { Real fOmTime = (Real)1.0 - fTime; Real fPowTime = fTime; Vector3<Real> kResult = fOmTime*m_akDer1CtrlPoint[0]; int iDegreeM1 = m_iDegree - 1; for (int i = 1; i < iDegreeM1; i++) { Real fCoeff = m_aafChoose[iDegreeM1][i]*fPowTime; kResult = (kResult+fCoeff*m_akDer1CtrlPoint[i])*fOmTime; fPowTime *= fTime; } kResult += fPowTime*m_akDer1CtrlPoint[iDegreeM1]; kResult *= Real(m_iDegree); return kResult; } //---------------------------------------------------------------------------- template <class Real> Vector3<Real> BezierCurve3<Real>::GetSecondDerivative (Real fTime) const { Real fOmTime = (Real)1.0 - fTime; Real fPowTime = fTime; Vector3<Real> kResult = fOmTime*m_akDer2CtrlPoint[0]; int iDegreeM2 = m_iDegree - 2; for (int i = 1; i < iDegreeM2; i++) { Real fCoeff = m_aafChoose[iDegreeM2][i]*fPowTime; kResult = (kResult+fCoeff*m_akDer2CtrlPoint[i])*fOmTime; fPowTime *= fTime; } kResult += fPowTime*m_akDer2CtrlPoint[iDegreeM2]; kResult *= Real(m_iDegree*(m_iDegree-1)); return kResult; } //---------------------------------------------------------------------------- template <class Real> Vector3<Real> BezierCurve3<Real>::GetThirdDerivative (Real fTime) const { if (m_iDegree < 3) { return Vector3<Real>::ZERO; } Real fOmTime = (Real)1.0 - fTime; Real fPowTime = fTime; Vector3<Real> kResult = fOmTime*m_akDer3CtrlPoint[0]; int iDegreeM3 = m_iDegree - 3; for (int i = 1; i < iDegreeM3; i++) { Real fCoeff = m_aafChoose[iDegreeM3][i]*fPowTime; kResult = (kResult+fCoeff*m_akDer3CtrlPoint[i])*fOmTime; fPowTime *= fTime; } kResult += fPowTime*m_akDer3CtrlPoint[iDegreeM3]; kResult *= Real(m_iDegree*(m_iDegree-1)*(m_iDegree-2)); return kResult; } //---------------------------------------------------------------------------- template <class Real> Real BezierCurve3<Real>::GetVariation (Real fT0, Real fT1, const Vector3<Real>* pkP0, const Vector3<Real>* pkP1) const { int i, j, k; Vector3<Real> kP0, kP1; if (!pkP0) { kP0 = GetPosition(fT0); pkP0 = &kP0; } if (!pkP1) { kP1 = GetPosition(fT1); pkP1 = &kP1; } // compute powers of t0, t1, 1-t0, 1-t1 Real fOmT0 = (Real)1.0 - fT0; Real fOmT1 = (Real)1.0 - fT1; for (i = 1, j = 0; i <= m_iTwoDegreePlusOne; i++, j++) { m_afPowT0[i] = fT0*m_afPowT0[j]; m_afPowT1[i] = fT1*m_afPowT1[j]; m_afPowOmT0[i] = fOmT0*m_afPowOmT0[j]; m_afPowOmT1[i] = fOmT1*m_afPowOmT1[j]; } // line segment is L(t) = P0 + ((t-t0)/(t1-t0))*(P1-P0) // var1 = integral(Dot(L,L)) static const Real s_fOneThird = ((Real)1.0)/(Real)3.0; Real fDT = fT1 - fT0; Real fP0P0 = pkP0->Dot(*pkP0); Real fP0P1 = pkP0->Dot(*pkP1); Real fP1P1 = pkP1->Dot(*pkP1); Real fVar1 = s_fOneThird*fDT*(fP0P0 + fP0P1 + fP1P1); // var2 = integral(Dot(X,P0)) // var3 = integral(Dot(X,P1-P0)*(t-t0)/(t1-t0)) Real fVar2 = (Real)0.0; Real fVar3 = (Real)0.0; Vector3<Real> kDir = *pkP1 - *pkP0; Real fIint = (Real)0.0; int iDp2 = m_iDegree+2, iDm1 = m_iDegree-1; Real fJint = (m_afPowOmT0[iDp2] - m_afPowOmT1[iDp2])*m_afRecip[iDm1]; Real fProd0, fProd1, fDot; for (i = 0, j = m_iDegree, k = m_iDegree+1; i <= m_iDegree; i++, j++, k--) { // compute I[i] fProd0 = m_afPowT0[i]*m_afPowOmT0[k]; fProd1 = m_afPowT1[i]*m_afPowOmT1[k]; fIint = (fProd0 - fProd1 + i*fIint)*m_afRecip[j]; // compute J[i] fProd0 = m_afPowT0[i+1]*m_afPowOmT0[k]; fProd1 = m_afPowT1[i+1]*m_afPowOmT1[k]; fJint = (fProd0 - fProd1 + (i+1)*fJint)*m_afRecip[j]; // update partial variations fDot = pkP0->Dot(m_akCtrlPoint[i]); fProd0 = m_aafChoose[m_iDegree][i]*fDot; fVar2 += fProd0*fIint; fDot = kDir.Dot(m_akCtrlPoint[i]); fProd0 = m_aafChoose[m_iDegree][i]*fDot; fVar3 += fProd0*(fJint - fT0*fIint); } fVar3 /= fDT; // var4 = integral(Dot(X,X)) Real fVar4 = (Real)0.0; Real fKint = (Real)0.0; for (i = 0, j = m_iTwoDegreePlusOne; i <= m_iTwoDegree; i++, j--) { // compute K[i] fProd0 = m_afPowT0[i]*m_afPowOmT0[j]; fProd1 = m_afPowT1[i]*m_afPowOmT1[j]; fKint = (fProd0 - fProd1 + i*fKint)*m_afRecip[i]; // update partial variation fVar4 += m_afSigma[i]*fKint; } Real fVar = fVar1 - ((Real)2.0)*(fVar2 + fVar3) + fVar4; return fVar; } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- // explicit instantiation //---------------------------------------------------------------------------- template WM4_FOUNDATION_ITEM class BezierCurve3<float>; template WM4_FOUNDATION_ITEM class BezierCurve3<double>; //---------------------------------------------------------------------------- }
30.838235
78
0.548784
wjezxujian
fe7451a36dd2930fea9af116943e8808fa4078d5
1,332
hpp
C++
src/Switch.Core/include/Switch/System/IFormatProvider.hpp
victor-timoshin/Switch
8e8e687a8bdc4f79d482680da3968e9b3e464b8b
[ "MIT" ]
4
2020-02-11T13:22:58.000Z
2022-02-24T00:37:43.000Z
src/Switch.Core/include/Switch/System/IFormatProvider.hpp
sgf/Switch
8e8e687a8bdc4f79d482680da3968e9b3e464b8b
[ "MIT" ]
null
null
null
src/Switch.Core/include/Switch/System/IFormatProvider.hpp
sgf/Switch
8e8e687a8bdc4f79d482680da3968e9b3e464b8b
[ "MIT" ]
2
2020-02-01T02:19:01.000Z
2021-12-30T06:44:00.000Z
/// @file /// @brief Contains Switch::System::IFormatProvider interface. #pragma once #include "../Interface.hpp" #include "Object.hpp" #include "Type.hpp" /// @cond namespace Switch { namespace System { class Type; } } /// @endcond /// @brief The Switch namespace contains all fundamental classes to access Hardware, Os, System, and more. namespace Switch { /// @brief The System namespace contains fundamental classes and base classes that define commonly-used value and reference data types, events and event handlers, interfaces, attributes, and processing exceptions. namespace System { /// @interface IFormatProvider /// @brief Provides a mechanism for retrieving an object to control formatting. /// @par Library /// Switch.Core class core_export_ IFormatProvider interface_ { public: /// @brief Returns an object that provides formatting services for the specified type. /// @param type An object that specifies the type of format object to return. /// @return object An instance of the object specified by formatType, if the IFormatProvider implementation can supply that type of object; otherwise, nullNothingnullptra null reference (Nothing in Visual Basic). virtual const Object& GetFormat(const Type& type) const = 0; }; } } using namespace Switch;
37
218
0.731231
victor-timoshin
fe762264675ebe43ba8af74eb4817a0d0bdace63
2,923
cpp
C++
src/example/main.cpp
Blitzman/practica-sistemas-percepcion-mayr
fbee0739b70bceadfc955a36207573fd31ca2e35
[ "MIT" ]
1
2016-01-12T22:10:16.000Z
2016-01-12T22:10:16.000Z
src/example/main.cpp
Blitzman/practica-sistemas-percepcion-mayr
fbee0739b70bceadfc955a36207573fd31ca2e35
[ "MIT" ]
null
null
null
src/example/main.cpp
Blitzman/practica-sistemas-percepcion-mayr
fbee0739b70bceadfc955a36207573fd31ca2e35
[ "MIT" ]
null
null
null
#include "ImageShapeSegmentation.hpp" #include "ImageColorSegmentation.hpp" #include "Shape.hpp" // #include <opencv2/opencv.hpp> #include <opencv2/core/core.hpp> #include <opencv2/imgcodecs.hpp> #include <opencv2/highgui/highgui.hpp> #include <iostream> #include <glob.h> #include <unistd.h> #include <limits.h> std::vector<std::string> globVector(const std::string& pattern){ glob_t glob_result; glob(pattern.c_str(),GLOB_TILDE,NULL,&glob_result); std::vector<std::string> files; for(unsigned int i=0;i<glob_result.gl_pathc;++i){ files.push_back(std::string(glob_result.gl_pathv[i])); } globfree(&glob_result); return files; } void merge_shapes(std::vector<Shape> & rShapesColor, std::vector<Shape> & rShapesShape) { for (unsigned int i = 0; i < rShapesColor.size(); ++i) { unsigned int min_index_ = 0; double min_distance_ = std::numeric_limits<double>::max(); cv::Point c_c_ = rShapesColor[i].getCentroid(); for (unsigned int j = 0; j < rShapesShape.size(); ++j) { cv::Point c_s_ = rShapesShape[j].get_vertex_centroid(); double distance_ = cv::norm(c_c_ - c_s_); if (distance_ < min_distance_) { min_distance_ = distance_; min_index_ = j; } } rShapesShape[min_index_].m_point_list = rShapesColor[i].m_point_list; std::cout << "Color[" << i << "] corresponds to Shape[" << min_index_ << "]...\n"; } } int main(int argc, char** argv ) { std::vector<std::string> files = globVector("../resources/*"); cv::Size size(640, 480); for(int i = 0; i < files.size(); i++) { cv::Mat frame; std::cout << files[i] << std::endl; std::vector<Shape> shapes_color_; ImageColorSegmentation ics(files[i]); ics.setHistogramOutput(false); ics.process(ImageColorSegmentation::HLS, frame, shapes_color_); cv::Mat color_resized; resize(frame, color_resized, size); cv::namedWindow( "DisplayWindow" ); // Create a window for display. cv::imshow("DisplayWindow", color_resized ); cv::Mat frame_shape_; ImageShapeSegmentation iss_(files[i]); iss_.process(frame_shape_); cv::Mat shape_resized_; resize(frame_shape_, shape_resized_, size); cv::namedWindow("DisplayWindow2"); cv::imshow("DisplayWindow2", shape_resized_); cv::Mat final_image_; final_image_ = cv::imread(files[i]); std::vector<Shape> shapes_shape_ = iss_.get_shapes(); merge_shapes(shapes_color_, shapes_shape_); std::cout << "Drawing shapes...\n"; for (Shape s_ : shapes_shape_) { s_.draw_name(final_image_, cv::Scalar(0, 0, 0)); s_.draw_box(final_image_, cv::Scalar(0, 0, 0)); s_.draw_contour(final_image_, cv::Scalar(0, 0, 0)); } std::cout << "Showing image...\n"; cv::Mat final_image_resized_; resize(final_image_, final_image_resized_, size); cv::namedWindow("Semantic Image"); cv::imshow("Semantic Image", final_image_resized_); cv::waitKey(0); } cv::waitKey(0); // */ return 0; }
27.575472
87
0.678413
Blitzman
fe7d985981eb3878d0572909d9dd7bde74176ff3
407
hpp
C++
optionals/police/script_component.hpp
kellerkompanie/kellerkompanie-mods
f15704710f77ba6c018c486d95cac4f7749d33b8
[ "MIT" ]
6
2018-05-05T22:28:57.000Z
2019-07-06T08:46:51.000Z
optionals/police/script_component.hpp
Schwaggot/kellerkompanie-mods
7a389e49e3675866dbde1b317a44892926976e9d
[ "MIT" ]
107
2018-04-11T19:42:27.000Z
2019-09-13T19:05:31.000Z
optionals/police/script_component.hpp
kellerkompanie/kellerkompanie-mods
f15704710f77ba6c018c486d95cac4f7749d33b8
[ "MIT" ]
3
2018-10-03T11:54:46.000Z
2019-02-28T13:30:16.000Z
#define COMPONENT police #define COMPONENT_BEAUTIFIED Police #include "\x\keko\addons\main\script_mod.hpp" // #define DEBUG_MODE_FULL // #define DISABLE_COMPILE_CACHE // #define ENABLE_PERFORMANCE_COUNTERS #ifdef DEBUG_ENABLED_POLICE #define DEBUG_MODE_FULL #endif #ifdef DEBUG_SETTINGS_POLICE #define DEBUG_SETTINGS DEBUG_SETTINGS_POLICE #endif #include "\x\keko\addons\main\script_macros.hpp"
22.611111
48
0.810811
kellerkompanie
fe7f082e879f6de9992cc0d134b84755c45860a0
594
hpp
C++
libs/mpi/include/hpx/mpi/force_linking.hpp
picanumber/hpx
76d6fe0bf4bd7f23e62c170fd8a0c8dbed66ec7d
[ "BSL-1.0" ]
null
null
null
libs/mpi/include/hpx/mpi/force_linking.hpp
picanumber/hpx
76d6fe0bf4bd7f23e62c170fd8a0c8dbed66ec7d
[ "BSL-1.0" ]
null
null
null
libs/mpi/include/hpx/mpi/force_linking.hpp
picanumber/hpx
76d6fe0bf4bd7f23e62c170fd8a0c8dbed66ec7d
[ "BSL-1.0" ]
null
null
null
// Copyright (c) 2019-2020 The STE||AR GROUP // // SPDX-License-Identifier: BSL-1.0 // 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) #if !defined(HPX_MPI_FORCE_LINKING_HPP) #define HPX_MPI_FORCE_LINKING_HPP #include <hpx/config.hpp> #include <hpx/mpi/mpi_future.hpp> #include <mpi.h> namespace hpx { namespace mpi { struct force_linking_helper { MPI_Errhandler* mpi_errhandler; }; force_linking_helper& force_linking(); }} // namespace hpx::mpi #endif
22.846154
80
0.718855
picanumber
fe8237956999f51fa4cc7487791f7ede9cc73e07
1,792
cpp
C++
codes/CSES/CSES_1082.cpp
chessbot108/solved-problems
0945be829a8ea9f0d5896c89331460d70d076691
[ "MIT" ]
2
2021-03-07T03:34:02.000Z
2021-03-09T01:22:21.000Z
codes/CSES/CSES_1082.cpp
chessbot108/solved-problems
0945be829a8ea9f0d5896c89331460d70d076691
[ "MIT" ]
1
2021-03-27T15:01:23.000Z
2021-03-27T15:55:34.000Z
codes/CSES/CSES_1082.cpp
chessbot108/solved-problems
0945be829a8ea9f0d5896c89331460d70d076691
[ "MIT" ]
1
2021-03-27T05:02:33.000Z
2021-03-27T05:02:33.000Z
#include <iostream> #include <cstdio> #include <cstring> #include <cstdlib> #include <ctime> #include <cmath> #include <cassert> #include <algorithm> #include <vector> #include <string> #include <map> #include <set> #include <sstream> #include <list> #include <queue> #include <stack> //#include <unordered_map> //#include <unordered_set> #include <functional> #define max_v 1100 #define LOGN 50 #define int_max 0x3f3f3f3f #define cont continue #define byte_max 0x3f #define pow_2(n) (1 << (n)) //tree #define lsb(n) ((n)&(-(n))) #define LC(n) (((n) << 1) + 1) #define RC(n) (((n) << 1) + 2) #define LOG2(n) ((int)(ceil(log2((n))))) using namespace std; void setIO(const string& file_name){ freopen((file_name+".in").c_str(), "r", stdin); freopen((file_name+".out").c_str(), "w+", stdout); } const long long mod = (long long)1e9 + 7; long long F(long long a, long long b){// returns sym of all integers [a, b] if(a > b) swap(a, b); long long A = (b + 1ll - a) % mod; long long B = ((a%mod) * A) % mod; long long C = ((b - a) % 2ll) ? b - a : (b - a) / 2ll; long long D = ((b + 1ll - a) % 2ll) ? b + 1ll - a : (b + 1ll- a) / 2ll; C %= mod; D %= mod; return ((C * D) % mod + B) % mod; } int main(){ long long n, tot = 0ll; scanf("%lld", &n); for(long long i = 1ll; n/i>(long long)floor(sqrt(n)); i += 1ll){ (tot += F(n/i, 1ll + (n/(i + 1ll))) * (i%mod)) %= mod; //printf("%lld %lld -> %lld\n", n/i, 1ll + (n/(i + 1ll)), F(n/i, 1ll + (n/(i + 1ll) * i))); } //printf("%lld\n", tot); //for(int i = 0; i<n; i++){ //long long a, b; //scanf("%lld%lld", &a, &b); //printf("%lld\n", F(a, b)); //} for(long long i = 1ll; i<=(long long)floor(sqrt(n)); i += 1ll){ (tot += (i%mod) * (n/i)) %= mod; } printf("%lld\n", tot); return 0; }
24.547945
96
0.551339
chessbot108
fe826b21359e277df6a7733a204f9b7aedcb4108
168
hpp
C++
libng/compiler/src/libng_compiler/json/JSONLexer.hpp
gapry/libng
8fbf927e5bb73f105bddbb618430d3e1bf2cf877
[ "MIT" ]
null
null
null
libng/compiler/src/libng_compiler/json/JSONLexer.hpp
gapry/libng
8fbf927e5bb73f105bddbb618430d3e1bf2cf877
[ "MIT" ]
null
null
null
libng/compiler/src/libng_compiler/json/JSONLexer.hpp
gapry/libng
8fbf927e5bb73f105bddbb618430d3e1bf2cf877
[ "MIT" ]
null
null
null
#pragma once #include <libng_core/types/noncopyable.hpp> namespace libng { class JSONLexer : public NonCopyable { public: void nextChar(); }; } // namespace libng
14
43
0.732143
gapry
fe839e09cdefe36f43533cb0a79f8c91718bac98
1,570
hh
C++
src/opbox/core/Singleton.hh
faodel/faodel
ef2bd8ff335433e695eb561d7ecd44f233e58bf0
[ "MIT" ]
2
2019-01-25T21:21:07.000Z
2021-04-29T17:24:00.000Z
src/opbox/core/Singleton.hh
faodel/faodel
ef2bd8ff335433e695eb561d7ecd44f233e58bf0
[ "MIT" ]
8
2018-10-09T14:35:30.000Z
2020-09-30T20:09:42.000Z
src/opbox/core/Singleton.hh
faodel/faodel
ef2bd8ff335433e695eb561d7ecd44f233e58bf0
[ "MIT" ]
2
2019-04-23T19:01:36.000Z
2021-05-11T07:44:55.000Z
// Copyright 2021 National Technology & Engineering Solutions of Sandia, LLC // (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the U.S. // Government retains certain rights in this software. #ifndef OPBOX_SINGLETON_HH #define OPBOX_SINGLETON_HH #include "faodel-common/Common.hh" #include "faodel-common/LoggingInterface.hh" #include "opbox/common/Types.hh" #include "opbox/OpBox.hh" #include "opbox/common/OpRegistry.hh" #include "opbox/core/OpBoxCoreBase.hh" #include "opbox/core/OpBoxCoreUnconfigured.hh" namespace opbox { namespace internal { /** * @brief The actual OpBox singleton, which manages bootstraps * */ class SingletonImpl : public faodel::bootstrap::BootstrapInterface, public faodel::LoggingInterface { public: SingletonImpl(); ~SingletonImpl() override; bool IsUnconfigured(); //Bootstrap API void Init(const faodel::Configuration &config) override; void Start() override; void Finish() override; void GetBootstrapDependencies(std::string &name, std::vector<std::string> &requires, std::vector<std::string> &optional) const override; void whookieInfoRegistry(faodel::ReplyStream &rs) { return registry.whookieInfo(rs); } OpRegistry registry; OpBoxCoreBase *core; private: OpBoxCoreUnconfigured unconfigured; }; /** * @brief A static placeholder for opbox's singleton */ class Singleton { public: static opbox::internal::SingletonImpl impl; }; } // namespace internal } // namespace opbox #endif // OPBOX_OPBOXSINGLETON_HH
21.506849
88
0.724841
faodel
fe866af8d807379922aef9e74916d21abfebe0e2
2,143
cpp
C++
tests/unit/net/collect-netifs.cpp
KITE-2018/kite-ndn-cxx
2a674e2bab42a39d0731b0a30c4d49369b084c1c
[ "OpenSSL" ]
4
2021-04-21T02:48:49.000Z
2021-06-25T06:08:58.000Z
tests/unit/net/collect-netifs.cpp
KITE-2018/kite-ndn-cxx
2a674e2bab42a39d0731b0a30c4d49369b084c1c
[ "OpenSSL" ]
11
2020-12-27T23:02:56.000Z
2021-10-18T08:00:50.000Z
tests/unit/net/collect-netifs.cpp
KITE-2018/kite-ndn-cxx
2a674e2bab42a39d0731b0a30c4d49369b084c1c
[ "OpenSSL" ]
3
2021-02-28T10:04:09.000Z
2021-09-23T05:01:00.000Z
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2013-2018 Regents of the University of California, * Arizona Board of Regents, * Colorado State University, * University Pierre & Marie Curie, Sorbonne University, * Washington University in St. Louis, * Beijing Institute of Technology, * The University of Memphis. * * This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions). * * ndn-cxx 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, either version 3 of the License, or (at your option) any later version. * * ndn-cxx 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 copies of the GNU General Public License and GNU Lesser * General Public License along with ndn-cxx, e.g., in COPYING.md file. If not, see * <http://www.gnu.org/licenses/>. * * See AUTHORS.md for complete list of ndn-cxx authors and contributors. */ #include "tests/unit/net/collect-netifs.hpp" #include "ndn-cxx/net/network-monitor.hpp" #include <boost/asio/io_service.hpp> namespace ndn { namespace net { namespace tests { std::vector<shared_ptr<const NetworkInterface>> collectNetworkInterfaces(bool allowCached) { static optional<std::vector<shared_ptr<const NetworkInterface>>> cached; if (!allowCached || !cached) { boost::asio::io_service io; NetworkMonitor netmon(io); if (netmon.getCapabilities() & NetworkMonitor::CAP_ENUM) { netmon.onEnumerationCompleted.connect([&io] { io.stop(); }); io.run(); io.reset(); } cached = netmon.listNetworkInterfaces(); } return *cached; } } // namespace tests } // namespace net } // namespace ndn
35.716667
87
0.673355
KITE-2018
fe867d89e878f21b412b2d01c662f100e5629058
6,475
hpp
C++
DiligentCore/Graphics/GraphicsEngineD3D12/include/ShaderResourcesD3D12.hpp
JorisSAN/DiligentEngine
5701b916bc2e9fefab1cf5ad0d20d4b6bb0f64c5
[ "Apache-2.0" ]
null
null
null
DiligentCore/Graphics/GraphicsEngineD3D12/include/ShaderResourcesD3D12.hpp
JorisSAN/DiligentEngine
5701b916bc2e9fefab1cf5ad0d20d4b6bb0f64c5
[ "Apache-2.0" ]
null
null
null
DiligentCore/Graphics/GraphicsEngineD3D12/include/ShaderResourcesD3D12.hpp
JorisSAN/DiligentEngine
5701b916bc2e9fefab1cf5ad0d20d4b6bb0f64c5
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2019-2020 Diligent Graphics LLC * Copyright 2015-2019 Egor Yusov * * 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. * * In no event and under no legal theory, whether in tort (including negligence), * contract, or otherwise, unless required by applicable law (such as deliberate * and grossly negligent acts) or agreed to in writing, shall any Contributor be * liable for any damages, including any direct, indirect, special, incidental, * or consequential damages of any character arising as a result of this License or * out of the use or inability to use the software (including but not limited to damages * for loss of goodwill, work stoppage, computer failure or malfunction, or any and * all other commercial damages or losses), even if such Contributor has been advised * of the possibility of such damages. */ #pragma once /// \file /// Declaration of Diligent::ShaderResourcesD3D12 class // ShaderResourcesD3D12 are created by ShaderD3D12Impl instances. They are then referenced by ShaderResourceLayoutD3D12 objects, which are in turn // created by instances of PipelineStatesD3D12Impl and ShaderD3D12Impl // // _________________ // | | // | ShaderD3D12Impl | // |_________________| // | // |shared_ptr // ________V_____________ _____________________________________________________________________ // | | unique_ptr | | | | | | | // | ShaderResourcesD3D12 |--------------->| CBs | TexSRVs | TexUAVs | BufSRVs | BufUAVs | Samplers | // |______________________| |________|___________|___________|___________|___________|____________| // A A A A // | \ / \ // |shared_ptr Ref Ref Ref // ________|__________________ ________\________________________/_________________________\_________________________________________ // | | unique_ptr | | | | | | | // | ShaderResourceLayoutD3D12 |--------------->| SRV_CBV_UAV[0] | SRV_CBV_UAV[1] | ... | Sampler[0] | Sampler[1] | ... | // |___________________________| |___________________|_________________|_______________|__________________|_________________|__________| // A | A // | |___________________SamplerId________________________| // | // __________|_____________ // | | // | PipelineStateD3D12Impl | // |________________________| // // // // One ShaderResourcesD3D12 instance can be referenced by multiple objects // // // ________________________ _<m_pShaderResourceLayouts>_ _____<m_pShaderVarMgrs>_____ ________________________________ // | | | | | | | | // | PipelineStateD3D12Impl |========>| ShaderResourceLayoutD3D12 |<-------| ShaderVariableManagerD3D12 |<====| ShaderResourceBindingD3D12Impl | // |________________________| |____________________________| |____________________________| |________________________________| // | A // |shared_ptr \ // _________________ ___________V__________ \ _____<m_pShaderVarMgrs>_____ ________________________________ // | | shared_ptr | | \ | | | | // | ShaderD3D12Impl |---------------->| ShaderResourcesD3D12 | '-------| ShaderVariableManagerD3D12 |<====| ShaderResourceBindingD3D12Impl | // |_________________| |______________________| |____________________________| |________________________________| // | |___________________ A // | | | // V V |shared_ptr // _______<m_StaticVarsMgr>____ ___<m_StaticResLayout>_|___ // | | | | // | ShaderVariableManagerD3D12 |------>| ShaderResourceLayoutD3D12 | // |____________________________| |___________________________| // #include "ShaderResources.hpp" namespace Diligent { /// Diligent::ShaderResourcesD3D12 class class ShaderResourcesD3D12 final : public ShaderResources { public: // Loads shader resources from the compiled shader bytecode ShaderResourcesD3D12(ID3DBlob* pShaderBytecode, const ShaderDesc& ShdrDesc, const char* CombinedSamplerSuffix, class IDXCompiler* pDXCompiler); // clang-format off ShaderResourcesD3D12 (const ShaderResourcesD3D12&) = delete; ShaderResourcesD3D12 ( ShaderResourcesD3D12&&) = delete; ShaderResourcesD3D12& operator = (const ShaderResourcesD3D12&) = delete; ShaderResourcesD3D12& operator = ( ShaderResourcesD3D12&&) = delete; // clang-format on }; } // namespace Diligent
59.40367
156
0.538378
JorisSAN
fe86b335bcfde6ccd185480177f1c4ba55265787
1,808
hpp
C++
Axis/System/Include/Axis/StaticArray.hpp
SimmyPeet/Axis
a58c073d13f74d0224fbfca34a4dcd4b9d0c6726
[ "Apache-2.0" ]
1
2022-01-23T14:51:51.000Z
2022-01-23T14:51:51.000Z
Axis/System/Include/Axis/StaticArray.hpp
SimmyPeet/Axis
a58c073d13f74d0224fbfca34a4dcd4b9d0c6726
[ "Apache-2.0" ]
null
null
null
Axis/System/Include/Axis/StaticArray.hpp
SimmyPeet/Axis
a58c073d13f74d0224fbfca34a4dcd4b9d0c6726
[ "Apache-2.0" ]
1
2022-01-10T21:01:54.000Z
2022-01-10T21:01:54.000Z
/// \copyright Simmypeet - Copyright (C) /// This file is subject to the terms and conditions defined in /// file 'LICENSE', which is part of this source code package. #ifndef AXIS_SYSTEM_STATICARRAY_HPP #define AXIS_SYSTEM_STATICARRAY_HPP #pragma once #include "Config.hpp" #include "Trait.hpp" namespace Axis { namespace System { /// \brief The wrapper over the compile-time known size array. /// /// \warning This class doesn't provide strong exception safety. template <RawType T, Size N> struct StaticArray { public: /// \brief The length of the static array. static constexpr Size Length = N; /// \brief Gets the length of the array. AXIS_NODISCARD constexpr Size GetLength() const noexcept; /// \brief Indexing operator. Gets the reference to the element at the specified index. /// /// \param[in] index The index of the element. /// /// \return The reference to the element at the specified index. AXIS_NODISCARD constexpr T& operator[](Size index); /// \brief Indexing operator. Gets the reference to the element at the specified index. /// AXIS_NODISCARD constexpr const T& operator[](Size index) const; /// \brief Iterator begin AXIS_NODISCARD constexpr T* begin() noexcept; /// \brief Const iterator begin AXIS_NODISCARD constexpr const T* begin() const noexcept; /// \brief Iterator end AXIS_NODISCARD constexpr T* end() noexcept; /// \brief Const iterator end AXIS_NODISCARD constexpr const T* end() const noexcept; /// \brief The internal stack allocated array. T _Elements[N] = {}; // Initializes array with default constructor }; } // namespace System } // namespace Axis #include "../../Private/Axis/StaticArrayImpl.inl" #endif // AXIS_SYSTEM_STATICARRAY_HPP
27.815385
91
0.698009
SimmyPeet
fe8edecc5f2a475ebb57cce4766c38d2ed538db6
15,911
cpp
C++
sycl/source/detail/allowlist.cpp
mgehre-xlx/sycl
2086745509ef4bc298d7bbec402a123dae68f25e
[ "Apache-2.0" ]
61
2019-04-12T18:49:57.000Z
2022-03-19T22:23:16.000Z
sycl/source/detail/allowlist.cpp
mgehre-xlx/sycl
2086745509ef4bc298d7bbec402a123dae68f25e
[ "Apache-2.0" ]
127
2019-04-09T00:55:50.000Z
2022-03-21T15:35:41.000Z
sycl/source/detail/allowlist.cpp
mgehre-xlx/sycl
2086745509ef4bc298d7bbec402a123dae68f25e
[ "Apache-2.0" ]
10
2019-04-02T18:25:40.000Z
2022-02-15T07:11:37.000Z
//==-------------- allowlist.cpp - SYCL_DEVICE_ALLOWLIST -------------------==// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include <detail/allowlist.hpp> #include <detail/config.hpp> #include <detail/device_impl.hpp> #include <detail/platform_info.hpp> #include <algorithm> #include <regex> __SYCL_INLINE_NAMESPACE(cl) { namespace sycl { namespace detail { constexpr char BackendNameKeyName[] = "BackendName"; constexpr char DeviceTypeKeyName[] = "DeviceType"; constexpr char DeviceVendorIdKeyName[] = "DeviceVendorId"; constexpr char DriverVersionKeyName[] = "DriverVersion"; constexpr char PlatformVersionKeyName[] = "PlatformVersion"; constexpr char DeviceNameKeyName[] = "DeviceName"; constexpr char PlatformNameKeyName[] = "PlatformName"; constexpr std::array<const char *, 7> SupportedAllowListKeyNames{ BackendNameKeyName, DeviceTypeKeyName, DeviceVendorIdKeyName, DriverVersionKeyName, PlatformVersionKeyName, DeviceNameKeyName, PlatformNameKeyName}; // Parsing and validating SYCL_DEVICE_ALLOWLIST variable value. // // The value has the following form: // DeviceDesc1|DeviceDesc2|<...>|DeviceDescN // DeviceDescN is the set of descriptions for the device which should be // allowed. The sets of device descriptions are separated by '|' symbol. The set // of descriptions has the following structure: // DeviceDescN = Key1:Value1,Key2:Value2,...,KeyN:ValueN // Device descriptions are separated by ',' symbol. // Key and value of a device description are separated by ":" symbol. // KeyN is the key of a device description, it could be one of the following // from SupportedAllowListKeyNames vector above. // DeviceName and PlatformName device descriptions are deprecated and will be // removed in one of the future releases. // ValueN is the value of a device description, it could be regex and some fixed // string. // Function should return parsed SYCL_DEVICE_ALLOWLIST variable value as // AllowListParsedT type (vector of maps), e.g.: // {{Key1: Value1, Key2: Value2}, ..., {Key1: Value1, ..., KeyN: ValueN}} AllowListParsedT parseAllowList(const std::string &AllowListRaw) { if (AllowListRaw.empty()) return {}; AllowListParsedT AllowListParsed; AllowListParsed.emplace_back(); constexpr std::array<const char *, 3> SupportedKeyNamesHaveFixedValue{ BackendNameKeyName, DeviceTypeKeyName, DeviceVendorIdKeyName}; constexpr std::array<const char *, 4> SupportedKeyNamesRequireRegexValue{ DriverVersionKeyName, PlatformVersionKeyName, DeviceNameKeyName, PlatformNameKeyName}; size_t KeyStart = 0, KeyEnd = 0, ValueStart = 0, ValueEnd = 0, DeviceDescIndex = 0; const char DelimiterBtwKeyAndValue = ':'; const char DelimiterBtwItemsInDeviceDesc = ','; const char DelimiterBtwDeviceDescs = '|'; if (AllowListRaw.find(DelimiterBtwKeyAndValue, KeyStart) == std::string::npos) throw sycl::runtime_error("SYCL_DEVICE_ALLOWLIST has incorrect format. For " "details, please refer to " "https://github.com/intel/llvm/blob/sycl/sycl/" "doc/EnvironmentVariables.md", PI_INVALID_VALUE); while ((KeyEnd = AllowListRaw.find(DelimiterBtwKeyAndValue, KeyStart)) != std::string::npos) { if ((ValueStart = AllowListRaw.find_first_not_of( DelimiterBtwKeyAndValue, KeyEnd)) == std::string::npos) break; const std::string &Key = AllowListRaw.substr(KeyStart, KeyEnd - KeyStart); // check that provided key is supported if (std::find(SupportedAllowListKeyNames.begin(), SupportedAllowListKeyNames.end(), Key) == SupportedAllowListKeyNames.end()) { throw sycl::runtime_error( "Unrecognized key in SYCL_DEVICE_ALLOWLIST. For details, please " "refer to " "https://github.com/intel/llvm/blob/sycl/sycl/doc/" "EnvironmentVariables.md", PI_INVALID_VALUE); } bool ShouldAllocateNewDeviceDescMap = false; std::string Value; auto &DeviceDescMap = AllowListParsed[DeviceDescIndex]; // check if Key is not already defined in DeviceDescMap, e.g., caused by the // following invalid syntax: Key1:Value1,Key2:Value2,Key1:Value3 if (DeviceDescMap.find(Key) == DeviceDescMap.end()) { // calculate and validate value which has fixed format if (std::find(SupportedKeyNamesHaveFixedValue.begin(), SupportedKeyNamesHaveFixedValue.end(), Key) != SupportedKeyNamesHaveFixedValue.end()) { ValueEnd = AllowListRaw.find(DelimiterBtwItemsInDeviceDesc, ValueStart); // check if it is the last Key:Value pair in the device description, and // correct end position of that value if (size_t ValueEndCand = AllowListRaw.find(DelimiterBtwDeviceDescs, ValueStart); (ValueEndCand != std::string::npos) && (ValueEndCand < ValueEnd)) { ValueEnd = ValueEndCand; ShouldAllocateNewDeviceDescMap = true; } if (ValueEnd == std::string::npos) ValueEnd = AllowListRaw.length(); Value = AllowListRaw.substr(ValueStart, ValueEnd - ValueStart); // post-processing checks for some values auto ValidateEnumValues = [&](std::string CheckingKeyName, auto SourceOfSupportedValues) { if (Key == CheckingKeyName) { bool ValueIsValid = false; for (const auto &Item : SourceOfSupportedValues) if (Value == Item.first) { ValueIsValid = true; break; } if (!ValueIsValid) throw sycl::runtime_error( "Value " + Value + " for key " + Key + " is not valid in " "SYCL_DEVICE_ALLOWLIST. For details, please refer to " "https://github.com/intel/llvm/blob/sycl/sycl/doc/" "EnvironmentVariables.md", PI_INVALID_VALUE); } }; // check that values of keys, which should have some fixed format, are // valid. E.g., for BackendName key, the allowed values are only ones // described in SyclBeMap ValidateEnumValues(BackendNameKeyName, getSyclBeMap()); ValidateEnumValues(DeviceTypeKeyName, getSyclDeviceTypeMap()); if (Key == DeviceVendorIdKeyName) { // DeviceVendorId should have hex format if (!std::regex_match(Value, std::regex("0[xX][0-9a-fA-F]+"))) { throw sycl::runtime_error( "Value " + Value + " for key " + Key + " is not valid in " "SYCL_DEVICE_ALLOWLIST. It should have the hex format. For " "details, please refer to " "https://github.com/intel/llvm/blob/sycl/sycl/doc/" "EnvironmentVariables.md", PI_INVALID_VALUE); } } } // calculate and validate value which has regex format else if (std::find(SupportedKeyNamesRequireRegexValue.begin(), SupportedKeyNamesRequireRegexValue.end(), Key) != SupportedKeyNamesRequireRegexValue.end()) { const std::string Prefix("{{"); // TODO: can be changed to string_view::starts_with after switching // DPC++ RT to C++20 if (Prefix != AllowListRaw.substr(ValueStart, Prefix.length())) { throw sycl::runtime_error("Key " + Key + " of SYCL_DEVICE_ALLOWLIST should have " "value which starts with " + Prefix, PI_INVALID_VALUE); } // cut off prefix from the value ValueStart += Prefix.length(); ValueEnd = ValueStart; const std::string Postfix("}}"); for (; ValueEnd < AllowListRaw.length() - Postfix.length() + 1; ++ValueEnd) { if (Postfix == AllowListRaw.substr(ValueEnd, Postfix.length())) break; // if it is the last iteration and next 2 symbols are not a postfix, // throw exception if (ValueEnd == AllowListRaw.length() - Postfix.length()) throw sycl::runtime_error( "Key " + Key + " of SYCL_DEVICE_ALLOWLIST should have " "value which ends with " + Postfix, PI_INVALID_VALUE); } size_t NextExpectedDelimiterPos = ValueEnd + Postfix.length(); // if it is not the end of the string, check that symbol next to a // postfix is a delimiter (, or ;) if ((AllowListRaw.length() != NextExpectedDelimiterPos) && (AllowListRaw[NextExpectedDelimiterPos] != DelimiterBtwItemsInDeviceDesc) && (AllowListRaw[NextExpectedDelimiterPos] != DelimiterBtwDeviceDescs)) throw sycl::runtime_error( "Unexpected symbol on position " + std::to_string(NextExpectedDelimiterPos) + ": " + AllowListRaw[NextExpectedDelimiterPos] + ". Should be either " + DelimiterBtwItemsInDeviceDesc + " or " + DelimiterBtwDeviceDescs, PI_INVALID_VALUE); if (AllowListRaw[NextExpectedDelimiterPos] == DelimiterBtwDeviceDescs) ShouldAllocateNewDeviceDescMap = true; Value = AllowListRaw.substr(ValueStart, ValueEnd - ValueStart); ValueEnd += Postfix.length(); } else assert(false && "Key should be either in SupportedKeyNamesHaveFixedValue " "or SupportedKeyNamesRequireRegexValue"); // add key and value to the map DeviceDescMap.emplace(Key, Value); } else throw sycl::runtime_error("Re-definition of key " + Key + " is not allowed in " "SYCL_DEVICE_ALLOWLIST", PI_INVALID_VALUE); KeyStart = ValueEnd; if (KeyStart != std::string::npos) ++KeyStart; if (ShouldAllocateNewDeviceDescMap) { ++DeviceDescIndex; AllowListParsed.emplace_back(); } } return AllowListParsed; } // Checking if we can allow device with device description DeviceDesc bool deviceIsAllowed(const DeviceDescT &DeviceDesc, const AllowListParsedT &AllowListParsed) { assert(std::all_of(SupportedAllowListKeyNames.begin(), SupportedAllowListKeyNames.end(), [&DeviceDesc](const auto &SupportedKeyName) { return DeviceDesc.find(SupportedKeyName) != DeviceDesc.end(); }) && "DeviceDesc map should have all supported keys for " "SYCL_DEVICE_ALLOWLIST."); auto EqualityComp = [&](const std::string &KeyName, const DeviceDescT &AllowListDeviceDesc) { // change to map::contains after switching DPC++ RT to C++20 if (AllowListDeviceDesc.find(KeyName) != AllowListDeviceDesc.end()) if (AllowListDeviceDesc.at(KeyName) != DeviceDesc.at(KeyName)) return false; return true; }; auto RegexComp = [&](const std::string &KeyName, const DeviceDescT &AllowListDeviceDesc) { if (AllowListDeviceDesc.find(KeyName) != AllowListDeviceDesc.end()) if (!std::regex_match(DeviceDesc.at(KeyName), std::regex(AllowListDeviceDesc.at(KeyName)))) return false; return true; }; bool ShouldDeviceBeAllowed = false; for (const auto &AllowListDeviceDesc : AllowListParsed) { if (!EqualityComp(BackendNameKeyName, AllowListDeviceDesc)) continue; if (!EqualityComp(DeviceTypeKeyName, AllowListDeviceDesc)) continue; if (!EqualityComp(DeviceVendorIdKeyName, AllowListDeviceDesc)) continue; if (!RegexComp(DriverVersionKeyName, AllowListDeviceDesc)) continue; if (!RegexComp(PlatformVersionKeyName, AllowListDeviceDesc)) continue; if (!RegexComp(DeviceNameKeyName, AllowListDeviceDesc)) continue; if (!RegexComp(PlatformNameKeyName, AllowListDeviceDesc)) continue; // no any continue was called on this iteration, so all parameters matched // successfully, so allow this device to use ShouldDeviceBeAllowed = true; break; } return ShouldDeviceBeAllowed; } void applyAllowList(std::vector<RT::PiDevice> &PiDevices, RT::PiPlatform PiPlatform, const plugin &Plugin) { AllowListParsedT AllowListParsed = parseAllowList(SYCLConfig<SYCL_DEVICE_ALLOWLIST>::get()); if (AllowListParsed.empty()) return; DeviceDescT DeviceDesc; // get BackendName value and put it to DeviceDesc sycl::backend Backend = Plugin.getBackend(); for (const auto &SyclBe : getSyclBeMap()) { if (SyclBe.second == Backend) { DeviceDesc.emplace(BackendNameKeyName, SyclBe.first); break; } } // get PlatformVersion value and put it to DeviceDesc DeviceDesc.emplace( PlatformVersionKeyName, sycl::detail::get_platform_info<std::string, info::platform::version>::get(PiPlatform, Plugin)); // get PlatformName value and put it to DeviceDesc DeviceDesc.emplace( PlatformNameKeyName, sycl::detail::get_platform_info<std::string, info::platform::name>::get( PiPlatform, Plugin)); int InsertIDx = 0; for (RT::PiDevice Device : PiDevices) { // get DeviceType value and put it to DeviceDesc RT::PiDeviceType PiDevType; Plugin.call<PiApiKind::piDeviceGetInfo>(Device, PI_DEVICE_INFO_TYPE, sizeof(RT::PiDeviceType), &PiDevType, nullptr); sycl::info::device_type DeviceType = pi::cast<info::device_type>(PiDevType); for (const auto &SyclDeviceType : getSyclDeviceTypeMap()) { if (SyclDeviceType.second == DeviceType) { const auto &DeviceTypeValue = SyclDeviceType.first; DeviceDesc[DeviceTypeKeyName] = DeviceTypeValue; break; } } // get DeviceVendorId value and put it to DeviceDesc uint32_t DeviceVendorIdUInt = sycl::detail::get_device_info<uint32_t, info::device::vendor_id>::get( Device, Plugin); std::stringstream DeviceVendorIdHexStringStream; DeviceVendorIdHexStringStream << "0x" << std::hex << DeviceVendorIdUInt; const auto &DeviceVendorIdValue = DeviceVendorIdHexStringStream.str(); DeviceDesc[DeviceVendorIdKeyName] = DeviceVendorIdValue; // get DriverVersion value and put it to DeviceDesc const auto &DriverVersionValue = sycl::detail::get_device_info< std::string, info::device::driver_version>::get(Device, Plugin); DeviceDesc[DriverVersionKeyName] = DriverVersionValue; // get DeviceName value and put it to DeviceDesc const auto &DeviceNameValue = sycl::detail::get_device_info<std::string, info::device::name>::get( Device, Plugin); DeviceDesc[DeviceNameKeyName] = DeviceNameValue; // check if we can allow device with such device description DeviceDesc if (deviceIsAllowed(DeviceDesc, AllowListParsed)) { PiDevices[InsertIDx++] = Device; } } PiDevices.resize(InsertIDx); } } // namespace detail } // namespace sycl } // __SYCL_INLINE_NAMESPACE(cl)
42.429333
80
0.629816
mgehre-xlx
fe9342a2cd4e25288f083537775247a1c249697e
1,109
cpp
C++
Eunoia-Engine/Src/Eunoia/Utils/SettingsLoader.cpp
EunoiaGames/Eunoia-Dev
94edea774d1de05dc6a0c24ffdd3bb91b91a3346
[ "Apache-2.0" ]
null
null
null
Eunoia-Engine/Src/Eunoia/Utils/SettingsLoader.cpp
EunoiaGames/Eunoia-Dev
94edea774d1de05dc6a0c24ffdd3bb91b91a3346
[ "Apache-2.0" ]
null
null
null
Eunoia-Engine/Src/Eunoia/Utils/SettingsLoader.cpp
EunoiaGames/Eunoia-Dev
94edea774d1de05dc6a0c24ffdd3bb91b91a3346
[ "Apache-2.0" ]
null
null
null
#include "SettingsLoader.h" #include "../Core/Engine.h" namespace Eunoia { void SettingsLoader::WriteSettingsToFile(const String& path, const EunoiaSettings& settings) { FILE* file = fopen(path.C_Str(), "wb"); if (!file) return; fwrite(&settings, sizeof(EunoiaSettings), 1, file); fclose(file); } void SettingsLoader::LoadSettingsFromFile(const String& path, b32 applySettings) { FILE* file = fopen(path.C_Str(), "rb"); if (!file) return; EunoiaSettings settings; fread(&settings, sizeof(EunoiaSettings), 1, file); fclose(file); if (applySettings) ApplySettings(settings); } void SettingsLoader::ApplySettings(const EunoiaSettings& settings) { Renderer2D* r2D = Engine::GetRenderer()->GetRenderer2D(); Renderer3D* r3D = Engine::GetRenderer()->GetRenderer3D(); r2D->SetProjection(settings.settings2D.projection); r2D->SetSpritePosOrigin(settings.settings2D.origin); r3D->SetAmbient(settings.settings3D.ambient); r3D->SetBloomThreshold(settings.settings3D.bloomThreshold); r3D->SetBloomBlurIterationCount(settings.settings3D.bloomBlurIterCount); } }
25.790698
93
0.737601
EunoiaGames
fe9881602fb5466a928517ace5c24e466538ffec
818
hpp
C++
include/matrix.hpp
Alan-Kuan/MatrixSpaces
38d490635dbd1c6bc6fbba75bc0128e9820456fc
[ "MIT" ]
null
null
null
include/matrix.hpp
Alan-Kuan/MatrixSpaces
38d490635dbd1c6bc6fbba75bc0128e9820456fc
[ "MIT" ]
null
null
null
include/matrix.hpp
Alan-Kuan/MatrixSpaces
38d490635dbd1c6bc6fbba75bc0128e9820456fc
[ "MIT" ]
null
null
null
#ifndef MATRIX_HPP #define MATRIX_HPP #include "fraction.hpp" #include <cassert> #include <iostream> using namespace std; struct Matrix{ int row_size, col_size; Fraction **rows; // Constructors Matrix(int n); Matrix(int m, int n); // Copy Constructor Matrix(const Matrix &M); // Destructor ~Matrix(); // Operater Overloading Fraction*& operator [] (const int &i); Fraction* operator [] (const int &i) const; // access-only Matrix operator - () const; // unary minus Matrix operator + (const Matrix &M); Matrix operator - (const Matrix &M); Matrix operator * (const Matrix &M); Matrix operator * (const int &x); // scalar multiplication Matrix& operator = (const Matrix &M); // Tranpose Matrix transpose(void) const; }; ostream& operator << (ostream &os, const Matrix &M); #endif
17.041667
60
0.680929
Alan-Kuan
fe9897c0a96bd599ca447f2182733f46fcd4987e
2,034
cpp
C++
src/Thor/Particle.cpp
Shinao/JustAGame
d2683b9a1b33f236e5f87b1cb26444be50a9851a
[ "MIT" ]
null
null
null
src/Thor/Particle.cpp
Shinao/JustAGame
d2683b9a1b33f236e5f87b1cb26444be50a9851a
[ "MIT" ]
null
null
null
src/Thor/Particle.cpp
Shinao/JustAGame
d2683b9a1b33f236e5f87b1cb26444be50a9851a
[ "MIT" ]
null
null
null
///////////////////////////////////////////////////////////////////////////////// // // Thor C++ Library // Copyright (c) 2011-2014 Jan Haller // // 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. // ///////////////////////////////////////////////////////////////////////////////// #include <Thor/Particles/Particle.hpp> namespace thor { Particle::Particle(sf::Time totalLifetime) : position() , velocity() , rotation() , rotationSpeed() , scale(1.f, 1.f) , color(255, 255, 255) , textureIndex(0) , totalLifetime(totalLifetime) , passedLifetime(sf::Time::Zero) { } sf::Time getElapsedLifetime(const Particle& particle) { return particle.passedLifetime; } sf::Time getTotalLifetime(const Particle& particle) { return particle.totalLifetime; } sf::Time getRemainingLifetime(const Particle& particle) { return getTotalLifetime(particle) - getElapsedLifetime(particle); } float getElapsedRatio(const Particle& particle) { return getElapsedLifetime(particle) / getTotalLifetime(particle); } float getRemainingRatio(const Particle& particle) { return getRemainingLifetime(particle) / getTotalLifetime(particle); } } // namespace thor
28.647887
82
0.663717
Shinao
fe999578e94c4e4f47034918b44d493a8870d28f
2,104
cpp
C++
libs/fnd/memory/test/src/unit_test_fnd_memory_addressof.cpp
myoukaku/bksge
0f8b60e475a3f1709723906e4796b5e60decf06e
[ "MIT" ]
4
2018-06-10T13:35:32.000Z
2021-06-03T14:27:41.000Z
libs/fnd/memory/test/src/unit_test_fnd_memory_addressof.cpp
myoukaku/bksge
0f8b60e475a3f1709723906e4796b5e60decf06e
[ "MIT" ]
566
2017-01-31T05:36:09.000Z
2022-02-09T05:04:37.000Z
libs/fnd/memory/test/src/unit_test_fnd_memory_addressof.cpp
myoukaku/bksge
0f8b60e475a3f1709723906e4796b5e60decf06e
[ "MIT" ]
1
2018-07-05T04:40:53.000Z
2018-07-05T04:40:53.000Z
/** * @file unit_test_fnd_memory_addressof.cpp * * @brief addressof のテスト * * @author myoukaku */ #include <bksge/fnd/memory/addressof.hpp> #include <bksge/fnd/config.hpp> #include <gtest/gtest.h> #include "constexpr_test.hpp" namespace bksge_memory_test { namespace addressof_test { struct UselessType {}; // operator&がオーバーロードされていないクラス struct A { }; // operator&がオーバーロードされているクラス struct B { BKSGE_CONSTEXPR UselessType operator&(void) const { return UselessType(); } }; // operator&がグローバル関数としてオーバーロードされているクラス struct C { }; BKSGE_CONSTEXPR UselessType operator&(C const&) { return UselessType(); } BKSGE_CONSTEXPR int func(UselessType) { return 0; } BKSGE_CONSTEXPR int func(A const*) { return 1; } BKSGE_CONSTEXPR int func(B const*) { return 2; } BKSGE_CONSTEXPR int func(C const*) { return 3; } GTEST_TEST(MemoryTest, AddressofTest) { { BKSGE_CONSTEXPR int n1 = 0; BKSGE_CONSTEXPR const int n2 = 0; volatile int n3 = 0; const volatile int n4 = 0; BKSGE_CONSTEXPR_EXPECT_TRUE(&n1 == bksge::addressof(n1)); BKSGE_CONSTEXPR_EXPECT_TRUE(&n2 == bksge::addressof(n2)); EXPECT_TRUE(&n3 == bksge::addressof(n3)); EXPECT_TRUE(&n4 == bksge::addressof(n4)); } { BKSGE_CONSTEXPR A a {}; BKSGE_CONSTEXPR_EXPECT_EQ(1, func(&a)); BKSGE_CONSTEXPR_EXPECT_EQ(1, func(bksge::addressof(a))); } { BKSGE_CONSTEXPR B b {}; BKSGE_CXX17_CONSTEXPR_EXPECT_EQ(0, func(&b)); #if defined(BKSGE_APPLE_CLANG) EXPECT_EQ(2, func(bksge::addressof(b))); #else BKSGE_CXX17_CONSTEXPR_EXPECT_EQ(2, func(bksge::addressof(b))); #endif } { BKSGE_CONSTEXPR C c {}; BKSGE_CXX17_CONSTEXPR_EXPECT_EQ(0, func(&c)); #if defined(BKSGE_APPLE_CLANG) EXPECT_EQ(3, func(bksge::addressof(c))); #else BKSGE_CXX17_CONSTEXPR_EXPECT_EQ(3, func(bksge::addressof(c))); #endif } } } // namespace addressof_test } // namespace bksge_memory_test
19.849057
65
0.637357
myoukaku
fe99db904207e277e3650932910de2a74856ae3e
1,241
cpp
C++
src/02/02.cpp
TrojanerHD/AdventofCode2021
2c378b3bc6545dbab5f6a825ed783a02da4a049e
[ "MIT" ]
1
2021-12-03T17:36:21.000Z
2021-12-03T17:36:21.000Z
src/02/02.cpp
TrojanerHD/AdventofCode2021
2c378b3bc6545dbab5f6a825ed783a02da4a049e
[ "MIT" ]
null
null
null
src/02/02.cpp
TrojanerHD/AdventofCode2021
2c378b3bc6545dbab5f6a825ed783a02da4a049e
[ "MIT" ]
1
2021-12-03T17:34:41.000Z
2021-12-03T17:34:41.000Z
#include <iostream> #include "../common/common.h" int main() { auto inputs = read_inputs(); auto values = split(inputs, "\n"); // Part 1 auto depth = 0; auto horizontal = 0; for (size_t i = 0; i < values.size(); i++) { auto input = values[i]; auto instructions = split(input, " "); if (instructions[0] == "forward") horizontal += stoi(instructions[1]); else if (instructions[0] == "down") depth += stoi(instructions[1]); else if (instructions[0] == "up") depth -= stoi(instructions[1]); } std::cout << "Part 1: " << horizontal * depth << std::endl; // Part 2 depth = 0; horizontal = 0; auto aim = 0; for (size_t i = 0; i < values.size(); i++) { auto input = values[i]; auto instructions = split(input, " "); if (instructions[0] == "forward") { horizontal += stoi(instructions[1]); depth += aim * stoi(instructions[1]); } else if (instructions[0] == "down") aim += stoi(instructions[1]); else if (instructions[0] == "up") aim -= stoi(instructions[1]); } std::cout << "Part 2: " << horizontal * depth << std::endl; }
31.820513
63
0.514102
TrojanerHD
fe9a747b82e472127db0e366216744fd8accae86
132,136
cpp
C++
CarenRengineCodes/Direct2D/CarenD2D1DCRenderTarget.cpp
VictorSantosReis/CarenRengine
8d0291171a6c5c402320ef2c0f6672ff2d412962
[ "Apache-2.0" ]
4
2020-10-19T17:17:11.000Z
2020-10-22T18:12:34.000Z
CarenRengineCodes/Direct2D/CarenD2D1DCRenderTarget.cpp
VictorSantosReis/CarenRengine
8d0291171a6c5c402320ef2c0f6672ff2d412962
[ "Apache-2.0" ]
1
2021-02-07T03:10:26.000Z
2021-02-07T03:10:26.000Z
CarenRengineCodes/Direct2D/CarenD2D1DCRenderTarget.cpp
VictorSantosReis/CarenRengine
8d0291171a6c5c402320ef2c0f6672ff2d412962
[ "Apache-2.0" ]
null
null
null
/* Copyright 2020 Victor Santos Reis 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 "../pch.h" #include "CarenD2D1DCRenderTarget.h" //Destruidor. CarenD2D1DCRenderTarget::~CarenD2D1DCRenderTarget() { //Define que a classe foi descartada Prop_DisposedClasse = true; } //Construtor. CarenD2D1DCRenderTarget::CarenD2D1DCRenderTarget() { //INICIALIZA SEM NENHUM PONTEIRO VINCULADO. } // Métodos da interface ICaren /// <summary> /// (QueryInterface) - Consulta o objeto COM atual para um ponteiro para uma de suas interfaces; identificando a interface por uma /// referência ao identificador de interface (IID). Se o objeto COM implementar a interface, o método retorna um ponteiro para essa /// interface depois de adicionar uma nova referência(AddRef). /// </summary> /// <param name="Param_Guid">O IID(Identificador de Interface) ou GUID para a interface desejada.</param> /// <param name="Param_InterfaceSolicitada">A interface que vai receber o ponteiro nativo. O usuário deve inicializar a interface antes de chamar o método. Libere a interface quando não for mais usá-la.</param> CarenResult CarenD2D1DCRenderTarget::ConsultarInterface(String^ Param_Guid, ICaren^ Param_InterfaceSolicitada) { //Variavel que vai retornar o resultado. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM HRESULT Hr = E_FAIL; //Variaveis a serem utilizadas GUID GuidInterface = GUID_NULL; wchar_t* DadosGuid = NULL; LPVOID* pInterfaceSolcitada = NULL; //Setor onde será criado o GUID para realizar a operação. { //Context Marshal. marshal_context ctx; //Lagrura da string int LarguraString = 0; //Variavel que vai conter os dados da String para o tipo não gerenciado. const char* DadosConvertidos = NULL; //Verifica se a string é valida. if (!String::IsNullOrEmpty(Param_Guid)) { //Obtém a largura da String. LarguraString = Param_Guid->Length + 1; //Converte os dados para um buffer de char. //O Proprio marshal_context destroi o buffer. DadosConvertidos = ctx.marshal_as<const char*>(Param_Guid); //Aloca memoria para o Dados do Guid. DadosGuid = new wchar_t[LarguraString]; //Copia os dados para o OLECHAR. mbstowcs_s(NULL, DadosGuid, LarguraString, DadosConvertidos, LarguraString - 1); //Chama o método que vai criar o CLSID adequado a aparti do guid Hr = CLSIDFromString(DadosGuid, (LPCLSID)&GuidInterface); } else { //Falhou ao criar o GUID Resultado.AdicionarCodigo(ResultCode::ER_GUID_INVALIDO, false); //A string não é valida goto Done; } } //Verifica se o guid foi criado com sucesso. if (GuidInterface == GUID_NULL) { //Falhou ao criar o GUID Resultado.AdicionarCodigo(ResultCode::ER_GUID_INVALIDO, false); //Sai do método goto Done; } //Chama o método para realizara operação Hr = PonteiroTrabalho->QueryInterface(GuidInterface, (LPVOID*)&pInterfaceSolcitada); //Processa o resultado da chamada. Resultado.ProcessarCodigoOperacao(Hr); //Verifica se obteve sucesso na operação. if (!Sucesso(static_cast<HRESULT>(Resultado.HResult))) { //Falhou ao realizar a operação. //Define o código na classe. Var_Glob_LAST_HRESULT = Hr; //Sai do método Sair; } //Define o ponteiro na interface solicitada. //A interface deve ter sido incializada pelo usuário. Resultado = Param_InterfaceSolicitada->AdicionarPonteiro(pInterfaceSolcitada); //Verifica o resultado da operação. if (Resultado.StatusCode != ResultCode::SS_OK) { //Libera a referência obtida a parti do QueryInterface. ((IUnknown*)pInterfaceSolcitada)->Release(); pInterfaceSolcitada = NULL; } Done:; //Verifica se o OLECHAR é valido e destroi if (ObjetoValido(DadosGuid)) { //Libera os dados. delete[] DadosGuid; } //Retorna o resultado return Resultado; } /// <summary> /// Método responsável por adicionar um novo ponteiro nativo a classe atual. /// Este método não é responsável por adicionar uma nova referência ao objeto COM. /// </summary> /// <param name="Param_PonteiroNativo">Variável (GERENCIADA) para o ponteiro nativo a ser adicionado.</param> CarenResult CarenD2D1DCRenderTarget::AdicionarPonteiro(IntPtr Param_PonteiroNativo) { //Variavel que vai retornar o resultado. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Verifica se o objeto é valido if (Param_PonteiroNativo == IntPtr::Zero) { //O objeto não é valido Resultado.AdicionarCodigo(ResultCode::ER_E_POINTER, false); //Sai do método. goto Done; } //Converte o ponteiro para o tipo especifico da classe. PonteiroTrabalho = reinterpret_cast<ID2D1DCRenderTarget*>(Param_PonteiroNativo.ToPointer()); //Verifica o ponteiro if (ObjetoValido(PonteiroTrabalho)) { //Define que o ponteiro foi definido com sucesso. Resultado.AdicionarCodigo(ResultCode::SS_OK, true); } else { //Define falha na operação Resultado.AdicionarCodigo(ResultCode::ER_E_POINTER, false); } Done:; //Retornao resultado return Resultado; } /// <summary> /// Método responsável por adicionar um novo ponteiro nativo a classe atual. /// Este método não é responsável por adicionar uma nova referência ao objeto COM. /// </summary> /// <param name="Param_PonteiroNativo">Variável (NATIVA) para o ponteiro nativo a ser adicionado.</param> CarenResult CarenD2D1DCRenderTarget::AdicionarPonteiro(LPVOID Param_PonteiroNativo) { //Variavel que vai retornar o resultado. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Verifica se o objeto é valido if (!ObjetoValido(Param_PonteiroNativo)) { //O objeto não é valido Resultado.AdicionarCodigo(ResultCode::ER_E_POINTER, false); //Sai do método goto Done; } //Converte o ponteiro para o tipo especifico da classe. PonteiroTrabalho = reinterpret_cast<ID2D1DCRenderTarget*>(Param_PonteiroNativo); //Verifica se o ponteiro é valido if (ObjetoValido(PonteiroTrabalho)) { //Ponteiro convertido com sucesso! //Define sucesso na operação Resultado.AdicionarCodigo(ResultCode::SS_OK, true); } else { //Falhou ao converter o ponteiro vazio para sua real representação. //Define falha no ponteiro Resultado.AdicionarCodigo(ResultCode::ER_E_POINTER, false); } Done:; //Retornao resultado return Resultado; } /// <summary> /// Método responsável por recuperar o ponteiro atual da classe. Se o ponteiro não for valido, o método retornar ResultCode::ER_PONTEIRO. /// Este método não é responsável por adicionar uma nova referência ao objeto COM. /// </summary> /// <param name="Param_Out_PonteiroNativo">Variável (GERENCIADA) que vai receber o ponteiro nativo.</param> CarenResult CarenD2D1DCRenderTarget::RecuperarPonteiro([Out] IntPtr% Param_Out_PonteiroNativo) { //Variavel que vai retornar o resultado. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Verifica se o ponteiro é valido if (!ObjetoValido(PonteiroTrabalho)) { //O ponteiro de trabalho é invalido. Resultado.AdicionarCodigo(ResultCode::ER_E_POINTER, false); //Sai do método goto Done; } //Cria e define o ponteiro gerenciado no parametro de saida. Param_Out_PonteiroNativo = IntPtr((LPVOID)PonteiroTrabalho); //Define o resultado Resultado.AdicionarCodigo(ResultCode::SS_OK, true); Done:; //Retorna o resultado return Resultado; } /// <summary> /// Método responsável por recuperar o ponteiro atual da classe. Se o ponteiro não for valido, o método retornar ResultCode::ER_PONTEIRO. /// Este método não é responsável por adicionar uma nova referência ao objeto COM. /// </summary> /// <param name="Param_Out_PonteiroNativo">Variável (NATIVA) que vai receber o ponteiro nativo.</param> CarenResult CarenD2D1DCRenderTarget::RecuperarPonteiro(LPVOID* Param_Out_PonteiroNativo) { //Variavel que vai retornar o resultado. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Verifica se o ponteiro é valido if (!ObjetoValido(PonteiroTrabalho)) { //O ponteiro de trabalho é invalido. Resultado.AdicionarCodigo(ResultCode::ER_E_POINTER, false); //Sai do método goto Done; } //Define o ponteiro de trabalho no parametro de saida. *Param_Out_PonteiroNativo = PonteiroTrabalho; //Define o resultado Resultado.AdicionarCodigo(ResultCode::SS_OK, true); Done:; //Retorna o resultado return Resultado; } /// <summary> /// Método responsável por retornar a quantidade de referências do objeto COM atual. /// </summary> /// <param name="Param_Out_Referencias">Variável que vai receber a quantidade de referências do objeto.</param> CarenResult CarenD2D1DCRenderTarget::RecuperarReferencias([Out] UInt64% Param_Out_Referencias) { //Variavel que vai retornar o resultado. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Verifica se o ponteiro é valido if (!ObjetoValido(PonteiroTrabalho)) { //O ponteiro de trabalho é invalido. Resultado.AdicionarCodigo(ResultCode::ER_E_POINTER, false); //Sai do método goto Done; } //Adiciona uma referência ao ponteiro ULONG CountRefs = PonteiroTrabalho->AddRef(); //Libera a referência adicional PonteiroTrabalho->Release(); //Decrementa o valor da quantidade de referência retornada em (-1) e define no parametro de saida. Param_Out_Referencias = static_cast<UInt64>(CountRefs - 1); //Define o resultado Resultado.AdicionarCodigo(ResultCode::SS_OK, true); Done:; //Retorna o resultado return Resultado; } /// <summary> /// Método responsável por indicar se o ponteiro COM atual é válido. /// </summary> CarenResult CarenD2D1DCRenderTarget::StatusPonteiro() { return (ObjetoValido(PonteiroTrabalho) ? CarenResult(ResultCode::SS_OK, true) : CarenResult(ResultCode::ER_E_POINTER, false)); } /// <summary> /// Método responsável por retornar a variável que armazena o último código de erro desconhecido ou não documentado gerado pela classe. /// Esse método não chama o método nativo (GetLastError), apenas retorna o código de erro que foi armazenado na classe. /// </summary> Int32 CarenD2D1DCRenderTarget::ObterCodigoErro() { return Var_Glob_LAST_HRESULT; } /// <summary> /// (AddRef) - Incrementa a contagem de referência para o ponteiro do objeto COM atual. Você deve chamar este método sempre que /// você fazer uma cópia de um ponteiro de interface. /// </summary> void CarenD2D1DCRenderTarget::AdicionarReferencia() { //Adiciona uma referência ao ponteiro PonteiroTrabalho->AddRef(); } /// <summary> /// (Release) - 'Decrementa' a contagem de referência do objeto COM atual. /// </summary> void CarenD2D1DCRenderTarget::LiberarReferencia() { //Libera a referência e obtém a quantidade atual. ULONG RefCount = PonteiroTrabalho->Release(); //Verifica se a quantidade é zero e se o ponteiro ainda é valido. //Se sim, vai deletar o ponteiro. if (RefCount == 0 && ObjetoValido(PonteiroTrabalho)) { //NULA o ponteiro vazio. PonteiroTrabalho = NULL; } } /// <summary> /// Método responsável por chamar o finalizador da interface para realizar a limpeza e descarte de dados pendentes. /// Este método pode ser escrito de forma diferente para cada interface. /// </summary> void CarenD2D1DCRenderTarget::Finalizar() { ////////////////////// //Código de descarte// ////////////////////// //Informa ao GC que a classe já foi limpa e pode ser descartada. GC::SuppressFinalize(this); //Nula o ponteiro de trabalho da classe. PonteiroTrabalho = Nulo; //Chama o finalizador da classe this->~CarenD2D1DCRenderTarget(); } // Métodos da interface proprietária(ICarenD2D1DCRenderTarget) /// <summary> /// Vincula o alvo de renderização ao contexto do dispositivo ao qual ele emite comandos de desenho. /// Antes de renderizar com o alvo de renderização DC, você deve usar seu método BindDC para associá-lo a um GDI DC. Você faz isso cada vez que usa um DC diferente, ou o tamanho da área /// que deseja desenhar para mudanças. /// </summary> /// <param name="Param_Hdc">O contexto do dispositivo para o qual o alvo de renderização emite comandos de desenho.</param> /// <param name="Param_SubRect">As dimensões da Handle(Param_Hdc) para um contexto de dispositivo (HDC) a que o alvo de renderização está vinculado.</param> CarenResult CarenD2D1DCRenderTarget::BindDC( IntPtr Param_Hdc, CA_RECT^ Param_SubRect) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. Utilidades Util; RECT* pRect = NULL; HDC pHdc = NULL; //Converte a estrutura. pRect = Util.ConverterRECTManagedToUnmanaged(Param_SubRect); //Obtém o HDC(IntPtr) pHdc = Util.ConverterIntPtrTo<HDC>(Param_Hdc); //Chama o método para realizar a operação. Hr = PonteiroTrabalho->BindDC(pHdc, pRect); //Processa o resultado da chamada. Resultado.ProcessarCodigoOperacao(Hr); //Verifica se obteve sucesso na operação. if (!Sucesso(static_cast<HRESULT>(Resultado.HResult))) { //Falhou ao realizar a operação. //Define o código na classe. Var_Glob_LAST_HRESULT = Hr; //Sai do método Sair; } Done:; //Libera a memória para a estrutura. DeletarEstruturaSafe(&pRect); //Retorna o resultado. return Resultado; } // Métodos da interface proprietária(ICarenD2D1RenderTarget) /// <summary> /// Inicia o desenho deste alvo de renderização. /// </summary> void CarenD2D1DCRenderTarget::BeginDraw() { //Chama o método para realizar a operação. PonteiroTrabalho->BeginDraw(); } /// <summary> /// Limpa a área de desenho para a cor especificada. /// </summary> /// <param name="Param_ClearColor"></param> void CarenD2D1DCRenderTarget::Clear(CA_D2D1_COLOR_F^ Param_ClearColor) { //Variaveis a serem utilizadas. Utilidades Util; D2D1_COLOR_F* pColorF = NULL; //Converte a estrutura gerenciada para a nativa. pColorF = Util.ConverterD2D1_COLOR_FManagedToUnmanaged(Param_ClearColor); //Chama o método para realizar a operação. PonteiroTrabalho->Clear(pColorF); //Libera a memória para a estrutura. DeletarEstruturaSafe(&pColorF); } /// <summary> /// Cria um bitmap do Direct2D de um ponteiro para dados de origem na memória. /// </summary> /// <param name="Param_Size">As dimensões em pixels do bitmap a ser criado.</param> /// <param name="Param_DadosOrigem">Um ponteiro para a localização da memória dos dados da imagem ou NULO para criar um bitmap não inicializado.</param> /// <param name="Param_Pitch">A contagem de bytes de cada linha de varredura, que é igual a (a largura da imagem em pixels × o número de bytes por pixel) + preenchimento de memória. Se (Param_DadosOrigem) é NULO, este valor é ignorado. (Note que o tom também é às vezes chamado de pitch.)</param> /// <param name="Param_PropriedadesBitmap">O formato de pixel e pontos por polegada (DPI) do bitmap a ser criado.</param> /// <param name="Param_Out_Bitmap">Retorna a interface (ICarenD2D1Bitmap) que contém um ponteiro para o novo bitmap.</param> CarenResult CarenD2D1DCRenderTarget::CreateBitmap( CA_D2D1_SIZE_U^ Param_Size, ICarenBuffer^ Param_DadosOrigem, UInt32 Param_Pitch, CA_D2D1_BITMAP_PROPERTIES^ Param_PropriedadesBitmap, [Out] ICarenD2D1Bitmap^% Param_Out_Bitmap) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. Utilidades Util; D2D1_SIZE_U* pSizeU = NULL; D2D1_BITMAP_PROPERTIES* pBitmapProps = NULL; IntPtr pBufferOrigem = IntPtr::Zero; ID2D1Bitmap* pOutBitmap = NULL; //Converte as estruturas gerenciadas para as nativas. pSizeU = Util.ConverterD2D1_SIZE_UManagedToUnmanaged(Param_Size); pBitmapProps = Util.ConverterD2D1_BITMAP_PROPERTIESManagedToUnmanaged(Param_PropriedadesBitmap); //Obtém o ponteiro para a memória de origem. Resultado = Param_DadosOrigem->GetInternalPointer(pBufferOrigem); //Verifica se não falhou. if (!CarenSucesso(Resultado)) { //Falhou ao recupera o ponteiro. //Sai do método Sair; } //Chama o método para realizar a operação. Hr = PonteiroTrabalho->CreateBitmap(*pSizeU, pBufferOrigem.ToPointer(), Param_Pitch, pBitmapProps, &pOutBitmap); //Processa o resultado da chamada. Resultado.ProcessarCodigoOperacao(Hr); //Verifica se obteve sucesso na operação. if (!Sucesso(static_cast<HRESULT>(Resultado.HResult))) { //Falhou ao realizar a operação. //Define o código na classe. Var_Glob_LAST_HRESULT = Hr; //Sai do método Sair; } //Cria a interface que será retornada Param_Out_Bitmap = gcnew CarenD2D1Bitmap(); //Define o ponteiro na interface de saida. Resultado = Param_Out_Bitmap->AdicionarPonteiro(pOutBitmap); //Verifica se houve erro. if (!CarenSucesso(Resultado)) { //Falhou ao definir o ponteiro. //Libera o ponteiro pOutBitmap->Release(); pOutBitmap = NULL; Param_Out_Bitmap->Finalizar(); Param_Out_Bitmap = nullptr; } Done:; //Libera a memória para as estruturas. DeletarEstruturaSafe(&pSizeU); DeletarEstruturaSafe(&pBitmapProps); //Retorna o resultado. return Resultado; } /// <summary> /// Cria um bitmap do Direct2D não inicializado. /// </summary> /// <param name="Param_Size">As dimensões em pixels do bitmap a ser criado.</param> /// <param name="Param_PropriedadesBitmap">O formato de pixel e pontos por polegada (DPI) do bitmap a ser criado.</param> /// <param name="Param_Out_Bitmap">Retorna a interface (ICarenD2D1Bitmap) que contém um ponteiro para o novo bitmap.</param> CarenResult CarenD2D1DCRenderTarget::CreateBitmap( CA_D2D1_SIZE_U^ Param_Size, CA_D2D1_BITMAP_PROPERTIES^ Param_PropriedadesBitmap, [Out] ICarenD2D1Bitmap^% Param_Out_Bitmap) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. Utilidades Util; D2D1_SIZE_U* pSizeU = NULL; D2D1_BITMAP_PROPERTIES* pBitmapProps = NULL; ID2D1Bitmap* pOutBitmap = NULL; //Converte as estruturas gerenciadas para as nativas. pSizeU = Util.ConverterD2D1_SIZE_UManagedToUnmanaged(Param_Size); pBitmapProps = Util.ConverterD2D1_BITMAP_PROPERTIESManagedToUnmanaged(Param_PropriedadesBitmap); //Chama o método para realizar a operação. Hr = PonteiroTrabalho->CreateBitmap(*pSizeU, *pBitmapProps, &pOutBitmap); //Processa o resultado da chamada. Resultado.ProcessarCodigoOperacao(Hr); //Verifica se obteve sucesso na operação. if (!Sucesso(static_cast<HRESULT>(Resultado.HResult))) { //Falhou ao realizar a operação. //Define o código na classe. Var_Glob_LAST_HRESULT = Hr; //Sai do método Sair; } //Cria a interface que será retornada Param_Out_Bitmap = gcnew CarenD2D1Bitmap(); //Define o ponteiro na interface de saida. Resultado = Param_Out_Bitmap->AdicionarPonteiro(pOutBitmap); //Verifica se houve erro. if (!CarenSucesso(Resultado)) { //Falhou ao definir o ponteiro. //Libera o ponteiro pOutBitmap->Release(); pOutBitmap = NULL; Param_Out_Bitmap->Finalizar(); Param_Out_Bitmap = nullptr; } Done:; //Libera a memória para as estruturas. DeletarEstruturaSafe(&pSizeU); DeletarEstruturaSafe(&pBitmapProps); //Retorna o resultado. return Resultado; } /// <summary> /// Cria um ICarenD2D1BitmapBrush a partir do bitmap especificado. /// </summary> /// <param name="Param_Bitmap">O conteúdo do bitmap do novo pincel(Brush).</param> /// <param name="Param_PropriedadesBitmapBrush">Os modos de extensão e o modo de interpolação do novo pincel, ou NULO. Se você definir este parâmetro como NULO,a escova padrão para o D2D1_EXTEND_MODE_CLAMP /// modos de extensão horizontal e vertical e o modo de interpolação D2D1_BITMAP_INTERPOLATION_MODE_LINEAR.</param> /// <param name="Param_PropriedadesBrush">Uma estrutura que contenha a opacidade e a transformação do novo pincel, ou NULO. Se você definir este parâmetro como NULO,o pincel define o membro da opacidade /// para 1.0F e o membro de transformação para a matriz de identidade.</param> /// <param name="Param_Out_BitmapBrush">Retorna a interface (ICarenD2D1BitmapBrush) que contém um ponteiro para o novo pincel(Brush).</param> CarenResult CarenD2D1DCRenderTarget::CreateBitmapBrush( ICarenD2D1Bitmap^ Param_Bitmap, CA_D2D1_BITMAP_BRUSH_PROPERTIES^ Param_PropriedadesBitmapBrush, CA_D2D1_BRUSH_PROPERTIES^ Param_PropriedadesBrush, [Out] ICarenD2D1BitmapBrush^% Param_Out_BitmapBrush) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. Utilidades Util; ID2D1Bitmap* pBitmap = NULL; D2D1_BITMAP_BRUSH_PROPERTIES* pBitmapBrushProps = NULL; //Pode ser NULO. D2D1_BRUSH_PROPERTIES* pBrushProps = NULL; //Pode ser NULO. ID2D1BitmapBrush* pOutBrush = NULL; //Recupera o ponteiro para o bitmap. Resultado = Param_Bitmap->RecuperarPonteiro((LPVOID*)&pBitmap); //Verifica se não houve erro. if (!CarenSucesso(Resultado)) { //Falhou. O ponteiro é invalido. //Sai do método Sair; } //Converte as estruturas gerenciadas para a nativa se validas. pBitmapBrushProps = ObjetoGerenciadoValido(Param_PropriedadesBitmapBrush) ? Util.ConverterD2D1_BITMAP_BRUSH_PROPERTIESManagedToUnmanaged(Param_PropriedadesBitmapBrush) : NULL; pBrushProps = ObjetoGerenciadoValido(Param_PropriedadesBrush) ? Util.ConverterD2D1_BRUSH_PROPERTIESManagedToUnmanaged(Param_PropriedadesBrush) : NULL; //Chama o método para realizar a operação. Hr = PonteiroTrabalho->CreateBitmapBrush(pBitmap, pBitmapBrushProps, pBrushProps, &pOutBrush); //Processa o resultado da chamada. Resultado.ProcessarCodigoOperacao(Hr); //Verifica se obteve sucesso na operação. if (!Sucesso(static_cast<HRESULT>(Resultado.HResult))) { //Falhou ao realizar a operação. //Define o código na classe. Var_Glob_LAST_HRESULT = Hr; //Sai do método Sair; } //Cria a classe a ser retornada. Param_Out_BitmapBrush = gcnew CarenD2D1BitmapBrush(); //Define o ponteiro da interface. Resultado = Param_Out_BitmapBrush->AdicionarPonteiro(pOutBrush); //Verifica se não houve erro if (!CarenSucesso(Resultado)) { //Falhou ao definir o ponteiro. //Libera os dados. pOutBrush->Release(); pOutBrush = NULL; Param_Out_BitmapBrush->Finalizar(); Param_Out_BitmapBrush = nullptr; } Done:; //Libera a memória para as estruturas. DeletarEstruturaSafe(&pBitmapBrushProps); DeletarEstruturaSafe(&pBrushProps); //Retorna o resultado. return Resultado; } /// <summary> /// Cria um ICarenD2D1BitmapBrush a partir do bitmap especificado. O pincel usa os valores padrão para seu modo de extensão, modo de interpolação, opacidade e transformação. /// </summary> /// <param name="Param_Bitmap">O conteúdo do bitmap do novo pincel.</param> /// <param name="Param_Out_BitmapBrush">Retorna a interface (ICarenD2D1BitmapBrush) que contém um ponteiro para o novo pincel(Brush).</param> CarenResult CarenD2D1DCRenderTarget::CreateBitmapBrush( ICarenD2D1Bitmap^ Param_Bitmap, [Out] ICarenD2D1BitmapBrush^% Param_Out_BitmapBrush) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. ID2D1Bitmap* pBitmap = NULL; ID2D1BitmapBrush* pOutBrush = NULL; //Recupera o ponteiro para o bitmap. Resultado = Param_Bitmap->RecuperarPonteiro((LPVOID*)&pBitmap); //Verifica se não houve erro. if (!CarenSucesso(Resultado)) { //Falhou. O ponteiro é invalido. //Sai do método Sair; } //Chama o método para realizar a operação. Hr = PonteiroTrabalho->CreateBitmapBrush(pBitmap, &pOutBrush); //Processa o resultado da chamada. Resultado.ProcessarCodigoOperacao(Hr); //Verifica se obteve sucesso na operação. if (!Sucesso(static_cast<HRESULT>(Resultado.HResult))) { //Falhou ao realizar a operação. //Define o código na classe. Var_Glob_LAST_HRESULT = Hr; //Sai do método Sair; } //Cria a classe a ser retornada. Param_Out_BitmapBrush = gcnew CarenD2D1BitmapBrush(); //Define o ponteiro da interface. Resultado = Param_Out_BitmapBrush->AdicionarPonteiro(pOutBrush); //Verifica se não houve erro if (!CarenSucesso(Resultado)) { //Falhou ao definir o ponteiro. //Libera os dados. pOutBrush->Release(); pOutBrush = NULL; Param_Out_BitmapBrush->Finalizar(); Param_Out_BitmapBrush = nullptr; } Done:; //Retorna o resultado. return Resultado; } /// <summary> /// Cria um ID2D1BitmapBrush a partir do bitmap especificado. O pincel usa os valores padrão para sua opacidade e transformação. /// O Brush bitmap criado por este método tem uma opacidade de 1.0f e a matriz de identidade como sua transformação. /// </summary> /// <param name="Param_Bitmap">O conteúdo do bitmap do novo pincel.</param> /// <param name="Param_PropriedadesBitmapBrush">Os modos de extensão e o modo de interpolação do novo pincel.</param> /// <param name="Param_Out_BitmapBrush">Retorna a interface (ICarenD2D1BitmapBrush) que contém um ponteiro para o novo pincel(Brush).</param> CarenResult CarenD2D1DCRenderTarget::CreateBitmapBrush( ICarenD2D1Bitmap^ Param_Bitmap, CA_D2D1_BITMAP_BRUSH_PROPERTIES^ Param_PropriedadesBitmapBrush, [Out] ICarenD2D1BitmapBrush^% Param_Out_BitmapBrush) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. Utilidades Util; ID2D1Bitmap* pBitmap = NULL; ID2D1BitmapBrush* pOutBrush = NULL; D2D1_BITMAP_BRUSH_PROPERTIES* pBitmapBrushProps = NULL; //Recupera o ponteiro para o bitmap. Resultado = Param_Bitmap->RecuperarPonteiro((LPVOID*)&pBitmap); //Verifica se não houve erro. if (!CarenSucesso(Resultado)) { //Falhou. O ponteiro é invalido. //Sai do método Sair; } //Converte as estruturas gerenciadas para a nativa se validas. pBitmapBrushProps = Util.ConverterD2D1_BITMAP_BRUSH_PROPERTIESManagedToUnmanaged(Param_PropriedadesBitmapBrush); //Chama o método para realizar a operação. Hr = PonteiroTrabalho->CreateBitmapBrush(pBitmap, *pBitmapBrushProps, &pOutBrush); //Processa o resultado da chamada. Resultado.ProcessarCodigoOperacao(Hr); //Verifica se obteve sucesso na operação. if (!Sucesso(static_cast<HRESULT>(Resultado.HResult))) { //Falhou ao realizar a operação. //Define o código na classe. Var_Glob_LAST_HRESULT = Hr; //Sai do método Sair; } //Cria a classe a ser retornada. Param_Out_BitmapBrush = gcnew CarenD2D1BitmapBrush(); //Define o ponteiro da interface. Resultado = Param_Out_BitmapBrush->AdicionarPonteiro(pOutBrush); //Verifica se não houve erro if (!CarenSucesso(Resultado)) { //Falhou ao definir o ponteiro. //Libera os dados. pOutBrush->Release(); pOutBrush = NULL; Param_Out_BitmapBrush->Finalizar(); Param_Out_BitmapBrush = nullptr; } Done:; //Libera a memória para a estrutura. DeletarEstruturaSafe(&pBitmapBrushProps); //Retorna o resultado. return Resultado; } /// <summary> /// Cria um ICarenD2D1Bitmap copiando o bitmap especificado do Microsoft Windows Imaging Component (WIC). /// </summary> /// <param name="Param_WicBitmapSource">Uma interface ICarenWICBitmapSource que contém os dados a serem copiados.</param> /// <param name="Param_PropriedadesBitmap">O formato de pixel e DPI do bitmap para criar. O formato pixel deve corresponder ao formato de pixel do wicBitmapSource, ou o método falhará. Para evitar uma /// incompatibilidade, você pode passar NULO ou passar o valor obtido ligando para a função de ajudante D2D1::PixelFormat sem especificar nenhum valor de parâmetro. Se o dpiX e o dpiY forem 0,0f, o /// DPI padrão, 96, será usado. As informações de DPI incorporadas no (Param_WicBitmapSource) são ignoradas.</param> /// <param name="Param_Out_Bitmap">Retorna a interface ICarenD2D1Bitmap que contém um ponteiro para o novo bitmap.</param> CarenResult CarenD2D1DCRenderTarget::CreateBitmapFromWicBitmap( ICaren^ Param_WicBitmapSource, CA_D2D1_BITMAP_PROPERTIES^ Param_PropriedadesBitmap, [Out] ICarenD2D1Bitmap^% Param_Out_Bitmap) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. Utilidades Util; IWICBitmapSource* pWicBitmapSource = NULL; D2D1_BITMAP_PROPERTIES* pBitmapProps = NULL; //Pode ser NULO. ID2D1Bitmap* pOutBitmap = NULL; //Recupera o ponteiro para o bitmap. Resultado = Param_WicBitmapSource->RecuperarPonteiro((LPVOID*)&pWicBitmapSource); //Verifica se não houve erro. if (!CarenSucesso(Resultado)) { //Falhou. O ponteiro é invalido. //Sai do método Sair; } //Converte a estrutura gerenciada para a nativa se valida. pBitmapProps = ObjetoGerenciadoValido(Param_PropriedadesBitmap) ? Util.ConverterD2D1_BITMAP_PROPERTIESManagedToUnmanaged(Param_PropriedadesBitmap) : NULL; //Chama o método para realizar a operação. Hr = PonteiroTrabalho->CreateBitmapFromWicBitmap(pWicBitmapSource, pBitmapProps, &pOutBitmap); //Processa o resultado da chamada. Resultado.ProcessarCodigoOperacao(Hr); //Verifica se obteve sucesso na operação. if (!Sucesso(static_cast<HRESULT>(Resultado.HResult))) { //Falhou ao realizar a operação. //Define o código na classe. Var_Glob_LAST_HRESULT = Hr; //Sai do método Sair; } //Cria a classe a ser retornada. Param_Out_Bitmap = gcnew CarenD2D1Bitmap(); //Define o ponteiro da interface. Resultado = Param_Out_Bitmap->AdicionarPonteiro(pOutBitmap); //Verifica se não houve erro if (!CarenSucesso(Resultado)) { //Falhou ao definir o ponteiro. //Libera os dados. pOutBitmap->Release(); pOutBitmap = NULL; Param_Out_Bitmap->Finalizar(); Param_Out_Bitmap = nullptr; } Done:; //Libera a memória para a estrutura. DeletarEstruturaSafe(&pBitmapProps); //Retorna o resultado. return Resultado; } /// <summary> /// Cria um ID2D1Bitmap copiando o bitmap especificado do Microsoft Windows Imaging Component (WIC). /// </summary> /// <param name="Param_WicBitmapSource">Uma interface ICarenWICBitmapSource que contém os dados a serem copiados.</param> /// <param name="Param_Out_Bitmap">Retorna a interface ICarenD2D1Bitmap que contém um ponteiro para o novo bitmap.</param> CarenResult CarenD2D1DCRenderTarget::CreateBitmapFromWicBitmap( ICaren^ Param_WicBitmapSource, [Out] ICarenD2D1Bitmap^% Param_Out_Bitmap) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. IWICBitmapSource* pWicBitmapSource = NULL; ID2D1Bitmap* pOutBitmap = NULL; //Recupera o ponteiro para o bitmap. Resultado = Param_WicBitmapSource->RecuperarPonteiro((LPVOID*)&pWicBitmapSource); //Verifica se não houve erro. if (!CarenSucesso(Resultado)) { //Falhou. O ponteiro é invalido. //Sai do método Sair; } //Chama o método para realizar a operação. Hr = PonteiroTrabalho->CreateBitmapFromWicBitmap(pWicBitmapSource, &pOutBitmap); //Processa o resultado da chamada. Resultado.ProcessarCodigoOperacao(Hr); //Verifica se obteve sucesso na operação. if (!Sucesso(static_cast<HRESULT>(Resultado.HResult))) { //Falhou ao realizar a operação. //Define o código na classe. Var_Glob_LAST_HRESULT = Hr; //Sai do método Sair; } //Cria a classe a ser retornada. Param_Out_Bitmap = gcnew CarenD2D1Bitmap(); //Define o ponteiro da interface. Resultado = Param_Out_Bitmap->AdicionarPonteiro(pOutBitmap); //Verifica se não houve erro if (!CarenSucesso(Resultado)) { //Falhou ao definir o ponteiro. //Libera os dados. pOutBitmap->Release(); pOutBitmap = NULL; Param_Out_Bitmap->Finalizar(); Param_Out_Bitmap = nullptr; } Done:; //Retorna o resultado. return Resultado; } /// <summary> /// Cria um alvo de renderização bitmap para uso durante o desenho offscreen intermediário compatível com o alvo de renderização atual. /// </summary> /// <param name="Param_DesiredSize">O tamanho desejado do novo alvo de renderização (em pixels independentes do dispositivo), se ele deve ser diferente do alvo de renderização original.</param> /// <param name="Param_DesiredPixelSize">O tamanho desejado do novo alvo de renderização em pixels se ele deve ser diferente do alvo de renderização original.</param> /// <param name="DesiredFormat">O formato de pixel desejado e o modo alfa do novo alvo de renderização. Se o formato do pixel for definido para DXGI_FORMAT_UNKNOWN, o novo alvo de renderização usará /// o mesmo formato de pixel que o alvo original da renderização. Se o modo alfa estiver D2D1_ALPHA_MODE_UNKNOWN,o modo alfa do novo destino renderizante padrão para D2D1_ALPHA_MODE_PREMULTIPLIED.</param> /// <param name="Param_Opcoes">Um valor que especifica se o novo alvo de renderização deve ser compatível com o GDI.</param> /// <param name="Param_Out_BitmapRenderTarget">Retorna a interface (ICarenD2D1BitmapRenderTarget) que contém um ponteiro para um novo alvo de renderização bitmap. O usuário deve inicializar a interface antes de chamar este método.</param> CarenResult CarenD2D1DCRenderTarget::CreateCompatibleRenderTarget( CA_D2D1_SIZE_F^ Param_DesiredSize, CA_D2D1_SIZE_U^ Param_DesiredPixelSize, CA_D2D1_PIXEL_FORMAT^ DesiredFormat, CA_D2D1_COMPATIBLE_RENDER_TARGET_OPTIONS Param_Opcoes, ICaren^ Param_Out_BitmapRenderTarget) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. Utilidades Util; D2D1_SIZE_F* pSizeF = NULL; D2D1_SIZE_U* pSizeU = NULL; D2D1_PIXEL_FORMAT* pPixelFormat = NULL; D2D1_COMPATIBLE_RENDER_TARGET_OPTIONS OptonsRender = static_cast<D2D1_COMPATIBLE_RENDER_TARGET_OPTIONS>(Param_Opcoes); ID2D1BitmapRenderTarget* pOutRenderTarget = NULL; //Converte as estruturas. pSizeF = Util.ConverterD2D1_SIZE_FManagedToUnmanaged(Param_DesiredSize); pSizeU = Util.ConverterD2D1_SIZE_UManagedToUnmanaged(Param_DesiredPixelSize); pPixelFormat = Util.ConverterD2D1_PIXEL_FORMATManagedToUnmanaged(DesiredFormat); //Chama o método para realizar a operação. Hr = PonteiroTrabalho->CreateCompatibleRenderTarget(*pSizeF, *pSizeU, *pPixelFormat, &pOutRenderTarget); //Processa o resultado da chamada. Resultado.ProcessarCodigoOperacao(Hr); //Verifica se obteve sucesso na operação. if (!Sucesso(static_cast<HRESULT>(Resultado.HResult))) { //Falhou ao realizar a operação. //Define o código na classe. Var_Glob_LAST_HRESULT = Hr; //Sai do método Sair; } //Define o ponteiro da interface inicializada pelo usuário. Libera a interface nativa em caso de erro. SairOnError(DefinirPonteiroInterface(pOutRenderTarget, Param_Out_BitmapRenderTarget, true)); Done:; //Libera a memória para as estruturas. DeletarEstruturaSafe(&pSizeF); DeletarEstruturaSafe(&pSizeU); DeletarEstruturaSafe(&pPixelFormat); //Retorna o resultado. return Resultado; } /// <summary> /// Cria um novo alvo de renderização bitmap para uso durante o desenho offscreen intermediário que é compatível com o alvo de renderização atual e tem o mesmo tamanho, DPI e formato de pixel /// (mas não o modo alfa) como o alvo de renderização atual. /// O alvo de renderização bitmap criado por este método não é compatível com o GDI, e tem um modo alfa de D2D1_ALPHA_MODE_PREMULTIPLIED. /// </summary> /// <param name="Param_Out_BitmapRenderTarget">Retorna a interface (ICarenD2D1BitmapRenderTarget) que contém um ponteiro para um novo alvo de renderização bitmap. O usuário deve inicializar a interface antes de chamar este método.</param> CarenResult CarenD2D1DCRenderTarget::CreateCompatibleRenderTarget(ICaren^ Param_Out_BitmapRenderTarget) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. ID2D1BitmapRenderTarget* pOutRenderTarget = NULL; //Chama o método para realizar a operação. PonteiroTrabalho->CreateCompatibleRenderTarget(&pOutRenderTarget); //Processa o resultado da chamada. Resultado.ProcessarCodigoOperacao(Hr); //Verifica se obteve sucesso na operação. if (!Sucesso(static_cast<HRESULT>(Resultado.HResult))) { //Falhou ao realizar a operação. //Define o código na classe. Var_Glob_LAST_HRESULT = Hr; //Sai do método Sair; } //Define o ponteiro da interface inicializada pelo usuário. Libera a interface nativa em caso de erro. SairOnError(DefinirPonteiroInterface(pOutRenderTarget, Param_Out_BitmapRenderTarget, true)); Done:; //Retorna o resultado. return Resultado; } /// <summary> /// Cria um alvo de renderização bitmap para uso durante o desenho offscreen intermediário compatível com o alvo de renderização atual. /// O alvo de renderização bitmap criado por este método não é compatível com o GDI. /// </summary> /// <param name="Param_DesiredSize">O tamanho desejado do novo destino de renderização em pixels independentes do dispositivo. O tamanho do pixel é calculado a partir do tamanho desejado usando o DPI pai de destino. /// Se o tamanho desejado for mapeado para um tamanho de pixel inteiro, o DPI do destino de renderização compatível será o mesmo que o DPI pai do destino. Se o Tamanho desejado é mapeado para um tamanho de pixel /// fracionário, o tamanho do pixel é arredondado para o número inteiro mais próximo e o DPI para o destino de renderização compatível é um pouco maior que o DPI do destino de renderização pai. Em todos os casos, /// a coordenada (Param_DesiredSize.width, Param_DesiredSize.height) é mapeada para o canto inferior direito do destino de renderização compatível.</param> /// <param name="Param_Out_BitmapRenderTarget">Retorna a interface (ICarenD2D1BitmapRenderTarget) que contém um ponteiro para um novo alvo de renderização bitmap. O usuário deve inicializar a interface antes de chamar este método.</param> CarenResult CarenD2D1DCRenderTarget::CreateCompatibleRenderTarget( CA_D2D1_SIZE_F^ Param_DesiredSize, ICaren^ Param_Out_BitmapRenderTarget) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. Utilidades Util; D2D1_SIZE_F* pSizeF = NULL; ID2D1BitmapRenderTarget* pOutRenderTarget = NULL; //Converte a estrutura. pSizeF = Util.ConverterD2D1_SIZE_FManagedToUnmanaged(Param_DesiredSize); //Chama o método para realizar a operação. Hr = PonteiroTrabalho->CreateCompatibleRenderTarget(*pSizeF, &pOutRenderTarget); //Processa o resultado da chamada. Resultado.ProcessarCodigoOperacao(Hr); //Verifica se obteve sucesso na operação. if (!Sucesso(static_cast<HRESULT>(Resultado.HResult))) { //Falhou ao realizar a operação. //Define o código na classe. Var_Glob_LAST_HRESULT = Hr; //Sai do método Sair; } //Define o ponteiro da interface inicializada pelo usuário. Libera a interface nativa em caso de erro. SairOnError(DefinirPonteiroInterface(pOutRenderTarget, Param_Out_BitmapRenderTarget)); Done:; //Libera a memória para as estruturas. DeletarEstruturaSafe(&pSizeF); //Retorna o resultado. return Resultado; } /// <summary> /// Cria um alvo de renderização bitmap para uso durante o desenho offscreen intermediário compatível com o alvo de renderização atual. /// </summary> /// <param name="Param_DesiredSize">O tamanho desejado do novo alvo de renderização (em pixels independentes do dispositivo), se ele deve ser diferente do alvo de renderização original.</param> /// <param name="Param_DesiredPixelSize">O tamanho desejado do novo alvo de renderização em pixels se ele deve ser diferente do alvo de renderização original.</param> /// <param name="Param_Out_BitmapRenderTarget">Retorna a interface (ICarenD2D1BitmapRenderTarget) que contém um ponteiro para um novo alvo de renderização bitmap. O usuário deve inicializar a interface antes de chamar este método.</param> CarenResult CarenD2D1DCRenderTarget::CreateCompatibleRenderTarget( CA_D2D1_SIZE_F^ Param_DesiredSize, CA_D2D1_SIZE_U^ Param_DesiredPixelSize, ICaren^ Param_Out_BitmapRenderTarget) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. Utilidades Util; D2D1_SIZE_F* pSizeF = NULL; D2D1_SIZE_U* pSizeU = NULL; ID2D1BitmapRenderTarget* pOutRenderTarget = NULL; //Converte as estruturas. pSizeF = Util.ConverterD2D1_SIZE_FManagedToUnmanaged(Param_DesiredSize); pSizeU = Util.ConverterD2D1_SIZE_UManagedToUnmanaged(Param_DesiredPixelSize); //Chama o método para realizar a operação. Hr = PonteiroTrabalho->CreateCompatibleRenderTarget(*pSizeF, *pSizeU, &pOutRenderTarget); //Processa o resultado da chamada. Resultado.ProcessarCodigoOperacao(Hr); //Verifica se obteve sucesso na operação. if (!Sucesso(static_cast<HRESULT>(Resultado.HResult))) { //Falhou ao realizar a operação. //Define o código na classe. Var_Glob_LAST_HRESULT = Hr; //Sai do método Sair; } //Define o ponteiro da interface inicializada pelo usuário. Libera a interface nativa em caso de erro. SairOnError(DefinirPonteiroInterface(pOutRenderTarget, Param_Out_BitmapRenderTarget)); Done:; //Libera a memória para as estruturas. DeletarEstruturaSafe(&pSizeF); DeletarEstruturaSafe(&pSizeU); //Retorna o resultado. return Resultado; } /// <summary> /// Cria um alvo de renderização bitmap para uso durante o desenho offscreen intermediário compatível com o alvo de renderização atual. /// </summary> /// <param name="Param_DesiredSize">O tamanho desejado do novo alvo de renderização (em pixels independentes do dispositivo), se ele deve ser diferente do alvo de renderização original.</param> /// <param name="Param_DesiredPixelSize">O tamanho desejado do novo alvo de renderização em pixels se ele deve ser diferente do alvo de renderização original.</param> /// <param name="DesiredFormat">O formato de pixel desejado e o modo alfa do novo alvo de renderização. Se o formato do pixel for definido para DXGI_FORMAT_UNKNOWN, o novo alvo de renderização usará o mesmo formato de pixel que o alvo original da renderização. Se o modo alfa estiver D2D1_ALPHA_MODE_UNKNOWN,o modo alfa do novo destino renderizante padrão para D2D1_ALPHA_MODE_PREMULTIPLIED.</param> /// <param name="Param_Out_BitmapRenderTarget">Retorna a interface (ICarenD2D1BitmapRenderTarget) que contém um ponteiro para um novo alvo de renderização bitmap. O usuário deve inicializar a interface antes de chamar este método.</param> CarenResult CarenD2D1DCRenderTarget::CreateCompatibleRenderTarget( CA_D2D1_SIZE_F^ Param_DesiredSize, CA_D2D1_SIZE_U^ Param_DesiredPixelSize, CA_D2D1_PIXEL_FORMAT^ DesiredFormat, ICaren^ Param_Out_BitmapRenderTarget) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. Utilidades Util; D2D1_SIZE_F* pSizeF = NULL; D2D1_SIZE_U* pSizeU = NULL; D2D1_PIXEL_FORMAT* pPixelFormat = NULL; ID2D1BitmapRenderTarget* pOutRenderTarget = NULL; //Converte as estruturas. pSizeF = Util.ConverterD2D1_SIZE_FManagedToUnmanaged(Param_DesiredSize); pSizeU = Util.ConverterD2D1_SIZE_UManagedToUnmanaged(Param_DesiredPixelSize); pPixelFormat = Util.ConverterD2D1_PIXEL_FORMATManagedToUnmanaged(DesiredFormat); //Chama o método para realizar a operação. Hr = PonteiroTrabalho->CreateCompatibleRenderTarget(*pSizeF, *pSizeU, *pPixelFormat, &pOutRenderTarget); //Processa o resultado da chamada. Resultado.ProcessarCodigoOperacao(Hr); //Verifica se obteve sucesso na operação. if (!Sucesso(static_cast<HRESULT>(Resultado.HResult))) { //Falhou ao realizar a operação. //Define o código na classe. Var_Glob_LAST_HRESULT = Hr; //Sai do método Sair; } //Define o ponteiro da interface inicializada pelo usuário. Libera a interface nativa em caso de erro. SairOnError(DefinirPonteiroInterface(pOutRenderTarget, Param_Out_BitmapRenderTarget)); Done:; //Libera a memória para as estruturas. DeletarEstruturaSafe(&pSizeF); DeletarEstruturaSafe(&pSizeU); DeletarEstruturaSafe(&pPixelFormat); //Retorna o resultado. return Resultado; } /// <summary> /// Cria uma interface de coleção ICarenD2D1GradientStop a partir do conjunto especificado de estruturas CA_D2D1_GRADIENT_STOP. /// </summary> /// <param name="Param_MatrizGraientStops">Uma matriz de estruturas CA_D2D1_GRADIENT_STOP.</param> /// <param name="Param_QuantidadeGradientes">Um valor maior ou igual a 1 que especifica o número de estruturas(CA_D2D1_GRADIENT_STOP) na matriz (Param_MatrizGraientStops).</param> /// <param name="Param_ColorInterpolationGamma">O espaço em que a interpolação de cores entre as paradas gradientes é realizada.</param> /// <param name="Param_ModoExtendido">O comportamento do gradiente fora da faixa [0,1] normalizada.</param> /// <param name="Param_Out_GradientStopCollection">Retorna a interface ICarenD2D1GradientStopCollection que contém um ponteiro para a nova GradientStopCollection.</param> CarenResult CarenD2D1DCRenderTarget::CreateGradientStopCollection( cli::array<CA_D2D1_GRADIENT_STOP^>^ Param_MatrizGraientStops, UInt32 Param_QuantidadeGradientes, CA_D2D1_GAMMA Param_ColorInterpolationGamma, CA_D2D1_EXTEND_MODE Param_ModoExtendido, [Out] ICarenD2D1GradientStopCollection^% Param_Out_GradientStopCollection) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. D2D1_GRADIENT_STOP* pMatrizGradientes = CriarMatrizEstruturas<D2D1_GRADIENT_STOP>(Param_QuantidadeGradientes); D2D1_GAMMA Gamma = static_cast<D2D1_GAMMA>(Param_ColorInterpolationGamma); D2D1_EXTEND_MODE ExtendMode = static_cast<D2D1_EXTEND_MODE>(Param_ModoExtendido); ID2D1GradientStopCollection* pOutGradientCollection = NULL; //Copia os dados da matriz gerenciada para a nativa. for (UInt32 i = 0; i < Param_QuantidadeGradientes; i++) { //Inicializa a estrutura no index especifico. ZeroMemory(&pMatrizGradientes[i], sizeof(D2D1_GRADIENT_STOP)); //Define os dados. pMatrizGradientes[i].position = Param_MatrizGraientStops[i]->position; //Define os dados ARGB. pMatrizGradientes->color.a = Param_MatrizGraientStops[i]->color->a; pMatrizGradientes->color.r = Param_MatrizGraientStops[i]->color->r; pMatrizGradientes->color.g = Param_MatrizGraientStops[i]->color->g; pMatrizGradientes->color.b = Param_MatrizGraientStops[i]->color->b; } //Chama o método para realizar a operação. Hr = PonteiroTrabalho->CreateGradientStopCollection(pMatrizGradientes, Param_QuantidadeGradientes, Gamma, ExtendMode, &pOutGradientCollection); //Processa o resultado da chamada. Resultado.ProcessarCodigoOperacao(Hr); //Verifica se obteve sucesso na operação. if (!Sucesso(static_cast<HRESULT>(Resultado.HResult))) { //Falhou ao realizar a operação. //Define o código na classe. Var_Glob_LAST_HRESULT = Hr; //Sai do método Sair; } //Cria a interface de saida. Param_Out_GradientStopCollection = gcnew CarenD2D1GradientStopCollection(); //Define o ponteiro da interface. Libera a interface nativa em caso de erro. SairOnError(DefinirPonteiroInterface(pOutGradientCollection, Param_Out_GradientStopCollection)); Done:; //Libera a memória para a matriz de estruturas. DeletarMatrizEstruturasSafe(&pMatrizGradientes); //Retorna o resultado. return Resultado; } /// <summary> /// Cria uma interface de coleção ICarenD2D1GradientStop a partir das estruturas GradientStops especificadas que usa o gama de interpolação de cores D2D1_GAMMA_2_2 e o modo de extensão do Clamp. /// </summary> /// <param name="Param_MatrizGraientStops">Uma matriz de estruturas CA_D2D1_GRADIENT_STOP.</param> /// <param name="Param_QuantidadeGradientes">Um valor maior ou igual a 1 que especifica o número de estruturas(CA_D2D1_GRADIENT_STOP) na matriz (Param_MatrizGraientStops).</param> /// <param name="Param_Out_GradientStopCollection">Retorna a interface ICarenD2D1GradientStopCollection que contém um ponteiro para a nova GradientStopCollection.</param> CarenResult CarenD2D1DCRenderTarget::CreateGradientStopCollection( cli::array<CA_D2D1_GRADIENT_STOP^>^ Param_MatrizGraientStops, UInt32 Param_QuantidadeGradientes, [Out] ICarenD2D1GradientStopCollection^% Param_Out_GradientStopCollection) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. Utilidades Util; D2D1_GRADIENT_STOP* pMatrizGradientes = CriarMatrizEstruturas<D2D1_GRADIENT_STOP>(Param_QuantidadeGradientes); ID2D1GradientStopCollection* pOutGradientCollection = NULL; //Copia os dados da matriz gerenciada para a nativa. for (UInt32 i = 0; i < Param_QuantidadeGradientes; i++) { //Inicializa a estrutura no index especifico. ZeroMemory(&pMatrizGradientes[i], sizeof(D2D1_GRADIENT_STOP)); //Define os dados. pMatrizGradientes[i].position = Param_MatrizGraientStops[i]->position; //Define os dados ARGB. pMatrizGradientes->color.a = Param_MatrizGraientStops[i]->color->a; pMatrizGradientes->color.r = Param_MatrizGraientStops[i]->color->r; pMatrizGradientes->color.g = Param_MatrizGraientStops[i]->color->g; pMatrizGradientes->color.b = Param_MatrizGraientStops[i]->color->b; } //Chama o método para realizar a operação. Hr = PonteiroTrabalho->CreateGradientStopCollection(pMatrizGradientes, Param_QuantidadeGradientes, &pOutGradientCollection); //Processa o resultado da chamada. Resultado.ProcessarCodigoOperacao(Hr); //Verifica se obteve sucesso na operação. if (!Sucesso(static_cast<HRESULT>(Resultado.HResult))) { //Falhou ao realizar a operação. //Define o código na classe. Var_Glob_LAST_HRESULT = Hr; //Sai do método Sair; } //Cria a interface de saida. Param_Out_GradientStopCollection = gcnew CarenD2D1GradientStopCollection(); //Define o ponteiro da interface. Libera a interface nativa em caso de erro. SairOnError(DefinirPonteiroInterface(pOutGradientCollection, Param_Out_GradientStopCollection)); Done:; //Libera a memória para a matriz de estruturas. DeletarMatrizEstruturasSafe(&pMatrizGradientes); //Retorna o resultado. return Resultado; } /// <summary> /// Cria um recurso de camada que pode ser usado com este alvo de renderização e seus alvos de renderização compatíveis. /// </summary> /// <param name="Param_Size">Se (0, 0) for especificado, nenhuma loja de backup será criada por trás do recurso de camada. O recurso de camada é alocado para o tamanho mínimo quando o PushLayer é chamado.</param> /// <param name="Param_Out_Layer">Retorna a interface ICarenD2D1Layer que contém um ponteiro para a nova camada(Layer).</param> CarenResult CarenD2D1DCRenderTarget::CreateLayer( CA_D2D1_SIZE_F^ Param_Size, [Out] ICarenD2D1Layer^% Param_Out_Layer) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. Utilidades Util; D2D1_SIZE_F* pSizeF = NULL; ID2D1Layer* pOutLayer = NULL; //Converte a estrutura. pSizeF = Util.ConverterD2D1_SIZE_FManagedToUnmanaged(Param_Size); //Chama o método para realizar a operação. Hr = PonteiroTrabalho->CreateLayer(pSizeF, &pOutLayer); //Processa o resultado da chamada. Resultado.ProcessarCodigoOperacao(Hr); //Verifica se obteve sucesso na operação. if (!Sucesso(static_cast<HRESULT>(Resultado.HResult))) { //Falhou ao realizar a operação. //Define o código na classe. Var_Glob_LAST_HRESULT = Hr; //Sai do método Sair; } //Cria a interface de saida. Param_Out_Layer = gcnew CarenD2D1Layer(); //Define o ponteiro da interface. Libera a interface nativa em caso de erro. SairOnError(DefinirPonteiroInterface(pOutLayer, Param_Out_Layer)); Done:; //Libera a memória para a estrutura. DeletarEstruturaSafe(&pSizeF); //Retorna o resultado. return Resultado; } /// <summary> /// Cria um recurso de camada que pode ser usado com este alvo de renderização e seus alvos de renderização compatíveis. /// </summary> /// <param name="Param_Out_Layer">Retorna a interface ICarenD2D1Layer que contém um ponteiro para a nova camada(Layer).</param> CarenResult CarenD2D1DCRenderTarget::CreateLayer([Out] ICarenD2D1Layer^% Param_Out_Layer) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. ID2D1Layer* pOutLayer = NULL; //Chama o método para realizar a operação. Hr = PonteiroTrabalho->CreateLayer(&pOutLayer); //Processa o resultado da chamada. Resultado.ProcessarCodigoOperacao(Hr); //Verifica se obteve sucesso na operação. if (!Sucesso(static_cast<HRESULT>(Resultado.HResult))) { //Falhou ao realizar a operação. //Define o código na classe. Var_Glob_LAST_HRESULT = Hr; //Sai do método Sair; } //Cria a interface de saida. Param_Out_Layer = gcnew CarenD2D1Layer(); //Define o ponteiro da interface. Libera a interface nativa em caso de erro. SairOnError(DefinirPonteiroInterface(pOutLayer, Param_Out_Layer)); Done:; //Retorna o resultado. return Resultado; } /// <summary> /// Cria um ICarenD2D1LinearGradientBrush que contém as GradientStops especificadas e tem a opacidade de transformação e base especificada. /// </summary> /// <param name="Param_PropriedadesLinerarGradientBrush">Os pontos de partida e fim do gradiente.</param> /// <param name="Param_PropriedadesBrush">A opacidade de transformação e base do novo pincel.</param> /// <param name="Param_GradientStopCollection">Uma interface que contém uma coleção de estruturas D2D1_GRADIENT_STOP que descrevem as cores no Brush Gradient e suas localizações ao longo da linha gradiente.</param> /// <param name="Param_Out_LinearGradientBrush">Retorna uma interface ICarenD2D1LinearGradientBrush que contém um ponteiro para o novo Pincel(Brush).</param> CarenResult CarenD2D1DCRenderTarget::CreateLinearGradientBrush( CA_D2D1_LINEAR_GRADIENT_BRUSH_PROPERTIES^ Param_PropriedadesLinerarGradientBrush, CA_D2D1_BRUSH_PROPERTIES^ Param_PropriedadesBrush, ICarenD2D1GradientStopCollection^ Param_GradientStopCollection, [Out] ICarenD2D1LinearGradientBrush^% Param_Out_LinearGradientBrush) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. Utilidades Util; D2D1_LINEAR_GRADIENT_BRUSH_PROPERTIES* pLinearGradientProps = NULL; D2D1_BRUSH_PROPERTIES* pBrushProps = NULL; ID2D1GradientStopCollection* pGradientStopCollection = NULL; ID2D1LinearGradientBrush* pOutLinearGradientBrush = NULL; //Converte as estruturas. pLinearGradientProps = Util.ConverterD2D1_LINEAR_GRADIENT_BRUSH_PROPERTIESManagedToUnmanaged(Param_PropriedadesLinerarGradientBrush); pBrushProps = Util.ConverterD2D1_BRUSH_PROPERTIESManagedToUnmanaged(Param_PropriedadesBrush); //Recupera o ponteiro para a coleção de gradientes. Resultado = RecuperarPonteiroCaren(Param_GradientStopCollection, &pGradientStopCollection); //Sai do método em caso de erro SairOnError(Resultado); //Chama o método para realizar a operação. Hr = PonteiroTrabalho->CreateLinearGradientBrush(pLinearGradientProps, pBrushProps, pGradientStopCollection, &pOutLinearGradientBrush); //Processa o resultado da chamada. Resultado.ProcessarCodigoOperacao(Hr); //Verifica se obteve sucesso na operação. if (!Sucesso(static_cast<HRESULT>(Resultado.HResult))) { //Falhou ao realizar a operação. //Define o código na classe. Var_Glob_LAST_HRESULT = Hr; //Sai do método Sair; } //Cria a interface de saida. Param_Out_LinearGradientBrush = gcnew CarenD2D1LinearGradientBrush(); //Define o ponteiro da interface. Libera a interface nativa em caso de erro. SairOnError(DefinirPonteiroInterface(pOutLinearGradientBrush, Param_Out_LinearGradientBrush)); Done:; //Libera a memória para as estruturas. DeletarEstruturaSafe(&pLinearGradientProps); DeletarEstruturaSafe(&pBrushProps); //Retorna o resultado. return Resultado; } /// <summary> /// Cria um ICarenD2D1LinearGradientBrush que contém os GradientStops especificados, não tem transformação e tem uma opacidade base de 1.0. /// </summary> /// <param name="Param_PropriedadesLinerarGradientBrush">Os pontos de partida e fim do gradiente.</param> /// <param name="Param_GradientStopCollection">Uma interface que contém uma coleção de estruturas D2D1_GRADIENT_STOP que descrevem as cores no Brush Gradient e suas localizações ao longo da linha gradiente.</param> /// <param name="Param_Out_LinearGradientBrush">Retorna uma interface ICarenD2D1LinearGradientBrush que contém um ponteiro para o novo Pincel(Brush).</param> CarenResult CarenD2D1DCRenderTarget::CreateLinearGradientBrush( CA_D2D1_LINEAR_GRADIENT_BRUSH_PROPERTIES^ Param_PropriedadesLinerarGradientBrush, ICarenD2D1GradientStopCollection^ Param_GradientStopCollection, [Out] ICarenD2D1LinearGradientBrush^% Param_Out_LinearGradientBrush) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. Utilidades Util; D2D1_LINEAR_GRADIENT_BRUSH_PROPERTIES* pLinearGradientProps = NULL; ID2D1GradientStopCollection* pGradientStopCollection = NULL; ID2D1LinearGradientBrush* pOutLinearGradientBrush = NULL; //Converte a estrutura. pLinearGradientProps = Util.ConverterD2D1_LINEAR_GRADIENT_BRUSH_PROPERTIESManagedToUnmanaged(Param_PropriedadesLinerarGradientBrush); //Recupera o ponteiro para a coleção de gradientes. Resultado = RecuperarPonteiroCaren(Param_GradientStopCollection, &pGradientStopCollection); //Sai do método em caso de erro SairOnError(Resultado); //Chama o método para realizar a operação. Hr = PonteiroTrabalho->CreateLinearGradientBrush(*pLinearGradientProps, pGradientStopCollection, &pOutLinearGradientBrush); //Processa o resultado da chamada. Resultado.ProcessarCodigoOperacao(Hr); //Verifica se obteve sucesso na operação. if (!Sucesso(static_cast<HRESULT>(Resultado.HResult))) { //Falhou ao realizar a operação. //Define o código na classe. Var_Glob_LAST_HRESULT = Hr; //Sai do método Sair; } //Cria a interface de saida. Param_Out_LinearGradientBrush = gcnew CarenD2D1LinearGradientBrush(); //Define o ponteiro da interface. Libera a interface nativa em caso de erro. SairOnError(DefinirPonteiroInterface(pOutLinearGradientBrush, Param_Out_LinearGradientBrush)); Done:; //Libera a memória para as estruturas. DeletarEstruturaSafe(&pLinearGradientProps); //Retorna o resultado. return Resultado; } /// <summary> /// Crie uma malha(Mesh) que usa triângulos para descrever uma forma. /// </summary> /// <param name="Param_Out_Mesh">Retorna uma interface ICarenD2D1Mesh que contém um ponteiro para a nova malha(Mesh).</param> CarenResult CarenD2D1DCRenderTarget::CreateMesh([Out] ICarenD2D1Mesh^% Param_Out_Mesh) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. ID2D1Mesh* pOutMesh = NULL; //Chama o método para realizar a operação. Hr = PonteiroTrabalho->CreateMesh(&pOutMesh); //Processa o resultado da chamada. Resultado.ProcessarCodigoOperacao(Hr); //Verifica se obteve sucesso na operação. if (!Sucesso(static_cast<HRESULT>(Resultado.HResult))) { //Falhou ao realizar a operação. //Define o código na classe. Var_Glob_LAST_HRESULT = Hr; //Sai do método Sair; } //Cria a interface de saida. Param_Out_Mesh = gcnew CarenD2D1Mesh(); //Define o ponteiro da interface. Libera a interface nativa em caso de erro. SairOnError(DefinirPonteiroInterface(pOutMesh, Param_Out_Mesh)); Done:; //Retorna o resultado. return Resultado; } /// <summary> /// Cria um ICarenD2D1RadialGradientBrush que contém os GradientStops especificados e tem a opacidade de transformação e base especificada. /// </summary> /// <param name="Param_PropriedadesRadialGradientBrush">O centro, a origem gradiente compensada, e raio x e raio y do gradiente do Brush.</param> /// <param name="Param_PropriedadesBrush">A opacidade de transformação e base do novo pincel(Brush).</param> /// <param name="Param_GradientStopCollection">Uma interface que contém uma coleção de estruturas D2D1_GRADIENT_STOP que descrevem as cores no Brush Gradient e suas localizações ao longo do gradiente.</param> /// <param name="Param_Out_RadialGradientBrush">Retorna uma interface ICarenD2D1RadialGradientBrush que contém um ponteiro para o novo Pincel(Brush).</param> CarenResult CarenD2D1DCRenderTarget::CreateRadialGradientBrush( CA_D2D1_RADIAL_GRADIENT_BRUSH_PROPERTIES^ Param_PropriedadesRadialGradientBrush, CA_D2D1_BRUSH_PROPERTIES^ Param_PropriedadesBrush, ICarenD2D1GradientStopCollection^ Param_GradientStopCollection, [Out] ICarenD2D1RadialGradientBrush^% Param_Out_RadialGradientBrush) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. Utilidades Util; D2D1_RADIAL_GRADIENT_BRUSH_PROPERTIES* pRadialGradientProps = NULL; D2D1_BRUSH_PROPERTIES* pBrushProps = NULL; ID2D1GradientStopCollection* pGradientStopCollection = NULL; ID2D1RadialGradientBrush* pOutRadialGradientBrush = NULL; //Converte as estruturas. pRadialGradientProps = Util.ConverterD2D1_RADIAL_GRADIENT_BRUSH_PROPERTIESManagedToUnmanaged(Param_PropriedadesRadialGradientBrush); pBrushProps = Util.ConverterD2D1_BRUSH_PROPERTIESManagedToUnmanaged(Param_PropriedadesBrush); //Recupera o ponteiro para a coleção de gradientes. Resultado = RecuperarPonteiroCaren(Param_GradientStopCollection, &pGradientStopCollection); //Sai do método em caso de erro SairOnError(Resultado); //Chama o método para realizar a operação. Hr = PonteiroTrabalho->CreateRadialGradientBrush(pRadialGradientProps, pBrushProps, pGradientStopCollection, &pOutRadialGradientBrush); //Processa o resultado da chamada. Resultado.ProcessarCodigoOperacao(Hr); //Verifica se obteve sucesso na operação. if (!Sucesso(static_cast<HRESULT>(Resultado.HResult))) { //Falhou ao realizar a operação. //Define o código na classe. Var_Glob_LAST_HRESULT = Hr; //Sai do método Sair; } //Cria a interface de saida. Param_Out_RadialGradientBrush = gcnew CarenD2D1RadialGradientBrush(); //Define o ponteiro da interface. Libera a interface nativa em caso de erro. SairOnError(DefinirPonteiroInterface(pOutRadialGradientBrush, Param_Out_RadialGradientBrush)); Done:; //Libera a memória para as estruturas. DeletarEstruturaSafe(&pRadialGradientProps); DeletarEstruturaSafe(&pBrushProps); //Retorna o resultado. return Resultado; } /// <summary> /// Cria um ICarenD2D1RadialGradientBrush que contém os GradientStops especificados, não tem transformação e tem uma opacidade base de 1.0. /// </summary> /// <param name="Param_PropriedadesRadialGradientBrush">O centro, a origem gradiente compensada, e raio x e raio y do gradiente do Brush.</param> /// <param name="Param_GradientStopCollection">Uma interface que contém uma coleção de estruturas D2D1_GRADIENT_STOP que descrevem as cores no Brush Gradient e suas localizações ao longo do gradiente.</param> /// <param name="Param_Out_RadialGradientBrush">Retorna uma interface ICarenD2D1RadialGradientBrush que contém um ponteiro para o novo Pincel(Brush).</param> CarenResult CarenD2D1DCRenderTarget::CreateRadialGradientBrush( CA_D2D1_RADIAL_GRADIENT_BRUSH_PROPERTIES^ Param_PropriedadesRadialGradientBrush, ICarenD2D1GradientStopCollection^ Param_GradientStopCollection, [Out] ICarenD2D1RadialGradientBrush^% Param_Out_RadialGradientBrush) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. Utilidades Util; D2D1_RADIAL_GRADIENT_BRUSH_PROPERTIES* pRadialGradientProps = NULL; ID2D1GradientStopCollection* pGradientStopCollection = NULL; ID2D1RadialGradientBrush* pOutRadialGradientBrush = NULL; //Converte a estrutura. pRadialGradientProps = Util.ConverterD2D1_RADIAL_GRADIENT_BRUSH_PROPERTIESManagedToUnmanaged(Param_PropriedadesRadialGradientBrush); //Recupera o ponteiro para a coleção de gradientes. Resultado = RecuperarPonteiroCaren(Param_GradientStopCollection, &pGradientStopCollection); //Sai do método em caso de erro SairOnError(Resultado); //Chama o método para realizar a operação. Hr = PonteiroTrabalho->CreateRadialGradientBrush(*pRadialGradientProps, pGradientStopCollection, &pOutRadialGradientBrush); //Processa o resultado da chamada. Resultado.ProcessarCodigoOperacao(Hr); //Verifica se obteve sucesso na operação. if (!Sucesso(static_cast<HRESULT>(Resultado.HResult))) { //Falhou ao realizar a operação. //Define o código na classe. Var_Glob_LAST_HRESULT = Hr; //Sai do método Sair; } //Cria a interface de saida. Param_Out_RadialGradientBrush = gcnew CarenD2D1RadialGradientBrush(); //Define o ponteiro da interface. Libera a interface nativa em caso de erro. SairOnError(DefinirPonteiroInterface(pOutRadialGradientBrush, Param_Out_RadialGradientBrush)); Done:; //Retorna o resultado. return Resultado; } /// <summary> /// Cria um ICarenD2D1Bitmap cujos dados são compartilhados com outro recurso. /// </summary> /// <param name="Param_Riid">O ID de interface do objeto que fornece os dados de origem.</param> /// <param name="Param_InterfaceDados">Uma ICarenD2D1Bitmap, ICarenDXGISurface ou uma ICarenWICBitmapLock que contém os dados para compartilhar com o novo ICarenD2D1Bitmap. </param> /// <param name="Param_PropriedadesBitmap">O formato de pixel e DPI do bitmap para criar. A DXGI_FORMAT parte do formato pixel deve corresponder à DXGI_FORMAT de dados ou o método falhará, mas os modos alfa /// não precisam coincidir. Para evitar uma incompatibilidade, você pode passar NULO ou o valor obtido da função auxiliar D2D1::PixelFormat. As configurações de DPI não têm que coincidir com as dos dados. /// Se o dpiX e o dpiY forem 0,0f, o DPI do alvo de renderização será usado.</param> /// <param name="Param_Out_Bitmap">Retorna uma interface ICarenD2D1Bitmap que contém um ponteiro para o novo bitmap.</param> CarenResult CarenD2D1DCRenderTarget::CreateSharedBitmap( String^ Param_Riid, ICaren^ Param_InterfaceDados, CA_D2D1_BITMAP_PROPERTIES^ Param_PropriedadesBitmap, [Out] ICarenD2D1Bitmap^% Param_Out_Bitmap) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. Utilidades Util; GUID Riid = GUID_NULL; PVOID pInterfaceDados = NULL; D2D1_BITMAP_PROPERTIES* pBitmapProps = NULL; //Poder ser NULO. ID2D1Bitmap* pOutBitmap = NULL; //Cria e converte os dados necessários. Riid = Util.CreateGuidFromString(Param_Riid); pBitmapProps = ObjetoGerenciadoValido(Param_PropriedadesBitmap) ? Util.ConverterD2D1_BITMAP_PROPERTIESManagedToUnmanaged(Param_PropriedadesBitmap) : NULL; //Recupera o ponteiro para a interface de dados. Resultado = RecuperarPonteiroCaren(Param_InterfaceDados, &pInterfaceDados); //Sai do método em caso de erro. SairOnError(Resultado); //Chama o método para realizar a operação. Hr = PonteiroTrabalho->CreateSharedBitmap(Riid, pInterfaceDados, pBitmapProps, &pOutBitmap); //Processa o resultado da chamada. Resultado.ProcessarCodigoOperacao(Hr); //Verifica se obteve sucesso na operação. if (!Sucesso(static_cast<HRESULT>(Resultado.HResult))) { //Falhou ao realizar a operação. //Define o código na classe. Var_Glob_LAST_HRESULT = Hr; //Sai do método Sair; } //Cria a interface de saida. Param_Out_Bitmap = gcnew CarenD2D1Bitmap(); //Define o ponteiro da interface. Libera a interface nativa em caso de erro. SairOnError(DefinirPonteiroInterface(pOutBitmap, Param_Out_Bitmap)); Done:; //Libera a memória para a estrutura. DeletarEstruturaSafe(&pBitmapProps); //Retorna o resultado. return Resultado; } /// <summary> /// Cria um novo ICarenD2D1SolidColorBrush que tem a cor e a opacidade especificados. /// </summary> /// <param name="Param_Cor">Os valores vermelho, verde, azul e alfa da cor do pincel.</param> /// <param name="Param_PropriedadesBrush">A opacidade base do pincel.</param> /// <param name="Param_Out_SolidColorBrush">Retorna uma interface ICarenD2D1Bitmap que contém um ponteiro para o novo pincel(Brush).</param> CarenResult CarenD2D1DCRenderTarget::CreateSolidColorBrush( CA_D2D1_COLOR_F^ Param_Cor, CA_D2D1_BRUSH_PROPERTIES^ Param_PropriedadesBrush, [Out] ICarenD2D1SolidColorBrush^% Param_Out_SolidColorBrush) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. Utilidades Util; D2D1_COLOR_F* pColorF = NULL; D2D1_BRUSH_PROPERTIES* pBrushProps = NULL; ID2D1SolidColorBrush* pOutSolidColorBrush = NULL; //Converte as estruturas. pColorF = Util.ConverterD2D1_COLOR_FManagedToUnmanaged(Param_Cor); pBrushProps = Util.ConverterD2D1_BRUSH_PROPERTIESManagedToUnmanaged(Param_PropriedadesBrush); //Chama o método para realizar a operação. Hr = PonteiroTrabalho->CreateSolidColorBrush(pColorF, pBrushProps, &pOutSolidColorBrush); //Processa o resultado da chamada. Resultado.ProcessarCodigoOperacao(Hr); //Verifica se obteve sucesso na operação. if (!Sucesso(static_cast<HRESULT>(Resultado.HResult))) { //Falhou ao realizar a operação. //Define o código na classe. Var_Glob_LAST_HRESULT = Hr; //Sai do método Sair; } //Cria a interface de saida. Param_Out_SolidColorBrush = gcnew CarenD2D1SolidColorBrush(); //Define o ponteiro da interface. Libera a interface nativa em caso de erro. SairOnError(DefinirPonteiroInterface(pOutSolidColorBrush, Param_Out_SolidColorBrush)); Done:; //Libera a memória para as estruturas. DeletarEstruturaSafe(&pColorF); DeletarEstruturaSafe(&pBrushProps); //Retorna o resultado. return Resultado; } /// <summary> /// Cria um novo ICarenD2D1SolidColorBrush que tem a cor especificada e uma opacidade base de 1.0f. /// </summary> /// <param name="Param_Cor">Os valores vermelho, verde, azul e alfa da cor do pincel(Brush).</param> /// <param name="Param_Out_SolidColorBrush">Retorna uma interface ICarenD2D1Bitmap que contém um ponteiro para o novo pincel(Brush).</param> CarenResult CarenD2D1DCRenderTarget::CreateSolidColorBrush( CA_D2D1_COLOR_F^ Param_Cor, [Out] ICarenD2D1SolidColorBrush^% Param_Out_SolidColorBrush) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. Utilidades Util; D2D1_COLOR_F* pColorF = NULL; ID2D1SolidColorBrush* pOutSolidColorBrush = NULL; //Converte a estrutura. pColorF = Util.ConverterD2D1_COLOR_FManagedToUnmanaged(Param_Cor); //Chama o método para realizar a operação. Hr = PonteiroTrabalho->CreateSolidColorBrush(*pColorF, &pOutSolidColorBrush); //Processa o resultado da chamada. Resultado.ProcessarCodigoOperacao(Hr); //Verifica se obteve sucesso na operação. if (!Sucesso(static_cast<HRESULT>(Resultado.HResult))) { //Falhou ao realizar a operação. //Define o código na classe. Var_Glob_LAST_HRESULT = Hr; //Sai do método Sair; } //Cria a interface de saida. Param_Out_SolidColorBrush = gcnew CarenD2D1SolidColorBrush(); //Define o ponteiro da interface. Libera a interface nativa em caso de erro. SairOnError(DefinirPonteiroInterface(pOutSolidColorBrush, Param_Out_SolidColorBrush)); Done:; //Libera a memória para as estruturas. DeletarEstruturaSafe(&pColorF); //Retorna o resultado. return Resultado; } /// <summary> /// Desenha o bitmap especificado depois de dimensioná-lo para o tamanho do retângulo especificado. /// Este método não retorna um código de erro se falhar. Para determinar se uma operação de desenho (como DrawBitmap) falhou, verifique o resultado retornado pelo ICarenD2D1RenderTarget::EndDraw /// ou ICarenD2D1RenderTarget::Flush. /// </summary> /// <param name="Param_Bitmap">O bitmap para renderizar.</param> /// <param name="Param_RetanguloDestino">O tamanho e a posição, em pixels independentes do dispositivo no espaço de coordenadas do alvo de renderização, da área para a qual o bitmap é desenhado. /// Se o retângulo não for bem ordenado, nada é desenhado, mas o alvo de renderização não entra em um estado de erro.</param> /// <param name="Param_Opacidade">Um valor entre 0,0f e 1,0f, inclusive, que especifica um valor de opacidade para aplicar ao bitmap; este valor é multiplicado em relação aos valores alfa do /// conteúdo do bitmap.</param> /// <param name="Param_InterpolationMode">O modo de interpolação a ser usado se o bitmap for dimensionado ou girado pela operação de desenho.</param> /// <param name="Param_RetanguloOrigem">O tamanho e a posição, em pixels independentes do dispositivo no espaço de coordenadas do bitmap, da área dentro do bitmap para desenhar.</param> CarenResult CarenD2D1DCRenderTarget::DrawBitmap( ICarenD2D1Bitmap^ Param_Bitmap, CA_D2D1_RECT_F^ Param_RetanguloDestino, float Param_Opacidade, CA_D2D1_BITMAP_INTERPOLATION_MODE Param_InterpolationMode, CA_D2D1_RECT_F^ Param_RetanguloOrigem) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. Utilidades Util; ID2D1Bitmap* pBitmapRender = NULL; D2D1_RECT_F* pRectDestinoF = NULL; D2D1_RECT_F* pRectOrigemF = NULL; D2D1_BITMAP_INTERPOLATION_MODE BitmapInterpolationMode = static_cast<D2D1_BITMAP_INTERPOLATION_MODE>(Param_InterpolationMode); //Recupera o ponteiro para o bitmap Resultado = RecuperarPonteiroCaren(Param_Bitmap, &pBitmapRender); //Sai do método em caso de erro SairOnError(Resultado); //Converte as estruturas. pRectDestinoF = Util.ConverterD2D1_RECT_FManagedToUnmanaged(Param_RetanguloDestino); pRectOrigemF = Util.ConverterD2D1_RECT_FManagedToUnmanaged(Param_RetanguloOrigem); //Chama o método para realizar a operação. PonteiroTrabalho->DrawBitmap(pBitmapRender, pRectDestinoF, Param_Opacidade, BitmapInterpolationMode, pRectOrigemF); //Define sucesso Resultado.AdicionarCodigo(ResultCode::SS_OK, true); Done:; //Libera a memória para as estruturas. DeletarEstruturaSafe(&pRectDestinoF); DeletarEstruturaSafe(&pRectOrigemF); //Retorna o resultado. return Resultado; } /// <summary> /// Desenha o contorno(Outline) da elipse especificada usando o estilo de traçado especificado. /// Este método não retorna um código de erro se falhar. Para determinar se uma operação de desenho (como DrawEllipse) falhou, verifique o resultado retornado pelo ICarenD2D1RenderTarget::EndDraw /// ou ICarenD2D1RenderTarget::Flush. /// </summary> /// <param name="Param_Ellipse">A posição e o raio da elipse para desenhar, em pixels independentes do dispositivo.</param> /// <param name="Param_Brush">O pincel(Brush) usado para pintar o contorno da elipse.</param> /// <param name="Param_StrokeWidth">A largura do Stroke, em pixels independentes do dispositivo. O valor deve ser maior ou igual a 0,0f. Se este parâmetro não for especificado, ele será padrão /// para 1.0f. O golpe está centrado na linha.</param> /// <param name="Param_StrokeStyle">O estilo do Stroke para aplicar ao contorno(Outline) da elipse, ou NULO para pintar um traço sólido.</param> CarenResult CarenD2D1DCRenderTarget::DrawEllipse( CA_D2D1_ELLIPSE^ Param_Ellipse, ICarenD2D1Brush^ Param_Brush, float Param_StrokeWidth, ICarenD2D1StrokeStyle^ Param_StrokeStyle) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. Utilidades Util; D2D1_ELLIPSE* pEllipse = NULL; ID2D1Brush* pBrush = NULL; ID2D1StrokeStyle* pStrokeStyle = NULL; //Pode ser NULO. //Recupera o ponteiro para o Brush. Resultado = RecuperarPonteiroCaren(Param_Brush, &pBrush); //Sai do método em caso de erro. SairOnError(Resultado); //Recupera o ponteiro para o Stroke se informado. if (ObjetoGerenciadoValido(Param_StrokeStyle)) { //Recupera o ponteiro. RecuperarPonteiroCaren(Param_StrokeStyle, &pStrokeStyle); } //Converte a estrutura. pEllipse = Util.ConverterD2D1_ELLIPSEManagedToUnmanaged(Param_Ellipse); //Chama o método para realizar a operação. PonteiroTrabalho->DrawEllipse(pEllipse, pBrush, Param_StrokeWidth, pStrokeStyle); //Define sucesso Resultado.AdicionarCodigo(ResultCode::SS_OK, true); Done:; //Libera a memória para a estrutura. DeletarEstruturaSafe(&pEllipse); //Retorna o resultado. return Resultado; } /// <summary> /// Desenha o contorno da geometria especificada usando o estilo de traçado especificado. /// Este método não retorna um código de erro se falhar. Para determinar se uma operação de desenho (como DrawGeometry) falhou, verifique o resultado retornado pelo ICarenD2D1RenderTarget::EndDraw /// ou ICarenD2D1RenderTarget::Flush. /// </summary> /// <param name="Param_Geometria">A geometria para desenhar.</param> /// <param name="Param_Brush">O pincel(Brush) para pintar o traço(Stroke) da geometria.</param> /// <param name="Param_StrokeWidth">A largura do traçado, em pixels independentes do dispositivo. O valor deve ser maior ou igual a 0,0f. Se este parâmetro não for especificado, ele será padrão /// para 1.0f. O golpe está centrado na linha.</param> /// <param name="Param_StrokeStyle">O estilo de traçado(Stroke) para aplicar ao contorno(Outline) da geometria, ou NULO para pintar um traço(Stroke) sólido.</param> CarenResult CarenD2D1DCRenderTarget::DrawGeometry( ICarenD2D1Geometry^ Param_Geometria, ICarenD2D1Brush^ Param_Brush, float Param_StrokeWidth, ICarenD2D1StrokeStyle^ Param_StrokeStyle) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. Utilidades Util; ID2D1Geometry* pGeometryRender = NULL; ID2D1Brush* pBrush = NULL; ID2D1StrokeStyle* pStrokeStyle = NULL; //Pode ser NULO. //Recupera o ponteiro para a gemetria. Resultado = RecuperarPonteiroCaren(Param_Geometria, &pGeometryRender); //Sai do método em caso de erro. SairOnError(Resultado); //Recupera o ponteiro para o Brush. Resultado = RecuperarPonteiroCaren(Param_Brush, &pBrush); //Sai do método em caso de erro. SairOnError(Resultado); //Recupera o ponteiro para o Stroke se informado. if (ObjetoGerenciadoValido(Param_StrokeStyle)) { //Recupera o ponteiro. RecuperarPonteiroCaren(Param_StrokeStyle, &pStrokeStyle); } //Chama o método para realizar a operação. PonteiroTrabalho->DrawGeometry(pGeometryRender, pBrush, Param_StrokeWidth, pStrokeStyle); //Define sucesso Resultado.AdicionarCodigo(ResultCode::SS_OK, true); Done:; //Retorna o resultado. return Resultado; } /// <summary> /// Desenha os glifos(Glyph) especificados. /// Este método não retorna um código de erro se falhar. Para determinar se uma operação de desenho (como DrawGlyphRun) falhou, verifique o resultado retornado pelo ICarenD2D1RenderTarget::EndDraw /// ou ICarenD2D1RenderTarget::Flush. /// </summary> /// <param name="Param_BaseLineOrigin">A origem, em pixels independentes de dispositivos, da linha de base dos glifos(Glyph).</param> /// <param name="Param_GlyphRun">Os glifos(Glyph) para renderizar.</param> /// <param name="Param_ForegroundBrush">O pincel(Brush) usado para pintar os glifos(Glyph) especificados.</param> /// <param name="Param_MeasuringMode">Um valor que indica como as métricas do glifo(Glyph) são usadas para medir o texto quando ele é formatado. O valor padrão é DWRITE_MEASURING_MODE_NATURAL.</param> CarenResult CarenD2D1DCRenderTarget::DrawGlyphRun( CA_D2D1_POINT_2F^ Param_BaseLineOrigin, CA_DWRITE_GLYPH_RUN^ Param_GlyphRun, ICarenD2D1Brush^ Param_ForegroundBrush, CA_DWRITE_MEASURING_MODE Param_MeasuringMode) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. Utilidades Util; D2D1_POINT_2F* pPoint = NULL; DWRITE_GLYPH_RUN* pGlyphRun = NULL; ID2D1Brush* pBrush = NULL; DWRITE_MEASURING_MODE DWriteMeasuringMode = static_cast<DWRITE_MEASURING_MODE>(Param_MeasuringMode); //Converte as estruturas. pPoint = Util.ConverterD2D1_POINT_2FManagedToUnmanaged(Param_BaseLineOrigin); pGlyphRun = Util.ConverterDWRITE_GLYPH_RUNManagedToUnmanaged(Param_GlyphRun); //Recupera o ponteiro para a interface do Brush Resultado = RecuperarPonteiroCaren(Param_ForegroundBrush, &pBrush); //Sai do método em caso de erro SairOnError(Resultado); //Chama o método para realizar a operação. PonteiroTrabalho->DrawGlyphRun(*pPoint, pGlyphRun, pBrush, DWriteMeasuringMode); //Define sucesso Resultado.AdicionarCodigo(ResultCode::SS_OK, true); Done:; //Libera a memória para as matrizes. DeletarEstruturaSafe(&pPoint); if (ObjetoValido(pGlyphRun)) { //Libera as matrizes internas da estrutura. DeletarMatrizUnidimensionalSafe(&pGlyphRun->glyphIndices); DeletarMatrizUnidimensionalSafe(&pGlyphRun->glyphAdvances); DeletarMatrizEstruturasSafe(&pGlyphRun->glyphOffsets); } DeletarEstruturaSafe(&pGlyphRun); //Retorna o resultado. return Resultado; } /// <summary> /// Desenha uma linha entre os pontos especificados usando o estilo de traçado especificado. /// Este método não retorna um código de erro se falhar. Para determinar se uma operação de desenho (como DrawLine) falhou, verifique o resultado retornado pelo ICarenD2D1RenderTarget::EndDraw /// ou ICarenD2D1RenderTarget::Flush. /// </summary> /// <param name="Param_Point0">O ponto de partida da linha, em pixels independentes de dispositivos.</param> /// <param name="Param_Point1">O ponto final da linha, em pixels independentes de dispositivos.</param> /// <param name="Param_Brush">O pincel(Brush) para pintar o traço da linha.</param> /// <param name="Param_StrokeWidth">A largura do Stroke, em pixels independentes do dispositivo.O valor deve ser maior ou igual a 0, 0f.Se esse parâmetro não for especificado, o padrão será 1.0f. /// O Stroke é centralizado na linha.</param> /// <param name="Param_StrokeStyle">O estilo de Stroke para pintar, ou NULO para pintar uma linha sólida.</param> CarenResult CarenD2D1DCRenderTarget::DrawLine( CA_D2D1_POINT_2F^ Param_Point0, CA_D2D1_POINT_2F^ Param_Point1, ICarenD2D1Brush^ Param_Brush, float Param_StrokeWidth, ICarenD2D1StrokeStyle^ Param_StrokeStyle) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. Utilidades Util; D2D1_POINT_2F* pPoint0 = NULL; D2D1_POINT_2F* pPoint1 = NULL; ID2D1Brush* pBrush = NULL; ID2D1StrokeStyle* pStrokeStyle = NULL; //Converte as estruturas. pPoint0 = Util.ConverterD2D1_POINT_2FManagedToUnmanaged(Param_Point0); pPoint1 = Util.ConverterD2D1_POINT_2FManagedToUnmanaged(Param_Point1); //Recupera o ponteiro para a interface do Brush Resultado = RecuperarPonteiroCaren(Param_Brush, &pBrush); //Sai do método em caso de erro SairOnError(Resultado); //Recupera o ponteiro para o Stroke se informado. if (ObjetoGerenciadoValido(Param_StrokeStyle)) { //Recupera o ponteiro. RecuperarPonteiroCaren(Param_StrokeStyle, &pStrokeStyle); } //Chama o método para realizar a operação. PonteiroTrabalho->DrawLine(*pPoint0, *pPoint1, pBrush, Param_StrokeWidth, pStrokeStyle); //Define sucesso Resultado.AdicionarCodigo(ResultCode::SS_OK, true); Done:; //Libera a memória para as estruturas. DeletarEstruturaSafe(&pPoint0); DeletarEstruturaSafe(&pPoint1); //Retorna o resultado. return Resultado; } /// <summary> /// Desenha o contorno(Outline) de um retângulo que tem as dimensões especificadas e o estilo de traçado. /// Este método não retorna um código de erro se falhar. Para determinar se uma operação de desenho (como DrawRectangle) falhou, verifique o resultado retornado pelo ICarenD2D1RenderTarget::EndDraw /// ou ICarenD2D1RenderTarget::Flush. /// </summary> /// <param name="Param_Rect">As dimensões do retângulo para desenhar, em pixels independentes do dispositivo.</param> /// <param name="Param_Brush">O pincel(Brush) usado para pintar o curso do retângulo.</param> /// <param name="Param_StrokeWidth">A largura do traçado(Stroke), em pixels independentes do dispositivo. O valor deve ser maior ou igual a 0,0f. Se esse parâmetro não for especificado, /// o padrão será 1.0f. O traço(Stroke) é centralizado na linha.</param> /// <param name="Param_StrokeStyle">O estilo do traço(Stroke) para pintar ou NULO para pintar um traçado sólido.</param> CarenResult CarenD2D1DCRenderTarget::DrawRectangle( CA_D2D1_RECT_F^ Param_Rect, ICarenD2D1Brush^ Param_Brush, float Param_StrokeWidth, ICarenD2D1StrokeStyle^ Param_StrokeStyle) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. Utilidades Util; D2D1_RECT_F* pRectF = NULL; ID2D1Brush* pBrush = NULL; ID2D1StrokeStyle* pStrokeStyle = NULL; //Converte a estrutura. pRectF = Util.ConverterD2D1_RECT_FManagedToUnmanaged(Param_Rect); //Recupera o ponteiro para a interface do Brush Resultado = RecuperarPonteiroCaren(Param_Brush, &pBrush); //Sai do método em caso de erro SairOnError(Resultado); //Recupera o ponteiro para o Stroke se informado. if (ObjetoGerenciadoValido(Param_StrokeStyle)) { //Recupera o ponteiro. RecuperarPonteiroCaren(Param_StrokeStyle, &pStrokeStyle); } //Chama o método para realizar a operação. PonteiroTrabalho->DrawRectangle(pRectF, pBrush, Param_StrokeWidth, pStrokeStyle); //Define sucesso Resultado.AdicionarCodigo(ResultCode::SS_OK, true); Done:; //Libera a memória para a estrutura. DeletarEstruturaSafe(&pRectF); //Retorna o resultado. return Resultado; } /// <summary> /// Desenha o contorno(Outline) do retângulo arredondado especificado usando o estilo de traçado especificado. /// Este método não retorna um código de erro se falhar. Para determinar se uma operação de desenho (como DrawRoundedRectangle) falhou, verifique o resultado retornado pelo ICarenD2D1RenderTarget::EndDraw /// ou ICarenD2D1RenderTarget::Flush. /// </summary> /// <param name="Param_RoundedRect">As dimensões do retângulo arredondado para desenhar, em pixels independentes do dispositivo.</param> /// <param name="Param_Brush">O pincel(Brush) usado para pintar o contorno do retângulo arredondado.</param> /// <param name="Param_StrokeWidth">A largura do traçado(Stroke), em pixels independentes do dispositivo. O valor deve ser maior ou igual a 0,0f. Se esse parâmetro não for especificado, o padrão /// será 1.0f. O traço(Stroke) é centralizado na linha.</param> /// <param name="Param_StrokeStyle">O estilo do traçado do retângulo arredondado, ou NULO para pintar um traço sólido. O valor padrão é NULO.</param> CarenResult CarenD2D1DCRenderTarget::DrawRoundedRectangle( CA_D2D1_ROUNDED_RECT^ Param_RoundedRect, ICarenD2D1Brush^ Param_Brush, float Param_StrokeWidth, ICarenD2D1StrokeStyle^ Param_StrokeStyle) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. Utilidades Util; D2D1_ROUNDED_RECT* pRoundedRect = NULL; ID2D1Brush* pBrush = NULL; ID2D1StrokeStyle* pStrokeStyle = NULL; //Converte a estrutura. pRoundedRect = Util.ConverterD2D1_ROUNDED_RECTManagedToUnmanaged(Param_RoundedRect); //Recupera o ponteiro para a interface do Brush Resultado = RecuperarPonteiroCaren(Param_Brush, &pBrush); //Sai do método em caso de erro SairOnError(Resultado); //Recupera o ponteiro para o Stroke se informado. if (ObjetoGerenciadoValido(Param_StrokeStyle)) { //Recupera o ponteiro. RecuperarPonteiroCaren(Param_StrokeStyle, &pStrokeStyle); } //Chama o método para realizar a operação. PonteiroTrabalho->DrawRoundedRectangle(pRoundedRect, pBrush, Param_StrokeWidth, pStrokeStyle); //Define sucesso Resultado.AdicionarCodigo(ResultCode::SS_OK, true); Done:; //Libera a memória para a estrutura. DeletarEstruturaSafe(&pRoundedRect); //Retorna o resultado. return Resultado; } /// <summary> /// Desenha o texto especificado usando as informações de formato fornecidas por um objeto ICarenDWriteTextFormat. /// Este método não retorna um código de erro se falhar. Para determinar se uma operação de desenho (como DrawText) falhou, verifique o resultado retornado pelo ICarenD2D1RenderTarget::EndDraw /// ou ICarenD2D1RenderTarget::Flush. /// </summary> /// <param name="Param_Texto">Uma string de caracteres Unicode para desenhar.</param> /// <param name="Param_TamanhoTexto">O número de caracteres em (Param_Texto).</param> /// <param name="Param_TextFormat">Uma interface(ICarenDWriteTextFormat) que descreve a formatação de detalhes do texto para desenhar, como a fonte, o tamanho da fonte e a direção do fluxo.</param> /// <param name="Param_LayoutRect">O tamanho e a posição da área em que o texto é desenhado.</param> /// <param name="Param_DefaultFillBrush">O pincel(Brush) usado para pintar o texto.</param> /// <param name="Param_Opcoes">Um valor que indica se o texto deve ser encaixado nos limites do pixel e se o texto deve ser cortado no retângulo de layout. O valor padrão é D2D1_DRAW_TEXT_OPTIONS_NONE, /// o que indica que o texto deve ser encaixado nos limites do pixel e não deve ser cortado para o retângulo de layout.</param> /// <param name="Param_MeasuringMode">Um valor que indica como as métricas do glifo(Glyph) são usadas para medir o texto quando ele é formatado. O valor padrão é DWRITE_MEASURING_MODE_NATURAL.</param> CarenResult CarenD2D1DCRenderTarget::DrawText( String^ Param_Texto, UInt32 Param_TamanhoTexto, ICaren^ Param_TextFormat, CA_D2D1_RECT_F^ Param_LayoutRect, ICarenD2D1Brush^ Param_DefaultFillBrush, CA_D2D1_DRAW_TEXT_OPTIONS Param_Opcoes, CA_DWRITE_MEASURING_MODE Param_MeasuringMode) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. Utilidades Util; PWCHAR pTexto = NULL; IDWriteTextFormat* pTextFormat = NULL; D2D1_RECT_F* pLayoutRectF = NULL; ID2D1Brush* pBrush = NULL; D2D1_DRAW_TEXT_OPTIONS DrawTextOptions = static_cast<D2D1_DRAW_TEXT_OPTIONS>(Param_Opcoes); DWRITE_MEASURING_MODE MeasuringMode = static_cast<DWRITE_MEASURING_MODE>(Param_MeasuringMode); //Verifica se a string é valida if (!ObjetoGerenciadoValido(Param_Texto)) throw gcnew NullReferenceException("O texto a ser desenhado não pode ser NULO!"); //Converte a string para wchar pTexto = Util.ConverterStringToWCHAR(Param_Texto); //Recupera o ponteiro para a interface de formato do texto. Resultado = RecuperarPonteiroCaren(Param_TextFormat, &pTextFormat); //Sai do método em caso de erro SairOnError(Resultado); //Recupera o ponteiro para a interface do Brush Resultado = RecuperarPonteiroCaren(Param_DefaultFillBrush, &pBrush); //Sai do método em caso de erro SairOnError(Resultado); //Converte a estrutura. pLayoutRectF = Util.ConverterD2D1_RECT_FManagedToUnmanaged(Param_LayoutRect); //Chama o método para realizar a operação. PonteiroTrabalho->DrawText(pTexto, Param_TamanhoTexto, pTextFormat, pLayoutRectF, pBrush, DrawTextOptions, MeasuringMode); //Define sucesso Resultado.AdicionarCodigo(ResultCode::SS_OK, true); Done:; //Libera a memória para os dados. DeletarStringAllocatedSafe(&pTexto); DeletarEstruturaSafe(&pLayoutRectF); //Retorna o resultado. return Resultado; } /// <summary> /// Desenha o texto formatado descrito pelo objeto ICarenDWriteTextLayout especificado. /// Ao desenhar o mesmo texto repetidamente, o uso do método DrawTextLayout é mais eficiente do que usar o método DrawText porque o texto não precisa ser formatado e o layout processado a cada chamada. /// Este método não retorna um código de erro se falhar. Para determinar se uma operação de desenho (como DrawTextLayout) falhou, verifique o resultado retornado pelo ICarenD2D1RenderTarget::EndDraw /// ou ICarenD2D1RenderTarget::Flush. /// </summary> /// <param name="Param_Origem">O ponto, descrito em pixels independentes do dispositivo, no qual o canto superior esquerdo do texto descrito pelo (Param_TextLayout) é desenhado.</param> /// <param name="Param_TextLayout">Uma interface(ICarenDWriteTextLayout) com o texto formatado para desenhar. Quaisquer efeitos de desenho que não herdem do ID2D1Resource são ignorados. Se houver /// efeitos de desenho que herdam do ICarenD2D1Resource que não são pincéis, este método falhará e o alvo de renderização é colocado em um estado de erro.</param> /// <param name="Param_DefaultFillBrush">O pincel(Brush) usado para pintar qualquer texto no (Param_TextLayout) que ainda não tenha um pincel associado a ele como efeito de desenho (especificado pelo /// método ICarenDWriteTextLayout::SetDrawingEffect).</param> /// <param name="Param_Opcoes">Um valor que indica se o texto deve ser encaixado nos limites do pixel e se o texto deve ser cortado no retângulo de layout. O valor padrão é D2D1_DRAW_TEXT_OPTIONS_NONE, /// o que indica que o texto deve ser encaixado nos limites do pixel e não deve ser cortado para o retângulo de layout.</param> CarenResult CarenD2D1DCRenderTarget::DrawTextLayout( CA_D2D1_POINT_2F^ Param_Origem, ICaren^ Param_TextLayout, ICarenD2D1Brush^ Param_DefaultFillBrush, CA_D2D1_DRAW_TEXT_OPTIONS Param_Opcoes) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Variaveis a serem utilizadas. Utilidades Util; D2D1_POINT_2F* pPointOrigem = NULL; IDWriteTextLayout* pDwriterTextLayout = NULL; ID2D1Brush* pBrush = NULL; D2D1_DRAW_TEXT_OPTIONS DrawTextOptions = static_cast<D2D1_DRAW_TEXT_OPTIONS>(Param_Opcoes); //Recupera o ponteiro para a interface de formato do texto. Resultado = RecuperarPonteiroCaren(Param_TextLayout, &pDwriterTextLayout); //Sai do método em caso de erro SairOnError(Resultado); //Recupera o ponteiro para a interface do Brush Resultado = RecuperarPonteiroCaren(Param_DefaultFillBrush, &pBrush); //Sai do método em caso de erro SairOnError(Resultado); //Converte a estrutura. pPointOrigem = Util.ConverterD2D1_POINT_2FManagedToUnmanaged(Param_Origem); //Chama o método para realizar a operação. PonteiroTrabalho->DrawTextLayout(*pPointOrigem, pDwriterTextLayout, pBrush, DrawTextOptions); //Define sucesso Resultado.AdicionarCodigo(ResultCode::SS_OK, true); Done:; //Libera a memória para a estrutura. DeletarEstruturaSafe(&pPointOrigem); //Retorna o resultado. return Resultado; } /// <summary> /// Termina as operações de desenho no alvo de renderização e indica o estado de erro atual e as tags associadas. /// </summary> /// <param name="Param_Out_Tag1">Quando este método retorna, contém a tag para operações de desenho que causaram erros ou 0 se não houver erros.</param> /// <param name="Param_Out_Tag2">Quando este método retorna, contém a tag para operações de desenho que causaram erros ou 0 se não houver erros.</param> CarenResult CarenD2D1DCRenderTarget::EndDraw( [Out] UInt64% Param_Out_Tag1, [Out] UInt64% Param_Out_Tag2) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. UINT64 OutTag1 = 0; UINT64 OutTag2 = 0; //Chama o método para realizar a operação. Hr = PonteiroTrabalho->EndDraw(&OutTag1, &OutTag2); //Processa o resultado da chamada. Resultado.ProcessarCodigoOperacao(Hr); //Verifica se obteve sucesso na operação. if (!Sucesso(static_cast<HRESULT>(Resultado.HResult))) { //Falhou ao realizar a operação. //Define o código na classe. Var_Glob_LAST_HRESULT = Hr; //Sai do método Sair; } //Define os valores nos parametros de saida. Param_Out_Tag1 = OutTag1; Param_Out_Tag2 = OutTag2; Done:; //Retorna o resultado. return Resultado; } /// <summary> /// Pinta o interior da elipse especificada. /// Este método não retorna um código de erro se falhar. Para determinar se uma operação de desenho (como FillEllipse) falhou, verifique o resultado retornado pelo ICarenD2D1RenderTarget::EndDraw /// ou ICarenD2D1RenderTarget::Flush. /// </summary> /// <param name="Param_Ellipse">A posição e o raio, em pixels independentes do dispositivo, da elipse para pintar.</param> /// <param name="Param_Brush">O pincel(Brush) usado para pintar o interior da elipse.</param> CarenResult CarenD2D1DCRenderTarget::FillEllipse( CA_D2D1_ELLIPSE^ Param_Ellipse, ICarenD2D1Brush^ Param_Brush) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Variaveis a serem utilizadas. Utilidades Util; D2D1_ELLIPSE* pEllipse = NULL; ID2D1Brush* pBrush = NULL; //Recupera o ponteiro para a interface do Brush Resultado = RecuperarPonteiroCaren(Param_Brush, &pBrush); //Sai do método em caso de erro SairOnError(Resultado); //Converte a estrutura. pEllipse = Util.ConverterD2D1_ELLIPSEManagedToUnmanaged(Param_Ellipse); //Chama o método para realizar a operação. PonteiroTrabalho->FillEllipse(pEllipse, pBrush); //Define sucesso Resultado.AdicionarCodigo(ResultCode::SS_OK, true); Done:; //Libera a memória para a estrutura. DeletarEstruturaSafe(&pEllipse); //Retorna o resultado. return Resultado; } /// <summary> /// Pinta o interior da geometria especificada. /// Se o parâmetro (Param_OpacityBrush) não for NULO, o valor alfa de cada pixel da opacidade mapeadaBrush é usado para determinar a opacidade resultante de cada pixel correspondente da geometria. /// Apenas o valor alfa de cada cor no Brush é usado para este processamento; todas as outras informações de cores são ignoradas. /// O valor alfa especificado pelo Brush é multiplicado pelo valor alfa da geometria após a geometria ter sido pintada pelo Brush. /// Este método não retorna um código de erro se falhar. Para determinar se uma operação de desenho (como FillGeometry) falhou, verifique o resultado retornado pelo ICarenD2D1RenderTarget::EndDraw /// ou ICarenD2D1RenderTarget::Flush. /// </summary> /// <param name="Param_Geometria">A geometria para pintar.</param> /// <param name="Param_Brush">O pincel(Brush) para pintar o interior da geometria.</param> /// <param name="Param_OpacityBrush">A máscara de opacidade para aplicar à geometria, ou NULO para nenhuma máscara de opacidade. Se uma máscara de opacidade (o parâmetro Param_OpacityBrush) for especificada, /// o (Param_Brush) deve ser um ICarenD2D1BitmapBrush que tem seus modos x e y-extend definidos para D2D1_EXTEND_MODE_CLAMP.</param> CarenResult CarenD2D1DCRenderTarget::FillGeometry( ICarenD2D1Geometry^ Param_Geometria, ICarenD2D1Brush^ Param_Brush, ICarenD2D1Brush^ Param_OpacityBrush) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Variaveis a serem utilizadas. ID2D1Geometry* pGeometry = NULL; ID2D1Brush* pBrush = NULL; ID2D1Brush* pOpacityBrush = NULL; //Pode ser NULO. //Recupera o ponteiro para a interface de Geometria. Resultado = RecuperarPonteiroCaren(Param_Geometria, &pGeometry); //Sai do método em caso de erro SairOnError(Resultado); //Recupera o ponteiro para a interface do Brush Resultado = RecuperarPonteiroCaren(Param_Brush, &pBrush); //Sai do método em caso de erro SairOnError(Resultado); //Verifica se forneceu o Brush de opacidade if (ObjetoGerenciadoValido(Param_OpacityBrush)) { //Recupera o ponteiro para a interface do Brush de opacidade. RecuperarPonteiroCaren(Param_OpacityBrush, &pOpacityBrush); } //Chama o método para realizar a operação. PonteiroTrabalho->FillGeometry(pGeometry, pBrush, pOpacityBrush); //Define sucesso Resultado.AdicionarCodigo(ResultCode::SS_OK, true); Done:; //Retorna o resultado. return Resultado; } /// <summary> /// Pinta o interior da malha especificada. /// O modo antialias atual do alvo de renderização deve ser D2D1_ANTIALIAS_MODE_ALIASED quando FillMesh é chamado. Para alterar o modo antialias do alvo de renderização, use o método SetAntialiasMode. /// FillMesh não espera uma ordem de enrolamento específica para os triângulos no ID2D1Mesh; tanto no sentido horário quanto no sentido anti-horário funcionará. /// Este método não retorna um código de erro se falhar. Para determinar se uma operação de desenho (como FillMesh) falhou, verifique o resultado retornado pelo ICarenD2D1RenderTarget::EndDraw /// ou ICarenD2D1RenderTarget::Flush. /// </summary> /// <param name="Param_Mesh">A malha para pintar.</param> /// <param name="Param_Brush">O pincel(Brush) para pintar a malha.</param> CarenResult CarenD2D1DCRenderTarget::FillMesh( ICarenD2D1Mesh^ Param_Mesh, ICarenD2D1Brush^ Param_Brush) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Variaveis a serem utilizadas. ID2D1Mesh* pMesh = NULL; ID2D1Brush* pBrush = NULL; //Recupera o ponteiro para a interface do Mesh Resultado = RecuperarPonteiroCaren(Param_Mesh, &pMesh); //Sai do método em caso de erro SairOnError(Resultado); //Recupera o ponteiro para a interface do Brush Resultado = RecuperarPonteiroCaren(Param_Brush, &pBrush); //Sai do método em caso de erro SairOnError(Resultado); //Chama o método para realizar a operação. PonteiroTrabalho->FillMesh(pMesh, pBrush); //Define sucesso Resultado.AdicionarCodigo(ResultCode::SS_OK, true); Done:; //Retorna o resultado. return Resultado; } /// <summary> /// Aplica a máscara de opacidade descrita pelo bitmap especificado em um pincel e usa esse pincel para pintar uma região do alvo de renderização. /// Para que este método funcione corretamente, o alvo de renderização deve estar usando o modo D2D1_ANTIALIAS_MODE_ALIASED antialiasing. Você pode definir o modo antialiasing chamando o método /// ICarenD2D1RenderTarget::SetAntialiasMode método. /// Este método não retorna um código de erro se falhar. Para determinar se uma operação de desenho (como FillOpacityMask) falhou, verifique o resultado retornado pelo ICarenD2D1RenderTarget::EndDraw /// ou ICarenD2D1RenderTarget::Flush. /// </summary> /// <param name="Param_OpacityMask">A máscara de opacidade para aplicar no pincel. O valor alfa de cada pixel na região especificado pelo (Param_RetanguloOrigem) é multiplicado com o valor alfa do /// Brush após o pincel(Brush) ter sido mapeado para a área definida pelo (Param_RetanguloDestino).</param> /// <param name="Param_Brush">O pincel(Brush) usado para pintar a região do alvo de render especificado pelo (Param_RetanguloDestino).</param> /// <param name="Param_Content">O tipo de conteúdo que a máscara de opacidade contém. O valor é usado para determinar o espaço de cor no qual a máscara de opacidade é misturada. /// A partir do Windows 8, o D2D1_OPACITY_MASK_CONTENT não é necessário. Consulte o método ICarenD2D1DeviceContext::FillOpacityMask, que não tem parâmetro D2D1_OPACITY_MASK_CONTENT.</param> /// <param name="Param_RetanguloDestino">A região do alvo de renderização para pintar, em pixels independentes do dispositivo.</param> /// <param name="Param_RetanguloOrigem">A região do bitmap para usar como máscara de opacidade, em pixels independentes de dispositivos.</param> CarenResult CarenD2D1DCRenderTarget::FillOpacityMask( ICarenD2D1Bitmap^ Param_OpacityMask, ICarenD2D1Brush^ Param_Brush, CA_D2D1_OPACITY_MASK_CONTENT Param_Content, CA_D2D1_RECT_F^ Param_RetanguloDestino, CA_D2D1_RECT_F^ Param_RetanguloOrigem) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Variaveis a serem utilizadas. Utilidades Util; ID2D1Bitmap* pOpacityMaskBitmap = NULL; ID2D1Brush* pBrush = NULL; D2D1_OPACITY_MASK_CONTENT OpacityMask = static_cast<D2D1_OPACITY_MASK_CONTENT>(Param_Content); D2D1_RECT_F* pRectDestinoF = NULL; D2D1_RECT_F* pRectOrigemF = NULL; //Recupera o ponteiro para a interface do Opacity Mask Resultado = RecuperarPonteiroCaren(Param_OpacityMask, &pOpacityMaskBitmap); //Sai do método em caso de erro SairOnError(Resultado); //Recupera o ponteiro para a interface do Brush Resultado = RecuperarPonteiroCaren(Param_Brush, &pBrush); //Sai do método em caso de erro SairOnError(Resultado); //Converte as estruturas. pRectDestinoF = Util.ConverterD2D1_RECT_FManagedToUnmanaged(Param_RetanguloDestino); pRectOrigemF = Util.ConverterD2D1_RECT_FManagedToUnmanaged(Param_RetanguloOrigem); //Chama o método para realizar a operação. PonteiroTrabalho->FillOpacityMask(pOpacityMaskBitmap, pBrush, OpacityMask, pRectDestinoF, pRectOrigemF); //Define sucesso Resultado.AdicionarCodigo(ResultCode::SS_OK, true); Done:; //Libera a memória para as estruturas. DeletarEstruturaSafe(&pRectDestinoF); DeletarEstruturaSafe(&pRectOrigemF); //Retorna o resultado. return Resultado; } /// <summary> /// Pinta o interior do retângulo especificado. /// Este método não retorna um código de erro se falhar. Para determinar se uma operação de desenho (como FillRectangle) falhou, verifique o resultado retornado pelo ICarenD2D1RenderTarget::EndDraw /// ou ICarenD2D1RenderTarget::Flush. /// </summary> /// <param name="Param_Rect">A dimensão do retângulo para pintar, em pixels independentes do dispositivo.</param> /// <param name="Param_Brush">O pincel(Brush) usado para pintar o interior do retângulo.</param> CarenResult CarenD2D1DCRenderTarget::FillRectangle( CA_D2D1_RECT_F^ Param_Rect, ICarenD2D1Brush^ Param_Brush) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Variaveis a serem utilizadas. Utilidades Util; D2D1_RECT_F* pRectF = NULL; ID2D1Brush* pBrush = NULL; //Recupera o ponteiro para a interface do Brush Resultado = RecuperarPonteiroCaren(Param_Brush, &pBrush); //Sai do método em caso de erro SairOnError(Resultado); //Converte a estrutura. pRectF = Util.ConverterD2D1_RECT_FManagedToUnmanaged(Param_Rect); //Chama o método para realizar a operação. PonteiroTrabalho->FillRectangle(pRectF, pBrush); //Define sucesso Resultado.AdicionarCodigo(ResultCode::SS_OK, true); Done:; //Libera a memória para a estrutura. DeletarEstruturaSafe(&pRectF); //Retorna o resultado. return Resultado; } /// <summary> /// Pinta o interior do retângulo arredondado especificado. /// Este método não retorna um código de erro se falhar. Para determinar se uma operação de desenho (como FillRoundedRectangle) falhou, verifique o resultado retornado pelo ICarenD2D1RenderTarget::EndDraw /// ou ICarenD2D1RenderTarget::Flush. /// </summary> /// <param name="Param_Rect">As dimensões do retângulo arredondado para pintar, em pixels independentes do dispositivo.</param> /// <param name="Param_Brush">O pincel(Brush) usado para pintar o interior do retângulo arredondado.</param> CarenResult CarenD2D1DCRenderTarget::FillRoundedRectangle( CA_D2D1_ROUNDED_RECT^ Param_Rect, ICarenD2D1Brush^ Param_Brush) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Variaveis a serem utilizadas. Utilidades Util; D2D1_ROUNDED_RECT* pRoundedRectF = NULL; ID2D1Brush* pBrush = NULL; //Recupera o ponteiro para a interface do Brush Resultado = RecuperarPonteiroCaren(Param_Brush, &pBrush); //Sai do método em caso de erro SairOnError(Resultado); //Converte a estrutura. pRoundedRectF = Util.ConverterD2D1_ROUNDED_RECTManagedToUnmanaged(Param_Rect); //Chama o método para realizar a operação. PonteiroTrabalho->FillRoundedRectangle(pRoundedRectF, pBrush); //Define sucesso Resultado.AdicionarCodigo(ResultCode::SS_OK, true); Done:; //Libera a memória para a estrutura. DeletarEstruturaSafe(&pRoundedRectF); //Retorna o resultado. return Resultado; } /// <summary> /// Executa todos os comandos de desenho pendentes. /// Este comando não libera o contexto do dispositivo Direct3D que está associado ao alvo de renderização. /// Chamar este método redefine o estado de erro do alvo de renderização. /// Se o método for bem sucedido, ele retorna SS_OK. Caso contrário, ele retorna um código de erro HRESULT e define Tag1 e Tag2 para as tags que estavam ativas quando o erro ocorreu. Se não ocorreu nenhum erro, /// este método define o estado de Tags de erro (0,0). /// </summary> /// <param name="Param_Out_Tag1">Quando este método retorna, contém a tag para operações de desenho que causaram erros ou 0 se não houver erros.</param> /// <param name="Param_Out_Tag2">Quando este método retorna, contém a tag para operações de desenho que causaram erros ou 0 se não houver erros.</param> CarenResult CarenD2D1DCRenderTarget::Flush( [Out] UInt64% Param_Out_Tag1, [Out] UInt64% Param_Out_Tag2) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. UINT64 OutTag1 = 0; UINT64 OutTag2 = 0; //Chama o método para realizar a operação. Hr = PonteiroTrabalho->Flush(&OutTag1, &OutTag2); //Processa o resultado da chamada. Resultado.ProcessarCodigoOperacao(Hr); //Verifica se obteve sucesso na operação. if (!Sucesso(static_cast<HRESULT>(Resultado.HResult))) { //Falhou ao realizar a operação. //Define o código na classe. Var_Glob_LAST_HRESULT = Hr; //Sai do método Sair; } //Define os valores nos parametros de saida. Param_Out_Tag1 = OutTag1; Param_Out_Tag2 = OutTag2; Done:; //Retorna o resultado. return Resultado; } /// <summary> /// Recupera o modo antialiasing atual para operações de desenho sem texto. /// </summary> /// <param name="Param_Out_AntialiasMode">Retorna o modo antialiasing atual para operações de desenho sem texto.</param> void CarenD2D1DCRenderTarget::GetAntialiasMode([Out] CA_D2D1_ANTIALIAS_MODE% Param_Out_AntialiasMode) { //Variaveis a serem utilizadas. D2D1_ANTIALIAS_MODE OutAliasMode; //Chama o método para realizar a operação. OutAliasMode = PonteiroTrabalho->GetAntialiasMode(); //Define no parametro de saida. Param_Out_AntialiasMode = static_cast<CA_D2D1_ANTIALIAS_MODE>(OutAliasMode); } /// <summary> /// Retorne os pontos do alvo de renderização por polegada (DPI). /// </summary> /// <param name="Param_Out_DpiX">Retorna o DPI horizontal do alvo de renderização.</param> /// <param name="Param_Out_DpiY">Retorna o DPI vertical do alvo de renderização. </param> void CarenD2D1DCRenderTarget::GetDpi( [Out] float% Param_Out_DpiX, [Out] float% Param_Out_DpiY) { //Variaveis a serem utilizadas. FLOAT OutDpiX; FLOAT OutDpiY; //Chama o método para realizar a operação. PonteiroTrabalho->GetDpi(&OutDpiX, &OutDpiY); //Define nos parametros de saida. Param_Out_DpiX = OutDpiX; Param_Out_DpiY = OutDpiY; } /// <summary> /// Obtém o tamanho máximo, em unidades dependentes de dispositivos (pixels), de qualquer dimensão de bitmap suportada pelo alvo de renderização. /// Este método retorna o tamanho máximo da textura do dispositivo Direct3D. /// O renderizador de software e os dispositivos WARP retornam o valor de 16 megapixels (16* 1024 * 1024). Você pode criar uma textura Direct2D que é deste tamanho, mas não uma textura Direct3D que /// é deste tamanho. /// </summary> /// <param name="Param_Out_MaximumSize">Retorna o tamanho máximo, em pixels, de qualquer dimensão de bitmap suportada pelo alvo de renderização.</param> void CarenD2D1DCRenderTarget::GetMaximumBitmapSize([Out] UInt32% Param_Out_MaximumSize) { //Chama o método para realizar a operação. Param_Out_MaximumSize = PonteiroTrabalho->GetMaximumBitmapSize(); } /// <summary> /// Recupera o formato de pixel e o modo alfa do alvo de renderização. /// </summary> /// <param name="Param_Out_PixelFormat">Retorna o formato pixel e o modo alfa do alvo de renderização.</param> void CarenD2D1DCRenderTarget::GetPixelFormat([Out] CA_D2D1_PIXEL_FORMAT^% Param_Out_PixelFormat) { //Variaveis a serem utilizadas. Utilidades Util; D2D1_PIXEL_FORMAT OutPixelFormat; //Chama o método para realizar a operação. OutPixelFormat = PonteiroTrabalho->GetPixelFormat(); //Converte e define no parametro de saida. Param_Out_PixelFormat = Util.ConverterD2D1_PIXEL_FORMATUnmanagedToManaged(&OutPixelFormat); } /// <summary> /// Retorna o tamanho do alvo de renderização em pixels do dispositivo. /// </summary> /// <param name="Param_Out_PixelSize">Retorna tamanho do alvo de renderização em pixels do dispositivo.</param> void CarenD2D1DCRenderTarget::GetPixelSize([Out] CA_D2D1_SIZE_U^% Param_Out_PixelSize) { //Variaveis a serem utilizadas. Utilidades Util; D2D1_SIZE_U OutSizeU; //Chama o método para realizar a operação. OutSizeU = PonteiroTrabalho->GetPixelSize(); //Converte e define no parametro de saida. Param_Out_PixelSize = Util.ConverterD2D1_SIZE_UUnmanagedToManaged(&OutSizeU); } /// <summary> /// Retorna o tamanho do alvo de renderização em pixels independentes do dispositivo. /// </summary> /// <param name="Param_Out_Size">Retorna tamanho atual do alvo de renderização em pixels independentes do dispositivo.</param> void CarenD2D1DCRenderTarget::GetSize([Out] CA_D2D1_SIZE_F^% Param_Out_Size) { //Variaveis a serem utilizadas. Utilidades Util; D2D1_SIZE_F OutSizeF; //Chama o método para realizar a operação. OutSizeF = PonteiroTrabalho->GetSize(); //Converte e define no parametro de saida. Param_Out_Size = Util.ConverterD2D1_SIZE_FUnmanagedToManaged(&OutSizeF); } /// <summary> /// Obtém o rótulo(Tags) para operações de desenho subsequentes. /// </summary> /// <param name="Param_Out_Tag1">Retorna o primeiro rótulo para operações de desenho subsequentes.</param> /// <param name="Param_Out_Tag2">Retorna o segundo rótulo para operações de desenho subsequentes.</param> void CarenD2D1DCRenderTarget::GetTags( [Out] UInt64% Param_Out_Tag1, [Out] UInt64% Param_Out_Tag2) { //Variaveis a serem utilizadas. UINT64 OutTag1; UINT64 OutTag2; //Chama o método para realizar a operação. PonteiroTrabalho->GetTags(&OutTag1, &OutTag2); //Define nos parametros de saida. Param_Out_Tag1 = OutTag1; Param_Out_Tag2 = OutTag2; } /// <summary> /// Obtém o modo antialiasing atual para operações de desenho de texto e glifo(Glyph). /// </summary> /// <param name="Param_Out_TextAntialiasMode">Retorna o modo antialiasing atual para operações de desenho de texto e glifo(Glyph).</param> void CarenD2D1DCRenderTarget::GetTextAntialiasMode([Out] CA_D2D1_TEXT_ANTIALIAS_MODE% Param_Out_TextAntialiasMode) { //Variaveis a serem utilizadas. D2D1_TEXT_ANTIALIAS_MODE OutTextAliasMode; //Chama o método para realizar a operação. OutTextAliasMode = PonteiroTrabalho->GetTextAntialiasMode(); //Converte e define no parametro de saida. Param_Out_TextAntialiasMode = static_cast<CA_D2D1_TEXT_ANTIALIAS_MODE>(OutTextAliasMode); } /// <summary> /// Recupera as opções de renderização de texto atual do alvo. /// </summary> /// <param name="Param_Out_TextRenderingParams">Retorna a interface (IDWriteRenderingParams) que contém um ponteiro para as opções de renderização de texto atuais do destino. O usuário deve inicializar a interface antes de chamar este método.</param> void CarenD2D1DCRenderTarget::GetTextRenderingParams(ICaren^ Param_Out_TextRenderingParams) { //Variaveis a serem utilizadas. IDWriteRenderingParams* pDWriteRendParams = NULL; //Chama o método para realizar a operação. PonteiroTrabalho->GetTextRenderingParams(&pDWriteRendParams); //Define na interface de destino no parametro. Param_Out_TextRenderingParams->AdicionarPonteiro(pDWriteRendParams); } /// <summary> /// Obtém a transformação atual do alvo render. /// </summary> /// <param name="Param_Out_Transform">Retorna a transformação atual do alvo de renderização.</param> void CarenD2D1DCRenderTarget::GetTransform([Out] CA_D2D1_MATRIX_3X2_F^% Param_Out_Transform) { //Variaveis a serem utilizadas. Utilidades Util; D2D1_MATRIX_3X2_F OutMatrix = { }; //Chama o método para realizar a operação. PonteiroTrabalho->GetTransform(&OutMatrix); //Converte e define no parametro de saida. Param_Out_Transform = Util.ConverterD2D1_MATRIX_3X2_FUnmanagedToManaged(&OutMatrix); } /// <summary> /// Indica se o alvo de renderização suporta as propriedades especificadas. /// Este método não avalia as configurações de DPI especificadas pelo parâmetro (Param_ProppriedadesRenderTarget). /// </summary> /// <param name="Param_ProppriedadesRenderTarget">As propriedades de destino de renderização para testar.</param> /// <param name="Param_Out_Suporta">Retorna um valor Booleano TRUE se as propriedades de destino de renderização especificadas forem suportadas por este alvo de renderização; caso contrário, FALSO.</param> void CarenD2D1DCRenderTarget::IsSupported( CA_D2D1_RENDER_TARGET_PROPERTIES^ Param_ProppriedadesRenderTarget, [Out] Boolean% Param_Out_Suporta) { //Variaveis a serem utilizadas. Utilidades Util; D2D1_RENDER_TARGET_PROPERTIES* pRenderTargetProps = NULL; BOOL IsSuported = FALSE; //Converte a estrutura. pRenderTargetProps = Util.ConverterD2D1_RENDER_TARGET_PROPERTIESManagedToUnmanaged(Param_ProppriedadesRenderTarget); //Chama o método para realizar a operação. IsSuported = PonteiroTrabalho->IsSupported(pRenderTargetProps); //Define no parametro de saida. Param_Out_Suporta = IsSuported ? true : false; //Libera a memória para a estrutura. DeletarEstruturaSafe(&pRenderTargetProps); } /// <summary> /// Remove o último clipe alinhado ao eixo do alvo de renderização. Depois que este método é chamado, o clipe não é mais aplicado às operações de desenho subsequentes. /// PopAxisAlignedClip deve ser chamado uma vez para cada chamada para PushAxisAlignedClip. /// Um par PushAxisAlignedClip/PopAxisAlignedClip pode ocorrer ao redor ou dentro de um par PushLayer/PopLayer, mas pode não se sobrepor. Por exemplo, uma sequência PushAxisAlignedClip, PushLayer, PopLayer, /// PopAxisAlignedClip é válida, mas uma sequência PushAxisAlignedClip, PushLayer, PopAxisAlignedClip, PopLayer não é. /// Este método não retorna um código de erro se falhar. Para determinar se uma operação de desenho (como PopAxisAlignedClip) falhou, verifique o resultado retornado pelo ICarenD2D1RenderTarget::EndDraw /// ou ICarenD2D1RenderTarget::Flush. /// </summary> void CarenD2D1DCRenderTarget::PopAxisAlignedClip() { //Chama o método para realizar a operação. PonteiroTrabalho->PopAxisAlignedClip(); } /// <summary> /// Interrompe o redirecionamento das operações de desenho para a camada especificada pela última chamada do PushLayer. /// Um PopLayer deve corresponder a uma chamada pushlayer anterior. /// Este método não retorna um código de erro se falhar. Para determinar se uma operação de desenho (como PopLayer) falhou, verifique o resultado retornado pelo ICarenD2D1RenderTarget::EndDraw /// ou ICarenD2D1RenderTarget::Flush. /// </summary> void CarenD2D1DCRenderTarget::PopLayer() { //Chama o método para realizar a operação. PonteiroTrabalho->PopLayer(); } /// <summary> /// Especifica um retângulo ao qual todas as operações de desenho subsequentes são cortadas. /// O PushAxisAlignedClip e o PopAxisAlignedClip devem coincidir. Caso contrário, o estado de erro está definido. Para que o alvo de renderização continue recebendo novos comandos, você pode chamar /// Flush para limpar o erro. /// Um par PushAxisAlignedClip e PopAxisAlignedClip pode ocorrer em torno ou dentro de um PushLayer e PopLayer, mas não pode se sobrepor. Por exemplo, a sequência de PushAxisAlignedClip, PushLayer, /// PopLayer, PopAxisAlignedClip é válida, mas a sequência de PushAxisAlignedClip, PushLayer, PopAxisAlignedClip, PopLayer é inválida. /// Este método não retorna um código de erro se falhar. Para determinar se uma operação de desenho (como PushAxisAlignedClip) falhou, verifique o resultado retornado pelo ICarenD2D1RenderTarget::EndDraw /// ou ICarenD2D1RenderTarget::Flush. /// </summary> /// <param name="Param_ClipRect">O tamanho e a posição da área de recorte, em pixels independentes do dispositivo.</param> /// <param name="Param_AntialiasMode">O modo antialiasing que é usado para desenhar as bordas das retagens de clipe que têm limites de subpixel, e para misturar o clipe com o conteúdo da cena. A mistura /// é realizada uma vez quando o método PopAxisAlignedClip é chamado, e não se aplica a cada primitivo dentro da camada.</param> void CarenD2D1DCRenderTarget::PushAxisAlignedClip( CA_D2D1_RECT_F^ Param_ClipRect, CA_D2D1_ANTIALIAS_MODE Param_AntialiasMode) { //Variaveis a serem utilizadas. Utilidades Util; D2D1_RECT_F* pClipRect = NULL; D2D1_ANTIALIAS_MODE AliasMode = static_cast<D2D1_ANTIALIAS_MODE>(Param_AntialiasMode); //Converte a estrutura. pClipRect = Util.ConverterD2D1_RECT_FManagedToUnmanaged(Param_ClipRect); //Chama o método para realizar a operação. PonteiroTrabalho->PushAxisAlignedClip(pClipRect, AliasMode); //Libera a memória para a estrutura. DeletarEstruturaSafe(&pClipRect); } /// <summary> /// Adicione a camada especificada ao destino renderização para que ela receba todas as operações de desenho subsequentes até que o PopLayer seja chamado. /// O método PushLayer permite que um chamador comece a redirecionar a renderização para uma camada. Todas as operações de renderização são válidas em uma camada. A localização da camada é afetada /// pela transformação mundial definida na meta de renderização. /// Cada PushLayer deve ter uma chamada PopLayer correspondente. Se houver mais chamadas do PopLayer do que chamadas PushLayer, o alvo de renderização será colocado em um estado de erro. Se flush /// for chamado antes de todas as camadas pendentes serem estouradas, o alvo de renderização será colocado em um estado de erro e um erro será retornado. O estado de erro pode ser liberado por uma chamada para EndDraw. /// Este método não retorna um código de erro se falhar. Para determinar se uma operação de desenho (como PushLayer) falhou, verifique o resultado retornado pelo ICarenD2D1RenderTarget::EndDraw /// ou ICarenD2D1RenderTarget::Flush. /// </summary> /// <param name="Param_ParametrosLayer">Os limites de conteúdo, máscara geométrica, opacidade, máscara de opções de opções de opções antialiasing para a camada.</param> /// <param name="Param_Layer">A camada que recebe operações de desenho subsequentes. Começando pelo Windows 8, este parâmetro é opcional. Se uma camada não for especificada, o Direct2D gerencia /// automaticamente o recurso de camada.</param> void CarenD2D1DCRenderTarget::PushLayer( CA_D2D1_LAYER_PARAMETERS^ Param_ParametrosLayer, ICarenD2D1Layer^ Param_Layer) { //Variaveis a serem utilizadas. Utilidades Util; D2D1_LAYER_PARAMETERS* pLayerParams = NULL; ID2D1Layer* pLayer = NULL; //Pode ser NULO. //Converte a estrutura. pLayerParams = Util.ConverterD2D1_LAYER_PARAMETERSManagedToUnmanaged(Param_ParametrosLayer); //Verifica se forneceu a camada if (ObjetoGerenciadoValido(Param_Layer)) { //Recupera o ponteiro para a interface da Layer RecuperarPonteiroCaren(Param_Layer, &pLayer); } //Chama o método para realizar a operação. PonteiroTrabalho->PushLayer(pLayerParams, pLayer); //Libera a memória para a estrutura. DeletarEstruturaSafe(&pLayerParams); } /// <summary> /// Define o estado de desenho do alvo de renderização ao do ID2D1DrawingStateBlock especificado. /// </summary> /// <param name="Param_DrawingStateBlock">O novo estado de desenho do alvo render.</param> CarenResult CarenD2D1DCRenderTarget::RestoreDrawingState(ICarenD2D1DrawingStateBlock^ Param_DrawingStateBlock) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. ID2D1DrawingStateBlock* pStateBlock = NULL; //Recupera o ponteiro para a interface da StateBlock Resultado = RecuperarPonteiroCaren(Param_DrawingStateBlock, &pStateBlock); //Sai do método em caso de erro SairOnError(Resultado); //Chama o método para realizar a operação. PonteiroTrabalho->RestoreDrawingState(pStateBlock); //Define sucesso Resultado.AdicionarCodigo(ResultCode::SS_OK, true); Done:; //Retorna o resultado. return Resultado; } /// <summary> /// Salva o estado de desenho atual para o ID2D1DrawingStateBlock especificado. /// </summary> /// <param name="Param_DrawingStateBlock">Retorna uma interface para o estado de desenho atual do alvo de renderização. Este parâmetro deve ser inicializado antes de passá-lo para o método.</param> CarenResult CarenD2D1DCRenderTarget::SaveDrawingState(ICarenD2D1DrawingStateBlock^ Param_DrawingStateBlock) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. ID2D1DrawingStateBlock* pStateBlock = NULL; //Recupera o ponteiro para a interface da StateBlock Resultado = RecuperarPonteiroCaren(Param_DrawingStateBlock, &pStateBlock); //Sai do método em caso de erro SairOnError(Resultado); //Chama o método para realizar a operação. PonteiroTrabalho->SaveDrawingState(pStateBlock); //Define sucesso Resultado.AdicionarCodigo(ResultCode::SS_OK, true); Done:; //Retorna o resultado. return Resultado; } /// <summary> /// Define o modo de antialiasing do alvo de renderização. O modo antialiasing aplica-se a todas as operações de desenho subsequentes, excluindo as operações de desenho de texto e glifo(Glyph). /// Para especificar o modo antialiasing para operações de texto e glifos(Glyph), use o método SetTextAntialiasMode. /// </summary> /// <param name="Param_AntialiasMode">O modo antialiasing para futuras operações de desenho.</param> void CarenD2D1DCRenderTarget::SetAntialiasMode(CA_D2D1_ANTIALIAS_MODE Param_AntialiasMode) { //Chama o método para realizar a operação. PonteiroTrabalho->SetAntialiasMode(static_cast<D2D1_ANTIALIAS_MODE>(Param_AntialiasMode)); } /// <summary> /// Define os pontos por polegada (DPI) do alvo de renderização. /// Este método especifica o mapeamento do espaço pixel para o espaço independente do dispositivo para o alvo de renderização. Se tanto o DpiX quanto o DpiY forem 0, o DPI do sistema de leitura /// de fábrica será escolhido. Se um parâmetro for zero e o outro não especificado, o DPI não será alterado. /// Para ICarenD2D1HwndRenderTarget, o DPI é padrão para o DPI mais recentemente do sistema de leitura de fábrica. O valor padrão para todas as outras metas de renderização é de 96 DPI. /// </summary> /// <param name="Param_DpiX">Um valor maior ou igual a zero que especifica o DPI horizontal do alvo de renderização.</param> /// <param name="Param_DpiY">Um valor maior ou igual a zero que especifica o DPI vertical do alvo de renderização.</param> void CarenD2D1DCRenderTarget::SetDpi( float Param_DpiX, float Param_DpiY) { //Chama o método para realizar a operação. PonteiroTrabalho->SetDpi(Param_DpiX, Param_DpiY); } /// <summary> /// Especifica um rótulo(Tag) para operações de desenho subsequentes. /// As etiquetas(Tags) especificadas por este método são impressas por mensagens de erro depuração. Se nenhuma tag for definida, o valor padrão de cada tag é 0. /// </summary> /// <param name="Param_Tag1">Um rótulo para aplicar às operações de desenho subsequentes.</param> /// <param name="Param_Tag2">Um rótulo para aplicar às operações de desenho subsequentes.</param> void CarenD2D1DCRenderTarget::SetTags( UInt64 Param_Tag1, UInt64 Param_Tag2) { //Chama o método para realizar a operação. PonteiroTrabalho->SetTags(Param_Tag1, Param_Tag2); } /// <summary> /// Especifica o modo antialiasing a ser usado para operações subsequentes de desenho de texto e glifo(Glyph). /// </summary> /// <param name="Param_TextAntialiasMode">O modo antialiasing para usar para operações subsequentes de desenho de texto e glifo(Glyph).</param> void CarenD2D1DCRenderTarget::SetTextAntialiasMode(CA_D2D1_TEXT_ANTIALIAS_MODE Param_TextAntialiasMode) { //Chama o método para realizar a operação. PonteiroTrabalho->SetTextAntialiasMode(static_cast<D2D1_TEXT_ANTIALIAS_MODE>(Param_TextAntialiasMode)); } /// <summary> /// Especifica as opções de renderização de texto a serem aplicadas a todas as operações subsequentes de desenho de texto e glifo(Glyph). /// Se as configurações especificadas por textRenderingParams forem incompatíveis com o modo antialiasing de texto do alvo de renderização (especificado por SetTextAntialiasMode), as operações /// subsequentes de desenho de texto e glifo(Glyph) falharão e colocarão o alvo de renderização em um estado de erro. /// </summary> /// <param name="Param_TextRenderingParams">Uma interface(IDWriteRenderingParams) para as opções de renderização de texto a serem aplicadas a todas as operações subsequentes de desenho /// de texto e glifoGlyph); NULO para limpar as opções atuais de renderização de texto.</param> CarenResult CarenD2D1DCRenderTarget::SetTextRenderingParams(ICaren^ Param_TextRenderingParams) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Variaveis a serem utilizadas. IDWriteRenderingParams* pDwriteParams = NULL; //Recupera o ponteiro para a interface da StateBlock Resultado = RecuperarPonteiroCaren(Param_TextRenderingParams, &pDwriteParams); //Sai do método em caso de erro SairOnError(Resultado); //Chama o método para realizar a operação. PonteiroTrabalho->SetTextRenderingParams(pDwriteParams); Done:; //Retorna o resultado. return Resultado; } /// <summary> /// Aplica a transformação especificada ao alvo de renderização, substituindo a transformação existente. Todas as operações subsequentes de desenho ocorrem no espaço transformado. /// </summary> /// <param name="Param_Transform">A transformação para aplicar ao alvo de renderização.</param> void CarenD2D1DCRenderTarget::SetTransform(CA_D2D1_MATRIX_3X2_F^ Param_Transform) { //Variaveis a serem utilizadas. Utilidades Util; D2D1_MATRIX_3X2_F* pMatrix = NULL; //Converte a estrutura. pMatrix = Util.ConverterD2D1_MATRIX_3X2_FManagedToUnmanaged(Param_Transform); //Chama o método para realizar a operação. PonteiroTrabalho->SetTransform(pMatrix); //Libera a memória para a estrutura DeletarEstruturaSafe(&pMatrix); } // Métodos da interface proprietária(ICarenD2D1Resource) /// <summary> /// Recupera a fábrica associada a este recurso. /// </summary> /// <param name="Param_Out_Factory">Retorna uma interface(ICarenD2D1Factory) que contém um ponteiro para a fabrica que criou esse recurso. O usuário deve inicializar a interface antes de chamar este método.</param> void CarenD2D1DCRenderTarget::GetFactory(ICaren^ Param_Out_Factory) { //Variaveis a serem utilizadas. ID2D1Factory* pFactory = NULL; //Variavel de resultados. CarenResult Resultado; //Chama o método para realizar a operação. PonteiroTrabalho->GetFactory(&pFactory); //Verifica se o ponteiro é válido if (!ObjetoValido(pFactory)) Sair; //Adiciona o ponteiro na interface informada. Resultado = Param_Out_Factory->AdicionarPonteiro(pFactory); //Verifica o resultado da operação. if (Resultado.StatusCode != ResultCode::SS_OK) { //Libera o ponteiro recuperado anteriormente. pFactory->Release(); pFactory = NULL; //Chama uma execeção para indicar o erro. throw gcnew Exception(String::Format("Ocorreu uma falha ao definir o ponteiro nativo na interface gerenciada. Código de erro > {0}", Resultado.StatusCode)); } Done:; }
37.807153
399
0.781127
VictorSantosReis
fe9e31c97b5420d6eed4e7e97897fbb5b33a2e00
11,062
cpp
C++
Mac_M1/DiodeAmplifier/Source/PluginEditor.cpp
landonviator/DiodeAmplifier
c26d9096435dc653687912ca9409888037af4958
[ "MIT" ]
null
null
null
Mac_M1/DiodeAmplifier/Source/PluginEditor.cpp
landonviator/DiodeAmplifier
c26d9096435dc653687912ca9409888037af4958
[ "MIT" ]
null
null
null
Mac_M1/DiodeAmplifier/Source/PluginEditor.cpp
landonviator/DiodeAmplifier
c26d9096435dc653687912ca9409888037af4958
[ "MIT" ]
null
null
null
/* ============================================================================== This file contains the basic framework code for a JUCE plugin editor. ============================================================================== */ #include "PluginProcessor.h" #include "PluginEditor.h" //============================================================================== DiodeAmplifierAudioProcessorEditor::DiodeAmplifierAudioProcessorEditor (DiodeAmplifierAudioProcessor& p) : AudioProcessorEditor (&p), audioProcessor (p) { shadowProperties.radius = 24; shadowProperties.offset = juce::Point<int> (-1, 12); shadowProperties.colour = juce::Colours::black.withAlpha(0.25f); dialShadow.setShadowProperties (shadowProperties); sliders.reserve(6); sliders = { &inputSlider, &driveSlider, &lowSlider, &midSlider, &highSlider, &outputSlider }; labels.reserve(6); labels = { &inputLabel, &driveLabel, &lowLabel, &midLabel, &highLabel, &outputLabel }; labelTexts.reserve(6); labelTexts = { inputSliderLabelText, driveSliderLabelText, lowSliderLabelText, midSliderLabelText, highSliderLabelText, outputSliderLabelText }; inputSlider.setLookAndFeel(&customDial); driveSlider.setLookAndFeel(&customDial); outputSlider.setLookAndFeel(&customDial); lowSlider.setLookAndFeel(&customDial2); midSlider.setLookAndFeel(&customDial2); highSlider.setLookAndFeel(&customDial2); for (auto i = 0; i < sliders.size(); i++) { addAndMakeVisible(sliders[i]); sliders[i]->setSliderStyle(juce::Slider::SliderStyle::RotaryVerticalDrag); sliders[i]->setTextBoxStyle(juce::Slider::TextBoxBelow, false, 64, 32); sliders[i]->setColour(0x1001400, juce::Colour::fromFloatRGBA(1, 1, 1, 0.5f)); sliders[i]->setColour(0x1001700, juce::Colour::fromFloatRGBA(1, 1, 1, 0.0f)); sliders[i]->setColour(0x1001500, juce::Colour::fromFloatRGBA(0, 0, 0, 0.25f)); sliders[i]->setComponentEffect(&dialShadow); sliders[i]->setRange(-24.0, 24.0, 0.25); sliders[i]->setDoubleClickReturnValue(true, 0.0); } driveSlider.setRange(0.0, 10.0, 0.25); lowSlider.setRange(-6.0, 6.0, 0.25); midSlider.setRange(-6.0, 6.0, 0.25); highSlider.setRange(-6.0, 6.0, 0.25); inputSliderAttach = std::make_unique<juce::AudioProcessorValueTreeState::SliderAttachment>(audioProcessor.treeState, inputGainSliderId, inputSlider); driveSliderAttach = std::make_unique<juce::AudioProcessorValueTreeState::SliderAttachment>(audioProcessor.treeState, driveSliderId, driveSlider); lowSliderAttach = std::make_unique<juce::AudioProcessorValueTreeState::SliderAttachment>(audioProcessor.treeState, lowSliderId, lowSlider); midSliderAttach = std::make_unique<juce::AudioProcessorValueTreeState::SliderAttachment>(audioProcessor.treeState, midSliderId, midSlider); highSliderAttach = std::make_unique<juce::AudioProcessorValueTreeState::SliderAttachment>(audioProcessor.treeState, highSliderId, highSlider); outputSliderAttach = std::make_unique<juce::AudioProcessorValueTreeState::SliderAttachment>(audioProcessor.treeState, outputGainSliderId, outputSlider); for (auto i = 0; i < labels.size(); i++) { addAndMakeVisible(labels[i]); labels[i]->setText(labelTexts[i], juce::dontSendNotification); labels[i]->setJustificationType(juce::Justification::centred); labels[i]->setColour(0x1000281, juce::Colour::fromFloatRGBA(1, 1, 1, 0.25f)); labels[i]->attachToComponent(sliders[i], false); } addAndMakeVisible(windowBorder); windowBorder.setText("Ignorant Diode Amplifier"); windowBorder.setColour(0x1005400, juce::Colour::fromFloatRGBA(1, 1, 1, 0.25f)); windowBorder.setColour(0x1005410, juce::Colour::fromFloatRGBA(1, 1, 1, 0.25f)); addAndMakeVisible(&brightButton); brightButton.setButtonText("Bright"); brightButton.setClickingTogglesState(true); brightButtonAttach = std::make_unique<juce::AudioProcessorValueTreeState::ButtonAttachment>(audioProcessor.treeState, brightId, brightButton); brightButton.setColour(0x1000100, juce::Colours::whitesmoke.darker(1.0).withAlpha(1.0f)); brightButton.setColour(0x1000c00, juce::Colour::fromFloatRGBA(0, 0, 0, 0)); brightButton.setColour(0x1000101, juce::Colours::lightgoldenrodyellow.darker(0.2f)); brightButton.setColour(0x1000102, juce::Colours::black.brighter(0.1)); brightButton.setColour(0x1000103, juce::Colours::black.brighter(0.1)); addAndMakeVisible(&cabButton); cabButton.setButtonText("Load IR"); cabButton.setColour(0x1000100, juce::Colours::whitesmoke.darker(1.0).withAlpha(1.0f)); cabButton.setColour(0x1000c00, juce::Colour::fromFloatRGBA(0, 0, 0, 0)); cabButton.setColour(0x1000101, juce::Colours::lightgoldenrodyellow.darker(0.2f)); cabButton.setColour(0x1000102, juce::Colours::black.brighter(0.1)); cabButton.setColour(0x1000103, juce::Colours::black.brighter(0.1)); addAndMakeVisible(&cabToggleButton); cabToggleButton.setClickingTogglesState(true); cabToggleButton.setToggleState(true, juce::dontSendNotification); cabToggleButton.setButtonText("Cab On"); cabToggleAttach = std::make_unique<juce::AudioProcessorValueTreeState::ButtonAttachment>(audioProcessor.treeState, cabId, cabToggleButton); cabToggleButton.setColour(0x1000100, juce::Colours::whitesmoke.darker(1.0).withAlpha(1.0f)); cabToggleButton.setColour(0x1000c00, juce::Colour::fromFloatRGBA(0, 0, 0, 0)); cabToggleButton.setColour(0x1000101, juce::Colours::lightgoldenrodyellow.darker(0.2f)); cabToggleButton.setColour(0x1000102, juce::Colours::black.brighter(0.1)); cabToggleButton.setColour(0x1000103, juce::Colours::black.brighter(0.1)); addAndMakeVisible(&resetIRButton); resetIRButton.setButtonText("Reset IR"); resetIRButton.setColour(0x1000100, juce::Colours::whitesmoke.darker(1.0).withAlpha(1.0f)); resetIRButton.setColour(0x1000c00, juce::Colour::fromFloatRGBA(0, 0, 0, 0)); resetIRButton.setColour(0x1000101, juce::Colours::lightgoldenrodyellow.darker(0.2f)); resetIRButton.setColour(0x1000102, juce::Colours::black.brighter(0.1)); resetIRButton.setColour(0x1000103, juce::Colours::black.brighter(0.1)); setCabButtonProps(); setSize (711, 500); } DiodeAmplifierAudioProcessorEditor::~DiodeAmplifierAudioProcessorEditor() { inputSlider.setLookAndFeel(nullptr); driveSlider.setLookAndFeel(nullptr); lowSlider.setLookAndFeel(nullptr); midSlider.setLookAndFeel(nullptr); highSlider.setLookAndFeel(nullptr); outputSlider.setLookAndFeel(nullptr); } //============================================================================== void DiodeAmplifierAudioProcessorEditor::paint (juce::Graphics& g) { //Image layer from Illustrator pluginBackground = juce::ImageCache::getFromMemory(BinaryData::PluginBackground1_png, BinaryData::PluginBackground1_pngSize); g.drawImageWithin(pluginBackground, 0, 0, AudioProcessorEditor::getWidth(), AudioProcessorEditor::getHeight(), juce::RectanglePlacement::stretchToFit); // Background dark-maker // juce::Rectangle<float> backgroundDarker; // backgroundDarker.setBounds(0, 0, AudioProcessorEditor::getWidth(), AudioProcessorEditor::getHeight()); // g.setColour(juce::Colour::fromFloatRGBA(0.09f, 0.10f, 0.12f, 0.65f)); // g.fillRect(backgroundDarker); // Header rectangle juce::Rectangle<float> header; header.setBounds(0, 0, AudioProcessorEditor::getWidth(), AudioProcessorEditor::getHeight() * 0.13f); g.setColour(juce::Colours::black.withAlpha(0.5f)); g.fillRect(header); // Set header text g.setFont (16.0f); g.setColour (juce::Colours::white.withAlpha(0.25f)); g.drawFittedText ("Algorithms by Landon Viator", 12, AudioProcessorEditor::getHeight() * 0.05, AudioProcessorEditor::getWidth(), AudioProcessorEditor::getHeight(), juce::Justification::topLeft, 1); // Logo mLogo = juce::ImageCache::getFromMemory(BinaryData::landon5504_png, BinaryData::landon5504_pngSize); g.drawImageWithin(mLogo, AudioProcessorEditor::getWidth() * 0.4f, AudioProcessorEditor::getHeight() * 0.025, AudioProcessorEditor::getHeight() * 0.08f * 4.58, AudioProcessorEditor::getHeight() * 0.08f, juce::RectanglePlacement::centred); } void DiodeAmplifierAudioProcessorEditor::resized() { //Master bounds object juce::Rectangle<int> bounds = getLocalBounds(); auto sliderSize {3.5}; //first column of gui juce::FlexBox flexboxColumnOne; flexboxColumnOne.flexDirection = juce::FlexBox::Direction::row; flexboxColumnOne.flexWrap = juce::FlexBox::Wrap::noWrap; flexboxColumnOne.alignContent = juce::FlexBox::AlignContent::center; juce::Array<juce::FlexItem> itemArrayColumnOne; itemArrayColumnOne.add(juce::FlexItem(bounds.getWidth() / sliderSize, bounds.getHeight() / sliderSize, inputSlider).withMargin(juce::FlexItem::Margin(0, 0, 0, 0))); itemArrayColumnOne.add(juce::FlexItem(bounds.getWidth() / sliderSize, bounds.getHeight() / sliderSize, driveSlider).withMargin(juce::FlexItem::Margin(0, 0, 0, 0))); itemArrayColumnOne.add(juce::FlexItem(bounds.getWidth() / sliderSize, bounds.getHeight() / sliderSize, outputSlider).withMargin(juce::FlexItem::Margin(0, 0, 0, 0))); flexboxColumnOne.items = itemArrayColumnOne; flexboxColumnOne.performLayout(bounds.removeFromTop(bounds.getHeight() - 72)); /* ============================================================================ */ lowSlider.setBounds(inputSlider.getX(), inputSlider.getY() + inputSlider.getHeight() + 32, inputSlider.getWidth(), inputSlider.getHeight()); midSlider.setBounds(driveSlider.getX(), driveSlider.getY() + driveSlider.getHeight() + 32, driveSlider.getWidth(), driveSlider.getHeight()); highSlider.setBounds(outputSlider.getX(), outputSlider.getY() + outputSlider.getHeight() + 32, outputSlider.getWidth(), outputSlider.getHeight()); brightButton.setBounds(outputSlider.getX() + outputSlider.getWidth() - 24, outputSlider.getY() * 1.5, 72, 32); cabButton.setBounds(brightButton.getX(), brightButton.getY() + brightButton.getHeight(), 72, 32); cabToggleButton.setBounds(cabButton.getX(), cabButton.getY() + cabButton.getHeight(), 72, 32); resetIRButton.setBounds(cabToggleButton.getX(), cabToggleButton.getY() + cabToggleButton.getHeight(), 72, 32); // Window border bounds windowBorder.setBounds ( 16, AudioProcessorEditor::getHeight() * 0.16, AudioProcessorEditor::getWidth() * 0.95, AudioProcessorEditor::getHeight() * .8 ); }
54.492611
241
0.683782
landonviator
fea407a7ea7b167aa1bbb49a184b5b7bd70a91b5
29,001
ipp
C++
generators/pd/templates/thrift-src/p4_pd_rpc_server.ipp
liusheng198933/PI
124ac3c45df72a4b93eee1664266e923f4b69545
[ "Apache-2.0" ]
1
2019-01-15T10:47:28.000Z
2019-01-15T10:47:28.000Z
generators/pd/templates/thrift-src/p4_pd_rpc_server.ipp
liusheng198933/PI
124ac3c45df72a4b93eee1664266e923f4b69545
[ "Apache-2.0" ]
null
null
null
generators/pd/templates/thrift-src/p4_pd_rpc_server.ipp
liusheng198933/PI
124ac3c45df72a4b93eee1664266e923f4b69545
[ "Apache-2.0" ]
null
null
null
//:: pd_prefix = "p4_pd_" + p4_prefix + "_" //:: api_prefix = p4_prefix + "_" #include "p4_prefix.h" #include <iostream> #include <string.h> #include "pd/pd.h" #include <list> #include <map> #include <mutex> #include <thread> #include <condition_variable> #include <future> using namespace ::p4_pd_rpc; using namespace ::res_pd_rpc; namespace { __attribute__ ((unused)) void bytes_meter_spec_thrift_to_pd( const ${api_prefix}bytes_meter_spec_t &meter_spec, p4_pd_bytes_meter_spec_t *pd_meter_spec) { pd_meter_spec->cir_kbps = meter_spec.cir_kbps; pd_meter_spec->cburst_kbits = meter_spec.cburst_kbits; pd_meter_spec->pir_kbps = meter_spec.pir_kbps; pd_meter_spec->pburst_kbits = meter_spec.pburst_kbits; pd_meter_spec->meter_type = meter_spec.color_aware ? PD_METER_TYPE_COLOR_AWARE : PD_METER_TYPE_COLOR_UNAWARE; } __attribute__ ((unused)) void packets_meter_spec_thrift_to_pd( const ${api_prefix}packets_meter_spec_t &meter_spec, p4_pd_packets_meter_spec_t *pd_meter_spec) { pd_meter_spec->cir_pps = meter_spec.cir_pps; pd_meter_spec->cburst_pkts = meter_spec.cburst_pkts; pd_meter_spec->pir_pps = meter_spec.pir_pps; pd_meter_spec->pburst_pkts = meter_spec.pburst_pkts; pd_meter_spec->meter_type = meter_spec.color_aware ? PD_METER_TYPE_COLOR_AWARE : PD_METER_TYPE_COLOR_UNAWARE; } __attribute__ ((unused)) void bytes_meter_spec_pd_to_thrift( const p4_pd_bytes_meter_spec_t &pd_meter_spec, ${api_prefix}bytes_meter_spec_t *meter_spec) { meter_spec->cir_kbps = pd_meter_spec.cir_kbps; meter_spec->cburst_kbits = pd_meter_spec.cburst_kbits; meter_spec->pir_kbps = pd_meter_spec.pir_kbps; meter_spec->pburst_kbits = pd_meter_spec.pburst_kbits; meter_spec->color_aware = (pd_meter_spec.meter_type == PD_METER_TYPE_COLOR_AWARE); } __attribute__ ((unused)) void packets_meter_spec_pd_to_thrift( const p4_pd_packets_meter_spec_t &pd_meter_spec, ${api_prefix}packets_meter_spec_t *meter_spec) { meter_spec->cir_pps = pd_meter_spec.cir_pps; meter_spec->cburst_pkts = pd_meter_spec.cburst_pkts; meter_spec->pir_pps = pd_meter_spec.pir_pps; meter_spec->pburst_pkts = pd_meter_spec.pburst_pkts; meter_spec->color_aware = (pd_meter_spec.meter_type == PD_METER_TYPE_COLOR_AWARE); } } // namespace //:: def get_direct_parameter_specs(t, api_prefix): //:: specs = [] //:: if t.direct_meters: //:: m = t.direct_meters //:: if m.unit == m.MeterUnit.PACKETS: //:: specs += ["const " + api_prefix + "packets_meter_spec_t &" + m.name + "_spec"] //:: else: //:: specs += ["const " + api_prefix + "bytes_meter_spec_t &" + m.name + "_spec"] //:: #endif //:: #endif //:: return specs //:: #enddef class ${p4_prefix}Handler : virtual public ${p4_prefix}If { private: class CbWrap { CbWrap() {} int wait() { std::unique_lock<std::mutex> lock(cb_mutex); while(cb_status == 0) { cb_condvar.wait(lock); } return 0; } void notify() { std::unique_lock<std::mutex> lock(cb_mutex); assert(cb_status == 0); cb_status = 1; cb_condvar.notify_one(); } static void cb_fn(int device_id, void *cookie) { (void) device_id; CbWrap *inst = static_cast<CbWrap *>(cookie); inst->notify(); } CbWrap(const CbWrap &other) = delete; CbWrap &operator=(const CbWrap &other) = delete; CbWrap(CbWrap &&other) = delete; CbWrap &operator=(CbWrap &&other) = delete; private: std::mutex cb_mutex{}; std::condition_variable cb_condvar{}; int cb_status{0}; }; public: ${p4_prefix}Handler() { } // Table entry add functions //:: for t_name, t in tables.items(): //:: t_type = t.type_ //:: if t_type != TableType.SIMPLE: continue //:: t_name = get_c_name(t_name) //:: match_type = t.match_type //:: has_match_spec = len(t.key) > 0 //:: for a_name, a in t.actions.items(): //:: a_name = get_c_name(a_name) //:: has_action_spec = len(a.runtime_data) > 0 //:: params = ["const SessionHandle_t sess_hdl", //:: "const DevTarget_t &dev_tgt"] //:: if has_match_spec: //:: params += ["const " + api_prefix + t_name + "_match_spec_t &match_spec"] //:: #endif //:: if match_type in {MatchType.TERNARY, MatchType.RANGE}: //:: params += ["const int32_t priority"] //:: #endif //:: if has_action_spec: //:: params += ["const " + api_prefix + a_name + "_action_spec_t &action_spec"] //:: #endif //:: if t.support_timeout: //:: params += ["const int32_t ttl"] //:: #endif //:: params += get_direct_parameter_specs(t, api_prefix) //:: param_str = ", ".join(params) //:: name = t_name + "_table_add_with_" + a_name //:: pd_name = pd_prefix + name EntryHandle_t ${name}(${param_str}) { std::cerr << "In ${name}\n"; p4_pd_dev_target_t pd_dev_tgt; pd_dev_tgt.device_id = dev_tgt.dev_id; pd_dev_tgt.dev_pipe_id = dev_tgt.dev_pipe_id; //:: if has_match_spec: ${pd_prefix}${t_name}_match_spec_t pd_match_spec; //:: match_params = gen_match_params(t.key) //:: for name, width in match_params: //:: name = get_c_name(name) //:: if width <= 4: pd_match_spec.${name} = match_spec.${name}; //:: else: memcpy(pd_match_spec.${name}, match_spec.${name}.c_str(), ${width}); //:: #endif //:: #endfor //:: #endif //:: if has_action_spec: ${pd_prefix}${a_name}_action_spec_t pd_action_spec; //:: action_params = gen_action_params(a.runtime_data) //:: for name, _, width in action_params: //:: name = get_c_name(name) //:: if width <= 4: pd_action_spec.${name} = action_spec.${name}; //:: else: memcpy(pd_action_spec.${name}, action_spec.${name}.c_str(), ${width}); //:: #endif //:: #endfor //:: #endif p4_pd_entry_hdl_t pd_entry; //:: pd_params = ["sess_hdl", "pd_dev_tgt"] //:: if has_match_spec: //:: pd_params += ["&pd_match_spec"] //:: #endif //:: if match_type in {MatchType.TERNARY, MatchType.RANGE}: //:: pd_params += ["priority"] //:: #endif //:: if has_action_spec: //:: pd_params += ["&pd_action_spec"] //:: #endif //:: if t.support_timeout: //:: pd_params += ["(uint32_t)ttl"] //:: #endif //:: # direct parameter specs //:: if t.direct_meters: //:: m = t.direct_meters //:: unit_name = MeterUnit.to_str(m.unit) p4_pd_${unit_name}_meter_spec_t pd_${m.name}_spec; ${unit_name}_meter_spec_thrift_to_pd(${m.name}_spec, &pd_${m.name}_spec); //:: pd_params += ["&pd_" + m.name + "_spec"] //:: #endif //:: pd_params += ["&pd_entry"] //:: pd_param_str = ", ".join(pd_params) ${pd_name}(${pd_param_str}); return pd_entry; } //:: #endfor //:: #endfor // Table entry modify functions //:: for t_name, t in tables.items(): //:: t_type = t.type_ //:: if t_type != TableType.SIMPLE: continue //:: t_name = get_c_name(t_name) //:: for a_name, a in t.actions.items(): //:: a_name = get_c_name(a_name) //:: has_action_spec = len(a.runtime_data) > 0 //:: params = ["const SessionHandle_t sess_hdl", //:: "const int8_t dev_id", //:: "const EntryHandle_t entry"] //:: if has_action_spec: //:: params += ["const " + api_prefix + a_name + "_action_spec_t &action_spec"] //:: #endif //:: params += get_direct_parameter_specs(t, api_prefix) //:: param_str = ", ".join(params) //:: name = t_name + "_table_modify_with_" + a_name //:: pd_name = pd_prefix + name EntryHandle_t ${name}(${param_str}) { std::cerr << "In ${name}\n"; //:: if has_action_spec: ${pd_prefix}${a_name}_action_spec_t pd_action_spec; //:: action_params = gen_action_params(a.runtime_data) //:: for name, _, width in action_params: //:: name = get_c_name(name) //:: if width <= 4: pd_action_spec.${name} = action_spec.${name}; //:: else: memcpy(pd_action_spec.${name}, action_spec.${name}.c_str(), ${width}); //:: #endif //:: #endfor //:: #endif //:: pd_params = ["sess_hdl", "dev_id", "entry"] //:: if has_action_spec: //:: pd_params += ["&pd_action_spec"] //:: #endif //:: # direct parameter specs //:: if t.direct_meters: //:: m = t.direct_meters //:: unit_name = MeterUnit.to_str(m.unit) p4_pd_${unit_name}_meter_spec_t pd_${m.name}_spec; ${unit_name}_meter_spec_thrift_to_pd(${m.name}_spec, &pd_${m.name}_spec); //:: pd_params += ["&pd_" + m.name + "_spec"] //:: #endif //:: pd_param_str = ", ".join(pd_params) return ${pd_name}(${pd_param_str}); } //:: #endfor //:: #endfor // Table entry delete functions //:: for t_name, t in tables.items(): //:: t_type = t.type_ //:: t_name = get_c_name(t_name) //:: name = t_name + "_table_delete" //:: pd_name = pd_prefix + name //:: params = ["const SessionHandle_t sess_hdl", //:: "const int8_t dev_id", //:: "const EntryHandle_t entry"] //:: param_str = ", ".join(params) int32_t ${name}(${param_str}) { std::cerr << "In ${name}\n"; return ${pd_name}(sess_hdl, dev_id, entry); } //:: #endfor // set default action //:: for t_name, t in tables.items(): //:: t_type = t.type_ //:: if t_type != TableType.SIMPLE: continue //:: t_name = get_c_name(t_name) //:: for a_name, a in t.actions.items(): //:: a_name = get_c_name(a_name) //:: has_action_spec = len(a.runtime_data) > 0 //:: params = ["const SessionHandle_t sess_hdl", //:: "const DevTarget_t &dev_tgt"] //:: if has_action_spec: //:: params += ["const " + api_prefix + a_name + "_action_spec_t &action_spec"] //:: #endif //:: params += get_direct_parameter_specs(t, api_prefix) //:: param_str = ", ".join(params) //:: name = t_name + "_set_default_action_" + a_name //:: pd_name = pd_prefix + name int32_t ${name}(${param_str}) { std::cerr << "In ${name}\n"; p4_pd_dev_target_t pd_dev_tgt; pd_dev_tgt.device_id = dev_tgt.dev_id; pd_dev_tgt.dev_pipe_id = dev_tgt.dev_pipe_id; //:: if has_action_spec: ${pd_prefix}${a_name}_action_spec_t pd_action_spec; //:: action_params = gen_action_params(a.runtime_data) //:: for name, _, width in action_params: //:: name = get_c_name(name) //:: if width <= 4: pd_action_spec.${name} = action_spec.${name}; //:: else: memcpy(pd_action_spec.${name}, action_spec.${name}.c_str(), ${width}); //:: #endif //:: #endfor //:: #endif p4_pd_entry_hdl_t pd_entry; //:: pd_params = ["sess_hdl", "pd_dev_tgt"] //:: if has_action_spec: //:: pd_params += ["&pd_action_spec"] //:: #endif //:: # direct parameter specs //:: if t.direct_meters: //:: m = t.direct_meters //:: unit_name = MeterUnit.to_str(m.unit) p4_pd_${unit_name}_meter_spec_t pd_${m.name}_spec; ${unit_name}_meter_spec_thrift_to_pd(${m.name}_spec, &pd_${m.name}_spec); //:: pd_params += ["&pd_" + m.name + "_spec"] //:: #endif //:: pd_params += ["&pd_entry"] //:: pd_param_str = ", ".join(pd_params) return ${pd_name}(${pd_param_str}); // return pd_entry; } //:: #endfor //:: #endfor //:: name = "clean_all" //:: pd_name = pd_prefix + name int32_t ${name}(const SessionHandle_t sess_hdl, const DevTarget_t &dev_tgt) { std::cerr << "In ${name}\n"; p4_pd_dev_target_t pd_dev_tgt; pd_dev_tgt.device_id = dev_tgt.dev_id; pd_dev_tgt.dev_pipe_id = dev_tgt.dev_pipe_id; return ${pd_name}(sess_hdl, pd_dev_tgt); } // INDIRECT ACTION DATA AND MATCH SELECT //:: for act_prof_name, act_prof in act_profs.items(): //:: act_prof_name = get_c_name(act_prof_name) //:: for a_name, a in act_prof.actions.items(): //:: a_name = get_c_name(a_name) //:: has_action_spec = len(a.runtime_data) > 0 //:: params = ["const SessionHandle_t sess_hdl", //:: "const DevTarget_t &dev_tgt"] //:: if has_action_spec: //:: params += ["const " + api_prefix + a_name + "_action_spec_t &action_spec"] //:: #endif //:: param_str = ", ".join(params) //:: name = act_prof_name + "_add_member_with_" + a_name //:: pd_name = pd_prefix + name EntryHandle_t ${name}(${param_str}) { std::cerr << "In ${name}\n"; p4_pd_dev_target_t pd_dev_tgt; pd_dev_tgt.device_id = dev_tgt.dev_id; pd_dev_tgt.dev_pipe_id = dev_tgt.dev_pipe_id; //:: if has_action_spec: ${pd_prefix}${a_name}_action_spec_t pd_action_spec; //:: action_params = gen_action_params(a.runtime_data) //:: for name, _, width in action_params: //:: name = get_c_name(name) //:: if width <= 4: pd_action_spec.${name} = action_spec.${name}; //:: else: memcpy(pd_action_spec.${name}, action_spec.${name}.c_str(), ${width}); //:: #endif //:: #endfor //:: #endif p4_pd_mbr_hdl_t pd_mbr_hdl; //:: pd_params = ["sess_hdl", "pd_dev_tgt"] //:: if has_action_spec: //:: pd_params += ["&pd_action_spec"] //:: #endif //:: pd_params += ["&pd_mbr_hdl"] //:: pd_param_str = ", ".join(pd_params) ${pd_name}(${pd_param_str}); return pd_mbr_hdl; } //:: params = ["const SessionHandle_t sess_hdl", //:: "const int8_t dev_id", //:: "const MemberHandle_t mbr"] //:: if has_action_spec: //:: params += ["const " + api_prefix + a_name + "_action_spec_t &action_spec"] //:: #endif //:: param_str = ", ".join(params) //:: name = act_prof_name + "_modify_member_with_" + a_name //:: pd_name = pd_prefix + name EntryHandle_t ${name}(${param_str}) { std::cerr << "In ${name}\n"; //:: if has_action_spec: ${pd_prefix}${a_name}_action_spec_t pd_action_spec; //:: action_params = gen_action_params(a.runtime_data) //:: for name, _, width in action_params: //:: name = get_c_name(name) //:: if width <= 4: pd_action_spec.${name} = action_spec.${name}; //:: else: memcpy(pd_action_spec.${name}, action_spec.${name}.c_str(), ${width}); //:: #endif //:: #endfor //:: #endif //:: pd_params = ["sess_hdl", "dev_id", "mbr"] //:: if has_action_spec: //:: pd_params += ["&pd_action_spec"] //:: #endif //:: pd_param_str = ", ".join(pd_params) return ${pd_name}(${pd_param_str}); } //:: #endfor //:: params = ["const SessionHandle_t sess_hdl", //:: "const int8_t dev_id", //:: "const MemberHandle_t mbr"] //:: param_str = ", ".join(params) //:: name = act_prof_name + "_del_member" //:: pd_name = pd_prefix + name int32_t ${name}(${param_str}) { std::cerr << "In ${name}\n"; return ${pd_name}(sess_hdl, dev_id, mbr); } //:: if not act_prof.with_selector: continue //:: //:: params = ["const SessionHandle_t sess_hdl", //:: "const DevTarget_t &dev_tgt", //:: "const int16_t max_grp_size"] //:: param_str = ", ".join(params) //:: name = act_prof_name + "_create_group" //:: pd_name = pd_prefix + name GroupHandle_t ${name}(${param_str}) { std::cerr << "In ${name}\n"; p4_pd_dev_target_t pd_dev_tgt; pd_dev_tgt.device_id = dev_tgt.dev_id; pd_dev_tgt.dev_pipe_id = dev_tgt.dev_pipe_id; p4_pd_grp_hdl_t pd_grp_hdl; ${pd_name}(sess_hdl, pd_dev_tgt, max_grp_size, &pd_grp_hdl); return pd_grp_hdl; } //:: params = ["const SessionHandle_t sess_hdl", //:: "const int8_t dev_id", //:: "const GroupHandle_t grp"] //:: param_str = ", ".join(params) //:: name = act_prof_name + "_del_group" //:: pd_name = pd_prefix + name int32_t ${name}(${param_str}) { std::cerr << "In ${name}\n"; return ${pd_name}(sess_hdl, dev_id, grp); } //:: params = ["const SessionHandle_t sess_hdl", //:: "const int8_t dev_id", //:: "const GroupHandle_t grp", //:: "const MemberHandle_t mbr"] //:: param_str = ", ".join(params) //:: name = act_prof_name + "_add_member_to_group" //:: pd_name = pd_prefix + name int32_t ${name}(${param_str}) { std::cerr << "In ${name}\n"; return ${pd_name}(sess_hdl, dev_id, grp, mbr); } //:: params = ["const SessionHandle_t sess_hdl", //:: "const int8_t dev_id", //:: "const GroupHandle_t grp", //:: "const MemberHandle_t mbr"] //:: param_str = ", ".join(params) //:: name = act_prof_name + "_del_member_from_group" //:: pd_name = pd_prefix + name int32_t ${name}(${param_str}) { std::cerr << "In ${name}\n"; return ${pd_name}(sess_hdl, dev_id, grp, mbr); } //:: params = ["const SessionHandle_t sess_hdl", //:: "const int8_t dev_id", //:: "const GroupHandle_t grp", //:: "const MemberHandle_t mbr"] //:: param_str = ", ".join(params) //:: name = act_prof_name + "_deactivate_group_member" //:: pd_name = pd_prefix + name int32_t ${name}(${param_str}) { std::cerr << "In ${name}\n"; return 0; } //:: params = ["const SessionHandle_t sess_hdl", //:: "const int8_t dev_id", //:: "const GroupHandle_t grp", //:: "const MemberHandle_t mbr"] //:: param_str = ", ".join(params) //:: name = act_prof_name + "_reactivate_group_member" //:: pd_name = pd_prefix + name int32_t ${name}(${param_str}) { std::cerr << "In ${name}\n"; return 0; } //:: #endfor //:: for t_name, t in tables.items(): //:: t_type = t.type_ //:: if t_type == TableType.SIMPLE: continue //:: t_name = get_c_name(t_name) //:: match_type = t.match_type //:: has_match_spec = len(t.key) > 0 //:: params = ["const SessionHandle_t sess_hdl", //:: "const DevTarget_t &dev_tgt"] //:: if has_match_spec: //:: params += ["const " + api_prefix + t_name + "_match_spec_t &match_spec"] //:: #endif //:: if match_type in {MatchType.TERNARY, MatchType.RANGE}: //:: params += ["const int32_t priority"] //:: #endif //:: params_wo = params + ["const MemberHandle_t mbr"] //:: param_str = ", ".join(params_wo) //:: name = t_name + "_add_entry" //:: pd_name = pd_prefix + name EntryHandle_t ${name}(${param_str}) { std::cerr << "In ${name}\n"; p4_pd_dev_target_t pd_dev_tgt; pd_dev_tgt.device_id = dev_tgt.dev_id; pd_dev_tgt.dev_pipe_id = dev_tgt.dev_pipe_id; //:: if has_match_spec: ${pd_prefix}${t_name}_match_spec_t pd_match_spec; //:: match_params = gen_match_params(t.key) //:: for name, width in match_params: //:: name = get_c_name(name) //:: if width <= 4: pd_match_spec.${name} = match_spec.${name}; //:: else: memcpy(pd_match_spec.${name}, match_spec.${name}.c_str(), ${width}); //:: #endif //:: #endfor //:: #endif p4_pd_entry_hdl_t pd_entry; //:: pd_params = ["sess_hdl", "pd_dev_tgt"] //:: if has_match_spec: //:: pd_params += ["&pd_match_spec"] //:: #endif //:: if match_type in {MatchType.TERNARY, MatchType.RANGE}: //:: pd_params += ["priority"] //:: #endif //:: pd_params += ["mbr", "&pd_entry"] //:: pd_param_str = ", ".join(pd_params) ${pd_name}(${pd_param_str}); return pd_entry; } //:: if t_type != TableType.INDIRECT_WS: continue //:: params_w = params + ["const GroupHandle_t grp"] //:: param_str = ", ".join(params_w) //:: name = t_name + "_add_entry_with_selector" //:: pd_name = pd_prefix + name EntryHandle_t ${name}(${param_str}) { std::cerr << "In ${name}\n"; p4_pd_dev_target_t pd_dev_tgt; pd_dev_tgt.device_id = dev_tgt.dev_id; pd_dev_tgt.dev_pipe_id = dev_tgt.dev_pipe_id; //:: if has_match_spec: ${pd_prefix}${t_name}_match_spec_t pd_match_spec; //:: match_params = gen_match_params(t.key) //:: for name, width in match_params: //:: name = get_c_name(name) //:: if width <= 4: pd_match_spec.${name} = match_spec.${name}; //:: else: memcpy(pd_match_spec.${name}, match_spec.${name}.c_str(), ${width}); //:: #endif //:: #endfor //:: #endif p4_pd_entry_hdl_t pd_entry; //:: pd_params = ["sess_hdl", "pd_dev_tgt"] //:: if has_match_spec: //:: pd_params += ["&pd_match_spec"] //:: #endif //:: if match_type in {MatchType.TERNARY, MatchType.RANGE}: //:: pd_params += ["priority"] //:: #endif //:: pd_params += ["grp", "&pd_entry"] //:: pd_param_str = ", ".join(pd_params) ${pd_name}(${pd_param_str}); return pd_entry; } //:: #endfor //:: for t_name, t in tables.items(): //:: t_type = t.type_ //:: if t_type == TableType.SIMPLE: continue //:: t_name = get_c_name(t_name) //:: params = ["const SessionHandle_t sess_hdl", //:: "const DevTarget_t &dev_tgt"] //:: params_wo = params + ["const MemberHandle_t mbr"] //:: param_str = ", ".join(params_wo) //:: name = t_name + "_set_default_entry" //:: pd_name = pd_prefix + name int32_t ${name}(${param_str}) { std::cerr << "In ${name}\n"; p4_pd_dev_target_t pd_dev_tgt; pd_dev_tgt.device_id = dev_tgt.dev_id; pd_dev_tgt.dev_pipe_id = dev_tgt.dev_pipe_id; p4_pd_entry_hdl_t pd_entry; //:: pd_params = ["sess_hdl", "pd_dev_tgt"] //:: pd_params += ["mbr", "&pd_entry"] //:: pd_param_str = ", ".join(pd_params) ${pd_name}(${pd_param_str}); return pd_entry; } //:: if t_type != TableType.INDIRECT_WS: continue //:: params_w = params + ["const GroupHandle_t grp"] //:: param_str = ", ".join(params_w) //:: name = t_name + "_set_default_entry_with_selector" //:: pd_name = pd_prefix + name int32_t ${name}(${param_str}) { std::cerr << "In ${name}\n"; p4_pd_dev_target_t pd_dev_tgt; pd_dev_tgt.device_id = dev_tgt.dev_id; pd_dev_tgt.dev_pipe_id = dev_tgt.dev_pipe_id; p4_pd_entry_hdl_t pd_entry; //:: pd_params = ["sess_hdl", "pd_dev_tgt"] //:: pd_params += ["grp", "&pd_entry"] //:: pd_param_str = ", ".join(pd_params) ${pd_name}(${pd_param_str}); return pd_entry; } //:: #endfor // COUNTERS //:: for ca_name, ca in counter_arrays.items(): //:: if ca.is_direct: //:: name = "counter_read_" + ca_name //:: pd_name = pd_prefix + name void ${name}(${api_prefix}counter_value_t &counter_value, const SessionHandle_t sess_hdl, const DevTarget_t &dev_tgt, const EntryHandle_t entry, const ${api_prefix}counter_flags_t &flags) { std::cerr << "In ${name}\n"; p4_pd_dev_target_t pd_dev_tgt; pd_dev_tgt.device_id = dev_tgt.dev_id; pd_dev_tgt.dev_pipe_id = dev_tgt.dev_pipe_id; int pd_flags = 0; if(flags.read_hw_sync) pd_flags |= COUNTER_READ_HW_SYNC; p4_pd_counter_value_t value = ${pd_name}(sess_hdl, pd_dev_tgt, entry, pd_flags); counter_value.packets = value.packets; counter_value.bytes = value.bytes; } //:: name = "counter_write_" + ca_name //:: pd_name = pd_prefix + name int32_t ${name}(const SessionHandle_t sess_hdl, const DevTarget_t &dev_tgt, const EntryHandle_t entry, const ${api_prefix}counter_value_t &counter_value) { std::cerr << "In ${name}\n"; p4_pd_dev_target_t pd_dev_tgt; pd_dev_tgt.device_id = dev_tgt.dev_id; pd_dev_tgt.dev_pipe_id = dev_tgt.dev_pipe_id; p4_pd_counter_value_t value; value.packets = counter_value.packets; value.bytes = counter_value.bytes; return ${pd_name}(sess_hdl, pd_dev_tgt, entry, value); } //:: else: //:: name = "counter_read_" + ca_name //:: pd_name = pd_prefix + name void ${name}(${api_prefix}counter_value_t &counter_value, const SessionHandle_t sess_hdl, const DevTarget_t &dev_tgt, const int32_t index, const ${api_prefix}counter_flags_t &flags) { std::cerr << "In ${name}\n"; p4_pd_dev_target_t pd_dev_tgt; pd_dev_tgt.device_id = dev_tgt.dev_id; pd_dev_tgt.dev_pipe_id = dev_tgt.dev_pipe_id; int pd_flags = 0; if(flags.read_hw_sync) pd_flags |= COUNTER_READ_HW_SYNC; p4_pd_counter_value_t value = ${pd_name}(sess_hdl, pd_dev_tgt, index, pd_flags); counter_value.packets = value.packets; counter_value.bytes = value.bytes; } //:: name = "counter_write_" + ca_name //:: pd_name = pd_prefix + name int32_t ${name}(const SessionHandle_t sess_hdl, const DevTarget_t &dev_tgt, const int32_t index, const ${api_prefix}counter_value_t &counter_value) { std::cerr << "In ${name}\n"; p4_pd_dev_target_t pd_dev_tgt; pd_dev_tgt.device_id = dev_tgt.dev_id; pd_dev_tgt.dev_pipe_id = dev_tgt.dev_pipe_id; p4_pd_counter_value_t value; value.packets = counter_value.packets; value.bytes = counter_value.bytes; return ${pd_name}(sess_hdl, pd_dev_tgt, index, value); } //:: #endif //:: #endfor //:: for ca_name, ca in counter_arrays.items(): //:: name = "counter_hw_sync_" + ca_name //:: pd_name = pd_prefix + name int32_t ${name}(const SessionHandle_t sess_hdl, const DevTarget_t &dev_tgt) { p4_pd_dev_target_t pd_dev_tgt; pd_dev_tgt.device_id = dev_tgt.dev_id; pd_dev_tgt.dev_pipe_id = dev_tgt.dev_pipe_id; std::promise<void> promise; auto future = promise.get_future(); struct HwSync { HwSync(std::promise<void> &promise) : promise(promise) { } std::promise<void> &promise; }; // lambda does not capture, so can be used as function pointer auto cb = [](int device_id, void *cookie) { static_cast<HwSync *>(cookie)->promise.set_value(); }; HwSync h(promise); ${pd_name}(sess_hdl, pd_dev_tgt, cb, static_cast<void *>(&h)); future.wait(); return 0; } //:: #endfor // METERS //:: for ma_name, ma in meter_arrays.items(): //:: params = ["const SessionHandle_t sess_hdl", //:: "const DevTarget_t &dev_tgt"] //:: pd_params = ["sess_hdl", "pd_dev_tgt"] //:: if ma.is_direct: //:: params += ["const EntryHandle_t entry"] //:: pd_params += ["entry"] //:: else: //:: params += ["const int32_t index"] //:: pd_params += ["index"] //:: #endif //:: if ma.unit == MeterUnit.PACKETS: //:: params += ["const " + api_prefix + "packets_meter_spec_t &meter_spec"] //:: else: //:: params += ["const " + api_prefix + "bytes_meter_spec_t &meter_spec"] //:: #endif //:: pd_params += ["&pd_meter_spec"] //:: param_str = ", ".join(params) //:: //:: pd_param_str = ", ".join(pd_params) //:: //:: name = "meter_set_" + ma_name //:: pd_name = pd_prefix + name int32_t ${name}(${param_str}) { std::cerr << "In ${name}\n"; p4_pd_dev_target_t pd_dev_tgt; pd_dev_tgt.device_id = dev_tgt.dev_id; pd_dev_tgt.dev_pipe_id = dev_tgt.dev_pipe_id; //:: if ma.unit == MeterUnit.PACKETS: p4_pd_packets_meter_spec_t pd_meter_spec; packets_meter_spec_thrift_to_pd(meter_spec, &pd_meter_spec); //:: else: p4_pd_bytes_meter_spec_t pd_meter_spec; bytes_meter_spec_thrift_to_pd(meter_spec, &pd_meter_spec); //:: #endif return ${pd_name}(${pd_param_str}); } //:: if ma.unit == MeterUnit.PACKETS: //:: params = [api_prefix + "packets_meter_spec_t &meter_spec"] //:: else: //:: params = [api_prefix + "bytes_meter_spec_t &meter_spec"] //:: #endif //:: params += ["const SessionHandle_t sess_hdl", //:: "const DevTarget_t &dev_tgt"] //:: pd_params = ["sess_hdl", "pd_dev_tgt"] //:: if ma.is_direct: //:: params += ["const EntryHandle_t entry"] //:: pd_params += ["entry"] //:: else: //:: params += ["const int32_t index"] //:: pd_params += ["index"] //:: #endif //:: pd_params += ["&pd_meter_spec"] //:: param_str = ", ".join(params) //:: //:: pd_param_str = ", ".join(pd_params) //:: //:: name = "meter_read_" + ma_name //:: pd_name = pd_prefix + name void ${name}(${param_str}) { std::cerr << "In ${name}\n"; p4_pd_dev_target_t pd_dev_tgt; pd_dev_tgt.device_id = dev_tgt.dev_id; pd_dev_tgt.dev_pipe_id = dev_tgt.dev_pipe_id; //:: if ma.unit == MeterUnit.PACKETS: p4_pd_packets_meter_spec_t pd_meter_spec; //:: else: p4_pd_bytes_meter_spec_t pd_meter_spec; //:: #endif p4_pd_status_t status = ${pd_name}(${pd_param_str}); if (status) return; //:: if ma.unit == MeterUnit.PACKETS: packets_meter_spec_pd_to_thrift(pd_meter_spec, &meter_spec); //:: else: bytes_meter_spec_pd_to_thrift(pd_meter_spec, &meter_spec); //:: #endif } //:: #endfor };
32.658784
193
0.603048
liusheng198933
fea473307303994bbc460172efce67143587bf36
44,007
cpp
C++
test/adiar/bdd/test_apply.cpp
logsem/adiar
056c62a37eedcc5a9e46ccc8c235b5aacedebe32
[ "MIT" ]
null
null
null
test/adiar/bdd/test_apply.cpp
logsem/adiar
056c62a37eedcc5a9e46ccc8c235b5aacedebe32
[ "MIT" ]
null
null
null
test/adiar/bdd/test_apply.cpp
logsem/adiar
056c62a37eedcc5a9e46ccc8c235b5aacedebe32
[ "MIT" ]
null
null
null
go_bandit([]() { describe("adiar/bdd/apply.cpp", []() { node_file bdd_F; node_file bdd_T; { // Garbage collect writers to free write-lock node_writer nw_F(bdd_F); nw_F << create_sink(false); node_writer nw_T(bdd_T); nw_T << create_sink(true); } ptr_t sink_T = create_sink_ptr(true); ptr_t sink_F = create_sink_ptr(false); node_file bdd_x0; node_file bdd_not_x0; node_file bdd_x1; node_file bdd_x2; { // Garbage collect writers early node_writer nw_x0(bdd_x0); nw_x0 << create_node(0,MAX_ID, sink_F, sink_T); node_writer nw_not_x0(bdd_not_x0); nw_not_x0 << create_node(0,MAX_ID, sink_T, sink_F); node_writer nw_x1(bdd_x1); nw_x1 << create_node(1,MAX_ID, sink_F, sink_T); node_writer nw_x2(bdd_x2); nw_x2 << create_node(2,MAX_ID, sink_F, sink_T); } node_file bdd_1; /* 1 ---- x0 / \ | 2 ---- x1 |/ \ 3 4 ---- x2 / \ / \ F T T 5 ---- x3 / \ F T */ node_t n1_5 = create_node(3,MAX_ID, sink_F, sink_T); node_t n1_4 = create_node(2,MAX_ID, sink_T, n1_5.uid); node_t n1_3 = create_node(2,MAX_ID-1, sink_F, sink_T); node_t n1_2 = create_node(1,MAX_ID, n1_3.uid, n1_4.uid); node_t n1_1 = create_node(0,MAX_ID, n1_3.uid, n1_2.uid); { // Garbage collect early and free write-lock node_writer nw_1(bdd_1); nw_1 << n1_5 << n1_4 << n1_3 << n1_2 << n1_1; } node_file bdd_2; /* ---- x0 1 ---- x1 / \ | T ---- x2 | 2 ---- x3 / \ T F */ node_t n2_2 = create_node(3,MAX_ID, sink_T, sink_F); node_t n2_1 = create_node(1,MAX_ID, n2_2.uid, sink_T); { // Garbage collect early and free write-lock node_writer nw_2(bdd_2); nw_2 << n2_2 << n2_1; } node_file bdd_3; /* 1 ---- x0 / \ 2 3 ---- x1 _/ X \_ | _/ \_ | X X / \ / \ 4 5 6 7 ---- x2 / \/ \/ \/ \ F T 8 T F ---- x3 / \ F T */ node_t n3_8 = create_node(3,MAX_ID, sink_F, sink_T); node_t n3_7 = create_node(2,MAX_ID, sink_T, sink_F); node_t n3_6 = create_node(2,MAX_ID - 1, n3_8.uid, sink_T); node_t n3_5 = create_node(2,MAX_ID - 2, sink_T, n3_8.uid); node_t n3_4 = create_node(2,MAX_ID - 3, sink_F, sink_T); node_t n3_3 = create_node(1,MAX_ID, n3_4.uid, n3_6.uid); node_t n3_2 = create_node(1,MAX_ID - 1, n3_5.uid, n3_7.uid); node_t n3_1 = create_node(0,MAX_ID, n3_2.uid, n3_3.uid); { // Garbage collect early and free write-lock node_writer nw_3(bdd_3); nw_3 << n3_8 << n3_7 << n3_6 << n3_5 << n3_4 << n3_3 << n3_2 << n3_1; } /* The product construction of bbd_1 and bdd_2 above is as follows in sorted order. (1,1) ---- x0 \_ _/ _X_ // Match in fst, but not coordinatewise / \ (3,1) (2,1) ---- x1 / \_ _/ \ / X \ /_______/ \ \ | \ \ (3,2) (3,T) (4,T) ---- x2 \ \ / \ / \ \ \ (F,T) (T,T) / \ \________ ___________/ \________ X________ X_________\ _______ / \ \ / \ \ (5,T) (F,2) (T,2) ---- x3 / \ / \ / \ (F,T) (T,T) (F,T)(F,F) (T,T)(T,F) */ describe("bdd_and(f,g)", [&]() { it("should resolve F /\\ T sink-only BDDs", [&]() { __bdd out = bdd_and(bdd_F, bdd_T); node_test_stream out_nodes(out); AssertThat(out_nodes.can_pull(), Is().True()); AssertThat(out_nodes.pull(), Is().EqualTo(create_sink(false))); AssertThat(out_nodes.can_pull(), Is().False()); AssertThat(out.get<node_file>().meta_size(), Is().EqualTo(0u)); }); it("should resolve T /\\ T sink-only BDDs", [&]() { __bdd out = bdd_and(bdd_T, bdd_T); node_test_stream out_nodes(out); AssertThat(out_nodes.can_pull(), Is().True()); AssertThat(out_nodes.pull(), Is().EqualTo(create_sink(true))); AssertThat(out_nodes.can_pull(), Is().False()); AssertThat(out.get<node_file>().meta_size(), Is().EqualTo(0u)); }); it("should shortcut on irrelevance on x0 /\\ T", [&]() { __bdd out = bdd_and(bdd_x0, bdd_T); AssertThat(out.get<node_file>()._file_ptr, Is().EqualTo(bdd_x0._file_ptr)); AssertThat(out.negate, Is().False()); }); it("should shortcut F /\\ x0", [&]() { __bdd out = bdd_and(bdd_F, bdd_x0); node_test_stream out_nodes(out); AssertThat(out_nodes.can_pull(), Is().True()); AssertThat(out_nodes.pull(), Is().EqualTo(create_sink(false))); AssertThat(out_nodes.can_pull(), Is().False()); AssertThat(out.get<node_file>().meta_size(), Is().EqualTo(0u)); }); it("should x0 and !x0", [&]() { /* 1 ---- x0 / \ F F */ __bdd out = bdd_and(bdd_x0, bdd_not_x0); node_arc_test_stream node_arcs(out); AssertThat(node_arcs.can_pull(), Is().False()); sink_arc_test_stream sink_arcs(out); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(0,0), sink_F })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(0,0)), sink_F })); AssertThat(sink_arcs.can_pull(), Is().False()); level_info_test_stream<arc_t> level_info(out); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(0,1u))); AssertThat(level_info.can_pull(), Is().False()); }); it("should shortcut F /\\ [2]", [&]() { __bdd out = bdd_and(bdd_F, bdd_2); node_test_stream out_nodes(out); AssertThat(out_nodes.can_pull(), Is().True()); AssertThat(out_nodes.pull(), Is().EqualTo(create_sink(false))); AssertThat(out_nodes.can_pull(), Is().False()); AssertThat(out.get<node_file>().meta_size(), Is().EqualTo(0u)); }); it("should compute (and shortcut) BBD 1 /\\ [2]", [&]() { /* 1 ---- x0 X / \ 2 3 ---- x1 / \ / \ / X \ /___/ \ \ / | \ 4 5 6 ---- x2 / \ / \_ _/ \ F 7 F T 8 ---- x3 / \ / \ T F F T */ __bdd out = bdd_and(bdd_1, bdd_2); node_arc_test_stream node_arcs(out); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(0,0)), create_node_ptr(1,0) })); AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(0,0), create_node_ptr(1,1) })); AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(1,0), create_node_ptr(2,0) })); AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(1,1), create_node_ptr(2,0) })); AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(1,1)), create_node_ptr(2,1) })); AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(1,0)), create_node_ptr(2,2) })); AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(2,2)), create_node_ptr(3,0) })); AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(2,0)), create_node_ptr(3,1) })); AssertThat(node_arcs.can_pull(), Is().False()); sink_arc_test_stream sink_arcs(out); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(2,0), sink_F })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(2,1), sink_F })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(2,1)), sink_T })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(2,2), sink_T })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(3,0), sink_F })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(3,0)), sink_T })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(3,1), sink_T })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(3,1)), sink_F })); AssertThat(sink_arcs.can_pull(), Is().False()); level_info_test_stream<arc_t> level_info(out); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(0,1u))); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(1,2u))); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(2,3u))); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(3,2u))); AssertThat(level_info.can_pull(), Is().False()); }); it("should return input on being given the same BDD twice", [&]() { __bdd out = bdd_and(bdd_1, bdd_1); AssertThat(out.get<node_file>()._file_ptr, Is().EqualTo(bdd_1._file_ptr)); AssertThat(out.negate, Is().False()); }); it("should group all recursion requests together", [&]() { // This is a counter-example to the prior "break ties on fst() with // snd()" approach. Here we will have three requests to the level of // x2, but in the following order: // // [((2,0),(2,1)), ((2,1),(2,0)), ((2,0),(2,1))] // // which all are tied, and hence the prior version would create // three nodes on this level rather than just two. /* 1 ---- x0 / \ 2 | ---- x1 / \| 3 4 ---- x2 / \\/ \ T F T */ // The second version is the same but has the nodes 3 and 4 mirrored // and the T sinks are replaced with an arc to a node for x3. node_file bdd_group_1, bdd_group_2; { // Garbage collect writers to free write-lock node_writer w1(bdd_group_1); w1 << create_node(2,1, create_sink_ptr(false), create_sink_ptr(true)) << create_node(2,0, create_sink_ptr(true), create_sink_ptr(false)) << create_node(1,0, create_node_ptr(2,0), create_node_ptr(2,1)) << create_node(0,1, create_node_ptr(1,0), create_node_ptr(2,1)); node_writer w2(bdd_group_2); w2 << create_node(3,0, create_sink_ptr(false), create_sink_ptr(true)) << create_node(2,1, create_node_ptr(3,0), create_sink_ptr(false)) << create_node(2,0, create_sink_ptr(false), create_node_ptr(3,0)) << create_node(1,0, create_node_ptr(2,1), create_node_ptr(2,0)) << create_node(0,1, create_node_ptr(1,0), create_node_ptr(2,0)); } __bdd out = bdd_and(bdd_group_1, bdd_group_2); node_arc_test_stream node_arcs(out); AssertThat(node_arcs.can_pull(), Is().True()); // (2,2) AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(0,0), create_node_ptr(1,0) })); AssertThat(node_arcs.can_pull(), Is().True()); // (3,4) AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(1,0), create_node_ptr(2,0) })); AssertThat(node_arcs.can_pull(), Is().True()); // (4,3) AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(0,0)), create_node_ptr(2,1) })); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(1,0)), create_node_ptr(2,1) })); AssertThat(node_arcs.can_pull(), Is().True()); // (T,5) i.e. the added node AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(2,0), create_node_ptr(3,0) })); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(2,1)), create_node_ptr(3,0) })); AssertThat(node_arcs.can_pull(), Is().False()); sink_arc_test_stream sink_arcs(out); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(2,0)), sink_F })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(2,1), sink_F })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(3,0), sink_F })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(3,0)), sink_T })); AssertThat(sink_arcs.can_pull(), Is().False()); level_info_test_stream<arc_t> level_info(out); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(0,1u))); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(1,1u))); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(2,2u))); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(3,1u))); AssertThat(level_info.can_pull(), Is().False()); }); }); describe("bdd_nand(f,g)", [&]() { it("should shortcut on negating on T and x0", [&]() { __bdd out = bdd_nand(bdd_x0, bdd_T); AssertThat(out.get<node_file>()._file_ptr, Is().EqualTo(bdd_x0._file_ptr)); AssertThat(out.negate, Is().True()); }); it("should shortcut on negating on T and x0", [&]() { __bdd out = bdd_nand(bdd_x0, bdd_T); AssertThat(out.get<node_file>()._file_ptr, Is().EqualTo(bdd_x0._file_ptr)); AssertThat(out.negate, Is().True()); }); it("should collapse on the same BDD twice, where one is negated [1]", [&]() { __bdd out = bdd_nand(bdd_2, bdd_not(bdd_2)); node_test_stream out_nodes(out); AssertThat(out_nodes.can_pull(), Is().True()); AssertThat(out_nodes.pull(), Is().EqualTo(create_sink(true))); AssertThat(out_nodes.can_pull(), Is().False()); AssertThat(out.get<node_file>().meta_size(), Is().EqualTo(0u)); }); }); describe("bdd_or(f,g)", [&]() { it("should resolve T \\/ F sink-only BDDs", [&]() { __bdd out = bdd_or(bdd_T, bdd_F); node_test_stream out_nodes(out); AssertThat(out_nodes.can_pull(), Is().True()); AssertThat(out_nodes.pull(), Is().EqualTo(create_sink(true))); AssertThat(out_nodes.can_pull(), Is().False()); AssertThat(out.get<node_file>().meta_size(), Is().EqualTo(0u)); }); it("should resolve T \\/ F sink-only BDDs", [&]() { __bdd out = bdd_or(bdd_F, bdd_F); node_test_stream out_nodes(out); AssertThat(out_nodes.can_pull(), Is().True()); AssertThat(out_nodes.pull(), Is().EqualTo(create_sink(false))); AssertThat(out_nodes.can_pull(), Is().False()); AssertThat(out.get<node_file>().meta_size(), Is().EqualTo(0u)); }); it("should shortcut on irrelevance on x0 \\/ F", [&]() { __bdd out = bdd_or(bdd_x0, bdd_F); AssertThat(out.get<node_file>()._file_ptr, Is().EqualTo(bdd_x0._file_ptr)); AssertThat(out.negate, Is().False()); }); it("should OR shortcut on irrelevance F \\/ x0", [&]() { __bdd out = bdd_or(bdd_F, bdd_x0); AssertThat(out.get<node_file>()._file_ptr, Is().EqualTo(bdd_x0._file_ptr)); AssertThat(out.negate, Is().False()); }); it("should shortcut on x0 \\/ x2", [&]() { /* 1 ---- x0 / \ | T | 2 ---- x2 / \ F T */ __bdd out = bdd_or(bdd_x0, bdd_x2); node_arc_test_stream node_arcs(out); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(0,0), create_node_ptr(2,0) })); AssertThat(node_arcs.can_pull(), Is().False()); sink_arc_test_stream sink_arcs(out); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(0,0)), sink_T })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(2,0), sink_F })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(2,0)), sink_T })); AssertThat(sink_arcs.can_pull(), Is().False()); level_info_test_stream<arc_t> level_info(out); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(0,1u))); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(2,1u))); AssertThat(level_info.can_pull(), Is().False()); }); it("should shortcut [1] \\/ T", [&]() { __bdd out = bdd_or(bdd_1, bdd_T); node_test_stream out_nodes(out); AssertThat(out_nodes.can_pull(), Is().True()); AssertThat(out_nodes.pull(), Is().EqualTo(create_sink(true))); AssertThat(out_nodes.can_pull(), Is().False()); AssertThat(out.get<node_file>().meta_size(), Is().EqualTo(0u)); }); it("should compute (and shortcut) [2] \\/ T", [&]() { __bdd out = bdd_or(bdd_2, bdd_T); node_test_stream out_nodes(out); AssertThat(out_nodes.can_pull(), Is().True()); AssertThat(out_nodes.pull(), Is().EqualTo(create_sink(true))); AssertThat(out_nodes.can_pull(), Is().False()); AssertThat(out.get<node_file>().meta_size(), Is().EqualTo(0u)); }); it("should compute (and shortcut) [1] \\/ [2]", [&]() { /* 1 ---- x0 / \ 2 3 ---- x1 / \ / \ | T | T \_ _/ 4 ---- x2 / \ 5 T ---- x3 / \ T F */ __bdd out = bdd_or(bdd_1, bdd_2); node_arc_test_stream node_arcs(out); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(0,0)), create_node_ptr(1,0) })); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(0,0), create_node_ptr(1,1) })); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(1,0), create_node_ptr(2,0) })); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(1,1), create_node_ptr(2,0) })); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(2,0), create_node_ptr(3,0) })); AssertThat(node_arcs.can_pull(), Is().False()); sink_arc_test_stream sink_arcs(out); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(1,0)), sink_T })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(1,1)), sink_T })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(2,0)), sink_T })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(3,0), sink_T })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(3,0)), sink_F })); AssertThat(sink_arcs.can_pull(), Is().False()); level_info_test_stream<arc_t> level_info(out); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(0,1u))); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(1,2u))); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(2,1u))); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(3,1u))); AssertThat(level_info.can_pull(), Is().False()); }); }); describe("bdd_nor(f,g)", [&]() { it("should collapse on the same BDD twice to a sink, where one is negated [2]", [&]() { __bdd out = bdd_nor(bdd_not(bdd_3), bdd_3); node_test_stream out_nodes(out); AssertThat(out_nodes.can_pull(), Is().True()); AssertThat(out_nodes.pull(), Is().EqualTo(create_sink(false))); AssertThat(out_nodes.can_pull(), Is().False()); AssertThat(out.get<node_file>().meta_size(), Is().EqualTo(0u)); }); }); describe("bdd_xor(f,g)", [&]() { it("should resolve F ^ T sink-only BDDs", [&]() { __bdd out = bdd_xor(bdd_F, bdd_T); node_test_stream out_nodes(out); AssertThat(out_nodes.can_pull(), Is().True()); AssertThat(out_nodes.pull(), Is().EqualTo(create_sink(true))); AssertThat(out_nodes.can_pull(), Is().False()); AssertThat(out.get<node_file>().meta_size(), Is().EqualTo(0u)); }); it("should resolve T ^ T sink-only BDDs", [&]() { __bdd out = bdd_xor(bdd_T, bdd_T); node_test_stream out_nodes(out); AssertThat(out_nodes.can_pull(), Is().True()) ; AssertThat(out_nodes.pull(), Is().EqualTo(create_sink(false))); AssertThat(out_nodes.can_pull(), Is().False()); AssertThat(out.get<node_file>().meta_size(), Is().EqualTo(0u)); }); it("should shortcut on negating on x0 ^ T", [&]() { __bdd out = bdd_xor(bdd_x0, bdd_T); AssertThat(out.get<node_file>()._file_ptr, Is().EqualTo(bdd_x0._file_ptr)); AssertThat(out.negate, Is().True()); }); it("should shortcut on negating on T ^ x0", [&]() { __bdd out = bdd_xor(bdd_x0, bdd_T); AssertThat(out.get<node_file>()._file_ptr, Is().EqualTo(bdd_x0._file_ptr)); AssertThat(out.negate, Is().True()); }); it("should compute x0 ^ x1", [&]() { /* The order on the leaves are due to the sorting of sink requests after evaluating x0 1 ---- x0 / \ 2 3 ---- x1 / \ / \ F T T F */ __bdd out = bdd_xor(bdd_x0, bdd_x1); node_arc_test_stream node_arcs(out); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(0,0), create_node_ptr(1,0) })); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(0,0)), create_node_ptr(1,1) })); AssertThat(node_arcs.can_pull(), Is().False()); sink_arc_test_stream sink_arcs(out); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(1,0), sink_F })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(1,0)), sink_T })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(1,1), sink_T })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(1,1)), sink_F })); AssertThat(sink_arcs.can_pull(), Is().False()); level_info_test_stream<arc_t> level_info(out); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(0,1u))); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(1,2u))); AssertThat(level_info.can_pull(), Is().False()); }); it("should compute [2] ^ x2", [&]() { /* ---- x0 (1,1) ---- x1 / \ (2,1) (T,1) ---- x2 / \ / \ / \ T F | | (2,F) (2,T) ---- x3 / \ / \ T F F T */ __bdd out = bdd_xor(bdd_2, bdd_x2); node_arc_test_stream node_arcs(out); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(1,0), create_node_ptr(2,0) })); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(1,0)), create_node_ptr(2,1) })); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(2,0), create_node_ptr(3,0) })); AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(2,0)), create_node_ptr(3,1) })); AssertThat(node_arcs.can_pull(), Is().False()); sink_arc_test_stream sink_arcs(out); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(2,1), sink_T })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(2,1)), sink_F })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(3,0), sink_T })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(3,0)), sink_F })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(3,1), sink_F })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(3,1)), sink_T })); AssertThat(sink_arcs.can_pull(), Is().False()); level_info_test_stream<arc_t> level_info(out); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(1,1u))); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(2,2u))); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(3,2u))); AssertThat(level_info.can_pull(), Is().False()); }); it("should compute [1] ^ [2]", [&]() { /* There is no shortcutting possible on an XOR, so see the product construction above. */ __bdd out = bdd_xor(bdd_1, bdd_2); node_arc_test_stream node_arcs(out); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(0,0)), create_node_ptr(1,0) })); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(0,0), create_node_ptr(1,1) })); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(1,0), create_node_ptr(2,0) })); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(1,1), create_node_ptr(2,0) })); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(1,1)), create_node_ptr(2,1) })); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(1,0)), create_node_ptr(2,2) })); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(2,2)), create_node_ptr(3,0) })); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(2,0), create_node_ptr(3,1) })); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(2,0)), create_node_ptr(3,2) })); AssertThat(node_arcs.can_pull(), Is().False()); sink_arc_test_stream sink_arcs(out); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(2,1), sink_T })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(2,1)), sink_F })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(2,2), sink_F })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(3,0), sink_T })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(3,0)), sink_F })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(3,1), sink_T })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(3,1)), sink_F })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(3,2), sink_F })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(3,2)), sink_T })); AssertThat(sink_arcs.can_pull(), Is().False()); level_info_test_stream<arc_t> level_info(out); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(0,1u))); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(1,2u))); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(2,3u))); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(3,3u))); AssertThat(level_info.can_pull(), Is().False()); }); it("should compute [3] ^ [1]", [&]() { /* The queue appD_data is used to forward data across the level. When [1] and 3 are combined, this is needed The product between the [3] and [1] then is (1,1) ---- x0 ________/ \_______ / \ (2,3) (3,2) ---- x1 / \_________ ________/ \ | X | // (5,3) (7,3) (4,3) (6,4) \__ _________/ \__________ / // min: 0 0 0 1 ___X___ X // max: 1 3 0 2 / \ _____/ \ // coord: 2 3 1 4 / \ / \ (4,3) (5,3) (6,4) (7,3) ---- x2 / \ / \ / \ / \ (F,F) (T,T) (T,F) | / \ (T,F) (F,T) | / \ | / | |/ | (8,T) (T,5) ---- x3 / \ / \ (F,T) (T,T) (T,F) (T,T) */ __bdd out = bdd_xor(bdd_3, bdd_1); node_arc_test_stream node_arcs(out); AssertThat(node_arcs.can_pull(), Is().True()); // (2,3) AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(0,0), create_node_ptr(1,0) })); AssertThat(node_arcs.can_pull(), Is().True()); // (3,2) AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(0,0)), create_node_ptr(1,1) })); AssertThat(node_arcs.can_pull(), Is().True()); // (4,3) AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(1,1), create_node_ptr(2,0) })); AssertThat(node_arcs.can_pull(), Is().True()); // (5,3) AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(1,0), create_node_ptr(2,1) })); AssertThat(node_arcs.can_pull(), Is().True()); // (6,4) AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(1,1)), create_node_ptr(2,2) })); AssertThat(node_arcs.can_pull(), Is().True()); // (7,3) AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(1,0)), create_node_ptr(2,3) })); AssertThat(node_arcs.can_pull(), Is().True()); // (8,T) AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(2,1)), create_node_ptr(3,0) })); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(2,2), create_node_ptr(3,0) })); AssertThat(node_arcs.can_pull(), Is().True()); // (T,5) AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(2,2)), create_node_ptr(3,1) })); AssertThat(node_arcs.can_pull(), Is().False()); sink_arc_test_stream sink_arcs(out); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(2,0), sink_F })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(2,0)), sink_F })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(2,1), sink_T })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(2,3), sink_T })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(2,3)), sink_T })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(3,0), sink_T })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(3,0)), sink_F })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(3,1), sink_T })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(3,1)), sink_F })); AssertThat(sink_arcs.can_pull(), Is().False()); level_info_test_stream<arc_t> level_info(out); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(0,1u))); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(1,2u))); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(2,4u))); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(3,2u))); AssertThat(level_info.can_pull(), Is().False()); }); it("should collapse on the same BDD twice", [&]() { __bdd out = bdd_xor(bdd_1, bdd_1); node_test_stream out_nodes(out); AssertThat(out_nodes.can_pull(), Is().True()); AssertThat(out_nodes.pull(), Is().EqualTo(create_sink(false))); AssertThat(out_nodes.can_pull(), Is().False()); AssertThat(out.get<node_file>().meta_size(), Is().EqualTo(0u)); }); it("should collapse on the same BDD twice to a sink, when both are negated", [&]() { __bdd out = bdd_xor(bdd_not(bdd_1), bdd_not(bdd_1)); node_test_stream out_nodes(out); AssertThat(out_nodes.can_pull(), Is().True()); AssertThat(out_nodes.pull(), Is().EqualTo(create_sink(false))); AssertThat(out_nodes.can_pull(), Is().False()); AssertThat(out.get<node_file>().meta_size(), Is().EqualTo(0u)); }); }); describe("bdd_xnor(f,g)", [&]() { // TODO }); describe("bdd_imp(f,g)", [&]() { it("should resolve F -> T sink-only BDDs", [&]() { __bdd out = bdd_imp(bdd_F, bdd_T); node_test_stream out_nodes(out); AssertThat(out_nodes.can_pull(), Is().True()); AssertThat(out_nodes.pull(), Is().EqualTo(create_sink(true))); AssertThat(out_nodes.can_pull(), Is().False()); AssertThat(out.get<node_file>().meta_size(), Is().EqualTo(0u)); }); it("should resolve T -> F sink-only BDDs", [&]() { __bdd out = bdd_imp(bdd_T, bdd_F); node_test_stream out_nodes(out); AssertThat(out_nodes.can_pull(), Is().True()); AssertThat(out_nodes.pull(), Is().EqualTo(create_sink(false))); AssertThat(out_nodes.can_pull(), Is().False()); AssertThat(out.get<node_file>().meta_size(), Is().EqualTo(0u)); }); it("should resolve T -> T sink-only BDDs", [&]() { __bdd out = bdd_imp(bdd_T, bdd_T); node_test_stream out_nodes(out); AssertThat(out_nodes.can_pull(), Is().True()); AssertThat(out_nodes.pull(), Is().EqualTo(create_sink(true))); AssertThat(out_nodes.can_pull(), Is().False()); AssertThat(out.get<node_file>().meta_size(), Is().EqualTo(0u)); }); it("should shortcut on irrelevance on T -> x0", [&]() { __bdd out = bdd_imp(bdd_T, bdd_x0); AssertThat(out.get<node_file>()._file_ptr, Is().EqualTo(bdd_x0._file_ptr)); AssertThat(out.negate, Is().False()); }); it("should shortcut on x0 -> x1", [&]() { /* The order on the leaves are due to the sorting of sink requests after evaluating x0 1 ---- x0 / \ T 2 ---- x1 / \ F T */ __bdd out = bdd_imp(bdd_x0, bdd_x1); node_arc_test_stream node_arcs(out); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(0,0)), create_node_ptr(1,0) })); AssertThat(node_arcs.can_pull(), Is().False()); sink_arc_test_stream sink_arcs(out); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(0,0), sink_T })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(1,0), sink_F })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(1,0)), sink_T })); AssertThat(sink_arcs.can_pull(), Is().False()); level_info_test_stream<arc_t> level_info(out); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(0,1u))); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(1,1u))); AssertThat(level_info.can_pull(), Is().False()); }); it("should shortcut F -> [1]", [&]() { __bdd out = bdd_imp(bdd_F, bdd_1); node_test_stream out_nodes(out); AssertThat(out_nodes.can_pull(), Is().True()); AssertThat(out_nodes.pull(), Is().EqualTo(create_sink(true))); AssertThat(out_nodes.can_pull(), Is().False()); AssertThat(out.get<node_file>().meta_size(), Is().EqualTo(0u)); }); it("should return the input when given the same BDD twice, where one is negated [1]", [&]() { __bdd out = bdd_imp(bdd_not(bdd_2), bdd_2); AssertThat(out.get<node_file>()._file_ptr, Is().EqualTo(bdd_2._file_ptr)); AssertThat(out.negate, Is().False()); // negated the already negated input doubly-negating }); it("should return input when given the same BDD twice, where one is negated [2]", [&]() { __bdd out = bdd_imp(bdd_2, bdd_not(bdd_2)); AssertThat(out.get<node_file>()._file_ptr, Is().EqualTo(bdd_2._file_ptr)); AssertThat(out.negate, Is().True()); // negated the first of the two }); }); describe("bdd_invimp(f,g)", [&]() { // TODO }); describe("bdd_equiv(f,g)", [&]() { // TODO }); describe("bdd_diff(f,g)", [&]() { // TODO }); describe("bdd_less(f,g)", [&]() { // TODO }); }); });
38.101299
111
0.547686
logsem
fea4ae8e6c63cf0b41b62212f9740569d2c8b344
1,382
cpp
C++
MVJ_Engine_base/ComponentLight.cpp
expelthegrace/ThomasTheEngine
d570c9746725e3f8232753799cce90cdc47a4b48
[ "Unlicense" ]
null
null
null
MVJ_Engine_base/ComponentLight.cpp
expelthegrace/ThomasTheEngine
d570c9746725e3f8232753799cce90cdc47a4b48
[ "Unlicense" ]
null
null
null
MVJ_Engine_base/ComponentLight.cpp
expelthegrace/ThomasTheEngine
d570c9746725e3f8232753799cce90cdc47a4b48
[ "Unlicense" ]
null
null
null
#include "ComponentLight.h" #include "GameObject.h" #include "ComponentTransform.h" #include "ModuleScene.h" #include "Application.h" #include "debugdraw.h" #include "JSONManager.h" ComponentLight::ComponentLight(GameObject * my_go) { this->my_go = my_go; this->type = LIGHT; if (App->scene->mainLight == nullptr) App->scene->mainLight = this; } ComponentLight::~ComponentLight() { my_go = nullptr; } update_status ComponentLight::Update() { position = my_go->transform->globalPosition; //direction = (my_go->transform->rotation * initialDirection).Normalized(); colorLight_Intensity = float3(colorLight.x * intensity, colorLight.y * intensity, colorLight.z * intensity); const ddVec3 boxColor = { 0.f, 0.6f, 0.8f }; dd::sphere(position, boxColor, 0.4 * App->GameScale); return UPDATE_CONTINUE; } void ComponentLight::Reset() { colorLight = { 0.5f, 0.5f, 0.5f }; intensity = 1.f; } void ComponentLight::Save(JSON_Value* componentsJSON) { JSON_Value* componentJSON = componentsJSON->createValue(); componentJSON->addInt("Type", type); componentJSON->addVector3("colorLight", colorLight); componentJSON->addFloat("Intensity", intensity); componentsJSON->addValue("Light", componentJSON); } void ComponentLight::Load(JSON_Value* componentJSON) { colorLight = componentJSON->getVector3("colorLight"); intensity = componentJSON->getFloat("Intensity"); }
26.075472
109
0.736614
expelthegrace
fea56f27d43c67c9ccb569e6d805f3364226f565
16,573
cc
C++
quiche/http2/test_tools/http2_frame_decoder_listener_test_util.cc
ktprime/quiche-1
abf85ce22e1409a870b1bf470cb5a68cbdb28e50
[ "BSD-3-Clause" ]
null
null
null
quiche/http2/test_tools/http2_frame_decoder_listener_test_util.cc
ktprime/quiche-1
abf85ce22e1409a870b1bf470cb5a68cbdb28e50
[ "BSD-3-Clause" ]
null
null
null
quiche/http2/test_tools/http2_frame_decoder_listener_test_util.cc
ktprime/quiche-1
abf85ce22e1409a870b1bf470cb5a68cbdb28e50
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "quiche/http2/test_tools/http2_frame_decoder_listener_test_util.h" #include "quiche/http2/decoder/http2_frame_decoder_listener.h" #include "quiche/http2/http2_constants.h" #include "quiche/http2/http2_structures.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/platform/api/quiche_test.h" namespace http2 { FailingHttp2FrameDecoderListener::FailingHttp2FrameDecoderListener() = default; FailingHttp2FrameDecoderListener::~FailingHttp2FrameDecoderListener() = default; bool FailingHttp2FrameDecoderListener::OnFrameHeader( const Http2FrameHeader& header) { ADD_FAILURE() << "OnFrameHeader: " << header; return false; } void FailingHttp2FrameDecoderListener::OnDataStart( const Http2FrameHeader& header) { FAIL() << "OnDataStart: " << header; } void FailingHttp2FrameDecoderListener::OnDataPayload(const char* /*data*/, size_t len) { FAIL() << "OnDataPayload: len=" << len; } void FailingHttp2FrameDecoderListener::OnDataEnd() { FAIL() << "OnDataEnd"; } void FailingHttp2FrameDecoderListener::OnHeadersStart( const Http2FrameHeader& header) { FAIL() << "OnHeadersStart: " << header; } void FailingHttp2FrameDecoderListener::OnHeadersPriority( const Http2PriorityFields& priority) { FAIL() << "OnHeadersPriority: " << priority; } void FailingHttp2FrameDecoderListener::OnHpackFragment(const char* /*data*/, size_t len) { FAIL() << "OnHpackFragment: len=" << len; } void FailingHttp2FrameDecoderListener::OnHeadersEnd() { FAIL() << "OnHeadersEnd"; } void FailingHttp2FrameDecoderListener::OnPriorityFrame( const Http2FrameHeader& header, const Http2PriorityFields& priority) { FAIL() << "OnPriorityFrame: " << header << "; priority: " << priority; } void FailingHttp2FrameDecoderListener::OnContinuationStart( const Http2FrameHeader& header) { FAIL() << "OnContinuationStart: " << header; } void FailingHttp2FrameDecoderListener::OnContinuationEnd() { FAIL() << "OnContinuationEnd"; } void FailingHttp2FrameDecoderListener::OnPadLength(size_t trailing_length) { FAIL() << "OnPadLength: trailing_length=" << trailing_length; } void FailingHttp2FrameDecoderListener::OnPadding(const char* /*padding*/, size_t skipped_length) { FAIL() << "OnPadding: skipped_length=" << skipped_length; } void FailingHttp2FrameDecoderListener::OnRstStream( const Http2FrameHeader& header, Http2ErrorCode error_code) { FAIL() << "OnRstStream: " << header << "; code=" << error_code; } void FailingHttp2FrameDecoderListener::OnSettingsStart( const Http2FrameHeader& header) { FAIL() << "OnSettingsStart: " << header; } void FailingHttp2FrameDecoderListener::OnSetting( const Http2SettingFields& setting_fields) { FAIL() << "OnSetting: " << setting_fields; } void FailingHttp2FrameDecoderListener::OnSettingsEnd() { FAIL() << "OnSettingsEnd"; } void FailingHttp2FrameDecoderListener::OnSettingsAck( const Http2FrameHeader& header) { FAIL() << "OnSettingsAck: " << header; } void FailingHttp2FrameDecoderListener::OnPushPromiseStart( const Http2FrameHeader& header, const Http2PushPromiseFields& promise, size_t total_padding_length) { FAIL() << "OnPushPromiseStart: " << header << "; promise: " << promise << "; total_padding_length: " << total_padding_length; } void FailingHttp2FrameDecoderListener::OnPushPromiseEnd() { FAIL() << "OnPushPromiseEnd"; } void FailingHttp2FrameDecoderListener::OnPing(const Http2FrameHeader& header, const Http2PingFields& ping) { FAIL() << "OnPing: " << header << "; ping: " << ping; } void FailingHttp2FrameDecoderListener::OnPingAck(const Http2FrameHeader& header, const Http2PingFields& ping) { FAIL() << "OnPingAck: " << header << "; ping: " << ping; } void FailingHttp2FrameDecoderListener::OnGoAwayStart( const Http2FrameHeader& header, const Http2GoAwayFields& goaway) { FAIL() << "OnGoAwayStart: " << header << "; goaway: " << goaway; } void FailingHttp2FrameDecoderListener::OnGoAwayOpaqueData(const char* /*data*/, size_t len) { FAIL() << "OnGoAwayOpaqueData: len=" << len; } void FailingHttp2FrameDecoderListener::OnGoAwayEnd() { FAIL() << "OnGoAwayEnd"; } void FailingHttp2FrameDecoderListener::OnWindowUpdate( const Http2FrameHeader& header, uint32_t increment) { FAIL() << "OnWindowUpdate: " << header << "; increment=" << increment; } void FailingHttp2FrameDecoderListener::OnAltSvcStart( const Http2FrameHeader& header, size_t origin_length, size_t value_length) { FAIL() << "OnAltSvcStart: " << header << "; origin_length: " << origin_length << "; value_length: " << value_length; } void FailingHttp2FrameDecoderListener::OnAltSvcOriginData(const char* /*data*/, size_t len) { FAIL() << "OnAltSvcOriginData: len=" << len; } void FailingHttp2FrameDecoderListener::OnAltSvcValueData(const char* /*data*/, size_t len) { FAIL() << "OnAltSvcValueData: len=" << len; } void FailingHttp2FrameDecoderListener::OnAltSvcEnd() { FAIL() << "OnAltSvcEnd"; } void FailingHttp2FrameDecoderListener::OnPriorityUpdateStart( const Http2FrameHeader& header, const Http2PriorityUpdateFields& priority_update) { FAIL() << "OnPriorityUpdateStart: " << header << "; prioritized_stream_id: " << priority_update.prioritized_stream_id; } void FailingHttp2FrameDecoderListener::OnPriorityUpdatePayload( const char* /*data*/, size_t len) { FAIL() << "OnPriorityUpdatePayload: len=" << len; } void FailingHttp2FrameDecoderListener::OnPriorityUpdateEnd() { FAIL() << "OnPriorityUpdateEnd"; } void FailingHttp2FrameDecoderListener::OnUnknownStart( const Http2FrameHeader& header) { FAIL() << "OnUnknownStart: " << header; } void FailingHttp2FrameDecoderListener::OnUnknownPayload(const char* /*data*/, size_t len) { FAIL() << "OnUnknownPayload: len=" << len; } void FailingHttp2FrameDecoderListener::OnUnknownEnd() { FAIL() << "OnUnknownEnd"; } void FailingHttp2FrameDecoderListener::OnPaddingTooLong( const Http2FrameHeader& header, size_t missing_length) { FAIL() << "OnPaddingTooLong: " << header << "; missing_length: " << missing_length; } void FailingHttp2FrameDecoderListener::OnFrameSizeError( const Http2FrameHeader& header) { FAIL() << "OnFrameSizeError: " << header; } LoggingHttp2FrameDecoderListener::LoggingHttp2FrameDecoderListener() : wrapped_(nullptr) {} LoggingHttp2FrameDecoderListener::LoggingHttp2FrameDecoderListener( Http2FrameDecoderListener* wrapped) : wrapped_(wrapped) {} LoggingHttp2FrameDecoderListener::~LoggingHttp2FrameDecoderListener() = default; bool LoggingHttp2FrameDecoderListener::OnFrameHeader( const Http2FrameHeader& header) { QUICHE_VLOG(1) << "OnFrameHeader: " << header; if (wrapped_ != nullptr) { return wrapped_->OnFrameHeader(header); } return true; } void LoggingHttp2FrameDecoderListener::OnDataStart( const Http2FrameHeader& header) { QUICHE_VLOG(1) << "OnDataStart: " << header; if (wrapped_ != nullptr) { wrapped_->OnDataStart(header); } } void LoggingHttp2FrameDecoderListener::OnDataPayload(const char* data, size_t len) { QUICHE_VLOG(1) << "OnDataPayload: len=" << len; if (wrapped_ != nullptr) { wrapped_->OnDataPayload(data, len); } } void LoggingHttp2FrameDecoderListener::OnDataEnd() { QUICHE_VLOG(1) << "OnDataEnd"; if (wrapped_ != nullptr) { wrapped_->OnDataEnd(); } } void LoggingHttp2FrameDecoderListener::OnHeadersStart( const Http2FrameHeader& header) { QUICHE_VLOG(1) << "OnHeadersStart: " << header; if (wrapped_ != nullptr) { wrapped_->OnHeadersStart(header); } } void LoggingHttp2FrameDecoderListener::OnHeadersPriority( const Http2PriorityFields& priority) { QUICHE_VLOG(1) << "OnHeadersPriority: " << priority; if (wrapped_ != nullptr) { wrapped_->OnHeadersPriority(priority); } } void LoggingHttp2FrameDecoderListener::OnHpackFragment(const char* data, size_t len) { QUICHE_VLOG(1) << "OnHpackFragment: len=" << len; if (wrapped_ != nullptr) { wrapped_->OnHpackFragment(data, len); } } void LoggingHttp2FrameDecoderListener::OnHeadersEnd() { QUICHE_VLOG(1) << "OnHeadersEnd"; if (wrapped_ != nullptr) { wrapped_->OnHeadersEnd(); } } void LoggingHttp2FrameDecoderListener::OnPriorityFrame( const Http2FrameHeader& header, const Http2PriorityFields& priority) { QUICHE_VLOG(1) << "OnPriorityFrame: " << header << "; priority: " << priority; if (wrapped_ != nullptr) { wrapped_->OnPriorityFrame(header, priority); } } void LoggingHttp2FrameDecoderListener::OnContinuationStart( const Http2FrameHeader& header) { QUICHE_VLOG(1) << "OnContinuationStart: " << header; if (wrapped_ != nullptr) { wrapped_->OnContinuationStart(header); } } void LoggingHttp2FrameDecoderListener::OnContinuationEnd() { QUICHE_VLOG(1) << "OnContinuationEnd"; if (wrapped_ != nullptr) { wrapped_->OnContinuationEnd(); } } void LoggingHttp2FrameDecoderListener::OnPadLength(size_t trailing_length) { QUICHE_VLOG(1) << "OnPadLength: trailing_length=" << trailing_length; if (wrapped_ != nullptr) { wrapped_->OnPadLength(trailing_length); } } void LoggingHttp2FrameDecoderListener::OnPadding(const char* padding, size_t skipped_length) { QUICHE_VLOG(1) << "OnPadding: skipped_length=" << skipped_length; if (wrapped_ != nullptr) { wrapped_->OnPadding(padding, skipped_length); } } void LoggingHttp2FrameDecoderListener::OnRstStream( const Http2FrameHeader& header, Http2ErrorCode error_code) { QUICHE_VLOG(1) << "OnRstStream: " << header << "; code=" << error_code; if (wrapped_ != nullptr) { wrapped_->OnRstStream(header, error_code); } } void LoggingHttp2FrameDecoderListener::OnSettingsStart( const Http2FrameHeader& header) { QUICHE_VLOG(1) << "OnSettingsStart: " << header; if (wrapped_ != nullptr) { wrapped_->OnSettingsStart(header); } } void LoggingHttp2FrameDecoderListener::OnSetting( const Http2SettingFields& setting_fields) { QUICHE_VLOG(1) << "OnSetting: " << setting_fields; if (wrapped_ != nullptr) { wrapped_->OnSetting(setting_fields); } } void LoggingHttp2FrameDecoderListener::OnSettingsEnd() { QUICHE_VLOG(1) << "OnSettingsEnd"; if (wrapped_ != nullptr) { wrapped_->OnSettingsEnd(); } } void LoggingHttp2FrameDecoderListener::OnSettingsAck( const Http2FrameHeader& header) { QUICHE_VLOG(1) << "OnSettingsAck: " << header; if (wrapped_ != nullptr) { wrapped_->OnSettingsAck(header); } } void LoggingHttp2FrameDecoderListener::OnPushPromiseStart( const Http2FrameHeader& header, const Http2PushPromiseFields& promise, size_t total_padding_length) { QUICHE_VLOG(1) << "OnPushPromiseStart: " << header << "; promise: " << promise << "; total_padding_length: " << total_padding_length; if (wrapped_ != nullptr) { wrapped_->OnPushPromiseStart(header, promise, total_padding_length); } } void LoggingHttp2FrameDecoderListener::OnPushPromiseEnd() { QUICHE_VLOG(1) << "OnPushPromiseEnd"; if (wrapped_ != nullptr) { wrapped_->OnPushPromiseEnd(); } } void LoggingHttp2FrameDecoderListener::OnPing(const Http2FrameHeader& header, const Http2PingFields& ping) { QUICHE_VLOG(1) << "OnPing: " << header << "; ping: " << ping; if (wrapped_ != nullptr) { wrapped_->OnPing(header, ping); } } void LoggingHttp2FrameDecoderListener::OnPingAck(const Http2FrameHeader& header, const Http2PingFields& ping) { QUICHE_VLOG(1) << "OnPingAck: " << header << "; ping: " << ping; if (wrapped_ != nullptr) { wrapped_->OnPingAck(header, ping); } } void LoggingHttp2FrameDecoderListener::OnGoAwayStart( const Http2FrameHeader& header, const Http2GoAwayFields& goaway) { QUICHE_VLOG(1) << "OnGoAwayStart: " << header << "; goaway: " << goaway; if (wrapped_ != nullptr) { wrapped_->OnGoAwayStart(header, goaway); } } void LoggingHttp2FrameDecoderListener::OnGoAwayOpaqueData(const char* data, size_t len) { QUICHE_VLOG(1) << "OnGoAwayOpaqueData: len=" << len; if (wrapped_ != nullptr) { wrapped_->OnGoAwayOpaqueData(data, len); } } void LoggingHttp2FrameDecoderListener::OnGoAwayEnd() { QUICHE_VLOG(1) << "OnGoAwayEnd"; if (wrapped_ != nullptr) { wrapped_->OnGoAwayEnd(); } } void LoggingHttp2FrameDecoderListener::OnWindowUpdate( const Http2FrameHeader& header, uint32_t increment) { QUICHE_VLOG(1) << "OnWindowUpdate: " << header << "; increment=" << increment; if (wrapped_ != nullptr) { wrapped_->OnWindowUpdate(header, increment); } } void LoggingHttp2FrameDecoderListener::OnAltSvcStart( const Http2FrameHeader& header, size_t origin_length, size_t value_length) { QUICHE_VLOG(1) << "OnAltSvcStart: " << header << "; origin_length: " << origin_length << "; value_length: " << value_length; if (wrapped_ != nullptr) { wrapped_->OnAltSvcStart(header, origin_length, value_length); } } void LoggingHttp2FrameDecoderListener::OnAltSvcOriginData(const char* data, size_t len) { QUICHE_VLOG(1) << "OnAltSvcOriginData: len=" << len; if (wrapped_ != nullptr) { wrapped_->OnAltSvcOriginData(data, len); } } void LoggingHttp2FrameDecoderListener::OnAltSvcValueData(const char* data, size_t len) { QUICHE_VLOG(1) << "OnAltSvcValueData: len=" << len; if (wrapped_ != nullptr) { wrapped_->OnAltSvcValueData(data, len); } } void LoggingHttp2FrameDecoderListener::OnAltSvcEnd() { QUICHE_VLOG(1) << "OnAltSvcEnd"; if (wrapped_ != nullptr) { wrapped_->OnAltSvcEnd(); } } void LoggingHttp2FrameDecoderListener::OnPriorityUpdateStart( const Http2FrameHeader& header, const Http2PriorityUpdateFields& priority_update) { QUICHE_VLOG(1) << "OnPriorityUpdateStart"; if (wrapped_ != nullptr) { wrapped_->OnPriorityUpdateStart(header, priority_update); } } void LoggingHttp2FrameDecoderListener::OnPriorityUpdatePayload(const char* data, size_t len) { QUICHE_VLOG(1) << "OnPriorityUpdatePayload"; if (wrapped_ != nullptr) { wrapped_->OnPriorityUpdatePayload(data, len); } } void LoggingHttp2FrameDecoderListener::OnPriorityUpdateEnd() { QUICHE_VLOG(1) << "OnPriorityUpdateEnd"; if (wrapped_ != nullptr) { wrapped_->OnPriorityUpdateEnd(); } } void LoggingHttp2FrameDecoderListener::OnUnknownStart( const Http2FrameHeader& header) { QUICHE_VLOG(1) << "OnUnknownStart: " << header; if (wrapped_ != nullptr) { wrapped_->OnUnknownStart(header); } } void LoggingHttp2FrameDecoderListener::OnUnknownPayload(const char* data, size_t len) { QUICHE_VLOG(1) << "OnUnknownPayload: len=" << len; if (wrapped_ != nullptr) { wrapped_->OnUnknownPayload(data, len); } } void LoggingHttp2FrameDecoderListener::OnUnknownEnd() { QUICHE_VLOG(1) << "OnUnknownEnd"; if (wrapped_ != nullptr) { wrapped_->OnUnknownEnd(); } } void LoggingHttp2FrameDecoderListener::OnPaddingTooLong( const Http2FrameHeader& header, size_t missing_length) { QUICHE_VLOG(1) << "OnPaddingTooLong: " << header << "; missing_length: " << missing_length; if (wrapped_ != nullptr) { wrapped_->OnPaddingTooLong(header, missing_length); } } void LoggingHttp2FrameDecoderListener::OnFrameSizeError( const Http2FrameHeader& header) { QUICHE_VLOG(1) << "OnFrameSizeError: " << header; if (wrapped_ != nullptr) { wrapped_->OnFrameSizeError(header); } } } // namespace http2
32.369141
80
0.679298
ktprime
feac833cbd24d7144743f1757a134c8932f38a2c
64,956
cpp
C++
common/workunit/wujobq.cpp
jeclrsg/HPCC-Platform
c1daafb6060f0c47c95bce98e5431fedc33c592d
[ "Apache-2.0" ]
286
2015-01-03T12:45:17.000Z
2022-03-25T18:12:57.000Z
common/workunit/wujobq.cpp
jeclrsg/HPCC-Platform
c1daafb6060f0c47c95bce98e5431fedc33c592d
[ "Apache-2.0" ]
9,034
2015-01-02T08:49:19.000Z
2022-03-31T20:34:44.000Z
common/workunit/wujobq.cpp
jeclrsg/HPCC-Platform
c1daafb6060f0c47c95bce98e5431fedc33c592d
[ "Apache-2.0" ]
208
2015-01-02T03:27:28.000Z
2022-02-11T05:54:52.000Z
/*############################################################################## HPCC SYSTEMS software Copyright (C) 2012 HPCC Systems®. 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 "platform.h" #include <algorithm> #include "limits.h" #include "jlib.hpp" #include "jbuff.hpp" #include "jsecrets.hpp" #include "dasess.hpp" #include "dautils.hpp" #include "portlist.h" #include "dacoven.hpp" #include "daclient.hpp" #include "dasds.hpp" #include "dasess.hpp" #include "daqueue.hpp" #include "workunit.hpp" #include "wujobq.hpp" #include "securesocket.hpp" #ifndef _CONTAINERIZED #include "environment.hpp" #endif #ifdef _MSC_VER #pragma warning (disable : 4355) #endif #if 0 JobQueues JobQueue @name= @count= @state=active|paused|stopped Edition <num> Client @session= @connected= @waiting= -- connections and waiting can be > 1 (multiple threads) Item* @wuid @owner @node @port @priority @session #endif class CJobQueueItem: implements IJobQueueItem, public CInterface { int priority; StringAttr wu; StringAttr owner; SessionId sessid; SocketEndpoint ep; unsigned port; CDateTime enqueuedt; public: IMPLEMENT_IINTERFACE; CJobQueueItem(MemoryBuffer &src) { deserialize(src); } CJobQueueItem(const char *_wu) : wu(_wu) { priority = 0; ep = queryMyNode()->endpoint(); port = 0; sessid = myProcessSession(); } CJobQueueItem(IPropertyTree *item) { const char * wuid = item->queryProp("@wuid"); if (*wuid=='~') wuid++; wu.set(wuid); owner.set(item->queryProp("@owner")); sessid = (SessionId)item->getPropInt64("@session"); priority = item->getPropInt("@priority"); ep.set(item->queryProp("@node")); port = (unsigned)item->getPropInt("@port"); StringBuffer dts; if (item->getProp("@enqueuedt",dts)) enqueuedt.setString(dts.str()); } static void assignBranch(IPropertyTree *item,IJobQueueItem *qi) { item->setPropInt64("@session",qi->getSessionId()); item->setPropInt("@priority",qi->getPriority()); item->setPropInt("@port",qi->getPort()); item->setProp("@wuid",qi->queryWUID()); item->setProp("@owner",qi->queryOwner()); StringBuffer eps; qi->queryEndpoint().getUrlStr(eps); item->setProp("@node",eps.str()); StringBuffer dts; qi->queryEnqueuedTime().getString(dts); if (dts.length()==0) { CDateTime dt; dt.setNow(); dt.getString(dts); qi->setEnqueuedTime(dt); } item->setProp("@enqueuedt",dts.str()); } const char *queryWUID() { return wu.get(); } int getPriority() { return priority; } unsigned getPort() { return port; } SessionId getSessionId() { return sessid; } SocketEndpoint &queryEndpoint() { return ep; } const char *queryOwner() { return owner.get(); } bool equals(IJobQueueItem *other) { // work unit is primary key return strcmp(wu.get(),other->queryWUID())==0; } CDateTime &queryEnqueuedTime() { return enqueuedt; } void setEnqueuedTime(const CDateTime &dt) { enqueuedt.set(dt); } void serialize(MemoryBuffer &tgt) { tgt.append(priority).append(port).append(wu).append(sessid); ep.serialize(tgt); StringBuffer dts; enqueuedt.getString(dts); tgt.append(owner).append(dts); } void deserialize(MemoryBuffer &src) { src.read(priority).read(port).read(wu).read(sessid); ep.deserialize(src); StringBuffer dts; src.read(owner).read(dts); enqueuedt.setString(dts.str()); } IJobQueueItem* clone() { IJobQueueItem* ret = new CJobQueueItem(wu); ret->setPriority(priority); ret->setPriority(port); ret->setEndpoint(ep); ret->setSessionId(sessid); return ret; } void setPriority(int _priority) { priority = _priority; } void setPort(unsigned _port) { port = _port; } void setEndpoint(const SocketEndpoint &_ep) { ep = _ep; } void setSessionId(SessionId _id) { if (_id) sessid = _id; else sessid = myProcessSession(); } void setOwner(const char *_owner) { owner.set(_owner); } bool isValidSession() { Owned<INode> node = createINode(ep); return (querySessionManager().lookupProcessSession(node)==sessid); } }; class CJobQueueIterator: implements IJobQueueIterator, public CInterface { public: CJobQueueContents &items; unsigned idx; IMPLEMENT_IINTERFACE; CJobQueueIterator(CJobQueueContents &_items) : items(_items) { idx = 0; } bool isValid() { return idx<items.ordinality(); } bool first() { idx = 0; return isValid(); } bool next() { idx++; return isValid(); } IJobQueueItem & query() { return items.item(idx); } }; IJobQueueIterator *CJobQueueContents::getIterator() { return new CJobQueueIterator(*this); } IJobQueueItem *createJobQueueItem(const char *wuid) { if (!wuid||!*wuid) throw MakeStringException(-1,"createJobQueueItem empty WUID"); return new CJobQueueItem(wuid);; } IJobQueueItem *deserializeJobQueueItem(MemoryBuffer &mb) { return new CJobQueueItem(mb); } #define ForEachQueue(qd) for (sQueueData *qd = qdata; qd!=NULL; qd=qd->next) #define ForEachQueueIn(parent,qd) for (sQueueData *qd = parent.qdata; qd!=NULL; qd=qd->next) struct sQueueData { sQueueData *next; IRemoteConnection *conn; StringAttr qname; IPropertyTree *root; SubscriptionId subscriberid; unsigned lastWaitEdition; }; class CJobQueueBase: implements IJobQueueConst, public CInterface { class cOrderedIterator { CJobQueueBase &parent; unsigned numqueues; unsigned *queueidx; sQueueData **queues; IPropertyTree **queuet; MemoryAttr ma; unsigned current; public: cOrderedIterator(CJobQueueBase&_parent) : parent(_parent) { numqueues=0; ForEachQueueIn(parent,qd1) if (qd1->root) numqueues++; queueidx = (unsigned *)ma.allocate(numqueues*(sizeof(unsigned)+sizeof(sQueueData *)+sizeof(IPropertyTree *))); queues = (sQueueData **)(queueidx+numqueues); queuet = (IPropertyTree **)(queues+numqueues); unsigned i = 0; ForEachQueueIn(parent,qd2) { if (qd2->root) queues[i++] = qd2; } current = (unsigned)-1; } bool first() { StringBuffer path; parent.getItemPath(path,0U); current = (unsigned)-1; for (unsigned i = 0; i<numqueues;i++) { queueidx[i] = 0; queuet[i] = queues[i]->root->queryPropTree(path.str()); if (queuet[i]) if ((current==(unsigned)-1)||parent.itemOlder(queuet[i],queuet[current])) current = i; } return current!=(unsigned)-1; } bool next() { if (current==(unsigned)-1) return false; queueidx[current]++; StringBuffer path; parent.getItemPath(path,queueidx[current]); queuet[current] = queues[current]->root->queryPropTree(path.str()); current = (unsigned)-1; for (unsigned i = 0; i<numqueues;i++) { if (queuet[i]) if ((current==(unsigned)-1)||parent.itemOlder(queuet[i],queuet[current])) current = i; } return current!=(unsigned)-1; } bool isValid() { return current!=(unsigned)-1; } void item(sQueueData *&qd, IPropertyTree *&t,unsigned &idx) { assertex(current!=(unsigned)-1); qd = queues[current]; t = queuet[current]; idx = queueidx[current]; } sQueueData &queryQueue() { assertex(current!=(unsigned)-1); return *queues[current]; } IPropertyTree &queryTree() { assertex(current!=(unsigned)-1); return *queuet[current]; } }; protected: bool doGetLastDequeuedInfo(sQueueData *qd, StringAttr &wuid, CDateTime &enqueuedt, int &priority) { priority = 0; if (!qd) return false; const char *w = qd->root->queryProp("@prevwuid"); if (!w||!*w) return false; wuid.set(w); StringBuffer dts; if (qd->root->getProp("@prevenqueuedt",dts)) enqueuedt.setString(dts.str()); priority = qd->root->getPropInt("@prevpriority"); return true; } public: sQueueData *qdata; Semaphore notifysem; CriticalSection crit; IMPLEMENT_IINTERFACE; CJobQueueBase(const char *_qname) { StringArray qlist; qlist.appendListUniq(_qname, ","); sQueueData *last = NULL; ForEachItemIn(i,qlist) { sQueueData *qd = new sQueueData; qd->next = NULL; qd->qname.set(qlist.item(i)); qd->conn = NULL; qd->root = NULL; qd->lastWaitEdition = 0; qd->subscriberid = 0; if (last) last->next = qd; else qdata = qd; last = qd; } }; virtual ~CJobQueueBase() { while (qdata) { sQueueData * next = qdata->next; delete qdata; qdata = next; } } StringBuffer &getItemPath(StringBuffer &path,const char *wuid) { if (!wuid||!*wuid) return getItemPath(path,0U); return path.appendf("Item[@wuid=\"%s\"]",wuid); } StringBuffer &getItemPath(StringBuffer &path,unsigned idx) { path.appendf("Item[@num=\"%d\"]",idx+1); return path; } IPropertyTree *queryClientRootIndex(sQueueData &qd, unsigned idx) { VStringBuffer path("Client[%d]", idx+1); return qd.root->queryPropTree(path); } bool itemOlder(IPropertyTree *qt1, IPropertyTree *qt2) { // if this ever becomes time critical thne could cache enqueued values StringBuffer d1s; if (qt1) qt1->getProp("@enqueuedt",d1s); StringBuffer d2s; if (qt2) qt2->getProp("@enqueuedt",d2s); return (strcmp(d1s.str(),d2s.str())<0); } IJobQueueItem *doGetItem(sQueueData &qd,unsigned idx) { if (idx==(unsigned)-1) { idx = qd.root->getPropInt("@count"); if (!idx) return NULL; idx--; } StringBuffer path; IPropertyTree *item = qd.root->queryPropTree(getItemPath(path,idx).str()); if (!item) return NULL; return new CJobQueueItem(item); } IJobQueueItem *getItem(sQueueData &qd,unsigned idx) { return doGetItem(qd, idx); } IJobQueueItem *getHead(sQueueData &qd) { return getItem(qd,0); } unsigned doFindRank(sQueueData &qd,const char *wuid) { StringBuffer path; IPropertyTree *item = qd.root->queryPropTree(getItemPath(path,wuid).str()); if (!item) return (unsigned)-1; return item->getPropInt("@num")-1; } unsigned findRank(sQueueData &qd,const char *wuid) { return doFindRank(qd,wuid); } IJobQueueItem *find(sQueueData &qd,const char *wuid) { StringBuffer path; IPropertyTree *item = qd.root->queryPropTree(getItemPath(path,wuid).str()); if (!item) return NULL; bool cached = item->getPropInt("@num",0)<=0; if (wuid&&cached) return NULL; // don't want cached value unless explicit return new CJobQueueItem(item); } unsigned copyItemsImpl(sQueueData &qd,CJobQueueContents &dest) { unsigned ret=0; StringBuffer path; for (unsigned i=0;;i++) { IPropertyTree *item = qd.root->queryPropTree(getItemPath(path.clear(),i).str()); if (!item) break; ret++; dest.append(*new CJobQueueItem(item)); } return ret; } virtual void copyItemsAndState(CJobQueueContents& contents, StringBuffer& state, StringBuffer& stateDetails) { assertex(qdata); assertex(qdata->root); copyItemsImpl(*qdata,contents); const char *st = qdata->root->queryProp("@state"); if (st&&*st) state.set(st); if (st && (strieq(st, "paused") || strieq(st, "stopped"))) { const char *stDetails = qdata->root->queryProp("@stateDetails"); if (stDetails&&*stDetails) stateDetails.set(stDetails); } } sQueueData *findQD(const char *wuid) { if (wuid&&*wuid) { ForEachQueue(qd) { unsigned idx = doFindRank(*qd,wuid); if (idx!=(unsigned)-1) return qd; } } return NULL; } virtual unsigned waiting() { unsigned ret = 0; ForEachQueue(qd) { for (unsigned i=0;;i++) { IPropertyTree *croot = queryClientRootIndex(*qd,i); if (!croot) break; ret += croot->getPropInt("@waiting"); } } return ret; } virtual unsigned findRank(const char *wuid) { assertex(qdata); if (!qdata->next) return findRank(*qdata,wuid); cOrderedIterator it(*this); unsigned i = 0; ForEach(it) { const char *twuid = it.queryTree().queryProp("@wuid"); if (twuid&&(strcmp(twuid,wuid)==0)) return i; i++; } return (unsigned)-1; } virtual unsigned copyItems(CJobQueueContents &dest) { assertex(qdata); if (!qdata->next) return copyItemsImpl(*qdata,dest); cOrderedIterator it(*this); unsigned ret = 0; ForEach(it) { dest.append(*new CJobQueueItem(&it.queryTree())); ret++; } return ret; } virtual IJobQueueItem *getItem(unsigned idx) { if (!qdata) return NULL; if (!qdata->next) return getItem(*qdata,idx); cOrderedIterator it(*this); unsigned i = 0; IPropertyTree *ret = NULL; ForEach(it) { if (i==idx) { ret = &it.queryTree(); break; } else if (idx==(unsigned)-1) // -1 means return last ret = &it.queryTree(); i++; } if (ret) return new CJobQueueItem(ret); return NULL; } virtual IJobQueueItem *getHead() { if (!qdata) return NULL; if (!qdata->next) return getHead(*qdata); return getItem(0); } virtual IJobQueueItem *getTail() { if (!qdata) return NULL; if (!qdata->next) return getHead(*qdata); return getItem((unsigned)-1); } virtual IJobQueueItem *find(const char *wuid) { if (!qdata) return NULL; sQueueData *qd = qdata->next?findQD(wuid):qdata; if (!qd) return NULL; return find(*qd,wuid); } virtual bool paused() { // true if all paused ForEachQueue(qd) { if (qd->root) { const char *state = qd->root->queryProp("@state"); if (state&&(strcmp(state,"paused")!=0)) return false; } } return true; } virtual bool paused(StringBuffer& info) { // true if all paused ForEachQueue(qd) { if (qd->root) { const char *state = qd->root->queryProp("@state"); if (state&&(strcmp(state,"paused")!=0)) return false; if (state&&!info.length()) { const char *stateDetails = qd->root->queryProp("@stateDetails"); if (stateDetails && *stateDetails) info.set(stateDetails); } } } return true; } virtual bool stopped() { // true if all stopped ForEachQueue(qd) { if (qd->root) { const char *state = qd->root->queryProp("@state"); if (state&&(strcmp(state,"stopped")!=0)) return false; } } return true; } virtual bool stopped(StringBuffer& info) { // true if all stopped ForEachQueue(qd) { if (qd->root) { const char *state = qd->root->queryProp("@state"); if (state&&(strcmp(state,"stopped")!=0)) return false; if (state&&!info.length()) { const char *stateDetails = qd->root->queryProp("@stateDetails"); if (stateDetails && *stateDetails) info.set(stateDetails); } } } return true; } virtual unsigned ordinality() { unsigned ret = 0; ForEachQueue(qd) { if (qd->root) ret += qd->root->getPropInt("@count"); } return ret; } virtual bool getLastDequeuedInfo(StringAttr &wuid, CDateTime &enqueuedt, int &priority) { return doGetLastDequeuedInfo(qdata, wuid, enqueuedt, priority); } //Similar to copyItemsAndState(), this method returns the state information for one queue. virtual void getState(StringBuffer& state, StringBuffer& stateDetails) { if (!qdata->root) return; const char *st = qdata->root->queryProp("@state"); if (!st || !*st) return; state.set(st); if ((strieq(st, "paused") || strieq(st, "stopped"))) stateDetails.set(qdata->root->queryProp("@stateDetails")); } }; class CJobQueueConst: public CJobQueueBase { Owned<IPropertyTree> jobQueueSnapshot; public: CJobQueueConst(const char *_qname, IPropertyTree* _jobQueueSnapshot) : CJobQueueBase(_qname) { if (!_jobQueueSnapshot) throw MakeStringException(-1, "No job queue snapshot"); jobQueueSnapshot.setown(_jobQueueSnapshot); ForEachQueue(qd) { VStringBuffer path("Queue[@name=\"%s\"]", qd->qname.get()); qd->root = jobQueueSnapshot->queryPropTree(path.str()); if (!qd->root) throw MakeStringException(-1, "No job queue found for %s", qd->qname.get()); } }; }; class CJobQueue: public CJobQueueBase, implements IJobQueue { public: sQueueData *activeq; SessionId sessionid; unsigned locknest; bool writemode; bool connected; Owned<IConversation> initiateconv; StringAttr initiatewu; bool dequeuestop; bool cancelwaiting; bool validateitemsessions; class csubs: implements ISDSSubscription, public CInterface { CJobQueue *parent; public: IMPLEMENT_IINTERFACE; csubs(CJobQueue *_parent) { parent = _parent; } void notify(SubscriptionId id, const char *xpath, SDSNotifyFlags flags, unsigned valueLen, const void *valueData) { CriticalBlock block(parent->crit); parent->notifysem.signal(); } } subs; IMPLEMENT_IINTERFACE; CJobQueue(const char *_qname) : CJobQueueBase(_qname), subs(this) { activeq = qdata; sessionid = myProcessSession(); validateitemsessions = false; writemode = false; locknest = 0; connected = false; dequeuestop = false; cancelwaiting = false; Cconnlockblock block(this,false); // this just checks queue exists } virtual ~CJobQueue() { try { while (locknest) connunlock(true); // auto rollback if (connected) disconnect(); } catch (IException *e) { // server error EXCLOG(e, "~CJobQueue"); e->Release(); } try { // must attempt to remove subscription before object destroyed. dounsubscribe(); } catch (IException *e) { EXCLOG(e, "~CJobQueue calling dounsubscribe"); e->Release(); } } void connlock(bool exclusive) { // must be in sect if (locknest++==0) { unsigned wait = qdata&&qdata->next?5000:INFINITE; ForEachQueue(qd) { for (;;) { StringBuffer path; path.appendf("/JobQueues/Queue[@name=\"%s\"]",qd->qname.get()); bool timeout; for (;;) { timeout=false; try { qd->conn = querySDS().connect(path.str(),myProcessSession(),exclusive?RTM_LOCK_WRITE:RTM_LOCK_READ,wait); if (qd->conn) break; } catch (ISDSException *e) { if (SDSExcpt_LockTimeout != e->errorCode()) throw; e->Release(); timeout = true; } // create queue Owned<IRemoteConnection> pconn; try { pconn.setown(querySDS().connect("/JobQueues",myProcessSession(),RTM_LOCK_WRITE|RTM_CREATE_QUERY,wait)); if (!pconn) throw MakeStringException(-1,"CJobQueue could not create JobQueues"); IPropertyTree *proot = pconn->queryRoot(); StringBuffer cpath; cpath.appendf("Queue[@name=\"%s\"]",qd->qname.get()); if (!proot->hasProp(cpath.str())) { IPropertyTree *pt = proot->addPropTree("Queue"); pt->setProp("@name",qd->qname.get()); pt->setProp("@state","active"); pt->setPropInt("@count", 0); pt->setPropInt("Edition", 1); } } catch (ISDSException *e) { if (SDSExcpt_LockTimeout != e->errorCode()) throw; e->Release(); timeout = true; } } if (!timeout) break; sQueueData *qd2 = qdata; do { ::Release(qd2->conn); qd2->conn = NULL; qd2->root = NULL; } while (qd2!=qd); PROGLOG("Job Queue contention - delaying before retrying"); Sleep(getRandom()%5000); // dining philosopher delay wait = getRandom()%4000+3000; // try and prevent sync qd = qdata; } qd->root = qd->conn->queryRoot(); } writemode = exclusive; } else { if (exclusive&&!writemode) { ForEachQueue(qd) { assertex(qd->conn); writemode = exclusive; bool lockreleased; safeChangeModeWrite(qd->conn,qd->qname.get(),lockreleased); qd->root = qd->conn->queryRoot(); } } } } void connunlock(bool rollback=false) { // should be in sect if (--locknest==0) { ForEachQueue(qd) { if (qd->conn) { // can occur if connection to dali threw exception if (writemode) { if (rollback) qd->conn->rollback(); else { qd->root->setPropInt("Edition",qd->root->getPropInt("Edition")+1); qd->conn->commit(); } } qd->conn->Release(); qd->conn = NULL; } qd->root = NULL; } writemode = false; } } void conncommit() // doesn't set edition { // called within sect if (writemode) { ForEachQueue(qd) { if (qd->conn) qd->conn->commit(); } } } class Cconnlockblock: public CriticalBlock { CJobQueue *parent; bool rollback; public: Cconnlockblock(CJobQueue *_parent,bool exclusive) : CriticalBlock(_parent->crit) { parent = _parent; parent->connlock(exclusive); rollback = false; } ~Cconnlockblock() { parent->connunlock(rollback); } void setRollback(bool set=true) { rollback = set; } void commit() { parent->conncommit(); } }; void removeItem(sQueueData &qd,IPropertyTree *item, bool cache) { // does not adjust or use @count unsigned n = item->getPropInt("@num"); if (!n) return; if (cache) { StringBuffer s; item->getProp("@wuid",s.clear()); qd.root->setProp("@prevwuid",s.str()); item->getProp("@enqueuedt",s.clear()); qd.root->setProp("@prevenqueuedt",s.str()); qd.root->setPropInt("@prevpriority",item->getPropInt("@priority")); } item->setPropInt("@num",-1); StringBuffer path; for (;;) { IPropertyTree *item2 = qd.root->queryPropTree(getItemPath(path.clear(),n).str()); if (!item2) break; item2->setPropInt("@num",n); n++; } qd.root->removeTree(item); } IPropertyTree *addItem(sQueueData &qd,IPropertyTree *item,unsigned idx,unsigned count) { // does not set any values other than num StringBuffer path; // first move following up unsigned n=count; while (n>idx) { n--; qd.root->queryPropTree(getItemPath(path.clear(),n).str())->setPropInt("@num",n+2); } item->setPropInt("@num",idx+1); return qd.root->addPropTree("Item",item); } void dosubscribe() { // called in crit section ForEachQueue(qd) { if (qd->subscriberid) { querySDS().unsubscribe(qd->subscriberid); qd->subscriberid = 0; } StringBuffer path; path.appendf("/JobQueues/Queue[@name=\"%s\"]/Edition",qd->qname.get()); qd->subscriberid = querySDS().subscribe(path.str(), subs, false); } } bool haschanged() // returns if any changed { bool changed = false; ForEachQueue(qd) { if (!qd->subscriberid) { StringBuffer path; path.appendf("/JobQueues/Queue[@name=\"%s\"]/Edition",qd->qname.get()); qd->subscriberid = querySDS().subscribe(path.str(), subs, false); } unsigned e = (unsigned)qd->root->getPropInt("Edition", 1); if (e!=qd->lastWaitEdition) { qd->lastWaitEdition = e; changed = true; break; } } return changed; } void dounsubscribe() { // called in crit section ForEachQueue(qd) { if (qd->subscriberid) { querySDS().unsubscribe(qd->subscriberid); qd->subscriberid = 0; } } } IPropertyTree *queryClientRootSession(sQueueData &qd) { VStringBuffer path("Client[@session=\"%" I64F "d\"]", sessionid); IPropertyTree *ret = qd.root->queryPropTree(path.str()); if (!ret) { ret = qd.root->addPropTree("Client"); ret->setPropInt64("@session",sessionid); StringBuffer eps; ret->setProp("@node",queryMyNode()->endpoint().getUrlStr(eps).str()); } return ret; } void connect(bool _validateitemsessions) { Cconnlockblock block(this,true); validateitemsessions = _validateitemsessions; if (connected) disconnect(); dosubscribe(); ForEachQueue(qd) { if (validateitemsessions) { unsigned connected; unsigned waiting; unsigned count; getStats(*qd,connected,waiting,count); // clear any duff clients } IPropertyTree *croot = queryClientRootSession(*qd); croot->setPropInt64("@connected",croot->getPropInt64("@connected",0)+1); } connected = true; } void disconnect() // signal no longer wil be dequeing (optional - done automatically on release) { Cconnlockblock block(this,true); if (connected) { dounsubscribe(); ForEachQueue(qd) { IPropertyTree *croot = queryClientRootSession(*qd); croot->setPropInt64("@connected",croot->getPropInt64("@connected",0)-1); } connected = false; } } sQueueData *findbestqueue(bool useprev,int minprio,unsigned numqueues,sQueueData **queues) { if (numqueues==0) return NULL; if (numqueues==1) return *queues; sQueueData *best = NULL; IPropertyTree *bestt = NULL; for (unsigned i=0;i<numqueues;i++) { sQueueData *qd = queues[i]; unsigned count = qd->root->getPropInt("@count"); if (count) { int mpr = useprev?std::max(qd->root->getPropInt("@prevpriority"),minprio):minprio; if (count&&((minprio==INT_MIN)||checkprio(*qd,mpr))) { StringBuffer path; IPropertyTree *item = qd->root->queryPropTree(getItemPath(path,0U).str()); if (!item) continue; if (item->getPropInt("@num",0)<=0) continue; CDateTime dt; StringBuffer enqueued; if (!best||itemOlder(item,bestt)) { best = qd; bestt = item; } } } } return best; } void setWaiting(unsigned numqueues,sQueueData **queues, bool set) { for (unsigned i=0; i<numqueues; i++) { IPropertyTree *croot = queryClientRootSession(*queues[i]); croot->setPropInt64("@waiting",croot->getPropInt64("@waiting",0)+(set?1:-1)); } } // 'simple' queuing IJobQueueItem *dodequeue(int minprio,unsigned timeout=INFINITE, bool useprev=false, bool *timedout=NULL) { bool hasminprio=(minprio!=INT_MIN); if (timedout) *timedout = false; IJobQueueItem *ret=NULL; bool waitingset = false; while (!dequeuestop) { unsigned t = 0; if (timeout!=(unsigned)INFINITE) t = msTick(); { Cconnlockblock block(this,true); block.setRollback(true); // assume not going to update // now cycle through queues looking at state unsigned total = 0; unsigned stopped = 0; PointerArray active; ForEachQueue(qd) { total++; const char *state = qd->root->queryProp("@state"); if (state) { if (strcmp(state,"stopped")==0) stopped++; else if (strcmp(state,"paused")!=0) active.append(qd); } else active.append(qd); } if (stopped==total) return NULL; // all stopped sQueueData **activeqds = (sQueueData **)active.getArray(); unsigned activenum = active.ordinality(); if (activenum) { sQueueData *bestqd = findbestqueue(useprev,minprio,activenum,activeqds); unsigned count = bestqd?bestqd->root->getPropInt("@count"):0; // load minp from cache if (count) { int mpr = useprev?std::max(bestqd->root->getPropInt("@prevpriority"),minprio):minprio; if (!hasminprio||checkprio(*bestqd,mpr)) { block.setRollback(false); ret = dotake(*bestqd,NULL,true,hasminprio,mpr); if (ret) // think it must be! timeout = 0; // so mark that done else if (!hasminprio) { WARNLOG("Resetting queue %s",bestqd->qname.get()); clear(*bestqd); // reset queue as seems to have become out of sync } } } if (timeout!=0) { // more to do if (!connected) { // if connect already done non-zero connect(validateitemsessions); block.setRollback(false); } if (!waitingset) { setWaiting(activenum,activeqds,true); block.commit(); waitingset = true; } } } if (timeout==0) { if (waitingset) { setWaiting(activenum,activeqds,false); block.commit(); } if (timedout) *timedout = (ret==NULL); break; } } unsigned to = 5*60*1000; // check every 5 mins independant of notify (in case subscription lost for some reason) if (to>timeout) to = timeout; notifysem.wait(to); if (timeout!=(unsigned)INFINITE) { t = msTick()-t; if (t<timeout) timeout -= t; else timeout = 0; } } return ret; } IJobQueueItem *dequeue(unsigned timeout=INFINITE) { return dodequeue(INT_MIN,timeout); } IJobQueueItem *prioDequeue(int minprio,unsigned timeout=INFINITE) // minprio == MAX_INT - used cache priority { return dodequeue(minprio,timeout); } void placeonqueue(sQueueData &qd, IJobQueueItem *qitem,unsigned idx) // takes ownership of qitem { Owned<IJobQueueItem> qi = qitem; remove(qi->queryWUID()); // just in case trying to put on twice! int priority = qi->getPriority(); unsigned count = qd.root->getPropInt("@count"); StringBuffer path; if (count&&(idx!=(unsigned)-1)) { // need to check before and after if (idx) { IPropertyTree *pt = qd.root->queryPropTree(getItemPath(path.clear(),idx-1).str()); if (pt) { int pp = pt->getPropInt("@priority"); if (priority>pp) { qi->setPriority(pp); priority = pp; } } else // what happened here? idx = (unsigned)-1; } if (idx<count) { IPropertyTree *pt = qd.root->queryPropTree(getItemPath(path.clear(),idx).str()); if (pt) { int pp = pt->getPropInt("@priority"); if (priority<pp) { qi->setPriority(pp); priority = pp; } } else // what happened here? idx = (unsigned)-1; } } if (idx==(unsigned)-1) { idx = count; while (idx) { IPropertyTree *previtem = qd.root->queryPropTree(getItemPath(path.clear(),idx-1).str()); if (previtem) { if (previtem->getPropInt("@priority")>=priority) { break; } } else count--; // how did that happen? idx--; } } CJobQueueItem::assignBranch(addItem(qd,createPTree("Item"),idx,count),qi); qd.root->setPropInt("@count",count+1); } void enqueue(sQueueData &qd,IJobQueueItem *qitem) // takes ownership of qitem { Cconnlockblock block(this,true); placeonqueue(qd,qitem,(unsigned)-1); } void enqueueBefore(sQueueData &qd,IJobQueueItem *qitem,const char *wuid) { Cconnlockblock block(this,true); placeonqueue(qd,qitem,doFindRank(qd,wuid)); } void enqueueAfter(sQueueData &qd,IJobQueueItem *qitem,const char *wuid) { Cconnlockblock block(this,true); unsigned idx = doFindRank(qd,wuid); if (idx!=(unsigned)-1) idx++; placeonqueue(qd,qitem,idx); } void enqueueTail(sQueueData &qd,IJobQueueItem *qitem) { Cconnlockblock block(this,true); Owned<IJobQueueItem> qi = getTail(qd); if (qi) enqueueAfter(qd,qitem,qi->queryWUID()); else enqueue(qd,qitem); } void enqueueHead(sQueueData &qd,IJobQueueItem *qitem) { Cconnlockblock block(this,true); Owned<IJobQueueItem> qi = doGetItem(qd, 0); if (qi) enqueueBefore(qd,qitem,qi->queryWUID()); else enqueue(qd,qitem); } unsigned ordinality(sQueueData &qd) { Cconnlockblock block(this,false); return qd.root->getPropInt("@count"); } IJobQueueItem *getTail(sQueueData &qd) { return doGetItem(qd,(unsigned)-1); } IJobQueueItem *loadItem(sQueueData &qd,IJobQueueItem *qi) { Cconnlockblock block(this,false); StringBuffer path; IPropertyTree *item = qd.root->queryPropTree(getItemPath(path,qi->queryWUID()).str()); if (!item) return NULL; bool cached = item->getPropInt("@num",0)<=0; if (cached) return NULL; // don't want cached value return new CJobQueueItem(item); } bool checkprio(sQueueData &qd,int minprio=0) { StringBuffer path; IPropertyTree *item = qd.root->queryPropTree(getItemPath(path,0U).str()); if (!item) return false; return (item->getPropInt("@priority")>=minprio); } IJobQueueItem *dotake(sQueueData &qd,const char *wuid,bool saveitem,bool hasminprio=false,int minprio=0) { StringBuffer path; IPropertyTree *item = qd.root->queryPropTree(getItemPath(path,wuid).str()); if (!item) return NULL; if (item->getPropInt("@num",0)<=0) return NULL; // don't want (old) cached value if (hasminprio&&(item->getPropInt("@priority")<minprio)) return NULL; IJobQueueItem *ret = new CJobQueueItem(item); removeItem(qd,item,saveitem); unsigned count = qd.root->getPropInt("@count"); assertex(count); qd.root->setPropInt("@count",count-1); return ret; } IJobQueueItem *take(sQueueData &qd,const char *wuid) { Cconnlockblock block(this,true); return dotake(qd,wuid,false); } unsigned takeItems(sQueueData &qd,CJobQueueContents &dest) { Cconnlockblock block(this,true); unsigned ret = copyItemsImpl(qd,dest); clear(qd); return ret; } void enqueueItems(sQueueData &qd,CJobQueueContents &items) { unsigned n=items.ordinality(); if (n) { Cconnlockblock block(this,true); for (unsigned i=0;i<n;i++) enqueue(qd,items.item(i).clone()); } } void enqueueBefore(IJobQueueItem *qitem,const char *wuid) { Cconnlockblock block(this,true); sQueueData *qd = qdata->next?findQD(wuid):qdata; enqueueBefore(*qd,qitem,wuid); } void enqueueAfter(IJobQueueItem *qitem,const char *wuid) { Cconnlockblock block(this,true); sQueueData *qd = qdata->next?findQD(wuid):qdata; enqueueAfter(*qd,qitem,wuid); } bool moveBefore(const char *wuid,const char *nextwuid) { if (!qdata) return false; Cconnlockblock block(this,true); sQueueData *qd = qdata->next?findQD(wuid):qdata; if (!qd) return false; IJobQueueItem *qi=take(*qd,wuid); if (!qi) return false; sQueueData *qdd = NULL; if (qdata->next) qdd = findQD(nextwuid); if (!qdd) qdd = qd; enqueueBefore(*qdd,qi,nextwuid); return true; } bool moveAfter(const char *wuid,const char *prevwuid) { if (!qdata) return false; Cconnlockblock block(this,true); sQueueData *qd = qdata->next?findQD(wuid):qdata; if (!qd) return false; IJobQueueItem *qi=take(*qd,wuid); if (!qi) return false; sQueueData *qdd = NULL; if (qdata->next) qdd = findQD(prevwuid); if (!qdd) qdd = qd; enqueueAfter(*qdd,qi,prevwuid); return true; } bool moveToHead(const char *wuid) { if (!qdata) return false; Cconnlockblock block(this,true); sQueueData *qd = qdata->next?findQD(wuid):qdata; if (!qd) return false; IJobQueueItem *qi=take(*qd,wuid); if (!qi) return false; enqueueHead(*qd,qi); return true; } bool moveToTail(const char *wuid) { if (!qdata) return false; Cconnlockblock block(this,true); sQueueData *qd = qdata->next?findQD(wuid):qdata; if (!qd) return false; IJobQueueItem *qi=take(*qd,wuid); if (!qi) return false; enqueueTail(*qd,qi); return true; } bool remove(const char *wuid) { if (!qdata) return false; Cconnlockblock block(this,true); sQueueData *qd = qdata->next?findQD(wuid):qdata; if (!qd) return false; StringBuffer path; IPropertyTree *item = qd->root->queryPropTree(getItemPath(path,wuid).str()); if (!item) return false; bool cached = item->getPropInt("@num",0)<=0; // old cached (bwd compat) removeItem(*qd,item,false); if (!cached) { unsigned count = qd->root->getPropInt("@count"); assertex(count); qd->root->setPropInt("@count",count-1); } return true; } bool changePriority(const char *wuid,int value) { if (!qdata) return false; Cconnlockblock block(this,true); sQueueData *qd = qdata->next?findQD(wuid):qdata; if (!qd) return false; IJobQueueItem *qi=take(*qd,wuid); if (!qi) { StringBuffer ws("~"); // change cached item ws.append(wuid); StringBuffer path; IPropertyTree *item = qd->root->queryPropTree(getItemPath(path,ws.str()).str()); if (item) { item->setPropInt("@priority",value); return true; } return false; } qi->setPriority(value); enqueue(*qd,qi); return true; } void clear(sQueueData &qd) { Cconnlockblock block(this,true); qd.root->setPropInt("@count",0); for (;;) { IPropertyTree *item = qd.root->queryPropTree("Item[1]"); if (!item) break; qd.root->removeTree(item); } } void lock() { connlock(false); // sub functions will change to exclusive if needed } void unlock(bool rollback=false) { connunlock(rollback); } void pause(sQueueData &qd) { Cconnlockblock block(this,true); qd.root->setProp("@state","paused"); } void resume(sQueueData &qd) { Cconnlockblock block(this,true); qd.root->setProp("@state","active"); } bool paused(sQueueData &qd) { Cconnlockblock block(this,false); const char *state = qd.root->queryProp("@state"); return (state&&(strcmp(state,"paused")==0)); } void stop(sQueueData &qd) { Cconnlockblock block(this,true); qd.root->setProp("@state","stopped"); } bool stopped(sQueueData &qd) { Cconnlockblock block(this,false); const char *state = qd.root->queryProp("@state"); return (state&&(strcmp(state,"stopped")==0)); } void doGetStats(sQueueData &qd,unsigned &connected,unsigned &waiting,unsigned &enqueued) { Cconnlockblock block(this,false); connected = 0; waiting = 0; unsigned i=0; for (;;) { IPropertyTree *croot = queryClientRootIndex(qd,i); if (!croot) break; if (validateitemsessions && !validSession(croot)) { Cconnlockblock block(this,true); qd.root->removeTree(croot); } else { waiting += croot->getPropInt("@waiting"); connected += croot->getPropInt("@connected"); i++; } } // now remove any duff queue items unsigned count = qd.root->getPropInt("@count"); if (!validateitemsessions) { enqueued = count; return; } i=0; StringBuffer path; for (;;) { IPropertyTree *item = qd.root->queryPropTree(getItemPath(path.clear(),i).str()); if (!item) break; if (!validSession(item)) { Cconnlockblock block(this,true); item = qd.root->queryPropTree(path.str()); if (!item) break; // PROGLOG("WUJOBQ: Removing %s as session %" I64F "x not active",item->queryProp("@wuid"),item->getPropInt64("@session")); removeItem(qd,item,false); } else i++; } if (count!=i) { Cconnlockblock block(this,true); qd.root->setPropInt("@count",i); } enqueued = i; } void getStats(sQueueData &qd,unsigned &connected,unsigned &waiting,unsigned &enqueued) { Cconnlockblock block(this,false); doGetStats(qd,connected,waiting,enqueued); } void getStats(unsigned &connected,unsigned &waiting,unsigned &enqueued) { // multi queue Cconnlockblock block(this,false); connected=0; waiting=0; enqueued=0; ForEachQueue(qd) { unsigned c; unsigned w; unsigned e; doGetStats(*qd,c,w,e); connected+=c; waiting+=w; enqueued+=e; } } IJobQueueItem *take(const char *wuid) { assertex(qdata); if (!qdata->next) return take(*qdata,wuid); Cconnlockblock block(this,true); ForEachQueue(qd) { IJobQueueItem *ret = dotake(*qd,wuid,false); if (ret) return ret; } return NULL; } unsigned takeItems(CJobQueueContents &dest) { assertex(qdata); if (!qdata->next) return takeItems(*qdata,dest); Cconnlockblock block(this,true); unsigned ret = 0; ForEachQueue(qd) { ret += copyItemsImpl(*qd,dest); clear(*qd); } return ret; } void enqueueItems(CJobQueueContents &items) { // enqueues to firs sub-queue (not sure that useful) assertex(qdata); return enqueueItems(*qdata,items); } void clear() { ForEachQueue(qd) { clear(*qd); } } bool validSession(IPropertyTree *item) { Owned<INode> node = createINode(item->queryProp("@node"),DALI_SERVER_PORT); // port should always be present return (querySessionManager().lookupProcessSession(node)==(SessionId)item->getPropInt64("@session")); } IConversation *initiateConversation(sQueueData &qd,IJobQueueItem *item) { CriticalBlock block(crit); assertex(!initiateconv.get()); SocketEndpoint ep = item->queryEndpoint(); unsigned short port = (unsigned short)item->getPort(); #if defined(_USE_OPENSSL) if (queryMtls()) initiateconv.setown(createSingletonSecureSocketConnection(port)); else #endif initiateconv.setown(createSingletonSocketConnection(port)); if (!port) item->setPort(initiateconv->setRandomPort(WUJOBQ_BASE_PORT,WUJOBQ_PORT_NUM)); initiatewu.set(item->queryWUID()); enqueue(qd,item); bool ok; { CriticalUnblock unblock(crit); ok = initiateconv->accept(INFINITE); } if (!ok) initiateconv.clear(); return initiateconv.getClear(); } IConversation *acceptConversation(IJobQueueItem *&retitem, unsigned prioritytransitiondelay,IDynamicPriority *maxp) { CriticalBlock block(crit); retitem = NULL; assertex(connected); // must be connected int curmp = maxp?maxp->get():0; int nextmp = curmp; for (;;) { bool timedout = false; Owned<IJobQueueItem> item; { CriticalUnblock unblock(crit); // this is a bit complicated with multi-thor if (prioritytransitiondelay||maxp) { item.setown(dodequeue((std::max(curmp,nextmp)/10)*10, // round down to multiple of 10 prioritytransitiondelay?prioritytransitiondelay:60000,prioritytransitiondelay>0,&timedout)); // if dynamic priority check every minute if (!prioritytransitiondelay) { curmp = nextmp; // using max above is a bit devious to allow transition nextmp = maxp->get(); } } else item.setown(dequeue(INFINITE)); } if (item.get()) { if (item->isValidSession()) { SocketEndpoint ep = item->queryEndpoint(); ep.port = item->getPort(); Owned<IConversation> acceptconv; #if defined(_USE_OPENSSL) if (queryMtls()) acceptconv.setown(createSingletonSecureSocketConnection(ep.port,&ep)); else #endif acceptconv.setown(createSingletonSocketConnection(ep.port,&ep)); if (acceptconv->connect(3*60*1000)) { // shouldn't need that long retitem = item.getClear(); return acceptconv.getClear(); } } } else if (prioritytransitiondelay) prioritytransitiondelay = 0; else if (!timedout) break; } return NULL; } void cancelInitiateConversation(sQueueData &qd) { CriticalBlock block(crit); if (initiatewu.get()) remove(initiatewu); if (initiateconv.get()) initiateconv->cancel(); } void cancelAcceptConversation() { CriticalBlock block(crit); dequeuestop = true; notifysem.signal(); } bool cancelInitiateConversation(sQueueData &qd,const char *wuid) { Cconnlockblock block(this,true); for (;;) { Owned<IJobQueueItem> item = dotake(qd,wuid,false); if (!item.get()) break; if (item->isValidSession()) { SocketEndpoint ep = item->queryEndpoint(); ep.port = item->getPort(); Owned<IConversation> acceptconv; #if defined(_USE_OPENSSL) if (queryMtls()) acceptconv.setown(createSingletonSecureSocketConnection(ep.port,&ep)); else #endif acceptconv.setown(createSingletonSocketConnection(ep.port,&ep)); acceptconv->connect(3*60*1000); // connect then close should close other end return true; } } return false; } bool waitStatsChange(unsigned timeout) { assertex(!connected); // not allowed to call this while connected cancelwaiting = false; while(!cancelwaiting) { { Cconnlockblock block(this,false); if (haschanged()) return true; } if (!notifysem.wait(timeout)) break; } return false; } void cancelWaitStatsChange() { CriticalBlock block(crit); cancelwaiting = true; notifysem.signal(); } virtual void enqueue(IJobQueueItem *qitem) { enqueue(*activeq,qitem); } void enqueueHead(IJobQueueItem *qitem) { enqueueHead(*activeq,qitem); } void enqueueTail(IJobQueueItem *qitem) { enqueueTail(*activeq,qitem); } void pause() { Cconnlockblock block(this,true); ForEachQueue(qd) { if (qd->root) qd->root->setProp("@state","paused"); } } void pause(const char* info) { Cconnlockblock block(this,true); ForEachQueue(qd) { if (qd->root) { qd->root->setProp("@state","paused"); if (info && *info) qd->root->setProp("@stateDetails",info); } } } void stop() { Cconnlockblock block(this,true); ForEachQueue(qd) { if (qd->root) qd->root->setProp("@state","stopped"); } } void stop(const char* info) { Cconnlockblock block(this,true); ForEachQueue(qd) { if (qd->root) { qd->root->setProp("@state","stopped"); if (info && *info) qd->root->setProp("@stateDetails",info); } } } void resume() { Cconnlockblock block(this,true); ForEachQueue(qd) { if (qd->root) qd->root->setProp("@state","active"); } } void resume(const char* info) { Cconnlockblock block(this,true); ForEachQueue(qd) { if (qd->root) { qd->root->setProp("@state","active"); if (info && *info) qd->root->setProp("@stateDetails",info); } } } IConversation *initiateConversation(IJobQueueItem *item) { return initiateConversation(*activeq,item); } void cancelInitiateConversation() { return cancelInitiateConversation(*activeq); } bool cancelInitiateConversation(const char *wuid) { return cancelInitiateConversation(*activeq,wuid); } const char * queryActiveQueueName() { return activeq->qname; } void setActiveQueue(const char *name) { ForEachQueue(qd) { if (!name||(strcmp(qd->qname.get(),name)==0)) { activeq = qd; return; } } if (name) throw MakeStringException (-1,"queue %s not found",name); } const char *nextQueueName(const char *last) { ForEachQueue(qd) { if (!last||(strcmp(qd->qname.get(),last)==0)) { if (qd->next) return qd->next->qname.get(); break; } } return NULL; } virtual bool paused() { Cconnlockblock block(this,false); return CJobQueueBase::paused(); } virtual bool paused(StringBuffer& info) { Cconnlockblock block(this,false); return CJobQueueBase::paused(info); } virtual bool stopped() { Cconnlockblock block(this,false); return CJobQueueBase::stopped(); } virtual bool stopped(StringBuffer& info) { Cconnlockblock block(this,false); return CJobQueueBase::stopped(info); } virtual unsigned ordinality() { Cconnlockblock block(this,false); return CJobQueueBase::ordinality(); } virtual unsigned waiting() { Cconnlockblock block(this,false); return CJobQueueBase::waiting(); } virtual IJobQueueItem *getItem(unsigned idx) { Cconnlockblock block(this,false); return CJobQueueBase::getItem(idx); } virtual IJobQueueItem *getHead() { Cconnlockblock block(this,false); return CJobQueueBase::getHead(); } virtual IJobQueueItem *getTail() { Cconnlockblock block(this,false); return CJobQueueBase::getTail(); } virtual IJobQueueItem *find(const char *wuid) { Cconnlockblock block(this,false); return CJobQueueBase::find(wuid); } virtual unsigned findRank(const char *wuid) { Cconnlockblock block(this,false); return CJobQueueBase::findRank(wuid); } virtual unsigned copyItems(CJobQueueContents &dest) { Cconnlockblock block(this,false); return CJobQueueBase::copyItems(dest); } virtual bool getLastDequeuedInfo(StringAttr &wuid, CDateTime &enqueuedt, int &priority) { Cconnlockblock block(this,false); return CJobQueueBase::doGetLastDequeuedInfo(activeq, wuid, enqueuedt, priority); } virtual void copyItemsAndState(CJobQueueContents& contents, StringBuffer& state, StringBuffer& stateDetails) { Cconnlockblock block(this,false); CJobQueueBase::copyItemsAndState(contents, state, stateDetails); } virtual void getState(StringBuffer& state, StringBuffer& stateDetails) { Cconnlockblock block(this,false); CJobQueueBase::getState(state, stateDetails); } }; class CJQSnapshot : public CInterface, implements IJQSnapshot { Owned<IPropertyTree> jobQueueInfo; public: IMPLEMENT_IINTERFACE; CJQSnapshot() { Owned<IRemoteConnection> connJobQueues = querySDS().connect("/JobQueues", myProcessSession(), RTM_LOCK_READ, 30000); if (!connJobQueues) throw MakeStringException(-1, "CJQSnapshot::CJQSnapshot: /JobQueues not found"); jobQueueInfo.setown(createPTreeFromIPT(connJobQueues->queryRoot())); } IJobQueueConst* getJobQueue(const char *name) { if (!jobQueueInfo) return NULL; return new CJobQueueConst(name, jobQueueInfo.getLink()); } }; IJQSnapshot *createJQSnapshot() { return new CJQSnapshot(); } IJobQueue *createJobQueue(const char *name) { if (!name||!*name) throw MakeStringException(-1,"createJobQueue empty name"); return new CJobQueue(name); } extern bool WORKUNIT_API runWorkUnit(const char *wuid, const char *queueName) { #ifdef _CONTAINERIZED StringBuffer agentQueue; getClusterEclAgentQueueName(agentQueue, queueName); #else //NB: In the non-container system the name of the roxie agent queue does not follow the convention for the containerized system Owned<IConstWUClusterInfo> clusterInfo = getTargetClusterInfo(queueName); if (!clusterInfo.get()) return false; SCMStringBuffer agentQueue; clusterInfo->getAgentQueue(agentQueue); if (!agentQueue.length()) return false; #endif Owned<IJobQueue> queue = createJobQueue(agentQueue.str()); if (!queue.get()) throw MakeStringException(-1, "Could not create workunit queue"); IJobQueueItem *item = createJobQueueItem(wuid); queue->enqueue(item); PROGLOG("Agent request '%s' enqueued on '%s'", wuid, agentQueue.str()); return true; } extern bool WORKUNIT_API runWorkUnit(const char *wuid) { Owned<IWorkUnitFactory> factory = getWorkUnitFactory(); Owned<IConstWorkUnit> w = factory->openWorkUnit(wuid); if (w) { StringAttr clusterName = (w->queryClusterName()); w.clear(); return runWorkUnit(wuid, clusterName.str()); } else return false; } extern WORKUNIT_API StringBuffer &getQueuesContainingWorkUnit(const char *wuid, StringBuffer &queueList) { Owned<IRemoteConnection> conn = querySDS().connect("/JobQueues", myProcessSession(), RTM_LOCK_READ, 5000); if (!conn) return queueList; VStringBuffer xpath("Queue[Item/@wuid='%s']", wuid); Owned<IPropertyTreeIterator> it = conn->getElements(xpath.str()); ForEach(*it) { if (queueList.length()) queueList.append(','); queueList.append(it->query().queryProp("@name")); } return queueList; } extern void WORKUNIT_API removeWorkUnitFromAllQueues(const char *wuid) { StringBuffer queueList; if (!getQueuesContainingWorkUnit(wuid, queueList).length()) return; Owned<IJobQueue> q = createJobQueue(queueList.str()); if (q) while(q->remove(wuid)); } extern bool WORKUNIT_API switchWorkUnitQueue(IWorkUnit* wu, const char *cluster) { if (!wu) return false; class cQswitcher: public CInterface, implements IQueueSwitcher { public: IMPLEMENT_IINTERFACE; void * getQ(const char * qname, const char * wuid) { Owned<IJobQueue> q = createJobQueue(qname); return q->take(wuid); } void putQ(const char * qname, const char * wuid, void * qitem) { Owned<IJobQueue> q = createJobQueue(qname); q->enqueue((IJobQueueItem *)qitem); } bool isAuto() { return false; } } switcher; return wu->switchThorQueue(cluster, &switcher); }
29.299053
136
0.518243
jeclrsg
fead0d2dc5afc81cf23e0c10f5d148679cea8263
13,657
cpp
C++
dali-toolkit/public-api/controls/scrollable/scroll-view/scroll-view.cpp
dalihub/dali-toolk
980728a7e35b8ddd28f70c090243e8076e21536e
[ "Apache-2.0", "BSD-3-Clause" ]
7
2016-11-18T10:26:51.000Z
2021-01-28T13:51:59.000Z
dali-toolkit/public-api/controls/scrollable/scroll-view/scroll-view.cpp
dalihub/dali-toolk
980728a7e35b8ddd28f70c090243e8076e21536e
[ "Apache-2.0", "BSD-3-Clause" ]
13
2020-07-15T11:33:03.000Z
2021-04-09T21:29:23.000Z
dali-toolkit/public-api/controls/scrollable/scroll-view/scroll-view.cpp
dalihub/dali-toolk
980728a7e35b8ddd28f70c090243e8076e21536e
[ "Apache-2.0", "BSD-3-Clause" ]
10
2019-05-17T07:15:09.000Z
2021-05-24T07:28:08.000Z
/* * Copyright (c) 2020 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ // CLASS HEADER #include <dali-toolkit/public-api/controls/scrollable/scroll-view/scroll-view.h> // EXTERNAL INCLUDES #include <dali/integration-api/debug.h> // INTERNAL INCLUDES #include <dali-toolkit/internal/controls/scrollable/scroll-view/scroll-view-impl.h> #include <dali-toolkit/public-api/controls/scrollable/scrollable.h> using namespace Dali; namespace Dali { namespace Toolkit { /////////////////////////////////////////////////////////////////////////////////////////////////// // RulerDomain /////////////////////////////////////////////////////////////////////////////////////////////////// RulerDomain::RulerDomain(float min, float max, bool enabled) : min(min), max(max), enabled(enabled) { } float RulerDomain::Clamp(float x, float length, float scale) const { ClampState clamped; return Clamp(x, length, scale, clamped); } float RulerDomain::Clamp(float x, float length, float scale, ClampState& clamped) const { if(!enabled) { clamped = NOT_CLAMPED; return x; } const float minExtent = min * scale; const float maxExtent = max * scale - length; if(x < minExtent) { clamped = CLAMPED_TO_MIN; return minExtent; } else if(x > maxExtent) { clamped = CLAMPED_TO_MAX; return maxExtent; } clamped = NOT_CLAMPED; return x; } float RulerDomain::GetSize() const { return max - min; } /////////////////////////////////////////////////////////////////////////////////////////////////// // Ruler /////////////////////////////////////////////////////////////////////////////////////////////////// Ruler::Ruler() : mType(FREE), mEnabled(true), mDomain(RulerDomain(0.0f, 1.0f, false)) { } Ruler::~Ruler() { } Ruler::RulerType Ruler::GetType() const { return mType; } bool Ruler::IsEnabled() const { return mEnabled; } void Ruler::Enable() { mEnabled = true; } void Ruler::Disable() { mEnabled = false; } void Ruler::SetDomain(RulerDomain domain) { mDomain = domain; } const RulerDomain& Ruler::GetDomain() const { return mDomain; } void Ruler::DisableDomain() { mDomain = RulerDomain(0.0f, 1.0f, false); } float Ruler::Clamp(float x, float length, float scale) const { return mDomain.Clamp(x, length, scale); } float Ruler::Clamp(float x, float length, float scale, ClampState& clamped) const { return mDomain.Clamp(x, length, scale, clamped); } float Ruler::SnapAndClamp(float x, float bias, float length, float scale) const { return Clamp(Snap(x, bias), length, scale); } float Ruler::SnapAndClamp(float x, float bias, float length, float scale, ClampState& clamped) const { return Clamp(Snap(x, bias), length, scale, clamped); } /////////////////////////////////////////////////////////////////////////////////////////////////// // DefaultRuler /////////////////////////////////////////////////////////////////////////////////////////////////// DefaultRuler::DefaultRuler() { mType = FREE; } float DefaultRuler::Snap(float x, float bias) const { return x; } float DefaultRuler::GetPositionFromPage(unsigned int page, unsigned int& volume, bool wrap) const { volume = 0; return 0.0f; } unsigned int DefaultRuler::GetPageFromPosition(float position, bool wrap) const { return 0; } unsigned int DefaultRuler::GetTotalPages() const { return 1; } /////////////////////////////////////////////////////////////////////////////////////////////////// // FixedRuler /////////////////////////////////////////////////////////////////////////////////////////////////// FixedRuler::FixedRuler(float spacing) : mSpacing(spacing) { if(fabsf(mSpacing) <= Math::MACHINE_EPSILON_1) { DALI_LOG_ERROR("Page spacing too small (%f).\n", double(spacing)); mSpacing = spacing >= 0.0f ? Math::MACHINE_EPSILON_1 : -Math::MACHINE_EPSILON_1; } mType = FIXED; } float FixedRuler::Snap(float x, float bias) const { return floor(x / mSpacing + bias) * mSpacing; } float FixedRuler::GetPositionFromPage(unsigned int page, unsigned int& volume, bool wrap) const { float position = mDomain.min; volume = 0; // spacing must be present. if(mEnabled) { unsigned int column = page; // In carry mode, a volume (carry) is produced when page exceeds limit within domain if(wrap) { unsigned int pagesPerVolume = mDomain.GetSize() / mSpacing; if(pagesPerVolume > 0) { column += pagesPerVolume; column %= pagesPerVolume; volume = page / pagesPerVolume; } } position = mDomain.min + column * mSpacing; } else // Domain (or Spacing) is not present, carry page to volume. { if(wrap) { volume = page; } } return position; } unsigned int FixedRuler::GetPageFromPosition(float position, bool wrap) const { unsigned int page = 0; // spacing must be present. if(mEnabled) { if(wrap) { position = WrapInDomain(position, mDomain.min, mDomain.max); } page = std::max(static_cast<double>(0.0f), static_cast<double>(floor((position - mDomain.min) / mSpacing + 0.5f))); if(wrap) { unsigned int pagesPerVolume = mDomain.GetSize() / mSpacing; // Defensive check to avoid a divide by zero below when the ruler is in an invalid state (entire domain smaller than spacing between pages of it): if(pagesPerVolume < 1u) { pagesPerVolume = 1u; DALI_LOG_ERROR("Ruler domain(%f) is smaller than its spacing(%f).\n", mDomain.GetSize() * 1.0, mSpacing * 1.0); } page %= pagesPerVolume; } } return page; } unsigned int FixedRuler::GetTotalPages() const { unsigned int pagesPerVolume = 1; // spacing must be present. if(mEnabled) { pagesPerVolume = mDomain.GetSize() / mSpacing; } return pagesPerVolume; } /////////////////////////////////////////////////////////////////////////////////////////////////// // ScrollView /////////////////////////////////////////////////////////////////////////////////////////////////// ScrollView::ScrollView() { } ScrollView::ScrollView(Internal::ScrollView& implementation) : Scrollable(implementation) { } ScrollView::ScrollView(Dali::Internal::CustomActor* internal) : Scrollable(internal) { VerifyCustomActorPointer<Internal::ScrollView>(internal); } ScrollView::ScrollView(const ScrollView& handle) = default; ScrollView::ScrollView(ScrollView&& rhs) = default; ScrollView& ScrollView::operator=(const ScrollView& handle) = default; ScrollView& ScrollView::operator=(ScrollView&& rhs) = default; ScrollView ScrollView::New() { return Internal::ScrollView::New(); } ScrollView::~ScrollView() { } ScrollView ScrollView::DownCast(BaseHandle handle) { return Control::DownCast<ScrollView, Internal::ScrollView>(handle); } AlphaFunction ScrollView::GetScrollSnapAlphaFunction() const { return GetImpl(*this).GetScrollSnapAlphaFunction(); } void ScrollView::SetScrollSnapAlphaFunction(AlphaFunction alpha) { GetImpl(*this).SetScrollSnapAlphaFunction(alpha); } AlphaFunction ScrollView::GetScrollFlickAlphaFunction() const { return GetImpl(*this).GetScrollFlickAlphaFunction(); } void ScrollView::SetScrollFlickAlphaFunction(AlphaFunction alpha) { GetImpl(*this).SetScrollFlickAlphaFunction(alpha); } float ScrollView::GetScrollSnapDuration() const { return GetImpl(*this).GetScrollSnapDuration(); } void ScrollView::SetScrollSnapDuration(float time) { GetImpl(*this).SetScrollSnapDuration(time); } float ScrollView::GetScrollFlickDuration() const { return GetImpl(*this).GetScrollFlickDuration(); } void ScrollView::SetScrollFlickDuration(float time) { GetImpl(*this).SetScrollFlickDuration(time); } void ScrollView::SetRulerX(RulerPtr ruler) { GetImpl(*this).SetRulerX(ruler); } void ScrollView::SetRulerY(RulerPtr ruler) { GetImpl(*this).SetRulerY(ruler); } void ScrollView::SetScrollSensitive(bool sensitive) { GetImpl(*this).SetScrollSensitive(sensitive); } void ScrollView::SetMaxOvershoot(float overshootX, float overshootY) { GetImpl(*this).SetMaxOvershoot(overshootX, overshootY); } void ScrollView::SetSnapOvershootAlphaFunction(AlphaFunction alpha) { GetImpl(*this).SetSnapOvershootAlphaFunction(alpha); } void ScrollView::SetSnapOvershootDuration(float duration) { GetImpl(*this).SetSnapOvershootDuration(duration); } void ScrollView::SetActorAutoSnap(bool enable) { GetImpl(*this).SetActorAutoSnap(enable); } void ScrollView::SetWrapMode(bool enable) { GetImpl(*this).SetWrapMode(enable); } int ScrollView::GetScrollUpdateDistance() const { return GetImpl(*this).GetScrollUpdateDistance(); } void ScrollView::SetScrollUpdateDistance(int distance) { GetImpl(*this).SetScrollUpdateDistance(distance); } bool ScrollView::GetAxisAutoLock() const { return GetImpl(*this).GetAxisAutoLock(); } void ScrollView::SetAxisAutoLock(bool enable) { GetImpl(*this).SetAxisAutoLock(enable); } float ScrollView::GetAxisAutoLockGradient() const { return GetImpl(*this).GetAxisAutoLockGradient(); } void ScrollView::SetAxisAutoLockGradient(float gradient) { GetImpl(*this).SetAxisAutoLockGradient(gradient); } float ScrollView::GetFrictionCoefficient() const { return GetImpl(*this).GetFrictionCoefficient(); } void ScrollView::SetFrictionCoefficient(float friction) { GetImpl(*this).SetFrictionCoefficient(friction); } float ScrollView::GetFlickSpeedCoefficient() const { return GetImpl(*this).GetFlickSpeedCoefficient(); } void ScrollView::SetFlickSpeedCoefficient(float speed) { GetImpl(*this).SetFlickSpeedCoefficient(speed); } Vector2 ScrollView::GetMinimumDistanceForFlick() const { return GetImpl(*this).GetMinimumDistanceForFlick(); } void ScrollView::SetMinimumDistanceForFlick(const Vector2& distance) { GetImpl(*this).SetMinimumDistanceForFlick(distance); } float ScrollView::GetMinimumSpeedForFlick() const { return GetImpl(*this).GetMinimumSpeedForFlick(); } void ScrollView::SetMinimumSpeedForFlick(float speed) { GetImpl(*this).SetMinimumSpeedForFlick(speed); } float ScrollView::GetMaxFlickSpeed() const { return GetImpl(*this).GetMaxFlickSpeed(); } void ScrollView::SetMaxFlickSpeed(float speed) { GetImpl(*this).SetMaxFlickSpeed(speed); } Vector2 ScrollView::GetWheelScrollDistanceStep() const { return GetImpl(*this).GetWheelScrollDistanceStep(); } void ScrollView::SetWheelScrollDistanceStep(Vector2 step) { GetImpl(*this).SetWheelScrollDistanceStep(step); } Vector2 ScrollView::GetCurrentScrollPosition() const { return GetImpl(*this).GetCurrentScrollPosition(); } unsigned int ScrollView::GetCurrentPage() const { return GetImpl(*this).GetCurrentPage(); } void ScrollView::ScrollTo(const Vector2& position) { GetImpl(*this).ScrollTo(position); } void ScrollView::ScrollTo(const Vector2& position, float duration) { GetImpl(*this).ScrollTo(position, duration); } void ScrollView::ScrollTo(const Vector2& position, float duration, AlphaFunction alpha) { GetImpl(*this).ScrollTo(position, duration, alpha); } void ScrollView::ScrollTo(const Vector2& position, float duration, DirectionBias horizontalBias, DirectionBias verticalBias) { GetImpl(*this).ScrollTo(position, duration, horizontalBias, verticalBias); } void ScrollView::ScrollTo(const Vector2& position, float duration, AlphaFunction alpha, DirectionBias horizontalBias, DirectionBias verticalBias) { GetImpl(*this).ScrollTo(position, duration, alpha, horizontalBias, verticalBias); } void ScrollView::ScrollTo(unsigned int page) { GetImpl(*this).ScrollTo(page); } void ScrollView::ScrollTo(unsigned int page, float duration) { GetImpl(*this).ScrollTo(page, duration); } void ScrollView::ScrollTo(unsigned int page, float duration, DirectionBias bias) { GetImpl(*this).ScrollTo(page, duration, bias); } void ScrollView::ScrollTo(Actor& actor) { GetImpl(*this).ScrollTo(actor); } void ScrollView::ScrollTo(Actor& actor, float duration) { GetImpl(*this).ScrollTo(actor, duration); } bool ScrollView::ScrollToSnapPoint() { return GetImpl(*this).ScrollToSnapPoint(); } void ScrollView::ApplyConstraintToChildren(Constraint constraint) { GetImpl(*this).ApplyConstraintToChildren(constraint); } void ScrollView::RemoveConstraintsFromChildren() { GetImpl(*this).RemoveConstraintsFromChildren(); } void ScrollView::ApplyEffect(ScrollViewEffect effect) { GetImpl(*this).ApplyEffect(effect); } void ScrollView::RemoveEffect(ScrollViewEffect effect) { GetImpl(*this).RemoveEffect(effect); } void ScrollView::RemoveAllEffects() { GetImpl(*this).RemoveAllEffects(); } void ScrollView::BindActor(Actor child) { GetImpl(*this).BindActor(child); } void ScrollView::UnbindActor(Actor child) { GetImpl(*this).UnbindActor(child); } ScrollView::SnapStartedSignalType& ScrollView::SnapStartedSignal() { return GetImpl(*this).SnapStartedSignal(); } void ScrollView::SetScrollingDirection(Radian direction, Radian threshold) { GetImpl(*this).SetScrollingDirection(direction, threshold); } void ScrollView::RemoveScrollingDirection(Radian direction) { GetImpl(*this).RemoveScrollingDirection(direction); } } // namespace Toolkit } // namespace Dali
22.425287
152
0.684191
dalihub
feb16307bf9150d1ed948e2e001c1f4fbb5a2dea
7,029
cpp
C++
archive/FirstCut/territory.cpp
MangoCats/gomer
2b8059122add2bfab8cb4738cbaeeed0c59e4b58
[ "MIT" ]
null
null
null
archive/FirstCut/territory.cpp
MangoCats/gomer
2b8059122add2bfab8cb4738cbaeeed0c59e4b58
[ "MIT" ]
null
null
null
archive/FirstCut/territory.cpp
MangoCats/gomer
2b8059122add2bfab8cb4738cbaeeed0c59e4b58
[ "MIT" ]
null
null
null
#include "territory.h" Territory::Territory(Board *parent) : QObject(parent) { bp = parent; size = 0.4; show = false; for ( int i = 0; i < bp->Xsize; i++ ) for ( int j = 0; j < bp->Ysize; j++ ) gi.append( -1 ); // -1 == undetermined territory, not yet in a group update(); } void Territory::setScene( BoardScene *scp ) { scene = scp; } /** * @brief Territory::clear - erase existing territory objects * in preparation for a new computation and possible display */ void Territory::clear() { clearDisplay(); foreach( TerritorySquare *tp, squareList ) delete tp; squareList.clear(); foreach( TerritoryGroup *gp, groupList ) delete gp; groupList.clear(); for ( int i = 0; i < bp->Xsize; i++ ) for ( int j = 0; j < bp->Ysize; j++ ) gi.replace( i + j * bp->Xsize, -1 ); } /** * @brief Territory::update - floodfill all empty grid points * and determine their current territory status: black, white or undetermined. */ void Territory::update() { clear(); // Determine how many territory groups there are, and what coordinates they each cover for ( int i = 0; i < bp->Xsize; i++ ) for ( int j = 0; j < bp->Ysize; j++ ) if ( gi.at( i + j * bp->Xsize ) == -1 ) { tFill( i, j, groupList.size() ); groupList.append( new TerritoryGroup(this) ); } // Fill the territory groups with square objects for ( int k = 0; k < groupList.size(); k++ ) { TerritoryGroup *tp = groupList.at(k); for ( int i = 0; i < bp->Xsize; i++ ) for ( int j = 0; j < bp->Ysize; j++ ) { if ( gi.at( i + j * bp->Xsize ) == k ) { TerritorySquare *ts = new TerritorySquare(this); ts->x = i; ts->y = j; ts->g = k; ts->c = -2; // Undetermined, at this time squareList.append(ts); tp->group.append(ts); } } } // Determine the color of each territory group for ( int k = 0; k < groupList.size(); k++ ) { TerritoryGroup *tp = groupList.at(k); int tc = -2; // -2 undeterminmed, -1 determined to be disputed, 0 black, 1 white bool done = ( groupList.size() <= 0 ) || ( tp->group.size() == 0 ); int i = 0; while( !done ) { TerritorySquare *ts = tp->group.at(i); if ( ts->x > 0 ) done |= territoryColor( ts->x-1, ts->y, &tc ); if ( ts->x < (bp->Xsize - 1) ) done |= territoryColor( ts->x+1, ts->y, &tc ); if ( ts->y > 0 ) done |= territoryColor( ts->x, ts->y-1, &tc ); if ( ts->y < (bp->Ysize - 1) ) done |= territoryColor( ts->x, ts->y+1, &tc ); if ( ++i >= tp->group.size() ) done = true; } groupList.at(k)->c = tc; foreach ( TerritorySquare *ts, tp->group ) ts->c = tc; } updateDisplay(); } /** * @brief Territory::territoryColor - judging adjacent squares to a territory and the current color determination * determine the continuing color evaluation of the territory * @param x - coordinate to evaluate * @param y - coordinate to evaluate * @param tc - current color assignment * @return true if the current color assignment has become disputed */ bool Territory::territoryColor( int x, int y, int *tc ) { int ii = x + bp->Xsize * y; if ( bp->board.size() <= ii ) return true; Stone *sp = bp->board.at( ii ); if ( sp == nullptr ) return false; // No info here if ( *tc == -1 ) return true; // Done before we start if ( *tc == -2 ) { *tc = sp->c; return false; } if ( *tc == sp->c ) return false; // Continuing the trend *tc = -1; // Contrasting neighbor found, territory is in dispute return true; } /** * @brief Territory::tFill - floodfill unclaimed territory with group index g * @param x - coordinate to look for unfilled neighbors from * @param y - coordinate to look for unfilled neighbors from * @param g - group index to fill this territory with */ void Territory::tFill( int x, int y, int g ) { int ii = x + y * bp->Xsize; if ( bp->board.size() <= ii ) return; if ( bp->board.at( ii ) != nullptr ) { gi.replace( ii, -2 - bp->board.at( ii )->c ); // -2 for blackstone, -3 for whitestone return; // floodfill search does not pass a stone } gi.replace( ii, g ); if ( x > 0 ) tCheck( x-1, y, g ); if ( x < ( bp->Xsize - 1 ) ) tCheck( x+1, y, g ); if ( y > 0 ) tCheck( x, y-1, g ); if ( y < ( bp->Ysize - 1 ) ) tCheck( x, y+1, g ); } /** * @brief Territory::tCheck * @param x - coordinate to check for stone * @param y - coordinate to check for stone * @param g - group index to mark this territory with */ void Territory::tCheck( int x, int y, int g ) { int ii = x + y * bp->Xsize; if ( bp->board.size() <= ii ) return; // Board is not ready yet, happens at first initialization if ( gi.size() < ii ) { qDebug( "ERROR: gi not ready yet" ); return; } if ( gi.at( ii ) != -1 ) { if (( gi.at( ii ) > -1 ) && ( gi.at( ii ) != g )) { QString msg = QString( "ERROR: tCheck @(%1,%2,%3) encountered another territory index %4" ).arg(x).arg(y).arg(g).arg(gi.at( ii ) ); qDebug( qPrintable( msg ) ); } return; // already marked } if ( bp->board.at( ii ) != nullptr ) { gi.replace( ii, -2 - bp->board.at( ii )->c ); // -2 for blackstone, -3 for whitestone return; // floodfill search does not pass a stone } tFill( x, y, g ); // Continue the floodfill search } /** * @brief Territory::clearDisplay - just clear the displayed * squares' graphics items, not the underlying data objects. */ void Territory::clearDisplay() { if ( scene == nullptr ) return; foreach( TerritorySquare *tp, squareList ) { if ( tp->ri != nullptr ) { tp->ri->setVisible( false ); scene->removeMyItem( tp->ri ); delete( tp->ri ); tp->ri = nullptr; } } } /** * @brief Territory::updateDisplay - just update the display * graphics items, not recalculating territory data objects. */ void Territory::updateDisplay() { clearDisplay(); if ( !show ) return; QPen tPen; QBrush tBrush; foreach( TerritorySquare *tp, squareList ) { // tp->ri == nullptr, done in clearDisplay if ( tp->c < 0 ) { tPen = scene->linePen; tBrush = scene->backBrush; } else if ( tp->c == 0 ) { tPen = Qt::NoPen; tBrush = scene->blackBrush; } else if ( tp->c == 1 ) { tPen = Qt::NoPen; tBrush = scene->whiteBrush; } else { tPen = Qt::NoPen; tBrush = scene->backBrush; qDebug( "Territory::updateDisplay() unknown color" ); } tp->ri = scene->addRect( (qreal)tp->x - size*0.5, (qreal)tp->y - size*0.5, size, size, tPen, tBrush ); // TODO: correct pen and brush for territory color } }
33.15566
141
0.548584
MangoCats
feb2bc4c8288cce2ee9c23f57a16e618adbd52ae
9,826
cpp
C++
tests/unit/Base/TestTimer.cpp
franjgonzalez/Quinoa
411eb8815e92618c563881b784e287e2dd916f89
[ "RSA-MD" ]
null
null
null
tests/unit/Base/TestTimer.cpp
franjgonzalez/Quinoa
411eb8815e92618c563881b784e287e2dd916f89
[ "RSA-MD" ]
null
null
null
tests/unit/Base/TestTimer.cpp
franjgonzalez/Quinoa
411eb8815e92618c563881b784e287e2dd916f89
[ "RSA-MD" ]
null
null
null
// ***************************************************************************** /*! \file tests/unit/Base/TestTimer.cpp \copyright 2012-2015 J. Bakosi, 2016-2018 Los Alamos National Security, LLC., 2019 Triad National Security, LLC. All rights reserved. See the LICENSE file for details. \brief Unit tests for tk::Timer \details Unit tests for tk::Timer */ // ***************************************************************************** #include <unistd.h> #include "NoWarning/tut.hpp" #include "TUTConfig.hpp" #include "Timer.hpp" #include "ContainerUtil.hpp" #include "NoWarning/tutsuite.decl.h" namespace unittest { extern CProxy_TUTSuite g_suiteProxy; } // unittest:: #ifndef DOXYGEN_GENERATING_OUTPUT namespace tut { //! All tests in group inherited from this base struct Timer_common { // cppcheck-suppress unusedStructMember double precision = 1.0e-3; // required precision in seconds for timings }; //! Test group shortcuts using Timer_group = test_group< Timer_common, MAX_TESTS_IN_GROUP >; using Timer_object = Timer_group::object; //! Define test group static Timer_group Timer( "Base/Timer" ); //! Test definitions for group //! Test timing a 0.1s duration as float with given precision template<> template<> void Timer_object::test< 1 >() { double prec = 1.0e-1; // only for this single test (to pass on Mac OS) set_test_name( "measure 0.1s using dsec() with " + std::to_string(prec) + "s prec" ); tk::Timer timer; usleep( 100000 ); // in micro-seconds, sleep for 0.1 second // test if time measured with at least 1/10th of a millisecond prec ensure_equals( "time 0.1s elapsed as float", timer.dsec(), 0.1, prec ); } //! Test timing a 1.0 duration as h:m:s with given precision template<> template<> void Timer_object::test< 2 >() { set_test_name( "measure 1.0s using hms() with " + std::to_string(precision) + "s prec" ); tk::Timer timer; usleep( 1000000 ); // in micro-seconds, sleep for 1.0 second const auto stamp = timer.hms(); // test if time measured with at least 1/10th of a millisecond precision ensure_equals( "time 1.0s elapsed as hrs", static_cast<tk::real>(stamp.hrs.count()), 0.0, precision ); ensure_equals( "time 1.0s elapsed as min", static_cast<tk::real>(stamp.min.count()), 0.0, precision ); ensure_equals( "time 1.0s elapsed as sec", static_cast<tk::real>(stamp.sec.count()), 1.0, precision ); } //! Test estimated time elapsed and to accomplishment triggered by term template<> template<> void Timer_object::test< 3 >() { set_test_name( "ETE and ETA triggered by terminate time" ); // Setup a duration case tk::real term = 5.0; // time at which to terminate time stepping tk::real time = 1.0; // current time uint64_t nstep = 1000; // max number of time steps to take (large) uint64_t it = 1; // current iteration tk::Timer timer; usleep( 1000000 ); // in micro-seconds, sleep for 1.0 second tk::Timer::Watch ete, eta; timer.eta( term, time, nstep, it, ete, eta ); // test estimated time elapsed with given precision ensure_equals( "estimated time elapsed in hrs", static_cast<tk::real>(ete.hrs.count()), 0.0, precision ); ensure_equals( "estimated time elapsed in min", static_cast<tk::real>(ete.min.count()), 0.0, precision ); ensure_equals( "estimated time elapsed in sec", static_cast<tk::real>(ete.sec.count()), 1.0, precision ); // test estimated time to accomplishment with given precision ensure_equals( "estimated time to accomplishment in hrs", static_cast<tk::real>(eta.hrs.count()), 0.0, precision ); ensure_equals( "estimated time to accomplishment in min", static_cast<tk::real>(eta.min.count()), 0.0, precision ); ensure_equals( "estimated time to accomplishment in sec", static_cast<tk::real>(eta.sec.count()), 4.0, precision ); } //! Test estimated time elapsed and to accomplishment triggered by nstep template<> template<> void Timer_object::test< 4 >() { set_test_name( "ETE and ETA triggered by max number of steps" ); // Setup a duration case tk::real term = 500.0; // time at which to terminate time stepping (large) tk::real time = 1.0; // current time uint64_t nstep = 100; // max number of time steps to take uint64_t it = 1; // current iteration tk::Timer timer; usleep( 1000000 ); // in micro-seconds, sleep for 1.0 second tk::Timer::Watch ete, eta; timer.eta( term, time, nstep, it, ete, eta ); // test estimated time elapsed with given precision ensure_equals( "estimated time elapsed in hrs", static_cast<tk::real>(ete.hrs.count()), 0.0, precision ); ensure_equals( "estimated time elapsed in min", static_cast<tk::real>(ete.min.count()), 0.0, precision ); ensure_equals( "estimated time elapsed in sec", static_cast<tk::real>(ete.sec.count()), 1.0, precision ); // test estimated time to accomplishment with given precision ensure_equals( "estimated time to accomplishment in hrs", static_cast<tk::real>(eta.hrs.count()), 0.0, precision ); ensure_equals( "estimated time to accomplishment in min", static_cast<tk::real>(eta.min.count()), 1.0, precision ); ensure_equals( "estimated time to accomplishment in sec", static_cast<tk::real>(eta.sec.count()), 39.0, precision ); } //! Test converting a 1.0s duration timed as a float to Timer::Watch template<> template<> void Timer_object::test< 5 >() { set_test_name( "convert time stamp in float to Watch" ); tk::Timer timer; usleep( 1000000 ); // in micro-seconds, sleep for 1.0 second // convert time stamp in float to Timer::Watch const auto w = tk::hms( timer.dsec() ); // test if time measured with at least 1/10th of a millisecond precision ensure_equals( "time 1.0s elapsed as float represented as Timer::Watch in hrs", static_cast<tk::real>(w.hrs.count()), 0.0, precision ); ensure_equals( "time 1.0s elapsed as float represented as Timer::Watch in min", static_cast<tk::real>(w.min.count()), 0.0, precision ); ensure_equals( "time 1.0s elapsed as float represented as Timer::Watch in sec", static_cast<tk::real>(w.sec.count()), 1.0, precision ); } //! Charm chare having a tk::Timer object class CharmTimer : public CBase_CharmTimer { public: explicit CharmTimer( const tk::Timer& timer ) { // Create test result struct, assume test is ok tut::test_result tr( "Base/Timer", 7, "Charm:migrate tk::Timer 2", tut::test_result::result_type::ok ); // Evaluate test: The incoming timer's time point is queried here that // includes the time elapsed before the Charm++ chare has been created + the // migration time, so tested with a somewhat lose precision that includes // the approximate (guessed) migration time. try { ensure( "timer different after migrated: ", timer.dsec() > 1.0 ); } catch ( const failure& ex ) { tr.result = ex.result(); tr.exception_typeid = ex.type(); tr.message = ex.what(); } // Send back a new test result, with tag "2", signaling the second part. unittest::g_suiteProxy.evaluate( { tr.group, tr.name, std::to_string(tr.result), tr.message, tr.exception_typeid } ); } }; //! Test Charm++ migration of a tk::Timer object across the network //! \details Every Charm++ migration test, such as this one, consists of two //! unit tests: one for send and one for receive. Both triggers a TUT test, //! but the receive side is created manually, i.e., without the awareness of //! the TUT library. Unfortunately thus, there is no good way to count up //! these additional tests, and thus if a test such as this is added to the //! suite this number must be updated in UnitTest/TUTSuite.h in //! unittest::TUTSuite::m_migrations. template<> template<> void Timer_object::test< 6 >() { // This test spawns a new Charm++ chare. The "1" at the end of the test name // signals that this is only the first part of this test: the part up to // firing up an asynchronous Charm++ chare. The second part creates a new test // result, sending it back to the suite if successful. If that chare never // executes, the suite will hang waiting for that chare to call back. set_test_name( "Charm:migrate tk::Timer 1" ); tk::Timer timer; usleep( 1000000 ); // in micro-seconds, sleep for 1.0 second CProxy_CharmTimer::ckNew( timer ); // fire up Charm++ chare } //! Test querying a timer from a std::map template<> template<> void Timer_object::test< 7 >() { double prec = 1.0e-2; // only for this single test (to pass on Mac OS) set_test_name( "query timer from map" ); std::map< std::string, tk::Timer > timer; timer[ "some timer" ];// start timing, assign to label usleep( 1000000 ); // in micro-seconds, sleep for 1.0 second const auto t = tk::ref_find( timer, "some timer" ); ensure_equals( "timer different", t.dsec(), 1.0, prec ); } //! Test that querying timer from a map throws with garbage key template<> template<> void Timer_object::test< 8 >() { set_test_name( "query throws with non-existent key" ); try { std::map< std::string, tk::Timer > timer; timer[ "some timer" ];// start timing, assign to label tk::cref_find( timer, std::string("some non-existent timer") ); fail( "should throw exception" ); } catch ( tk::Exception& ) { // exception thrown, test ok } } } // tut:: #endif // DOXYGEN_GENERATING_OUTPUT #include "NoWarning/charmtimer.def.h"
40.436214
81
0.650926
franjgonzalez
feb42da88f6f4a48cae396ac03a3654e0f7a30f1
32,005
cpp
C++
cplus/libcfint/CFIntMimeTypeTableObj.cpp
msobkow/cfint_2_13
63ff9dfc85647066d0c8d61469ada572362e2b48
[ "Apache-2.0" ]
null
null
null
cplus/libcfint/CFIntMimeTypeTableObj.cpp
msobkow/cfint_2_13
63ff9dfc85647066d0c8d61469ada572362e2b48
[ "Apache-2.0" ]
null
null
null
cplus/libcfint/CFIntMimeTypeTableObj.cpp
msobkow/cfint_2_13
63ff9dfc85647066d0c8d61469ada572362e2b48
[ "Apache-2.0" ]
null
null
null
// Description: C++18 Table Object implementation for CFInt. /* * org.msscf.msscf.CFInt * * Copyright (c) 2020 Mark Stephen Sobkow * * MSS Code Factory CFInt 2.13 Internet Essentials * * Copyright 2020-2021 Mark Stephen Sobkow * * This file is part of MSS Code Factory. * * MSS Code Factory is available under dual commercial license from Mark Stephen * Sobkow, or under the terms of the GNU General Public License, Version 3 * or later. * * MSS Code Factory is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MSS Code Factory 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 MSS Code Factory. If not, see <https://www.gnu.org/licenses/>. * * Donations to support MSS Code Factory can be made at * https://www.paypal.com/paypalme2/MarkSobkow * * Please contact Mark Stephen Sobkow at mark.sobkow@gmail.com for commercial licensing. * * Manufactured by MSS Code Factory 2.12 */ #include <cflib/ICFLibPublic.hpp> using namespace std; #include <cfint/ICFIntPublic.hpp> #include <cfintobj/ICFIntObjPublic.hpp> #include <cfintobj/CFIntClusterObj.hpp> #include <cfintobj/CFIntHostNodeObj.hpp> #include <cfintobj/CFIntISOCcyObj.hpp> #include <cfintobj/CFIntISOCtryObj.hpp> #include <cfintobj/CFIntISOCtryCcyObj.hpp> #include <cfintobj/CFIntISOCtryLangObj.hpp> #include <cfintobj/CFIntISOLangObj.hpp> #include <cfintobj/CFIntISOTZoneObj.hpp> #include <cfintobj/CFIntLicenseObj.hpp> #include <cfintobj/CFIntMajorVersionObj.hpp> #include <cfintobj/CFIntMimeTypeObj.hpp> #include <cfintobj/CFIntMinorVersionObj.hpp> #include <cfintobj/CFIntSecAppObj.hpp> #include <cfintobj/CFIntSecDeviceObj.hpp> #include <cfintobj/CFIntSecFormObj.hpp> #include <cfintobj/CFIntSecGroupObj.hpp> #include <cfintobj/CFIntSecGroupFormObj.hpp> #include <cfintobj/CFIntSecGrpIncObj.hpp> #include <cfintobj/CFIntSecGrpMembObj.hpp> #include <cfintobj/CFIntSecSessionObj.hpp> #include <cfintobj/CFIntSecUserObj.hpp> #include <cfintobj/CFIntServiceObj.hpp> #include <cfintobj/CFIntServiceTypeObj.hpp> #include <cfintobj/CFIntSubProjectObj.hpp> #include <cfintobj/CFIntSysClusterObj.hpp> #include <cfintobj/CFIntTSecGroupObj.hpp> #include <cfintobj/CFIntTSecGrpIncObj.hpp> #include <cfintobj/CFIntTSecGrpMembObj.hpp> #include <cfintobj/CFIntTenantObj.hpp> #include <cfintobj/CFIntTldObj.hpp> #include <cfintobj/CFIntTopDomainObj.hpp> #include <cfintobj/CFIntTopProjectObj.hpp> #include <cfintobj/CFIntURLProtocolObj.hpp> #include <cfintobj/CFIntClusterEditObj.hpp> #include <cfintobj/CFIntHostNodeEditObj.hpp> #include <cfintobj/CFIntISOCcyEditObj.hpp> #include <cfintobj/CFIntISOCtryEditObj.hpp> #include <cfintobj/CFIntISOCtryCcyEditObj.hpp> #include <cfintobj/CFIntISOCtryLangEditObj.hpp> #include <cfintobj/CFIntISOLangEditObj.hpp> #include <cfintobj/CFIntISOTZoneEditObj.hpp> #include <cfintobj/CFIntLicenseEditObj.hpp> #include <cfintobj/CFIntMajorVersionEditObj.hpp> #include <cfintobj/CFIntMimeTypeEditObj.hpp> #include <cfintobj/CFIntMinorVersionEditObj.hpp> #include <cfintobj/CFIntSecAppEditObj.hpp> #include <cfintobj/CFIntSecDeviceEditObj.hpp> #include <cfintobj/CFIntSecFormEditObj.hpp> #include <cfintobj/CFIntSecGroupEditObj.hpp> #include <cfintobj/CFIntSecGroupFormEditObj.hpp> #include <cfintobj/CFIntSecGrpIncEditObj.hpp> #include <cfintobj/CFIntSecGrpMembEditObj.hpp> #include <cfintobj/CFIntSecSessionEditObj.hpp> #include <cfintobj/CFIntSecUserEditObj.hpp> #include <cfintobj/CFIntServiceEditObj.hpp> #include <cfintobj/CFIntServiceTypeEditObj.hpp> #include <cfintobj/CFIntSubProjectEditObj.hpp> #include <cfintobj/CFIntSysClusterEditObj.hpp> #include <cfintobj/CFIntTSecGroupEditObj.hpp> #include <cfintobj/CFIntTSecGrpIncEditObj.hpp> #include <cfintobj/CFIntTSecGrpMembEditObj.hpp> #include <cfintobj/CFIntTenantEditObj.hpp> #include <cfintobj/CFIntTldEditObj.hpp> #include <cfintobj/CFIntTopDomainEditObj.hpp> #include <cfintobj/CFIntTopProjectEditObj.hpp> #include <cfintobj/CFIntURLProtocolEditObj.hpp> #include <cfintobj/CFIntClusterTableObj.hpp> #include <cfintobj/CFIntHostNodeTableObj.hpp> #include <cfintobj/CFIntISOCcyTableObj.hpp> #include <cfintobj/CFIntISOCtryTableObj.hpp> #include <cfintobj/CFIntISOCtryCcyTableObj.hpp> #include <cfintobj/CFIntISOCtryLangTableObj.hpp> #include <cfintobj/CFIntISOLangTableObj.hpp> #include <cfintobj/CFIntISOTZoneTableObj.hpp> #include <cfintobj/CFIntLicenseTableObj.hpp> #include <cfintobj/CFIntMajorVersionTableObj.hpp> #include <cfintobj/CFIntMimeTypeTableObj.hpp> #include <cfintobj/CFIntMinorVersionTableObj.hpp> #include <cfintobj/CFIntSecAppTableObj.hpp> #include <cfintobj/CFIntSecDeviceTableObj.hpp> #include <cfintobj/CFIntSecFormTableObj.hpp> #include <cfintobj/CFIntSecGroupTableObj.hpp> #include <cfintobj/CFIntSecGroupFormTableObj.hpp> #include <cfintobj/CFIntSecGrpIncTableObj.hpp> #include <cfintobj/CFIntSecGrpMembTableObj.hpp> #include <cfintobj/CFIntSecSessionTableObj.hpp> #include <cfintobj/CFIntSecUserTableObj.hpp> #include <cfintobj/CFIntServiceTableObj.hpp> #include <cfintobj/CFIntServiceTypeTableObj.hpp> #include <cfintobj/CFIntSubProjectTableObj.hpp> #include <cfintobj/CFIntSysClusterTableObj.hpp> #include <cfintobj/CFIntTSecGroupTableObj.hpp> #include <cfintobj/CFIntTSecGrpIncTableObj.hpp> #include <cfintobj/CFIntTSecGrpMembTableObj.hpp> #include <cfintobj/CFIntTenantTableObj.hpp> #include <cfintobj/CFIntTldTableObj.hpp> #include <cfintobj/CFIntTopDomainTableObj.hpp> #include <cfintobj/CFIntTopProjectTableObj.hpp> #include <cfintobj/CFIntURLProtocolTableObj.hpp> namespace cfint { const std::string CFIntMimeTypeTableObj::CLASS_NAME( "CFIntMimeTypeTableObj" ); const std::string CFIntMimeTypeTableObj::TABLE_NAME( "MimeType" ); const std::string CFIntMimeTypeTableObj::TABLE_DBNAME( "MimeType" ); CFIntMimeTypeTableObj::CFIntMimeTypeTableObj() { schema = NULL; members = new std::map<cfint::CFIntMimeTypePKey, cfint::ICFIntMimeTypeObj*>(); allMimeType = NULL; indexByUNameIdx = new std::map< cfint::CFIntMimeTypeByUNameIdxKey, cfint::ICFIntMimeTypeObj*>(); } CFIntMimeTypeTableObj::CFIntMimeTypeTableObj( cfint::ICFIntSchemaObj* argSchema ) { schema = dynamic_cast<cfint::ICFIntSchemaObj*>( argSchema ); members = new std::map<cfint::CFIntMimeTypePKey, cfint::ICFIntMimeTypeObj*>(); allMimeType = NULL; indexByUNameIdx = new std::map< cfint::CFIntMimeTypeByUNameIdxKey, cfint::ICFIntMimeTypeObj*>(); } CFIntMimeTypeTableObj::~CFIntMimeTypeTableObj() { minimizeMemory(); if( indexByUNameIdx != NULL ) { delete indexByUNameIdx; indexByUNameIdx = NULL; } if( members != NULL ) { cfint::ICFIntMimeTypeObj* curMember; auto membersIter = members->begin(); while( membersIter != members->end() ) { curMember = membersIter->second; if( curMember != NULL ) { delete curMember; } members->erase( membersIter ); membersIter = members->begin(); } delete members; members = NULL; } } cfint::ICFIntSchemaObj* CFIntMimeTypeTableObj::getSchema() { return( schema ); } void CFIntMimeTypeTableObj::setSchema( cfint::ICFIntSchemaObj* value ) { schema = dynamic_cast<cfint::ICFIntSchemaObj*>( value ); } const std::string CFIntMimeTypeTableObj::getTableName() { return( TABLE_NAME ); } const std::string CFIntMimeTypeTableObj::getTableDbName() { return( TABLE_DBNAME ); } const classcode_t* CFIntMimeTypeTableObj::getObjQualifyingClassCode() { return( NULL ); } void CFIntMimeTypeTableObj::minimizeMemory() { if( allMimeType != NULL ) { allMimeType->clear(); delete allMimeType; allMimeType = NULL; } if( indexByUNameIdx != NULL ) { indexByUNameIdx->clear(); } if( members != NULL ) { cfint::ICFIntMimeTypeObj* cur = NULL; cfint::ICFIntMimeTypeEditObj* edit = NULL; auto iter = members->begin(); auto end = members->end(); while( iter != end ) { cur = iter->second; if( cur != NULL ) { iter->second = NULL; edit = cur->getEdit(); if( edit != NULL ) { edit->endEdit(); edit = NULL; } delete cur; cur = NULL; } iter ++; } members->clear(); } } cfint::ICFIntMimeTypeObj* CFIntMimeTypeTableObj::newInstance() { cfint::ICFIntMimeTypeObj* inst = dynamic_cast<cfint::ICFIntMimeTypeObj*>( new CFIntMimeTypeObj( schema ) ); return( inst ); } cfint::ICFIntMimeTypeEditObj* CFIntMimeTypeTableObj::newEditInstance( cfint::ICFIntMimeTypeObj* orig ) { cfint::ICFIntMimeTypeEditObj* edit = dynamic_cast<cfint::ICFIntMimeTypeEditObj*>( new CFIntMimeTypeEditObj( orig )); return( edit ); } cfint::ICFIntMimeTypeObj* CFIntMimeTypeTableObj::realizeMimeType( cfint::ICFIntMimeTypeObj* Obj ) { static const std::string S_ProcName( "realizeMimeType" ); static const std::string S_ExistingObj( "existingObj" ); static const std::string S_KeepObj( "keepObj" ); static const std::string S_Obj( "Obj" ); if( Obj == NULL ) { throw cflib::CFLibNullArgumentException( CLASS_NAME, S_ProcName, 1, S_Obj ); } cfint::ICFIntMimeTypeObj* obj = Obj; cfint::ICFIntMimeTypeObj* existingObj = NULL; cfint::CFIntMimeTypePKey* pkey = obj->getPKey(); cfint::ICFIntMimeTypeObj* keepObj = NULL; auto searchMembers = members->find( *pkey ); if( searchMembers != members->end() ) { existingObj = searchMembers->second; if( existingObj == NULL ) { throw cflib::CFLibNullArgumentException( CLASS_NAME, S_ProcName, 0, S_ExistingObj ); } keepObj = existingObj; pkey = keepObj->getPKey(); /* * We always rebind the data because if we're being called, some index may have been * updated and is refreshing it's data, which may require binding a different lookup key */ // Detach object from alternate and duplicate indexes, leave PKey alone if( indexByUNameIdx != NULL ) { cfint::CFIntMimeTypeByUNameIdxKey keyUNameIdx; keyUNameIdx.setRequiredName( keepObj->getRequiredName() ); auto removalProbe = indexByUNameIdx->find( keyUNameIdx ); if( removalProbe != indexByUNameIdx->end() ) { indexByUNameIdx->erase( removalProbe ); } } keepObj->setBuff( dynamic_cast<cfint::CFIntMimeTypeBuff*>( Obj->getBuff()->clone() ) ); // Attach new object to alternate and duplicate indexes -- PKey stays stable if( indexByUNameIdx != NULL ) { static const std::string S_AUNameIdxObj( "aUNameIdxObj" ); cfint::ICFIntMimeTypeObj* aUNameIdxObj = dynamic_cast<cfint::ICFIntMimeTypeObj*>( keepObj ); if( aUNameIdxObj == NULL ) { throw cflib::CFLibNullArgumentException( CLASS_NAME, S_ProcName, 0, S_AUNameIdxObj ); } cfint::CFIntMimeTypeByUNameIdxKey keyUNameIdx; keyUNameIdx.setRequiredName( keepObj->getRequiredName() ); indexByUNameIdx->insert( std::map< cfint::CFIntMimeTypeByUNameIdxKey, cfint::ICFIntMimeTypeObj* >::value_type( keyUNameIdx, aUNameIdxObj ) ); } if( allMimeType != NULL ) { allMimeType->insert( std::map< cfint::CFIntMimeTypePKey, cfint::ICFIntMimeTypeObj* >::value_type( *(keepObj->getPKey()), keepObj ) ); } } else { keepObj = obj; keepObj->setIsNew( false ); pkey = keepObj->getPKey(); // Attach new object to PKey, all, alternate, and duplicate indexes members->insert( std::map< cfint::CFIntMimeTypePKey, cfint::ICFIntMimeTypeObj* >::value_type( *(keepObj->getPKey()), keepObj ) ); // Attach new object to alternate and duplicate indexes -- PKey stay stable if( indexByUNameIdx != NULL ) { static const std::string S_AUNameIdxObj( "aUNameIdxObj" ); cfint::ICFIntMimeTypeObj* aUNameIdxObj = dynamic_cast<cfint::ICFIntMimeTypeObj*>( keepObj ); if( aUNameIdxObj == NULL ) { throw cflib::CFLibNullArgumentException( CLASS_NAME, S_ProcName, 0, S_AUNameIdxObj ); } cfint::CFIntMimeTypeByUNameIdxKey keyUNameIdx; keyUNameIdx.setRequiredName( keepObj->getRequiredName() ); indexByUNameIdx->insert( std::map< cfint::CFIntMimeTypeByUNameIdxKey, cfint::ICFIntMimeTypeObj* >::value_type( keyUNameIdx, aUNameIdxObj ) ); } if( allMimeType != NULL ) { allMimeType->insert( std::map< cfint::CFIntMimeTypePKey, cfint::ICFIntMimeTypeObj* >::value_type( *(keepObj->getPKey()), keepObj ) ); } } if( keepObj != obj ) { delete obj; obj = NULL; } // Something is leaking, so I've added this paranoid check if( ( keepObj != existingObj ) && ( existingObj != NULL ) ) { delete existingObj; existingObj = NULL; } return( keepObj ); } void CFIntMimeTypeTableObj::deepDisposeByIdIdx( const int32_t MimeTypeId ) { static const std::string S_ProcName( "deepDisposeByIdIdx" ); std::vector<cfint::ICFIntMimeTypeObj*> list; cfint::ICFIntMimeTypeObj* existingObj = readCachedMimeTypeByIdIdx( MimeTypeId ); if( existingObj != NULL ) { list.push_back( existingObj ); } cfint::ICFIntMimeTypeObj* cur = NULL; classcode_t classCode; auto listIter = list.begin(); auto listEnd = list.end(); while( listIter != listEnd ) { cur = *listIter; if( cur != NULL ) { classCode = cur->getClassCode(); if( classCode == cfint::CFIntMimeTypeBuff::CLASS_CODE ) { dynamic_cast<cfint::CFIntMimeTypeTableObj*>( schema->getMimeTypeTableObj() )->reallyDeepDisposeMimeType( dynamic_cast<cfint::ICFIntMimeTypeObj*>( cur ) ); } } listIter ++; } } void CFIntMimeTypeTableObj::deepDisposeByUNameIdx( const std::string& Name ) { static const std::string S_ProcName( "deepDisposeByUNameIdx" ); std::vector<cfint::ICFIntMimeTypeObj*> list; cfint::ICFIntMimeTypeObj* existingObj = readCachedMimeTypeByUNameIdx( Name ); if( existingObj != NULL ) { list.push_back( existingObj ); } cfint::ICFIntMimeTypeObj* cur = NULL; classcode_t classCode; auto listIter = list.begin(); auto listEnd = list.end(); while( listIter != listEnd ) { cur = *listIter; if( cur != NULL ) { classCode = cur->getClassCode(); if( classCode == cfint::CFIntMimeTypeBuff::CLASS_CODE ) { dynamic_cast<cfint::CFIntMimeTypeTableObj*>( schema->getMimeTypeTableObj() )->reallyDeepDisposeMimeType( dynamic_cast<cfint::ICFIntMimeTypeObj*>( cur ) ); } } listIter ++; } } void CFIntMimeTypeTableObj::reallyDeepDisposeMimeType( cfint::ICFIntMimeTypeObj* Obj ) { static const std::string S_ProcName( "reallyDeepDisposeMimeType" ); if( Obj == NULL ) { return; } cfint::ICFIntMimeTypeObj* obj = Obj; classcode_t classCode = obj->getClassCode(); if( classCode == cfint::CFIntMimeTypeBuff::CLASS_CODE ) { dynamic_cast<cfint::CFIntMimeTypeTableObj*>( schema->getMimeTypeTableObj() )->reallyDetachFromIndexesMimeType( dynamic_cast<cfint::ICFIntMimeTypeObj*>( obj ) ); } if( obj->getEdit() != NULL ) { obj->endEdit(); } delete obj; obj = NULL; } cfint::ICFIntMimeTypeObj* CFIntMimeTypeTableObj::createMimeType( cfint::ICFIntMimeTypeEditObj* Obj ) { static const std::string S_ProcName( "createMimeType" ); static const std::string S_Obj( "obj" ); static const std::string S_Cloneable( "cloneable" ); static const std::string S_ClonedBuff( "clonedbuff" ); CFLIB_EXCEPTION_DECLINFO cfint::ICFIntMimeTypeObj* obj = dynamic_cast<cfint::ICFIntMimeTypeObj*>( Obj->getOrig() ); try { cfint::CFIntMimeTypeBuff* buff = dynamic_cast<cfint::CFIntMimeTypeBuff*>( Obj->getBuff()->clone() ); // C++18 version of create returns a new buffer instance and takes over ownership of the passed-in buffer // MSS TODO WORKING The xmsg client will need to return the buffer instance created by processing // the response message, while xmsg rqst will have to delete the backing store instance // it receives after preparing the reply message so that memory doesn't leak on every request. cflib::ICFLibCloneableObj* cloneable = dynamic_cast<ICFIntSchema*>( schema->getBackingStore() )->getTableMimeType()->createMimeType( schema->getAuthorization(), buff ); if( cloneable == NULL ) { throw cflib::CFLibNullArgumentException( CLASS_NAME, S_ProcName, 0, S_Cloneable ); } Obj->endEdit(); obj->setBuff( dynamic_cast<cfint::CFIntMimeTypeBuff*>( cloneable ) ); obj = dynamic_cast<cfint::ICFIntMimeTypeObj*>( obj->realize() ); if( obj == NULL ) { throw cflib::CFLibNullArgumentException( CLASS_NAME, S_ProcName, 0, S_Obj ); } } CFLIB_EXCEPTION_CATCH_FALLTHROUGH if( ! CFLIB_EXCEPTION_EMPTY ) { if( obj->getEdit() != NULL ) { obj->endEdit(); } if( obj->getIsNew() ) { delete obj; obj = NULL; } CFLIB_EXCEPTION_RETHROW_CFLIBEXCEPTION } return( obj ); } cfint::ICFIntMimeTypeObj* CFIntMimeTypeTableObj::readMimeType( cfint::CFIntMimeTypePKey* pkey, bool forceRead ) { static const std::string S_Obj( "obj" ); static const std::string S_Realized( "realized" ); static const std::string S_ProcName( "readMimeType" ); cfint::ICFIntMimeTypeObj* obj = NULL; cfint::ICFIntMimeTypeObj* realized = NULL; if( ! forceRead ) { auto searchMembers = members->find( *pkey ); if( searchMembers != members->end() ) { // obj could be NULL if cache misses is enabled obj = searchMembers->second; realized = obj; } } if( forceRead || ( obj == NULL ) ) { cfint::CFIntMimeTypeBuff* readBuff = dynamic_cast<ICFIntSchema*>( schema->getBackingStore() )->getTableMimeType()->readDerivedByIdIdx( schema->getAuthorization(), pkey->getRequiredMimeTypeId() ); if( readBuff != NULL ) { obj = dynamic_cast<cfint::CFIntMimeTypeTableObj*>( schema->getMimeTypeTableObj() )->newInstance(); obj->setBuff( readBuff ); realized = dynamic_cast<cfint::ICFIntMimeTypeObj*>( obj->realize() ); if( realized == NULL ) { throw cflib::CFLibNullArgumentException( CLASS_NAME, S_ProcName, 0, S_Realized ); } // No need to delete obj -- realize() auto-destructs the instance it decided to discard obj = NULL; } } return( realized ); } cfint::ICFIntMimeTypeObj* CFIntMimeTypeTableObj::lockMimeType( cfint::CFIntMimeTypePKey* pkey ) { static const std::string S_ProcName( "lockMimeType" ); cfint::ICFIntMimeTypeObj* locked = NULL; cfint::CFIntMimeTypeBuff* lockBuff = dynamic_cast<ICFIntSchema*>( schema->getBackingStore() )->getTableMimeType()->lockDerived( schema->getAuthorization(), pkey ); if( lockBuff != NULL ) { locked = dynamic_cast<cfint::CFIntMimeTypeTableObj*>( schema->getMimeTypeTableObj() )->newInstance(); locked->setBuff( lockBuff ); locked = dynamic_cast<cfint::ICFIntMimeTypeObj*>( locked->realize() ); } else { return( NULL ); } return( locked ); } std::vector<cfint::ICFIntMimeTypeObj*> CFIntMimeTypeTableObj::readAllMimeType( bool forceRead ) { static const std::string S_ProcName( "readAllMimeType" ); static const std::string S_Idx( "idx" ); static const std::string S_Realized( "realized" ); CFLIB_EXCEPTION_DECLINFO cfint::ICFIntMimeTypeObj* realized = NULL; if( forceRead || ( allMimeType == NULL ) ) { std::map<cfint::CFIntMimeTypePKey, cfint::ICFIntMimeTypeObj*>* map = new std::map<cfint::CFIntMimeTypePKey,cfint::ICFIntMimeTypeObj*>(); allMimeType = map; std::TCFLibOwningVector<cfint::CFIntMimeTypeBuff*> buffList = dynamic_cast<ICFIntSchema*>( schema->getBackingStore() )->getTableMimeType()->readAllDerived( schema->getAuthorization() ); cfint::CFIntMimeTypeBuff* buff = NULL; cfint::ICFIntMimeTypeObj* obj = NULL; try { for( size_t idx = 0; idx < buffList.size(); idx ++ ) { buff = buffList[ idx ]; buffList[ idx ] = NULL; obj = newInstance(); obj->setBuff( buff ); realized = dynamic_cast<cfint::ICFIntMimeTypeObj*>( obj->realize() ); if( realized == NULL ) { throw cflib::CFLibNullArgumentException( CLASS_NAME, S_ProcName, 0, S_Realized ); } allMimeType->insert( std::map< cfint::CFIntMimeTypePKey, cfint::ICFIntMimeTypeObj* >::value_type( *(realized->getPKey()), realized ) ); // No need to delete obj -- realize() auto-destructs the instance it decided to discard obj = NULL; } } CFLIB_EXCEPTION_CATCH_FALLTHROUGH if( ( obj != NULL ) && obj->getIsNew() ) { delete obj; obj = NULL; } CFLIB_EXCEPTION_RETHROW_CFLIBEXCEPTION } size_t len = allMimeType->size(); std::vector<cfint::ICFIntMimeTypeObj*> arr; auto valIter = allMimeType->begin(); size_t idx = 0; while( valIter != allMimeType->end() ) { arr.push_back( valIter->second ); valIter ++; } return( arr ); } cfint::ICFIntMimeTypeObj* CFIntMimeTypeTableObj::readMimeTypeByIdIdx( const int32_t MimeTypeId, bool forceRead ) { static const std::string S_ProcName( "readMimeTypeByIdIdx" ); static const std::string S_Realized( "realized" ); cfint::CFIntMimeTypePKey pkey; pkey.setRequiredMimeTypeId( MimeTypeId ); cfint::ICFIntMimeTypeObj* obj = readMimeType( &pkey, forceRead ); return( obj ); } cfint::ICFIntMimeTypeObj* CFIntMimeTypeTableObj::readMimeTypeByUNameIdx( const std::string& Name, bool forceRead ) { static const std::string S_ProcName( "readMimeTypeByUNameIdx" ); static const std::string S_Realized( "realized" ); if( indexByUNameIdx == NULL ) { indexByUNameIdx = new std::map< cfint::CFIntMimeTypeByUNameIdxKey, cfint::ICFIntMimeTypeObj*>(); } cfint::CFIntMimeTypeByUNameIdxKey key; key.setRequiredName( Name ); cfint::ICFIntMimeTypeObj* obj = NULL; cfint::ICFIntMimeTypeObj* realized = NULL; if( ! forceRead ) { auto searchIndexByUNameIdx = indexByUNameIdx->find( key ); if( searchIndexByUNameIdx != indexByUNameIdx->end() ) { // Note: obj may be null if cache misses is enabled obj = searchIndexByUNameIdx->second; realized = obj; } } if( forceRead || ( obj == NULL ) ) { cfint::CFIntMimeTypeBuff* buff = dynamic_cast<ICFIntSchema*>( schema->getBackingStore() )->getTableMimeType()->readDerivedByUNameIdx( schema->getAuthorization(), Name ); if( buff != NULL ) { obj = dynamic_cast<cfint::CFIntMimeTypeTableObj*>( schema->getMimeTypeTableObj() )->newInstance(); obj->setBuff( buff ); realized = dynamic_cast<cfint::ICFIntMimeTypeObj*>( obj->realize() ); if( realized == NULL ) { throw cflib::CFLibNullArgumentException( CLASS_NAME, S_ProcName, 0, S_Realized ); } indexByUNameIdx->insert( std::map< cfint::CFIntMimeTypeByUNameIdxKey, cfint::ICFIntMimeTypeObj*>::value_type( key, dynamic_cast<cfint::ICFIntMimeTypeObj*>( realized ) ) ); // No need to delete obj -- realize() auto-destructs the instance it decided to discard obj = realized; } } return( obj ); } cfint::ICFIntMimeTypeObj* CFIntMimeTypeTableObj::readMimeTypeByLookupUNameIdx( const std::string& Name, bool forceRead ) { static const std::string S_Realized( "realized" ); static const std::string S_Obj( "obj" ); static const std::string S_ProcName( "readMimeTypeByLookupUNameIdx" ); if( indexByUNameIdx == NULL ) { indexByUNameIdx = new std::map< cfint::CFIntMimeTypeByUNameIdxKey, cfint::ICFIntMimeTypeObj*>(); } cfint::CFIntMimeTypeByUNameIdxKey key; key.setRequiredName( Name ); cfint::ICFIntMimeTypeObj* obj = NULL; cfint::ICFIntMimeTypeObj* realized = NULL; if( ! forceRead ) { auto searchIndexByUNameIdx = indexByUNameIdx->find( key ); if( searchIndexByUNameIdx != indexByUNameIdx->end() ) { obj = searchIndexByUNameIdx->second; } } if( forceRead || ( obj == NULL ) ) { cfint::CFIntMimeTypeBuff* buff = dynamic_cast<ICFIntSchema*>( schema->getBackingStore() )->getTableMimeType()->readDerivedByLookupUNameIdx( schema->getAuthorization(), Name ); if( buff != NULL ) { obj = dynamic_cast<cfint::ICFIntMimeTypeObj*>( dynamic_cast<cfint::CFIntMimeTypeTableObj*>( schema->getMimeTypeTableObj() )->newInstance() ); obj->setBuff( buff ); realized = dynamic_cast<cfint::ICFIntMimeTypeObj*>( obj->realize() ); if( realized == NULL ) { throw cflib::CFLibNullArgumentException( CLASS_NAME, S_ProcName, 0, S_Realized ); } indexByUNameIdx->insert( std::map< cfint::CFIntMimeTypeByUNameIdxKey, cfint::ICFIntMimeTypeObj*>::value_type( key, dynamic_cast<cfint::ICFIntMimeTypeObj*>( realized ) ) ); // No need to delete obj -- realize() auto-destructs the instance it decided to discard obj = realized; } } return( obj ); } cfint::ICFIntMimeTypeObj* CFIntMimeTypeTableObj::readCachedMimeType( cfint::CFIntMimeTypePKey* pkey ) { static const std::string S_Obj( "obj" ); static const std::string S_Realized( "realized" ); static const std::string S_ProcName( "readMimeType" ); cfint::ICFIntMimeTypeObj* obj = NULL; cfint::ICFIntMimeTypeObj* realized = NULL; auto searchMembers = members->find( *pkey ); if( searchMembers != members->end() ) { // obj could be NULL if cache misses is enabled obj = searchMembers->second; realized = obj; } return( realized ); } cfint::ICFIntMimeTypeObj* CFIntMimeTypeTableObj::readCachedMimeTypeByIdIdx( const int32_t MimeTypeId ) { static const std::string S_ProcName( "readCachedMimeTypeByIdIdx" ); static const std::string S_Realized( "realized" ); cfint::CFIntMimeTypePKey pkey; pkey.setRequiredMimeTypeId( MimeTypeId ); cfint::ICFIntMimeTypeObj* obj = readCachedMimeType( &pkey ); return( obj ); } cfint::ICFIntMimeTypeObj* CFIntMimeTypeTableObj::readCachedMimeTypeByUNameIdx( const std::string& Name ) { static const std::string S_ProcName( "readCachedMimeTypeByUNameIdx" ); static const std::string S_Realized( "realized" ); if( indexByUNameIdx == NULL ) { indexByUNameIdx = new std::map< cfint::CFIntMimeTypeByUNameIdxKey, cfint::ICFIntMimeTypeObj*>(); } cfint::CFIntMimeTypeByUNameIdxKey key; key.setRequiredName( Name ); cfint::ICFIntMimeTypeObj* obj = NULL; auto searchIndexByUNameIdx = indexByUNameIdx->find( key ); if( searchIndexByUNameIdx != indexByUNameIdx->end() ) { // Note: obj may be null if cache misses is enabled obj = searchIndexByUNameIdx->second; } else { for( auto iterMembers = members->begin(); ( obj == NULL ) && ( iterMembers != members->end() ); iterMembers ++ ) { obj = iterMembers->second; if( obj != NULL ) { if( *(dynamic_cast<cfint::CFIntMimeTypeBuff*>( obj->getBuff() ) ) != key ) { obj = NULL; } } } } return( obj ); } cfint::ICFIntMimeTypeObj* CFIntMimeTypeTableObj::readCachedMimeTypeByLookupUNameIdx( const std::string& Name ) { static const std::string S_Realized( "realized" ); static const std::string S_Obj( "obj" ); static const std::string S_ProcName( "readCachedMimeTypeByLookupUNameIdx" ); if( indexByUNameIdx == NULL ) { indexByUNameIdx = new std::map< cfint::CFIntMimeTypeByUNameIdxKey, cfint::ICFIntMimeTypeObj*>(); } cfint::CFIntMimeTypeByUNameIdxKey key; key.setRequiredName( Name ); cfint::ICFIntMimeTypeObj* obj = NULL; cfint::ICFIntMimeTypeObj* realized = NULL; auto searchIndexByUNameIdx = indexByUNameIdx->find( key ); if( searchIndexByUNameIdx != indexByUNameIdx->end() ) { obj = searchIndexByUNameIdx->second; } else { for( auto iterMembers = members->begin(); ( obj == NULL ) && ( iterMembers != members->end() ); iterMembers ++ ) { obj = iterMembers->second; if( obj != NULL ) { if( *(dynamic_cast<cfint::CFIntMimeTypeBuff*>( obj->getBuff() ) ) != key ) { obj = NULL; } } } } return( obj ); } cfint::ICFIntMimeTypeObj* CFIntMimeTypeTableObj::updateMimeType( cfint::ICFIntMimeTypeEditObj* Obj ) { static const std::string S_ProcName( "updateMimeType" ); static const std::string S_Obj( "obj" ); static const std::string S_Updated( "updated" ); CFLIB_EXCEPTION_DECLINFO cfint::ICFIntMimeTypeObj* obj = dynamic_cast<cfint::ICFIntMimeTypeObj*>( Obj->getOrig() ); try { cfint::CFIntMimeTypeBuff* updated = dynamic_cast<ICFIntSchema*>( schema->getBackingStore() )->getTableMimeType()->updateMimeType( schema->getAuthorization(), dynamic_cast<cfint::CFIntMimeTypeBuff*>( Obj->getMimeTypeBuff()->clone() ) ); if( updated == NULL ) { throw cflib::CFLibNullArgumentException( CLASS_NAME, S_ProcName, 0, S_Updated ); } obj = dynamic_cast<cfint::ICFIntMimeTypeObj*>( dynamic_cast<cfint::CFIntMimeTypeTableObj*>( schema->getMimeTypeTableObj() )->newInstance() ); obj->setBuff( updated ); obj = dynamic_cast<cfint::ICFIntMimeTypeObj*>( obj->realize() ); if( obj == NULL ) { throw cflib::CFLibNullArgumentException( CLASS_NAME, S_ProcName, 0, S_Obj ); } if( obj->getEdit() != NULL ) { obj->endEdit(); } } CFLIB_EXCEPTION_CATCH_FALLTHROUGH if( ! CFLIB_EXCEPTION_EMPTY ) { if( obj->getEdit() != NULL ) { obj->endEdit(); } CFLIB_EXCEPTION_RETHROW_CFLIBEXCEPTION } return( obj ); } void CFIntMimeTypeTableObj::deleteMimeType( cfint::ICFIntMimeTypeEditObj* Obj ) { cfint::ICFIntMimeTypeObj* obj = Obj; dynamic_cast<ICFIntSchema*>( schema->getBackingStore() )->getTableMimeType()->deleteMimeType( schema->getAuthorization(), obj->getMimeTypeBuff() ); deepDisposeByIdIdx( obj->getRequiredMimeTypeId() ); } void CFIntMimeTypeTableObj::deleteMimeTypeByIdIdx( const int32_t MimeTypeId ) { cfint::CFIntMimeTypePKey pkey; pkey.setRequiredMimeTypeId( MimeTypeId ); cfint::ICFIntMimeTypeObj* obj = readMimeType( &pkey, true ); if( obj != NULL ) { cfint::ICFIntMimeTypeEditObj* editObj = dynamic_cast<cfint::ICFIntMimeTypeEditObj*>( obj->getEdit() ); if( editObj == NULL ) { editObj = dynamic_cast<cfint::ICFIntMimeTypeEditObj*>( obj->beginEdit() ); } if( editObj != NULL ) { editObj->deleteInstance(); editObj = NULL; } } } void CFIntMimeTypeTableObj::deleteMimeTypeByUNameIdx( const std::string& Name ) { if( indexByUNameIdx == NULL ) { indexByUNameIdx = new std::map< cfint::CFIntMimeTypeByUNameIdxKey, cfint::ICFIntMimeTypeObj*>(); } cfint::CFIntMimeTypeByUNameIdxKey key; key.setRequiredName( Name ); cfint::ICFIntMimeTypeObj* obj = NULL; auto searchIndexByUNameIdx = indexByUNameIdx->find( key ); if( searchIndexByUNameIdx != indexByUNameIdx->end() ) { dynamic_cast<ICFIntSchema*>( schema->getBackingStore() )->getTableMimeType()->deleteMimeTypeByUNameIdx( schema->getAuthorization(), Name ); } else { dynamic_cast<ICFIntSchema*>( schema->getBackingStore() )->getTableMimeType()->deleteMimeTypeByUNameIdx( schema->getAuthorization(), Name ); } deepDisposeByUNameIdx( Name ); } void CFIntMimeTypeTableObj::reallyDetachFromIndexesMimeType( cfint::ICFIntMimeTypeObj* Obj ) { static const std::string S_ProcName( "reallyDetachFromIndexesMimeType" ); static const std::string S_Obj( "Obj" ); static const std::string S_ExistingObj( "ExistingObj" ); if( Obj == NULL ) { throw cflib::CFLibNullArgumentException( CLASS_NAME, S_ProcName, 1, S_Obj ); } cfint::ICFIntMimeTypeObj* obj = Obj; cfint::CFIntMimeTypePKey* pkey = obj->getPKey(); auto searchMembers = members->find( *pkey ); if( searchMembers != members->end() ) { cfint::ICFIntMimeTypeObj* existingObj = searchMembers->second; if( existingObj == NULL ) { throw cflib::CFLibNullArgumentException( CLASS_NAME, S_ProcName, 0, S_ExistingObj ); } if( indexByUNameIdx != NULL ) { cfint::CFIntMimeTypeByUNameIdxKey keyUNameIdx; keyUNameIdx.setRequiredName( obj->getRequiredName() ); auto removalProbe = indexByUNameIdx->find( keyUNameIdx ); if( removalProbe != indexByUNameIdx->end() ) { indexByUNameIdx->erase( removalProbe ); } } members->erase( searchMembers ); } } }
37.389019
188
0.716732
msobkow
feb62b058d2646a7bba9f74e3efa21e9785d546e
5,352
cc
C++
src/core/heap.cc
upscalesoftware/swoole-src
c99796171a5f9bb90450b570a400e2496490c44b
[ "Apache-2.0" ]
2
2020-08-16T01:24:24.000Z
2021-07-02T03:13:31.000Z
src/core/heap.cc
sunnyMlon/swoole-src
c99796171a5f9bb90450b570a400e2496490c44b
[ "Apache-2.0" ]
null
null
null
src/core/heap.cc
sunnyMlon/swoole-src
c99796171a5f9bb90450b570a400e2496490c44b
[ "Apache-2.0" ]
null
null
null
/* +----------------------------------------------------------------------+ | Swoole | +----------------------------------------------------------------------+ | This source file is subject to version 2.0 of the Apache license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.apache.org/licenses/LICENSE-2.0.html | | If you did not receive a copy of the Apache2.0 license and are unable| | to obtain it through the world-wide-web, please send a note to | | license@swoole.com so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: Tianfeng Han <mikan.tenny@gmail.com> | +----------------------------------------------------------------------+ */ #include "swoole.h" #include "heap.h" #define left(i) ((i) << 1) #define right(i) (((i) << 1) + 1) #define parent(i) ((i) >> 1) static void swHeap_bubble_up(swHeap *heap, uint32_t i); static uint32_t swHeap_maxchild(swHeap *heap, uint32_t i); static void swHeap_percolate_down(swHeap *heap, uint32_t i); swHeap *swHeap_new(size_t n, uint8_t type) { swHeap *heap = (swHeap *) sw_malloc(sizeof(swHeap)); if (!heap) { return nullptr; } if (!(heap->nodes = (swHeap_node **) sw_malloc((n + 1) * sizeof(void *)))) { sw_free(heap); return nullptr; } heap->num = 1; heap->size = (n + 1); heap->type = type; return heap; } void swHeap_free(swHeap *heap) { sw_free(heap->nodes); sw_free(heap); } static sw_inline int swHeap_compare(uint8_t type, uint64_t a, uint64_t b) { if (type == SW_MIN_HEAP) { return a > b; } else { return a < b; } } uint32_t swHeap_size(swHeap *q) { return (q->num - 1); } static uint32_t swHeap_maxchild(swHeap *heap, uint32_t i) { uint32_t child_i = left(i); if (child_i >= heap->num) { return 0; } swHeap_node *child_node = heap->nodes[child_i]; if ((child_i + 1) < heap->num && swHeap_compare(heap->type, child_node->priority, heap->nodes[child_i + 1]->priority)) { child_i++; } return child_i; } static void swHeap_bubble_up(swHeap *heap, uint32_t i) { swHeap_node *moving_node = heap->nodes[i]; uint32_t parent_i; for (parent_i = parent(i); (i > 1) && swHeap_compare(heap->type, heap->nodes[parent_i]->priority, moving_node->priority); i = parent_i, parent_i = parent(i)) { heap->nodes[i] = heap->nodes[parent_i]; heap->nodes[i]->position = i; } heap->nodes[i] = moving_node; moving_node->position = i; } static void swHeap_percolate_down(swHeap *heap, uint32_t i) { uint32_t child_i; swHeap_node *moving_node = heap->nodes[i]; while ((child_i = swHeap_maxchild(heap, i)) && swHeap_compare(heap->type, moving_node->priority, heap->nodes[child_i]->priority)) { heap->nodes[i] = heap->nodes[child_i]; heap->nodes[i]->position = i; i = child_i; } heap->nodes[i] = moving_node; moving_node->position = i; } swHeap_node *swHeap_push(swHeap *heap, uint64_t priority, void *data) { void *tmp; uint32_t i; uint32_t newsize; if (heap->num >= heap->size) { newsize = heap->size * 2; if (!(tmp = sw_realloc(heap->nodes, sizeof(void *) * newsize))) { return nullptr; } heap->nodes = (swHeap_node **) tmp; heap->size = newsize; } swHeap_node *node = (swHeap_node *) sw_malloc(sizeof(swHeap_node)); if (!node) { return nullptr; } node->priority = priority; node->data = data; i = heap->num++; heap->nodes[i] = node; swHeap_bubble_up(heap, i); return node; } void swHeap_change_priority(swHeap *heap, uint64_t new_priority, void *ptr) { swHeap_node *node = (swHeap_node *) ptr; uint32_t pos = node->position; uint64_t old_pri = node->priority; node->priority = new_priority; if (swHeap_compare(heap->type, old_pri, new_priority)) { swHeap_bubble_up(heap, pos); } else { swHeap_percolate_down(heap, pos); } } void swHeap_remove(swHeap *heap, swHeap_node *node) { uint32_t pos = node->position; heap->nodes[pos] = heap->nodes[--heap->num]; if (swHeap_compare(heap->type, node->priority, heap->nodes[pos]->priority)) { swHeap_bubble_up(heap, pos); } else { swHeap_percolate_down(heap, pos); } } void *swHeap_pop(swHeap *heap) { swHeap_node *head; if (!heap || heap->num == 1) { return nullptr; } head = heap->nodes[1]; heap->nodes[1] = heap->nodes[--heap->num]; swHeap_percolate_down(heap, 1); void *data = head->data; sw_free(head); return data; } void *swHeap_peek(swHeap *heap) { if (heap->num == 1) { return nullptr; } swHeap_node *node = heap->nodes[1]; if (!node) { return nullptr; } return node->data; } void swHeap_print(swHeap *heap) { for (uint32_t i = 1; i < heap->num; i++) { printf("#%d\tpriority=%ld, data=%p\n", i, (long) heap->nodes[i]->priority, heap->nodes[i]->data); } }
29.086957
105
0.560725
upscalesoftware
feb6e5965a4dcbd3a8ec03fe55e54d8f251289d5
14,666
cpp
C++
src/parse.cpp
Phildo/expandpass
7e4a5ac77e6b194dcbcb26284b1201ba841fee77
[ "MIT" ]
165
2018-03-19T15:06:33.000Z
2021-11-15T15:44:39.000Z
src/parse.cpp
Phildo/expandpass
7e4a5ac77e6b194dcbcb26284b1201ba841fee77
[ "MIT" ]
3
2021-01-05T05:04:10.000Z
2021-12-24T03:18:57.000Z
src/parse.cpp
Phildo/expandpass
7e4a5ac77e6b194dcbcb26284b1201ba841fee77
[ "MIT" ]
11
2018-04-30T17:51:21.000Z
2021-05-01T03:37:54.000Z
#include "parse.h" #include "util.h" int parse_child(FILE *fp, int unquoted, int *line_n, char *buff, char **b, group *g, group *prev_g, int depth, parse_error *er) { g->countable = 1; //until proven otherwise int n_chars = 0; while(buff[n_chars] != '\0') n_chars++; size_t line_buff_len = max_read_line_len; char *s = *b; while(g->type == GROUP_TYPE_NULL) { if(*s == '\0') { n_chars = getline(&buff, &line_buff_len, fp); *line_n = *line_n+1; if(n_chars <= 0) { *buff = '\0'; er->error = ERROR_EOF; safe_sprintf(er->txt,"ERROR: EOF\nline %d\n",*line_n); return 0; } s = buff; } while(*s == ' ' || *s == '\t') s++; if(*s == '<' ) { g->type = GROUP_TYPE_SEQUENCE; s++; } else if(*s == '{' ) { g->type = GROUP_TYPE_OPTION; s++; } else if(*s == '(' ) { g->type = GROUP_TYPE_PERMUTE; s++; } else if(*s == '"' ) { g->type = GROUP_TYPE_CHARS; s++; } else if(*s == '[' ) { g->type = GROUP_TYPE_MODIFICATION; s++; } else if(*s == '#' ) { g->type = GROUP_TYPE_NULL; s++; *s = '\0'; } else if(*s == '\n') { g->type = GROUP_TYPE_NULL; s++; *s = '\0'; } else if(*s == '\0') { g->type = GROUP_TYPE_NULL; s++; *s = '\0'; } else if(*s == '-') { char *c; g->type = GROUP_TYPE_CHARS; g->n = 0; g->chars = (char *)safe_malloc(sizeof(char)*g->n+1); c = g->chars; s++; *c = '\0'; *b = s; return 1; } else if(unquoted && *s != '>' && *s != '}' && *s != ')' && *s != ']') { char *c; g->type = GROUP_TYPE_CHARS; if(*s == '\\') s++; g->n = 1; g->chars = (char *)safe_malloc(sizeof(char)*g->n+1); c = g->chars; *c = *s; c++; s++; *c = '\0'; *b = s; return 1; } else { *b = s; er->error = ERROR_INVALID_LINE; if(buff[n_chars-1] == '\n') n_chars--; buff[n_chars] = '\0'; safe_sprintf(er->txt,"ERROR: Invalid line\nline %d ( %s )\n",*line_n,buff); return 0; } if(g->type != GROUP_TYPE_CHARS) { while(*s == ' ' || *s == '\t') s++; } char *c; if(g->type == GROUP_TYPE_OPTION) g->countable = 0; //TODO: this limitation renders "countability" a farce switch(g->type) { case GROUP_TYPE_SEQUENCE: case GROUP_TYPE_OPTION: case GROUP_TYPE_PERMUTE: g->n = 0; *b = s; if(g->type == GROUP_TYPE_SEQUENCE) { if(!parse_tag(fp, line_n, buff, b, &g->tag_u, 1, er)) return 0; if(!parse_tag(fp, line_n, buff, b, &g->tag_g, 0, er)) return 0; if(g->tag_u) g->countable = 0; if(g->tag_g) g->countable = 0; } return parse_childs(fp, unquoted, line_n, buff, b, g, depth+1, er); break; case GROUP_TYPE_CHARS: c = s; while(*c != '"' && *c != '\n' && *c != '\0') { if(*c == '\\') c++; c++; } if(*c == '"') { g->n = (c-s); g->chars = (char *)safe_malloc(sizeof(char)*g->n+1); c = g->chars; while(*s != '"' && *s != '\n' && *s != '\0') { if(*s == '\\') { s++; g->n--; } *c = *s; c++; s++; } if(*s != '"') { er->error = ERROR_UNTERMINATED_STRING; if(buff[n_chars-1] == '\n') n_chars--; buff[n_chars] = '\0'; safe_sprintf(er->txt,"ERROR: Unterminated string\nline %d ( %s )\n",*line_n,buff); return 0; } s++; *c = '\0'; } else { er->error = ERROR_INVALID_STRING; if(buff[n_chars-1] == '\n') n_chars--; buff[n_chars] = '\0'; safe_sprintf(er->txt,"ERROR: Invalid characters after begining string\nline %d ( %s )\n",*line_n,buff); return 0; } break; case GROUP_TYPE_MODIFICATION: //special case if(!prev_g) { er->error = ERROR_UNPARENTED_MODIFICATION; if(buff[n_chars-1] == '\n') n_chars--; buff[n_chars] = '\0'; safe_sprintf(er->txt,"ERROR: Modification with no previous group\nline %d ( %s )\n",*line_n,buff); return 0; } *b = s; return parse_modifications(fp, line_n, buff, b, prev_g, er); break; case GROUP_TYPE_NULL: ; break; default: //appease compiler break; } } *b = s; return 1; } int parse_tag(FILE *fp, int *line_n, char *buff, char **b, tag *t, int u, parse_error *er) { assert(!*t); int n_chars = 0; while(buff[n_chars] != '\0') n_chars++; size_t line_buff_len = max_read_line_len; char *s = *b; while(1) { if(*s == '\0') { n_chars = getline(&buff, &line_buff_len, fp); *line_n = *line_n+1; if(n_chars <= 0) { *buff = '\0'; er->error = ERROR_BADEOF; safe_sprintf(er->txt,"ERROR: EOF parsing tag\nline %d\n",*line_n); return 0; } s = buff; } else if(*s == ' ' || *s == '\t') s++; else break; } int parsed = 0; int d; if((u && *s == 'U') || (!u && *s == 'G')) { s++; while((d = parse_number(s,&parsed)) != -1) { if(parsed < 1 || parsed >= max_tag_count) { er->error = ERROR_TAG_RANGE; if(u) safe_sprintf(er->txt,"ERROR: unique tag outside of valid range [1-%d]\nline %d\n",max_tag_count-1,*line_n); else safe_sprintf(er->txt,"ERROR: group tag outside of valid range [1-%d]\nline %d\n",max_tag_count-1,*line_n); return 0; } s += d; *t |= 1 << (parsed-1); if(*s == ',') s++; } if(!*t) { er->error = ERROR_TAG_SPECIFY; if(u) safe_sprintf(er->txt,"ERROR: unique tag not specified\nline %d\n",*line_n); else safe_sprintf(er->txt,"ERROR: group tag not specified\nline %d\n",*line_n); return 0; } } *b = s; return 1; } int parse_modification(FILE *fp, int *line_n, char *buff, char **b, modification *m, parse_error *er) { int n_chars = 0; while(buff[n_chars] != '\0') n_chars++; size_t line_buff_len = max_read_line_len; char *s = *b; int found = 0; while(!found) { if(*s == '\0') { n_chars = getline(&buff, &line_buff_len, fp); *line_n = *line_n+1; if(n_chars <= 0) { *buff = '\0'; er->error = ERROR_BADEOF; safe_sprintf(er->txt,"ERROR: EOF parsing modification\nline %d\n",*line_n); return 0; } s = buff; } int d = 1; while(d > 0) { while(*s == ' ' || *s == '\t') s++; if(*s == 'c' ) { s++; d = parse_number(s,&m->n_copys); m->n_copys -= 1; } //m->n_copys = 0 means "just do it once" (ie default) else if(*s == 'd' ) { s++; d = parse_number(s,&m->n_deletions); } else if(*s == 's' ) { s++; d = parse_number(s,&m->n_substitutions); } else if(*s == 'i' ) { s++; d = parse_number(s,&m->n_injections); } else if(*s == 'm' ) { s++; d = parse_number(s,&m->n_smart_substitutions); } else if(*s == '-' ) { s++; *b = s; if(m->n_injections+m->n_smart_substitutions+m->n_substitutions+m->n_deletions+m->n_copys == 0) return 1; else d = -1; } else break; if(d < 0) { er->error = ERROR_INVALID_NULL_MODIFICATION; if(buff[n_chars-1] == '\n') n_chars--; buff[n_chars] = '\0'; safe_sprintf(er->txt,"ERROR: Invalid null modification\nline %d ( %s )\n",*line_n,buff); return 0; } else { s += d; found = 1; } } if(!found) { if(*s == '#' ) { s++; *s = '\0'; } else if(*s == '\n') { s++; *s = '\0'; } else if(*s == '\0') { s++; *s = '\0'; } else { *b = s; er->error = ERROR_INVALID_MODIFICATION; if(buff[n_chars-1] == '\n') n_chars--; buff[n_chars] = '\0'; safe_sprintf(er->txt,"ERROR: Invalid line in modification\nline %d ( %s )\n",*line_n,buff); return 0; } } else { if(*s == '#' ) { s++; *s = '\0'; } else if(*s == '\n') { s++; *s = '\0'; } else if(*s == '\0') { s++; *s = '\0'; } else if(*s == '"' ) //get chars { s++; char *c = s; while(*c != '"' && *c != '\n' && *c != '\0') { if(*c == '\\') c++; c++; } if(*c == '"') { m->n = (c-s); m->chars = (char *)safe_malloc(sizeof(char)*m->n+1); c = m->chars; while(*s != '"' && *s != '\n' && *s != '\0') { if(*s == '\\') { s++; m->n--; } *c = *s; c++; s++; } if(*s != '"') { er->error = ERROR_UNTERMINATED_STRING; if(buff[n_chars-1] == '\n') n_chars--; buff[n_chars] = '\0'; safe_sprintf(er->txt,"ERROR: Unterminated modification gamut\nline %d ( %s )\n",*line_n,buff); return 0; } s++; *c = '\0'; } else { er->error = ERROR_INVALID_STRING; if(buff[n_chars-1] == '\n') n_chars--; buff[n_chars] = '\0'; safe_sprintf(er->txt,"ERROR: Invalid characters after begining gamut\nline %d ( %s )\n",*line_n,buff); return 0; } } } if(m->n_substitutions+m->n_injections > 0 && !m->n) { er->error = ERROR_MODIFICATION_EMPTY_GAMUT; if(buff[n_chars-1] == '\n') n_chars--; buff[n_chars] = '\0'; safe_sprintf(er->txt,"ERROR: gamut required with substitution or injection\nline %d ( %s )\n",*line_n,buff); return 0; } } *b = s; return 1; } int parse_modifications(FILE *fp, int *line_n, char *buff, char **b, group *g, parse_error *er) { char *s; int valid_modification = 1; modification *m = (modification *)safe_malloc(sizeof(modification)); while(valid_modification) { zero_modification(m); valid_modification = parse_modification(fp,line_n,buff,b,m,er); if(valid_modification) { if(m->n_smart_substitutions) g->countable = 0; g->n_mods++; if(g->n_mods == 1) g->mods = (modification *)safe_malloc(sizeof(modification)); else g->mods = (modification *)safe_realloc(g->mods,sizeof(modification)*g->n_mods); g->mods[g->n_mods-1] = *m; } } free(m); if(er->error == ERROR_BADEOF) return 0; //close everything if(er->error != ERROR_INVALID_MODIFICATION) return 0; //let "invalid modification" attempt parse as "end modification" if(er->force) return 0; //if error force, don't allow passthrough ("unexpected parse" should only bubble up one level) s = *b; if(*s != ']') { //er->error; //retain error from stack int n_chars = 0; while(buff[n_chars] != '\0') n_chars++; if(buff[n_chars-1] == '\n') n_chars--; buff[n_chars] = '\0'; safe_sprintf(er->txt,"ERROR: Invalid characters within modifiers\nline %d ( %s )\n",*line_n,buff); er->force = 1; return 0; } s++; *b = s; return 1; } int parse_childs(FILE *fp, int unquoted, int *line_n, char *buff, char **b, group *g, int depth, parse_error *er) { char *s; int valid_kid = 1; group *prev_c = 0; group *c = (group *)safe_malloc(sizeof(group)); while(valid_kid) { zero_group(c); valid_kid = parse_child(fp, unquoted, line_n, buff, b, c, prev_c, depth+1, er); if(valid_kid) { if(c->type == GROUP_TYPE_MODIFICATION) { //ok } else if(c->type == GROUP_TYPE_NULL) { er->error = ERROR_NULL_CHILD; int n_chars = 0; while(buff[n_chars] != '\0') n_chars++; if(buff[n_chars-1] == '\n') n_chars--; buff[n_chars] = '\0'; safe_sprintf(er->txt,"Null child type found\nline %d ( %s )\n",*line_n,buff); } else { g->n++; if(g->n == 1) g->childs = (group *)safe_malloc(sizeof(group)); else g->childs = (group *)safe_realloc(g->childs,sizeof(group)*g->n); g->childs[g->n-1] = *c; prev_c = &g->childs[g->n-1]; } } } free(c); if(er->error == ERROR_EOF) { if(depth == 0) return 1; //close everything else { er->error = ERROR_BADEOF; //upgrade error switch(g->type) { case GROUP_TYPE_SEQUENCE: safe_sprintf(er->txt,"ERROR: EOF unclosed sequence\nline %d\n",*line_n); break; case GROUP_TYPE_OPTION: safe_sprintf(er->txt,"ERROR: EOF unclosed option\nline %d\n",*line_n); break; case GROUP_TYPE_PERMUTE: safe_sprintf(er->txt,"ERROR: EOF unclosed permute\nline %d\n",*line_n); break; default: break; //appease compiler } return 0; } } if(er->error != ERROR_INVALID_LINE) return 0; //let "invalid line" attempt parse as "end line" if(er->force) return 0; //if error force, don't allow passthrough ("unexpected parse" should only bubble up one level) s = *b; if(*s == '>' && g->type == GROUP_TYPE_SEQUENCE) s++; //great else if(*s == '}' && g->type == GROUP_TYPE_OPTION) s++; //great else if(*s == ')' && g->type == GROUP_TYPE_PERMUTE) s++; //great else { //er->error; //retain error from stack int n_chars = 0; while(buff[n_chars] != '\0') n_chars++; if(buff[n_chars-1] == '\n') n_chars--; buff[n_chars] = '\0'; if(g->type == GROUP_TYPE_SEQUENCE) safe_sprintf(er->txt,"ERROR: Invalid characters within sequence\nline %d ( %s )\n",*line_n,buff); if(g->type == GROUP_TYPE_OPTION) safe_sprintf(er->txt,"ERROR: Invalid characters within option\nline %d ( %s )\n",*line_n,buff); if(g->type == GROUP_TYPE_PERMUTE) safe_sprintf(er->txt,"ERROR: Invalid characters within permute\nline %d ( %s )\n",*line_n,buff); er->force = 1; return 0; } *b = s; return 1; } group *parse(FILE *fp, int unquoted) { char *buff; buff = (char *)safe_malloc(sizeof(char)*max_read_line_len); parse_error er; er.error = ERROR_NULL; er.force = 0; er.txt = (char *)safe_malloc(sizeof(char)*max_sprintf_len); int line_n = 0; group *g = (group *)safe_malloc(sizeof(group)); zero_group(g); g->type = GROUP_TYPE_SEQUENCE; char *b = buff; *b = '\0'; if(!parse_childs(fp, unquoted, &line_n, buff, &b, g, 0, &er)) { fprintf(stderr, "%s", er.txt); exit(1); } while(g->n == 1 && g->n_mods == 0 && (g->type == GROUP_TYPE_SEQUENCE || g->type == GROUP_TYPE_OPTION || g->type == GROUP_TYPE_PERMUTE)) { group *og = g->childs; *g = g->childs[0]; free(og); } free(buff); free(er.txt); return g; }
30.746331
150
0.503409
Phildo
feb98a5159c3b687e49309e21f4d66b38b96d70e
871
cc
C++
src/record_stack.cc
DouglasRMiles/QuProlog
798d86f87fb4372b8918ef582ef2f0fc0181af2d
[ "Apache-2.0" ]
5
2019-11-20T02:05:31.000Z
2022-01-06T18:59:16.000Z
src/record_stack.cc
logicmoo/QuProlog
798d86f87fb4372b8918ef582ef2f0fc0181af2d
[ "Apache-2.0" ]
null
null
null
src/record_stack.cc
logicmoo/QuProlog
798d86f87fb4372b8918ef582ef2f0fc0181af2d
[ "Apache-2.0" ]
2
2022-01-08T13:52:24.000Z
2022-03-07T17:41:37.000Z
// record_stack.cc - Fundamental stack arrangement. // // ##Copyright## // // Copyright 2000-2016 Peter Robinson (pjr@itee.uq.edu.au) // // 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.00 // // 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. // // ##Copyright## // // $Id: record_stack.cc,v 1.3 2001/06/07 05:18:12 qp Exp $ #include "area_offsets.h" #include "defs.h" #include "record_stack.h" #include "stack_qp.h"
31.107143
75
0.718714
DouglasRMiles
febad553870935dd75de39924f5beb8a6314fae0
1,445
cpp
C++
src/wmecore/Timer.cpp
retrowork/wme
54cf8905091736aef0a35fe6d3e05b818441f3c8
[ "MIT" ]
null
null
null
src/wmecore/Timer.cpp
retrowork/wme
54cf8905091736aef0a35fe6d3e05b818441f3c8
[ "MIT" ]
null
null
null
src/wmecore/Timer.cpp
retrowork/wme
54cf8905091736aef0a35fe6d3e05b818441f3c8
[ "MIT" ]
null
null
null
// This file is part of Wintermute Engine // For conditions of distribution and use, see copyright notice in license.txt #include "Wme.h" #include "Timer.h" namespace Wme { ////////////////////////////////////////////////////////////////////////// Timer::Timer() { m_OgreTimer = new Ogre::Timer(); Reset(); } ////////////////////////////////////////////////////////////////////////// Timer::~Timer() { SAFE_DELETE(m_OgreTimer); } ////////////////////////////////////////////////////////////////////////// void Timer::Reset() { m_CurrentTime = m_PrevTime = m_ElapsedTime = 0; m_IsFrozen = false; m_Multiplier = 1.0; } ////////////////////////////////////////////////////////////////////////// unsigned long Timer::Update() { if (m_IsFrozen) { m_ElapsedTime = 0; return m_CurrentTime; } unsigned long currentTime = m_OgreTimer->getMilliseconds(); unsigned long delta = currentTime - m_PrevTime; if (delta > 1000) delta = 1000; delta = (unsigned long)((float)delta * m_Multiplier); m_CurrentTime += delta; m_PrevTime = currentTime; m_ElapsedTime = delta; return m_CurrentTime; } ////////////////////////////////////////////////////////////////////////// void Timer::Freeze() { m_IsFrozen = true; } ////////////////////////////////////////////////////////////////////////// void Timer::Unfreeze() { m_IsFrozen = false; } } // namespace Wme
20.942029
79
0.445675
retrowork
febca984c8257a8aedff4f3ceb5e763bae9d7866
833
hpp
C++
include/avr/io/register/detail/all_state_representation_at_compiletime.hpp
ricardocosme/avrIO
b60238b48d1283324f8f73e530d582432c6c5f71
[ "MIT" ]
10
2021-02-03T09:51:58.000Z
2021-06-07T20:34:26.000Z
include/avr/io/register/detail/all_state_representation_at_compiletime.hpp
ricardocosme/avrIO
b60238b48d1283324f8f73e530d582432c6c5f71
[ "MIT" ]
null
null
null
include/avr/io/register/detail/all_state_representation_at_compiletime.hpp
ricardocosme/avrIO
b60238b48d1283324f8f73e530d582432c6c5f71
[ "MIT" ]
null
null
null
#pragma once #include "avr/io/detail/type_traits/enable_if.hpp" namespace avr { namespace io { namespace detail { template<typename Bit, typename... Rest> struct all_state_representation_at_compiletime { constexpr static bool value = all_state_representation_at_compiletime<Bit>::value && all_state_representation_at_compiletime<Rest...>::value; }; template<typename Bit> struct all_state_representation_at_compiletime<Bit> { constexpr static bool value = !Bit::representation_at_runtime; }; template<typename... Bits> using enable_if_state_representation_at_runtime = enable_if_t< !all_state_representation_at_compiletime<Bits...>::value>; template<typename... Bits> using enable_if_state_representation_at_compiletime = enable_if_t< all_state_representation_at_compiletime<Bits...>::value>; }}}
29.75
67
0.788715
ricardocosme
fec60fafebf268157110b35e1ec6557c78bb43b6
3,173
hpp
C++
libs/sprite/include/sge/sprite/geometry/detail/fill_texture_coordinates.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
2
2016-01-27T13:18:14.000Z
2018-05-11T01:11:32.000Z
libs/sprite/include/sge/sprite/geometry/detail/fill_texture_coordinates.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
null
null
null
libs/sprite/include/sge/sprite/geometry/detail/fill_texture_coordinates.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
3
2018-05-11T01:11:34.000Z
2021-04-24T19:47:45.000Z
// Copyright Carl Philipp Reh 2006 - 2019. // 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) #ifndef SGE_SPRITE_GEOMETRY_DETAIL_FILL_TEXTURE_COORDINATES_HPP_INCLUDED #define SGE_SPRITE_GEOMETRY_DETAIL_FILL_TEXTURE_COORDINATES_HPP_INCLUDED #include <sge/renderer/lock_rect_to_coords.hpp> #include <sge/renderer/texture/planar.hpp> #include <sge/sprite/object_impl.hpp> #include <sge/sprite/detail/config/has_normal_size.hpp> #include <sge/sprite/detail/config/has_repetition.hpp> #include <sge/sprite/detail/config/has_texture_coordinates.hpp> #include <sge/sprite/geometry/detail/convert_texture_rect.hpp> #include <sge/sprite/geometry/detail/fill_texture_coordinates_rect.hpp> #include <sge/texture/area_texc.hpp> #include <sge/texture/part.hpp> #include <fcppt/config/external_begin.hpp> #include <type_traits> #include <fcppt/config/external_end.hpp> namespace sge::sprite::geometry::detail { template <typename Level, typename Iterator, typename Choices> inline std::enable_if_t< std::conjunction_v< sge::sprite::detail::config::has_texture_coordinates<Choices>, sge::sprite::detail::config::has_normal_size<Choices>>, void> fill_texture_coordinates( Level const &, Iterator const &_iterator, sge::sprite::object<Choices> const &_sprite, sge::texture::part const &) { sge::sprite::geometry::detail::fill_texture_coordinates_rect<Level, Choices>( _iterator, _sprite.template texture_coordinates_level<Level::value>()); } template <typename Level, typename Iterator, typename Choices> inline std::enable_if_t< std::conjunction_v< sge::sprite::detail::config::has_repetition<Choices>, sge::sprite::detail::config::has_normal_size<Choices>>, void> fill_texture_coordinates( Level const &, Iterator const &_iterator, sge::sprite::object<Choices> const &_sprite, sge::texture::part const &_texture) { sge::sprite::geometry::detail::fill_texture_coordinates_rect<Level, Choices>( _iterator, sge::sprite::geometry::detail::convert_texture_rect<Choices>( sge::texture::area_texc<typename Choices::type_choices::float_type>( _texture, _sprite.repetition()))); } template <typename Level, typename Iterator, typename Choices> inline std::enable_if_t< std::conjunction_v< sge::sprite::detail::config::has_normal_size<Choices>, std::negation<std::disjunction< sge::sprite::detail::config::has_repetition<Choices>, sge::sprite::detail::config::has_texture_coordinates<Choices>>>>, void> fill_texture_coordinates( Level const &, Iterator const &_iterator, sge::sprite::object<Choices> const &, sge::texture::part const &_texture) { sge::sprite::geometry::detail::fill_texture_coordinates_rect<Level, Choices>( _iterator, sge::sprite::geometry::detail::convert_texture_rect<Choices>( sge::renderer::lock_rect_to_coords<typename Choices::type_choices::float_type>( _texture.area(), _texture.texture().size()))); } } #endif
37.329412
89
0.734006
cpreh
feca71ac33e521b0471ed2505ff0a2d750a05eb6
114
cpp
C++
src/math/Bezier.cpp
daysofwonder/common-cpp
e191be23299ec502c91cf4224eb8a2def9295cf5
[ "MIT" ]
null
null
null
src/math/Bezier.cpp
daysofwonder/common-cpp
e191be23299ec502c91cf4224eb8a2def9295cf5
[ "MIT" ]
1
2019-09-18T09:51:21.000Z
2019-09-18T09:51:21.000Z
src/math/Bezier.cpp
daysofwonder/common-cpp
e191be23299ec502c91cf4224eb8a2def9295cf5
[ "MIT" ]
1
2021-07-28T01:26:07.000Z
2021-07-28T01:26:07.000Z
// // Created by Dawid Drozd aka Gelldur on 03.12.17. // #include "Bezier.h" //////////////////////////////////
14.25
50
0.447368
daysofwonder
fecd9fedf2261dfb43a515ede96c8c77de2dd7c0
1,769
cpp
C++
ngraph/core/src/op/util/elementwise_args.cpp
uikilin100/openvino
afc5191b8c75b1de4adc8cb07c6269b52882ddfe
[ "Apache-2.0" ]
1
2021-03-16T17:40:26.000Z
2021-03-16T17:40:26.000Z
ngraph/core/src/op/util/elementwise_args.cpp
uikilin100/openvino
afc5191b8c75b1de4adc8cb07c6269b52882ddfe
[ "Apache-2.0" ]
42
2020-11-23T08:09:57.000Z
2022-02-21T13:03:34.000Z
ngraph/core/src/op/util/elementwise_args.cpp
tsocha/openvino
3081fac7581933568b496a3c4e744d1cee481619
[ "Apache-2.0" ]
4
2021-04-02T08:48:38.000Z
2021-07-01T06:59:02.000Z
// Copyright (C) 2018-2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include "ngraph/op/util/elementwise_args.hpp" #include "ngraph/op/util/binary_elementwise_arithmetic.hpp" using namespace ngraph; std::tuple<element::Type, PartialShape> ngraph::op::util::validate_and_infer_elementwise_args( Node* node, const op::AutoBroadcastSpec& autob) { NGRAPH_CHECK(node != nullptr, "nGraph node is empty! Cannot validate eltwise arguments."); element::Type element_type = node->get_input_element_type(0); PartialShape pshape = node->get_input_partial_shape(0); if (node->get_input_size() > 1) { for (size_t i = 1; i < node->get_input_size(); ++i) { NODE_VALIDATION_CHECK(node, element::Type::merge(element_type, element_type, node->get_input_element_type(i)), "Argument element types are inconsistent."); if (autob.m_type == op::AutoBroadcastType::NONE) { NODE_VALIDATION_CHECK(node, PartialShape::merge_into(pshape, node->get_input_partial_shape(i)), "Argument shapes are inconsistent."); } else if (autob.m_type == op::AutoBroadcastType::NUMPY || autob.m_type == op::AutoBroadcastType::PDPD) { NODE_VALIDATION_CHECK( node, PartialShape::broadcast_merge_into(pshape, node->get_input_partial_shape(i), autob), "Argument shapes are inconsistent."); } else { NODE_VALIDATION_CHECK(node, false, "Unsupported auto broadcast specification"); } } } return std::make_tuple(element_type, pshape); }
43.146341
117
0.613906
uikilin100
fece7dfe948feccd2380bf75b01c1e871ceee992
457
cpp
C++
codes/Leetcode/leetcode042.cpp
JeraKrs/ACM
edcd61ec6764b8cd804bf1538dfde53d0ff572b5
[ "Apache-2.0" ]
null
null
null
codes/Leetcode/leetcode042.cpp
JeraKrs/ACM
edcd61ec6764b8cd804bf1538dfde53d0ff572b5
[ "Apache-2.0" ]
null
null
null
codes/Leetcode/leetcode042.cpp
JeraKrs/ACM
edcd61ec6764b8cd804bf1538dfde53d0ff572b5
[ "Apache-2.0" ]
null
null
null
class Solution { public: int trap(vector<int>& height) { int n = height.size(), h; int* l = new int[n]; int* r = new int[n]; h = 0; for (int i = 0; i < n; i++) { h = max(h, height[i]); l[i] = h; } h = 0; for (int i = n-1; i >= 0; i--) { h = max(h, height[i]); r[i] = h; } int ans = 0; for (int i = 0; i < n; i++) ans += min(l[i], r[i]) - height[i]; delete l; delete r; return ans; } };
15.758621
39
0.422319
JeraKrs
feceae921eb58a8d86f0e86ac939e421b90804b1
3,818
cpp
C++
src/reader/lmpBaseReader.cpp
martintb/correlate
b0be89af4e57cc5fe96ec3a5c7a9bb84430d2433
[ "MIT" ]
3
2018-02-26T19:53:46.000Z
2021-05-05T10:06:52.000Z
src/reader/lmpBaseReader.cpp
martintb/correlate
b0be89af4e57cc5fe96ec3a5c7a9bb84430d2433
[ "MIT" ]
1
2018-07-03T14:38:15.000Z
2018-07-09T19:06:01.000Z
src/reader/lmpBaseReader.cpp
martintb/correlate
b0be89af4e57cc5fe96ec3a5c7a9bb84430d2433
[ "MIT" ]
1
2019-03-28T03:02:07.000Z
2019-03-28T03:02:07.000Z
#include <iostream> #include <fstream> #include <sstream> #include <regex> #include <map> #include "lmpBaseReader.hpp" #include "debug.hpp" using namespace std; void lmpBaseReader::goToSection(ifstream &f, string section_title) { f.seekg(0,ios::beg); //return to top of file regex sectionRE(section_title+".*",regex::extended); string line; while (getline(f,line)) { if (regex_search(line,sectionRE)) { getline(f,line);// blank line break; } } } map<string,float> lmpBaseReader::readHeader(ifstream &f) { f.seekg(0,ios::beg); //return to top of file if (not f.good()) { cout << "file.bad(): " << boolalpha << f.bad() << endl; cout << "file.fail(): " << boolalpha << f.fail() << endl; cout << "file.eof(): " << boolalpha << f.eof() << endl; LOC(); exit(EXIT_FAILURE); } regex natoms("(.*) atoms",regex::extended); regex nbonds("(.*) bonds",regex::extended); regex nangles("(.*) angles",regex::extended); regex ndih("(.*) dihedrals",regex::extended); regex nimp("(.*) impropers",regex::extended); regex ntypes("(.*) atom types",regex::extended); regex nbtypes("(.*) bond types",regex::extended); regex natypes("(.*) angle types",regex::extended); regex ndtypes("(.*) dihedral types",regex::extended); regex nitypes("(.*) improper types",regex::extended); regex boxx("(.*) (.*) xlo xhi",regex::extended); regex boxy("(.*) (.*) ylo yhi",regex::extended); regex boxz("(.*) (.*) zlo zhi",regex::extended); map<string,float> headerData; smatch m; string line; float temp1,temp2; int lineNo=0; int maxHeaderSize = 50; while (getline(f,line)) { if (regex_search(line,m,boxz)) { istringstream (m[1].str()) >> temp1; istringstream (m[2].str()) >> temp2; headerData["zlo"] = temp1; headerData["zhi"] = temp2; headerData["lz"] = temp2 - temp1; } else if (regex_search(line,m,boxy)) { istringstream (m[1].str()) >> temp1; istringstream (m[2].str()) >> temp2; headerData["ylo"] = temp1; headerData["yhi"] = temp2; headerData["ly"] = temp2 - temp1; } else if (regex_search(line,m,boxx)) { istringstream (m[1].str()) >> temp1; istringstream (m[2].str()) >> temp2; headerData["xlo"] = temp1; headerData["xhi"] = temp2; headerData["lx"] = temp2 - temp1; } else if (regex_search(line,m,nitypes)) { istringstream (m[1].str()) >> temp1; headerData["nimpropertypes"] = temp1; } else if (regex_search(line,m,ndtypes)) { istringstream (m[1].str()) >> temp1; headerData["ndihedraltypes"] = temp1; } else if (regex_search(line,m,natypes)) { istringstream (m[1].str()) >> temp1; headerData["nangletypes"] = temp1; } else if (regex_search(line,m,nbtypes)) { istringstream (m[1].str()) >> temp1; headerData["nbondtypes"] = temp1; } else if (regex_search(line,m,ntypes)) { istringstream (m[1].str()) >> temp1; headerData["natomtypes"] = temp1; } else if (regex_search(line,m,nimp)) { istringstream (m[1].str()) >> temp1; headerData["nimpropers"] = temp1; } else if (regex_search(line,m,ndih)) { istringstream (m[1].str()) >> temp1; headerData["ndihedrals"] = temp1; } else if (regex_search(line,m,nangles)) { istringstream (m[1].str()) >> temp1; headerData["nangles"] = temp1; } else if (regex_search(line,m,nbonds)) { istringstream (m[1].str()) >> temp1; headerData["nbonds"] = temp1; } else if (regex_search(line,m,natoms)) { istringstream (m[1].str()) >> temp1; headerData["natoms"] = temp1; } if (lineNo>maxHeaderSize) break; lineNo++; } // nead to clear eofbit and failbit in case the end of the file was reached f.clear(); return headerData; }
32.913793
77
0.602672
martintb
fed1da7b625370f1b36f72716fcc0a6b1e1b0d18
2,914
cpp
C++
3rdparty/aws-sdk-cpp-master/aws-cpp-sdk-cognito-sync/source/model/IdentityUsage.cpp
prateek-s/mesos
4b81147797e4d9a45e0b2f5e5634d4a214dbc4e8
[ "Apache-2.0" ]
2
2019-02-08T21:29:57.000Z
2021-07-27T06:59:19.000Z
3rdparty/aws-sdk-cpp-master/aws-cpp-sdk-cognito-sync/source/model/IdentityUsage.cpp
prateek-s/mesos
4b81147797e4d9a45e0b2f5e5634d4a214dbc4e8
[ "Apache-2.0" ]
null
null
null
3rdparty/aws-sdk-cpp-master/aws-cpp-sdk-cognito-sync/source/model/IdentityUsage.cpp
prateek-s/mesos
4b81147797e4d9a45e0b2f5e5634d4a214dbc4e8
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 <aws/cognito-sync/model/IdentityUsage.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace CognitoSync { namespace Model { IdentityUsage::IdentityUsage() : m_identityIdHasBeenSet(false), m_identityPoolIdHasBeenSet(false), m_lastModifiedDateHasBeenSet(false), m_datasetCount(0), m_datasetCountHasBeenSet(false), m_dataStorage(0), m_dataStorageHasBeenSet(false) { } IdentityUsage::IdentityUsage(const JsonValue& jsonValue) : m_identityIdHasBeenSet(false), m_identityPoolIdHasBeenSet(false), m_lastModifiedDateHasBeenSet(false), m_datasetCount(0), m_datasetCountHasBeenSet(false), m_dataStorage(0), m_dataStorageHasBeenSet(false) { *this = jsonValue; } IdentityUsage& IdentityUsage::operator =(const JsonValue& jsonValue) { if(jsonValue.ValueExists("IdentityId")) { m_identityId = jsonValue.GetString("IdentityId"); m_identityIdHasBeenSet = true; } if(jsonValue.ValueExists("IdentityPoolId")) { m_identityPoolId = jsonValue.GetString("IdentityPoolId"); m_identityPoolIdHasBeenSet = true; } if(jsonValue.ValueExists("LastModifiedDate")) { m_lastModifiedDate = jsonValue.GetDouble("LastModifiedDate"); m_lastModifiedDateHasBeenSet = true; } if(jsonValue.ValueExists("DatasetCount")) { m_datasetCount = jsonValue.GetInteger("DatasetCount"); m_datasetCountHasBeenSet = true; } if(jsonValue.ValueExists("DataStorage")) { m_dataStorage = jsonValue.GetInt64("DataStorage"); m_dataStorageHasBeenSet = true; } return *this; } JsonValue IdentityUsage::Jsonize() const { JsonValue payload; if(m_identityIdHasBeenSet) { payload.WithString("IdentityId", m_identityId); } if(m_identityPoolIdHasBeenSet) { payload.WithString("IdentityPoolId", m_identityPoolId); } if(m_lastModifiedDateHasBeenSet) { payload.WithDouble("LastModifiedDate", m_lastModifiedDate.SecondsWithMSPrecision()); } if(m_datasetCountHasBeenSet) { payload.WithInteger("DatasetCount", m_datasetCount); } if(m_dataStorageHasBeenSet) { payload.WithInt64("DataStorage", m_dataStorage); } return payload; } } // namespace Model } // namespace CognitoSync } // namespace Aws
22.244275
87
0.738161
prateek-s
fed2e18c581f5ef3fbc79fdf68267f20e7aeac5a
266
cpp
C++
CPP/HelloCpp2/chapter_20/Inheritance.cpp
hrntsm/study-language
922578a5321d70c26b935e6052f400125e15649c
[ "MIT" ]
1
2022-02-06T10:50:42.000Z
2022-02-06T10:50:42.000Z
CPP/HelloCpp2/chapter_20/Inheritance.cpp
hrntsm/study-language
922578a5321d70c26b935e6052f400125e15649c
[ "MIT" ]
null
null
null
CPP/HelloCpp2/chapter_20/Inheritance.cpp
hrntsm/study-language
922578a5321d70c26b935e6052f400125e15649c
[ "MIT" ]
null
null
null
#include<iostream> using namespace std; class Kitty{ public: void nyan(){cout << "Kitty on your lap\n";} }; class Di_Gi_Gharat : public Kitty{ public: void nyo(){cout << "Di Gi Gharat\n";} } obj; int main(){ obj.nyo(); obj.nyan(); return 0; }
14
47
0.605263
hrntsm
fed74b345d578e1fc34f463c52ac3009e8ba218a
795
cpp
C++
Source/Engine/Filesystem/Resource.cpp
kukiric/SomeGame
8c058d82a93bc3f276bbb3ec57a3978ae57de82c
[ "MIT" ]
null
null
null
Source/Engine/Filesystem/Resource.cpp
kukiric/SomeGame
8c058d82a93bc3f276bbb3ec57a3978ae57de82c
[ "MIT" ]
null
null
null
Source/Engine/Filesystem/Resource.cpp
kukiric/SomeGame
8c058d82a93bc3f276bbb3ec57a3978ae57de82c
[ "MIT" ]
null
null
null
#include "Resource.h" #define PREFETCH_SIZE 128*1024 using namespace Filesystem; HashMap<String, Resource*> Resource::pool; const Resource& Resource::request(StringRef path) { Resource* resource; auto iter = pool.find(path); if(iter != pool.end()) { resource = iter->second; } else { resource = new Resource(path); pool.emplace(path, resource); } return *resource; } void Resource::drop(StringRef path) { auto it = pool.find(path); if (it != pool.end()) { delete it->second; pool.erase(it); } } Resource::Resource(const File& file) : file(file) { } Resource::~Resource() { } void Resource::compile() { } const File& Resource::getFile() const { return file; }
17.282609
50
0.584906
kukiric
fedcd3881f438a16f148f7d91dd7b60b69efbffa
469
cc
C++
app_tuner/linux/flutter/generated_plugin_registrant.cc
MacherelR/instrument_tuner
fbdc3e2ad1dc825b1f74d7ee9c903212cd14f4a6
[ "MIT" ]
null
null
null
app_tuner/linux/flutter/generated_plugin_registrant.cc
MacherelR/instrument_tuner
fbdc3e2ad1dc825b1f74d7ee9c903212cd14f4a6
[ "MIT" ]
null
null
null
app_tuner/linux/flutter/generated_plugin_registrant.cc
MacherelR/instrument_tuner
fbdc3e2ad1dc825b1f74d7ee9c903212cd14f4a6
[ "MIT" ]
null
null
null
// // Generated file. Do not edit. // // clang-format off #include "generated_plugin_registrant.h" #include <flutter_audio_capture/flutter_audio_capture_plugin.h> void fl_register_plugins(FlPluginRegistry* registry) { g_autoptr(FlPluginRegistrar) flutter_audio_capture_registrar = fl_plugin_registry_get_registrar_for_plugin(registry, "FlutterAudioCapturePlugin"); flutter_audio_capture_plugin_register_with_registrar(flutter_audio_capture_registrar); }
29.3125
89
0.833689
MacherelR
fedebf0ab22b554961dd5cb652cf512052355879
711
cpp
C++
userspace/libs/libwidget/elements/IconElement.cpp
GeGuNa/skift_oss2
8e674f5bfa24c009df5c683fefa02daf14d9a40f
[ "MIT" ]
1,724
2019-03-02T18:31:16.000Z
2022-03-31T18:35:42.000Z
userspace/libs/libwidget/elements/IconElement.cpp
GeGuNa/skift_oss2
8e674f5bfa24c009df5c683fefa02daf14d9a40f
[ "MIT" ]
280
2019-03-06T09:36:49.000Z
2022-03-30T18:56:14.000Z
userspace/libs/libwidget/elements/IconElement.cpp
GeGuNa/skift_oss2
8e674f5bfa24c009df5c683fefa02daf14d9a40f
[ "MIT" ]
263
2019-03-14T15:04:12.000Z
2022-03-26T19:28:36.000Z
#include <libgraphic/Painter.h> #include <libwidget/elements/IconElement.h> namespace Widget { IconElement::IconElement(Ref<Graphic::Icon> icon, Graphic::IconSize size) : _icon{icon}, _icon_size{size} { } void IconElement::paint(Graphic::Painter &painter, const Math::Recti &) { if (!_icon) { return; } Math::Recti destination = _icon->bound(_icon_size).centered_within(bound()); painter.blit( *_icon, _icon_size, destination, color(THEME_FOREGROUND)); } Math::Vec2i IconElement::size() { if (_icon) { return _icon->bound(_icon_size).size(); } else { return bound().size(); } } } // namespace Widget
17.341463
80
0.61744
GeGuNa
fee033277ccbc9e01ae726b0ec3494cbe2814547
32,954
hpp
C++
heart/test/TestCardiacSimulation.hpp
SoftMatterMechanics/ApicalStressFibers
17d343c09a246a50f9e3a3cbfc399ca6bef353ce
[ "Apache-2.0", "BSD-3-Clause" ]
1
2020-09-10T16:12:13.000Z
2020-09-10T16:12:13.000Z
heart/test/TestCardiacSimulation.hpp
SoftMatterMechanics/ApicalStressFibers
17d343c09a246a50f9e3a3cbfc399ca6bef353ce
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
heart/test/TestCardiacSimulation.hpp
SoftMatterMechanics/ApicalStressFibers
17d343c09a246a50f9e3a3cbfc399ca6bef353ce
[ "Apache-2.0", "BSD-3-Clause" ]
1
2020-09-10T16:12:21.000Z
2020-09-10T16:12:21.000Z
/* Copyright (c) 2005-2020, University of Oxford. All rights reserved. University of Oxford means the Chancellor, Masters and Scholars of the University of Oxford, having an administrative office at Wellington Square, Oxford OX1 2JD, UK. This file is part of Chaste. 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 University of Oxford nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TESTCARDIACSIMULATION_HPP_ #define TESTCARDIACSIMULATION_HPP_ #include <cxxtest/TestSuite.h> #include <string> #include <vector> #include <sstream> #include "AbstractCardiacProblem.hpp" #include "MonodomainProblem.hpp" #include "CardiacSimulation.hpp" #include "OutputFileHandler.hpp" #include "CompareHdf5ResultsFiles.hpp" #include "FileFinder.hpp" #include "PetscTools.hpp" #include "HeartEventHandler.hpp" #include "AbstractCardiacCellInterface.hpp" #include "DistributedVectorFactory.hpp" #include "Warnings.hpp" #include "CellMLToSharedLibraryConverter.hpp" #include "PetscSetupAndFinalize.hpp" class TestCardiacSimulation : public CxxTest::TestSuite { void setUp() { HeartEventHandler::Reset(); } // // void CreateOptionsFile(const OutputFileHandler& rHandler, // const std::string& rModelName, // const std::vector<std::string>& rArgs, // const std::string& rExtraXml="") // { // if (PetscTools::AmMaster()) // { // out_stream p_optfile = rHandler.OpenOutputFile(rModelName + "-conf.xml"); // (*p_optfile) << "<?xml version='1.0'?>" << std::endl // << "<pycml_config>" << std::endl // << "<command_line_args>" << std::endl; // for (unsigned i=0; i<rArgs.size(); i++) // { // (*p_optfile) << "<arg>" << rArgs[i] << "</arg>" << std::endl; // } // (*p_optfile) << "</command_line_args>" << std::endl // << rExtraXml // << "</pycml_config>" << std::endl; // p_optfile->close(); // } // PetscTools::Barrier("CreateOptionsFile"); // } public: void TestMono1dSmall() { if (PetscTools::GetNumProcs() > 3u) { TS_TRACE("This test is not suitable for more than 3 processes."); return; } // Fox2002BackwardEuler cell model CardiacSimulation simulation("heart/test/data/xml/monodomain1d_small.xml", true); TS_ASSERT( CompareFilesViaHdf5DataReader("heart/test/data/cardiac_simulations", "mono_1d_small", false, "SaveMono1D", "SimulationResults", true, 1e-6)); /* If the above fails, and you are happy the new results are correct, uncomment the following line, * run the test, and then do cp /tmp/$USER/testoutput/SaveMono1D/SimulationResults.h5 heart/test/data/cardiac_simulations/mono_1d_small.h5 */ //assert(0); CardiacSimulation simulation2("heart/test/data/xml/monodomain1d_resume.xml", true); } void TestMono2dSmall() { if (PetscTools::GetNumProcs() > 3u) { TS_TRACE("This test is not suitable for more than 3 processes."); return; } //Clear any warnings from previous tests Warnings::QuietDestroy(); { CardiacSimulation simulation("heart/test/data/xml/monodomain2d_small.xml", false, true); boost::shared_ptr<AbstractUntemplatedCardiacProblem> p_problem = simulation.GetSavedProblem(); TS_ASSERT(p_problem); MonodomainProblem<2,2>* p_mono_problem = dynamic_cast<MonodomainProblem<2,2>*>(p_problem.get()); TS_ASSERT(p_mono_problem != NULL); DistributedVectorFactory* p_vector_factory = p_mono_problem->rGetMesh().GetDistributedVectorFactory(); for (unsigned node_global_index = p_vector_factory->GetLow(); node_global_index < p_vector_factory->GetHigh(); node_global_index++) { AbstractCardiacCellInterface* p_cell = p_mono_problem->GetTissue()->GetCardiacCell(node_global_index); TS_ASSERT_DELTA(p_cell->GetParameter("membrane_fast_sodium_current_conductance"), 23 * 0.99937539038101175, 1e-6); TS_ASSERT_DELTA(p_cell->GetParameter("membrane_rapid_delayed_rectifier_potassium_current_conductance"), 0.282/3.0, 1e-6); } if (p_vector_factory->GetLocalOwnership() > 0) { TS_ASSERT_EQUALS(Warnings::Instance()->GetNumWarnings(), p_vector_factory->GetLocalOwnership()); std::stringstream msg; msg << "Cannot apply drug to cell at node " << p_vector_factory->GetLow() << " as it has no parameter named 'not_a_current_conductance'."; TS_ASSERT_EQUALS(Warnings::Instance()->GetNextWarningMessage(), msg.str()); } else { //There is now a warning on the top processes about the fact that no cells were assigned TS_ASSERT_EQUALS(Warnings::Instance()->GetNumWarnings(), 1u); std::stringstream msg; msg << "No cells were assigned to process "<< PetscTools::GetMyRank(); msg << " in AbstractCardiacTissue constructor. Advice: Make total number of processors no greater than number of nodes in the mesh"; TS_ASSERT_EQUALS(Warnings::Instance()->GetNextWarningMessage(), msg.str()); } } //Check that the post-processed file is there and remove it FileFinder pseudoecg("SaveMono2D/output/PseudoEcgFromElectrodeAt_0.05_0.05_0.dat", RelativeTo::ChasteTestOutput); if (PetscTools::AmMaster()) { TS_ASSERT(pseudoecg.Exists()); // Only master tests. This prevents master from removing file before other processes have seen it pseudoecg.Remove(); TS_ASSERT(pseudoecg.Exists() == false); } //Check that archive which has just been produced can be read CardiacSimulation simulation2("heart/test/data/xml/monodomain2d_resume.xml"); //Check that the post-processed file is back after the simulation has been restarted TS_ASSERT(pseudoecg.Exists()); // (Should check that it's bigger than the one we deleted) Warnings::QuietDestroy(); } /* Do the same as before but ask for post-processing after the simulation has been run and checkpointed. */ void TestMono2dSmallAddPostprocessingOnResume() { if (PetscTools::GetNumProcs() > 3u) { TS_TRACE("This test is not suitable for more than 3 processes."); return; } //Clear any warnings from previous tests Warnings::QuietDestroy(); { CardiacSimulation simulation("heart/test/data/xml/monodomain2d_small2.xml", false, true); } //Check that the post-processed file is not produced in the original simulation FileFinder pseudoecg("SaveMono2D2/output/PseudoEcgFromElectrodeAt_0.05_0.05_0.dat", RelativeTo::ChasteTestOutput); TS_ASSERT(pseudoecg.Exists() == false); //Check that archive which has just been produced can be read CardiacSimulation simulation2("heart/test/data/xml/monodomain2d_resume2.xml"); //Check that the post-processed file is present after the simulation has been restarted TS_ASSERT(pseudoecg.Exists()); // (Should check that it's bigger than the one we deleted) Warnings::QuietDestroy(); } void TestMono3dSmall() { if (PetscTools::GetNumProcs() > 3u) { TS_TRACE("This test is not suitable for more than 3 processes."); return; } CardiacSimulation simulation("heart/test/data/xml/monodomain3d_small.xml"); //Check that archive which has just been produced can be read CardiacSimulation simulation2("heart/test/data/xml/monodomain3d_resume.xml"); } void TestMono1dSodiumBlockBySettingNamedParameter() { CardiacSimulation simulation("heart/test/data/xml/monodomain1d_sodium_block.xml"); TS_ASSERT( CompareFilesViaHdf5DataReader("heart/test/data/cardiac_simulations", "mono_1d_sodium_block", false, "Mono1dSodiumBlock", "SimulationResults", true, 2.5e-3)); // Test exception TS_ASSERT_THROWS_THIS(CardiacSimulation bad_param("heart/test/data/xml/bad_cell_parameter.xml"), "No parameter named 'missing-parameter'."); } void TestMonoStimUsingEllipsoids() { if (PetscTools::GetNumProcs() > 3u) { TS_TRACE("This test is not suitable for more than 3 processes."); return; } // Fox2002BackwardEuler cell model CardiacSimulation simulation("heart/test/data/xml/monodomain1d_stim_using_ellipsoid.xml", true); TS_ASSERT( CompareFilesViaHdf5DataReader("heart/test/data/cardiac_simulations", "monodomain1d_stim_using_ellipsoid", false, "Mono1DStimUsingEllipsoid", "SimulationResults", true, 1e-6)); } void TestBi1dSmall() { if (PetscTools::GetNumProcs() > 3u) { TS_TRACE("This test is not suitable for more than 3 processes."); return; } { CardiacSimulation simulation("heart/test/data/xml/bidomain1d_small.xml"); } { CardiacSimulation simulation2("heart/test/data/xml/bidomain1d_resume.xml"); } { // The default resume file specifies a simulation duration of zero. // In reality the user should edit the file to specify something sensible... FileFinder resume_xml("SaveBi1D_checkpoints/0.1ms/ResumeParameters.xml", RelativeTo::ChasteTestOutput); TS_ASSERT_THROWS_THIS(CardiacSimulation simulation(resume_xml.GetAbsolutePath()), "The simulation duration must be positive, not -0.1"); } } void TestBi2dSmall() { if (PetscTools::GetNumProcs() > 3u) { TS_TRACE("This test is not suitable for more than 3 processes."); return; } CardiacSimulation simulation("heart/test/data/xml/bidomain2d_small.xml"); //Check that archive which has just been produced can be read CardiacSimulation simulation2("heart/test/data/xml/bidomain2d_resume.xml"); } void TestBi3dSmall() { if (PetscTools::GetNumProcs() > 3u) { TS_TRACE("This test is not suitable for more than 3 processes."); return; } CardiacSimulation simulation("heart/test/data/xml/bidomain3d_small.xml"); //Check that archive which has just been produced can be read CardiacSimulation simulation2("heart/test/data/xml/bidomain3d_resume.xml"); } void TestBiWithBath1dSmall() { { CardiacSimulation simulation("heart/test/data/xml/bidomain_with_bath1d_small.xml"); } { CardiacSimulation simulation2("heart/test/data/xml/bidomain_with_bath1d_resume.xml"); } { // The default resume file specifies a simulation duration of zero. // In reality the user should edit the file to specify something sensible... FileFinder resume_xml("SaveBiWithBath1D_checkpoints/0.1ms/ResumeParameters.xml", RelativeTo::ChasteTestOutput); TS_ASSERT_THROWS_THIS(CardiacSimulation simulation(resume_xml.GetAbsolutePath()), "The simulation duration must be positive, not -0.1"); } } void TestBiWithBath2dSmall() { CardiacSimulation simulation("heart/test/data/xml/bidomain_with_bath2d_small.xml"); CardiacSimulation simulation2("heart/test/data/xml/bidomain_with_bath2d_resume.xml"); } void TestBiWithBath3dSmall() { CardiacSimulation simulation("heart/test/data/xml/bidomain_with_bath3d_small.xml"); CardiacSimulation simulation2("heart/test/data/xml/bidomain_with_bath3d_resume.xml"); } void TestBiWith2dHeterogeneousConductivities() { CardiacSimulation simulation("heart/test/data/xml/bidomain2d_heterogeneous.xml", true); } void TestCardiacSimulationBasicBidomainShort() { // Fox2002BackwardEuler cell model // run a bidomain_with_bath simulation CardiacSimulation simulation("heart/test/data/xml/base_bidomain_short.xml"); // compare the files, using the CompareFilesViaHdf5DataReader() method TS_ASSERT( CompareFilesViaHdf5DataReader("heart/test/data/cardiac_simulations", "base_bidomain_short_results", false, "BaseBidomainShort", "SimulationResults", true, 1e-6)); } void TestCardiacSimulationBasicMonodomainShort() { // Fox2002BackwardEuler cell model // run a bidomain simulation CardiacSimulation simulation("heart/test/data/xml/base_monodomain_short.xml"); // compare the files, using the CompareFilesViaHdf5DataReader() method TS_ASSERT( CompareFilesViaHdf5DataReader("heart/test/data/cardiac_simulations", "base_monodomain_short_results", false, "BaseMonodomainShort", "SimulationResults", true, 1e-6)); } void TestCardiacSimulationPostprocessMonodomain() { // Fox2002BackwardEuler cell model // run a bidomain simulation CardiacSimulation simulation("heart/test/data/xml/postprocess_monodomain_short.xml"); std::string foldername = "PostprocessMonodomainShort"; // compare the files, using the CompareFilesViaHdf5DataReader() method TS_ASSERT( CompareFilesViaHdf5DataReader("heart/test/data/cardiac_simulations", "postprocess_monodomain_short_results", false, foldername, "SimulationResults", true, 1e-6)); { // look for the existence of post-processing files TS_ASSERT(FileFinder(foldername + "/output/Apd_90_minus_30_Map.dat", RelativeTo::ChasteTestOutput).Exists()); TS_ASSERT(FileFinder(foldername + "/output/ConductionVelocityFromNode10.dat", RelativeTo::ChasteTestOutput).Exists()); TS_ASSERT(FileFinder(foldername + "/output/ConductionVelocityFromNode20.dat", RelativeTo::ChasteTestOutput).Exists()); TS_ASSERT(FileFinder(foldername + "/output/MaxUpstrokeVelocityMap_minus_30.dat", RelativeTo::ChasteTestOutput).Exists()); TS_ASSERT(FileFinder(foldername + "/output/UpstrokeTimeMap_minus_30.dat", RelativeTo::ChasteTestOutput).Exists()); TS_ASSERT(FileFinder(foldername + "/output/PseudoEcgFromElectrodeAt_0.05_0.05_0.dat", RelativeTo::ChasteTestOutput).Exists()); } } void TestCardiacSimulationArchiveBidomain() { // Fox2002BackwardEuler cell model // run a bidomain simulation CardiacSimulation simulation("heart/test/data/xml/save_bidomain_short.xml"); std::string foldername = "SaveBidomainShort"; // compare the files, using the CompareFilesViaHdf5DataReader() method TS_ASSERT(CompareFilesViaHdf5DataReader("heart/test/data/cardiac_simulations", "save_bidomain_short_results", false, foldername, "SimulationResults", true, 1e-5)); FileFinder file(foldername + "_checkpoints/0.2ms/" + foldername + "_0.2ms/archive.arch.0", RelativeTo::ChasteTestOutput); TS_ASSERT(file.Exists()); /* If you want to update the .h5 results for this test for any reason, you need to stop the following test adding to them. * So uncomment the assert(), run the test, and then do: cp /tmp/chaste/testoutput/SaveBidomainShort/SimulationResults.h5 heart/test/data/cardiac_simulations/save_bidomain_short_results.h5 */ //assert(0); } // requires TestCardiacSimulationArchiveBidomain() to have been run void TestCardiacSimulationResumeBidomain() { // run a bidomain simulation HeartConfig::Instance()->SetSpaceDimension(1); FileFinder resume_xml("heart/test/data/xml/resume_bidomain_short.xml", RelativeTo::ChasteSourceRoot); OutputFileHandler checkpoint_dir("SaveBidomainShort_checkpoints/0.2ms", false); FileFinder copied_xml = checkpoint_dir.CopyFileTo(resume_xml); CardiacSimulation simulation(copied_xml.GetAbsolutePath()); std::string foldername = "SaveBidomainShort"; // compare the files, using the CompareFilesViaHdf5DataReader() method TS_ASSERT( CompareFilesViaHdf5DataReader("heart/test/data/cardiac_simulations", "resume_bidomain_short_results", false, foldername, "SimulationResults", true, 1e-5)); //assert(0); } void TestCardiacSimulationArchiveMonodomain() { // Fox2002BackwardEuler cell model // run a bidomain simulation CardiacSimulation simulation("heart/test/data/xml/save_monodomain_short.xml"); std::string foldername = "SaveMonodomainShort"; // compare the files, using the CompareFilesViaHdf5DataReader() method TS_ASSERT( CompareFilesViaHdf5DataReader("heart/test/data/cardiac_simulations", "save_monodomain_short_results", false, foldername, "SimulationResults", true, 1e-6)); FileFinder file(foldername + "_checkpoints/0.2ms/" + foldername + "_0.2ms/archive.arch.0", RelativeTo::ChasteTestOutput); TS_ASSERT(file.Exists()); /* If you want to update the .h5 results for this test for any reason, you need to stop the following test adding to them. * So uncomment the assert(), run the test, and then do: cp /tmp/chaste/testoutput/SaveMonodomainShort/SimulationResults.h5 heart/test/data/cardiac_simulations/save_monodomain_short_results.h5 */ //assert(0); } // requires TestCardiacSimulationArchiveMonodomain() to have been run void TestCardiacSimulationResumeMonodomain() { // run a monodomain simulation HeartConfig::Instance()->SetSpaceDimension(1); CardiacSimulation simulation("heart/test/data/xml/resume_monodomain_short.xml"); std::string foldername = "SaveMonodomainShort"; // compare the files, using the CompareFilesViaHdf5DataReader() method TS_ASSERT( CompareFilesViaHdf5DataReader("heart/test/data/cardiac_simulations", "resume_monodomain_short_results", false, foldername, "SimulationResults", true, 1e-6)); } void TestCardiacSimulationArchiveDynamic() { #ifdef CHASTE_CAN_CHECKPOINT_DLLS // run a monodomain simulation { CardiacSimulation simulation("heart/test/data/xml/save_monodomain_dynamic.xml"); } std::string foldername = "SaveMonodomainDynamic"; // compare the files, using the CompareFilesViaHdf5DataReader() method TS_ASSERT( CompareFilesViaHdf5DataReader("heart/test/data/cardiac_simulations", "save_monodomain_dynamic", false, foldername, "SimulationResults", true)); FileFinder file(foldername + "_checkpoints/0.2ms/" + foldername + "_0.2ms/archive.arch.0", RelativeTo::ChasteTestOutput); TS_ASSERT(file.Exists()); /* If you want to update the .h5 results for this test for any reason, you need to stop the following lines adding to them. * So uncomment the assert(), run the test, and then do: cp /tmp/chaste/testoutput/SaveMonodomainDynamic/SimulationResults.h5 heart/test/data/cardiac_simulations/save_monodomain_dynamic.h5 */ //assert(0); //resume the simulation { CardiacSimulation simulation("heart/test/data/xml/resume_monodomain_dynamic.xml"); } // compare the files, using the CompareFilesViaHdf5DataReader() method TS_ASSERT( CompareFilesViaHdf5DataReader("heart/test/data/cardiac_simulations", "resume_monodomain_dynamic", false, foldername, "SimulationResults", true)); #endif // CHASTE_CAN_CHECKPOINT_DLLS } /** * Note: from Chaste release 3.1 onward we no longer support Boost 1.33. * The earliest version of Boost supported is 1.34 * Run TestCardiacSimulationArchiveBidomain on 4 processors to create the archive for this test, * and copy it to the repository using: * scons build=GccOpt_hostconfig,boost=1-34_4 test_suite=heart/test/TestCardiacSimulation.hpp cp -r /tmp/$USER/testoutput/SaveBidomainShort_checkpoints/0.2ms heart/test/data/checkpoint_migration_via_xml/ rm -f heart/test/data/checkpoint_migration_via_xml/0.2ms/SaveBidomainShort/progress_status.txt rm -f heart/test/data/checkpoint_migration_via_xml/0.2ms/SaveBidomainShort_0.2ms/mesh.ncl rm -f heart/test/data/checkpoint_migration_via_xml/0.2ms/SaveBidomainShort_0.2ms/ChasteParameters_?_?xsd rm -rf heart/test/data/checkpoint_migration_via_xml/0.2ms/SaveBidomainShort/output */ void TestCardiacSimulationResumeMigration() { // We can only load simulations from CHASTE_TEST_OUTPUT, so copy the archives there std::string source_directory = "heart/test/data/checkpoint_migration_via_xml/0.2ms/"; std::string folder_1 = "SaveBidomainShort"; std::string folder_2 = "SaveBidomainShort_0.2ms"; FileFinder to_directory1(OutputFileHandler::GetChasteTestOutputDirectory() + folder_1, RelativeTo::Absolute); FileFinder to_directory2(OutputFileHandler::GetChasteTestOutputDirectory() + folder_2, RelativeTo::Absolute); FileFinder from_directory1(source_directory + folder_1, RelativeTo::ChasteSourceRoot); FileFinder from_directory2(source_directory + folder_2, RelativeTo::ChasteSourceRoot); TRY_IF_MASTER( to_directory1.Remove(); to_directory2.Remove(); TS_ASSERT_EQUALS(to_directory1.Exists(), false); TS_ASSERT_EQUALS(to_directory2.Exists(), false); from_directory1.CopyTo(to_directory1); from_directory2.CopyTo(to_directory2); ); // Resume CardiacSimulation simulation("heart/test/data/xml/resume_migration.xml"); // Compare results TS_ASSERT( CompareFilesViaHdf5DataReader("heart/test/data/cardiac_simulations", "resume_bidomain_short_results", false, "SaveBidomainShort", "SimulationResults", true, 1e-5)); } void runSimulation(const std::string& rParametersFileName) { CardiacSimulation simulation(rParametersFileName); } void checkParameter(AbstractCardiacCellInterface* pCell, unsigned globalIndex) { // Check one of the parameters has been set in the central region TS_ASSERT_EQUALS(pCell->GetNumberOfParameters(), 3u); double expected_value; if (globalIndex <= 4 || globalIndex >= 16) { expected_value = 23.0; } else { expected_value = 0.0; } TS_ASSERT_DELTA(pCell->GetParameter("membrane_fast_sodium_current_conductance"), expected_value, 1e-12); TS_ASSERT_DELTA(pCell->GetParameter("membrane_rapid_delayed_rectifier_potassium_current_conductance"), 0.282, 1e-12); TS_ASSERT_DELTA(pCell->GetParameter("membrane_L_type_calcium_current_conductance"), 0.09, 1e-12); // Check stimulus has been replaced. It started as 0-1ms at x<=0.02, and should now be 600-601ms at x<=0.02 if (globalIndex < 3) { TS_ASSERT_EQUALS(pCell->GetStimulus(0.0), 0.0); TS_ASSERT_EQUALS(pCell->GetStimulus(0.5), 0.0); TS_ASSERT_EQUALS(pCell->GetStimulus(1.0), 0.0); TS_ASSERT_EQUALS(pCell->GetStimulus(599.9), 0.0); TS_ASSERT_EQUALS(pCell->GetStimulus(600.0), -200000.0); TS_ASSERT_EQUALS(pCell->GetStimulus(600.5), -200000.0); TS_ASSERT_EQUALS(pCell->GetStimulus(601.0), -200000.0); TS_ASSERT_EQUALS(pCell->GetStimulus(601.1), 0.0); } else { // Always zero... TS_ASSERT_EQUALS(pCell->GetStimulus(0.0), 0.0); TS_ASSERT_EQUALS(pCell->GetStimulus(0.5), 0.0); TS_ASSERT_EQUALS(pCell->GetStimulus(600.5), 0.0); TS_ASSERT_EQUALS(pCell->GetStimulus(10.0), 0.0); } } void doTestResumeChangingSettings(const std::string& rParametersFileName) { std::string foldername = "SaveMonodomainWithParameter"; // Save runSimulation(rParametersFileName); // Just check that the checkpoint exists FileFinder archive(foldername + "_checkpoints/1ms/" + foldername + "_1ms/archive.arch.0", RelativeTo::ChasteTestOutput); TS_ASSERT(archive.Exists()); { // Load CardiacSimulation simulation("heart/test/data/xml/resume_monodomain_changing_parameter.xml", false, true); boost::shared_ptr<AbstractUntemplatedCardiacProblem> p_problem = simulation.GetSavedProblem(); TS_ASSERT(p_problem); MonodomainProblem<1,1>* p_mono_problem = dynamic_cast<MonodomainProblem<1,1>*>(p_problem.get()); TS_ASSERT(p_mono_problem != NULL); DistributedVectorFactory* p_vector_factory = p_mono_problem->rGetMesh().GetDistributedVectorFactory(); for (unsigned node_global_index = p_vector_factory->GetLow(); node_global_index < p_vector_factory->GetHigh(); node_global_index++) { AbstractCardiacCellInterface* p_cell = p_mono_problem->GetTissue()->GetCardiacCell(node_global_index); checkParameter(p_cell, node_global_index); } // compare the files, using the CompareFilesViaHdf5DataReader() method TS_ASSERT( CompareFilesViaHdf5DataReader("heart/test/data/cardiac_simulations", "resume_monodomain_changing_parameter_results", false, foldername, "SimulationResults", true)); } } void TestResumeChangingSettings() { doTestResumeChangingSettings("heart/test/data/xml/save_monodomain_with_parameter.xml"); doTestResumeChangingSettings("heart/test/data/xml/save_monodomain_with_parameter_append.xml"); } void TestCardiacSimulationPatchwork() { OutputFileHandler handler("DynamicallyLoadedModel"); FileFinder cellml_file("heart/dynamic/luo_rudy_1991_dyn.cellml", RelativeTo::ChasteSourceRoot); handler.CopyFileTo(cellml_file); CardiacSimulation simulation("heart/test/data/xml/base_monodomain_patchwork.xml"); std::string foldername = "Patchwork"; // compare the files, using the CompareFilesViaHdf5DataReader() method TS_ASSERT(CompareFilesViaHdf5DataReader("heart/test/data/cardiac_simulations", "patchwork_results", false, foldername, "SimulationResults", true, 1e-5)); } void TestCardiacSimulationKirsten() { if (PetscTools::GetNumProcs() > 2u) { // There are only 2 layers of nodes in this simulation -- z length is equal to space step. TS_TRACE("This test is not suitable for more than 2 processes."); return; } CardiacSimulation simulation("heart/test/data/xml/base_monodomain_tt06_region.xml"); std::string foldername = "Kirsten"; TS_ASSERT(CompareFilesViaHdf5DataReaderGlobalNorm("heart/test/data/cardiac_simulations", "Kirsten", false, foldername, "SimulationResults", true, 5e-4)); // lower tolerance as comparing with non-backward-euler results. } void TestTransmuralCellularheterogeneities() { CardiacSimulation simulation("heart/test/data/xml/ChasteParametersCellHeterogeneities.xml"); std::string foldername = "ChasteResults_heterogeneities"; TS_ASSERT( CompareFilesViaHdf5DataReaderGlobalNorm("heart/test/data/cardiac_simulations", "transmural_heterogeneities_results", false, foldername, "SimulationResults", true)); } void TestElectrodes() { CardiacSimulation simulation("heart/test/data/xml/bidomain_with_bath2d_electrodes.xml"); std::string foldername = "ChasteResults_electrodes"; TS_ASSERT( CompareFilesViaHdf5DataReaderGlobalNorm("heart/test/data/cardiac_simulations", "electrodes_results", false, foldername, "SimulationResults", true, 1e-4)); } void TestExceptions() { TS_ASSERT_THROWS_THIS(CardiacSimulation simulation("heart/test/data/xml/monodomain8d_small.xml"), "Space dimension not supported: should be 1, 2 or 3"); TS_ASSERT_THROWS_THIS(CardiacSimulation simulation("heart/test/data/xml/bidomain8d_small.xml"), "Space dimension not supported: should be 1, 2 or 3"); #ifndef __APPLE__ ///\todo Passing error is fatal on Mac OSX TS_ASSERT_THROWS_THIS(CardiacSimulation simulation("heart/test/data/xml/base_monodomain_frankenstein.xml"), "XML parsing error in configuration file: heart/test/data/xml/base_monodomain_frankenstein.xml"); #endif TS_ASSERT_THROWS_THIS(CardiacSimulation simulation("no file"), "Missing file parsing configuration file: no file"); TS_ASSERT_THROWS_THIS(CardiacSimulation simulation(""), "No XML file name given"); #ifdef __APPLE__ FileFinder model("file_does_not_exist.dylib", RelativeTo::ChasteSourceRoot); #else FileFinder model("file_does_not_exist.so", RelativeTo::ChasteSourceRoot); #endif TS_ASSERT_THROWS_THIS(CardiacSimulation simulation("heart/test/data/xml/missing_dynamic_model.xml"), "Dynamically loadable cell model '" + model.GetAbsolutePath() + "' does not exist."); TS_ASSERT_THROWS_THIS(CardiacSimulation simulation("heart/test/data/xml/bidomain_with_bath2d_noelectrodes.xml"), "Simulation needs a stimulus (either <Stimuli> or <Electrodes>)."); #ifndef CHASTE_CAN_CHECKPOINT_DLLS TS_ASSERT_THROWS_THIS(CardiacSimulation simulation("heart/test/data/xml/dynamic_checkpoint.xml"), "Checkpointing is not compatible with dynamically loaded cell models on Mac OS X."); #endif } void TestDynamicallyLoadingCvodeCell() { // Coverage - using native CVODE cells should no longer throw #ifdef CHASTE_CVODE OutputFileHandler handler_cvode("DynamicallyLoadedModelCvode"); FileFinder cellml_file("heart/dynamic/luo_rudy_1991_dyn.cellml", RelativeTo::ChasteSourceRoot); handler_cvode.CopyFileTo(cellml_file); std::vector<std::string> args; args.push_back("--cvode"); CellMLToSharedLibraryConverter::CreateOptionsFile(handler_cvode, "luo_rudy_1991_dyn", args); CardiacSimulation simulation("heart/test/data/xml/dynamic_cvode_model.xml"); #else std::cout << "CVODE is not enabled.\n"; #endif } }; #endif /*TESTCARDIACSIMULATION_HPP_*/
48.108029
169
0.669479
SoftMatterMechanics
fee78a7881cf52687f363f7ee477a91dfd3abe8b
2,341
cc
C++
src/mqtt_api.cc
blumamir/wavplayeralsa
b219cf5d3377ac78ea82674d57ace3306cc39660
[ "MIT" ]
3
2020-11-30T12:11:05.000Z
2020-12-14T12:28:17.000Z
src/mqtt_api.cc
BlumAmir/wavplayeralsa
b219cf5d3377ac78ea82674d57ace3306cc39660
[ "MIT" ]
1
2020-12-01T07:34:12.000Z
2020-12-09T11:05:06.000Z
src/mqtt_api.cc
blumamir/wavplayeralsa
b219cf5d3377ac78ea82674d57ace3306cc39660
[ "MIT" ]
null
null
null
#include "mqtt_api.h" #include <iostream> #include <functional> #include <boost/date_time/time_duration.hpp> namespace wavplayeralsa { MqttApi::MqttApi(boost::asio::io_service &io_service) : io_service_(io_service), reconnect_timer_(io_service) { } void MqttApi::Initialize(std::shared_ptr<spdlog::logger> logger, const std::string &mqtt_host, uint16_t mqtt_port) { // set class members logger_ = logger; const char *mqtt_client_id = "wavplayeralsa"; logger_->info("creating mqtt connection to host {} on port {} with client id {}", mqtt_host, mqtt_port, mqtt_client_id); logger_->info("will publish current song updates on topic {}", CURRENT_SONG_TOPIC); mqtt_client_ = mqtt::make_sync_client(io_service_, mqtt_host, mqtt_port); mqtt_client_->set_client_id(mqtt_client_id); mqtt_client_->set_clean_session(true); mqtt_client_->set_error_handler(std::bind(&MqttApi::OnError, this, std::placeholders::_1)); mqtt_client_->set_close_handler(std::bind(&MqttApi::OnClose, this)); mqtt_client_->set_connack_handler(std::bind(&MqttApi::OnConnAck, this, std::placeholders::_1, std::placeholders::_2)); mqtt_client_->connect(); } void MqttApi::ReportCurrentSong(const std::string &json_str) { last_status_msg_ = json_str; PublishCurrentSong(); } void MqttApi::OnError(boost::system::error_code ec) { logger_->error("client disconnected from mqtt server. will try reconnect in {} ms", RECONNECT_WAIT_MS); reconnect_timer_.expires_from_now(boost::posix_time::milliseconds(RECONNECT_WAIT_MS)); reconnect_timer_.async_wait( [this] (boost::system::error_code ec) { if (ec != boost::asio::error::operation_aborted) { mqtt_client_->connect(); } }); } void MqttApi::OnClose() { logger_->error("client connection to mqtt server is closed"); } bool MqttApi::OnConnAck(bool session_present, std::uint8_t connack_return_code) { logger_->info("connack handler called. clean session: {}. coonack rerturn code: {}", session_present, mqtt::connect_return_code_to_str(connack_return_code)); PublishCurrentSong(); return true; } void MqttApi::PublishCurrentSong() { if(!this->mqtt_client_) return; if(last_status_msg_.empty()) return; this->mqtt_client_->publish_exactly_once(CURRENT_SONG_TOPIC, last_status_msg_, true); } }
29.632911
159
0.73302
blumamir
fee791c47707c37ae072012c2fb133f7444bcee8
24,867
cc
C++
src/core/prometheus.cc
liubangchen/seastar
5bf108406ae79a5f30383bf8e498dd9d4b51d1a5
[ "Apache-2.0" ]
1
2017-12-18T20:23:33.000Z
2017-12-18T20:23:33.000Z
src/core/prometheus.cc
liubangchen/seastar
5bf108406ae79a5f30383bf8e498dd9d4b51d1a5
[ "Apache-2.0" ]
2
2021-01-29T13:04:16.000Z
2021-05-12T13:25:34.000Z
src/core/prometheus.cc
liubangchen/seastar
5bf108406ae79a5f30383bf8e498dd9d4b51d1a5
[ "Apache-2.0" ]
3
2020-12-05T15:31:49.000Z
2020-12-12T16:11:20.000Z
/* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. 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. */ /* * Copyright (C) 2016 ScyllaDB */ #include <seastar/core/prometheus.hh> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/io/zero_copy_stream_impl_lite.h> #include "proto/metrics2.pb.h" #include <sstream> #include <seastar/core/scollectd_api.hh> #include "core/scollectd-impl.hh" #include <seastar/core/metrics_api.hh> #include <seastar/http/function_handlers.hh> #include <boost/algorithm/string/replace.hpp> #include <boost/range/algorithm_ext/erase.hpp> #include <boost/algorithm/string.hpp> #include <boost/range/algorithm.hpp> #include <boost/range/combine.hpp> #include <seastar/core/thread.hh> #include <seastar/core/loop.hh> namespace seastar { extern seastar::logger seastar_logger; namespace prometheus { namespace pm = io::prometheus::client; namespace mi = metrics::impl; /** * Taken from an answer in stackoverflow: * http://stackoverflow.com/questions/2340730/are-there-c-equivalents-for-the-protocol-buffers-delimited-i-o-functions-in-ja */ static bool write_delimited_to(const google::protobuf::MessageLite& message, google::protobuf::io::ZeroCopyOutputStream* rawOutput) { google::protobuf::io::CodedOutputStream output(rawOutput); #if GOOGLE_PROTOBUF_VERSION >= 3004000 const size_t size = message.ByteSizeLong(); output.WriteVarint64(size); #else const int size = message.ByteSize(); output.WriteVarint32(size); #endif uint8_t* buffer = output.GetDirectBufferForNBytesAndAdvance(size); if (buffer != nullptr) { message.SerializeWithCachedSizesToArray(buffer); } else { message.SerializeWithCachedSizes(&output); if (output.HadError()) { return false; } } return true; } static pm::Metric* add_label(pm::Metric* mt, const metrics::impl::metric_id & id, const config& ctx) { mt->mutable_label()->Reserve(id.labels().size() + 1); if (ctx.label) { auto label = mt->add_label(); label->set_name(ctx.label->key()); label->set_value(ctx.label->value()); } for (auto &&i : id.labels()) { auto label = mt->add_label(); label->set_name(i.first); label->set_value(i.second); } return mt; } static void fill_metric(pm::MetricFamily& mf, const metrics::impl::metric_value& c, const metrics::impl::metric_id & id, const config& ctx) { switch (c.type()) { case scollectd::data_type::DERIVE: add_label(mf.add_metric(), id, ctx)->mutable_counter()->set_value(c.i()); mf.set_type(pm::MetricType::COUNTER); break; case scollectd::data_type::GAUGE: add_label(mf.add_metric(), id, ctx)->mutable_gauge()->set_value(c.d()); mf.set_type(pm::MetricType::GAUGE); break; case scollectd::data_type::HISTOGRAM: { auto h = c.get_histogram(); auto mh = add_label(mf.add_metric(), id,ctx)->mutable_histogram(); mh->set_sample_count(h.sample_count); mh->set_sample_sum(h.sample_sum); for (auto b : h.buckets) { auto bc = mh->add_bucket(); bc->set_cumulative_count(b.count); bc->set_upper_bound(b.upper_bound); } mf.set_type(pm::MetricType::HISTOGRAM); break; } default: add_label(mf.add_metric(), id, ctx)->mutable_counter()->set_value(c.ui()); mf.set_type(pm::MetricType::COUNTER); break; } } static std::string to_str(seastar::metrics::impl::data_type dt) { switch (dt) { case seastar::metrics::impl::data_type::GAUGE: return "gauge"; case seastar::metrics::impl::data_type::COUNTER: return "counter"; case seastar::metrics::impl::data_type::HISTOGRAM: return "histogram"; case seastar::metrics::impl::data_type::DERIVE: // Prometheus server does not respect derive parameters // So we report them as counter return "counter"; default: break; } return "untyped"; } static std::string to_str(const seastar::metrics::impl::metric_value& v) { switch (v.type()) { case seastar::metrics::impl::data_type::GAUGE: return std::to_string(v.d()); case seastar::metrics::impl::data_type::COUNTER: return std::to_string(v.i()); case seastar::metrics::impl::data_type::DERIVE: return std::to_string(v.ui()); default: break; } return ""; // we should never get here but it makes the compiler happy } static void add_name(std::ostream& s, const sstring& name, const std::map<sstring, sstring>& labels, const config& ctx) { s << name << "{"; const char* delimiter = ""; if (ctx.label) { s << ctx.label->key() << "=\"" << ctx.label->value() << '"'; delimiter = ","; } if (!labels.empty()) { for (auto l : labels) { s << delimiter; s << l.first << "=\"" << l.second << '"'; delimiter = ","; } } s << "} "; } /*! * \brief iterator for metric family * * In prometheus, a single shard collecct all the data from the other * shards and report it. * * Each shard returns a value_copy struct that has a vector of vector values (a vector per metric family) * and a vector of metadata (and insdie it a vector of metric metadata) * * The metrics are sorted by the metric family name. * * In prometheus, all the metrics that belongs to the same metric family are reported together. * * For efficiency the results from the metrics layer are kept in a vector. * * So we have a vector of shards of a vector of metric families of a vector of values. * * To produce the result, we use the metric_family_iterator that is created by metric_family_range. * * When iterating over the metrics we use two helper structure. * * 1. A map between metric family name and the total number of values (combine on all shards) and * pointer to the metric family metadata. * 2. A vector of positions to the current metric family for each shard. * * The metric_family_range returns a metric_family_iterator that goes over all the families. * * The iterator returns a metric_family object, that can report the metric_family name, the size (how many * metrics in total belongs to the metric family) and a a foreach_metric method. * * The foreach_metric method can be used to perform an action on each of the metric that belongs to * that metric family * * Iterating over the metrics is done: * - go over each of the shard and each of the entry in the position vector: * - if the current family (the metric family that we get from the shard and position) has the current name: * - iterate over each of the metrics belong to that metric family: * * for example, if m is a metric_family_range * * for (auto&& i : m) { * std::cout << i.name() << std::endl; * i.foreach_metric([](const mi::metric_value& value, const mi::metric_info& value_info) { * std::cout << value_info.id.labels().size() <<std::cout; * }); * } * * Will print all the metric family names followed by the number of labels each metric has. */ class metric_family_iterator; class metric_family_range; class metrics_families_per_shard { using metrics_family_per_shard_data_container = std::vector<foreign_ptr<mi::values_reference>>; metrics_family_per_shard_data_container _data; using comp_function = std::function<bool(const sstring&, const mi::metric_family_metadata&)>; /*! * \brief find the last item in a range of metric family based on a comparator function * */ metric_family_iterator find_bound(const sstring& family_name, comp_function comp) const; public: using const_iterator = metrics_family_per_shard_data_container::const_iterator; using iterator = metrics_family_per_shard_data_container::iterator; using reference = metrics_family_per_shard_data_container::reference; using const_reference = metrics_family_per_shard_data_container::const_reference; /*! * \brief find the first item following a metric family range. * metric family are sorted, this will return the first item that is outside * of the range */ metric_family_iterator upper_bound(const sstring& family_name) const; /*! * \brief find the first item in a range of metric family. * metric family are sorted, the first item, is the first to match the * criteria. */ metric_family_iterator lower_bound(const sstring& family_name) const; /** * \defgroup Variables Global variables */ /* * @defgroup Vector properties * The following methods making metrics_families_per_shard act as * a vector of foreign_ptr<mi::values_reference> * @{ * * */ iterator begin() { return _data.begin(); } iterator end() { return _data.end(); } const_iterator begin() const { return _data.begin(); } const_iterator end() const { return _data.end(); } void resize(size_t new_size) { _data.resize(new_size); } reference& operator[](size_t n) { return _data[n]; } const_reference& operator[](size_t n) const { return _data[n]; } /** @} */ }; static future<> get_map_value(metrics_families_per_shard& vec) { vec.resize(smp::count); return parallel_for_each(boost::irange(0u, smp::count), [&vec] (auto cpu) { return smp::submit_to(cpu, [] { return mi::get_values(); }).then([&vec, cpu] (auto res) { vec[cpu] = std::move(res); }); }); } /*! * \brief a facade class for metric family */ class metric_family { const sstring* _name = nullptr; uint32_t _size = 0; const mi::metric_family_info* _family_info = nullptr; metric_family_iterator& _iterator_state; metric_family(metric_family_iterator& state) : _iterator_state(state) { } metric_family(const sstring* name , uint32_t size, const mi::metric_family_info* family_info, metric_family_iterator& state) : _name(name), _size(size), _family_info(family_info), _iterator_state(state) { } metric_family(const metric_family& info, metric_family_iterator& state) : metric_family(info._name, info._size, info._family_info, state) { } public: metric_family(const metric_family&) = delete; metric_family(metric_family&&) = delete; const sstring& name() const { return *_name; } const uint32_t size() const { return _size; } const mi::metric_family_info& metadata() const { return *_family_info; } void foreach_metric(std::function<void(const mi::metric_value&, const mi::metric_info&)>&& f); bool end() const { return !_name || !_family_info; } friend class metric_family_iterator; }; class metric_family_iterator { const metrics_families_per_shard& _families; std::vector<size_t> _positions; metric_family _info; void next() { if (_positions.empty()) { return; } const sstring *new_name = nullptr; const mi::metric_family_info* new_family_info = nullptr; _info._size = 0; for (auto&& i : boost::combine(_positions, _families)) { auto& pos_in_metric_per_shard = boost::get<0>(i); auto& metric_family = boost::get<1>(i); if (_info._name && pos_in_metric_per_shard < metric_family->metadata->size() && metric_family->metadata->at(pos_in_metric_per_shard).mf.name.compare(*_info._name) <= 0) { pos_in_metric_per_shard++; } if (pos_in_metric_per_shard >= metric_family->metadata->size()) { // no more metric family in this shard continue; } auto& metadata = metric_family->metadata->at(pos_in_metric_per_shard); int cmp = (!new_name) ? -1 : metadata.mf.name.compare(*new_name); if (cmp < 0) { new_name = &metadata.mf.name; new_family_info = &metadata.mf; _info._size = 0; } if (cmp <= 0) { _info._size += metadata.metrics.size(); } } _info._name = new_name; _info._family_info = new_family_info; } public: metric_family_iterator() = delete; metric_family_iterator(const metric_family_iterator& o) : _families(o._families), _positions(o._positions), _info(*this) { next(); } metric_family_iterator(metric_family_iterator&& o) : _families(o._families), _positions(std::move(o._positions)), _info(*this) { next(); } metric_family_iterator(const metrics_families_per_shard& families, unsigned shards) : _families(families), _positions(shards, 0), _info(*this) { next(); } metric_family_iterator(const metrics_families_per_shard& families, std::vector<size_t>&& positions) : _families(families), _positions(std::move(positions)), _info(*this) { next(); } metric_family_iterator& operator++() { next(); return *this; } metric_family_iterator operator++(int) { metric_family_iterator previous(*this); next(); return previous; } bool operator!=(const metric_family_iterator& o) const { return !(*this == o); } bool operator==(const metric_family_iterator& o) const { if (end()) { return o.end(); } if (o.end()) { return false; } return name() == o.name(); } metric_family& operator*() { return _info; } metric_family* operator->() { return &_info; } const sstring& name() const { return *_info._name; } const uint32_t size() const { return _info._size; } const mi::metric_family_info& metadata() const { return *_info._family_info; } bool end() const { return _positions.empty() || _info.end(); } void foreach_metric(std::function<void(const mi::metric_value&, const mi::metric_info&)>&& f) { // iterating over the shard vector and the position vector for (auto&& i : boost::combine(_positions, _families)) { auto& pos_in_metric_per_shard = boost::get<0>(i); auto& metric_family = boost::get<1>(i); if (pos_in_metric_per_shard >= metric_family->metadata->size()) { // no more metric family in this shard continue; } auto& metadata = metric_family->metadata->at(pos_in_metric_per_shard); // the the name is different, that means that on this shard, the metric family // does not exist, because everything is sorted by metric family name, this is fine. if (metadata.mf.name == name()) { const mi::value_vector& values = metric_family->values[pos_in_metric_per_shard]; const mi::metric_metadata_vector& metrics_metadata = metadata.metrics; for (auto&& vm : boost::combine(values, metrics_metadata)) { auto& value = boost::get<0>(vm); auto& metric_metadata = boost::get<1>(vm); f(value, metric_metadata); } } } } }; void metric_family::foreach_metric(std::function<void(const mi::metric_value&, const mi::metric_info&)>&& f) { _iterator_state.foreach_metric(std::move(f)); } class metric_family_range { metric_family_iterator _begin; metric_family_iterator _end; public: metric_family_range(const metrics_families_per_shard& families) : _begin(families, smp::count), _end(metric_family_iterator(families, 0)) { } metric_family_range(const metric_family_iterator& b, const metric_family_iterator& e) : _begin(b), _end(e) { } metric_family_iterator begin() const { return _begin; } metric_family_iterator end() const { return _end; } }; metric_family_iterator metrics_families_per_shard::find_bound(const sstring& family_name, comp_function comp) const { std::vector<size_t> positions; positions.reserve(smp::count); for (auto& shard_info : _data) { std::vector<mi::metric_family_metadata>& metadata = *(shard_info->metadata); std::vector<mi::metric_family_metadata>::iterator it_b = boost::range::upper_bound(metadata, family_name, comp); positions.emplace_back(it_b - metadata.begin()); } return metric_family_iterator(*this, std::move(positions)); } metric_family_iterator metrics_families_per_shard::lower_bound(const sstring& family_name) const { return find_bound(family_name, [](const sstring& a, const mi::metric_family_metadata& b) { //sstring doesn't have a <= operator return a < b.mf.name || a == b.mf.name; }); } metric_family_iterator metrics_families_per_shard::upper_bound(const sstring& family_name) const { return find_bound(family_name, [](const sstring& a, const mi::metric_family_metadata& b) { return a < b.mf.name; }); } /*! * \brief a helper function to get metric family range * if metric_family_name is empty will return everything, if not, it will return * the range of metric family that match the metric_family_name. * * if prefix is true the match will be based on prefix */ metric_family_range get_range(const metrics_families_per_shard& mf, const sstring& metric_family_name, bool prefix) { if (metric_family_name == "") { return metric_family_range(mf); } auto upper_bount_prefix = metric_family_name; ++upper_bount_prefix.back(); if (prefix) { return metric_family_range(mf.lower_bound(metric_family_name), mf.lower_bound(upper_bount_prefix)); } auto lb = mf.lower_bound(metric_family_name); if (lb.end() || lb->name() != metric_family_name) { return metric_family_range(lb, lb); // just return an empty range } auto up = lb; ++up; return metric_family_range(lb, up); } future<> write_text_representation(output_stream<char>& out, const config& ctx, const metric_family_range& m) { return seastar::async([&ctx, &out, &m] () mutable { bool found = false; for (metric_family& metric_family : m) { auto name = ctx.prefix + "_" + metric_family.name(); found = false; metric_family.foreach_metric([&out, &ctx, &found, &name, &metric_family](auto value, auto value_info) mutable { std::stringstream s; if (!found) { if (metric_family.metadata().d.str() != "") { s << "# HELP " << name << " " << metric_family.metadata().d.str() << "\n"; } s << "# TYPE " << name << " " << to_str(metric_family.metadata().type) << "\n"; found = true; } if (value.type() == mi::data_type::HISTOGRAM) { auto&& h = value.get_histogram(); std::map<sstring, sstring> labels = value_info.id.labels(); add_name(s, name + "_sum", labels, ctx); s << h.sample_sum; s << "\n"; add_name(s, name + "_count", labels, ctx); s << h.sample_count; s << "\n"; auto& le = labels["le"]; auto bucket = name + "_bucket"; for (auto i : h.buckets) { le = std::to_string(i.upper_bound); add_name(s, bucket, labels, ctx); s << i.count; s << "\n"; } labels["le"] = "+Inf"; add_name(s, bucket, labels, ctx); s << h.sample_count; s << "\n"; } else { add_name(s, name, value_info.id.labels(), ctx); s << to_str(value); s << "\n"; } out.write(s.str()).get(); thread::maybe_yield(); }); } }); } future<> write_protobuf_representation(output_stream<char>& out, const config& ctx, metric_family_range& m) { return do_for_each(m, [&ctx, &out](metric_family& metric_family) mutable { std::string s; google::protobuf::io::StringOutputStream os(&s); auto& name = metric_family.name(); pm::MetricFamily mtf; mtf.set_name(ctx.prefix + "_" + name); mtf.mutable_metric()->Reserve(metric_family.size()); metric_family.foreach_metric([&mtf, &ctx](auto value, auto value_info) { fill_metric(mtf, value, value_info.id, ctx); }); if (!write_delimited_to(mtf, &os)) { seastar_logger.warn("Failed to write protobuf metrics"); } return out.write(s); }); } bool is_accept_text(const std::string& accept) { std::vector<std::string> strs; boost::split(strs, accept, boost::is_any_of(",")); for (auto i : strs) { boost::trim(i); if (boost::starts_with(i, "application/vnd.google.protobuf;")) { return false; } } return true; } class metrics_handler : public handler_base { sstring _prefix; config _ctx; /*! * \brief tries to trim an asterisk from the end of the string * return true if an asterisk exists. */ bool trim_asterisk(sstring& name) { if (name.size() && name.back() == '*') { name.resize(name.length() - 1); return true; } // Prometheus uses url encoding for the path so '*' is encoded as '%2A' if (boost::algorithm::ends_with(name, "%2A")) { // This assert is obviously true. It is in here just to // silence a bogus gcc warning: // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=89337 assert(name.length() >= 3); name.resize(name.length() - 3); return true; } return false; } public: metrics_handler(config ctx) : _ctx(ctx) {} future<std::unique_ptr<httpd::reply>> handle(const sstring& path, std::unique_ptr<httpd::request> req, std::unique_ptr<httpd::reply> rep) override { auto text = is_accept_text(req->get_header("Accept")); sstring metric_family_name = req->get_query_param("name"); bool prefix = trim_asterisk(metric_family_name); rep->write_body((text) ? "txt" : "proto", [this, text, metric_family_name, prefix] (output_stream<char>&& s) { return do_with(metrics_families_per_shard(), output_stream<char>(std::move(s)), [this, text, prefix, &metric_family_name] (metrics_families_per_shard& families, output_stream<char>& s) mutable { return get_map_value(families).then([&s, &families, this, text, prefix, &metric_family_name]() mutable { return do_with(get_range(families, metric_family_name, prefix), [&s, this, text](metric_family_range& m) { return (text) ? write_text_representation(s, _ctx, m) : write_protobuf_representation(s, _ctx, m); }); }).finally([&s] () mutable { return s.close(); }); }); }); return make_ready_future<std::unique_ptr<httpd::reply>>(std::move(rep)); } }; future<> add_prometheus_routes(http_server& server, config ctx) { server._routes.put(GET, "/metrics", new metrics_handler(ctx)); return make_ready_future<>(); } future<> add_prometheus_routes(distributed<http_server>& server, config ctx) { return server.invoke_on_all([ctx](http_server& s) { return add_prometheus_routes(s, ctx); }); } future<> start(httpd::http_server_control& http_server, config ctx) { return add_prometheus_routes(http_server.server(), ctx); } } }
34.633705
134
0.620018
liubangchen
fee845322dd8be6b297c2bc610eeb5a9bf1bc4dc
2,272
cpp
C++
lib/Submix.cpp
gpeter12/amuse
d96be61e296031d5417e46dba1d3b9060b2ab6c0
[ "MIT" ]
36
2016-05-05T21:49:16.000Z
2022-03-20T02:28:41.000Z
lib/Submix.cpp
gpeter12/amuse
d96be61e296031d5417e46dba1d3b9060b2ab6c0
[ "MIT" ]
10
2016-06-26T21:05:22.000Z
2021-08-14T11:46:55.000Z
lib/Submix.cpp
gpeter12/amuse
d96be61e296031d5417e46dba1d3b9060b2ab6c0
[ "MIT" ]
5
2016-09-16T08:38:16.000Z
2021-01-08T22:37:52.000Z
#include "amuse/Submix.hpp" namespace amuse { Submix::Submix(Engine& engine) : m_root(engine) {} EffectChorus& Submix::makeChorus(uint32_t baseDelay, uint32_t variation, uint32_t period) { return makeEffect<EffectChorus>(baseDelay, variation, period); } EffectChorus& Submix::makeChorus(const EffectChorusInfo& info) { return makeEffect<EffectChorus>(info); } EffectDelay& Submix::makeDelay(uint32_t initDelay, uint32_t initFeedback, uint32_t initOutput) { return makeEffect<EffectDelay>(initDelay, initFeedback, initOutput); } EffectDelay& Submix::makeDelay(const EffectDelayInfo& info) { return makeEffect<EffectDelay>(info); } EffectReverbStd& Submix::makeReverbStd(float coloration, float mix, float time, float damping, float preDelay) { return makeEffect<EffectReverbStd>(coloration, mix, time, damping, preDelay); } EffectReverbStd& Submix::makeReverbStd(const EffectReverbStdInfo& info) { return makeEffect<EffectReverbStd>(info); } EffectReverbHi& Submix::makeReverbHi(float coloration, float mix, float time, float damping, float preDelay, float crosstalk) { return makeEffect<EffectReverbHi>(coloration, mix, time, damping, preDelay, crosstalk); } EffectReverbHi& Submix::makeReverbHi(const EffectReverbHiInfo& info) { return makeEffect<EffectReverbHi>(info); } void Submix::applyEffect(int16_t* audio, size_t frameCount, const ChannelMap& chanMap) const { for (const std::unique_ptr<EffectBaseTypeless>& effect : m_effectStack) ((EffectBase<int16_t>&)*effect).applyEffect(audio, frameCount, chanMap); } void Submix::applyEffect(int32_t* audio, size_t frameCount, const ChannelMap& chanMap) const { for (const std::unique_ptr<EffectBaseTypeless>& effect : m_effectStack) ((EffectBase<int32_t>&)*effect).applyEffect(audio, frameCount, chanMap); } void Submix::applyEffect(float* audio, size_t frameCount, const ChannelMap& chanMap) const { for (const std::unique_ptr<EffectBaseTypeless>& effect : m_effectStack) ((EffectBase<float>&)*effect).applyEffect(audio, frameCount, chanMap); } void Submix::resetOutputSampleRate(double sampleRate) { for (const std::unique_ptr<EffectBaseTypeless>& effect : m_effectStack) effect->resetOutputSampleRate(sampleRate); } } // namespace amuse
43.692308
117
0.767606
gpeter12
feea116fac1614a6841a468795ea1b23442b2ffd
2,946
cpp
C++
src/Sobol.cpp
lilesper/SparseVoxelOctree
9c4c79ab746758d21070bb733dafe4f78438e4b5
[ "MIT" ]
338
2019-08-02T03:57:05.000Z
2022-03-29T20:49:21.000Z
src/Sobol.cpp
lilesper/SparseVoxelOctree
9c4c79ab746758d21070bb733dafe4f78438e4b5
[ "MIT" ]
12
2020-01-10T09:03:22.000Z
2022-03-25T02:03:23.000Z
src/Sobol.cpp
lilesper/SparseVoxelOctree
9c4c79ab746758d21070bb733dafe4f78438e4b5
[ "MIT" ]
36
2019-08-08T11:15:23.000Z
2022-02-26T00:31:13.000Z
#include "Sobol.hpp" constexpr uint32_t kMaxDimension = 64; constexpr VkDeviceSize kBufferSize = (kMaxDimension + 1) * sizeof(uint32_t); /*void Sobol::Next(float *out) { uint8_t c = get_first_zero_bit(m_index++); //uint8_t c = glm::findLSB(~(m_index ++)); for (unsigned j = 0; j < m_dim; ++j) out[j] = (float) ((m_x[j] ^= kMatrices[j][c]) / 4294967296.0); }*/ void Sobol::Initialize(const std::shared_ptr<myvk::Device> &device) { m_descriptor_pool = myvk::DescriptorPool::Create(device, 1, {{VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1}}); { VkDescriptorSetLayoutBinding sobol_binding = {}; sobol_binding.binding = 0; sobol_binding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; sobol_binding.descriptorCount = 1; sobol_binding.stageFlags = VK_SHADER_STAGE_COMPUTE_BIT | VK_SHADER_STAGE_FRAGMENT_BIT; m_descriptor_set_layout = myvk::DescriptorSetLayout::Create(device, {sobol_binding}); } m_descriptor_set = myvk::DescriptorSet::Create(m_descriptor_pool, m_descriptor_set_layout); m_sobol_buffer = myvk::Buffer::Create(device, kBufferSize, VMA_MEMORY_USAGE_GPU_ONLY, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT); m_descriptor_set->UpdateStorageBuffer(m_sobol_buffer, 0); m_staging_buffer = myvk::Buffer::CreateStaging(device, kBufferSize); { uint32_t *data = (uint32_t *)m_staging_buffer->Map(); std::fill(data, data + kMaxDimension + 1, 0u); m_staging_buffer->Unmap(); } m_pipeline_layout = myvk::PipelineLayout::Create(device, {m_descriptor_set_layout}, {{VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(uint32_t)}}); { constexpr uint32_t kSobolCompSpv[] = { #include "spirv/sobol.comp.u32" }; std::shared_ptr<myvk::ShaderModule> sobol_shader_module = myvk::ShaderModule::Create(device, kSobolCompSpv, sizeof(kSobolCompSpv)); m_compute_pipeline = myvk::ComputePipeline::Create(m_pipeline_layout, sobol_shader_module); } } void Sobol::CmdNext(const std::shared_ptr<myvk::CommandBuffer> &command_buffer) { command_buffer->CmdBindDescriptorSets({m_descriptor_set}, m_pipeline_layout, VK_PIPELINE_BIND_POINT_COMPUTE, {}); command_buffer->CmdPushConstants(m_pipeline_layout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(uint32_t), &m_dimension); command_buffer->CmdBindPipeline(m_compute_pipeline); command_buffer->CmdDispatch(1, 1, 1); } void Sobol::Reset(const std::shared_ptr<myvk::CommandPool> &command_pool, uint32_t dimension) { m_dimension = dimension; std::shared_ptr<myvk::Fence> fence = myvk::Fence::Create(command_pool->GetDevicePtr()); std::shared_ptr<myvk::CommandBuffer> command_buffer = myvk::CommandBuffer::Create(command_pool); command_buffer->Begin(VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT); command_buffer->CmdCopy(m_staging_buffer, m_sobol_buffer, {{0, 0, kBufferSize}}); command_buffer->End(); command_buffer->Submit(fence); fence->Wait(); }
43.970149
117
0.746436
lilesper
feefb161222befd1d66d36e7a487a859ed3ff3fb
786
cpp
C++
110.平衡二叉树/isBalanced.cpp
YichengZhong/Top-Interview-Questions
124828d321f482a0eaa30012b3706267487bfd24
[ "MIT" ]
1
2019-10-21T14:40:39.000Z
2019-10-21T14:40:39.000Z
110.平衡二叉树/isBalanced.cpp
YichengZhong/Top-Interview-Questions
124828d321f482a0eaa30012b3706267487bfd24
[ "MIT" ]
null
null
null
110.平衡二叉树/isBalanced.cpp
YichengZhong/Top-Interview-Questions
124828d321f482a0eaa30012b3706267487bfd24
[ "MIT" ]
1
2020-11-04T07:33:34.000Z
2020-11-04T07:33:34.000Z
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: bool isBalanced(TreeNode* root) { if(root==NULL) { return true; } int maxDepthLeft=maxDepth(root->left) ; int maxDepthRight=maxDepth(root->right) ; if(abs(maxDepthLeft-maxDepthRight)>1) { return false; } return isBalanced(root->left) && isBalanced(root->right); } int maxDepth(TreeNode* root) { if (!root) return 0; return 1 + max(maxDepth(root->left), maxDepth(root->right)); } };
21.243243
68
0.507634
YichengZhong
fef18edd36750ebc832bf59cc21067f4dee0c528
8,637
cpp
C++
cpp/godot-cpp/src/gen/Line2D.cpp
GDNative-Gradle/proof-of-concept
162f467430760cf959f68f1638adc663fd05c5fd
[ "MIT" ]
1
2021-03-16T09:51:00.000Z
2021-03-16T09:51:00.000Z
cpp/godot-cpp/src/gen/Line2D.cpp
GDNative-Gradle/proof-of-concept
162f467430760cf959f68f1638adc663fd05c5fd
[ "MIT" ]
null
null
null
cpp/godot-cpp/src/gen/Line2D.cpp
GDNative-Gradle/proof-of-concept
162f467430760cf959f68f1638adc663fd05c5fd
[ "MIT" ]
null
null
null
#include "Line2D.hpp" #include <core/GodotGlobal.hpp> #include <core/CoreTypes.hpp> #include <core/Ref.hpp> #include <core/Godot.hpp> #include "__icalls.hpp" #include "Curve.hpp" #include "Gradient.hpp" #include "Texture.hpp" namespace godot { Line2D::___method_bindings Line2D::___mb = {}; void Line2D::___init_method_bindings() { ___mb.mb__curve_changed = godot::api->godot_method_bind_get_method("Line2D", "_curve_changed"); ___mb.mb__gradient_changed = godot::api->godot_method_bind_get_method("Line2D", "_gradient_changed"); ___mb.mb_add_point = godot::api->godot_method_bind_get_method("Line2D", "add_point"); ___mb.mb_clear_points = godot::api->godot_method_bind_get_method("Line2D", "clear_points"); ___mb.mb_get_antialiased = godot::api->godot_method_bind_get_method("Line2D", "get_antialiased"); ___mb.mb_get_begin_cap_mode = godot::api->godot_method_bind_get_method("Line2D", "get_begin_cap_mode"); ___mb.mb_get_curve = godot::api->godot_method_bind_get_method("Line2D", "get_curve"); ___mb.mb_get_default_color = godot::api->godot_method_bind_get_method("Line2D", "get_default_color"); ___mb.mb_get_end_cap_mode = godot::api->godot_method_bind_get_method("Line2D", "get_end_cap_mode"); ___mb.mb_get_gradient = godot::api->godot_method_bind_get_method("Line2D", "get_gradient"); ___mb.mb_get_joint_mode = godot::api->godot_method_bind_get_method("Line2D", "get_joint_mode"); ___mb.mb_get_point_count = godot::api->godot_method_bind_get_method("Line2D", "get_point_count"); ___mb.mb_get_point_position = godot::api->godot_method_bind_get_method("Line2D", "get_point_position"); ___mb.mb_get_points = godot::api->godot_method_bind_get_method("Line2D", "get_points"); ___mb.mb_get_round_precision = godot::api->godot_method_bind_get_method("Line2D", "get_round_precision"); ___mb.mb_get_sharp_limit = godot::api->godot_method_bind_get_method("Line2D", "get_sharp_limit"); ___mb.mb_get_texture = godot::api->godot_method_bind_get_method("Line2D", "get_texture"); ___mb.mb_get_texture_mode = godot::api->godot_method_bind_get_method("Line2D", "get_texture_mode"); ___mb.mb_get_width = godot::api->godot_method_bind_get_method("Line2D", "get_width"); ___mb.mb_remove_point = godot::api->godot_method_bind_get_method("Line2D", "remove_point"); ___mb.mb_set_antialiased = godot::api->godot_method_bind_get_method("Line2D", "set_antialiased"); ___mb.mb_set_begin_cap_mode = godot::api->godot_method_bind_get_method("Line2D", "set_begin_cap_mode"); ___mb.mb_set_curve = godot::api->godot_method_bind_get_method("Line2D", "set_curve"); ___mb.mb_set_default_color = godot::api->godot_method_bind_get_method("Line2D", "set_default_color"); ___mb.mb_set_end_cap_mode = godot::api->godot_method_bind_get_method("Line2D", "set_end_cap_mode"); ___mb.mb_set_gradient = godot::api->godot_method_bind_get_method("Line2D", "set_gradient"); ___mb.mb_set_joint_mode = godot::api->godot_method_bind_get_method("Line2D", "set_joint_mode"); ___mb.mb_set_point_position = godot::api->godot_method_bind_get_method("Line2D", "set_point_position"); ___mb.mb_set_points = godot::api->godot_method_bind_get_method("Line2D", "set_points"); ___mb.mb_set_round_precision = godot::api->godot_method_bind_get_method("Line2D", "set_round_precision"); ___mb.mb_set_sharp_limit = godot::api->godot_method_bind_get_method("Line2D", "set_sharp_limit"); ___mb.mb_set_texture = godot::api->godot_method_bind_get_method("Line2D", "set_texture"); ___mb.mb_set_texture_mode = godot::api->godot_method_bind_get_method("Line2D", "set_texture_mode"); ___mb.mb_set_width = godot::api->godot_method_bind_get_method("Line2D", "set_width"); } Line2D *Line2D::_new() { return (Line2D *) godot::nativescript_1_1_api->godot_nativescript_get_instance_binding_data(godot::_RegisterState::language_index, godot::api->godot_get_class_constructor((char *)"Line2D")()); } void Line2D::_curve_changed() { ___godot_icall_void(___mb.mb__curve_changed, (const Object *) this); } void Line2D::_gradient_changed() { ___godot_icall_void(___mb.mb__gradient_changed, (const Object *) this); } void Line2D::add_point(const Vector2 position, const int64_t at_position) { ___godot_icall_void_Vector2_int(___mb.mb_add_point, (const Object *) this, position, at_position); } void Line2D::clear_points() { ___godot_icall_void(___mb.mb_clear_points, (const Object *) this); } bool Line2D::get_antialiased() const { return ___godot_icall_bool(___mb.mb_get_antialiased, (const Object *) this); } Line2D::LineCapMode Line2D::get_begin_cap_mode() const { return (Line2D::LineCapMode) ___godot_icall_int(___mb.mb_get_begin_cap_mode, (const Object *) this); } Ref<Curve> Line2D::get_curve() const { return Ref<Curve>::__internal_constructor(___godot_icall_Object(___mb.mb_get_curve, (const Object *) this)); } Color Line2D::get_default_color() const { return ___godot_icall_Color(___mb.mb_get_default_color, (const Object *) this); } Line2D::LineCapMode Line2D::get_end_cap_mode() const { return (Line2D::LineCapMode) ___godot_icall_int(___mb.mb_get_end_cap_mode, (const Object *) this); } Ref<Gradient> Line2D::get_gradient() const { return Ref<Gradient>::__internal_constructor(___godot_icall_Object(___mb.mb_get_gradient, (const Object *) this)); } Line2D::LineJointMode Line2D::get_joint_mode() const { return (Line2D::LineJointMode) ___godot_icall_int(___mb.mb_get_joint_mode, (const Object *) this); } int64_t Line2D::get_point_count() const { return ___godot_icall_int(___mb.mb_get_point_count, (const Object *) this); } Vector2 Line2D::get_point_position(const int64_t i) const { return ___godot_icall_Vector2_int(___mb.mb_get_point_position, (const Object *) this, i); } PoolVector2Array Line2D::get_points() const { return ___godot_icall_PoolVector2Array(___mb.mb_get_points, (const Object *) this); } int64_t Line2D::get_round_precision() const { return ___godot_icall_int(___mb.mb_get_round_precision, (const Object *) this); } real_t Line2D::get_sharp_limit() const { return ___godot_icall_float(___mb.mb_get_sharp_limit, (const Object *) this); } Ref<Texture> Line2D::get_texture() const { return Ref<Texture>::__internal_constructor(___godot_icall_Object(___mb.mb_get_texture, (const Object *) this)); } Line2D::LineTextureMode Line2D::get_texture_mode() const { return (Line2D::LineTextureMode) ___godot_icall_int(___mb.mb_get_texture_mode, (const Object *) this); } real_t Line2D::get_width() const { return ___godot_icall_float(___mb.mb_get_width, (const Object *) this); } void Line2D::remove_point(const int64_t i) { ___godot_icall_void_int(___mb.mb_remove_point, (const Object *) this, i); } void Line2D::set_antialiased(const bool antialiased) { ___godot_icall_void_bool(___mb.mb_set_antialiased, (const Object *) this, antialiased); } void Line2D::set_begin_cap_mode(const int64_t mode) { ___godot_icall_void_int(___mb.mb_set_begin_cap_mode, (const Object *) this, mode); } void Line2D::set_curve(const Ref<Curve> curve) { ___godot_icall_void_Object(___mb.mb_set_curve, (const Object *) this, curve.ptr()); } void Line2D::set_default_color(const Color color) { ___godot_icall_void_Color(___mb.mb_set_default_color, (const Object *) this, color); } void Line2D::set_end_cap_mode(const int64_t mode) { ___godot_icall_void_int(___mb.mb_set_end_cap_mode, (const Object *) this, mode); } void Line2D::set_gradient(const Ref<Gradient> color) { ___godot_icall_void_Object(___mb.mb_set_gradient, (const Object *) this, color.ptr()); } void Line2D::set_joint_mode(const int64_t mode) { ___godot_icall_void_int(___mb.mb_set_joint_mode, (const Object *) this, mode); } void Line2D::set_point_position(const int64_t i, const Vector2 position) { ___godot_icall_void_int_Vector2(___mb.mb_set_point_position, (const Object *) this, i, position); } void Line2D::set_points(const PoolVector2Array points) { ___godot_icall_void_PoolVector2Array(___mb.mb_set_points, (const Object *) this, points); } void Line2D::set_round_precision(const int64_t precision) { ___godot_icall_void_int(___mb.mb_set_round_precision, (const Object *) this, precision); } void Line2D::set_sharp_limit(const real_t limit) { ___godot_icall_void_float(___mb.mb_set_sharp_limit, (const Object *) this, limit); } void Line2D::set_texture(const Ref<Texture> texture) { ___godot_icall_void_Object(___mb.mb_set_texture, (const Object *) this, texture.ptr()); } void Line2D::set_texture_mode(const int64_t mode) { ___godot_icall_void_int(___mb.mb_set_texture_mode, (const Object *) this, mode); } void Line2D::set_width(const real_t width) { ___godot_icall_void_float(___mb.mb_set_width, (const Object *) this, width); } }
43.40201
193
0.789858
GDNative-Gradle
fef4987df264d2777297d68fb45de9c3eba67905
723
cpp
C++
src/log.cpp
vzwGrey/filter-magic
59e3ccc238716ab4b1b1b3ae560021e558f6718a
[ "MIT" ]
5
2018-08-16T16:51:16.000Z
2018-09-09T08:35:21.000Z
src/log.cpp
vzwGrey/filter-magic
59e3ccc238716ab4b1b1b3ae560021e558f6718a
[ "MIT" ]
null
null
null
src/log.cpp
vzwGrey/filter-magic
59e3ccc238716ab4b1b1b3ae560021e558f6718a
[ "MIT" ]
1
2018-10-08T03:30:12.000Z
2018-10-08T03:30:12.000Z
#include <string> #include <sstream> #include <iostream> #include "log.h" using std::string; using std::stringstream; void log::info(string message) { std::cout << "\e[0;32m[INFO]\e[0m - " << message << std::endl; } void log::error(string name, string message) { std::cerr << "\e[0;31m" << name << ":\e[0m " << message << std::endl; } void log::fatal(string name, string message) { stringstream err_name; err_name << "Fatal - " << name; log::error(err_name.str(), message); exit(1); } void log::missing_argument(string command, string parameter) { stringstream message; message << "Command `" << command << "' expects an argument of `" << parameter << "'."; log::fatal("Missing Argument", message.str()); }
23.322581
88
0.64592
vzwGrey
fef4d4554f28b3db44bc9ab02d52776b079892de
15,885
cpp
C++
tools/extras/irstlm/src/ngt.cpp
scscscscscsc/kaldi-trunk
aa9a8143e0fee12d85562ccc1d06e0e99f630029
[ "Apache-2.0" ]
4
2016-06-05T14:19:32.000Z
2016-06-07T09:21:10.000Z
tools/extras/irstlm/src/ngt.cpp
MistSC/kaldi-trunk
aa9a8143e0fee12d85562ccc1d06e0e99f630029
[ "Apache-2.0" ]
null
null
null
tools/extras/irstlm/src/ngt.cpp
MistSC/kaldi-trunk
aa9a8143e0fee12d85562ccc1d06e0e99f630029
[ "Apache-2.0" ]
null
null
null
// $Id: ngt.cpp 245 2009-04-02 14:05:40Z fabio_brugnara $ /****************************************************************************** IrstLM: IRST Language Model Toolkit Copyright (C) 2006 Marcello Federico, ITC-irst Trento, Italy 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; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 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 ******************************************************************************/ // ngt // by M. Federico // Copyright Marcello Federico, ITC-irst, 1998 #include <iostream> #include <sstream> #include <cmath> #include "util.h" #include "cmd.h" #include "mfstream.h" #include "mempool.h" #include "htable.h" #include "dictionary.h" #include "n_gram.h" #include "ngramtable.h" using namespace std; void print_help(int TypeFlag=0){ std::cerr << std::endl << "ngt - collects n-grams" << std::endl; std::cerr << std::endl << "USAGE:" << std::endl; std::cerr << " ngt -i=<inputfile> [options]" << std::endl; std::cerr << std::endl << "OPTIONS:" << std::endl; FullPrintParams(TypeFlag, 0, 1, stderr); } void usage(const char *msg = 0) { if (msg){ std::cerr << msg << std::endl; } else{ print_help(); } } int main(int argc, char **argv) { char *inp=NULL; char *out=NULL; char *dic=NULL; // dictionary filename char *subdic=NULL; // subdictionary filename char *filterdict=NULL; // subdictionary filename char *filtertable=NULL; // ngramtable filename char *iknfile=NULL; // filename to save IKN statistics double filter_hit_rate=1.0; // minimum hit rate of filter char *aug=NULL; // augmentation data char *hmask=NULL; // historymask bool inputgoogleformat=false; //reads ngrams in Google format bool outputgoogleformat=false; //print ngrams in Google format int ngsz=0; // n-gram default size int dstco=0; // compute distance co-occurrences bool bin=false; bool ss=false; //generate single table bool LMflag=false; //work with LM table int inplen=0; //input length for mask generation bool tlm=false; //test lm table char* ftlm=NULL; //file to test LM table bool memuse=false; bool help=false; DeclareParams((char*) "Dictionary", CMDSTRINGTYPE|CMDMSG, &dic, "dictionary filename", "d", CMDSTRINGTYPE|CMDMSG, &dic, "dictionary filename", "NgramSize", CMDSUBRANGETYPE|CMDMSG, &ngsz, 1, MAX_NGRAM, "n-gram default size; default is 0", "n", CMDSUBRANGETYPE|CMDMSG, &ngsz, 1, MAX_NGRAM, "n-gram default size; default is 0", "InputFile", CMDSTRINGTYPE|CMDMSG, &inp, "input file", "i", CMDSTRINGTYPE|CMDMSG, &inp, "input file", "OutputFile", CMDSTRINGTYPE|CMDMSG, &out, "output file", "o", CMDSTRINGTYPE|CMDMSG, &out, "output file", "InputGoogleFormat", CMDBOOLTYPE|CMDMSG, &inputgoogleformat, "the input file contains data in the n-gram Google format; default is false", "gooinp", CMDBOOLTYPE|CMDMSG, &inputgoogleformat, "the input file contains data in the n-gram Google format; default is false", "OutputGoogleFormat", CMDBOOLTYPE|CMDMSG, &outputgoogleformat, "the output file contains data in the n-gram Google format; default is false", "gooout", CMDBOOLTYPE|CMDMSG, &outputgoogleformat, "the output file contains data in the n-gram Google format; default is false", "SaveBinaryTable", CMDBOOLTYPE|CMDMSG, &bin, "saves into binary format; default is false", "b", CMDBOOLTYPE|CMDMSG, &bin, "saves into binary format; default is false", "LmTable", CMDBOOLTYPE|CMDMSG, &LMflag, "works with LM table; default is false", "lm", CMDBOOLTYPE|CMDMSG, &LMflag, "works with LM table; default is false", "DistCo", CMDINTTYPE|CMDMSG, &dstco, "computes distance co-occurrences at the specified distance; default is 0", "dc", CMDINTTYPE|CMDMSG, &dstco, "computes distance co-occurrences at the specified distance; default is 0", "AugmentFile", CMDSTRINGTYPE|CMDMSG, &aug, "augmentation data", "aug", CMDSTRINGTYPE|CMDMSG, &aug, "augmentation data", "SaveSingle", CMDBOOLTYPE|CMDMSG, &ss, "generates single table; default is false", "ss", CMDBOOLTYPE|CMDMSG, &ss, "generates single table; default is false", "SubDict", CMDSTRINGTYPE|CMDMSG, &subdic, "subdictionary", "sd", CMDSTRINGTYPE|CMDMSG, &subdic, "subdictionary", "FilterDict", CMDSTRINGTYPE|CMDMSG, &filterdict, "filter dictionary", "fd", CMDSTRINGTYPE|CMDMSG, &filterdict, "filter dictionary", "ConvDict", CMDSTRINGTYPE|CMDMSG, &subdic, "subdictionary", "cd", CMDSTRINGTYPE|CMDMSG, &subdic, "subdictionary", "FilterTable", CMDSTRINGTYPE|CMDMSG, &filtertable, "ngramtable filename", "ftr", CMDDOUBLETYPE|CMDMSG, &filter_hit_rate, "ngramtable filename", "FilterTableRate", CMDDOUBLETYPE|CMDMSG, &filter_hit_rate, "minimum hit rate of filter; default is 1.0", "ft", CMDSTRINGTYPE|CMDMSG, &filtertable, "minimum hit rate of filter; default is 1.0", "HistoMask",CMDSTRINGTYPE|CMDMSG, &hmask, "history mask", "hm",CMDSTRINGTYPE|CMDMSG, &hmask, "history mask", "InpLen",CMDINTTYPE|CMDMSG, &inplen, "input length for mask generation; default is 0", "il",CMDINTTYPE|CMDMSG, &inplen, "input length for mask generation; default is 0", "tlm", CMDBOOLTYPE|CMDMSG, &tlm, "test LM table; default is false", "ftlm", CMDSTRINGTYPE|CMDMSG, &ftlm, "file to test LM table", "memuse", CMDBOOLTYPE|CMDMSG, &memuse, "default is false", "iknstat", CMDSTRINGTYPE|CMDMSG, &iknfile, "filename to save IKN statistics", "Help", CMDBOOLTYPE|CMDMSG, &help, "print this help", "h", CMDBOOLTYPE|CMDMSG, &help, "print this help", (char *)NULL ); if (argc == 1){ usage(); exit_error(IRSTLM_NO_ERROR); } GetParams(&argc, &argv, (char*) NULL); if (help){ usage(); exit_error(IRSTLM_NO_ERROR); } if (inp==NULL) { usage(); exit_error(IRSTLM_ERROR_DATA,"Warning: no input file specified"); }; if (out==NULL) { cerr << "Warning: no output file specified!\n"; } TABLETYPE table_type=COUNT; if (LMflag) { cerr << "Working with LM table\n"; table_type=LEAFPROB; } // check word order of subdictionary if (filtertable) { { ngramtable ngt(filtertable,1,NULL,NULL,NULL,0,0,NULL,0,table_type); mfstream inpstream(inp,ios::in); //google input table mfstream outstream(out,ios::out); //google output table cerr << "Filtering table " << inp << " assumed to be in Google Format with size " << ngsz << "\n"; cerr << "with table " << filtertable << " of size " << ngt.maxlevel() << "\n"; cerr << "with hit rate " << filter_hit_rate << "\n"; //order of filter table must be smaller than that of input n-grams assert(ngt.maxlevel() <= ngsz); //read input googletable of ngrams of size ngsz //output entries made of at least X% n-grams contained in filtertable //<unk> words are not accepted ngram ng(ngt.dict), ng2(ng.dict); double hits=0; double maxhits=(double)(ngsz-ngt.maxlevel()+1); long c=0; while(inpstream >> ng) { if (ng.size>= ngt.maxlevel()) { //need to make a copy ng2=ng; ng2.size=ngt.maxlevel(); //cerr << "check if " << ng2 << " is contained: "; hits+=(ngt.get(ng2)?1:0); } if (ng.size==ngsz) { if (!(++c % 1000000)) cerr << "."; //cerr << ng << " -> " << is_included << "\n"; //you reached the last word before freq inpstream >> ng.freq; //consistency check of n-gram if (((hits/maxhits)>=filter_hit_rate) && (!ng.containsWord(ngt.dict->OOV(),ng.size)) ) outstream << ng << "\n"; hits=0; ng.size=0; } } outstream.flush(); inpstream.flush(); } exit_error(IRSTLM_NO_ERROR); } //ngramtable* ngt=new ngramtable(inp,ngsz,NULL,dic,dstco,hmask,inplen,table_type); ngramtable* ngt=new ngramtable(inp,ngsz,NULL,NULL,filterdict,inputgoogleformat,dstco,hmask,inplen,table_type); if (aug) { ngt->dict->incflag(1); // ngramtable ngt2(aug,ngsz,isym,NULL,0,NULL,0,table_type); ngramtable ngt2(aug,ngsz,NULL,NULL,NULL,0,0,NULL,0,table_type); ngt->augment(&ngt2); ngt->dict->incflag(0); } if (subdic) { ngramtable *ngt2=new ngramtable(NULL,ngsz,NULL,NULL,NULL,0,0,NULL,0,table_type); // enforce the subdict to follow the same word order of the main dictionary dictionary tmpdict(subdic); ngt2->dict->incflag(1); for (int j=0; j<ngt->dict->size(); j++) { if (tmpdict.encode(ngt->dict->decode(j)) != tmpdict.oovcode()) { ngt2->dict->encode(ngt->dict->decode(j)); } } ngt2->dict->incflag(0); ngt2->dict->cleanfreq(); //possibly include standard symbols if (ngt->dict->encode(ngt->dict->EoS())!=ngt->dict->oovcode()) { ngt2->dict->incflag(1); ngt2->dict->encode(ngt2->dict->EoS()); ngt2->dict->incflag(0); } if (ngt->dict->encode(ngt->dict->BoS())!=ngt->dict->oovcode()) { ngt2->dict->incflag(1); ngt2->dict->encode(ngt2->dict->BoS()); ngt2->dict->incflag(0); } ngram ng(ngt->dict); ngram ng2(ngt2->dict); ngt->scan(ng,INIT,ngsz); long c=0; while (ngt->scan(ng,CONT,ngsz)) { ng2.trans(ng); ngt2->put(ng2); if (!(++c % 1000000)) cerr << "."; } //makes ngt2 aware of oov code int oov=ngt2->dict->getcode(ngt2->dict->OOV()); if(oov>=0) ngt2->dict->oovcode(oov); for (int j=0; j<ngt->dict->size(); j++) { ngt2->dict->incfreq(ngt2->dict->encode(ngt->dict->decode(j)), ngt->dict->freq(j)); } cerr <<" oov: " << ngt2->dict->freq(ngt2->dict->oovcode()) << "\n"; delete ngt; ngt=ngt2; } if (ngsz < ngt->maxlevel() && hmask) { cerr << "start projection of ngramtable " << inp << " according to hmask\n"; int selmask[MAX_NGRAM]; memset(selmask, 0, sizeof(int)*MAX_NGRAM); //parse hmask selmask[0]=1; int i=1; for (size_t c=0; c<strlen(hmask); c++) { cerr << hmask[c] << "\n"; if (hmask[c] == '1'){ selmask[i]=c+2; i++; } } if (i!= ngsz) { std::stringstream ss_msg; ss_msg << "wrong mask: 1 bits=" << i << " maxlev=" << ngsz; exit_error(IRSTLM_ERROR_DATA, ss_msg.str()); } if (selmask[ngsz-1] > ngt->maxlevel()) { std::stringstream ss_msg; ss_msg << "wrong mask: farest bits=" << selmask[ngsz-1] << " maxlev=" << ngt->maxlevel() << "\n"; exit_error(IRSTLM_ERROR_DATA, ss_msg.str()); } //ngramtable* ngt2=new ngramtable(NULL,ngsz,NULL,NULL,0,NULL,0,table_type); ngramtable* ngt2=new ngramtable(NULL,ngsz,NULL,NULL,NULL,0,0,NULL,0,table_type); ngt2->dict->incflag(1); ngram ng(ngt->dict); ngram png(ngt->dict,ngsz); ngram ng2(ngt2->dict,ngsz); ngt->scan(ng,INIT,ngt->maxlevel()); long c=0; while (ngt->scan(ng,CONT,ngt->maxlevel())) { //projection for (int j=0; j<ngsz; j++) *png.wordp(j+1)=*ng.wordp(selmask[j]); png.freq=ng.freq; //transfer ng2.trans(png); ngt2->put(ng2); if (!(++c % 1000000)) cerr << "."; } char info[100]; sprintf(info,"hm%s",hmask); ngt2->ngtype(info); //makes ngt2 aware of oov code int oov=ngt2->dict->getcode(ngt2->dict->OOV()); if(oov>=0) ngt2->dict->oovcode(oov); for (int j=0; j<ngt->dict->size(); j++) { ngt2->dict->incfreq(ngt2->dict->encode(ngt->dict->decode(j)), ngt->dict->freq(j)); } cerr <<" oov: " << ngt2->dict->freq(ngt2->dict->oovcode()) << "\n"; delete ngt; ngt=ngt2; } if (tlm && table_type==LEAFPROB) { ngram ng(ngt->dict); cout.setf(ios::scientific); cout << "> "; while(cin >> ng) { ngt->bo_state(0); if (ng.size>=ngsz) { cout << ng << " p= " << log(ngt->prob(ng)); cout << " bo= " << ngt->bo_state() << "\n"; } else cout << ng << " p= NULL\n"; cout << "> "; } } if (ftlm && table_type==LEAFPROB) { ngram ng(ngt->dict); cout.setf(ios::fixed); cout.precision(2); mfstream inptxt(ftlm,ios::in); int Nbo=0,Nw=0,Noov=0; float logPr=0,PP=0,PPwp=0; int bos=ng.dict->encode(ng.dict->BoS()); while(inptxt >> ng) { // reset ngram at begin of sentence if (*ng.wordp(1)==bos) { ng.size=1; continue; } ngt->bo_state(0); if (ng.size>=1) { logPr+=log(ngt->prob(ng)); if (*ng.wordp(1) == ngt->dict->oovcode()) Noov++; Nw++; if (ngt->bo_state()) Nbo++; } } PP=exp(-logPr/Nw); PPwp= PP * exp(Noov * log(10000000.0-ngt->dict->size())/Nw); cout << "%%% NGT TEST OF SMT LM\n"; cout << "%% LM=" << inp << " SIZE="<< ngt->maxlevel(); cout << " TestFile="<< ftlm << "\n"; cout << "%% OOV PENALTY = 1/" << 10000000.0-ngt->dict->size() << "\n"; cout << "%% Nw=" << Nw << " PP=" << PP << " PPwp=" << PPwp << " Nbo=" << Nbo << " Noov=" << Noov << " OOV=" << (float)Noov/Nw * 100.0 << "%\n"; } if (memuse) ngt->stat(0); if (iknfile) { //compute and save statistics of Improved Kneser Ney smoothing ngram ng(ngt->dict); int n1,n2,n3,n4; int unover3=0; mfstream iknstat(iknfile,ios::out); //output of ikn statistics for (int l=1; l<=ngt->maxlevel(); l++) { cerr << "level " << l << "\n"; iknstat << "level: " << l << " "; cerr << "computing statistics\n"; n1=0; n2=0; n3=0,n4=0; ngt->scan(ng,INIT,l); while(ngt->scan(ng,CONT,l)) { //skip ngrams containing _OOV if (l>1 && ng.containsWord(ngt->dict->OOV(),l)) { //cerr << "skp ngram" << ng << "\n"; continue; } //skip n-grams containing </s> in context if (l>1 && ng.containsWord(ngt->dict->EoS(),l-1)) { //cerr << "skp ngram" << ng << "\n"; continue; } //skip 1-grams containing <s> if (l==1 && ng.containsWord(ngt->dict->BoS(),l)) { //cerr << "skp ngram" << ng << "\n"; continue; } if (ng.freq==1) n1++; else if (ng.freq==2) n2++; else if (ng.freq==3) n3++; else if (ng.freq==4) n4++; if (l==1 && ng.freq >=3) unover3++; } cerr << " n1: " << n1 << " n2: " << n2 << " n3: " << n3 << " n4: " << n4 << "\n"; iknstat << " n1: " << n1 << " n2: " << n2 << " n3: " << n3 << " n4: " << n4 << " unover3: " << unover3 << "\n"; } } if (out) bin?ngt->savebin(out,ngsz): ngt->savetxt(out,ngsz,outputgoogleformat); }
31.961771
158
0.568398
scscscscscsc
67929a6fac94dc82d84a35be1d35711827556229
583
hpp
C++
cmdstan/stan/lib/stan_math/stan/math/fwd/scal/fun/trunc.hpp
yizhang-cae/torsten
dc82080ca032325040844cbabe81c9a2b5e046f9
[ "BSD-3-Clause" ]
null
null
null
cmdstan/stan/lib/stan_math/stan/math/fwd/scal/fun/trunc.hpp
yizhang-cae/torsten
dc82080ca032325040844cbabe81c9a2b5e046f9
[ "BSD-3-Clause" ]
null
null
null
cmdstan/stan/lib/stan_math/stan/math/fwd/scal/fun/trunc.hpp
yizhang-cae/torsten
dc82080ca032325040844cbabe81c9a2b5e046f9
[ "BSD-3-Clause" ]
null
null
null
#ifndef STAN_MATH_FWD_SCAL_FUN_TRUNC_HPP #define STAN_MATH_FWD_SCAL_FUN_TRUNC_HPP #include <stan/math/fwd/core.hpp> #include <stan/math/prim/scal/fun/trunc.hpp> namespace stan { namespace math { /** * Return the nearest integral value that is not larger in * magnitude than the specified argument. * * @tparam T Scalar type of autodiff variable. * @param[in] x Argument. * @return The truncated argument. */ template <typename T> inline fvar<T> trunc(const fvar<T>& x) { return fvar<T>(trunc(x.val_), 0); } } } #endif
22.423077
62
0.665523
yizhang-cae
6793a3651e37ce20a965b39f9266372777880584
248
cc
C++
squid/squid3-3.3.8.spaceify/src/auth/CredentialState.cc
spaceify/spaceify
4296d6c93cad32bb735cefc9b8157570f18ffee4
[ "MIT" ]
4
2015-01-20T15:25:34.000Z
2017-12-20T06:47:42.000Z
squid/squid3-3.3.8.spaceify/src/auth/CredentialState.cc
spaceify/spaceify
4296d6c93cad32bb735cefc9b8157570f18ffee4
[ "MIT" ]
4
2015-05-15T09:32:55.000Z
2016-02-18T13:43:31.000Z
squid/squid3-3.3.8.spaceify/src/auth/CredentialState.cc
spaceify/spaceify
4296d6c93cad32bb735cefc9b8157570f18ffee4
[ "MIT" ]
null
null
null
/* * Auto-Generated File. Changes will be destroyed. */ #include "squid.h" #include "auth/CredentialState.h" namespace Auth { const char *CredentialState_str[] = { "Unchecked", "Ok", "Pending", "Handshake", "Failed" }; }; // namespace Auth
14.588235
50
0.669355
spaceify
6793e0664bb299b08132a2c4a966e06cced0aeaa
7,713
cpp
C++
newton-4.00/sdk/dCollision/ndShapeStaticMesh.cpp
MADEAPPS/newton-dynamics
e346eec9d19ffb1c995b09417400167d3c52a635
[ "Zlib" ]
1,031
2015-01-02T14:08:47.000Z
2022-03-29T02:25:27.000Z
newton-4.00/sdk/dCollision/ndShapeStaticMesh.cpp
MADEAPPS/newton-dynamics
e346eec9d19ffb1c995b09417400167d3c52a635
[ "Zlib" ]
240
2015-01-11T04:27:19.000Z
2022-03-30T00:35:57.000Z
newton-4.00/sdk/dCollision/ndShapeStaticMesh.cpp
MADEAPPS/newton-dynamics
e346eec9d19ffb1c995b09417400167d3c52a635
[ "Zlib" ]
224
2015-01-05T06:13:54.000Z
2022-02-25T14:39:51.000Z
/* Copyright (c) <2003-2021> <Julio Jerez, Newton Game Dynamics> * * 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. */ #include "dCoreStdafx.h" #include "ndCollisionStdafx.h" #include "ndShapeInstance.h" #include "ndContactSolver.h" #include "ndCollisionStdafx.h" #include "ndShapeStaticMesh.h" D_CLASS_REFLECTION_IMPLEMENT_LOADER(ndShapeStaticMesh) void ndPolygonMeshDesc::SortFaceArray() { dInt32 stride = 8; if (m_faceCount >= 8) { dInt32 stack[D_MAX_COLLIDING_FACES][2]; stack[0][0] = 0; stack[0][1] = m_faceCount - 1; dInt32 stackIndex = 1; while (stackIndex) { stackIndex--; dInt32 lo = stack[stackIndex][0]; dInt32 hi = stack[stackIndex][1]; if ((hi - lo) > stride) { dInt32 i = lo; dInt32 j = hi; dFloat32 dist = m_hitDistance[(lo + hi) >> 1]; do { while (m_hitDistance[i] < dist) i++; while (m_hitDistance[j] > dist) j--; if (i <= j) { dSwap(m_hitDistance[i], m_hitDistance[j]); dSwap(m_faceIndexStart[i], m_faceIndexStart[j]); dSwap(m_faceIndexCount[i], m_faceIndexCount[j]); i++; j--; } } while (i <= j); if (i < hi) { stack[stackIndex][0] = i; stack[stackIndex][1] = hi; stackIndex++; } if (lo < j) { stack[stackIndex][0] = lo; stack[stackIndex][1] = j; stackIndex++; } dAssert(stackIndex < dInt32(sizeof(stack) / (2 * sizeof(stack[0][0])))); } } } stride = stride * 2; if (m_faceCount < stride) { stride = m_faceCount; } for (dInt32 i = 1; i < stride; i++) { if (m_hitDistance[i] < m_hitDistance[0]) { dSwap(m_hitDistance[i], m_hitDistance[0]); dSwap(m_faceIndexStart[i], m_faceIndexStart[0]); dSwap(m_faceIndexCount[i], m_faceIndexCount[0]); } } for (dInt32 i = 1; i < m_faceCount; i++) { dInt32 j = i; dInt32 ptr = m_faceIndexStart[i]; dInt32 count = m_faceIndexCount[i]; dFloat32 dist = m_hitDistance[i]; for (; dist < m_hitDistance[j - 1]; j--) { dAssert(j > 0); m_hitDistance[j] = m_hitDistance[j - 1]; m_faceIndexStart[j] = m_faceIndexStart[j - 1]; m_faceIndexCount[j] = m_faceIndexCount[j - 1]; } m_hitDistance[j] = dist; m_faceIndexStart[j] = ptr; m_faceIndexCount[j] = count; } #ifdef _DEBUG for (dInt32 i = 0; i < m_faceCount - 1; i++) { dAssert(m_hitDistance[i] <= m_hitDistance[i + 1]); } #endif } ndPolygonMeshDesc::ndPolygonMeshDesc(ndContactSolver& proxy, bool ccdMode) :dFastAabb() ,m_boxDistanceTravelInMeshSpace(dVector::m_zero) ,m_faceCount(0) ,m_vertexStrideInBytes(0) ,m_skinThickness(proxy.m_skinThickness) ,m_convexInstance(&proxy.m_instance0) ,m_polySoupInstance(&proxy.m_instance1) ,m_vertex(nullptr) ,m_faceIndexCount(nullptr) ,m_faceVertexIndex(nullptr) ,m_faceIndexStart(nullptr) ,m_hitDistance(nullptr) ,m_maxT(dFloat32 (1.0f)) ,m_doContinuesCollisionTest(ccdMode) { const dMatrix& hullMatrix = m_convexInstance->GetGlobalMatrix(); const dMatrix& soupMatrix = m_polySoupInstance->GetGlobalMatrix(); dMatrix& matrix = *this; matrix = hullMatrix * soupMatrix.Inverse(); dMatrix convexMatrix (dGetIdentityMatrix()); switch (m_polySoupInstance->GetScaleType()) { case ndShapeInstance::m_unit: { break; } case ndShapeInstance::m_uniform: { const dVector& invScale = m_polySoupInstance->GetInvScale(); convexMatrix[0][0] = invScale.GetScalar(); convexMatrix[1][1] = invScale.GetScalar(); convexMatrix[2][2] = invScale.GetScalar(); matrix.m_posit = matrix.m_posit * (invScale | dVector::m_wOne); break; } case ndShapeInstance::m_nonUniform: { const dVector& invScale = m_polySoupInstance->GetInvScale(); dMatrix tmp (matrix[0] * invScale, matrix[1] * invScale, matrix[2] * invScale, dVector::m_wOne); convexMatrix = tmp * matrix.Inverse(); convexMatrix.m_posit = dVector::m_wOne; matrix.m_posit = matrix.m_posit * (invScale | dVector::m_wOne); break; } case ndShapeInstance::m_global: default: { dAssert (0); } } dMatrix fullMatrix (convexMatrix * matrix); m_convexInstance->CalculateAabb(fullMatrix, m_p0, m_p1); dVector p0; dVector p1; SetTransposeAbsMatrix(matrix); m_convexInstance->CalculateAabb(convexMatrix, p0, p1); m_size = dVector::m_half * (p1 - p0); m_posit = matrix.TransformVector(dVector::m_half * (p1 + p0)); dAssert (m_posit.m_w == dFloat32 (1.0f)); } ndShapeStaticMesh::ndShapeStaticMesh(ndShapeID id) :ndShape(id) { } ndShapeStaticMesh::ndShapeStaticMesh(const dLoadSaveBase::dLoadDescriptor&) :ndShape(m_staticMesh) { } ndShapeStaticMesh::~ndShapeStaticMesh() { } void ndShapeStaticMesh::CalculateAabb(const dMatrix& matrix, dVector &p0, dVector &p1) const { dVector origin(matrix.TransformVector(m_boxOrigin)); dVector size(matrix.m_front.Abs().Scale(m_boxSize.m_x) + matrix.m_up.Abs().Scale(m_boxSize.m_y) + matrix.m_right.Abs().Scale(m_boxSize.m_z)); p0 = (origin - size) & dVector::m_triplexMask; p1 = (origin + size) & dVector::m_triplexMask; } //dInt32 ndShapeStaticMesh::CalculatePlaneIntersection(const dFloat32* const vertex, const dInt32* const index, dInt32 indexCount, dInt32 stride, const dPlane& localPlane, dVector* const contactsOut) const dInt32 ndShapeStaticMesh::CalculatePlaneIntersection(const dFloat32* const, const dInt32* const, dInt32, dInt32, const dPlane&, dVector* const) const { dAssert(0); return 0; //dInt32 count = 0; //dInt32 j = index[indexCount - 1] * stride; //dVector p0(&vertex[j]); //p0 = p0 & dVector::m_triplexMask; //dFloat32 side0 = localPlane.Evalue(p0); //for (dInt32 i = 0; i < indexCount; i++) { // j = index[i] * stride; // dVector p1(&vertex[j]); // p1 = p1 & dVector::m_triplexMask; // dFloat32 side1 = localPlane.Evalue(p1); // // if (side0 < dFloat32(0.0f)) { // if (side1 >= dFloat32(0.0f)) { // dVector dp(p1 - p0); // dAssert(dp.m_w == dFloat32(0.0f)); // dFloat32 t = localPlane.DotProduct(dp).GetScalar(); // dAssert(dgAbs(t) >= dFloat32(0.0f)); // if (dgAbs(t) < dFloat32(1.0e-8f)) { // t = dgSign(t) * dFloat32(1.0e-8f); // } // dAssert(0); // contactsOut[count] = p0 - dp.Scale(side0 / t); // count++; // // } // } // else if (side1 <= dFloat32(0.0f)) { // dVector dp(p1 - p0); // dAssert(dp.m_w == dFloat32(0.0f)); // dFloat32 t = localPlane.DotProduct(dp).GetScalar(); // dAssert(dgAbs(t) >= dFloat32(0.0f)); // if (dgAbs(t) < dFloat32(1.0e-8f)) { // t = dgSign(t) * dFloat32(1.0e-8f); // } // dAssert(0); // contactsOut[count] = p0 - dp.Scale(side0 / t); // count++; // } // // side0 = side1; // p0 = p1; //} // //return count; } void ndShapeStaticMesh::Save(const dLoadSaveBase::dSaveDescriptor& desc) const { nd::TiXmlElement* const childNode = new nd::TiXmlElement(ClassName()); desc.m_rootNode->LinkEndChild(childNode); childNode->SetAttribute("hashId", desc.m_nodeNodeHash); ndShape::Save(dLoadSaveBase::dSaveDescriptor(desc, childNode)); }
28.252747
205
0.678465
MADEAPPS
679416add763d00f118a12d5e0526bd2e9703df7
836
hpp
C++
Addons/CommandCentre/ModuleVehicleCam.hpp
DPSO/LRG-Fundamentals
bf60b956d13346c46beacc24e940b1487cc480b6
[ "MIT" ]
5
2019-03-05T17:14:42.000Z
2021-03-09T00:43:10.000Z
Addons/CommandCentre/ModuleVehicleCam.hpp
DPSO/LRG-Fundamentals
bf60b956d13346c46beacc24e940b1487cc480b6
[ "MIT" ]
19
2019-01-17T15:17:01.000Z
2019-01-31T22:10:49.000Z
Addons/CommandCentre/ModuleVehicleCam.hpp
DPSO/LRG-Fundamentals
bf60b956d13346c46beacc24e940b1487cc480b6
[ "MIT" ]
9
2019-02-19T21:17:19.000Z
2021-03-29T08:37:16.000Z
class LRG_ModuleVehicleCam: Module_F { scope = 2; displayName = "Add Vehicle Camera"; icon = "\z\LRG Fundamentals\addons\media\images\icons\Camera.paa"; category = "LRG_CommandCentre"; function = "LR_fnc_moduleVehicleCam"; functionPriority = 4; isGlobal = 0; isTriggerActivated = 0; isDisposable = 0; is3DEN = 0; class Attributes: AttributesBase { class ModuleDescription: ModuleDescription{}; }; class ModuleDescription: ModuleDescription { description[] = { "Synched vehicle can be viewed from the Command Center screens.", "You can sync as many vehicles to this module as you like." }; position = 0; // Position is taken into effect direction = 0; // Direction is taken into effect optional = 0; // Synced entity is optional duplicate = 1; // Multiple entities of this type can be synced }; };
29.857143
68
0.7189
DPSO
67964c684702e19f401c86f6eec7e47d0de2a327
469
cpp
C++
test/tga/test.cpp
shizgnit/asuka
5390bea8a376f5900714d28bf5cc5ecb0b17a5dd
[ "BSD-3-Clause" ]
null
null
null
test/tga/test.cpp
shizgnit/asuka
5390bea8a376f5900714d28bf5cc5ecb0b17a5dd
[ "BSD-3-Clause" ]
null
null
null
test/tga/test.cpp
shizgnit/asuka
5390bea8a376f5900714d28bf5cc5ecb0b17a5dd
[ "BSD-3-Clause" ]
null
null
null
#include "asuka.hpp" int main(void) { cout<<"starting up"<<endl; AT::Resource::Manager t; t.accept("/usr/lib/asuka/resource"); for(int i=0; i<10; i++) { AT::Field image = t.input("a24bit.tga"); cout<<"=["<<i<<"]============================"<<endl; cout<<"width: "<<image["header"]["width"]<<endl; cout<<"height: "<<image["header"]["height"]<<endl; cout<<"bpp: "<<image["header"]["bpp"]<<endl; t.release(image); } exit(0); }
23.45
58
0.509595
shizgnit
67a4d8676287f3c315828cb7820aa0f6a0c32cf1
13,406
cpp
C++
print/XPSDrvSmpl/src/filters/booklet/bkflt.cpp
ixjf/Windows-driver-samples
38985ba91feb685095754775e101389ad90c2aa6
[ "MS-PL" ]
3,084
2015-03-18T04:40:32.000Z
2019-05-06T17:14:33.000Z
print/XPSDrvSmpl/src/filters/booklet/bkflt.cpp
ixjf/Windows-driver-samples
38985ba91feb685095754775e101389ad90c2aa6
[ "MS-PL" ]
275
2015-03-19T18:44:41.000Z
2019-05-06T14:13:26.000Z
print/XPSDrvSmpl/src/filters/booklet/bkflt.cpp
ixjf/Windows-driver-samples
38985ba91feb685095754775e101389ad90c2aa6
[ "MS-PL" ]
3,091
2015-03-19T00:08:54.000Z
2019-05-06T16:42:01.000Z
/*++ Copyright (c) 2005 Microsoft Corporation All rights reserved. THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. File Name: bkflt.cpp Abstract: Booklet filter implementation. This class derives from the Xps filter class and implements the necessary part handlers to support booklet printing. The booklet filter is responsible for re-ordering pages and re-uses the NUp filter to provide 2-up and offset support. --*/ #include "precomp.h" #include "debug.h" #include "globals.h" #include "xdstring.h" #include "xdexcept.h" #include "pthndlr.h" #include "bkflt.h" #include "bksax.h" #include "bkpthndlr.h" using XDPrintSchema::Binding::BindingData; /*++ Routine Name: CBookletFilter::CBookletFilter Routine Description: Default constructor for the booklet filter which initialises the filter to sensible default values Arguments: None Return Value: None --*/ CBookletFilter::CBookletFilter() : m_bSendAllDocs(TRUE), m_bookScope(CBkPTProperties::None) { } /*++ Routine Name: CBookletFilter::~CBookletFilter Routine Description: Default destructor for the booklet filter Arguments: None Return Value: None --*/ CBookletFilter::~CBookletFilter() { } /*++ Routine Name: CNUpFilter::ProcessPart Routine Description: Method for processing each fixed document sequence part in a container Arguments: pFDS - Pointer to the fixed document sequence to process Return Value: HRESULT S_OK - On success E_* - On error --*/ HRESULT CBookletFilter::ProcessPart( _Inout_ IFixedDocumentSequence* pFDS ) { VERBOSE("Processing Fixed Document Sequence part with booklet filter handler\n"); HRESULT hr = S_OK; if (SUCCEEDED(hr = CHECK_POINTER(pFDS, E_POINTER))) { // // Get the PT manager to return the FixedDocumentSequence ticket. // IXMLDOMDocument2* pPT = NULL; if (SUCCEEDED(hr = m_ptManager.SetTicket(pFDS)) && SUCCEEDED(hr = m_ptManager.GetTicket(kPTJobScope, &pPT))) { // // Set the binding scope from the PrintTicket // hr = SetBindingScope(pPT); } } if (SUCCEEDED(hr)) { hr = m_pXDWriter->SendFixedDocumentSequence(pFDS); } ERR_ON_HR(hr); return hr; } /*++ Routine Name: CBookletFilter::ProcessPart Routine Description: Method for processing each fixed document part in a container Arguments: pFD - Pointer to the fixed document to process Return Value: HRESULT S_OK - On success S_FALSE - When not enabled in the PT E_* - On error --*/ HRESULT CBookletFilter::ProcessPart( _Inout_ IFixedDocument* pFD ) { VERBOSE("Processing Fixed Document part with booklet filter handler\n"); HRESULT hr = S_OK; if (SUCCEEDED(hr = CHECK_POINTER(pFD, E_POINTER)) && SUCCEEDED(hr = m_ptManager.SetTicket(pFD))) { // // If we are in a JobBook session we want to maintain the current // JobBook settings // if (m_bookScope != CBkPTProperties::Job) { // // Flush any outstanding pages in case we have just completed a // DocNUp sequence // hr = FlushCache(); // // Get the PT manager to return the FixedDocument ticket. // IXMLDOMDocument2* pPT = NULL; if (SUCCEEDED(hr) && SUCCEEDED(hr = m_ptManager.GetTicket(kPTDocumentScope, &pPT))) { // // Set the binding scope from the PrintTicket // hr = SetBindingScope(pPT); } } } if (SUCCEEDED(hr) && m_bSendAllDocs) { hr = m_pXDWriter->SendFixedDocument(pFD); // // If we are JobBindAllDocuments we only ever send one doc - now we have // sent the first document we can test to see if we need to send all of them // if (m_bookScope == CBkPTProperties::Job) { m_bSendAllDocs = FALSE; } } ERR_ON_HR(hr); return hr; } /*++ Routine Name: CBookletFilter::ProcessPart Routine Description: Method for processing each fixed page part in a container Arguments: pFP - Pointer to the fixed page to process Return Value: HRESULT S_OK - On success E_* - On error --*/ HRESULT CBookletFilter::ProcessPart( _Inout_ IFixedPage* pFP ) { ASSERTMSG(m_pXDWriter != NULL, "XD writer is not initialised.\n"); VERBOSE("Processing Fixed Page with booklet filter handler\n"); HRESULT hr = S_OK; if (SUCCEEDED(hr = CHECK_POINTER(pFP, E_POINTER)) && SUCCEEDED(hr = CHECK_POINTER(m_pXDWriter, E_PENDING))) { // // Check if we are processing a booklet job // if (m_bookScope != CBkPTProperties::None) { // // Cache pages for reordering // try { m_cacheFP.push_back(pFP); } catch (exception& DBG_ONLY(e)) { ERR(e.what()); hr = E_FAIL; } } else { hr = m_pXDWriter->SendFixedPage(pFP); } } ERR_ON_HR(hr); return hr; } /*++ Routine Name: CBookletFilter::Finalize Routine Description: Method to flush the cache of pages as the last action of the filter Arguments: None Return Value: HRESULT S_OK - On success E_* - On error --*/ HRESULT CBookletFilter::Finalize( VOID ) { // // Just flush the cache of pages // return FlushCache(); } /*++ Routine Name: CBookletFilter::FlushCache Routine Description: Method to send the cached collection of pages in the correct order back Arguments: None Return Value: HRESULT S_OK - On success E_* - On error --*/ HRESULT CBookletFilter::FlushCache( VOID ) { HRESULT hr = S_OK; if (m_pXDWriter == NULL) { hr = E_PENDING; } size_t cPages = m_cacheFP.size(); if (SUCCEEDED(hr) && cPages > 0 && m_bookScope != CBkPTProperties::None) { // // We may need to add a pad page if the page count is odd // CComPtr<IFixedPage> pNewFP(NULL); if (cPages%2 == 1 && SUCCEEDED(hr = CreatePadPage(&pNewFP))) { // // We successfully created our pad page; add it to the cache // try { m_cacheFP.push_back(pNewFP); } catch (exception& DBG_ONLY(e)) { ERR(e.what()); hr = E_FAIL; } cPages++; } if (SUCCEEDED(hr)) { try { // // Re-order pages in the cache // map<size_t, IFixedPage*> reorderedPages; size_t newIndex = 0; size_t pageIndex = 0; for (pageIndex = 0; pageIndex < cPages/2; pageIndex++) { reorderedPages[newIndex] = m_cacheFP[pageIndex]; newIndex += 2; } newIndex = cPages - 1; for (pageIndex = cPages/2; pageIndex < cPages; pageIndex++) { reorderedPages[newIndex] = m_cacheFP[pageIndex]; newIndex -= 2; } // // Write out reordered pages // for (pageIndex = 0; pageIndex < cPages && SUCCEEDED(hr); pageIndex++) { hr = m_pXDWriter->SendFixedPage(reorderedPages[pageIndex]); } // // Clean out the cache // m_cacheFP.clear(); } catch (exception& DBG_ONLY(e)) { ERR(e.what()); hr = E_FAIL; } } } ERR_ON_HR(hr); return hr; } /*++ Routine Name: CBookletFilter::CreatePadPage Routine Description: Method to create a pad page which is required for odd page counts to ensure pages are correctly ordered for presentation as a booklet Arguments: ppNewPage - Pointer to a pointer to the newly created fixed page Return Value: HRESULT S_OK - On success E_* - On error --*/ HRESULT CBookletFilter::CreatePadPage( _Outptr_ IFixedPage** ppNewPage ) { HRESULT hr = S_OK; // // Validate parameters and members before proceeding // if (SUCCEEDED(hr = CHECK_POINTER(ppNewPage, E_POINTER)) && SUCCEEDED(hr = CHECK_POINTER(m_pXDWriter, E_PENDING))) { *ppNewPage = NULL; PCWSTR pszPageName = NULL; try { // // Create a unique name for the pad page for this print session // CStringXDW szNewPageName; szNewPageName.Format(L"/Pad_page_%u.xaml", GetUniqueNumber()); pszPageName = szNewPageName.GetBuffer(); // // Create a new empty page and retrieve a writer. Also get a // reader from the first page so we can copy the FixedPage root // element. This ensures the page sizes match. // CComPtr<IPrintWriteStream> pWriter(NULL); CComPtr<ISAXXMLReader> pSaxRdr(NULL); if (SUCCEEDED(hr) && SUCCEEDED(hr = m_pXDWriter->GetNewEmptyPart(pszPageName, IID_IFixedPage, reinterpret_cast<PVOID*>(ppNewPage), &pWriter)) && SUCCEEDED(hr = pSaxRdr.CoCreateInstance(CLSID_SAXXMLReader60))) { // // We use a simple SAX handler which copies only the root // element and discards all other content. // CBkSaxHandler bkSaxHndlr(pWriter); CComPtr<IPrintReadStream> pReader(NULL); IFixedPage* pFP = NULL; pFP = m_cacheFP[0]; if (SUCCEEDED(hr) && SUCCEEDED(hr = pSaxRdr->putContentHandler(&bkSaxHndlr)) && SUCCEEDED(hr = pFP->GetStream(&pReader))) { CComPtr<ISequentialStream> pReadStreamToSeq(NULL); pReadStreamToSeq.Attach(new(std::nothrow) pfp::PrintReadStreamToSeqStream(pReader)); if (SUCCEEDED(hr = CHECK_POINTER(pReadStreamToSeq, E_OUTOFMEMORY))) { hr = pSaxRdr->parse(CComVariant(static_cast<ISequentialStream*>(pReadStreamToSeq))); } } pWriter->Close(); } } catch (CXDException& e) { hr = e; } } ERR_ON_HR(hr); return hr; } /*++ Routine Name: CBookletFilter::SetBindingScope Routine Description: Method to retrieve the binding scope from a PrintTicket Arguments: pPT - Pointer to the PrintTicket to retrieve the scope from Return Value: HRESULT S_OK - On success S_FALSE - Booklet settings not present in the PT E_* - On error --*/ HRESULT CBookletFilter::SetBindingScope( _In_ IXMLDOMDocument2* pPT ) { HRESULT hr = S_OK; if (SUCCEEDED(hr = CHECK_POINTER(pPT, E_POINTER))) { try { BindingData bindingData; CBookPTHandler bkPTHandler(pPT); // // Retrieve the booklet properties from the ticket via the handler // if (SUCCEEDED(hr) && SUCCEEDED(hr = bkPTHandler.GetData(&bindingData))) { CBkPTProperties bookletPTProps(bindingData); // // Retrieve the booklet scope // hr = bookletPTProps.GetScope(&m_bookScope); } else if (hr == E_ELEMENT_NOT_FOUND) { // // Booklet PT settings are not present - reset hr to S_FALSE and proceed // hr = S_FALSE; } } catch (CXDException& e) { hr = e; } } return hr; }
22.64527
109
0.518425
ixjf
67a4fa120a52db19fe68dd92cc03e67e9f09811b
9,495
cc
C++
src/ArtificialViscosity/TensorCRKSPHViscosity.cc
jmikeowen/Spheral
3e1082a7aefd6b328bd3ae24ca1a477108cfc3c4
[ "BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP" ]
22
2018-07-31T21:38:22.000Z
2020-06-29T08:58:33.000Z
src/ArtificialViscosity/TensorCRKSPHViscosity.cc
jmikeowen/Spheral
3e1082a7aefd6b328bd3ae24ca1a477108cfc3c4
[ "BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP" ]
41
2020-09-28T23:14:27.000Z
2022-03-28T17:01:33.000Z
src/ArtificialViscosity/TensorCRKSPHViscosity.cc
jmikeowen/Spheral
3e1082a7aefd6b328bd3ae24ca1a477108cfc3c4
[ "BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP" ]
7
2019-12-01T07:00:06.000Z
2020-09-15T21:12:39.000Z
//---------------------------------Spheral++----------------------------------// // ArtificialViscosity -- The base class for all ArtificialViscosities in // Spheral++. //----------------------------------------------------------------------------// #include "FileIO/FileIO.hh" #include "Hydro/HydroFieldNames.hh" #include "Boundary/Boundary.hh" #include "Kernel/TableKernel.hh" #include "NodeList/FluidNodeList.hh" #include "DataBase/State.hh" #include "DataBase/StateDerivatives.hh" #include "Neighbor/ConnectivityMap.hh" #include "Utilities/rotationMatrix.hh" #include "Utilities/GeometricUtilities.hh" #include "RK/RKFieldNames.hh" #include "RK/gradientRK.hh" #include "TensorCRKSPHViscosity.hh" #include <algorithm> using std::vector; using std::string; using std::pair; using std::make_pair; using std::cout; using std::cerr; using std::endl; using std::min; using std::max; using std::abs; namespace Spheral { //------------------------------------------------------------------------------ // Construct with the given value for the linear and quadratic coefficients. //------------------------------------------------------------------------------ template<typename Dimension> TensorCRKSPHViscosity<Dimension>:: TensorCRKSPHViscosity(Scalar Clinear, Scalar Cquadratic): TensorMonaghanGingoldViscosity<Dimension>(Clinear, Cquadratic), mGradVel(FieldStorageType::CopyFields){ } //------------------------------------------------------------------------------ // Destructor. //------------------------------------------------------------------------------ template<typename Dimension> TensorCRKSPHViscosity<Dimension>:: ~TensorCRKSPHViscosity() { } //------------------------------------------------------------------------------ // Method to apply the viscous acceleration, work, and pressure, to the derivatives // all in one step (efficiency and all). //------------------------------------------------------------------------------ template<typename Dimension> pair<typename Dimension::Tensor, typename Dimension::Tensor> TensorCRKSPHViscosity<Dimension>:: Piij(const unsigned nodeListi, const unsigned i, const unsigned nodeListj, const unsigned j, const Vector& xi, const Vector& etai, const Vector& vi, const Scalar rhoi, const Scalar csi, const SymTensor& /*Hi*/, const Vector& xj, const Vector& etaj, const Vector& vj, const Scalar rhoj, const Scalar csj, const SymTensor& /*Hj*/) const { // Estimate the velocity difference. Vector vij = vi - vj; const Vector xij = xi - xj; const Tensor& DvDxi = mGradVel(nodeListi, i); const Tensor& DvDxj = mGradVel(nodeListj, j); const Vector vi1 = vi - 0.5*(DvDxi.dot(xij)); const Vector vj1 = vj + 0.5*(DvDxj.dot(xij)); const Vector vij1 = vi1 - vj1; if (((vi1 - vj).dot(vij) > 0.0) and ((vi - vj1).dot(vij) > 0.0) and (vij1.dot(vij) > 0.0)) { const Vector vijhat = vij.unitVector(); // const bool barf = (vij.magnitude() > 1.0e-5); // if (barf) cerr << "Cutting vij from " << vij << " to "; vij = min(vij.magnitude(), vij1.magnitude())*vijhat; // if (barf) cerr << vij << endl; } // If the nodes are not closing, then skip the rest and the Q is zero. if (vij.dot(xij) < 0.0) { const double tiny = 1.0e-20; double Cl = this->mClinear; double Cq = this->mCquadratic; const double eps2 = this->mEpsilon2; //const bool balsara = this->mBalsaraShearCorrection; const bool limiter = this->mLimiterSwitch; // Grab the FieldLists scaling the coefficients. // These incorporate things like the Balsara shearing switch or Morris & Monaghan time evolved // coefficients. const Scalar fCli = this->mClMultiplier(nodeListi, i); const Scalar fCqi = this->mCqMultiplier(nodeListi, i); const Scalar fClj = this->mClMultiplier(nodeListj, j); const Scalar fCqj = this->mCqMultiplier(nodeListj, j); const Scalar fshear = std::max(this->mShearCorrection(nodeListi, i), this->mShearCorrection(nodeListj, j)); Cl *= 0.5*(fCli + fClj)*fshear; Cq *= 0.5*(fCqi + fCqj)*fshear; // Some more geometry. const Scalar xij2 = xij.magnitude2(); const Vector xijUnit = xij.unitVector(); const Scalar hi2 = xij2/(etai.magnitude2() + tiny); const Scalar hj2 = xij2/(etaj.magnitude2() + tiny); const Scalar hi = sqrt(hi2); const Scalar hj = sqrt(hj2); // BOOGA! const Tensor& _sigmai = this->mSigma(nodeListi, i); const Tensor& _sigmaj = this->mSigma(nodeListj, j); Tensor sigmai = _sigmai; Tensor sigmaj = _sigmaj; { const Tensor R = rotationMatrix(xijUnit); const Tensor Rinverse = R.Transpose(); const Vector thpt1 = sqrt(xij2)*(R*vij); const Vector deltaSigmai = thpt1/(xij2 + eps2*hi2); const Vector deltaSigmaj = thpt1/(xij2 + eps2*hj2); sigmai.rotationalTransform(R); sigmaj.rotationalTransform(R); sigmai.setColumn(0, deltaSigmai); sigmaj.setColumn(0, deltaSigmaj); sigmai.rotationalTransform(Rinverse); sigmaj.rotationalTransform(Rinverse); } // BOOGA! // Calculate the tensor viscous internal energy. const Tensor mui = hi*sigmai; Tensor Qepsi = -Cl*csi*mui.Transpose() + Cq*mui*mui; if (limiter) Qepsi = this->calculateLimiter(vi, vj, csi, csj, hi, hj, nodeListi, i)*Qepsi; const Tensor muj = hj*sigmaj; Tensor Qepsj = -Cl*csj*muj.Transpose() + Cq*muj*muj; if (limiter) Qepsj = this->calculateLimiter(vj, vi, csj, csi, hj, hi, nodeListj, j)*Qepsj; // We now have enough to compute Pi! const Tensor QPii = Qepsi/rhoi; const Tensor QPij = Qepsj/rhoj; return make_pair(QPii, QPij); } else { return make_pair(Tensor::zero, Tensor::zero); } } //------------------------------------------------------------------------------ // Compute the internal background sigma and grad-div-v fields. //------------------------------------------------------------------------------ template<typename Dimension> void TensorCRKSPHViscosity<Dimension>:: calculateSigmaAndGradDivV(const DataBase<Dimension>& dataBase, const State<Dimension>& state, const StateDerivatives<Dimension>& /*derivs*/, const TableKernel<Dimension>& /*W*/, typename TensorCRKSPHViscosity<Dimension>::ConstBoundaryIterator boundaryBegin, typename TensorCRKSPHViscosity<Dimension>::ConstBoundaryIterator boundaryEnd) { const auto order = ArtificialViscosity<Dimension>::QcorrectionOrder(); auto& sigma = ArtificialViscosity<Dimension>::mSigma; auto& gradDivVelocity = ArtificialViscosity<Dimension>::mGradDivVelocity; // Get the necessary state. const auto mass = state.fields(HydroFieldNames::mass, 0.0); const auto position = state.fields(HydroFieldNames::position, Vector::zero); const auto velocity = state.fields(HydroFieldNames::velocity, Vector::zero); const auto rho = state.fields(HydroFieldNames::massDensity, 0.0); const auto H = state.fields(HydroFieldNames::H, SymTensor::zero); const auto WR = state.template getAny<ReproducingKernel<Dimension>>(RKFieldNames::reproducingKernel(order)); const auto corrections = state.fields(RKFieldNames::rkCorrections(order), RKCoefficients<Dimension>()); const auto& connectivityMap = dataBase.connectivityMap(); const auto numNodeLists = dataBase.numFluidNodeLists(); // Compute the basic velocity gradient. const auto vol = mass/rho; mGradVel = gradientRK(velocity, position, vol, H, connectivityMap, WR, corrections, NodeCoupling()); sigma = mGradVel; sigma.copyFields(); // Compute sigma and build the velocity divergence. auto divVel = dataBase.newFluidFieldList(0.0, "velocity divergence"); for (auto nodeListi = 0u; nodeListi != numNodeLists; ++nodeListi) { for (auto iItr = connectivityMap.begin(nodeListi); iItr < connectivityMap.end(nodeListi); ++iItr) { const auto i = *iItr; auto& sigmai = sigma(nodeListi, i); // Update the velocity divergence. divVel(nodeListi, i) = sigmai.Trace(); // Now limit to just negative eigen-values. This is 'cause we only // care about convergent geometries for the Q. const auto sigmai_s = sigmai.Symmetric(); const auto sigmai_a = sigmai.SkewSymmetric(); auto eigeni = sigmai_s.eigenVectors(); sigmai = constructTensorWithMinDiagonal(eigeni.eigenValues, 0.0); sigmai.rotationalTransform(eigeni.eigenVectors); // sigmai += sigmai_a; } } // Apply boundary conditions. for (auto boundItr = boundaryBegin; boundItr < boundaryEnd; ++boundItr) (*boundItr)->applyFieldListGhostBoundary(divVel); for (auto boundItr = boundaryBegin; boundItr < boundaryEnd; ++boundItr) (*boundItr)->finalizeGhostBoundary(); // Compute the gradient of div vel. gradDivVelocity = gradientRK(divVel, position, vol, H, connectivityMap, WR, corrections, NodeCoupling()); // Apply boundary conditions. for (auto boundItr = boundaryBegin; boundItr < boundaryEnd; ++boundItr) { (*boundItr)->applyFieldListGhostBoundary(sigma); (*boundItr)->applyFieldListGhostBoundary(gradDivVelocity); (*boundItr)->applyFieldListGhostBoundary(mGradVel); } // for (typename ArtificialViscosity<Dimension>::ConstBoundaryIterator boundItr = boundaryBegin; // boundItr != boundaryEnd; // ++boundItr) { // (*boundItr)->finalizeGhostBoundary(); // } } }
39.39834
123
0.635071
jmikeowen
67a57f1e230da950109c4536ffd684d3ca0ea070
13,732
cpp
C++
modules/gles2/functional/es2fTextureSizeTests.cpp
billkris-ms/VK-GL-CTS
fbd32b9e48d981580e40c6e4b54d30ddb4980867
[ "Apache-2.0" ]
1
2017-09-20T12:24:13.000Z
2017-09-20T12:24:13.000Z
modules/gles2/functional/es2fTextureSizeTests.cpp
billkris-ms/VK-GL-CTS
fbd32b9e48d981580e40c6e4b54d30ddb4980867
[ "Apache-2.0" ]
null
null
null
modules/gles2/functional/es2fTextureSizeTests.cpp
billkris-ms/VK-GL-CTS
fbd32b9e48d981580e40c6e4b54d30ddb4980867
[ "Apache-2.0" ]
null
null
null
/*------------------------------------------------------------------------- * drawElements Quality Program OpenGL ES 2.0 Module * ------------------------------------------------- * * Copyright 2014 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. * *//*! * \file * \brief Texture size tests. *//*--------------------------------------------------------------------*/ #include "es2fTextureSizeTests.hpp" #include "glsTextureTestUtil.hpp" #include "gluTexture.hpp" #include "gluStrUtil.hpp" #include "gluTextureUtil.hpp" #include "gluPixelTransfer.hpp" #include "tcuTestLog.hpp" #include "tcuTextureUtil.hpp" #include "glwEnums.hpp" #include "glwFunctions.hpp" namespace deqp { namespace gles2 { namespace Functional { using tcu::TestLog; using std::vector; using std::string; using tcu::Sampler; using namespace glu; using namespace gls::TextureTestUtil; using namespace glu::TextureTestUtil; class Texture2DSizeCase : public tcu::TestCase { public: Texture2DSizeCase (tcu::TestContext& testCtx, glu::RenderContext& renderCtx, const char* name, const char* description, deUint32 format, deUint32 dataType, int width, int height, bool mipmaps); ~Texture2DSizeCase (void); void init (void); void deinit (void); IterateResult iterate (void); private: Texture2DSizeCase (const Texture2DSizeCase& other); Texture2DSizeCase& operator= (const Texture2DSizeCase& other); glu::RenderContext& m_renderCtx; deUint32 m_format; deUint32 m_dataType; int m_width; int m_height; bool m_useMipmaps; glu::Texture2D* m_texture; TextureRenderer m_renderer; }; Texture2DSizeCase::Texture2DSizeCase (tcu::TestContext& testCtx, glu::RenderContext& renderCtx, const char* name, const char* description, deUint32 format, deUint32 dataType, int width, int height, bool mipmaps) : TestCase (testCtx, name, description) , m_renderCtx (renderCtx) , m_format (format) , m_dataType (dataType) , m_width (width) , m_height (height) , m_useMipmaps (mipmaps) , m_texture (DE_NULL) , m_renderer (renderCtx, testCtx.getLog(), glu::GLSL_VERSION_100_ES, glu::PRECISION_MEDIUMP) { } Texture2DSizeCase::~Texture2DSizeCase (void) { Texture2DSizeCase::deinit(); } void Texture2DSizeCase::init (void) { DE_ASSERT(!m_texture); m_texture = new Texture2D(m_renderCtx, m_format, m_dataType, m_width, m_height); int numLevels = m_useMipmaps ? deLog2Floor32(de::max(m_width, m_height))+1 : 1; // Fill levels. for (int levelNdx = 0; levelNdx < numLevels; levelNdx++) { m_texture->getRefTexture().allocLevel(levelNdx); tcu::fillWithComponentGradients(m_texture->getRefTexture().getLevel(levelNdx), tcu::Vec4(-1.0f, -1.0f, -1.0f, 2.0f), tcu::Vec4(1.0f, 1.0f, 1.0f, 0.0f)); } } void Texture2DSizeCase::deinit (void) { delete m_texture; m_texture = DE_NULL; m_renderer.clear(); } Texture2DSizeCase::IterateResult Texture2DSizeCase::iterate (void) { const glw::Functions& gl = m_renderCtx.getFunctions(); TestLog& log = m_testCtx.getLog(); RandomViewport viewport (m_renderCtx.getRenderTarget(), 128, 128, deStringHash(getName())); tcu::Surface renderedFrame (viewport.width, viewport.height); tcu::Surface referenceFrame (viewport.width, viewport.height); tcu::RGBA threshold = m_renderCtx.getRenderTarget().getPixelFormat().getColorThreshold() + tcu::RGBA(7,7,7,7); deUint32 wrapS = GL_CLAMP_TO_EDGE; deUint32 wrapT = GL_CLAMP_TO_EDGE; // Do not minify with GL_NEAREST. A large POT texture with a small POT render target will produce // indeterminate results. deUint32 minFilter = m_useMipmaps ? GL_NEAREST_MIPMAP_NEAREST : GL_LINEAR; deUint32 magFilter = GL_NEAREST; vector<float> texCoord; computeQuadTexCoord2D(texCoord, tcu::Vec2(0.0f, 0.0f), tcu::Vec2(1.0f, 1.0f)); // Setup base viewport. gl.viewport(viewport.x, viewport.y, viewport.width, viewport.height); // Upload texture data to GL. m_texture->upload(); // Bind to unit 0. gl.activeTexture(GL_TEXTURE0); gl.bindTexture(GL_TEXTURE_2D, m_texture->getGLTexture()); gl.texParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapS); gl.texParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapT); gl.texParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, minFilter); gl.texParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, magFilter); GLU_EXPECT_NO_ERROR(gl.getError(), "Set texturing state"); // Draw. m_renderer.renderQuad(0, &texCoord[0], TEXTURETYPE_2D); glu::readPixels(m_renderCtx, viewport.x, viewport.y, renderedFrame.getAccess()); // Compute reference. sampleTexture(tcu::SurfaceAccess(referenceFrame, m_renderCtx.getRenderTarget().getPixelFormat()), m_texture->getRefTexture(), &texCoord[0], ReferenceParams(TEXTURETYPE_2D, mapGLSampler(wrapS, wrapT, minFilter, magFilter))); // Compare and log. bool isOk = compareImages(log, referenceFrame, renderedFrame, threshold); m_testCtx.setTestResult(isOk ? QP_TEST_RESULT_PASS : QP_TEST_RESULT_FAIL, isOk ? "Pass" : "Image comparison failed"); return STOP; } class TextureCubeSizeCase : public tcu::TestCase { public: TextureCubeSizeCase (tcu::TestContext& testCtx, glu::RenderContext& renderCtx, const char* name, const char* description, deUint32 format, deUint32 dataType, int width, int height, bool mipmaps); ~TextureCubeSizeCase (void); void init (void); void deinit (void); IterateResult iterate (void); private: TextureCubeSizeCase (const TextureCubeSizeCase& other); TextureCubeSizeCase& operator= (const TextureCubeSizeCase& other); bool testFace (tcu::CubeFace face); glu::RenderContext& m_renderCtx; deUint32 m_format; deUint32 m_dataType; int m_width; int m_height; bool m_useMipmaps; glu::TextureCube* m_texture; TextureRenderer m_renderer; int m_curFace; bool m_isOk; }; TextureCubeSizeCase::TextureCubeSizeCase (tcu::TestContext& testCtx, glu::RenderContext& renderCtx, const char* name, const char* description, deUint32 format, deUint32 dataType, int width, int height, bool mipmaps) : TestCase (testCtx, name, description) , m_renderCtx (renderCtx) , m_format (format) , m_dataType (dataType) , m_width (width) , m_height (height) , m_useMipmaps (mipmaps) , m_texture (DE_NULL) , m_renderer (renderCtx, testCtx.getLog(), glu::GLSL_VERSION_100_ES, glu::PRECISION_MEDIUMP) , m_curFace (0) , m_isOk (false) { } TextureCubeSizeCase::~TextureCubeSizeCase (void) { TextureCubeSizeCase::deinit(); } void TextureCubeSizeCase::init (void) { DE_ASSERT(!m_texture); DE_ASSERT(m_width == m_height); m_texture = new TextureCube(m_renderCtx, m_format, m_dataType, m_width); static const tcu::Vec4 gradients[tcu::CUBEFACE_LAST][2] = { { tcu::Vec4(-1.0f, -1.0f, -1.0f, 2.0f), tcu::Vec4(1.0f, 1.0f, 1.0f, 0.0f) }, // negative x { tcu::Vec4( 0.0f, -1.0f, -1.0f, 2.0f), tcu::Vec4(1.0f, 1.0f, 1.0f, 0.0f) }, // positive x { tcu::Vec4(-1.0f, 0.0f, -1.0f, 2.0f), tcu::Vec4(1.0f, 1.0f, 1.0f, 0.0f) }, // negative y { tcu::Vec4(-1.0f, -1.0f, 0.0f, 2.0f), tcu::Vec4(1.0f, 1.0f, 1.0f, 0.0f) }, // positive y { tcu::Vec4(-1.0f, -1.0f, -1.0f, 0.0f), tcu::Vec4(1.0f, 1.0f, 1.0f, 1.0f) }, // negative z { tcu::Vec4( 0.0f, 0.0f, 0.0f, 2.0f), tcu::Vec4(1.0f, 1.0f, 1.0f, 0.0f) } // positive z }; int numLevels = m_useMipmaps ? deLog2Floor32(de::max(m_width, m_height))+1 : 1; // Fill levels. for (int levelNdx = 0; levelNdx < numLevels; levelNdx++) { for (int face = 0; face < tcu::CUBEFACE_LAST; face++) { m_texture->getRefTexture().allocLevel((tcu::CubeFace)face, levelNdx); fillWithComponentGradients(m_texture->getRefTexture().getLevelFace(levelNdx, (tcu::CubeFace)face), gradients[face][0], gradients[face][1]); } } // Upload texture data to GL. m_texture->upload(); // Initialize iteration state. m_curFace = 0; m_isOk = true; } void TextureCubeSizeCase::deinit (void) { delete m_texture; m_texture = DE_NULL; m_renderer.clear(); } bool TextureCubeSizeCase::testFace (tcu::CubeFace face) { const glw::Functions& gl = m_renderCtx.getFunctions(); TestLog& log = m_testCtx.getLog(); RandomViewport viewport (m_renderCtx.getRenderTarget(), 128, 128, deStringHash(getName())+(deUint32)face); tcu::Surface renderedFrame (viewport.width, viewport.height); tcu::Surface referenceFrame (viewport.width, viewport.height); tcu::RGBA threshold = m_renderCtx.getRenderTarget().getPixelFormat().getColorThreshold() + tcu::RGBA(7,7,7,7); deUint32 wrapS = GL_CLAMP_TO_EDGE; deUint32 wrapT = GL_CLAMP_TO_EDGE; // Do not minify with GL_NEAREST. A large POT texture with a small POT render target will produce // indeterminate results. deUint32 minFilter = m_useMipmaps ? GL_NEAREST_MIPMAP_NEAREST : GL_LINEAR; deUint32 magFilter = GL_NEAREST; vector<float> texCoord; computeQuadTexCoordCube(texCoord, face); // \todo [2011-10-28 pyry] Image set name / section? log << TestLog::Message << face << TestLog::EndMessage; // Setup base viewport. gl.viewport(viewport.x, viewport.y, viewport.width, viewport.height); // Bind to unit 0. gl.activeTexture(GL_TEXTURE0); gl.bindTexture(GL_TEXTURE_CUBE_MAP, m_texture->getGLTexture()); gl.texParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, wrapS); gl.texParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, wrapT); gl.texParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, minFilter); gl.texParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, magFilter); GLU_EXPECT_NO_ERROR(gl.getError(), "Set texturing state"); m_renderer.renderQuad(0, &texCoord[0], TEXTURETYPE_CUBE); glu::readPixels(m_renderCtx, viewport.x, viewport.y, renderedFrame.getAccess()); // Compute reference. Sampler sampler = mapGLSampler(wrapS, wrapT, minFilter, magFilter); sampler.seamlessCubeMap = false; sampleTexture(tcu::SurfaceAccess(referenceFrame, m_renderCtx.getRenderTarget().getPixelFormat()), m_texture->getRefTexture(), &texCoord[0], ReferenceParams(TEXTURETYPE_CUBE, sampler)); // Compare and log. return compareImages(log, referenceFrame, renderedFrame, threshold); } TextureCubeSizeCase::IterateResult TextureCubeSizeCase::iterate (void) { // Execute test for all faces. if (!testFace((tcu::CubeFace)m_curFace)) m_isOk = false; m_curFace += 1; if (m_curFace == tcu::CUBEFACE_LAST) { m_testCtx.setTestResult(m_isOk ? QP_TEST_RESULT_PASS : QP_TEST_RESULT_FAIL, m_isOk ? "Pass" : "Image comparison failed"); return STOP; } else return CONTINUE; } TextureSizeTests::TextureSizeTests (Context& context) : TestCaseGroup(context, "size", "Texture Size Tests") { } TextureSizeTests::~TextureSizeTests (void) { } void TextureSizeTests::init (void) { struct { int width; int height; } sizes2D[] = { { 64, 64 }, // Spec-mandated minimum. { 65, 63 }, { 512, 512 }, { 1024, 1024 }, { 2048, 2048 } }; struct { int width; int height; } sizesCube[] = { { 15, 15 }, { 16, 16 }, // Spec-mandated minimum { 64, 64 }, { 128, 128 }, { 256, 256 }, { 512, 512 } }; struct { const char* name; deUint32 format; deUint32 dataType; } formats[] = { { "l8", GL_LUMINANCE, GL_UNSIGNED_BYTE }, { "rgba4444", GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4 }, { "rgb888", GL_RGB, GL_UNSIGNED_BYTE }, { "rgba8888", GL_RGBA, GL_UNSIGNED_BYTE } }; // 2D cases. tcu::TestCaseGroup* group2D = new tcu::TestCaseGroup(m_testCtx, "2d", "2D Texture Size Tests"); addChild(group2D); for (int sizeNdx = 0; sizeNdx < DE_LENGTH_OF_ARRAY(sizes2D); sizeNdx++) { int width = sizes2D[sizeNdx].width; int height = sizes2D[sizeNdx].height; bool isPOT = deIsPowerOfTwo32(width) && deIsPowerOfTwo32(height); for (int formatNdx = 0; formatNdx < DE_LENGTH_OF_ARRAY(formats); formatNdx++) { for (int mipmap = 0; mipmap < (isPOT ? 2 : 1); mipmap++) { std::ostringstream name; name << width << "x" << height << "_" << formats[formatNdx].name << (mipmap ? "_mipmap" : ""); group2D->addChild(new Texture2DSizeCase(m_testCtx, m_context.getRenderContext(), name.str().c_str(), "", formats[formatNdx].format, formats[formatNdx].dataType, width, height, mipmap != 0)); } } } // Cubemap cases. tcu::TestCaseGroup* groupCube = new tcu::TestCaseGroup(m_testCtx, "cube", "Cubemap Texture Size Tests"); addChild(groupCube); for (int sizeNdx = 0; sizeNdx < DE_LENGTH_OF_ARRAY(sizesCube); sizeNdx++) { int width = sizesCube[sizeNdx].width; int height = sizesCube[sizeNdx].height; bool isPOT = deIsPowerOfTwo32(width) && deIsPowerOfTwo32(height); for (int formatNdx = 0; formatNdx < DE_LENGTH_OF_ARRAY(formats); formatNdx++) { for (int mipmap = 0; mipmap < (isPOT ? 2 : 1); mipmap++) { std::ostringstream name; name << width << "x" << height << "_" << formats[formatNdx].name << (mipmap ? "_mipmap" : ""); groupCube->addChild(new TextureCubeSizeCase(m_testCtx, m_context.getRenderContext(), name.str().c_str(), "", formats[formatNdx].format, formats[formatNdx].dataType, width, height, mipmap != 0)); } } } } } // Functional } // gles2 } // deqp
32.084112
224
0.696257
billkris-ms
67b6b67284e1c04aadcc357ddfa90519f056b94b
3,450
cpp
C++
Source/NewtonPhysics/Newton6DOFConstraint.cpp
TrevorCash/rbfx-newton
a8465870a85d69386709a4d65d758fa28b69918b
[ "MIT" ]
9
2019-05-07T00:23:10.000Z
2022-03-15T20:54:03.000Z
Source/NewtonPhysics/Newton6DOFConstraint.cpp
TrevorCash/rbfx-newton
a8465870a85d69386709a4d65d758fa28b69918b
[ "MIT" ]
null
null
null
Source/NewtonPhysics/Newton6DOFConstraint.cpp
TrevorCash/rbfx-newton
a8465870a85d69386709a4d65d758fa28b69918b
[ "MIT" ]
2
2019-11-10T06:56:14.000Z
2020-07-05T11:32:21.000Z
#include "Newton6DOFConstraint.h" #include "NewtonPhysicsWorld.h" #include "UrhoNewtonConversions.h" #include "dCustomSixdof.h" #include "Urho3D/Core/Context.h" namespace Urho3D { NewtonSixDofConstraint::NewtonSixDofConstraint(Context* context) : NewtonConstraint(context) { } NewtonSixDofConstraint::~NewtonSixDofConstraint() { } void NewtonSixDofConstraint::RegisterObject(Context* context) { context->RegisterFactory<NewtonSixDofConstraint>(DEF_PHYSICS_CATEGORY.c_str()); URHO3D_COPY_BASE_ATTRIBUTES(NewtonConstraint); } void NewtonSixDofConstraint::SetPitchLimits(float minLimit, float maxLimit) { if (pitchLimits_ != Vector2(minLimit, maxLimit)) { pitchLimits_.x_ = minLimit; pitchLimits_.y_ = maxLimit; if (newtonJoint_) { static_cast<dCustomSixdof*>(newtonJoint_)->SetPitchLimits(pitchLimits_.x_, pitchLimits_.y_); } else MarkDirty(); } } void NewtonSixDofConstraint::SetPitchLimits(const Vector3& limits) { SetPitchLimits(limits.x_, limits.y_); } void NewtonSixDofConstraint::SetYawLimits(float minLimit, float maxLimit) { if (yawLimits_ != Vector2(minLimit, maxLimit)) { yawLimits_.x_ = minLimit; yawLimits_.y_ = maxLimit; if (newtonJoint_) { static_cast<dCustomSixdof*>(newtonJoint_)->SetYawLimits(yawLimits_.x_, yawLimits_.y_); } else MarkDirty(); } } void NewtonSixDofConstraint::SetYawLimits(const Vector3& limits) { SetYawLimits(limits.x_, limits.y_); } void NewtonSixDofConstraint::SetRollLimits(float minLimit, float maxLimit) { if (rollLimits_ != Vector2(minLimit, maxLimit)) { rollLimits_.x_ = minLimit; rollLimits_.y_ = maxLimit; if (newtonJoint_) { static_cast<dCustomSixdof*>(newtonJoint_)->SetRollLimits(rollLimits_.x_, rollLimits_.y_); } else MarkDirty(); } } void NewtonSixDofConstraint::SetRollLimits(const Vector3& limits) { SetRollLimits(limits.x_, limits.y_); } void NewtonSixDofConstraint::DrawDebugGeometry(DebugRenderer* debug, bool depthTest) { NewtonConstraint::DrawDebugGeometry(debug, depthTest); } void NewtonSixDofConstraint::buildConstraint() { newtonJoint_ = new dCustomSixdof(UrhoToNewton(GetOwnBuildWorldFrame()), UrhoToNewton(GetOtherBuildWorldFrame()), GetOwnNewtonBody(), GetOtherNewtonBody()); } bool NewtonSixDofConstraint::applyAllJointParams() { if (!NewtonConstraint::applyAllJointParams()) return false; static_cast<dCustomSixdof*>(newtonJoint_)->SetLinearLimits(dVector(M_LARGE_VALUE, M_LARGE_VALUE, M_LARGE_VALUE)*-1.0f, dVector(M_LARGE_VALUE, M_LARGE_VALUE, M_LARGE_VALUE)); static_cast<dCustomSixdof*>(newtonJoint_)->SetPitchLimits(pitchLimits_.x_ * dDegreeToRad, pitchLimits_.y_* dDegreeToRad); static_cast<dCustomSixdof*>(newtonJoint_)->SetYawLimits(yawLimits_.x_* dDegreeToRad, yawLimits_.y_* dDegreeToRad); static_cast<dCustomSixdof*>(newtonJoint_)->SetRollLimits(rollLimits_.x_* dDegreeToRad, rollLimits_.y_* dDegreeToRad); return true; } }
29.237288
181
0.656812
TrevorCash
67bc50a40b2e0bebd13a71c214d38e24f8dad1eb
1,247
cpp
C++
test/MathTest.cpp
helmertz/noxoscope
2c663e12ef5a54e61eae7b60f4efa934f84a1814
[ "CC-BY-3.0", "Apache-2.0" ]
null
null
null
test/MathTest.cpp
helmertz/noxoscope
2c663e12ef5a54e61eae7b60f4efa934f84a1814
[ "CC-BY-3.0", "Apache-2.0" ]
null
null
null
test/MathTest.cpp
helmertz/noxoscope
2c663e12ef5a54e61eae7b60f4efa934f84a1814
[ "CC-BY-3.0", "Apache-2.0" ]
null
null
null
//===----------------------------------------------------------------------===// // // This file is part of the Noxoscope project // // Copyright (c) 2016 Niklas Helmertz // //===----------------------------------------------------------------------===// #include "TestShared.h" #include <Logging.h> #include <GeometryMath.h> TEST_CASE("Example test") { REQUIRE(1 + 1 == 2); } TEST_CASE("Test converting spherical and back") { using namespace glm; rc::prop("", []() { float radius = floatInRange(0.01f, 100.0f); float inclination = floatInRange(0.0f, PI_F); float azimuth = floatInRange(0.0f, 2.0f * PI_F); vec3 cartesian = sphericalToCartesian(radius, inclination, azimuth); vec3 sphericalRes = cartesianToSpherical(cartesian); float resRadius = sphericalRes.x; float resInclination = sphericalRes.y; float resAzimuth = fmod(sphericalRes.z + 2.0f * PI_F, 2.0f * PI_F); // Convert from [-pi,pi] to [0,2*pi] RC_ASSERT(approxEqual(radius, resRadius)); RC_ASSERT(approxEqual(inclination, resInclination)); // If inclination is either straight up or down, any azimuth would be valid if (!approxEqual(inclination, 0.0f) && !approxEqual(inclination, PI_F)) { RC_ASSERT(approxEqual(azimuth, resAzimuth)); } }); }
30.414634
106
0.614274
helmertz
67be146857546dffe08c50450f7a2e344235fa03
5,506
cpp
C++
Game/Source/GameObjects/Trainer.cpp
Crewbee/Pokemon-Clone-DX12
188bdde03d5078899a1532305a87d15c611c6c13
[ "CC0-1.0" ]
null
null
null
Game/Source/GameObjects/Trainer.cpp
Crewbee/Pokemon-Clone-DX12
188bdde03d5078899a1532305a87d15c611c6c13
[ "CC0-1.0" ]
null
null
null
Game/Source/GameObjects/Trainer.cpp
Crewbee/Pokemon-Clone-DX12
188bdde03d5078899a1532305a87d15c611c6c13
[ "CC0-1.0" ]
null
null
null
#include "GamePCH.h" #include "GameObjects/GameObject.h" #include "Trainer.h" #include "Controllers/PlayerController.h" #include "Sprites/AnimatedSprite.h" #include "GameplayHelpers/ResourceManager.h" #include "GameplayHelpers/TileMap.h" #include "Mesh/Mesh.h" #include "GameplayHelpers/SceneManager.h" #include "Scenes/Scene.h" #include "Scenes/OakLab.h" #include "Scenes/PalletTown.h" Trainer::Trainer(ResourceManager * aResourceManager, GameCore * myGame, Mesh * myMesh, GLuint aTexture) :GameObject(myGame, myMesh, aTexture) { myDirection = SpriteWalkDown; myResourceManager = aResourceManager; m_pMesh->GenerateFrameMesh(); //Initialize the animated sprites for (int i = 0; i < NUM_DIRECTIONS; i++) { m_Animations[i] = new AnimatedSprite(myResourceManager, myGame, myMesh, 2, aTexture); m_Animations[i]->AddFrame(AnimationKeys[i] + "1.png"); m_Animations[i]->AddFrame(AnimationKeys[i] + "2.png"); m_Animations[i]->AddFrame(AnimationKeys[i] + "1.png"); m_Animations[i]->AddFrame(AnimationKeys[i] + "3.png"); m_Animations[i]->SetFrameSpeed(6.0f); m_Animations[i]->SetLoop(true); m_Animations[i]->SetPosition(m_Position); } m_Stop = false; m_InTransition = false; } Trainer::~Trainer() { for (int i = 0; i < NUM_DIRECTIONS; i++) { delete m_Animations[i]; m_Animations[i] = nullptr; } myResourceManager = nullptr; } void Trainer::Update(float deltatime) { Pause(); if (m_InTransition == false) { if (myController) { if (m_Stop == false) { if (myController->IsForwardHeld()) { Move(SpriteWalkUp, deltatime); } if (myController->IsReverseHeld()) { Move(SpriteWalkDown, deltatime); } if (myController->IsTurnRightHeld()) { Move(SpriteWalkRight, deltatime); } if (myController->IsTurnLeftHeld()) { Move(SpriteWalkLeft, deltatime); } if (myController->IsInputReleased()) { for (int i = 0; i < NUM_DIRECTIONS; i++) { m_Animations[i]->SetFrameIndex(0); } } } } } if (m_InTransition == true) { if (myDirection == SpriteWalkUp || myDirection == SpriteWalkRight) { if (m_Position.y < aTransitionDestination.y) { Move(myDirection, deltatime); } else if (m_Position.x < aTransitionDestination.x) { Move(myDirection, deltatime); } else { m_InTransition = false; } } if (myDirection == SpriteWalkDown || myDirection == SpriteWalkLeft) { if (m_Position.y > aTransitionDestination.y) { Move(myDirection, deltatime); } else if (m_Position.x > aTransitionDestination.x) { Move(myDirection, deltatime); } else { m_InTransition = false; } } } for (int i = 0; i < NUM_DIRECTIONS; i++) { m_Animations[i]->SetPosition(GetPosition()); m_Animations[i]->Update(deltatime); } } void Trainer::Draw(vec2 camPos, vec2 projecScale) { m_Animations[myDirection]->Draw(camPos, projecScale); } void Trainer::Move(SpriteDirection dir, float deltatime) { NewPosition = m_Position; Resume(); if (myDirection != dir) { myDirection = dir; } vec2 velocity = DIRECTIONVECTOR[dir] * PLAYER_SPEED; NewPosition += velocity * deltatime; if (m_InTransition == false) { if (CheckForCollision(NewPosition) == true) { SetPosition(NewPosition); } } else { SetPosition(NewPosition); } } void Trainer::Pause() { for (int i = 0; i < NUM_DIRECTIONS; i++) { m_Animations[i]->Pause(); } } void Trainer::Resume() { for (int i = 0; i < NUM_DIRECTIONS; i++) { m_Animations[i]->Resume(); } } void Trainer::SetStop(bool StopPlayer) { if (m_Stop != StopPlayer) { m_Stop = StopPlayer; } } void Trainer::OnEvent(Event * anEvent) { DoorEvent* e = (DoorEvent*)anEvent; if (e->GetDoorType() == 11) { myDirection = SpriteWalkUp; SetPosition(m_pGame->GetSceneManager()->GetActiveScene()->GetPlayerStart()); PlayerTransition(); } if (e->GetDoorType() == 10) { myDirection = SpriteWalkDown; SetPosition(m_pGame->GetSceneManager()->GetActiveScene()->GetPlayerStart()); PlayerTransition(); } } void Trainer::PlayerTransition() { m_InTransition = true; aTransitionDestination = GetPosition() + vec2(DIRECTIONVECTOR[myDirection] * (TILESIZE / 4)); } SpriteDirection Trainer::GetMyDirection() { return myDirection; } bool Trainer::CheckForCollision(vec2 playerNewPosition) { //Get the location of each point of collision on the player and then truncate it to a row and column ivec2 OriginIndex = ivec2((playerNewPosition.x / TILESIZE), ((playerNewPosition.y - 0.3f) / TILESIZE)); ivec2 TopLeftIndex = ivec2((playerNewPosition.x / TILESIZE), (((playerNewPosition.y - 0.5f) + (TILESIZE / 2)) / TILESIZE)); ivec2 TopRightIndex = ivec2(((playerNewPosition.x + (TILESIZE / 2)) / TILESIZE), (((playerNewPosition.y - 0.5f) + (TILESIZE / 2)) / TILESIZE)); ivec2 BottomRightIndex = ivec2(((playerNewPosition.x + (TILESIZE / 2)) / TILESIZE), ((playerNewPosition.y - 0.3f) / TILESIZE)); //Check each index for whether the tile it lands on is walkable bool CheckOrigin = m_pGame->GetTileMap()->GetTileAtPlayer(OriginIndex); bool CheckTopLeft = m_pGame->GetTileMap()->GetTileAtPlayer(TopLeftIndex); bool CheckTopRight = m_pGame->GetTileMap()->GetTileAtPlayer(TopRightIndex); bool CheckBottomRight = m_pGame->GetTileMap()->GetTileAtPlayer(BottomRightIndex); //If all the point land on walkable tile return true else return false bool Collision = (CheckOrigin && CheckTopLeft && CheckTopRight && CheckBottomRight); return Collision; }
23.429787
144
0.689248
Crewbee
67bee141c7cf9e3b007eac22c03c6430698db2f2
4,104
cxx
C++
TRD/TRDbase/AliTRDUshortInfo.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
52
2016-12-11T13:04:01.000Z
2022-03-11T11:49:35.000Z
TRD/TRDbase/AliTRDUshortInfo.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
1,388
2016-11-01T10:27:36.000Z
2022-03-30T15:26:09.000Z
TRD/TRDbase/AliTRDUshortInfo.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
275
2016-06-21T20:24:05.000Z
2022-03-31T13:06:19.000Z
/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Id: AliTRDUshortInfo.cxx 27946 2008-08-13 15:26:24Z cblume $ */ /////////////////////////////////////////////////////////////////////////////// // // // Calibration base class for a single ROC // // Contains one UShort_t value per pad // // However, values are set and get as float, there are stored internally as // // (UShort_t) value * 10000 // // // /////////////////////////////////////////////////////////////////////////////// #include "AliTRDUshortInfo.h" ClassImp(AliTRDUshortInfo) //_____________________________________________________________________________ AliTRDUshortInfo::AliTRDUshortInfo() :TObject() ,fSize(0) ,fData(0) { // // Default constructor // } //_____________________________________________________________________________ AliTRDUshortInfo::AliTRDUshortInfo(Int_t n) :TObject() ,fSize(n) ,fData(0) { // // Constructor that initializes a given size // fData = new UShort_t[fSize]; for(Int_t k = 0; k < fSize; k++){ fData[k] = 0; } } //_____________________________________________________________________________ AliTRDUshortInfo::AliTRDUshortInfo(const AliTRDUshortInfo &c) :TObject(c) ,fSize(c.fSize) ,fData(0) { // // AliTRDUshortInfo copy constructor // Int_t iBin = 0; fData = new UShort_t[fSize]; for (iBin = 0; iBin < fSize; iBin++) { fData[iBin] = ((AliTRDUshortInfo &) c).fData[iBin]; } } //_____________________________________________________________________________ AliTRDUshortInfo::~AliTRDUshortInfo() { // // AliTRDUshortInfo destructor // if (fData) { delete [] fData; fData = 0; } } //_____________________________________________________________________________ AliTRDUshortInfo &AliTRDUshortInfo::operator=(const AliTRDUshortInfo &c) { // // Assignment operator // if (this == &c) { return *this; } fSize = c.fSize; if (fData) { delete [] fData; } fData = new UShort_t[fSize]; for (Int_t iBin = 0; iBin < fSize; iBin++) { fData[iBin] = c.fData[iBin]; } return *this; } //_____________________________________________________________________________ void AliTRDUshortInfo::Copy(TObject &c) const { // // Copy function // Int_t iBin = 0; ((AliTRDUshortInfo &) c).fSize = fSize; if (((AliTRDUshortInfo &) c).fData) delete [] ((AliTRDUshortInfo &) c).fData; ((AliTRDUshortInfo &) c).fData = new UShort_t[fSize]; for (iBin = 0; iBin < fSize; iBin++) { ((AliTRDUshortInfo &) c).fData[iBin] = fData[iBin]; } TObject::Copy(c); } //_____________________________________________________________________________ void AliTRDUshortInfo::SetSize(Int_t n) { // // Set the size // if(fData) delete [] fData; fData = new UShort_t[n]; fSize = n; }
27
79
0.560916
AllaMaevskaya
67cb0da9678791c31d058a4b20a418820681f81e
9,190
cpp
C++
states/editor/editoroptions.cpp
Adriqun/Ninja2
98aff59bcb63928dd6894ea45e00bfe12e46e6bc
[ "MIT" ]
5
2018-06-10T09:14:37.000Z
2022-01-24T10:08:12.000Z
states/editor/editoroptions.cpp
Adriqun/Ninja2
98aff59bcb63928dd6894ea45e00bfe12e46e6bc
[ "MIT" ]
2
2016-11-01T14:39:28.000Z
2017-02-12T20:54:29.000Z
states/editor/editoroptions.cpp
Adriqun/Ninja2
98aff59bcb63928dd6894ea45e00bfe12e46e6bc
[ "MIT" ]
1
2016-12-27T05:06:07.000Z
2016-12-27T05:06:07.000Z
#include "editoroptions.h" #include "loading.h" #include "colors.h" #include "definitions.h" EditorOptions::EditorOptions() { free(); } EditorOptions::~EditorOptions() { free(); } void EditorOptions::free() { if (!keytextvec.empty()) { for (auto &it : keytextvec) { delete it; it = nullptr; } keytextvec.clear(); } if (!infotextvec.empty()) { for (auto &it : infotextvec) { delete it; it = nullptr; } infotextvec.clear(); } reset(); lastPage = 3; } void EditorOptions::reset() { currPage = 0; active = false; } void EditorOptions::load(const float& screen_w, const float& screen_h) { free(); float scale_x = screen_w / 1920; if (scale_x > 1.0f) scale_x = 1; float scale_y = screen_h / 1080; if (scale_y > 1.0f) scale_y = 1; // Set button. button.load("images/buttons/settings.png"); if (Loading::isError()) return; button.setVolume(MIN_SOUND_VOLUME); // muted button.setScale(screen_w / 2560, screen_h / 1440); button.setPosition(screen_w - (screen_w / 256 + button.getWidth()) * 4, screen_h / 144); // Set button label. Loading::add(label.setFont(cmm::JCANDLE_FONT_PATH)); if (Loading::isError()) return; label.setText("options"); label.setAlpha(MAX_ALPHA); label.setPosition(button.getLeft() + button.getWidth() / 2 - label.getWidth() / 2.5, button.getBot() + screen_w / 300.0f); label.setSize(screen_w / 60); // Set board. Loading::add(plank.load("images/other/plank.png")); if (Loading::isError()) return; plank.setScale(scale_x, scale_y); plank.center(screen_w / 2, screen_h / 2); // Set black layer. blackLayer.setFillColor(sf::Color(0, 0, 0, 140)); blackLayer.setSize(sf::Vector2f(screen_w, screen_h)); blackLayer.setPosition(0, 0); // Set left/right buttons. Loading::add(leftbutton.load("images/icons/lefticon.png")); Loading::add(rightbutton.load("images/icons/righticon.png")); if (Loading::isError()) return; float factor = 0.9f; leftbutton.setScale(scale_x * factor, scale_y * factor); rightbutton.setScale(scale_x * factor, scale_y * factor); leftbutton.setPosition(plank.getLeft() + screen_w / 128, plank.getTop() + plank.getHeight() / 2 - leftbutton.getHeight() / 2); rightbutton.setPosition((plank.getRight() - screen_w / 128) - rightbutton.getWidth(), leftbutton.getY()); leftbutton.setAlpha(MAX_ALPHA / 1.5); rightbutton.setAlpha(MAX_ALPHA / 1.5); // Set texts. for (int i = 0; i < LABELS::AMOUNT; ++i) { keytextvec.push_back(new cmm::Text); infotextvec.push_back(new cmm::Text); Loading::add(keytextvec.back()->setFont(cmm::JAPOKKI_FONT_PATH)); Loading::add(infotextvec.back()->setFont(cmm::JAPOKKI_FONT_PATH)); if (Loading::isError()) return; keytextvec.back()->setSize(plank.getWidth() / 25); infotextvec.back()->setSize(plank.getWidth() / 25); keytextvec.back()->setFillColor(cmm::DULL_IRON_COLOR); infotextvec.back()->setFillColor(cmm::WHITISH_COLOR); keytextvec.back()->setAlpha(MAX_ALPHA); infotextvec.back()->setAlpha(MAX_ALPHA); } keytextvec[ESCAPE]->setText("[ESC]"); keytextvec[ENTER]->setText("[ENTER]"); keytextvec[CTRL_Z]->setText("[CTRL+Z]"); keytextvec[SPACE]->setText("[SPACE]"); keytextvec[LCTRL]->setText("[LCTRL]"); keytextvec[LSHIFT]->setText("[LSHIFT]"); keytextvec[A]->setText("[A]\t\t"); keytextvec[S]->setText("[S]\t\t"); keytextvec[D]->setText("[D]\t\t"); keytextvec[Z]->setText("[Z]\t\t"); keytextvec[X]->setText("[X]\t\t"); keytextvec[C]->setText("[C]\t\t"); keytextvec[LEFT]->setText("[LEFT]"); keytextvec[RIGHT]->setText("[RIGHT]"); keytextvec[UP]->setText("[UP]"); keytextvec[DOWN]->setText("[DOWN]"); keytextvec[LEFTMOUSE]->setText("[LEFT MOUSE BUTTON]"); keytextvec[RIGHTMOUSE]->setText("[RIGHT MOUSE BUTTON]"); keytextvec[SCROLLMOUSE]->setText("[MOUSE SCROLL]"); infotextvec[ESCAPE]->setText("Closes current open window. Turns off\ncurrent active mode.\nResets group and chosen entity from group.\n"); infotextvec[ENTER]->setText("Agrees with current decision in message log.\nApproves choice yes/ok.\n"); infotextvec[CTRL_Z]->setText("Undo. Back to previous world state.\nDetermines current state then goes back to\nthe previous.\n"); infotextvec[SPACE]->setText("Temporary quick mode. Does actions like\nput (place) or remove. Based on current\nmode it deletes or puts entity very fast.\n"); infotextvec[LCTRL]->setText("Temporary delete mode. Enables user to\nremove entity that mouse is pointing at.\n"); infotextvec[LSHIFT]->setText("Temporary whole collision mode. This mode\nis very useful while placing tiles.\nTurnt on checks the whole rect occupied by\nentity.\n\n"); infotextvec[A]->setText("Moves to the previous group of entities."); infotextvec[S]->setText("Reset the chosen group to none."); infotextvec[D]->setText("Moves to the succeding group of entities.\n"); infotextvec[Z]->setText("Goes to previous entity from the group."); infotextvec[X]->setText("Goes to nearest middle one from the group."); infotextvec[C]->setText("Goes to next entity from the group.\n"); infotextvec[LEFT]->setText("Moves current world content's position\nleftward (it does not change entities position).\n"); infotextvec[RIGHT]->setText("Moves current world content's position\nrightward (same as above).\n"); infotextvec[UP]->setText("Moves current world content's position upward\n(same as above).\n"); infotextvec[DOWN]->setText("Moves current world content's position\ndownward (same as above).\n"); infotextvec[LEFTMOUSE]->setText("Puts entity or removes\n(depends on current mode).\n\n"); infotextvec[RIGHTMOUSE]->setText("If mouse cursor is hovered\nabove the entity it opens\nthe options of a group.\n\n\n"); infotextvec[SCROLLMOUSE]->setText("Changes entity of chosen group\nto upward or downward one."); // Set page text. Loading::add(pageText.setFont(cmm::JCANDLE_FONT_PATH)); if (Loading::isError()) return; pageText.setAlpha(MAX_ALPHA); pageText.setSize(plank.getWidth() / 20); setPageText(); } void EditorOptions::handle(const sf::Event &event) { if (event.type == sf::Event::MouseButtonPressed) { if (event.mouseButton.button == sf::Mouse::Left) { float x = (float)event.mouseButton.x; float y = (float)event.mouseButton.y; if (!active && button.handle(event)) { active = button.isActive(); if (active) setText(); return; } if (!active) return; if (leftbutton.checkCollision(x, y)) { if (isAbleToGoLeft()) { --currPage; setText(); } } else if (rightbutton.checkCollision(x, y)) { if (isAbleToGoRight()) { ++currPage; setText(); } } else if (!plank.checkCollision(x, y)) { active = false; button.setActive(false); reset(); } } } if (!active) return; if (event.type == sf::Event::KeyPressed) { if (event.key.code == sf::Keyboard::Escape) { active = false; button.setActive(false); reset(); return; } } // hovering... if (event.type == sf::Event::MouseMoved) { leftbutton.setAlpha(MAX_ALPHA / 1.5); rightbutton.setAlpha(MAX_ALPHA / 1.5); float x = (float)event.mouseMove.x; float y = (float)event.mouseMove.y; if (isAbleToGoLeft() && leftbutton.checkCollision(x, y)) leftbutton.setAlpha(MAX_ALPHA); else if (isAbleToGoRight() &&rightbutton.checkCollision(x, y)) rightbutton.setAlpha(MAX_ALPHA); } } void EditorOptions::drawButton(sf::RenderWindow* &window) { // Draw button and label always. button.draw(window); window->draw(label); } void EditorOptions::draw(sf::RenderWindow* &window) { if (!active) return; window->draw(blackLayer); window->draw(plank); // Draw descriptions / texts. for (int i = first; i <= last; ++i) { window->draw(*keytextvec[i]); window->draw(*infotextvec[i]); } // Draw left/right buttons. if (currPage != 0) window->draw(leftbutton); if (currPage != lastPage) window->draw(rightbutton); window->draw(pageText); } void EditorOptions::setText() { setPageText(); setBorders(); // set position of current scope keytextvec[first]->setPosition(plank.getX() + plank.getWidth() / 64, plank.getY() + plank.getHeight() / 64); infotextvec[first]->setPosition(keytextvec[first]->getX() + keytextvec[first]->getWidth() + plank.getWidth() / 64, keytextvec[first]->getY()); for (int i = first + 1; i <= last; ++i) { keytextvec[i]->setPosition(keytextvec[first]->getX(), infotextvec[i - 1]->getBot()); infotextvec[i]->setPosition(keytextvec[i]->getX() + keytextvec[i]->getWidth() + plank.getWidth() / 64, infotextvec[i - 1]->getBot()); } } void EditorOptions::setPageText() { pageText.setText(std::to_string(currPage) + "/" + std::to_string(lastPage)); pageText.setPosition(plank.getLeft() + plank.getWidth() - pageText.getWidth() * 1.2, plank.getTop() + plank.getHeight() - plank.getWidth() / 15); } void EditorOptions::setBorders() { if (currPage == 0) { first = 0; last = SPACE; } else if (currPage == 1) { first = LCTRL; last = C; } else if (currPage == lastPage - 1) { first = LEFT; last = DOWN; } else { first = LEFTMOUSE; last = SCROLLMOUSE; } } bool EditorOptions::isAbleToGoLeft() { return currPage > 0; } bool EditorOptions::isAbleToGoRight() { return currPage < lastPage; }
28.990536
169
0.685528
Adriqun
67cff565a26fd1a11e1ec60ffe60331abb38a9f1
680
hpp
C++
phoenix/cocoa/widget/viewport.hpp
vgmtool/vgm2pre
f4f917df35d531512292541234a5c1722b8af96f
[ "MIT" ]
21
2015-04-13T03:07:12.000Z
2021-11-20T00:27:00.000Z
phoenix/cocoa/widget/viewport.hpp
apollolux/hello-phoenix
71510b5f329804c525a9576fb0367fe8ab2487cd
[ "MIT" ]
2
2015-10-06T14:59:48.000Z
2022-01-27T08:57:57.000Z
phoenix/cocoa/widget/viewport.hpp
apollolux/hello-phoenix
71510b5f329804c525a9576fb0367fe8ab2487cd
[ "MIT" ]
2
2021-11-19T08:36:57.000Z
2022-03-04T16:03:16.000Z
@interface CocoaViewport : NSView { @public phoenix::Viewport* viewport; } -(id) initWith:(phoenix::Viewport&)viewport; -(void) drawRect:(NSRect)rect; -(BOOL) acceptsFirstResponder; -(NSDragOperation) draggingEntered:(id<NSDraggingInfo>)sender; -(BOOL) performDragOperation:(id<NSDraggingInfo>)sender; -(void) keyDown:(NSEvent*)event; -(void) keyUp:(NSEvent*)event; @end namespace phoenix { struct pViewport : public pWidget { Viewport& viewport; CocoaViewport* cocoaViewport = nullptr; uintptr_t handle(); void setDroppable(bool droppable); pViewport(Viewport& viewport) : pWidget(viewport), viewport(viewport) {} void constructor(); void destructor(); }; }
23.448276
74
0.741176
vgmtool
67d071a55a5a9cab05bf9668523ed5eb8f689b6f
967
hpp
C++
libs/core/include/fcppt/time/output_tm.hpp
pmiddend/fcppt
9f437acbb10258e6df6982a550213a05815eb2be
[ "BSL-1.0" ]
null
null
null
libs/core/include/fcppt/time/output_tm.hpp
pmiddend/fcppt
9f437acbb10258e6df6982a550213a05815eb2be
[ "BSL-1.0" ]
null
null
null
libs/core/include/fcppt/time/output_tm.hpp
pmiddend/fcppt
9f437acbb10258e6df6982a550213a05815eb2be
[ "BSL-1.0" ]
null
null
null
// Copyright Carl Philipp Reh 2009 - 2018. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef FCPPT_TIME_OUTPUT_TM_HPP_INCLUDED #define FCPPT_TIME_OUTPUT_TM_HPP_INCLUDED #include <fcppt/detail/symbol.hpp> #include <fcppt/io/ostream_fwd.hpp> #include <fcppt/config/external_begin.hpp> #include <ctime> #include <fcppt/config/external_end.hpp> namespace fcppt { namespace time { /** \brief Outputs an <code>%std::tm</code> to a stream \ingroup fcppttime Outputs \a tm to \a stream using the <code>std::time_put</code> locale facet, obtained from the locale of \a stream. Example: \snippet output_tm.cpp output_tm \param stream The stream to output to \param tm The time struct to output \return \a stream */ FCPPT_DETAIL_SYMBOL fcppt::io::ostream & output_tm( fcppt::io::ostream &stream, std::tm const &tm ); } } #endif
20.145833
77
0.737332
pmiddend
67d6ad2490edc8e8690bb1c5773f33069e3f920e
1,233
cpp
C++
third_party/boost/libs/parameter/test/macros.cpp
Jackarain/tinyrpc
07060e3466776aa992df8574ded6c1616a1a31af
[ "BSL-1.0" ]
32
2019-02-27T06:57:07.000Z
2021-08-29T10:56:19.000Z
third_party/boost/libs/parameter/test/macros.cpp
avplayer/cxxrpc
7049b4079fac78b3828e68f787d04d699ce52f6d
[ "BSL-1.0" ]
1
2019-04-04T18:00:00.000Z
2019-04-04T18:00:00.000Z
third_party/boost/libs/parameter/test/macros.cpp
avplayer/cxxrpc
7049b4079fac78b3828e68f787d04d699ce52f6d
[ "BSL-1.0" ]
5
2019-08-20T13:45:04.000Z
2022-03-01T18:23:49.000Z
// Copyright David Abrahams, Daniel Wallin 2003. Use, modification and // distribution is subject to the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include <boost/parameter.hpp> #include <boost/parameter/macros.hpp> #include <boost/bind.hpp> #include <boost/static_assert.hpp> #include <boost/ref.hpp> #include <cassert> #include <string.h> #include "basics.hpp" namespace test { BOOST_PARAMETER_FUN(int, f, 2, 4, f_parameters) { p[tester]( p[name] , p[value || boost::bind(&value_default) ] #if BOOST_WORKAROUND(__DECCXX_VER, BOOST_TESTED_AT(60590042)) , p[test::index | 999 ] #else , p[index | 999 ] #endif ); return 1; } } // namespace test int main() { using test::f; using test::name; using test::value; using test::index; using test::tester; f( test::values(S("foo"), S("bar"), S("baz")) , S("foo"), S("bar"), S("baz") ); int x = 56; f( test::values("foo", 666.222, 56) , index = boost::ref(x), name = "foo" ); return boost::report_errors(); }
21.258621
72
0.583131
Jackarain
67d6bac0c85022d2e8fd437d316295bf8d10c947
1,222
hpp
C++
android-31/java/security/cert/PKIXRevocationChecker.hpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
12
2020-03-26T02:38:56.000Z
2022-03-14T08:17:26.000Z
android-31/java/security/cert/PKIXRevocationChecker.hpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
1
2021-01-27T06:07:45.000Z
2021-11-13T19:19:43.000Z
android-29/java/security/cert/PKIXRevocationChecker.hpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
3
2021-02-02T12:34:55.000Z
2022-03-08T07:45:57.000Z
#pragma once #include "./PKIXCertPathChecker.hpp" class JObject; namespace java::net { class URI; } namespace java::security::cert { class X509Certificate; } namespace java::security::cert { class PKIXRevocationChecker : public java::security::cert::PKIXCertPathChecker { public: // Fields // QJniObject forward template<typename ...Ts> explicit PKIXRevocationChecker(const char *className, const char *sig, Ts...agv) : java::security::cert::PKIXCertPathChecker(className, sig, std::forward<Ts>(agv)...) {} PKIXRevocationChecker(QJniObject obj); // Constructors // Methods java::security::cert::PKIXRevocationChecker clone() const; JObject getOcspExtensions() const; java::net::URI getOcspResponder() const; java::security::cert::X509Certificate getOcspResponderCert() const; JObject getOcspResponses() const; JObject getOptions() const; JObject getSoftFailExceptions() const; void setOcspExtensions(JObject arg0) const; void setOcspResponder(java::net::URI arg0) const; void setOcspResponderCert(java::security::cert::X509Certificate arg0) const; void setOcspResponses(JObject arg0) const; void setOptions(JObject arg0) const; }; } // namespace java::security::cert
27.772727
196
0.748773
YJBeetle
67d8635bbbf5b70ada4b6515f338ef69d251bfab
1,591
cpp
C++
v1/Lewcid/OSBinding_SDL.cpp
Jess-Stuart/FreedGames
a8f1dcb9daa8063740f9875a1615500ad8ca9498
[ "BSL-1.0" ]
2
2020-12-05T08:35:17.000Z
2021-03-06T20:32:28.000Z
v1/Lewcid/OSBinding_SDL.cpp
Jess-Stuart/FreedGames
a8f1dcb9daa8063740f9875a1615500ad8ca9498
[ "BSL-1.0" ]
1
2021-04-05T21:58:09.000Z
2021-04-06T00:18:26.000Z
v1/Lewcid/OSBinding_SDL.cpp
Jess-Stuart/FreedGames
a8f1dcb9daa8063740f9875a1615500ad8ca9498
[ "BSL-1.0" ]
3
2021-04-02T03:55:53.000Z
2021-04-09T20:18:04.000Z
#include <stdio.h> #include <math.h> #include <time.h> #ifdef WIN32 #include <windows.h> #include <iostream.h> #include <stdlib.h> #include <time.h> #include <stdio.h> #include <math.h> #include <fstream.h> void SetRandomSeed() { LARGE_INTEGER la; QueryPerformanceCounter( &la ); srand( (unsigned int)la.QuadPart ); } void ShowMessage(char* mess, char* title) { // SDL_WM_SetCaption(mess, 0); // MessageBox(0, mess, title, MB_OK); } double LC_GetCurrentTime() { double val = clock(); return (val / 1000.0); } #define UseMessageBoxForIntro false #else #define UseMessageBoxForIntro false // put the Mac Carbon headers here #include <OpenGL/gl.h> #include <OpenGL/glu.h> #include <GLUT/glut.h> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <math.h> void SetRandomSeed() { srand( clock() ); } void ConvertCToPascalString(char* from, unsigned char* to) { int i=0; for(i=0; from[i]; i++) { to[i+1] = from[i]; } to[0] = i; } void ShowMessage(char* mess, char* title) { unsigned char buff1[200], buff2[200]; ConvertCToPascalString( ((char*)mess), buff1); ConvertCToPascalString( ((char*)title), buff2); short res; StandardAlert(kAlertNoteAlert, buff2, buff1, 0, &res); } /* void ShowMessage(char* mess, char* title) { printf("\n%s\n", title); for (int i=0; title[i]; i++) printf("-"); printf("\n%s\n\n", mess); } */ double LC_GetCurrentTime() { double val = clock(); return (val / 100.0); } #endif
16.747368
59
0.610937
Jess-Stuart
67ddc59593676eb432301ab3fd9bbe98badc48e0
612
hpp
C++
include/vsim/env/rigid_body.hpp
malasiot/vsim
2a69e27364bab29194328af3d050e34f907e226b
[ "MIT" ]
null
null
null
include/vsim/env/rigid_body.hpp
malasiot/vsim
2a69e27364bab29194328af3d050e34f907e226b
[ "MIT" ]
null
null
null
include/vsim/env/rigid_body.hpp
malasiot/vsim
2a69e27364bab29194328af3d050e34f907e226b
[ "MIT" ]
null
null
null
#ifndef __VSIM_RIGID_BODY_HPP__ #define __VSIM_RIGID_BODY_HPP__ #include <string> #include <vector> #include <memory> #include <Eigen/Core> #include <vsim/env/scene_fwd.hpp> #include <vsim/env/pose.hpp> #include <vsim/env/base_element.hpp> namespace vsim { class RigidBody ; typedef std::shared_ptr<RigidBody> BodyPtr ; // class defining a rigid body class RigidBody: public BaseElement { public: RigidBody() = default ; public: std::vector<CollisionShapePtr> shapes_ ; Pose pose_ ; float mass_ ; Eigen::Vector3f velocity_, angular_velocity_ ; NodePtr visual_ ; }; } #endif
15.3
50
0.72549
malasiot
67e2738ca714e1aef79e4f33a4df272ff188782e
3,473
hpp
C++
src/libs/optframe/src/OptFrame/MultiMoveCost.hpp
fellipessanha/LMRRC-Team-AIDA
8076599427df0e35890caa7301972a53ae327edb
[ "MIT" ]
1
2021-08-19T13:31:29.000Z
2021-08-19T13:31:29.000Z
src/libs/optframe/src/OptFrame/MultiMoveCost.hpp
fellipessanha/LMRRC-Team-AIDA
8076599427df0e35890caa7301972a53ae327edb
[ "MIT" ]
null
null
null
src/libs/optframe/src/OptFrame/MultiMoveCost.hpp
fellipessanha/LMRRC-Team-AIDA
8076599427df0e35890caa7301972a53ae327edb
[ "MIT" ]
null
null
null
// OptFrame - Optimization Framework // Copyright (C) 2009-2015 // http://optframe.sourceforge.net/ // // This file is part of the OptFrame optimization framework. This framework // is free software; you can redistribute it and/or modify it under the // terms of the GNU Lesser General Public License v3 as published by the // Free Software Foundation. // This framework 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 v3 for more details. // You should have received a copy of the GNU Lesser General Public License v3 // along with this library; see the file COPYING. If not, write to the Free // Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, // USA. #ifndef OPTFRAME_MULTI_MOVE_COST_HPP_ #define OPTFRAME_MULTI_MOVE_COST_HPP_ #include <cstdlib> #include <iostream> #include <cmath> #include "Component.hpp" #include "BaseConcepts.hpp" #include "Evaluation.hpp" #include "MoveCost.hpp" using namespace std; namespace optframe { //// more than 'objval' we need to ensure arithmetics here... TODO: see that (same as Evaluation) template<optframe::objval ObjType = evtype, XEvaluation XEv = Evaluation<ObjType>> //template<class ObjType = evtype, XEvaluation XEv = Evaluation<ObjType>> class MultiMoveCost: public Component { protected: vector<MoveCost<ObjType, XEv>*> vmc; public: explicit MultiMoveCost(vector<MoveCost<>*> _vmc) : vmc(_vmc) { } MultiMoveCost(const MultiMoveCost<>& mc) : vmc(mc.vmc) { } virtual ~MultiMoveCost() { } int size() const { return vmc.size(); } bool hasCost(int k) const { return vmc[k]; } bool isEstimated(int k) const { return vmc[k]->estimated; } const vector<pair<ObjType, ObjType> >& getAlternativeCosts(int k) const { return vmc[k]->alternatives; } ObjType getObjFunctionCost(int k) const { return vmc[k]->objFunction; } ObjType getInfMeasureCost(int k) const { return vmc[k]->infMeasure; } void addAlternativeCost(const pair<ObjType, ObjType>& alternativeCost, int k) { vmc[k]->alternatives.push_back(alternativeCost); } void setAlternativeCosts(const vector<pair<ObjType, ObjType> >& alternativeCosts, int k) { vmc[k]->alternatives = alternativeCosts; } void setObjFunctionCost(ObjType obj, int k) { vmc[k]->objFunction = obj; } void setInfMeasureCost(ObjType inf, int k) { vmc[k]->infMeasure = inf; } ObjType cost(int k) const { return vmc[k]->cost(); } static string idComponent() { return "OptFrame:MultiMoveCost"; } virtual string id() const { return idComponent(); } virtual void print() const { cout << fixed; // disable scientific notation cout << "MultiMoveCost for " << size() << " objectives:" << endl; for(unsigned i=0; i<vmc.size(); i++) if(vmc[i]) vmc[i]->print(); else cout << "NO COST" << endl; } virtual MultiMoveCost<>& operator=(const MultiMoveCost<>& mmc) { if (&mmc == this) // auto ref check return *this; vmc = mmc.vmc; // TODO fix: this should handle some local instances, for the future... return *this; } virtual MultiMoveCost<>& clone() const { return *new MultiMoveCost<>(*this); } }; #ifndef NDEBUG struct optframe_debug_test_multimove_cost { MultiMoveCost<> testMoveCost; }; #endif } // namespace optframe #endif /*OPTFRAME_MULTI_MOVE_COST_HPP_*/
21.306748
97
0.708033
fellipessanha
67e31c601d860a04539d998362e8d1659aee1477
3,871
hpp
C++
include/wprofile.hpp
aegistudio/wdedup
686af391347418991260d421f33316171047fe95
[ "MIT" ]
null
null
null
include/wprofile.hpp
aegistudio/wdedup
686af391347418991260d421f33316171047fe95
[ "MIT" ]
null
null
null
include/wprofile.hpp
aegistudio/wdedup
686af391347418991260d421f33316171047fe95
[ "MIT" ]
null
null
null
/* Copyright © 2019 Haoran Luo * * 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. */ /** * @file wprofile.hpp * @author Haoran Luo * @brief wdedup Profile header. * * This file describes the profile structures. Profiles are stored in a * (logically) sorted-by-word, FIFO and immutable file. * * According to previous studying of sorted table implementation, multiple * variance of physical implementation is observed, and which one excels * has not been verified. So the profiler file is designed as a virtual * interface, and provided as wdedup::Config item. */ #pragma once #include "wtypes.hpp" #include <string> namespace wdedup { /** * @brief Defines the profile item in profile input and output. * * Various implementation must customize their interfaces to return such * kind of items. */ struct ProfileItem { /// Current recorded word. std::string word; /// Whether this word has been repeated. bool repeated; /// The first occurence of the word. /// If repeated is true, this field should be ignored by the /// scanning algorithms. fileoff_t occur; /// Construct a repeated item. ProfileItem(std::string word) noexcept: word(std::move(word)), repeated(true), occur(0) {} /// Construct a single occurence item. ProfileItem(std::string word, fileoff_t occur) noexcept: word(std::move(word)), repeated(false), occur(occur) {} /// Move constructor of a profile item. ProfileItem(ProfileItem&& item) noexcept: word(std::move(item.word)), repeated(item.repeated), occur(item.occur) {} }; /// @brief Defines the virtual read interface of profile. struct ProfileInput { /// Virtual destructor for pure virtual classes. virtual ~ProfileInput() noexcept {}; /// Test whether there's content in the file. virtual bool empty() const noexcept = 0; /// Peeking the head profileItem from the input table. /// If there's no more content in the table, the content /// returned by the table will be undefined. virtual const ProfileItem& peek() const noexcept = 0; /// Pop the head profileItem from the input table. /// If there's no more content in the table, popping /// from the table will cause exception to be thrown. virtual ProfileItem pop() throw (wdedup::Error) = 0; }; /// @brief Defines the virtual write interface of profile. struct ProfileOutput { /// Virtual destructor for pure virtual classes. virtual ~ProfileOutput() noexcept {}; /// Push content to the profile output. /// Exception will be thrown if there's I/O error on the /// underlying (append-only) files. virtual void push(ProfileItem) throw (wdedup::Error) = 0; /// Indicates that this is the end of profile output. /// The size of the generated file will be collected and /// return to the caller. virtual size_t close() throw (wdedup::Error) = 0; }; } // namespace wdedup
35.513761
75
0.727977
aegistudio
67e538aa22d0282fc0866f9438d1c45e28b6a41e
2,050
cpp
C++
tests/transport/test_send_multi.cpp
boeschf/GHEX-OLD
a1c8e12e50b4781cc6d0b0314f17bd3f91ac3769
[ "BSD-3-Clause" ]
null
null
null
tests/transport/test_send_multi.cpp
boeschf/GHEX-OLD
a1c8e12e50b4781cc6d0b0314f17bd3f91ac3769
[ "BSD-3-Clause" ]
null
null
null
tests/transport/test_send_multi.cpp
boeschf/GHEX-OLD
a1c8e12e50b4781cc6d0b0314f17bd3f91ac3769
[ "BSD-3-Clause" ]
null
null
null
#include <ghex/transport_layer/callback_communicator.hpp> #include <ghex/transport_layer/mpi/communicator.hpp> #include <iostream> #include <iomanip> #include <gtest/gtest.h> template<typename Comm, typename Alloc> using callback_comm_t = gridtools::ghex::tl::callback_communicator<Comm,Alloc>; //using callback_comm_t = gridtools::ghex::tl::callback_communicator_ts<Comm,Alloc>; const int SIZE = 4000000; int mpi_rank; //#define GHEX_TEST_COUNT_ITERATIONS TEST(transport, send_multi) { { int size; MPI_Comm_size(MPI_COMM_WORLD, &size); EXPECT_EQ(size, 4); } MPI_Comm_rank(MPI_COMM_WORLD, &mpi_rank); MPI_Barrier(MPI_COMM_WORLD); using comm_type = gridtools::ghex::tl::communicator<gridtools::ghex::tl::mpi_tag>; comm_type comm; using allocator_type = std::allocator<unsigned char>; using smsg_type = gridtools::ghex::tl::shared_message_buffer<allocator_type>; callback_comm_t<comm_type,allocator_type> cb_comm(comm); if (mpi_rank == 0) { smsg_type smsg{SIZE}; int * data = smsg.data<int>(); for (int i = 0; i < SIZE/(int)sizeof(int); ++i) { data[i] = i; } std::array<int, 3> dsts = {1,2,3}; cb_comm.send_multi(smsg, dsts, 42); #ifdef GHEX_TEST_COUNT_ITERATIONS int c = 0; #endif while (cb_comm.progress()) { #ifdef GHEX_TEST_COUNT_ITERATIONS c++; #endif } EXPECT_EQ(smsg.use_count(), 1); #ifdef GHEX_TEST_COUNT_ITERATIONS std::cout << "\n***********\n"; std::cout << "*" << std::setw(8) << c << " *\n"; std::cout << "***********\n"; #endif } else { gridtools::ghex::tl::message_buffer<> rmsg{SIZE}; auto fut = comm.recv(rmsg, 0, 42); fut.wait(); bool ok = true; for (int i = 0; i < (int)rmsg.size()/(int)sizeof(int); ++i) { int * data = rmsg.data<int>(); if ( data[i] != i ) ok = false; } EXPECT_TRUE(ok); } EXPECT_FALSE(cb_comm.progress()); }
23.295455
86
0.603415
boeschf
67e9695533fd6b9311054129b64516ea00c82d5f
2,172
hpp
C++
raintk/RainTkRow.hpp
preet/raintk
9cbd596d9cec9aca7d3bbf3994a2931bac87e98d
[ "Apache-2.0" ]
4
2016-05-03T20:47:51.000Z
2021-04-15T09:33:34.000Z
raintk/RainTkRow.hpp
preet/raintk
9cbd596d9cec9aca7d3bbf3994a2931bac87e98d
[ "Apache-2.0" ]
null
null
null
raintk/RainTkRow.hpp
preet/raintk
9cbd596d9cec9aca7d3bbf3994a2931bac87e98d
[ "Apache-2.0" ]
1
2017-07-26T07:31:35.000Z
2017-07-26T07:31:35.000Z
/* Copyright (C) 2015 Preet Desai (preet.desai@gmail.com) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #ifndef RAINTK_ROW_HPP #define RAINTK_ROW_HPP #include <map> #include <list> #include <raintk/RainTkWidget.hpp> namespace raintk { class Row : public Widget { public: using base_type = raintk::Widget; enum class LayoutDirection { LeftToRight, RightToLeft }; Row(ks::Object::Key const &key, Scene* scene, shared_ptr<Widget> parent); void Init(ks::Object::Key const &, shared_ptr<Row> const &); ~Row(); void AddChild(shared_ptr<Widget> const &child) override; void RemoveChild(shared_ptr<Widget> const &child) override; // Properties Property<float> spacing{ 0.0f }; Property<float> children_width{ 0.0f }; Property<float> children_height{ 0.0f }; Property<LayoutDirection> layout_direction{ LayoutDirection::LeftToRight }; protected: void onSpacingChanged(); void onLayoutDirectionChanged(); void onChildDimsChanged(); Id m_cid_spacing; Id m_cid_layout_direction; private: void update() override; struct Item { Widget* widget; Id cid_width; Id cid_height; }; // TODO replace list if performance is an issue std::list<Item> m_list_items; std::map<Id,std::list<Item>::iterator> m_lkup_id_item_it; }; } #endif // RAINTK_ROW_HPP
23.868132
75
0.609576
preet
67f810d0c8717bb0d3ab7d45802bde1ee0e9c04b
3,460
cc
C++
src/cameras/camera.cc
BlurryLight/DiRender
1ea55ff8a10bb76993ce9990b200ee8ed173eb3e
[ "MIT" ]
20
2020-06-28T03:55:40.000Z
2022-03-08T06:00:31.000Z
src/cameras/camera.cc
BlurryLight/DiRender
1ea55ff8a10bb76993ce9990b200ee8ed173eb3e
[ "MIT" ]
null
null
null
src/cameras/camera.cc
BlurryLight/DiRender
1ea55ff8a10bb76993ce9990b200ee8ed173eb3e
[ "MIT" ]
1
2020-06-29T08:47:21.000Z
2020-06-29T08:47:21.000Z
// // Created by panda on 2021/2/26. // #include <cameras/camera.h> #include <cores/scene.h> using namespace DR; void Film::write_ppm(const std::string &filename) { auto fp = std::unique_ptr<FILE, decltype(&fclose)>( fopen(filename.c_str(), "wb"), &fclose); (void)fprintf(fp.get(), "P6\n%d %d\n255\n", height, width); for (uint i = 0; i < width * height; ++i) { static unsigned char color[3]; color[0] = (unsigned char)(255 * std::pow(clamp(0.0f, 1.0f, framebuffer_[i].x), 0.6f)); color[1] = (unsigned char)(255 * std::pow(clamp(0.0f, 1.0f, framebuffer_[i].y), 0.6f)); color[2] = (unsigned char)(255 * std::pow(clamp(0.0f, 1.0f, framebuffer_[i].z), 0.6f)); fwrite(color, 1, 3, fp.get()); } } Transform Camera::look_at(Point3f origin, Vector3f WorldUp, Vector3f target) { auto cam_origin = static_cast<Vector3f>(origin); auto cam_target = (static_cast<Vector3f>(origin) - target).normalize(); auto cam_right = cross(WorldUp.normalize(), cam_target).normalize(); auto cam_up = cross(cam_target, cam_right).normalize(); Matrix4 part2 = Matrix4(1.0f); part2.m[0][3] = -cam_origin[0]; part2.m[1][3] = -cam_origin[1]; part2.m[2][3] = -cam_origin[2]; Matrix4 part1 = Matrix4(1.0f); part1.m[0][0] = cam_right[0]; part1.m[0][1] = cam_right[1]; part1.m[0][2] = cam_right[2]; part1.m[1][0] = cam_up[0]; part1.m[1][1] = cam_up[1]; part1.m[1][2] = cam_up[2]; part1.m[2][0] = cam_target[0]; part1.m[2][1] = cam_target[1]; part1.m[2][2] = cam_target[2]; return Transform(part1 * part2); } Camera::Camera(Point3f origin, Vector3f WorldUp, Vector3f target, float fov, uint height, uint width, observer_ptr<Scene> scene, bool gamma) : position_(origin), fov_(fov), aspect_ratio_(float(width) / height), scene_(scene) { auto view_trans = Camera::look_at(origin, WorldUp, target); auto [trans, trans_inv] = scene->trans_table.get_tf_and_inv(view_trans); view_trans_ = trans; view_trans_inverse_ = trans_inv; film_ptr_ = std::make_unique<Film>(width, height, gamma); } void Film::write(const std::string &filename, PicType type, uint spp) const { std::unique_ptr<uint8_t[]> data{ new uint8_t[height * width * 3]}; // don't support alpha & HDR float inv_spp = 1.0f / float(spp); for (uint i = 0; i < height * width; i++) { for (uint j = 0; j < 3; j++) { uint8_t tmp = 0; static constexpr float gamma_index = 1 / 2.2f; // Tone mapping auto AcesFilmicToneMapping = [](float color) { float a = 2.51f; float b = 0.03f; float c = 2.43f; float d = 0.59f; float e = 0.14f; float new_cl = clamp(0.0f, 1.0f, (color * (a * color + b)) / (color * (c * color + d) + e)); return new_cl; }; float value = tone_mapping_ ? AcesFilmicToneMapping(framebuffer_[i][j] * inv_spp) : framebuffer_[i][j] * inv_spp; if (gamma_) { tmp = static_cast<uint8_t>( std::pow(clamp(0.0f, kOneMinusEps, value), gamma_index) * 255); } else { tmp = static_cast<uint8_t>(clamp(0.0f, kOneMinusEps, value) * 255); } data[3 * i + j] = tmp; } } Image img(data.get(), height, width, type, 3); if (!img.write_image(filename, false)) { std::cerr << "Error: Writing " + filename << "failed" << std::endl; } }
34.257426
119
0.592486
BlurryLight
67fcac273c5d64e4b5d88d8de1e0ade6c11005d5
123
hpp
C++
src/FSNG/Forge/Ticket.hpp
ChristofferGreen/Forsoning
838b35587c00227f2f5cdd91ba78bc63b76835fe
[ "BSD-2-Clause" ]
null
null
null
src/FSNG/Forge/Ticket.hpp
ChristofferGreen/Forsoning
838b35587c00227f2f5cdd91ba78bc63b76835fe
[ "BSD-2-Clause" ]
null
null
null
src/FSNG/Forge/Ticket.hpp
ChristofferGreen/Forsoning
838b35587c00227f2f5cdd91ba78bc63b76835fe
[ "BSD-2-Clause" ]
null
null
null
#pragma once namespace FSNG { using Ticket = uint64_t; inline Ticket InvalidTicket = 0; inline Ticket FirstTicket = 1; }
17.571429
32
0.747967
ChristofferGreen
67fd5c5d44da68fae86afeac9f5450e67686a413
449
cxx
C++
src/Comment.cxx
astrorigin/html5xx
cbaaeb232597a713630df7425752051036cf0cb2
[ "MIT" ]
null
null
null
src/Comment.cxx
astrorigin/html5xx
cbaaeb232597a713630df7425752051036cf0cb2
[ "MIT" ]
null
null
null
src/Comment.cxx
astrorigin/html5xx
cbaaeb232597a713630df7425752051036cf0cb2
[ "MIT" ]
null
null
null
/* * */ #include "Comment.hxx" using namespace std; namespace html { string Comment::toString() const { string s = m_text; size_t found, pos = 0; const string ind = indent(); const string nl = "\n" + ind + ' '; while ((found = s.find('\n', pos)) != string::npos) { s.replace(found, 1, nl); pos = found + nl.length(); } return ind + "<!-- " + s + " -->\n"; } } // end namespace html // vi: set ai et sw=2 sts=2 ts=2 :
14.966667
55
0.545657
astrorigin
db0ac9ea061a61622c3a25112e13c796699f3bc1
3,127
cpp
C++
src/native/QmlNet/QmlNet/types/NetSignalInfo.cpp
joachim-egger/Qml.Net
53525c0ba0f135a6b16f47b09ad62b349d54e844
[ "MIT" ]
null
null
null
src/native/QmlNet/QmlNet/types/NetSignalInfo.cpp
joachim-egger/Qml.Net
53525c0ba0f135a6b16f47b09ad62b349d54e844
[ "MIT" ]
null
null
null
src/native/QmlNet/QmlNet/types/NetSignalInfo.cpp
joachim-egger/Qml.Net
53525c0ba0f135a6b16f47b09ad62b349d54e844
[ "MIT" ]
null
null
null
#include <QmlNet/types/NetSignalInfo.h> #include <QmlNet/qml/NetValueMetaObjectPacker.h> #include <QmlNetUtilities.h> NetSignalInfo::NetSignalInfo(QSharedPointer<NetTypeInfo> parentType, QString name) : _parentType(parentType), _name(name) { } QSharedPointer<NetTypeInfo> NetSignalInfo::getParentType() { return _parentType; } QString NetSignalInfo::getName() { return _name; } void NetSignalInfo::addParameter(NetVariantTypeEnum type) { if(type == NetVariantTypeEnum_Invalid) return; _parameters.append(type); } int NetSignalInfo::getParameterCount() { return _parameters.size(); } NetVariantTypeEnum NetSignalInfo::getParameter(int index) { if(index < 0) return NetVariantTypeEnum_Invalid; if(index >= _parameters.length()) return NetVariantTypeEnum_Invalid; return _parameters.at(index); } QString NetSignalInfo::getSignature() { QString signature = _name; signature.append("("); for(int parameterIndex = 0; parameterIndex <= _parameters.size() - 1; parameterIndex++) { if(parameterIndex > 0) { signature.append(","); } signature.append(NetMetaValueQmlType(_parameters.at(parameterIndex))); } signature.append(")"); return signature; } QString NetSignalInfo::getSlotSignature() { QString signature = _name; signature.append("_internal_slot_for_net_del("); if(_parameters.size() > 0) { for(int parameterIndex = 0; parameterIndex <= _parameters.size() - 1; parameterIndex++) { if(parameterIndex > 0) { signature.append(","); } signature.append(NetMetaValueQmlType(_parameters.at(parameterIndex))); } } signature.append(")"); return signature; } extern "C" { Q_DECL_EXPORT NetSignalInfoContainer* signal_info_create(NetTypeInfoContainer* parentTypeContainer, LPWSTR name) { NetSignalInfoContainer* result = new NetSignalInfoContainer(); NetSignalInfo* instance = new NetSignalInfo(parentTypeContainer->netTypeInfo, QString::fromUtf16((const char16_t*)name)); result->signal = QSharedPointer<NetSignalInfo>(instance); return result; } Q_DECL_EXPORT void signal_info_destroy(NetSignalInfoContainer* container) { delete container; } Q_DECL_EXPORT NetTypeInfoContainer* signal_info_getParentType(NetSignalInfoContainer* container) { NetTypeInfoContainer* result = new NetTypeInfoContainer{container->signal->getParentType()}; return result; } Q_DECL_EXPORT QmlNetStringContainer* signal_info_getName(NetSignalInfoContainer* container) { QString result = container->signal->getName(); return createString(result); } Q_DECL_EXPORT void signal_info_addParameter(NetSignalInfoContainer* container, NetVariantTypeEnum type) { container->signal->addParameter(type); } Q_DECL_EXPORT int signal_info_getParameterCount(NetSignalInfoContainer* container) { return container->signal->getParameterCount(); } Q_DECL_EXPORT NetVariantTypeEnum signal_info_getParameter(NetSignalInfoContainer* container, int index) { return container->signal->getParameter(index); } }
25.422764
125
0.73361
joachim-egger
db13a60db28ce26d15f3a779921aeb2079bc39c8
9,074
cpp
C++
src/sutil/sutil.cpp
kevinkingo/OptixRenderer
dbfbabfa7a96527fed84878c0d34eaca2ee8fae7
[ "MIT" ]
41
2020-06-26T03:58:23.000Z
2022-02-20T07:45:11.000Z
src/sutil/sutil.cpp
A-guridi/thesis_render
c03b5b988c41a2d8c4b774037ff4039e03501b87
[ "MIT" ]
5
2020-12-05T13:39:17.000Z
2022-03-23T01:27:32.000Z
src/sutil/sutil.cpp
A-guridi/thesis_render
c03b5b988c41a2d8c4b774037ff4039e03501b87
[ "MIT" ]
20
2020-06-27T22:18:51.000Z
2022-03-01T23:28:22.000Z
/* * Copyright (c) 2016, NVIDIA CORPORATION. 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 NVIDIA CORPORATION 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 ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // Note: wglew.h has to be included before sutil.h on Windows #include <sutil/sutil.h> //#include <sutil/PPMLoader.h> #include <sampleConfig.h> #include <optixu/optixu_math_namespace.h> #include <cstdlib> #include <cstring> #include <iostream> #include <fstream> #include <stdint.h> #if defined(_WIN32) # ifndef WIN32_LEAN_AND_MEAN # define WIN32_LEAN_AND_MEAN 1 # endif # include<windows.h> # include<mmsystem.h> #else // Apple and Linux both use this # include<sys/time.h> # include <unistd.h> # include <dirent.h> #endif using namespace optix; namespace { // Global variables for GLUT display functions RTcontext g_context = 0; RTbuffer g_image_buffer = 0; void checkBuffer( RTbuffer buffer ) { // Check to see if the buffer is two dimensional unsigned int dimensionality; RT_CHECK_ERROR( rtBufferGetDimensionality(buffer, &dimensionality) ); if (2 != dimensionality) throw Exception( "Attempting to display non-2D buffer" ); // Check to see if the buffer is of type float{1,3,4} or uchar4 RTformat format; RT_CHECK_ERROR( rtBufferGetFormat(buffer, &format) ); if( RT_FORMAT_FLOAT != format && RT_FORMAT_FLOAT4 != format && RT_FORMAT_FLOAT3 != format && RT_FORMAT_UNSIGNED_BYTE4 != format ) throw Exception( "Attempting to diaplay buffer with format not float, float3, float4, or uchar4"); } bool dirExists( const char* path ) { #if defined(_WIN32) DWORD attrib = GetFileAttributes( path ); return (attrib != INVALID_FILE_ATTRIBUTES) && (attrib & FILE_ATTRIBUTE_DIRECTORY); #else DIR* dir = opendir( path ); if( dir == NULL ) return false; closedir(dir); return true; #endif } } // end anonymous namespace void sutil::reportErrorMessage( const char* message ) { std::cerr << "OptiX Error: '" << message << "'\n"; #if defined(_WIN32) && defined(RELEASE_PUBLIC) { char s[2048]; sprintf( s, "OptiX Error: %s", message ); MessageBox( 0, s, "OptiX Error", MB_OK|MB_ICONWARNING|MB_SYSTEMMODAL ); } #endif } void sutil::handleError( RTcontext context, RTresult code, const char* file, int line) { const char* message; char s[2048]; rtContextGetErrorString(context, code, &message); sprintf(s, "%s\n(%s:%d)", message, file, line); reportErrorMessage( s ); } const char* sutil::samplesDir() { static char s[512]; // Allow for overrides. const char* dir = getenv( "OPTIX_SAMPLES_SDK_DIR" ); if (dir) { strcpy(s, dir); return s; } // Return hardcoded path if it exists. if( dirExists( SAMPLES_DIR ) ) return SAMPLES_DIR; // Last resort. return "."; } const char* sutil::samplesPTXDir() { static char s[512]; // Allow for overrides. const char* dir = getenv( "OPTIX_SAMPLES_SDK_PTX_DIR" ); if (dir) { strcpy(s, dir); return s; } // Return hardcoded path if it exists. if( dirExists(SAMPLES_PTX_DIR) ) return SAMPLES_PTX_DIR; // Last resort. return "."; } optix::Buffer sutil::createOutputBuffer( optix::Context context, RTformat format, unsigned width, unsigned height, bool use_pbo ) { optix::Buffer buffer; buffer = context->createBuffer( RT_BUFFER_OUTPUT, format, width, height ); return buffer; } optix::GeometryInstance sutil::createOptiXGroundPlane( optix::Context context, const std::string& parallelogram_ptx, const optix::Aabb& aabb, optix::Material material, float scale ) { optix::Geometry parallelogram = context->createGeometry(); parallelogram->setPrimitiveCount( 1u ); parallelogram->setBoundingBoxProgram( context->createProgramFromPTXFile( parallelogram_ptx, "bounds" ) ); parallelogram->setIntersectionProgram( context->createProgramFromPTXFile( parallelogram_ptx, "intersect" ) ); const float extent = scale*fmaxf( aabb.extent( 0 ), aabb.extent( 2 ) ); const float3 anchor = make_float3( aabb.center(0) - 0.5f*extent, aabb.m_min.y - 0.001f*aabb.extent( 1 ), aabb.center(2) - 0.5f*extent ); float3 v1 = make_float3( 0.0f, 0.0f, extent ); float3 v2 = make_float3( extent, 0.0f, 0.0f ); const float3 normal = normalize( cross( v1, v2 ) ); float d = dot( normal, anchor ); v1 *= 1.0f / dot( v1, v1 ); v2 *= 1.0f / dot( v2, v2 ); float4 plane = make_float4( normal, d ); parallelogram["plane"]->setFloat( plane ); parallelogram["v1"]->setFloat( v1 ); parallelogram["v2"]->setFloat( v2 ); parallelogram["anchor"]->setFloat( anchor ); optix::GeometryInstance instance = context->createGeometryInstance( parallelogram, &material, &material + 1 ); return instance; } void sutil::calculateCameraVariables( float3 eye, float3 lookat, float3 up, float fov, float aspect_ratio, float3& U, float3& V, float3& W, bool fov_is_vertical ) { float ulen, vlen, wlen; W = lookat - eye; // Do not normalize W -- it implies focal length wlen = length( W ); U = normalize( cross( W, up ) ); V = normalize( cross( U, W ) ); if ( fov_is_vertical ) { vlen = wlen * tanf( 0.5f * fov * M_PIf / 180.0f ); V *= vlen; ulen = vlen * aspect_ratio; U *= ulen; } else { ulen = wlen * tanf( 0.5f * fov * M_PIf / 180.0f ); U *= ulen; vlen = ulen / aspect_ratio; V *= vlen; } } void sutil::parseDimensions( const char* arg, int& width, int& height ) { // look for an 'x': <width>x<height> size_t width_end = strchr( arg, 'x' ) - arg; size_t height_begin = width_end + 1; if ( height_begin < strlen( arg ) ) { // find the beginning of the height string/ const char *height_arg = &arg[height_begin]; // copy width to null-terminated string char width_arg[32]; strncpy( width_arg, arg, width_end ); width_arg[width_end] = '\0'; // terminate the width string width_arg[width_end] = '\0'; width = atoi( width_arg ); height = atoi( height_arg ); return; } throw Exception( "Failed to parse width, heigh from string '" + std::string( arg ) + "'" ); } double sutil::currentTime() { #if defined(_WIN32) // inv_freq is 1 over the number of ticks per second. static double inv_freq; static bool freq_initialized = 0; static bool use_high_res_timer = 0; if(!freq_initialized) { LARGE_INTEGER freq; use_high_res_timer = ( QueryPerformanceFrequency( &freq ) != 0 ); inv_freq = 1.0/freq.QuadPart; freq_initialized = 1; } if (use_high_res_timer) { LARGE_INTEGER c_time; if( QueryPerformanceCounter( &c_time ) ) return c_time.QuadPart*inv_freq; else throw Exception( "sutil::currentTime: QueryPerformanceCounter failed" ); } return static_cast<double>( timeGetTime() ) * 1.0e-3; #else struct timeval tv; if( gettimeofday( &tv, 0 ) ) throw Exception( "sutil::urrentTime(): gettimeofday failed!\n" ); return tv.tv_sec+ tv.tv_usec * 1.0e-6; #endif } void sutil::sleep( int seconds ) { #if defined(_WIN32) Sleep( seconds * 1000 ); #else ::sleep( seconds ); #endif }
28.092879
140
0.642164
kevinkingo
db141668a5bf95cc0b6e79401c7c9bb54f844cf3
3,990
cc
C++
src/file/classicopts.cc
aaszodi/multovl
00c5b74e65c7aa37cddea8b2ae277fe67fbc59a8
[ "MIT" ]
2
2018-03-06T02:36:25.000Z
2020-01-13T10:55:35.000Z
src/file/classicopts.cc
aaszodi/multovl
00c5b74e65c7aa37cddea8b2ae277fe67fbc59a8
[ "MIT" ]
null
null
null
src/file/classicopts.cc
aaszodi/multovl
00c5b74e65c7aa37cddea8b2ae277fe67fbc59a8
[ "MIT" ]
null
null
null
/* <LICENSE> License for the MULTOVL multiple genomic overlap tools Copyright (c) 2007-2012, Dr Andras Aszodi, Campus Science Support Facilities GmbH (CSF), Dr-Bohr-Gasse 3, A-1030 Vienna, Austria, Europe. 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 Campus Science Support Facilities GmbH nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. </LICENSE> */ // == MODULE classicopts.cc == // -- Standard headers -- #include <algorithm> // -- Own header -- #include "classicopts.hh" #include "thirdparty.h" // -- Boost headers -- #include "boost/algorithm/string/case_conv.hpp" // == Implementation == namespace multovl { ClassicOpts::ClassicOpts(): MultovlOptbase() { add_option<std::string>("source", &_source, "multovl", "Source field in GFF output", 's'); add_option<std::string>("outformat", &_outformat, "GFF", "Output format {BED,GFF}, case-insensitive, default GFF", 'f'); add_option<std::string>("save", &_saveto, "", "Save program data to archive file, default: do not save"); add_option<std::string>("load", &_loadfrom, "", "Load program data from archive file, default: do not load"); } bool ClassicOpts::check_variables() { MultovlOptbase::check_variables(); // canonicalize the output format: currently BED and GFF are accepted boost::algorithm::to_upper(_outformat); if (_outformat != "BED" && _outformat != "GFF") _outformat = "GFF"; // default // there must be at least 1 positional param // unless --load has been set in which case // all input comes from the archive unsigned int filecnt = pos_opts().size(); if (_loadfrom == "" && filecnt < 1) { add_error("Must specify at least one input file"); } return (!error_status()); } std::string ClassicOpts::param_str() const { std::string outstr = MultovlOptbase::param_str(); outstr += " -s " + _source + " -f " + _outformat; if (_loadfrom != "") outstr += " --load " + _loadfrom; if (_saveto != "") outstr += " --save " + _saveto; return outstr; } std::ostream& ClassicOpts::print_help(std::ostream& out) const { out << "Multiple Chromosome / Multiple Region Overlaps" << std::endl << "Usage: multovl [options] [<infile1> [ <infile2> ... ]]" << std::endl << "Accepted input file formats: BED, GFF/GTF" ; if (config_have_bamtools()) { out << ", BAM"; } out << " (detected from extension)" << std::endl << "<infileX> arguments are ignored if --load is set" << std::endl << "Output goes to stdout, select format with the -f option" << std::endl; Polite::print_help(out); return out; } } // namespace multovl
35.625
79
0.704261
aaszodi
db1448e88f99dd32970373dfb5ff0ee103d6ed9f
40,214
cpp
C++
GCG_Source.build/module.requests.status_codes.cpp
Pckool/GCG
cee786d04ea30f3995e910bca82635f442b2a6a8
[ "MIT" ]
null
null
null
GCG_Source.build/module.requests.status_codes.cpp
Pckool/GCG
cee786d04ea30f3995e910bca82635f442b2a6a8
[ "MIT" ]
null
null
null
GCG_Source.build/module.requests.status_codes.cpp
Pckool/GCG
cee786d04ea30f3995e910bca82635f442b2a6a8
[ "MIT" ]
null
null
null
/* Generated code for Python source for module 'requests.status_codes' * created by Nuitka version 0.5.28.2 * * This code is in part copyright 2017 Kay Hayen. * * 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 "nuitka/prelude.h" #include "__helpers.h" /* The _module_requests$status_codes is a Python object pointer of module type. */ /* Note: For full compatibility with CPython, every module variable access * needs to go through it except for cases where the module cannot possibly * have changed in the mean time. */ PyObject *module_requests$status_codes; PyDictObject *moduledict_requests$status_codes; /* The module constants used, if any. */ extern PyObject *const_str_plain_status_codes; static PyObject *const_tuple_str_plain_LookupDict_tuple; static PyObject *const_str_plain__codes; extern PyObject *const_str_plain_ModuleSpec; extern PyObject *const_str_plain___spec__; extern PyObject *const_str_plain___package__; extern PyObject *const_str_chr_47; extern PyObject *const_str_plain_requests; extern PyObject *const_int_pos_1; extern PyObject *const_str_plain___file__; static PyObject *const_tuple_tuple_str_chr_92_str_chr_47_tuple_tuple; extern PyObject *const_str_plain_upper; extern PyObject *const_str_plain_code; extern PyObject *const_str_plain_codes; static PyObject *const_str_digest_840f3e0b846ec96891b7f18eb56afcd8; extern PyObject *const_tuple_str_chr_92_str_chr_47_tuple; extern PyObject *const_str_plain_items; static PyObject *const_str_digest_ac287d930ccff60e2a2e6a9bf4946046; static PyObject *const_dict_35dd1864798a043a10ec23eaefcf5219; extern PyObject *const_tuple_empty; static PyObject *const_dict_38252060f20256dc080a28c7e1fb8512; extern PyObject *const_str_plain_LookupDict; extern PyObject *const_str_plain_structures; extern PyObject *const_str_plain_title; extern PyObject *const_str_plain___loader__; static PyObject *const_str_digest_e26a01ee85033c35e44f056d847dbade; static PyObject *const_str_plain_titles; extern PyObject *const_str_plain_startswith; extern PyObject *const_str_plain_name; extern PyObject *const_str_chr_92; extern PyObject *const_str_plain___doc__; extern PyObject *const_str_plain___cached__; static PyObject *module_filename_obj; static bool constants_created = false; static void createModuleConstants( void ) { const_tuple_str_plain_LookupDict_tuple = PyTuple_New( 1 ); PyTuple_SET_ITEM( const_tuple_str_plain_LookupDict_tuple, 0, const_str_plain_LookupDict ); Py_INCREF( const_str_plain_LookupDict ); const_str_plain__codes = UNSTREAM_STRING( &constant_bin[ 71 ], 6, 1 ); const_tuple_tuple_str_chr_92_str_chr_47_tuple_tuple = PyTuple_New( 1 ); PyTuple_SET_ITEM( const_tuple_tuple_str_chr_92_str_chr_47_tuple_tuple, 0, const_tuple_str_chr_92_str_chr_47_tuple ); Py_INCREF( const_tuple_str_chr_92_str_chr_47_tuple ); const_str_digest_840f3e0b846ec96891b7f18eb56afcd8 = UNSTREAM_STRING( &constant_bin[ 1850620 ], 24, 0 ); const_str_digest_ac287d930ccff60e2a2e6a9bf4946046 = UNSTREAM_STRING( &constant_bin[ 1850644 ], 21, 0 ); const_dict_35dd1864798a043a10ec23eaefcf5219 = PyMarshal_ReadObjectFromString( (char *)&constant_bin[ 1850665 ], 2348 ); const_dict_38252060f20256dc080a28c7e1fb8512 = _PyDict_NewPresized( 1 ); PyDict_SetItem( const_dict_38252060f20256dc080a28c7e1fb8512, const_str_plain_name, const_str_plain_status_codes ); assert( PyDict_Size( const_dict_38252060f20256dc080a28c7e1fb8512 ) == 1 ); const_str_digest_e26a01ee85033c35e44f056d847dbade = UNSTREAM_STRING( &constant_bin[ 1853013 ], 30, 0 ); const_str_plain_titles = UNSTREAM_STRING( &constant_bin[ 1487553 ], 6, 1 ); constants_created = true; } #ifndef __NUITKA_NO_ASSERT__ void checkModuleConstants_requests$status_codes( void ) { // The module may not have been used at all. if (constants_created == false) return; } #endif // The module code objects. static PyCodeObject *codeobj_caa175f940b5d1e60f5a0891c7d91121; static void createModuleCodeObjects(void) { module_filename_obj = MAKE_RELATIVE_PATH( const_str_digest_840f3e0b846ec96891b7f18eb56afcd8 ); codeobj_caa175f940b5d1e60f5a0891c7d91121 = MAKE_CODEOBJ( module_filename_obj, const_str_digest_e26a01ee85033c35e44f056d847dbade, 1, const_tuple_empty, 0, 0, CO_NOFREE ); } // The module function declarations. // The module function definitions. #if PYTHON_VERSION >= 300 static struct PyModuleDef mdef_requests$status_codes = { PyModuleDef_HEAD_INIT, "requests.status_codes", /* m_name */ NULL, /* m_doc */ -1, /* m_size */ NULL, /* m_methods */ NULL, /* m_reload */ NULL, /* m_traverse */ NULL, /* m_clear */ NULL, /* m_free */ }; #endif #if PYTHON_VERSION >= 300 extern PyObject *metapath_based_loader; #endif #if PYTHON_VERSION >= 330 extern PyObject *const_str_plain___loader__; #endif extern void _initCompiledCellType(); extern void _initCompiledGeneratorType(); extern void _initCompiledFunctionType(); extern void _initCompiledMethodType(); extern void _initCompiledFrameType(); #if PYTHON_VERSION >= 350 extern void _initCompiledCoroutineTypes(); #endif #if PYTHON_VERSION >= 360 extern void _initCompiledAsyncgenTypes(); #endif // The exported interface to CPython. On import of the module, this function // gets called. It has to have an exact function name, in cases it's a shared // library export. This is hidden behind the MOD_INIT_DECL. MOD_INIT_DECL( requests$status_codes ) { #if defined(_NUITKA_EXE) || PYTHON_VERSION >= 300 static bool _init_done = false; // Modules might be imported repeatedly, which is to be ignored. if ( _init_done ) { return MOD_RETURN_VALUE( module_requests$status_codes ); } else { _init_done = true; } #endif #ifdef _NUITKA_MODULE // In case of a stand alone extension module, need to call initialization // the init here because that's the first and only time we are going to get // called here. // Initialize the constant values used. _initBuiltinModule(); createGlobalConstants(); /* Initialize the compiled types of Nuitka. */ _initCompiledCellType(); _initCompiledGeneratorType(); _initCompiledFunctionType(); _initCompiledMethodType(); _initCompiledFrameType(); #if PYTHON_VERSION >= 350 _initCompiledCoroutineTypes(); #endif #if PYTHON_VERSION >= 360 _initCompiledAsyncgenTypes(); #endif #if PYTHON_VERSION < 300 _initSlotCompare(); #endif #if PYTHON_VERSION >= 270 _initSlotIternext(); #endif patchBuiltinModule(); patchTypeComparison(); // Enable meta path based loader if not already done. setupMetaPathBasedLoader(); #if PYTHON_VERSION >= 300 patchInspectModule(); #endif #endif /* The constants only used by this module are created now. */ #ifdef _NUITKA_TRACE puts("requests.status_codes: Calling createModuleConstants()."); #endif createModuleConstants(); /* The code objects used by this module are created now. */ #ifdef _NUITKA_TRACE puts("requests.status_codes: Calling createModuleCodeObjects()."); #endif createModuleCodeObjects(); // puts( "in initrequests$status_codes" ); // Create the module object first. There are no methods initially, all are // added dynamically in actual code only. Also no "__doc__" is initially // set at this time, as it could not contain NUL characters this way, they // are instead set in early module code. No "self" for modules, we have no // use for it. #if PYTHON_VERSION < 300 module_requests$status_codes = Py_InitModule4( "requests.status_codes", // Module Name NULL, // No methods initially, all are added // dynamically in actual module code only. NULL, // No __doc__ is initially set, as it could // not contain NUL this way, added early in // actual code. NULL, // No self for modules, we don't use it. PYTHON_API_VERSION ); #else module_requests$status_codes = PyModule_Create( &mdef_requests$status_codes ); #endif moduledict_requests$status_codes = MODULE_DICT( module_requests$status_codes ); CHECK_OBJECT( module_requests$status_codes ); // Seems to work for Python2.7 out of the box, but for Python3, the module // doesn't automatically enter "sys.modules", so do it manually. #if PYTHON_VERSION >= 300 { int r = PyObject_SetItem( PySys_GetObject( (char *)"modules" ), const_str_digest_ac287d930ccff60e2a2e6a9bf4946046, module_requests$status_codes ); assert( r != -1 ); } #endif // For deep importing of a module we need to have "__builtins__", so we set // it ourselves in the same way than CPython does. Note: This must be done // before the frame object is allocated, or else it may fail. if ( GET_STRING_DICT_VALUE( moduledict_requests$status_codes, (Nuitka_StringObject *)const_str_plain___builtins__ ) == NULL ) { PyObject *value = (PyObject *)builtin_module; // Check if main module, not a dict then but the module itself. #if !defined(_NUITKA_EXE) || !0 value = PyModule_GetDict( value ); #endif UPDATE_STRING_DICT0( moduledict_requests$status_codes, (Nuitka_StringObject *)const_str_plain___builtins__, value ); } #if PYTHON_VERSION >= 330 UPDATE_STRING_DICT0( moduledict_requests$status_codes, (Nuitka_StringObject *)const_str_plain___loader__, metapath_based_loader ); #endif // Temp variables if any PyObject *tmp_for_loop_1__for_iterator = NULL; PyObject *tmp_for_loop_1__iter_value = NULL; PyObject *tmp_for_loop_2__for_iterator = NULL; PyObject *tmp_for_loop_2__iter_value = NULL; PyObject *tmp_tuple_unpack_1__element_1 = NULL; PyObject *tmp_tuple_unpack_1__element_2 = NULL; PyObject *tmp_tuple_unpack_1__source_iter = NULL; PyObject *exception_type = NULL; PyObject *exception_value = NULL; PyTracebackObject *exception_tb = NULL; NUITKA_MAY_BE_UNUSED int exception_lineno = 0; PyObject *exception_keeper_type_1; PyObject *exception_keeper_value_1; PyTracebackObject *exception_keeper_tb_1; NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_1; PyObject *exception_keeper_type_2; PyObject *exception_keeper_value_2; PyTracebackObject *exception_keeper_tb_2; NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_2; PyObject *exception_keeper_type_3; PyObject *exception_keeper_value_3; PyTracebackObject *exception_keeper_tb_3; NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_3; PyObject *exception_keeper_type_4; PyObject *exception_keeper_value_4; PyTracebackObject *exception_keeper_tb_4; NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_4; PyObject *tmp_args_element_name_1; PyObject *tmp_args_element_name_2; PyObject *tmp_assign_source_1; PyObject *tmp_assign_source_2; PyObject *tmp_assign_source_3; PyObject *tmp_assign_source_4; PyObject *tmp_assign_source_5; PyObject *tmp_assign_source_6; PyObject *tmp_assign_source_7; PyObject *tmp_assign_source_8; PyObject *tmp_assign_source_9; PyObject *tmp_assign_source_10; PyObject *tmp_assign_source_11; PyObject *tmp_assign_source_12; PyObject *tmp_assign_source_13; PyObject *tmp_assign_source_14; PyObject *tmp_assign_source_15; PyObject *tmp_assign_source_16; PyObject *tmp_assign_source_17; PyObject *tmp_assign_source_18; PyObject *tmp_assign_source_19; PyObject *tmp_called_instance_1; PyObject *tmp_called_instance_2; PyObject *tmp_called_instance_3; PyObject *tmp_called_name_1; PyObject *tmp_called_name_2; int tmp_cond_truth_1; PyObject *tmp_cond_value_1; PyObject *tmp_fromlist_name_1; PyObject *tmp_globals_name_1; PyObject *tmp_import_name_from_1; PyObject *tmp_iter_arg_1; PyObject *tmp_iter_arg_2; PyObject *tmp_iter_arg_3; PyObject *tmp_iterator_attempt; PyObject *tmp_iterator_name_1; PyObject *tmp_kw_name_1; PyObject *tmp_level_name_1; PyObject *tmp_locals_name_1; PyObject *tmp_name_name_1; PyObject *tmp_next_source_1; PyObject *tmp_next_source_2; PyObject *tmp_setattr_attr_1; PyObject *tmp_setattr_attr_2; PyObject *tmp_setattr_target_1; PyObject *tmp_setattr_target_2; PyObject *tmp_setattr_value_1; PyObject *tmp_setattr_value_2; PyObject *tmp_unpack_1; PyObject *tmp_unpack_2; NUITKA_MAY_BE_UNUSED PyObject *tmp_unused; struct Nuitka_FrameObject *frame_caa175f940b5d1e60f5a0891c7d91121; NUITKA_MAY_BE_UNUSED char const *type_description_1 = NULL; // Module code. tmp_assign_source_1 = Py_None; UPDATE_STRING_DICT0( moduledict_requests$status_codes, (Nuitka_StringObject *)const_str_plain___doc__, tmp_assign_source_1 ); tmp_assign_source_2 = module_filename_obj; UPDATE_STRING_DICT0( moduledict_requests$status_codes, (Nuitka_StringObject *)const_str_plain___file__, tmp_assign_source_2 ); tmp_assign_source_3 = metapath_based_loader; UPDATE_STRING_DICT0( moduledict_requests$status_codes, (Nuitka_StringObject *)const_str_plain___loader__, tmp_assign_source_3 ); // Frame without reuse. frame_caa175f940b5d1e60f5a0891c7d91121 = MAKE_MODULE_FRAME( codeobj_caa175f940b5d1e60f5a0891c7d91121, module_requests$status_codes ); // Push the new frame as the currently active one, and we should be exclusively // owning it. pushFrameStack( frame_caa175f940b5d1e60f5a0891c7d91121 ); assert( Py_REFCNT( frame_caa175f940b5d1e60f5a0891c7d91121 ) == 2 ); // Framed code: frame_caa175f940b5d1e60f5a0891c7d91121->m_frame.f_lineno = 1; { PyObject *module = PyImport_ImportModule("importlib._bootstrap"); if (likely( module != NULL )) { tmp_called_name_1 = PyObject_GetAttr( module, const_str_plain_ModuleSpec ); } else { tmp_called_name_1 = NULL; } } if ( tmp_called_name_1 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 1; goto frame_exception_exit_1; } tmp_args_element_name_1 = const_str_digest_ac287d930ccff60e2a2e6a9bf4946046; tmp_args_element_name_2 = metapath_based_loader; frame_caa175f940b5d1e60f5a0891c7d91121->m_frame.f_lineno = 1; { PyObject *call_args[] = { tmp_args_element_name_1, tmp_args_element_name_2 }; tmp_assign_source_4 = CALL_FUNCTION_WITH_ARGS2( tmp_called_name_1, call_args ); } if ( tmp_assign_source_4 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 1; goto frame_exception_exit_1; } UPDATE_STRING_DICT1( moduledict_requests$status_codes, (Nuitka_StringObject *)const_str_plain___spec__, tmp_assign_source_4 ); tmp_assign_source_5 = Py_None; UPDATE_STRING_DICT0( moduledict_requests$status_codes, (Nuitka_StringObject *)const_str_plain___cached__, tmp_assign_source_5 ); tmp_assign_source_6 = const_str_plain_requests; UPDATE_STRING_DICT0( moduledict_requests$status_codes, (Nuitka_StringObject *)const_str_plain___package__, tmp_assign_source_6 ); tmp_name_name_1 = const_str_plain_structures; tmp_globals_name_1 = (PyObject *)moduledict_requests$status_codes; tmp_locals_name_1 = Py_None; tmp_fromlist_name_1 = const_tuple_str_plain_LookupDict_tuple; tmp_level_name_1 = const_int_pos_1; frame_caa175f940b5d1e60f5a0891c7d91121->m_frame.f_lineno = 3; tmp_import_name_from_1 = IMPORT_MODULE5( tmp_name_name_1, tmp_globals_name_1, tmp_locals_name_1, tmp_fromlist_name_1, tmp_level_name_1 ); if ( tmp_import_name_from_1 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 3; goto frame_exception_exit_1; } tmp_assign_source_7 = IMPORT_NAME( tmp_import_name_from_1, const_str_plain_LookupDict ); Py_DECREF( tmp_import_name_from_1 ); if ( tmp_assign_source_7 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 3; goto frame_exception_exit_1; } UPDATE_STRING_DICT1( moduledict_requests$status_codes, (Nuitka_StringObject *)const_str_plain_LookupDict, tmp_assign_source_7 ); tmp_assign_source_8 = PyDict_Copy( const_dict_35dd1864798a043a10ec23eaefcf5219 ); UPDATE_STRING_DICT1( moduledict_requests$status_codes, (Nuitka_StringObject *)const_str_plain__codes, tmp_assign_source_8 ); tmp_called_name_2 = GET_STRING_DICT_VALUE( moduledict_requests$status_codes, (Nuitka_StringObject *)const_str_plain_LookupDict ); if (unlikely( tmp_called_name_2 == NULL )) { tmp_called_name_2 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_LookupDict ); } if ( tmp_called_name_2 == NULL ) { exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "LookupDict" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 85; goto frame_exception_exit_1; } tmp_kw_name_1 = PyDict_Copy( const_dict_38252060f20256dc080a28c7e1fb8512 ); frame_caa175f940b5d1e60f5a0891c7d91121->m_frame.f_lineno = 85; tmp_assign_source_9 = CALL_FUNCTION_WITH_KEYARGS( tmp_called_name_2, tmp_kw_name_1 ); Py_DECREF( tmp_kw_name_1 ); if ( tmp_assign_source_9 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 85; goto frame_exception_exit_1; } UPDATE_STRING_DICT1( moduledict_requests$status_codes, (Nuitka_StringObject *)const_str_plain_codes, tmp_assign_source_9 ); tmp_called_instance_1 = GET_STRING_DICT_VALUE( moduledict_requests$status_codes, (Nuitka_StringObject *)const_str_plain__codes ); if (unlikely( tmp_called_instance_1 == NULL )) { tmp_called_instance_1 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain__codes ); } if ( tmp_called_instance_1 == NULL ) { exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "_codes" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 87; goto frame_exception_exit_1; } frame_caa175f940b5d1e60f5a0891c7d91121->m_frame.f_lineno = 87; tmp_iter_arg_1 = CALL_METHOD_NO_ARGS( tmp_called_instance_1, const_str_plain_items ); if ( tmp_iter_arg_1 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 87; goto frame_exception_exit_1; } tmp_assign_source_10 = MAKE_ITERATOR( tmp_iter_arg_1 ); Py_DECREF( tmp_iter_arg_1 ); if ( tmp_assign_source_10 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 87; goto frame_exception_exit_1; } assert( tmp_for_loop_1__for_iterator == NULL ); tmp_for_loop_1__for_iterator = tmp_assign_source_10; // Tried code: loop_start_1:; tmp_next_source_1 = tmp_for_loop_1__for_iterator; CHECK_OBJECT( tmp_next_source_1 ); tmp_assign_source_11 = ITERATOR_NEXT( tmp_next_source_1 ); if ( tmp_assign_source_11 == NULL ) { if ( CHECK_AND_CLEAR_STOP_ITERATION_OCCURRED() ) { goto loop_end_1; } else { FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 87; goto try_except_handler_1; } } { PyObject *old = tmp_for_loop_1__iter_value; tmp_for_loop_1__iter_value = tmp_assign_source_11; Py_XDECREF( old ); } // Tried code: tmp_iter_arg_2 = tmp_for_loop_1__iter_value; CHECK_OBJECT( tmp_iter_arg_2 ); tmp_assign_source_12 = MAKE_ITERATOR( tmp_iter_arg_2 ); if ( tmp_assign_source_12 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 87; goto try_except_handler_2; } { PyObject *old = tmp_tuple_unpack_1__source_iter; tmp_tuple_unpack_1__source_iter = tmp_assign_source_12; Py_XDECREF( old ); } // Tried code: tmp_unpack_1 = tmp_tuple_unpack_1__source_iter; CHECK_OBJECT( tmp_unpack_1 ); tmp_assign_source_13 = UNPACK_NEXT( tmp_unpack_1, 0, 2 ); if ( tmp_assign_source_13 == NULL ) { if ( !ERROR_OCCURRED() ) { exception_type = PyExc_StopIteration; Py_INCREF( exception_type ); exception_value = NULL; exception_tb = NULL; } else { FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); } exception_lineno = 87; goto try_except_handler_3; } { PyObject *old = tmp_tuple_unpack_1__element_1; tmp_tuple_unpack_1__element_1 = tmp_assign_source_13; Py_XDECREF( old ); } tmp_unpack_2 = tmp_tuple_unpack_1__source_iter; CHECK_OBJECT( tmp_unpack_2 ); tmp_assign_source_14 = UNPACK_NEXT( tmp_unpack_2, 1, 2 ); if ( tmp_assign_source_14 == NULL ) { if ( !ERROR_OCCURRED() ) { exception_type = PyExc_StopIteration; Py_INCREF( exception_type ); exception_value = NULL; exception_tb = NULL; } else { FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); } exception_lineno = 87; goto try_except_handler_3; } { PyObject *old = tmp_tuple_unpack_1__element_2; tmp_tuple_unpack_1__element_2 = tmp_assign_source_14; Py_XDECREF( old ); } tmp_iterator_name_1 = tmp_tuple_unpack_1__source_iter; CHECK_OBJECT( tmp_iterator_name_1 ); // Check if iterator has left-over elements. CHECK_OBJECT( tmp_iterator_name_1 ); assert( HAS_ITERNEXT( tmp_iterator_name_1 ) ); tmp_iterator_attempt = (*Py_TYPE( tmp_iterator_name_1 )->tp_iternext)( tmp_iterator_name_1 ); if (likely( tmp_iterator_attempt == NULL )) { PyObject *error = GET_ERROR_OCCURRED(); if ( error != NULL ) { if ( EXCEPTION_MATCH_BOOL_SINGLE( error, PyExc_StopIteration )) { CLEAR_ERROR_OCCURRED(); } else { FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 87; goto try_except_handler_3; } } } else { Py_DECREF( tmp_iterator_attempt ); // TODO: Could avoid PyErr_Format. #if PYTHON_VERSION < 300 PyErr_Format( PyExc_ValueError, "too many values to unpack" ); #else PyErr_Format( PyExc_ValueError, "too many values to unpack (expected 2)" ); #endif FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 87; goto try_except_handler_3; } goto try_end_1; // Exception handler code: try_except_handler_3:; exception_keeper_type_1 = exception_type; exception_keeper_value_1 = exception_value; exception_keeper_tb_1 = exception_tb; exception_keeper_lineno_1 = exception_lineno; exception_type = NULL; exception_value = NULL; exception_tb = NULL; exception_lineno = 0; Py_XDECREF( tmp_tuple_unpack_1__source_iter ); tmp_tuple_unpack_1__source_iter = NULL; // Re-raise. exception_type = exception_keeper_type_1; exception_value = exception_keeper_value_1; exception_tb = exception_keeper_tb_1; exception_lineno = exception_keeper_lineno_1; goto try_except_handler_2; // End of try: try_end_1:; goto try_end_2; // Exception handler code: try_except_handler_2:; exception_keeper_type_2 = exception_type; exception_keeper_value_2 = exception_value; exception_keeper_tb_2 = exception_tb; exception_keeper_lineno_2 = exception_lineno; exception_type = NULL; exception_value = NULL; exception_tb = NULL; exception_lineno = 0; Py_XDECREF( tmp_tuple_unpack_1__element_1 ); tmp_tuple_unpack_1__element_1 = NULL; Py_XDECREF( tmp_tuple_unpack_1__element_2 ); tmp_tuple_unpack_1__element_2 = NULL; // Re-raise. exception_type = exception_keeper_type_2; exception_value = exception_keeper_value_2; exception_tb = exception_keeper_tb_2; exception_lineno = exception_keeper_lineno_2; goto try_except_handler_1; // End of try: try_end_2:; Py_XDECREF( tmp_tuple_unpack_1__source_iter ); tmp_tuple_unpack_1__source_iter = NULL; tmp_assign_source_15 = tmp_tuple_unpack_1__element_1; CHECK_OBJECT( tmp_assign_source_15 ); UPDATE_STRING_DICT0( moduledict_requests$status_codes, (Nuitka_StringObject *)const_str_plain_code, tmp_assign_source_15 ); Py_XDECREF( tmp_tuple_unpack_1__element_1 ); tmp_tuple_unpack_1__element_1 = NULL; tmp_assign_source_16 = tmp_tuple_unpack_1__element_2; CHECK_OBJECT( tmp_assign_source_16 ); UPDATE_STRING_DICT0( moduledict_requests$status_codes, (Nuitka_StringObject *)const_str_plain_titles, tmp_assign_source_16 ); Py_XDECREF( tmp_tuple_unpack_1__element_2 ); tmp_tuple_unpack_1__element_2 = NULL; Py_XDECREF( tmp_tuple_unpack_1__element_1 ); tmp_tuple_unpack_1__element_1 = NULL; Py_XDECREF( tmp_tuple_unpack_1__element_2 ); tmp_tuple_unpack_1__element_2 = NULL; tmp_iter_arg_3 = GET_STRING_DICT_VALUE( moduledict_requests$status_codes, (Nuitka_StringObject *)const_str_plain_titles ); if (unlikely( tmp_iter_arg_3 == NULL )) { tmp_iter_arg_3 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_titles ); } if ( tmp_iter_arg_3 == NULL ) { exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "titles" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 88; goto try_except_handler_1; } tmp_assign_source_17 = MAKE_ITERATOR( tmp_iter_arg_3 ); if ( tmp_assign_source_17 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 88; goto try_except_handler_1; } { PyObject *old = tmp_for_loop_2__for_iterator; tmp_for_loop_2__for_iterator = tmp_assign_source_17; Py_XDECREF( old ); } // Tried code: loop_start_2:; tmp_next_source_2 = tmp_for_loop_2__for_iterator; CHECK_OBJECT( tmp_next_source_2 ); tmp_assign_source_18 = ITERATOR_NEXT( tmp_next_source_2 ); if ( tmp_assign_source_18 == NULL ) { if ( CHECK_AND_CLEAR_STOP_ITERATION_OCCURRED() ) { goto loop_end_2; } else { FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 88; goto try_except_handler_4; } } { PyObject *old = tmp_for_loop_2__iter_value; tmp_for_loop_2__iter_value = tmp_assign_source_18; Py_XDECREF( old ); } tmp_assign_source_19 = tmp_for_loop_2__iter_value; CHECK_OBJECT( tmp_assign_source_19 ); UPDATE_STRING_DICT0( moduledict_requests$status_codes, (Nuitka_StringObject *)const_str_plain_title, tmp_assign_source_19 ); tmp_setattr_target_1 = GET_STRING_DICT_VALUE( moduledict_requests$status_codes, (Nuitka_StringObject *)const_str_plain_codes ); if (unlikely( tmp_setattr_target_1 == NULL )) { tmp_setattr_target_1 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_codes ); } if ( tmp_setattr_target_1 == NULL ) { exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "codes" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 89; goto try_except_handler_4; } tmp_setattr_attr_1 = GET_STRING_DICT_VALUE( moduledict_requests$status_codes, (Nuitka_StringObject *)const_str_plain_title ); if (unlikely( tmp_setattr_attr_1 == NULL )) { tmp_setattr_attr_1 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_title ); } if ( tmp_setattr_attr_1 == NULL ) { exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "title" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 89; goto try_except_handler_4; } tmp_setattr_value_1 = GET_STRING_DICT_VALUE( moduledict_requests$status_codes, (Nuitka_StringObject *)const_str_plain_code ); if (unlikely( tmp_setattr_value_1 == NULL )) { tmp_setattr_value_1 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_code ); } if ( tmp_setattr_value_1 == NULL ) { exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "code" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 89; goto try_except_handler_4; } tmp_unused = BUILTIN_SETATTR( tmp_setattr_target_1, tmp_setattr_attr_1, tmp_setattr_value_1 ); if ( tmp_unused == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 89; goto try_except_handler_4; } tmp_called_instance_2 = GET_STRING_DICT_VALUE( moduledict_requests$status_codes, (Nuitka_StringObject *)const_str_plain_title ); if (unlikely( tmp_called_instance_2 == NULL )) { tmp_called_instance_2 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_title ); } if ( tmp_called_instance_2 == NULL ) { exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "title" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 90; goto try_except_handler_4; } frame_caa175f940b5d1e60f5a0891c7d91121->m_frame.f_lineno = 90; tmp_cond_value_1 = CALL_METHOD_WITH_ARGS1( tmp_called_instance_2, const_str_plain_startswith, &PyTuple_GET_ITEM( const_tuple_tuple_str_chr_92_str_chr_47_tuple_tuple, 0 ) ); if ( tmp_cond_value_1 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 90; goto try_except_handler_4; } tmp_cond_truth_1 = CHECK_IF_TRUE( tmp_cond_value_1 ); if ( tmp_cond_truth_1 == -1 ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); Py_DECREF( tmp_cond_value_1 ); exception_lineno = 90; goto try_except_handler_4; } Py_DECREF( tmp_cond_value_1 ); if ( tmp_cond_truth_1 == 1 ) { goto branch_no_1; } else { goto branch_yes_1; } branch_yes_1:; tmp_setattr_target_2 = GET_STRING_DICT_VALUE( moduledict_requests$status_codes, (Nuitka_StringObject *)const_str_plain_codes ); if (unlikely( tmp_setattr_target_2 == NULL )) { tmp_setattr_target_2 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_codes ); } if ( tmp_setattr_target_2 == NULL ) { exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "codes" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 91; goto try_except_handler_4; } tmp_called_instance_3 = GET_STRING_DICT_VALUE( moduledict_requests$status_codes, (Nuitka_StringObject *)const_str_plain_title ); if (unlikely( tmp_called_instance_3 == NULL )) { tmp_called_instance_3 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_title ); } if ( tmp_called_instance_3 == NULL ) { exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "title" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 91; goto try_except_handler_4; } frame_caa175f940b5d1e60f5a0891c7d91121->m_frame.f_lineno = 91; tmp_setattr_attr_2 = CALL_METHOD_NO_ARGS( tmp_called_instance_3, const_str_plain_upper ); if ( tmp_setattr_attr_2 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 91; goto try_except_handler_4; } tmp_setattr_value_2 = GET_STRING_DICT_VALUE( moduledict_requests$status_codes, (Nuitka_StringObject *)const_str_plain_code ); if (unlikely( tmp_setattr_value_2 == NULL )) { tmp_setattr_value_2 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_code ); } if ( tmp_setattr_value_2 == NULL ) { Py_DECREF( tmp_setattr_attr_2 ); exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "code" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 91; goto try_except_handler_4; } tmp_unused = BUILTIN_SETATTR( tmp_setattr_target_2, tmp_setattr_attr_2, tmp_setattr_value_2 ); Py_DECREF( tmp_setattr_attr_2 ); if ( tmp_unused == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 91; goto try_except_handler_4; } branch_no_1:; if ( CONSIDER_THREADING() == false ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 88; goto try_except_handler_4; } goto loop_start_2; loop_end_2:; goto try_end_3; // Exception handler code: try_except_handler_4:; exception_keeper_type_3 = exception_type; exception_keeper_value_3 = exception_value; exception_keeper_tb_3 = exception_tb; exception_keeper_lineno_3 = exception_lineno; exception_type = NULL; exception_value = NULL; exception_tb = NULL; exception_lineno = 0; Py_XDECREF( tmp_for_loop_2__iter_value ); tmp_for_loop_2__iter_value = NULL; Py_XDECREF( tmp_for_loop_2__for_iterator ); tmp_for_loop_2__for_iterator = NULL; // Re-raise. exception_type = exception_keeper_type_3; exception_value = exception_keeper_value_3; exception_tb = exception_keeper_tb_3; exception_lineno = exception_keeper_lineno_3; goto try_except_handler_1; // End of try: try_end_3:; Py_XDECREF( tmp_for_loop_2__iter_value ); tmp_for_loop_2__iter_value = NULL; Py_XDECREF( tmp_for_loop_2__for_iterator ); tmp_for_loop_2__for_iterator = NULL; if ( CONSIDER_THREADING() == false ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 87; goto try_except_handler_1; } goto loop_start_1; loop_end_1:; goto try_end_4; // Exception handler code: try_except_handler_1:; exception_keeper_type_4 = exception_type; exception_keeper_value_4 = exception_value; exception_keeper_tb_4 = exception_tb; exception_keeper_lineno_4 = exception_lineno; exception_type = NULL; exception_value = NULL; exception_tb = NULL; exception_lineno = 0; Py_XDECREF( tmp_for_loop_1__iter_value ); tmp_for_loop_1__iter_value = NULL; Py_XDECREF( tmp_for_loop_1__for_iterator ); tmp_for_loop_1__for_iterator = NULL; // Re-raise. exception_type = exception_keeper_type_4; exception_value = exception_keeper_value_4; exception_tb = exception_keeper_tb_4; exception_lineno = exception_keeper_lineno_4; goto frame_exception_exit_1; // End of try: try_end_4:; // Restore frame exception if necessary. #if 0 RESTORE_FRAME_EXCEPTION( frame_caa175f940b5d1e60f5a0891c7d91121 ); #endif popFrameStack(); assertFrameObject( frame_caa175f940b5d1e60f5a0891c7d91121 ); goto frame_no_exception_1; frame_exception_exit_1:; #if 0 RESTORE_FRAME_EXCEPTION( frame_caa175f940b5d1e60f5a0891c7d91121 ); #endif if ( exception_tb == NULL ) { exception_tb = MAKE_TRACEBACK( frame_caa175f940b5d1e60f5a0891c7d91121, exception_lineno ); } else if ( exception_tb->tb_frame != &frame_caa175f940b5d1e60f5a0891c7d91121->m_frame ) { exception_tb = ADD_TRACEBACK( exception_tb, frame_caa175f940b5d1e60f5a0891c7d91121, exception_lineno ); } // Put the previous frame back on top. popFrameStack(); // Return the error. goto module_exception_exit; frame_no_exception_1:; Py_XDECREF( tmp_for_loop_1__iter_value ); tmp_for_loop_1__iter_value = NULL; Py_XDECREF( tmp_for_loop_1__for_iterator ); tmp_for_loop_1__for_iterator = NULL; return MOD_RETURN_VALUE( module_requests$status_codes ); module_exception_exit: RESTORE_ERROR_OCCURRED( exception_type, exception_value, exception_tb ); return MOD_RETURN_VALUE( NULL ); }
33.344942
176
0.71781
Pckool
db23cc892c19ff1989a737ffc99aea47d34fbd7d
1,528
hpp
C++
src/lib/repository/extractor.hpp
bunsanorg/pm
67300580a21591cf84d64f1239dd219659797dca
[ "Apache-2.0" ]
null
null
null
src/lib/repository/extractor.hpp
bunsanorg/pm
67300580a21591cf84d64f1239dd219659797dca
[ "Apache-2.0" ]
1
2015-02-12T10:02:56.000Z
2015-02-12T10:02:56.000Z
src/lib/repository/extractor.hpp
bunsanorg/pm
67300580a21591cf84d64f1239dd219659797dca
[ "Apache-2.0" ]
null
null
null
#pragma once #include "cache.hpp" #include <bunsan/pm/repository.hpp> #include <boost/noncopyable.hpp> namespace bunsan { namespace pm { class repository::extractor : private boost::noncopyable { public: extractor(repository &self, const extract_config &config); void extract(const entry &package, const boost::filesystem::path &destination); void install(const entry &package, const boost::filesystem::path &destination); void update(const entry &package, const boost::filesystem::path &destination); bool need_update(const boost::filesystem::path &destination, std::time_t lifetime); /*! * \note Will merge directories but will fail on file collisions * \warning Will work only on the local_system_().tempdir_for_build()'s * filesystem */ void extract_source(const entry &package, const std::string &source_id, const boost::filesystem::path &destination); void extract_build(const entry &package, const boost::filesystem::path &destination); void extract_installation(const entry &package, const boost::filesystem::path &destination); private: static void merge_directories(const boost::filesystem::path &source, const boost::filesystem::path &destination); private: cache &cache_(); local_system &local_system_(); private: repository &m_self; extract_config m_config; }; } // namespace pm } // namespace bunsan
27.285714
80
0.672775
bunsanorg
db23e629dce0b969ffcd105dca1bdd067ddad091
916
cpp
C++
DOJ/#843.cpp
Nickel-Angel/ACM-and-OI
79d13fd008c3a1fe9ebf35329aceb1fcb260d5d9
[ "MIT" ]
null
null
null
DOJ/#843.cpp
Nickel-Angel/ACM-and-OI
79d13fd008c3a1fe9ebf35329aceb1fcb260d5d9
[ "MIT" ]
1
2021-11-18T15:10:29.000Z
2021-11-20T07:13:31.000Z
DOJ/#843.cpp
Nickel-Angel/ACM-and-OI
79d13fd008c3a1fe9ebf35329aceb1fcb260d5d9
[ "MIT" ]
null
null
null
/* * @author Nickel_Angel (1239004072@qq.com) * @copyright Copyright (c) 2022 */ #include <algorithm> #include <cstdio> #include <cstring> int n, a[5010], f[5010][5010]; int main() { scanf("%d", &n); for (int i = 1; i <= n; ++i) scanf("%d", a + i); std::sort(a + 1, a + n + 1); for (int i = 1; i <= n; ++i) { for (int j = i + 1; j <= n; ++j) f[i][j] = 2; } int ans = 2; for (int i = 1, l, r; i <= n; ++i) { l = i - 1, r = i + 1; while (l > 0 && r <= n) { if (1ll * a[l] + a[r] == 2ll * a[i]) { f[i][r] = std::max(f[i][r], f[l][i] + 1); ans = std::max(ans, f[i][r]); ++r; } else if (1ll * a[l] + a[r] > 2ll * a[i]) --l; else ++r; } } printf("%d\n", ans); return 0; }
21.302326
57
0.340611
Nickel-Angel
db29cda31dbc086c00bb3bb8acdc96f447ff6164
2,456
cpp
C++
keysmappingdialog.cpp
HankHenshaw/Chip8Qt
968e7505b26b653397c8708a2514acfe12d294a4
[ "MIT" ]
null
null
null
keysmappingdialog.cpp
HankHenshaw/Chip8Qt
968e7505b26b653397c8708a2514acfe12d294a4
[ "MIT" ]
null
null
null
keysmappingdialog.cpp
HankHenshaw/Chip8Qt
968e7505b26b653397c8708a2514acfe12d294a4
[ "MIT" ]
null
null
null
#include "keysmappingdialog.h" #include "ui_keysmappingdialog.h" KeysMappingDialog::KeysMappingDialog(QWidget *parent) : QDialog(parent), ui(new Ui::KeysMappingDialog) { ui->setupUi(this); this->setWindowTitle("Keys Options"); connect(ui->A_pushButton, &QPushButton::pressed, this, &KeysMappingDialog::slotKeysMapping); connect(ui->B_pushButton, &QPushButton::pressed, this, &KeysMappingDialog::slotKeysMapping); connect(ui->C_pushButton, &QPushButton::pressed, this, &KeysMappingDialog::slotKeysMapping); connect(ui->D_pushButton, &QPushButton::pressed, this, &KeysMappingDialog::slotKeysMapping); connect(ui->E_pushButton, &QPushButton::pressed, this, &KeysMappingDialog::slotKeysMapping); connect(ui->F_pushButton, &QPushButton::pressed, this, &KeysMappingDialog::slotKeysMapping); connect(ui->G_pushButton, &QPushButton::pressed, this, &KeysMappingDialog::slotKeysMapping); connect(ui->H_pushButton, &QPushButton::pressed, this, &KeysMappingDialog::slotKeysMapping); connect(ui->I_pushButton, &QPushButton::pressed, this, &KeysMappingDialog::slotKeysMapping); connect(ui->J_pushButton, &QPushButton::pressed, this, &KeysMappingDialog::slotKeysMapping); connect(ui->K_pushButton, &QPushButton::pressed, this, &KeysMappingDialog::slotKeysMapping); connect(ui->L_pushButton, &QPushButton::pressed, this, &KeysMappingDialog::slotKeysMapping); connect(ui->M_pushButton, &QPushButton::pressed, this, &KeysMappingDialog::slotKeysMapping); connect(ui->N_pushButton, &QPushButton::pressed, this, &KeysMappingDialog::slotKeysMapping); connect(ui->O_pushButton, &QPushButton::pressed, this, &KeysMappingDialog::slotKeysMapping); connect(ui->P_pushButton, &QPushButton::pressed, this, &KeysMappingDialog::slotKeysMapping); } KeysMappingDialog::~KeysMappingDialog() { delete ui; } void KeysMappingDialog::on_buttonBox_accepted() { accept(); } void KeysMappingDialog::on_buttonBox_rejected() { reject(); } void KeysMappingDialog::slotKeysMapping() { QChar keyChar = sender()->objectName().at(0); keyNumber = keyChar.unicode() - 65; qDebug() << "Button:" << keyChar; emit signalSetKeyNumber(keyNumber); } void KeysMappingDialog::slotGetKey(Qt::Key key) { KeyMappingDialog dialog(key, this); if(dialog.exec() == QDialog::Accepted) { qDebug() << "Ok"; emit signalSendNewKeyValue(keyNumber, dialog.getNewKeyValue()); } }
39.612903
96
0.739414
HankHenshaw
db2af2c45c57222ebbd5ff6617da32adbbd1d55b
1,604
cpp
C++
examples/std_parts/fixed.cpp
denkoken/fase
05d995170d53539f122b1318c084c99ca71fd393
[ "MIT" ]
2
2019-03-18T10:49:26.000Z
2019-05-27T09:44:05.000Z
examples/std_parts/fixed.cpp
denkoken/fase
05d995170d53539f122b1318c084c99ca71fd393
[ "MIT" ]
null
null
null
examples/std_parts/fixed.cpp
denkoken/fase
05d995170d53539f122b1318c084c99ca71fd393
[ "MIT" ]
1
2021-01-13T05:30:42.000Z
2021-01-13T05:30:42.000Z
#include <fase2/fase.h> #include <fase2/imgui_editor/imgui_editor.h> #include <fase2/stdparts.h> #include <string> #include <vector> #include "../extra_parts.h" #include "../fase_gl_utils.h" #include "funcs.h" int main() { // Create Fase instance with GUI editor fase::Fase<fase::ImGuiEditor, fase::FixedPipelineParts, NFDParts> app; std::vector<std::string> in_arg{"red", "green", "blue", "count"}; std::vector<std::string> out_arg{ "dst_red", "dst_green", "dst_blue", }; auto api = app.newPipeline<float, float, float>("fixed", in_arg, out_arg) .fix<float, float, float, float>(); auto hook = [&](std::vector<float>* bg_col) { try { if (!api) { return; // "fixed" is deleted or something went wrong. } bg_col->resize(3); auto [r, g, b] = api(bg_col->at(0), bg_col->at(1), bg_col->at(2), 0.f); r = r > 1.f ? r - 1.f : r; g = g > 1.f ? g - 1.f : g; b = b > 1.f ? b - 1.f : b; bg_col->at(0) = r; bg_col->at(1) = g; bg_col->at(2) = b; } catch (fase::TryToGetEmptyVariable&) { } }; AddNFDButtons(app, app); // Create OpenGL window GLFWwindow* window = InitOpenGL("GUI Editor Example"); if (!window) { return 0; } // Initialize ImGui InitImGui(window, "../third_party/imgui/misc/fonts/Cousine-Regular.ttf"); // Start main loop RunRenderingLoop(window, app, hook); return 0; }
25.870968
77
0.524938
denkoken