hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
sequencelengths
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
sequencelengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
sequencelengths
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
b57ab05c3f3f7779b0c026b6c4d7c7243c79daf9
1,430
cpp
C++
uhk/acm5624.cpp
Hyyyyyyyyyy/acm
d7101755b2c2868d51bb056f094e024d0333b56f
[ "MIT" ]
null
null
null
uhk/acm5624.cpp
Hyyyyyyyyyy/acm
d7101755b2c2868d51bb056f094e024d0333b56f
[ "MIT" ]
null
null
null
uhk/acm5624.cpp
Hyyyyyyyyyy/acm
d7101755b2c2868d51bb056f094e024d0333b56f
[ "MIT" ]
null
null
null
#include <cstdio> #include <cstring> #include <algorithm> using namespace std; typedef long long ll; const int maxn = 15000 + 10; const int MAX = 100000000; struct node { int u; int v; ll w; }; node edge[maxn]; int N, M, cnt; ll res; int F[maxn]; bool comp(const node& a, const node& b) { return a.w < b.w; } void addedge(int u, int v, ll w) { edge[cnt].u = u; edge[cnt].v = v; edge[cnt++].w = w; } int find(int x) { if (F[x] == -1) return x; else return F[x] = find(F[x]); } ll kruskal(int f) { int i, j, k, count = 0; ll ans = 0; memset(F, -1, sizeof(F)); for (i = f; i < cnt; i++) { int u = edge[i].u; int v = edge[i].v; ll w = edge[i].w; int t1 = find(u); int t2 = find(v); if (t1 != t2) { F[t2] = t1; ans += w; count++; } if (count == N - 1) break; } if (count < N - 1) return -1; else return edge[i].w - edge[f].w; } int main() { int i, j, k, n, m, a, b; ll c; while (scanf("%d", &n) != EOF) { for (m = 1; m <= n; m++) { cnt = 0; res = MAX; scanf("%d %d", &N, &M); for (i = 1; i <= M; i++) { scanf("%d %d %lld", &a, &b, &c); addedge(a, b, c); } sort(edge, edge + cnt, comp); res = kruskal(0); if (res == -1) { printf("-1\n"); continue; } for (i = 1; i <= cnt-N+1; i++) { ll t = kruskal(i); if (t < 0) continue; if (res > t) res = t; } printf("%lld\n", res); } } return 0; }
14.742268
39
0.479021
Hyyyyyyyyyy
b58004d3527ba76f6a550c910f2c61f558ca6db7
4,151
cc
C++
UA_BlackJack_Server/DBServer/test/test_RedisService.cc
lsxk-jwj/gRPC_demo
4a772dbb68726f2f253e6023271fd7b629006853
[ "Apache-2.0" ]
null
null
null
UA_BlackJack_Server/DBServer/test/test_RedisService.cc
lsxk-jwj/gRPC_demo
4a772dbb68726f2f253e6023271fd7b629006853
[ "Apache-2.0" ]
null
null
null
UA_BlackJack_Server/DBServer/test/test_RedisService.cc
lsxk-jwj/gRPC_demo
4a772dbb68726f2f253e6023271fd7b629006853
[ "Apache-2.0" ]
null
null
null
#include "../RedisService.h" #include <gtest/gtest.h> #include <unordered_set> using ua_black_jack_server::data_base_server::RedisService; RedisService* service; const char* nickname = "owen1"; const int64_t uid = 2345; const char* password = "ASIKrgubhy"; int main() { acl::redis_client client("127.0.0.1:6379"); acl::redis conn(&client); conn.set("UID", "2345"); conn.set("MID", "1234"); service = new RedisService(client); ::testing::InitGoogleTest(); auto ret = RUN_ALL_TESTS(); getchar(); delete service; client.close(); } TEST(RedisService, nicknameToUID) { // const char* nickname = "owen1"; // constexpr int64_t uid = 2345; EXPECT_TRUE(service->SetUid(nickname, uid)); EXPECT_TRUE(service->NameExists(nickname)); EXPECT_EQ(service->GetUid(nickname), acl::string("2345")); } TEST(RedisService, nextUID) { EXPECT_EQ(service->NextUid(), 2346); EXPECT_EQ(service->NextUid(), 2347); EXPECT_EQ(service->NextUid(), 2348); EXPECT_EQ(service->NextUid(), 2349); EXPECT_EQ(service->NextUid(), 2350); } TEST(RedisService, nextMatchId) { EXPECT_EQ(service->NextMatchId(), 1235); EXPECT_EQ(service->NextMatchId(), 1236); EXPECT_EQ(service->NextMatchId(), 1237); EXPECT_EQ(service->NextMatchId(), 1238); EXPECT_EQ(service->NextMatchId(), 1239); EXPECT_EQ(service->NextMatchId(), 1240); } TEST(RedisService, UIDToPassword) { // ; // const int64_t uid = 2234; EXPECT_TRUE(service->setPassword(uid, password)); EXPECT_EQ(service->GetPassword(uid), acl::string(password)); } TEST(RedisService, UIDToNickname) { // const char* nickname = "owen1"; // const int64_t uid = 2345; EXPECT_TRUE(service->SetNickname(uid, nickname)); EXPECT_EQ(service->GetNickname(uid), acl::string(nickname)); } TEST(RedisService, UIDToScore) { EXPECT_TRUE(service->SetScore(uid, 1000)); EXPECT_EQ(service->GetScore(uid), 1000); EXPECT_TRUE(service->AddScore(uid, 1000)); EXPECT_EQ(service->GetScore(uid), 2000); EXPECT_TRUE(service->AddScore(uid, -1000)); EXPECT_EQ(service->GetScore(uid), 1000); } TEST(RedisService, UIDToFriendList) { EXPECT_TRUE(service->InsertFriendList(uid, 1234)); EXPECT_TRUE(service->InsertFriendList(uid, 1235)); EXPECT_TRUE(service->InsertFriendList(uid, 1236)); EXPECT_TRUE(service->InsertFriendList(uid, 1237)); auto ret = service->GetFriendList(uid); EXPECT_EQ(ret.size(), 4); std::unordered_set<std::string> set1; set1.insert("1234"); set1.insert("1235"); set1.insert("1236"); set1.insert("1237"); for(const auto str : ret) { set1.erase(std::string(str.c_str())); } EXPECT_TRUE(set1.empty()); EXPECT_TRUE(service->RemoveFriendList(uid, 1234)); EXPECT_EQ(service->GetFriendList(uid).size(), 3); } TEST(RedisService, UIDToRank) { EXPECT_TRUE(service->UpdateRank(uid, 1000)); EXPECT_TRUE(service->UpdateRank(uid + 1, 2000)); EXPECT_TRUE(service->UpdateRank(uid + 2, 3000)); EXPECT_EQ(service->GetRank(uid), 3); EXPECT_EQ(service->GetRank(uid + 1), 2); EXPECT_EQ(service->GetRank(uid + 2), 1); EXPECT_TRUE(service->AddRankScore(uid, 3000)); EXPECT_EQ(service->GetRank(uid), 1); auto ret = service->GetTopPlayer(2); EXPECT_EQ(ret.size(), 2); decltype(ret) rank = { "2345", "2347" }; EXPECT_EQ(rank, ret); } TEST(RedisService, MatchList) { EXPECT_TRUE(service->InsertMatchList(uid, 1000)); EXPECT_TRUE(service->InsertMatchList(uid, 1200)); EXPECT_TRUE(service->InsertMatchList(uid, 1300)); EXPECT_TRUE(service->InsertMatchList(uid, 1400)); const std::vector<acl::string> vec = {"1400", "1300", "1200", "1000"}; EXPECT_EQ(service->GetMatchList(uid), vec); } TEST(RedisService, MatchInfo) { EXPECT_TRUE(service->InsertMatchInfo(1000, "time", "12000")); EXPECT_TRUE(service->InsertMatchInfo(1000, "2345", "+12")); EXPECT_TRUE(service->InsertMatchInfo(1000, "2346", "-24")); EXPECT_TRUE(service->InsertMatchInfo(1000, "2347", "+12")); EXPECT_EQ(service->GetMatchInfo(1000).size(), 4); }
30.977612
74
0.669718
lsxk-jwj
b58022bbd3bbacc3c23f06777eb67a41f8982771
16,261
hpp
C++
core/src/cogs/io/net/telnet.hpp
cogmine/cogs
ef1c369a36a4f811704e0ced0493c3a6f8eca821
[ "MIT" ]
5
2019-02-08T15:59:14.000Z
2022-01-22T19:12:33.000Z
core/src/cogs/io/net/telnet.hpp
cogmine/cogs
ef1c369a36a4f811704e0ced0493c3a6f8eca821
[ "MIT" ]
1
2019-12-03T03:11:34.000Z
2019-12-03T03:11:34.000Z
core/src/cogs/io/net/telnet.hpp
cogmine/cogs
ef1c369a36a4f811704e0ced0493c3a6f8eca821
[ "MIT" ]
null
null
null
// // Copyright (C) 2000-2020 - Colen M. Garoutte-Carson <colen at cogmine.com>, Cog Mine LLC // // Status: Good, NeedsTesting #ifndef COGS_HEADER_IO_NET_TELNET #define COGS_HEADER_IO_NET_TELNET #include "cogs/collections/container_queue.hpp" #include "cogs/collections/string.hpp" #include "cogs/env.hpp" #include "cogs/io/datastream_protocol.hpp" namespace cogs { namespace io { namespace net { // Adapts a datastream, usually TCP at remote port 23 /// @ingroup Net /// @brief Implements the telnet protocol. class telnet : public datastream_protocol { public: // Interface for terminal emulation that supports telnet options class terminal { private: weak_rcptr<telnet> m_telnet; friend class telnet; public: // notifications/requests // NOP by default virtual void telnet_are_you_there() {} // Called when remote party sends an AYT req. // This party needs to respond with something to prove they are there. virtual void telnet_interrupt_process() {} // Received an Interrupt Process (IP) message from remote party virtual void telnet_abort_output() {} // Received an Abort Output (AO) message from remote party virtual void telnet_erase_char() {} // Received an Erase Character (EC) message from remote party virtual void telnet_erase_line() {} // Received an Erase Line (EL) message from remote party virtual void telnet_break() {} // Received a Break message from remote party virtual bool telnet_request_echo(bool) { return false; } // received request to set echo state virtual bool telnet_notify_echo(bool echoOn) { return echoOn; } // received request to set echo state virtual cstring get_telnet_terminal_type() { return cstring::literal("UNKNOWN"); } virtual void get_window_size(uint16_t& width, uint16_t& height) { (void)width; (void)height; } // Terminal utils void send_window_size(uint16_t width, uint16_t height) { rcptr<telnet> t = m_telnet; if (!!t) t->send_window_size(width, height); } }; private: weak_rcptr<terminal> m_terminal; volatile buffer m_recvBuffer; static constexpr unsigned char IAC = 255; static constexpr unsigned char DONT = 254; static constexpr unsigned char DO = 253; static constexpr unsigned char WONT = 252; static constexpr unsigned char WILL = 251; static constexpr unsigned char SB = 250; static constexpr unsigned char GA = 249; static constexpr unsigned char EL = 248; static constexpr unsigned char EC = 247; static constexpr unsigned char AYT = 246; static constexpr unsigned char AO = 245; static constexpr unsigned char IP = 244; static constexpr unsigned char BRK = 243; static constexpr unsigned char DATAMARK =242; static constexpr unsigned char NOP = 241; static constexpr unsigned char SE = 240; static constexpr unsigned char SEND = 1; static constexpr unsigned char IS = 0; static constexpr unsigned char TELOPT_BINARY = 0; static constexpr unsigned char TELOPT_ECHO = 1; static constexpr unsigned char TELOPT_SGA = 3; // Suppress Go Ahead. static constexpr unsigned char TELOPT_STATUS = 5; static constexpr unsigned char TELOPT_TIMING = 6; static constexpr unsigned char TELOPT_RCTE = 7; static constexpr unsigned char TELOPT_NAOCRD = 10; static constexpr unsigned char TELOPT_NAOHTS = 11; static constexpr unsigned char TELOPT_NAOHTD = 12; static constexpr unsigned char TELOPT_NAOFFD = 13; static constexpr unsigned char TELOPT_NAOVTS = 14; static constexpr unsigned char TELOPT_NAOVTD = 15; static constexpr unsigned char TELOPT_NAOLFD = 16; static constexpr unsigned char TELOPT_EXTEND_ASCII = 17; // WILL, DO static constexpr unsigned char TELOPT_LOGOUT = 18; // static constexpr unsigned char TELOPT_BM = 19; // Byte Macro static constexpr unsigned char TELOPT_DET = 20; // Data Entry Terminal static constexpr unsigned char TELOPT_SUPDUP = 21; // SUPDUP terminal? RFC734 static constexpr unsigned char TELOPT_SUPDUPOUTPUT = 22; // SUPDUP terminal within existing term? RFC749 static constexpr unsigned char TELOPT_SENDLOCATION = 23; // Send location string static constexpr unsigned char TELOPT_TTYPE = 24; // Terminal Type - RFC1091 static constexpr unsigned char TELOPT_EOR = 25; // Necessary? static constexpr unsigned char TELOPT_TUID = 26; // TAC? - Anyone still use this? static constexpr unsigned char TELOPT_OUTMRK = 27; // RFC933 static constexpr unsigned char TELOPT_TTYLOC = 28; // Terminal ID number static constexpr unsigned char TELOPT_3270REGIME = 29; // 3270 terminal? static constexpr unsigned char TELOPT_X3PAD = 30; // Support X.3-PAD static constexpr unsigned char TELOPT_NAWS = 31; // Negotiate about window size. static constexpr unsigned char TELOPT_TERMSPEED = 32; // Not meaningful anymore static constexpr unsigned char TELOPT_FLOWCONTROL = 33; // Not meaningful anymore static constexpr unsigned char TELOPT_LINEMODE = 34; // Line edit mode - Lots to do there static constexpr unsigned char TELOPT_XDISPLOC = 35; // X-Windows display addr static constexpr unsigned char TELOPT_AUTHENTICATION=37; // RFC2941 static constexpr unsigned char TELOPT_ENCRYPT = 38; // RFC2946 static constexpr unsigned char TELOPT_NEWENVIRON = 39; // Environment options static constexpr unsigned char TELOPT_TN3270E = 40; // TN3270 Enchancements RFC2355 static constexpr unsigned char TELOPT_XAUTH = 41; // XAUTH? static constexpr unsigned char TELOPT_CHARSET = 42; // RFC2066 static constexpr unsigned char TELOPT_RSP = 42; // Remote Serial Port static constexpr unsigned char TELOPT_COMPORTOPTION= 44; // Not meaningful anymore static constexpr unsigned char TELOPT_SLE = 45; // Suppress Local Echo static constexpr unsigned char TELOPT_STARTTLS = 46; // Start TLS static constexpr unsigned char TELOPT_KERMIT = 47; // Kermit static constexpr unsigned char TELOPT_SENDURL = 48; // Send URL static constexpr unsigned char TELOPT_FORWARDX = 49; // Forward X? static constexpr unsigned char TELOPT_EXOPL = 255; int m_parserState = 0; unsigned char m_optionVerb; unsigned char m_myNegotiationState[256]; // A negotiation state per option unsigned char m_theirNegotiationState[256]; // A negotiation state per option // negotiation state values: // // 0 = news to me, I assume they wouldn't use it (6) // 1 = just sent DO/WILL without provocation, waiting // 2 = just sent DONT/WONT without provocation, waiting // 3 = just sent DONT/WONT response to WILL/DO, waiting // 4 = just sent DO/WILL response to WONT/DONT, waiting // 5 = We've decided that I/they WILL/DO // 6 = We've decided that I/they WONT/DONT cstring m_incomingSB; char m_option; bool m_sendNAWS = true; void handle_option(bool response) { unsigned char msg[3]; msg[0] = IAC; msg[2] = m_option; bool pos = (m_optionVerb == DO) || (m_optionVerb == WILL); bool asking = (m_optionVerb == DO) || (m_optionVerb == DONT); unsigned char* state; if (asking) { state = m_myNegotiationState; msg[1] = WONT; if (response) msg[1] = WILL; } else { state = m_theirNegotiationState; msg[1] = DONT; if (response) msg[1] = DO; } if (pos) { switch (*state) { case 0: // unsolicited case 6: // unsolicited, but already discussed case 2: // I just said no, and they are disagreeing. case 3: // I just said no, and they are disagreeing. get_sink_filter()->bypass(buffer((char*)&msg[0], 3)); case 1: // Said I would, this must be the response case 4: // They came around. *state = response ? 6 : 3; case 5: // must not respond when already in this mode break; default: COGS_ASSERT(false); break; } } else { switch (*state) { case 0: // unsolicitied case 1: // Was going to, but was just told not to. Confirm. case 4: // I just said I would, and they are disagreeing. case 5: // Already agreed I would, they changed their mind. get_sink_filter()->bypass(buffer((char*)&msg[0], 3)); case 2: // Already said I wont, this was a response. case 3: // They came around *state = response ? 5 : 4; case 6: // We already discussed this, no change, ignored. break; default: COGS_ASSERT(false); break; } } } virtual composite_buffer filtering_source(composite_buffer& src) { composite_buffer result; composite_buffer::const_iterator itor = src.get_first_const_iterator(); while (!!itor) { unsigned char c = *itor; switch (m_parserState) { case 0: // Normal state { if (c == IAC) { // always eat the first IAC. result.append(src.split_off_before(itor.get_position())); itor = src.get_first_const_iterator(); m_parserState = 1; } else ++itor; break; } case 5: // SB content { if (c == IAC) // Two in a row means the value itself { m_incomingSB.append(IAC); m_parserState = 4; ++itor; break; } if (c == SE) // sub neg is over { // I suppose once we support some options that have SBs, that could go here m_parserState = 0; ++itor; src.set_to_subrange(itor.get_position()); itor = src.get_first_const_iterator(); break; } // Looks like SB was interrupt with a new IAC. // Fall through to state 1 } case 1: // Got an IAC { switch (c) { case IAC: // second IAC indicates it's intended to be passed through. { m_parserState = 0; ++itor; break; } case DO: case DONT: case WILL: case WONT: { m_optionVerb = c; m_parserState = 2; ++itor; break; } case SB: { m_optionVerb = c; m_parserState = 3; ++itor; break; } case AYT: { rcptr<terminal> term = m_terminal; if (!!term) term->telnet_are_you_there(); m_parserState = 0; ++itor; src.set_to_subrange(itor.get_position()); itor = src.get_first_const_iterator(); break; } case AO: { rcptr<terminal> term = m_terminal; if (!!term) term->telnet_abort_output(); m_parserState = 0; ++itor; src.set_to_subrange(itor.get_position()); itor = src.get_first_const_iterator(); break; } case EC: { rcptr<terminal> term = m_terminal; if (!!term) term->telnet_erase_char(); m_parserState = 0; ++itor; src.set_to_subrange(itor.get_position()); itor = src.get_first_const_iterator(); break; } case EL: { rcptr<terminal> term = m_terminal; if (!!term) term->telnet_erase_line(); m_parserState = 0; ++itor; src.set_to_subrange(itor.get_position()); itor = src.get_first_const_iterator(); break; } case BRK: { rcptr<terminal> term = m_terminal; if (!!term) term->telnet_break(); m_parserState = 0; ++itor; src.set_to_subrange(itor.get_position()); itor = src.get_first_const_iterator(); break; } case IP: { rcptr<terminal> term = m_terminal; if (!!term) term->telnet_interrupt_process(); m_parserState = 0; ++itor; src.set_to_subrange(itor.get_position()); itor = src.get_first_const_iterator(); break; } case GA: // Go-Ahead is unnecessary. We won't ever be using any half-duplex connections. case NOP: default: { m_parserState = 0; ++itor; src.set_to_subrange(itor.get_position()); itor = src.get_first_const_iterator(); } } break; } case 2: // Receive option name - Pass option on to handler { m_option = c; switch (m_option) { case TELOPT_BINARY: // always binary on case TELOPT_SGA: // always SGA { handle_option(true); break; } case TELOPT_ECHO: // ask terminal { rcptr<terminal> term = m_terminal; if (!!term) { bool b; if ((m_optionVerb == DO) || (m_optionVerb == DONT)) b = term->telnet_request_echo(m_optionVerb == DO); else b = term->telnet_notify_echo(m_optionVerb == WILL); handle_option(b); } break; } case TELOPT_TTYPE: { if (m_optionVerb == DO) { handle_option(true); rcptr<terminal> term = m_terminal; cstring termType = (!!term) ? term->get_telnet_terminal_type() : cstring::literal("UNKNOWN"); unsigned char msg[4] = { IAC, SB, TELOPT_TTYPE, IS }; get_sink_filter()->bypass(buffer((char*)&msg[0], 4)); get_sink_filter()->bypass(encode_buffer_const(buffer(&termType[0], termType.get_length()))); //msg[0] = IAC; msg[1] = SE; get_sink_filter()->bypass(buffer((char*)&msg[0], 2)); } else handle_option(m_optionVerb == WILL); break; } case TELOPT_NAWS: { if (m_optionVerb == DONT) { m_sendNAWS = false; handle_option(false); } else if (m_optionVerb == DO) { m_sendNAWS = true; handle_option(true); rcptr<terminal> term = m_terminal; if (!!term) { uint16_t width = 80; uint16_t height = 24; term->get_window_size(width, height); send_window_size(width, height); } } else handle_option(m_optionVerb == WILL); break; } default: handle_option(false); break; } m_parserState = 0; src.set_to_subrange(itor.get_position()); itor = src.get_first_const_iterator(); break; } case 3: // Receive option name, then wait for content, plus IAC SE { m_option = c; m_incomingSB.clear(); m_parserState = 4; ++itor; break; } case 4: { // Do IAC's need escaping in an SB sequence? // We're supposed to receive one right before an SE. // But, what if we get one and something other than SE if after it? if (c == IAC) m_parserState = 5; else m_incomingSB.append(c); ++itor; break; } default: { COGS_ASSERT(false); break; } } } return result; } const buffer iacBuf{ 1, (char)IAC }; virtual composite_buffer filtering_sink(composite_buffer& src) { return encode_buffer(src); } composite_buffer encode_buffer_const(const composite_buffer& src) { composite_buffer src2(src); return encode_buffer(src2); } composite_buffer encode_buffer(composite_buffer& src) { composite_buffer result; composite_buffer::const_iterator itor = src.get_first_const_iterator(); while (!!itor) { bool foundIAC = ((unsigned char)*itor == IAC); ++itor; if (!foundIAC) continue; result.append(src.split_off_before(itor.get_position())); result.append(iacBuf); itor = src.get_first_const_iterator(); continue; } return result; } public: explicit telnet(const rcref<datastream>& ds, const rcptr<terminal>& term = 0) : datastream_protocol(ds), m_terminal(term) { if (!!term) term->m_telnet = this_rcref; memset(m_myNegotiationState, 0, 256); memset(m_theirNegotiationState, 0, 256); unsigned char msg[3]; msg[0] = IAC; msg[1] = WILL; msg[2] = TELOPT_SGA; get_sink_filter()->bypass(buffer((char*)&msg[0], 3)); m_myNegotiationState[TELOPT_SGA] = 1; //msg[0] = IAC; msg[1] = DO; //msg[2] = TELOPT_SGA; get_sink_filter()->bypass(buffer((char*)&msg[0], 3)); m_theirNegotiationState[TELOPT_SGA] = 1; //msg[0] = IAC; //msg[1] = DO; msg[2] = TELOPT_BINARY; get_sink_filter()->bypass(buffer((char*)&msg[0], 3)); m_theirNegotiationState[TELOPT_BINARY] = 1; //msg[0] = IAC; msg[1] = WILL; //msg[2] = TELOPT_BINARY; get_sink_filter()->bypass(buffer((char*)&msg[0], 3)); m_myNegotiationState[TELOPT_BINARY] = 1; //msg[0] = IAC; //msg[1] = WILL; msg[2] = TELOPT_TTYPE; get_sink_filter()->bypass(buffer((char*)&msg[0], 3)); m_myNegotiationState[TELOPT_TTYPE] = 1; } void send_window_size(uint16_t width, uint16_t height) { if (m_sendNAWS) { unsigned char msg[4] = { IAC, SB, TELOPT_NAWS }; get_sink_filter()->bypass(buffer((char*)&msg[0], 3)); msg[0] = (char)(width >> 8); msg[1] = (char)width; msg[2] = (char)(height >> 8); msg[3] = (char)height; get_sink_filter()->bypass(encode_buffer_const(buffer((char*)&msg[0], 4))); msg[0] = IAC; msg[1] = SE; get_sink_filter()->bypass(buffer((char*)&msg[0], 2)); } } }; } } } #endif
27.939863
108
0.665703
cogmine
b5869a966c858be6c802aeed55b10dba98576bc4
7,147
hpp
C++
tests/vex_tests.hpp
LIBHALA/hala
ff3950aef18b6cede48b45669be275b174f362a5
[ "BSD-3-Clause" ]
1
2021-02-25T16:21:42.000Z
2021-02-25T16:21:42.000Z
tests/vex_tests.hpp
mkstoyanov/hala
ff3950aef18b6cede48b45669be275b174f362a5
[ "BSD-3-Clause" ]
9
2020-09-03T23:31:22.000Z
2020-10-21T23:40:11.000Z
tests/vex_tests.hpp
mkstoyanov/hala
ff3950aef18b6cede48b45669be275b174f362a5
[ "BSD-3-Clause" ]
2
2020-03-03T17:39:37.000Z
2020-11-05T16:01:28.000Z
/* * Code Author: Miroslav Stoyanov * * Copyright (C) 2018 Miroslav Stoyanov * * This file is part of * Hardware Accelerated Linear Algebra (HALA) * */ #include "testing_common.hpp" template<typename T> T mabs2(T a){ return a * a; } template<typename T> std::complex<T> mabs2(std::complex<T> a){ T r = std::abs(a)*std::abs(a); return {r, r}; } template<typename T> T mabs(T a){ return std::abs(a); } template<typename T> std::complex<T> mabs(std::complex<T> a){ T r = std::abs(a); return {r, r}; } template<typename T, hala::regtype reg> void test_extended_registers(){ current_test<T> tests(regname(reg)); hala_rnd = 0; size_t N = 128; auto x = make_vector<T>(N); auto y = make_vector<T>(N); auto y2 = y; auto y_ref = y; T alpha = static_cast<T>(2.0); for(size_t i=0; i<N; i++) y_ref[i] += alpha * x[i]; // using vectorization, test multiply hala::mmpack<T, reg> scalar(alpha); for(size_t i=0; i<N; i+=scalar.stride){ hala::mmpack<T, reg> chunky = &y[i]; chunky += scalar * hala::mmload<reg>(&x[i]); chunky.put(&y[i]); } hassert(testvec(y, y_ref)); // test multiply add (fmadd) for(size_t i=0; i<N; i+=scalar.stride){ hala::mmpack<T, reg> chunky = &y2[i]; chunky.fmadd(scalar, &x[i]); chunky.put(&y2[i]); } hassert(testvec(y2, y_ref)); y = y_ref; auto vv = hala::mmzero<T, reg>(); std::stringstream ss; ss << vv; // covers the << overwrites // test divide scalar = static_cast<T>(4.0); hala::mmpack<T, reg> vexx; for(size_t i=0; i<N; i+=scalar.stride) hala::mmbind<reg>(&y[i]) /= scalar; for(size_t i=0; i<N; i++) y_ref[i] /= static_cast<T>(4.0); hassert(testvec(y, y_ref)); // test scale by mmpack y = y_ref; scalar -= hala::mmload<reg>(static_cast<T>(2.0)); for(size_t i=0; i<N; i+=scalar.stride){ auto v = hala::mmbind<reg>(&y[i]); v *= scalar; } for(size_t i=0; i<N; i++) y_ref[i] *= static_cast<T>(2.0); hassert(testvec(y, y_ref)); // test scale by value for(size_t i=0; i<N; i+=scalar.stride) hala::mmbind<reg>(&y[i]) *= scalar; for(size_t i=0; i<N; i++) y_ref[i] *= static_cast<T>(2.0); hassert(testvec(y, y_ref)); // test square-root x = y; y_ref = y; for(size_t i=0; i<N; i+=scalar.stride) hala::mmload<reg>(&x[i]).sqrt().put(&y[i]); for(size_t i=0; i<N; i+=scalar.stride) hala::mmbind<reg>(&x[i]).set_sqrt(); for(size_t i=0; i<N; i++) y_ref[i] = std::sqrt(y_ref[i]); hassert(testvec(y, y_ref, 5.E+01)); hassert(testvec(x, y_ref, 5.E+01)); // test abs() and abs2() hala_rnd = -20; y = make_vector<T>(N); y_ref = y; auto y_ref2 = y; auto nrm = hala::hala_abs(y[0]); for(auto v : y) nrm = std::max(nrm, hala::hala_abs(v)); for(size_t i=0; i<N; i+=scalar.stride) hala::mmload<reg>(&y[i]).abs().put(&x[i]); for(size_t i=0; i<N; i+=scalar.stride) hala::mmload<reg>(&y[i]).abs2().put(&y[i]); for(size_t i=0; i<N; i++) y_ref2[i] = mabs2(y_ref2[i]); for(size_t i=0; i<N; i++) y_ref[i] = mabs(y_ref[i]); hassert(testvec(x, y_ref)); hassert(testvec(y, y_ref2, nrm * nrm)); // test real and imag hala_rnd = 1; y = make_vector<T>(hala::mmpack<T, reg>::stride); for(size_t i=0; i<hala::mmpack<T, reg>::stride; i++){ auto yr = hala::mmload<reg>(&y[0]).real(i); auto yrr = std::real(y[i]); hassert(testnum(yr, yrr)); yr = hala::mmload<reg>(&y[0]).imag(i); yrr = std::imag(y[i]); hassert(testnum(yr, yrr)); } // test simple copy hala_rnd = 3; y = make_vector<T>(hala::mmpack<T, reg>::stride); hala::mmpack<T, reg> ytemp; for(size_t i=0; i<hala::mmpack<T, reg>::stride; i++) ytemp[i] = y[i]; y_ref = make_vector<T>(hala::mmpack<T, reg>::stride); ytemp.put(y_ref.data()); hassert(testvec(y, y_ref)); } template<typename T, template<typename, typename> class vclass, hala::regtype reg> void test_type_aligned_allocator(){ current_test<T> tests(std::string("alloc-") + regname(reg)); std::vector<T> x_ref, x_test; vclass<T, hala::aligned_allocator<T, reg>> x = {1.0, 2.0, 3.0}; hala::vcopy(x, x_ref); auto y = x; y.resize(11); std::swap(x, y); x = y; hala::vcopy(x, x_test); hassert(testvec(x_test, x_ref)); { auto t = std::move(x); x = vclass<T, hala::aligned_allocator<T, reg>>(2); x = std::move(t); } hala::vcopy(x, x_test); hassert(testvec(x_test, x_ref)); std::vector<vclass<T, hala::aligned_allocator<T, reg>>> fake_matrix(11, {17}); for(auto const& r : fake_matrix){ size_t pval = reinterpret_cast<size_t>(hala::get_data(r)); constexpr size_t alignment = hala::mmpack<T, reg>::stride * sizeof(T); hassert(pval % alignment == 0); // proper alignment } hala_rnd = 3; hala::aligned_vector<T, reg> vv, ww, rref; hala::vcopy( make_vector<T>(hala::mmpack<T, reg>::stride * 3), vv ); hala::vcopy( make_vector<T>(hala::mmpack<T, reg>::stride * 3), ww ); hala::vcopy(vv, rref); hala::axpy(1, ww, rref); for(auto iv = vv.begin(), iw = ww.begin(); iv != vv.end(); iv += hala::mmpack<T, reg>::stride, iw += hala::mmpack<T, reg>::stride) { hala::mmpack<T, reg> mm = &*iv; mm += &*iw; mm.put(&*iv); } hassert(testvec(vv, rref)); } template<template<typename, typename> class vclass, hala::regtype reg> void test_aligned_allocator(){ test_type_aligned_allocator<float, vclass, reg>(); test_type_aligned_allocator<double, vclass, reg>(); test_type_aligned_allocator<std::complex<float>, vclass, reg>(); test_type_aligned_allocator<std::complex<double>, vclass, reg>(); } template<typename T> void test_default(){ current_test<T> tests(std::string("alloc-default")); size_t num_entries = 256; hala_rnd = 3; // get some semi-random numbers auto rndx = make_vector<T>(num_entries); auto rndy = make_vector<T>(num_entries); // define two vectors aligned to the default register type hala::aligned_vector<T> x, y; // fill the vectors with the random data hala::vcopy(rndx, x); hala::vcopy(rndy, y); // perform operations using iterators for(auto ix = hala::mmbegin(x), iy = hala::mmbegin(y); ix < hala::mmend(x) && iy <= hala::mmend(y); hala::mmadvance(ix, iy)) { auto mmx = hala::mmbind(ix); // tests mmbind(iterator) mmx += iy; // tests += iterator auto mmy = hala::mmload(iy); // tests mmload(iterator) mmx *= mmy; // tests *= mmpack() } // on exit, mmx will sync back with ix // perform the same operations using the simple vectors for(size_t i=0; i<num_entries; i++) rndx[i] = (rndx[i] + rndy[i]) * rndy[i]; // copy the result to the rndy hala::vcopy(x, rndy); // compare the result computed with mmpack vs the regular one hassert(testvec(rndx, rndy)); }
30.156118
118
0.577165
LIBHALA
b58bd59f08a69d9871df8ccb02f407adcc23138c
5,461
cpp
C++
VISUALC/source/repos/Project10/main.cpp
giljr/c
b8058423f9feda06f05e67af617a1e2f5089f9e8
[ "MIT" ]
null
null
null
VISUALC/source/repos/Project10/main.cpp
giljr/c
b8058423f9feda06f05e67af617a1e2f5089f9e8
[ "MIT" ]
null
null
null
VISUALC/source/repos/Project10/main.cpp
giljr/c
b8058423f9feda06f05e67af617a1e2f5089f9e8
[ "MIT" ]
1
2021-06-29T08:26:40.000Z
2021-06-29T08:26:40.000Z
/* #Project 10 - Visual C++ 2019 - Exercise 1 - Homework - Snack Bar Description This program calculates how much each customer spends in a snack bar. In essence, this program initializes 3 matrices: p[1][7] - Price of the Snack bar Products q[7][1] - Quantity of each item asked t[1][7] - Total price to pay Then, Make the math matrices multiplication: p[1][7] * q[7][1] = t[1][7] _ _ _ _ | 5.00 | | 5.00 | | 8.79 | | 8.79 | | 9.99 | * [1,1,1,1,1,1,1] = | 9.99 | | 6.89 | | 6.89 | | 4.80 | | 4.80 | | 3.49 | | 3.49 | |_ 4.99_| |_ 4.99_| Total = $ 43.95 Other matrices, like 'seq', 'code' and 'menu' serves only for presentation purpose; The user enter Code + Product + Space serially; The user can accumulate the products; When done, type 'q' to get the Receipt; It is for the academy's elegant solution of Project 31:) Printing on the screen a test of the program using the first 3 digits for products and the last 3 digits for quantity of the RU identifier: *********************** Output: (RU 333 6 662) ------------------------------- :::::::JayThree Snack Bar:::::: Welcome!! ------------------------------- --------------MENU------------- Code Product Price ------------------------------- 1 Hot_Dog 5.00 2 X_Salad 8.79 3 X_Bacon 9.99 4 Mix 6.89 5 Salad 4.80 6 Water 3.49 7 Soda 4.99 ------------------------------- Please Choose your Combo:) Type:Code>Space>Quant>Enter: To Quit, type 'q':) 3 6 You chose: 6 x X-Bacon 3 6 You chose: 6 x X-Bacon 3 2 You chose: 2 x X-Bacon q Good Choice! Here you have the ticket: ___________Receipt:____________ Quant Price Product Total ------------------------------- 14 x 9.99 X_Bacon 139.86 ------------------------------- Total = 139.86 ------------------------------- Thank you for your visit and have a good appetite! *********************** Editor J3 Date: Jul, 15/2020 I'd like to thank Prof. Borin, Me.(https://br.linkedin.com/in/borinvini) o/ */ #include <stdio.h> int main() { int seq[1][7] = { 1, 2, 3, 4, 5, 6, 7 }; int code[1][7] = { 100, 101, 102, 103, 104, 105, 106 }; char menu[7][10] = { "Hot_Dog", "X_Salad", "X_Bacon", "Mix", "Salad", "Water", "Soda" }; float p[1][7] = { 5.00, 8.79, 9.99, 6.89, 4.80, 3.49, 4.99 }, t[1][7] = { 0 }, debit; int q[7][1] = { 0,0,0,0,0,0,0 }; int prows = 1, pcolumns = 7, qrows = 7, qcolumns = 1, trows = 1, tcolumns = 7; int i, j, k; float res = 0, sum = 0; int prod = 0; int quant = 0; /* Menu on screen splash */ printf("\n-------------------------------"); printf("\n:::::::JayThree Snack Bar::::::"); printf("\n\t Welcome!!"); printf("\n-------------------------------"); printf("\n--------------MENU-------------\n"); printf("Code\tProduct\t\tPrice\n"); printf("-------------------------------\n"); for (int i = 0; i < 1; i++) { for (int j = 0; j < 7; j++) { printf("%i\t", seq[i][j]); printf("%s\t\t", menu[j]); printf("%.2f\t\n", p[i][j]); } printf("-------------------------------"); } printf("\n\nPlease Choose your Combo:)\nType:Code>Space>Quant>Enter:\n"); printf("To Quit, type 'q':)\n"); scanf_s("%i %i", &prod, &quant); /* Populating 'q' matrix - quantity of each product indexed */ /* While loop exit by typing 'q' - Quit */ /* Product can be accumulated in a single bid */ while (getchar() != 'q') { switch (prod) { case 1: printf("You chose: %d x Hot Dog\n", quant); q[0][0] += quant; break; case 2: printf("You chose: %d x X-Salad\n", quant); q[1][0] += quant; break; case 3: printf("You chose: %d x X-Bacon\n", quant); q[2][0] += quant; break; case 4: printf("You chose: %d x Mix\n", quant); q[3][0] += quant; break; case 5: printf("You chose: %d x Salad\n", quant); q[4][0] += quant; break; case 6: printf("You chose: %d x Water\n", quant); q[5][0] += quant; break; case 7: printf("You chose: %d x Soda\n", quant); q[6][0] += quant; break; default: printf("Invalid Product:/\n"); break; } scanf_s("%i %i", &prod, &quant); } printf("\tGood Choice!\n"); /* Calculating all 't' matrix - total to pay = debit */ int m = 0; for (i = 0; i < prows; i++) { for (j = 0; j < qcolumns; j++) { for (k = 0; k < qrows; k++) { res += p[i][k] * q[k][j]; t[i][m] = res; m++; sum += res; res = 0; } debit = sum; sum = 0; } } /* Printing the receipt - print when there is value on 't' index */ printf("\n Here you have the ticket:\n\n"); printf("___________Receipt:____________\n"); printf("Quant\tPrice\tProduct\tTotal\n"); printf("-------------------------------\n"); for (i = 0; i < trows; i++) { for (j = 0; j < tcolumns; j++) { if (t[i][j] != 0) { printf("%d x\t", q[i][j]); printf("%.2f\t", p[i][j]); printf("%s\t", menu[j]); printf("%.2f\t\n", t[i][j]); } } printf("-------------------------------\n"); printf("\t\tTotal = %.2f\t", debit); printf("\t\t\n-------------------------------"); printf("\t\t\n"); } printf("\nThank you for your visit\nand have a good appetite!\n"); //system("pause"); return 0; }
24.271111
90
0.478301
giljr
b590fd34fdece371bdfa3668cfc75fdf0b20a1a4
10,537
cpp
C++
MCUME/teensycastaway41/mem.cpp
DigiTorus86/Teensy-R4ge-Pro
d94a73f4f60957b3f28a27b7d6f74b01a61121fa
[ "MIT" ]
1
2022-01-13T02:00:52.000Z
2022-01-13T02:00:52.000Z
MCUME/teensycastaway41/mem.cpp
DigiTorus86/Teensy-R4ge-Pro
d94a73f4f60957b3f28a27b7d6f74b01a61121fa
[ "MIT" ]
null
null
null
MCUME/teensycastaway41/mem.cpp
DigiTorus86/Teensy-R4ge-Pro
d94a73f4f60957b3f28a27b7d6f74b01a61121fa
[ "MIT" ]
1
2022-01-11T12:55:50.000Z
2022-01-11T12:55:50.000Z
/* * Castaway * (C) 1994 - 2002 Martin Doering, Joachim Hoenig * * $File$ - memory read/write * * This file is distributed under the GPL, version 2 or at your * option any later version. See doc/license.txt for details. * * revision history * 23.05.2002 JH FAST1.0.1 code import: KR -> ANSI, restructuring * 30.05.2002 JH Discontinued using mmap and mprotect, now using * Martin's memory access jump table. * 12.06.2002 JH Correct bus error/address error exception stack frame * 14.06.2002 JH LowRamSetX() functions improved. * 09.07.2002 JH Now loads any 192k ROM file * 10.07.2002 MAD Now loads any ROM file * 16.09.2002 JH Bugfix: Word access on unmapped I/O address stacked * two bus error stack frames. Fault address corrected. * 08.10.2002 JH Fixed integer types. * 27.10.2002 AG Trashed everything for more speed! mwuhahaha! */ #include <stdio.h> #include <stdlib.h> #include <malloc.h> #ifndef DREAMCAST #else #include <string.h> #endif #include "dcastaway.h" #include "st.h" #include "mem.h" #include "m68k_intrf.h" #include <Arduino.h> static unsigned rombase_pos=0; char rom[80]; // = ROM; #ifdef DREAMCAST void reinit_sdcard(void); char rom_sd[24] = ROM_SD; #endif static int samvol[16]={0,0,0,1,1,1,2,3,5,7,11,17,25,38,57,85}; extern uint32 psg[26]; #define lastpsg psg[25] #define sampos psg[24] PROGMEM char GetMemB(unsigned long address) { address &= MEMADDRMASK; if (address<MEMSIZE) return ReadB(address + membase); else if (address<ROMBASE2) return -1; else if (address<IOBASE) return ReadB(address + rombase); else if (address<IOBASE+IOSIZE) return DoIORB(address); return -1; } /* Fetch word, address may not be word-aligned */ PROGMEM short GetMemW(unsigned long address) { #ifdef CHKADDRESSERR address &= MEMADDRMASK; if (address & 0x1){ ExceptionGroup0(ADDRESSERR, address, 1); return -1; } #else address &= MEMADDRMASKS; #endif if (address<MEMSIZE) return ReadW(address + membase); else if (address<ROMBASE2) return -1; else if (address<IOBASE) return ReadW(address + rombase); else if (address<IOBASE+IOSIZE) return DoIORW(address); return -1; } /* Fetch dword, address may not be dword-aligned */ PROGMEM long GetMemL(unsigned long address) { #ifdef CHKADDRESSERR address &= MEMADDRMASK; if (address & 0x1){ ExceptionGroup0(ADDRESSERR, address, 1); return -1; } #else address &= MEMADDRMASKS; #endif if (address<MEMSIZE) return ReadL(address + membase); else if (address<ROMBASE2) return -1; if (address<IOBASE) return ReadL(address + rombase); if (address<IOBASE+IOSIZE) return DoIORL(address); return -1; } /* Write byte to address */ PROGMEM void SetMemB (unsigned long address, unsigned char value) { address &= MEMADDRMASK; ON_WRITE(address, value); if (address<MEMSIZE) { //RAM if (address<SVADDR && !GetFC2()){ ExceptionGroup0(BUSERR, address, 0); return; } WriteB(address + membase, value); return; } if (address>=IOBASE && address<IOBASE+IOSIZE) { //IO DoIOWB(address, value); return; } //Unmapped ON_UNMAPPED(address, value); } /* Write word, address may not be word-aligned */ PROGMEM void SetMemW(unsigned long address, unsigned short value) { #ifdef CHKADDRESSERR address &= MEMADDRMASK; if (address & 0x1){ ExceptionGroup0(ADDRESSERR, address, 1); return; } #else address &= MEMADDRMASKS; #endif ON_WRITE(address, value); if (address<MEMSIZE) { //RAM if (address<SVADDR ){ if (!GetFC2()||address<8){ ExceptionGroup0(BUSERR, address, 0); return; } } WriteW(address + membase, value); return; } if (address>=IOBASE && address<IOBASE+IOSIZE) { //IO DoIOWW(address, value); return; } //Unmapped ON_UNMAPPED(address, value); } /* Write dword, address may not be dword-aligned */ PROGMEM void SetMemL(unsigned long address, unsigned long value) { #ifdef CHKADDRESSERR address &= MEMADDRMASK; if (address & 0x1){ ExceptionGroup0(ADDRESSERR, address, 1); return; } #else address &= MEMADDRMASKS; #endif ON_WRITE(address, value); if (address<MEMSIZE) { //RAM if (address<SVADDR){ if (!GetFC2()||address<8){ ExceptionGroup0(BUSERR, address, 0); return; } } #ifdef OPTIMIZE_VMEM if ( (address >= vid_mem) && (address < (vid_mem+32768) ) ) { printf("vwlmem\n"); WriteL(&videobuf[address-vid_mem], value); } else #endif WriteL(address + membase, value); return; } if (address>=IOBASE && address<IOBASE+IOSIZE) { //IO DoIOWL(address, value); return; } //Unmapped ON_UNMAPPED(address, value); } #ifdef UNUSED //Simplifed versions of memory access commands used for instructions fetch //Instruction fetch is likely only to be from ram or rom, otherwise the //program will surely have crashed anyway! char GetMemBpc(unsigned long address) { address &= MEMADDRMASK; if (address<MEMSIZE) return ReadB(address + membase); else return ReadB(address + rombase); } short GetMemWpc(unsigned long address) { address &= MEMADDRMASK; if (address<MEMSIZE) return ReadW(address + membase); else return ReadW(address + rombase); } /* Fetch dword, address may not be dword-aligned */ long GetMemLpc(unsigned long address) { address &= MEMADDRMASK; if (address<MEMSIZE) return ReadL(address + membase); else return ReadL(address + rombase); } //Movep support //------------- void SetMemPW(unsigned long address, unsigned long value) { // int8 psgctrl1,value1; if (address&0xffff03==0xff8800) { uint32 psgctrl1=(value>>8)&15; uint32 value1=value&255; psg[psgctrl1]=value1; if (psgctrl1==lastpsg) sample[sampos++]=samvol[psg[8]]+samvol[psg[9]]+samvol[value1]; else if (psgctrl1==13 || psgctrl1==12) psg_epos=0; return; } address &= MEMADDRMASK; if (address>=IOBASE && address<IOBASE+IOSIZE) { //IO DoIOWB(address, (int8)(value>>8)); DoIOWB(address+2, (int8)value); return; } if (address<MEMSIZE) { //RAM if (address<SVADDR && !GetFC2()) ExceptionGroup0(BUSERR, address, 0); address+=(uint32)membase; WriteB(address, (int8)(value>>8)); WriteB(address+2, (int8)value); return; } } void SetMemPL(unsigned long address, unsigned long value) {// int8 psgctrl1,psgctrl2,value1,value2; if (address&0xffff03==0xff8800) { uint32 psgctrl1=(value>>24)&15; uint32 value1=(value>>16)&255; psg[psgctrl1]=value1; if (psgctrl1==lastpsg) sample[sampos++]=samvol[psg[8]]+samvol[psg[9]]+samvol[value1]; else if (psgctrl1==13 || psgctrl1==12) psg_epos=0; psgctrl1=(value>>8)&15; value1=value&255; if (psgctrl1==lastpsg) sample[sampos++]=samvol[psg[8]]+samvol[psg[9]]+samvol[value1]; else if (psgctrl1==13 || psgctrl1==12) psg_epos=0; return; } address &= MEMADDRMASK; if (address>=IOBASE && address<IOBASE+IOSIZE) { //IO DoIOWB(address, (int8)(value>>24)); DoIOWB(address+2, (int8)(value>>16)); DoIOWB(address+4, (int8)(value>>8)); DoIOWB(address+6, (int8)value); return; } if (address<MEMSIZE) { //RAM if (address<SVADDR && !GetFC2()) ExceptionGroup0(BUSERR, address, 0); address+=(uint32)membase; WriteB(address, (int8)(value>>24)); WriteB(address+2, (int8)(value>>16)); WriteB(address+4, (int8)(value>>8)); WriteB(address+6, (int8)value); return; } } static void *__rombase=NULL, *__membase=NULL; void MemQuit(void) { if (__membase) free(__membase); __membase=NULL; if (__rombase) free(__rombase); __rombase=NULL; } static void _set_dword(void *buf,unsigned dat) { unsigned short *b=(unsigned short *)buf; *b++=dat&0xffff; *b=dat>>16; } void MemClean(void) { membase=(int8*)__membase; memset(membase,0,MEMSIZE); //savestate_init(); memcpy (membase, ((int8*)__rombase)+rombase_pos, 8); _set_dword(membase+0x420,0x752019f3); _set_dword(membase+0x43a,0x237698aa); _set_dword(membase+0x51a,0x5555aaaa); #if MEMSIZE==0x00080000 _set_dword(membase+0x436,0x80000-0x8000); _set_dword(membase+0x42e,0x80000); WriteB(membase+0x425,1); WriteB(rombase+0xff8000,1); memconf=1; #else #if MEMSIZE==0x00100000 _set_dword(membase+0x436,0x100000-0x8000); _set_dword(membase+0x42e,0x100000); WriteB(membase+0x425,5); WriteB(rombase+0xff8000,5); memconf=5; #else #if MEMSIZE==0x00200000 _set_dword(membase+0x436,0x200000-0x8000); _set_dword(membase+0x42e,0x200000); WriteB(membase+0x425,2); WriteB(rombase+0xff8000,2); memconf=2; #else #if MEMSIZE==0x00400000 _set_dword(membase+0x436,0x400000-0x8000); _set_dword(membase+0x42e,0x400000); WriteB(membase+0x425,0xA); WriteB(rombase+0xff8000,0xA); memconf=0xA; #else #error DCaSTaway ERROR: MEMSIZE incorrect. #endif #endif #endif #endif _set_dword(membase+0x4c2,3); WriteW(membase+0x4a6,2); //if (TosCountry) // vid_syncmode=2; //else // vid_syncmode=0; } static unsigned actual_rom_crc=0; static unsigned rom_checksum(void) { int n; unsigned crc=0; for(n=ROMBASE2;n<MEMADDRSIZE;n++) crc+=(n+1)*rombase[n]; return crc; } void MemReInit(void) { unsigned crc=rom_checksum(); if (crc!=actual_rom_crc) MemInit(); else MemClean(); } PROGMEM int MemInit(void) { int n; uint8 val1,val2; unsigned long len; FILE *roms; //Load ROM if (NULL == (roms = fopen (rom, "rb"))) { #ifdef DREAMCAST reinit_sdcard(); if (NULL == (roms = fopen (rom_sd, "rb"))) #endif { if (__membase) memset(__membase,0,MEMSIZE); return 1; } } MemQuit(); fseek(roms,0,SEEK_END); len=(unsigned long)ftell(roms); fseek(roms,0,SEEK_SET); if (len>(MEMADDRSIZE-ROMBASE2)) len=(MEMADDRSIZE-ROMBASE2); if (len<=(192*1024)) rombase_pos=ROMBASE-ROMBASE2; else rombase_pos=0; if (!__rombase) __rombase = calloc(1,MEMADDRSIZE-ROMBASE2); rombase=(int8*)__rombase; for(n=0;n<(MEMADDRSIZE-ROMBASE2);n+=2) { rombase[n]=0x4e; rombase[n+1]=0x71; } if (len != fread(rombase+rombase_pos,1,len,roms)) { fclose(roms); return 2; } fclose (roms); #ifdef BYTES_SWAP for (n=0; n<(MEMADDRSIZE-ROMBASE2); n+=2) { val1 = rombase[n]; val2 = rombase[n+1]; rombase[n] = val2; rombase[n+1] =val1; } #endif /* precalculate rombase - now just address-adding happens later */ if (rombase_pos) { rombase -= ROMBASE2+rombase_pos-(ROMBASE-ROMBASE2); memcpy(rombase+ROMBASE2,rombase+ROMBASE,(MEMADDRSIZE-ROMBASE)); } else { rombase -= ROMBASE2; memcpy(rombase+ROMBASE,rombase+ROMBASE2,(MEMADDRSIZE-ROMBASE)); } TOS_FixRom((uint8 *)(((int8*)__rombase)+rombase_pos)); //Allocate and clear RAM if (!__membase) __membase = (int8*)calloc(1,MEMSIZE+0x10); MemClean(); actual_rom_crc=rom_checksum(); initialize_memmap(); return 0; } #endif
21.63655
86
0.692892
DigiTorus86
b59205c22fb73cbd3f92597ed12c7ff49f7d821c
730
cpp
C++
hw5/src/test_Country.cpp
Rytheking/OOP-refleming
db81b3efe7e99b00f84ca116287f6510c9e77493
[ "MIT" ]
null
null
null
hw5/src/test_Country.cpp
Rytheking/OOP-refleming
db81b3efe7e99b00f84ca116287f6510c9e77493
[ "MIT" ]
null
null
null
hw5/src/test_Country.cpp
Rytheking/OOP-refleming
db81b3efe7e99b00f84ca116287f6510c9e77493
[ "MIT" ]
null
null
null
#include "Country.h" #include "gtest/gtest.h" using namespace std; using namespace france; TEST(Country, Constructor) { float GDP = 314000000000; string continent("europe"); Country Country(GDP,continent); ASSERT_EQ(Country.GDP(),GDP); ASSERT_EQ(Country.continent(),continent); float newGDP = 130000; Country.GDP(newGDP); ASSERT_EQ(Country.GDP(),newGDP); } TEST(Country, Constness) { float GDP = 999999; string continent("africa"); const Country Country(GDP,continent); ASSERT_EQ(Country.GDP(),GDP); ASSERT_EQ(Country.continent(),continent); } int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
24.333333
47
0.664384
Rytheking
b594a909f22095675ae48fd2966ef8f1bb73403e
417
hpp
C++
libctrpf/include/CTRPluginFramework/System/Clock.hpp
MirayXS/Vapecord-ACNL-Plugin
247eb270dfe849eda325cc0c6adc5498d51de3ef
[ "MIT" ]
null
null
null
libctrpf/include/CTRPluginFramework/System/Clock.hpp
MirayXS/Vapecord-ACNL-Plugin
247eb270dfe849eda325cc0c6adc5498d51de3ef
[ "MIT" ]
null
null
null
libctrpf/include/CTRPluginFramework/System/Clock.hpp
MirayXS/Vapecord-ACNL-Plugin
247eb270dfe849eda325cc0c6adc5498d51de3ef
[ "MIT" ]
null
null
null
#ifndef CTRPLUGINFRAMREWORK_CLOCK_HPP #define CTRPLUGINFRAMREWORK_CLOCK_HPP #include "CTRPluginFramework/System/Time.hpp" namespace CTRPluginFramework { class Clock { public: Clock(void); Clock(Time time); Time GetElapsedTime(void) const; bool HasTimePassed(Time time) const; Time Restart(void); private: Time _startTime; }; } #endif
18.954545
47
0.64988
MirayXS
b59d7c70c5f754130b39ba2fe863763260c080e6
992
hpp
C++
src/gui.hpp
MisterIsmed/PhotoStick
9383a0b86409f4c1f398eb3b913b32adb9762070
[ "MIT" ]
null
null
null
src/gui.hpp
MisterIsmed/PhotoStick
9383a0b86409f4c1f398eb3b913b32adb9762070
[ "MIT" ]
null
null
null
src/gui.hpp
MisterIsmed/PhotoStick
9383a0b86409f4c1f398eb3b913b32adb9762070
[ "MIT" ]
null
null
null
#ifndef GUI_HPP #define GUI_HPP #include "GUIslice.h" #include "GUIslice_drv.h" #include "GUIslice_ex.h" #include "SdFat.h" #include "util.hpp" enum Animation { ANIM_LIGHT, ANIM_BLINK, ANIM_MARQUEE, }; struct StickConfig { const char *fileToLoad; Animation animation; CRGB animationColor; uint8_t brightness; uint8_t speed; uint8_t countdown; uint8_t repetitions; }; namespace Gui { // Initialize GUI. Needs SD access to enumerate BMP files. void init(SdFat &sd); // Update GUI, must be called periodically. If enableWarning is true, sets // background color to red (to warn about low battery voltage). // If is Running is true, will update status text void update(bool enableWarning, bool isRunning); // Return true if user has requested to launch IMAGE or CREATIVE mode. // In this case, cfg will be updated to carry all user-configured settings. // Otherwise, return false. bool readyToGo(StickConfig &cfg); } #endif // vim: et ts=2
21.106383
75
0.721774
MisterIsmed
b59edf51969128b8b7bbed720ce96ae262d8068c
723
cpp
C++
learncpp/average.cpp
ignaciop/c-varios
c8ef033485efd19a01fbc43658be36473eb1d08d
[ "MIT" ]
null
null
null
learncpp/average.cpp
ignaciop/c-varios
c8ef033485efd19a01fbc43658be36473eb1d08d
[ "MIT" ]
null
null
null
learncpp/average.cpp
ignaciop/c-varios
c8ef033485efd19a01fbc43658be36473eb1d08d
[ "MIT" ]
null
null
null
#include <iostream> #include <cstdint> class Average { private: int32_t m_total = 0; int8_t m_numbers = 0; public: Average() {} friend std::ostream& operator<<(std::ostream &out, const Average &average) { out << static_cast<double>(average.m_total) / average.m_numbers; return out; } Average& operator+=(int num) { m_total += num; ++m_numbers; return *this; } }; int main() { Average avg; avg += 4; std::cout << avg << '\n'; avg += 8; std::cout << avg << '\n'; avg += 24; std::cout << avg << '\n'; avg += -10; std::cout << avg << '\n'; (avg += 6) += 10; // 2 calls chained together std::cout << avg << '\n'; Average copy = avg; std::cout << copy << '\n'; return 0; }
15.0625
77
0.562932
ignaciop
b27158435fe44061b11bd04087b322d571542b30
4,017
hpp
C++
ConvertTours/Data/Tour_File.hpp
kravitz/transims4
ea0848bf3dc71440d54724bb3ecba3947b982215
[ "NASA-1.3" ]
2
2018-04-27T11:07:02.000Z
2020-04-24T06:53:21.000Z
ConvertTours/Data/Tour_File.hpp
idkravitz/transims4
ea0848bf3dc71440d54724bb3ecba3947b982215
[ "NASA-1.3" ]
null
null
null
ConvertTours/Data/Tour_File.hpp
idkravitz/transims4
ea0848bf3dc71440d54724bb3ecba3947b982215
[ "NASA-1.3" ]
null
null
null
//******************************************************** // Tour_File.hpp - Tour File Input/Output //******************************************************** #ifndef TOUR_FILE_HPP #define TOUR_FILE_HPP #include "Ext_Header.hpp" //--------------------------------------------------------- // Tour_File Class definition //--------------------------------------------------------- class Tour_File : public Ext_Header { public: Tour_File (Access_Type access = READ, Format_Type format = DEFAULT_FORMAT); Tour_File (char *filename, Access_Type access = READ, Format_Type format = DEFAULT_FORMAT); virtual ~Tour_File (void); int Household (void) { Get_Field (hhold, &lvalue); return (lvalue); } int Person (void) { Get_Field (person, &lvalue); return (lvalue); } int Tour (void) { Get_Field (tour, &lvalue); return (lvalue); } int Purpose (void) { Get_Field (purpose, &lvalue); return (lvalue); } int Mode (void) { Get_Field (mode, &lvalue); return (lvalue); } int Origin (void) { Get_Field (origin, &lvalue); return (lvalue); } int Destination (void) { Get_Field (destination, &lvalue); return (lvalue); } int Stop_Out (void) { Get_Field (stop_out, &lvalue); return (lvalue); } int Stop_In (void) { Get_Field (stop_in, &lvalue); return (lvalue); } int Start (void) { Get_Field (start, &lvalue); return (lvalue); } int Return (void) { Get_Field (end, &lvalue); return (lvalue); } int Group (void) { Get_Field (group, &lvalue); return (lvalue); } void Household (int value) { Put_Field (hhold, value); } void Person (int value) { Put_Field (person, value); } void Tour (int value) { Put_Field (tour, value); } void Purpose (int value) { Put_Field (purpose, value); } void Mode (int value) { Put_Field (mode, value); } void Origin (int value) { Put_Field (origin, value); } void Destination (int value) { Put_Field (destination, value); } void Stop_Out (int value) { Put_Field (stop_out, value); } void Stop_In (int value) { Put_Field (stop_in, value); } void Start (int value) { Put_Field (start, value); } void Return (int value) { Put_Field (end, value); } void Group (int value) { Put_Field (group, value); } virtual bool Create_Fields (void); int HHold_Field (void) { return (hhold); } int Person_Field (void) { return (person); } int Tour_Field (void) { return (tour); } int Purpose_Field (void) { return (purpose); } int Mode_Field (void) { return (mode); } int Origin_Field (void) { return (origin); } int Dest_Field (void) { return (destination); } int Stop_Out_Field (void) { return (stop_out); } int Stop_In_Field (void) { return (stop_in); } int Start_Field (void) { return (start); } int Return_Field (void) { return (end); } int Group_Field (void) { return (group); } int HHold_Field (char *name) { return ((hhold = Required_Field (name))); } int Person_Field (char *name) { return ((person = Required_Field (name))); } int Tour_Field (char *name) { return ((tour = Required_Field (name))); } int Purpose_Field (char *name) { return ((purpose = Required_Field (name))); } int Mode_Field (char *name) { return ((mode = Required_Field (name))); } int Origin_Field (char *name) { return ((origin = Required_Field (name))); } int Dest_Field (char *name) { return ((destination = Required_Field (name))); } int Stop_Out_Field (char *name) { return ((stop_out = Required_Field (name))); } int Stop_In_Field (char *name) { return ((stop_in = Required_Field (name))); } int Start_Field (char *name) { return ((start = Required_Field (name))); } int Return_Field (char *name) { return ((end = Required_Field (name))); } int Group_Field (char *name) { return ((group = Required_Field (name))); } protected: virtual bool Set_Field_Numbers (void); private: void Setup (void); int lvalue; int hhold, person, tour, purpose, mode, origin, destination, stop_out, stop_in, start, end, group; }; #endif
45.647727
99
0.620861
kravitz
b27440fa42855642dba8775c9d2c8585dcb325a5
5,999
hpp
C++
inc/goo_bitset.hpp
CrankOne/Goo
b909c72a5c87cd11d9c27d42b8332c1b5694cfe0
[ "MIT" ]
null
null
null
inc/goo_bitset.hpp
CrankOne/Goo
b909c72a5c87cd11d9c27d42b8332c1b5694cfe0
[ "MIT" ]
2
2017-12-28T10:09:43.000Z
2018-02-21T13:34:02.000Z
inc/goo_bitset.hpp
CrankOne/Goo
b909c72a5c87cd11d9c27d42b8332c1b5694cfe0
[ "MIT" ]
null
null
null
# include <cstdint> # include <cstddef> # include <ostream> # include <cassert> # include <cstring> # include <stdexcept> # include <bitset> # include <iostream> // XXX # pragma once namespace goo { /**@class Bitset * @brief A dynamic bitset implementaation. * * We want some nice features of bitsets which length may be parameterised * once during the runtime (or supposed to undergo rare resizes in non-critical * sections). We don't want to bring the boost dependencies, however. * * It has to be similar to std::vector<>, but optimized rather for single * allocation, rather than utilize some pro-active allocating strategies. * * We also want some synctactic sugar, like in std::bitset<N> (all(), none(), * binary operators, etc.). * * It may be wiped in future, if STL will introduce such a thing... Perhaps, * for the time being the bitset is a nice container to study for novice. * * Bits layout scheme * * For bitset of size N, the M words will be allocated, where M is computed as: * M = N/sizeof(Word_t) ; if N%sizeof(Word_t) == 0 * M = N/sizeof(Word_t) + 1 ; otherwise * Bits the will be placed in member Word_t * _data: * * | 0100 ... | 1100 ... | ... | 1010 .. | * Word #0 Word #1 ... Word #M * * In each word, the bits are numerated from right to left. For case when * _size%sizeof(Word_t) != 0, there is a last Word_t block which is * used only partially. Generally, we do not care about its content. To get rid * of it there is a special `_tailMask' member containing a bitmask disabling * those insignificant bits. * * @TODO: profile, study performance against different Word_t types * @TODO: allocators * @TODO: bitshift operators (<<. <<=, >>, >>=). * @TODO: check for big-endian platforms */ class Bitset { protected: typedef uint32_t Word_t; constexpr static size_t nBiW = 8*sizeof(Word_t); private: size_t _size; Word_t * _data; size_t _nWords; // real physical size of the _data Word_t _tailMask; protected: virtual Word_t * _alloc( size_t ); virtual void _delete( Word_t * ); void _free(); public: /// Empty set ctr. Bitset(); /// Bitset copy ctr. Bitset( const Bitset & ); /// Allocates set of size N. Bitset(size_t length); /// Allocates set of size N and sets to value. Bitset(size_t length, unsigned long v); /// Frees allocated memory. ~Bitset(); /// Assignment operator. Bitset & operator=(const Bitset&); /// Sets all bits to true. void set(); /// Sets n-th bit to `value'. void set(size_t n, bool value=true); /// Sets all bits to false. void reset(); /// Sets n-th bit to false. void reset(size_t n); /// Re-allocates the bitset. New bits will be appended to the back in /// undefined state. void resize(size_t); /// Inverts n-th bit in set, returns *this ref. Bitset & flip(size_t); /// Returns true if bitset is empty (of zero size). inline bool empty() const { return !_size; } // todo: suboptimal? /// Returns number of bits stored. inline size_t size() const { return _size; } /// Returns value of n-th bit. inline bool test(size_t n) const { assert( size() > n ); return _data[n/nBiW] & (Word_t{1} << (n%nBiW)); } /// Returns true, if all bits are set to truth. bool all() const; operator bool() const { return any(); } /// Returns true if any of bits is set to truth. bool any() const; /// Returns true if none of bits is set to truth. bool none() const; /// Inverts all bits in set, returns *this ref. Bitset & flip(); Bitset operator~() const; /// Computes bitwise-and with given bitset, writing result to current set. Bitset & bitwise_and( const Bitset & ); inline Bitset & operator&=( const Bitset & bs) { return bitwise_and(bs); } Bitset operator&( const Bitset & ) const; /// Computes bitwise-or with givine bitset, writing result to current set. Bitset & bitwise_or( const Bitset & ); inline Bitset & operator|=( const Bitset & bs) { return bitwise_or(bs); } Bitset operator|( const Bitset & ) const; /// Computes bitwise-exclusive-or with givine bitset, writing result to /// current set. Bitset & bitwise_xor( const Bitset & ); inline Bitset & operator^=( const Bitset & bs) { return bitwise_xor(bs); } Bitset operator^( const Bitset & ) const; /// Template method performing bitwise conversion to certain type. template<typename T> T to() const; /// Returns textual representation of the bitset as a sequence of 1 and 0. std::string to_string() const; /// Returns unsigned long representation of bitset. inline unsigned long to_ulong() const { return to<unsigned long>(); } /// Returns unsigned long long representation of bitset. inline unsigned long long to_ullong() const { return to<unsigned long long>(); } friend std::ostream & operator<<( std::ostream & os, const Bitset & bs ) { os << bs.to_string(); return os; } //void dump( std::ostream &); // XXX: for debugging }; template<typename T> T Bitset::to() const { // Note: to follow strict aliasing rule, we have to create a temporary copy // of words array. Violating this rule causes optimized code to mess up the // copying logic yielding malformed results. if( sizeof(T)*8 < _size ) throw std::overflow_error("Bitset is too large."); Word_t result[ sizeof(T) > sizeof(Word_t) ? sizeof(T)/sizeof(Word_t) : 1 ]; bzero( result, sizeof(result) ); for( size_t nw = 0; nw < _nWords; ++nw ) { memcpy( result + nw , _data + nw , sizeof(Word_t) ); } *result &= _tailMask; T r; memcpy( &r, result, sizeof(T) ); return r; } template<> std::string Bitset::to<std::string>() const; # if 0 template<size_t N> std::bitset<N> Bitset::to<std::bitset<N>>() const { // ... } # endif } // namespace goo
34.28
84
0.643441
CrankOne
b27646379e7355c5d70bb819fe7d05851993e12d
951
cpp
C++
src/dev/memory_dev.cpp
RupertAvery/et3400
243c0ed407bee20f43e2f1c528f10cc6ffb12664
[ "BSD-3-Clause" ]
3
2020-11-06T22:30:32.000Z
2021-12-24T06:30:32.000Z
src/dev/memory_dev.cpp
RupertAvery/et3400
243c0ed407bee20f43e2f1c528f10cc6ffb12664
[ "BSD-3-Clause" ]
null
null
null
src/dev/memory_dev.cpp
RupertAvery/et3400
243c0ed407bee20f43e2f1c528f10cc6ffb12664
[ "BSD-3-Clause" ]
1
2021-12-24T06:30:38.000Z
2021-12-24T06:30:38.000Z
#include "stdlib.h" #include "memory_dev.h" #include "string.h" memory_device::memory_device(offs_t start, size_t size, bool readonly) { this->readonly = readonly; this->start = start; this->size = size; end = start + size - 1; memory = (uint8_t *)malloc(size); next = NULL; }; memory_device::~memory_device() { free(memory); } uint8_t memory_device::read(offs_t addr) { return memory[addr - start]; }; void memory_device::write(offs_t addr, uint8_t data) { if (!readonly) { memory[addr - start] = data; } }; bool memory_device::is_mapped(offs_t addr) { return addr >= start && addr <= end; } uint8_t *memory_device::get_mapped_memory() { return memory; }; offs_t memory_device::get_start() { return start; }; offs_t memory_device::get_end() { return end; }; void memory_device::load(offs_t addr, uint8_t *data, int size) { memcpy(&memory[addr - start], data, size); }
16.396552
70
0.648791
RupertAvery
b280fe5af68259f4869de4427cd49488b58b46ec
4,083
cpp
C++
tests/db.cpp
Carlosnuji/Plantas
01b822794184b5d8803bb445cd927b38ad6e57d5
[ "MIT" ]
null
null
null
tests/db.cpp
Carlosnuji/Plantas
01b822794184b5d8803bb445cd927b38ad6e57d5
[ "MIT" ]
null
null
null
tests/db.cpp
Carlosnuji/Plantas
01b822794184b5d8803bb445cd927b38ad6e57d5
[ "MIT" ]
null
null
null
#include "db.h" Db::Db() { m_db = QSqlDatabase::addDatabase("QPSQL"); m_db.setHostName("localhost"); m_db.setDatabaseName("template1"); m_db.setPort(5432); m_db.setUserName("postgres"); m_db.setPassword(""); } bool Db::isNumber(const std::string& s) { std::string::const_iterator it = s.begin(); while (it != s.end() && std::isdigit(*it)) ++it; return !s.empty() && it == s.end(); } bool Db::init() { bool init = false; bool ok = m_db.open(); if(ok) { qDebug() << "Eliminando base datos"; QSqlQuery query("DROP DATABASE IF EXISTS testplantas", m_db); if(query.lastError().type() == QSqlError::NoError) { qDebug() << "Creando base datos"; QSqlQuery query1("CREATE DATABASE testplantas", m_db); if(query1.lastError().type() == QSqlError::NoError) { m_db.close(); m_db.setDatabaseName("testplantas"); m_db.open(); QSqlQuery extension("CREATE EXTENSION pgcrypto;", m_db); QString createUser = "CREATE TABLE usuario ( \ idusuario serial PRIMARY KEY, \ nombre VARCHAR (50) UNIQUE NOT NULL, \ password TEXT NOT NULL, \ email VARCHAR (100) UNIQUE NOT NULL, \ status INTEGER )"; QSqlQuery query1 (createUser, m_db); QString createPlanta = "CREATE TABLE planta ( \ idplanta serial PRIMARY KEY, \ nombre VARCHAR (50) NOT NULL, \ nombrecientifico VARCHAR (50) NOT NULL, \ descripcion VARCHAR (50) NOT NULL, \ imagen BYTEA )"; QSqlQuery query2 (createPlanta, m_db); QString createToken = "CREATE TABLE token ( \ idtoken serial PRIMARY KEY, \ uuid TEXT, \ idusuario INTEGER, \ date date default CURRENT_DATE )"; QSqlQuery query3 (createToken, m_db); QString createQueja = "CREATE TABLE queja ( \ idqueja serial PRIMARY KEY, \ idusuario INTEGER, \ queja TEXT )"; QSqlQuery query4 (createQueja, m_db); QString createFavorito = "CREATE TABLE favorito ( \ idfavorito serial PRIMARY KEY, \ idusuario INTEGER, \ idplanta INTEGER )"; QSqlQuery query5 (createFavorito, m_db); init = true; } } // end if } // end if return init; } bool Db::insert(const std::string nombreTabla, const std::vector<std::string>& campos, const std::vector<std::string>& valores) { /// 1. Crear insert std::string strQuery = "INSERT INTO " + nombreTabla + " ("; for (ulong x = 0; x < campos.size(); x++) { if(x < campos.size() -1) strQuery += campos.at(x) + ","; else strQuery += campos.at(x); } strQuery += ") VALUES ("; for (ulong y = 0; y < valores.size(); y++) { if (!isNumber(valores.at(y)) && y < valores.size() - 1) strQuery += "'" + valores.at(y) + "'" + ","; else if (isNumber(valores.at(y)) && y < valores.size() - 1) strQuery += valores.at(y) + ","; else if (!isNumber(valores.at(y)) && y == valores.size() - 1) strQuery += "'" + valores.at(y) + "'"; } strQuery += ")"; //std::cout << strQuery << std::endl; /// 2. Ejecutar insert QSqlQuery query; query.prepare(QString::fromUtf8(strQuery.c_str())); bool ok = query.exec(); return ok; }
26.006369
127
0.467303
Carlosnuji
b281df1d8c43ace27ddd97bfd868a4e9f6b74703
130
cc
C++
Blob_Lib/assimp-5.2.3/assimp/contrib/draco/src/draco/javascript/emscripten/decoder_webidl_wrapper.cc
antholuo/Blob_Traffic
5d6acf88044e9abc63c0ff356714179eaa4b75bf
[ "MIT" ]
null
null
null
Blob_Lib/assimp-5.2.3/assimp/contrib/draco/src/draco/javascript/emscripten/decoder_webidl_wrapper.cc
antholuo/Blob_Traffic
5d6acf88044e9abc63c0ff356714179eaa4b75bf
[ "MIT" ]
null
null
null
Blob_Lib/assimp-5.2.3/assimp/contrib/draco/src/draco/javascript/emscripten/decoder_webidl_wrapper.cc
antholuo/Blob_Traffic
5d6acf88044e9abc63c0ff356714179eaa4b75bf
[ "MIT" ]
null
null
null
version https://git-lfs.github.com/spec/v1 oid sha256:be80c5d3aa7630ec26446c50687042c447392f0e383d7d5c046d90a089c2bc11 size 14155
32.5
75
0.884615
antholuo
b287806730d8a4096663c5b6d97afeab3dd8c923
6,355
cpp
C++
src/TotalEnergy/localTotalEnergy.cpp
pmu2022/lsms
3c5f266812cad0b6d570bef9f5abb590d044ef92
[ "BSD-3-Clause" ]
1
2022-01-27T14:45:51.000Z
2022-01-27T14:45:51.000Z
src/TotalEnergy/localTotalEnergy.cpp
pmu2022/lsms
3c5f266812cad0b6d570bef9f5abb590d044ef92
[ "BSD-3-Clause" ]
null
null
null
src/TotalEnergy/localTotalEnergy.cpp
pmu2022/lsms
3c5f266812cad0b6d570bef9f5abb590d044ef92
[ "BSD-3-Clause" ]
null
null
null
#include "localTotalEnergy.hpp" #include <cmath> #include "Misc/integrator.hpp" #include "PhysicalConstants.hpp" #include "Misc/poisson.hpp" extern "C" { void zeropt_(Real *ezpt, Real *tpzpt, Real *atvol, Real *ztotss); } /** * Calculates the total energy `energy` for each site * * @param lsms system parameters * @param atom atom object * @param energy total energy * @param pressure total pressure */ void localTotalEnergy(LSMSSystemParameters &lsms, AtomData &atom, Real &energy, Real &pressure) { Real eigenvalueSum = 0.0; Real kineticEnergy = 0.0; Real coulombEnergy = 0.0; Real xcEnergy = 0.0; Real ezpt = 0.0; Real tpzpt = 0.0; Real lsf_energy = 0.0; std::vector<Real> integral(atom.r_mesh.size()); std::vector<Real> integrand(atom.r_mesh.size()); energy = 0.0; pressure = 0.0; Real rSphere; switch (lsms.mtasa) { case 1: rSphere = atom.rws; break; case 2: rSphere = atom.rws; break; default: rSphere = atom.rInscribed; } /** * Calculate the zeropoint energy */ zeropt_(&ezpt, &tpzpt, &atom.omegaWS, &atom.ztotss); // calculate kinetic energy T: // T = \sum_{Core} e_i -- (1) // + \int^{E_F} e n(e) de -- (2) // - \int \rho(r) (v_{Coulomb} + v_{xc}) d^3r -- (3) // + \int m(r) (B_{xc} + B_{external}) d^3 -- (4) /** * Kinetic energy contributions */ if (lsms.n_spin_pola == 1) { eigenvalueSum = atom.evalsum[0] + atom.esemv[0]; kineticEnergy = atom.ecorv[0] + atom.esemv[0]; // (1) kineticEnergy += atom.evalsum[0]; // (2) for (int i = 0; i < atom.r_mesh.size(); i++) { integrand[i] = (atom.rhoNew(i, 0) * atom.vr(i, 0)) / (atom.r_mesh[i]); } } else { // spin polarized eigenvalueSum = atom.evalsum[0] + atom.evalsum[1] + atom.esemv[0] + atom.esemv[1]; kineticEnergy = atom.ecorv[0] + atom.ecorv[1] + atom.esemv[0] + atom.esemv[1]; // (1) kineticEnergy += atom.evalsum[0] + atom.evalsum[1]; // (2) for (int i = 0; i < atom.r_mesh.size(); i++) { integrand[i] = (atom.rhoNew(i, 0) * atom.vr(i, 0) + atom.rhoNew(i, 1) * atom.vr(i, 1)) / (atom.r_mesh[i]); } } kineticEnergy -= lsms::radialIntegral(integrand, atom.r_mesh, rSphere); if (lsms.global.iprint >= 0) { printf("evssum = %35.25lf Ry\n", eigenvalueSum); printf("kinetic Energy = %35.25lf Ry\n", kineticEnergy); } // calculate Coulomb Energy E_C: // E_C = \int \rho(r) v_{Coulomb} d^3r -- (5) // + E_{Madelung} -- (6) // external to this // routine // break the Coulomb integral in two parts: // \int \rho(r) v_{Coulomb} d^3r // = \int \rho(r) \int^r rho(r')/r' dr' dr -- (5a) // + \int rho(r) Z/r dr -- (5b) /** * Calculation of Coulomb contribution (5a) */ std::vector<double> vhartreederiv(atom.r_mesh.size(), 0.0); std::vector<double> vhartree(atom.r_mesh.size(), 0.0); std::vector<double> density(atom.r_mesh.size(), 0.0); if (lsms.n_spin_pola == 1) { for (auto i = 0; i < atom.r_mesh.size(); i++) { density[i] = atom.rhoNew(i, 0); } } else { for (auto i = 0; i < atom.r_mesh.size(); i++) { density[i] = (atom.rhoNew(i, 0) + atom.rhoNew(i, 1)); } } std::vector<double> radial_mesh_deriv(atom.r_mesh.size(), 0.0); for (auto i = 0; i < atom.r_mesh.size(); i++) { radial_mesh_deriv[i] = atom.r_mesh[i] * atom.h; } lsms::radial_poisson(vhartree, vhartreederiv, atom.r_mesh, radial_mesh_deriv, density, atom.jmt); if (lsms.n_spin_pola == 1) { for (auto i = 0; i < atom.r_mesh.size(); i++) { integral[i] = vhartree[i] * atom.rhoNew(i, 0); } } else { for (auto i = 0; i < atom.r_mesh.size(); i++) { integral[i] = vhartree[i] * (atom.rhoNew(i, 0) + atom.rhoNew(i, 1)); } } double erho = lsms::radialIntegral(integral, atom.r_mesh, rSphere); if (lsms.global.iprint >= 0) { printf("erho = %35.25lf Ry\n", erho); } /** * Calculation of the Coulomb contribution (5b) */ if (lsms.n_spin_pola == 1) { for (int i = 0; i < atom.r_mesh.size(); i++) { integrand[i] = 2.0 * (atom.rhoNew(i, 0)) * atom.ztotss / (atom.r_mesh[i]); } } else { // spin polarized for (int i = 0; i < atom.r_mesh.size(); i++) { integrand[i] = 2.0 * (atom.rhoNew(i, 0) + atom.rhoNew(i, 1)) * atom.ztotss / (atom.r_mesh[i]); } } Real ezrho = -lsms::radialIntegral(integrand, atom.r_mesh, rSphere); // FILE *fp; // fp = fopen("example.txt","w"); // for(int ir = 0; ir < atom.r_mesh.size(); ir++) { // std::fprintf(fp, "%.30e %.30e\n", integrand[ir], atom.r_mesh[ir]); // } // std::fclose(fp); if (lsms.global.iprint >= 0) { printf("ezrho = %35.25lf Ry\n", ezrho); } coulombEnergy = erho + ezrho; // (5) if (lsms.global.iprint >= 0) printf("Coulomb Energy = %35.25lf Ry\n", coulombEnergy); /** * Exchange-Correlation energy -- (7) */ if (lsms.n_spin_pola == 1) { for (int i = 0; i < atom.r_mesh.size(); i++) { integrand[i] = (atom.rhoNew(i, 0) * atom.exchangeCorrelationEnergy(i, 0)); } } else { // spin polarized for (int i = 0; i < atom.r_mesh.size(); i++) { integrand[i] = (atom.rhoNew(i, 0) * atom.exchangeCorrelationEnergy(i, 0) + atom.rhoNew(i, 1) * atom.exchangeCorrelationEnergy(i, 1)); } } xcEnergy = lsms::radialIntegral(integrand, atom.r_mesh, rSphere); if (lsms.global.iprint >= 0) { printf("Exchange-Correlation Energy = %35.25lf Ry\n", xcEnergy); printf("ezpt = %35.25lf Ry\n\n", ezpt); } /** * Longitudinal spin fluctuations */ if (lsms.n_spin_pola == 2) { auto mag_mom = atom.mvalws; lsf_energy += -convertKtoRydberg * lsms.temperature * atom.lsf_functional.entropy(mag_mom); } if (lsms.global.iprint >= 0) { printf("LSF energy = %35.25lf Ry\n\n", lsf_energy); } energy += kineticEnergy + coulombEnergy + xcEnergy + ezpt + lsf_energy; }
29.421296
80
0.545397
pmu2022
b287a4dfdf70b1f0ece58849a0385f7efcc2f599
5,745
cpp
C++
src/preferences/time/ClockView.cpp
Kirishikesan/haiku
835565c55830f2dab01e6e332cc7e2d9c015b51e
[ "MIT" ]
1,338
2015-01-03T20:06:56.000Z
2022-03-26T13:49:54.000Z
src/preferences/time/ClockView.cpp
Kirishikesan/haiku
835565c55830f2dab01e6e332cc7e2d9c015b51e
[ "MIT" ]
15
2015-01-17T22:19:32.000Z
2021-12-20T12:35:00.000Z
src/preferences/time/ClockView.cpp
Kirishikesan/haiku
835565c55830f2dab01e6e332cc7e2d9c015b51e
[ "MIT" ]
350
2015-01-08T14:15:27.000Z
2022-03-21T18:14:35.000Z
/* * Copyright 2004-2011, Haiku, Inc. All Rights Reserved. * Distributed under the terms of the MIT License. * * Authors: * John Scipione <jscipione@gmail.com> */ #include "ClockView.h" #include <Alignment.h> #include <Box.h> #include <Catalog.h> #include <CheckBox.h> #include <ControlLook.h> #include <LayoutBuilder.h> #include <Locale.h> #include <Message.h> #include <Messenger.h> #include <RadioButton.h> #include <SpaceLayoutItem.h> #include <Window.h> #include "TimeMessages.h" static const char* kDeskbarSignature = "application/x-vnd.Be-TSKB"; #undef B_TRANSLATION_CONTEXT #define B_TRANSLATION_CONTEXT "Time" ClockView::ClockView(const char* name) : BView(name, 0), fCachedShowClock(B_CONTROL_ON), fCachedShowSeconds(B_CONTROL_OFF), fCachedShowDayOfWeek(B_CONTROL_OFF), fCachedShowTimeZone(B_CONTROL_OFF) { fShowClock = new BCheckBox(B_TRANSLATE("Show clock in Deskbar"), new BMessage(kShowHideTime)); fShowSeconds = new BCheckBox(B_TRANSLATE("Display time with seconds"), new BMessage(kShowSeconds)); fShowDayOfWeek = new BCheckBox(B_TRANSLATE("Show day of week"), new BMessage(kShowDayOfWeek)); fShowTimeZone = new BCheckBox(B_TRANSLATE("Show time zone"), new BMessage(kShowTimeZone)); BView* view = BLayoutBuilder::Group<>(B_VERTICAL, 0) .SetExplicitMaxSize(BSize(B_SIZE_UNLIMITED, B_SIZE_UNSET)) .Add(fShowSeconds) .Add(fShowDayOfWeek) .Add(fShowTimeZone) .AddGlue() .SetInsets(B_USE_DEFAULT_SPACING) .View(); BBox* showClockBox = new BBox("show clock box"); showClockBox->SetExplicitAlignment(BAlignment(B_ALIGN_LEFT, B_ALIGN_TOP)); showClockBox->SetLabel(fShowClock); showClockBox->AddChild(view); BLayoutBuilder::Group<>(this) .AddGroup(B_VERTICAL, 0) .Add(showClockBox) .End() .SetInsets(B_USE_WINDOW_SPACING, B_USE_WINDOW_SPACING, B_USE_WINDOW_SPACING, B_USE_DEFAULT_SPACING); } ClockView::~ClockView() { } void ClockView::AttachedToWindow() { AdoptParentColors(); fShowClock->SetTarget(this); fShowSeconds->SetTarget(this); fShowDayOfWeek->SetTarget(this); fShowTimeZone->SetTarget(this); // Disable these controls initially, they'll be enabled // when we get a response from Deskbar. fShowClock->SetEnabled(false); fShowSeconds->SetEnabled(false); fShowDayOfWeek->SetEnabled(false); fShowTimeZone->SetEnabled(false); // Ask Deskbar for current clock settings, it will reply // asynchronously in MesssageReceived() below. BMessenger* messenger = new BMessenger(kDeskbarSignature); BMessenger replyMessenger(this); BMessage* message = new BMessage(kGetClockSettings); messenger->SendMessage(message, replyMessenger); } void ClockView::MessageReceived(BMessage* message) { switch (message->what) { case kGetClockSettings: { // Get current clock settings from Deskbar bool showClock; bool showSeconds; bool showDayOfWeek; bool showTimeZone; if (message->FindBool("showSeconds", &showSeconds) == B_OK) { fCachedShowSeconds = showSeconds ? B_CONTROL_ON : B_CONTROL_OFF; fShowSeconds->SetValue(fCachedShowSeconds); fShowSeconds->SetEnabled(true); } if (message->FindBool("showDayOfWeek", &showDayOfWeek) == B_OK) { fCachedShowDayOfWeek = showDayOfWeek ? B_CONTROL_ON : B_CONTROL_OFF; fShowDayOfWeek->SetValue(fCachedShowDayOfWeek); fShowDayOfWeek->SetEnabled(true); } if (message->FindBool("showTimeZone", &showTimeZone) == B_OK) { fCachedShowTimeZone = showTimeZone ? B_CONTROL_ON : B_CONTROL_OFF; fShowTimeZone->SetValue(fCachedShowTimeZone); fShowTimeZone->SetEnabled(true); } // do this one last because it might disable the others if (message->FindBool("showClock", &showClock) == B_OK) { fCachedShowClock = showClock ? B_CONTROL_ON : B_CONTROL_OFF; fShowClock->SetValue(fCachedShowClock); fShowClock->SetEnabled(true); fShowSeconds->SetEnabled(showClock); fShowDayOfWeek->SetEnabled(showClock); fShowTimeZone->SetEnabled(showClock); } break; } case kShowHideTime: { bool showClock; if (message->FindBool("showClock", &showClock) == B_OK) { // message originated from Deskbar, handle special fShowClock->SetValue(showClock ? B_CONTROL_ON : B_CONTROL_OFF); fShowSeconds->SetEnabled(showClock); fShowDayOfWeek->SetEnabled(showClock); fShowTimeZone->SetEnabled(showClock); Window()->PostMessage(kMsgChange); break; // don't fall through } showClock = fShowClock->Value() == B_CONTROL_ON; fShowSeconds->SetEnabled(showClock); fShowDayOfWeek->SetEnabled(showClock); fShowTimeZone->SetEnabled(showClock); } // fall-through case kShowSeconds: case kShowDayOfWeek: case kShowTimeZone: { BMessenger* messenger = new BMessenger(kDeskbarSignature); messenger->SendMessage(message); Window()->PostMessage(kMsgChange); break; } case kMsgRevert: _Revert(); break; default: BView::MessageReceived(message); break; } } bool ClockView::CheckCanRevert() { return fShowClock->Value() != fCachedShowClock || fShowSeconds->Value() != fCachedShowSeconds || fShowDayOfWeek->Value() != fCachedShowDayOfWeek || fShowTimeZone->Value() != fCachedShowTimeZone; } void ClockView::_Revert() { if (fShowClock->Value() != fCachedShowClock) { fShowClock->SetValue(fCachedShowClock); fShowClock->Invoke(); } if (fShowSeconds->Value() != fCachedShowSeconds) { fShowSeconds->SetValue(fCachedShowSeconds); fShowSeconds->Invoke(); } if (fShowDayOfWeek->Value() != fCachedShowDayOfWeek) { fShowDayOfWeek->SetValue(fCachedShowDayOfWeek); fShowDayOfWeek->Invoke(); } if (fShowTimeZone->Value() != fCachedShowTimeZone) { fShowTimeZone->SetValue(fCachedShowTimeZone); fShowTimeZone->Invoke(); } }
25.30837
75
0.734378
Kirishikesan
b28833182c3530b089ade20291943b95527413f0
1,164
cpp
C++
practice/table.cpp
tntptntp/UCR-U16-CS10v
be0f360c4d29a1d2c5fac72ba6ab1e2db9df7654
[ "MIT" ]
null
null
null
practice/table.cpp
tntptntp/UCR-U16-CS10v
be0f360c4d29a1d2c5fac72ba6ab1e2db9df7654
[ "MIT" ]
null
null
null
practice/table.cpp
tntptntp/UCR-U16-CS10v
be0f360c4d29a1d2c5fac72ba6ab1e2db9df7654
[ "MIT" ]
null
null
null
#include <iostream> #include <iomanip> #include <string> using namespace std; const int MONTHS = 12; string monthName(int monthNumber){ string monthNames[] = {"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"}; return monthNames[monthNumber - 1]; } void PrintHeader (int yearColWidth, int tableColWidth) { string spacer(yearColWidth, ' '); cout << spacer; int i = 0; for (i = 1; i <= MONTHS; ++i) { cout << setw(tableColWidth) << monthName(i); } cout << endl; } int main(){ int years = 5; double data = 0.3; int startYear = 2012; int tableColWidth = 6; int yearColWidth = 8; // construct table of results: // start by outputting table header, // leaving blank space for Year column header: PrintHeader(yearColWidth, tableColWidth); // print table int i = 0; int j = 0; for (i = 0; i < years; ++i) { cout << setw(yearColWidth) << startYear + i; for (j = 0; j < MONTHS; ++j) { cout << setw(tableColWidth) << data; } cout << endl; } return 0; }
19.728814
100
0.546392
tntptntp
b289c5d51edb9c9502e6ebc3954c17fc58fddd28
274
hh
C++
nox/src/nox/lib/nox-config.hh
ayjazz/OESS
deadc504d287febc7cbd7251ddb102bb5c8b1f04
[ "Apache-2.0" ]
28
2015-02-04T13:59:25.000Z
2021-12-29T03:44:47.000Z
nox/src/nox/lib/nox-config.hh
ayjazz/OESS
deadc504d287febc7cbd7251ddb102bb5c8b1f04
[ "Apache-2.0" ]
552
2015-01-05T18:25:54.000Z
2022-03-16T18:51:13.000Z
nox/src/nox/lib/nox-config.hh
ayjazz/OESS
deadc504d287febc7cbd7251ddb102bb5c8b1f04
[ "Apache-2.0" ]
25
2015-02-04T18:48:20.000Z
2020-06-18T15:51:05.000Z
#ifndef NOX_CONFIG_HH #define NOX_CONFIG_HH const char* pkgdatadir = PKGDATADIR; const char* pkgsysconfdir = PKGSYSCONFDIR; const char* pkglibdir = PKGLIBDIR; const char* version = NOX_VERSION; const int buildnr = BUILDNR; #endif // -- NOX_CONFIG_HH
24.909091
42
0.715328
ayjazz
b28c6096a350a06a2f7eec772e063d1a62994bb9
2,420
cpp
C++
Hackerank/C++/A Very Big Sum.cpp
abdzitter/Daily-Coding-DS-ALGO-Practice
26ddbf7a3673608039a07d26d812fce31b69871a
[ "MIT" ]
289
2021-05-15T22:56:03.000Z
2022-03-28T23:13:25.000Z
Hackerank/C++/A Very Big Sum.cpp
abdzitter/Daily-Coding-DS-ALGO-Practice
26ddbf7a3673608039a07d26d812fce31b69871a
[ "MIT" ]
1,812
2021-05-09T13:49:58.000Z
2022-01-15T19:27:17.000Z
Hackerank/C++/A Very Big Sum.cpp
abdzitter/Daily-Coding-DS-ALGO-Practice
26ddbf7a3673608039a07d26d812fce31b69871a
[ "MIT" ]
663
2021-05-09T16:57:58.000Z
2022-03-27T14:15:07.000Z
/* Program Link: https://www.hackerrank.com/challenges/a-very-big-sum/problem Ques. In this challenge, you are required to calculate and print the sum of the elements in an array, keeping in mind that some of those integers may be quite large. Function Description Complete the aVeryBigSum function in the editor below. It must return the sum of all array elements. aVeryBigSum has the following parameter(s): - int ar[n]: an array of integers . Return - long: the sum of all array elements Sample Input: 5 1000000001 1000000002 1000000003 1000000004 1000000005 Output: 5000000015 */ #include <bits/stdc++.h> using namespace std; string ltrim(const string &); string rtrim(const string &); vector<string> split(const string &); /* * Complete the 'aVeryBigSum' function below. * * The function is expected to return a LONG_INTEGER. * The function accepts LONG_INTEGER_ARRAY ar as parameter. */ long aVeryBigSum(vector<long> ar) { int i; long sum=0; //when vector is of long size, take the variable array of datatype long, so that we can store tha value for(i=0;i<ar.size();i++){ sum+=ar[i]; //adding the values } return sum; } int main() { ofstream fout(getenv("OUTPUT_PATH")); string ar_count_temp; getline(cin, ar_count_temp); int ar_count = stoi(ltrim(rtrim(ar_count_temp))); string ar_temp_temp; getline(cin, ar_temp_temp); vector<string> ar_temp = split(rtrim(ar_temp_temp)); vector<long> ar(ar_count); for (int i = 0; i < ar_count; i++) { long ar_item = stol(ar_temp[i]); ar[i] = ar_item; } long result = aVeryBigSum(ar); fout << result << "\n"; fout.close(); return 0; } string ltrim(const string &str) { string s(str); s.erase( s.begin(), find_if(s.begin(), s.end(), not1(ptr_fun<int, int>(isspace))) ); return s; } string rtrim(const string &str) { string s(str); s.erase( find_if(s.rbegin(), s.rend(), not1(ptr_fun<int, int>(isspace))).base(), s.end() ); return s; } vector<string> split(const string &str) { vector<string> tokens; string::size_type start = 0; string::size_type end = 0; while ((end = str.find(" ", start)) != string::npos) { tokens.push_back(str.substr(start, end - start)); start = end + 1; } tokens.push_back(str.substr(start)); return tokens; }
20.862069
159
0.650413
abdzitter
b28ebc6c0c2cb69f6788975c718518096a2e27f9
691
hpp
C++
src/opengl/opengl_version/ff8/FF8Menu.hpp
Sebanisu/Field-Map-Editor
2f37986459785a78766de34e38fc3e21db8b6f14
[ "Unlicense" ]
null
null
null
src/opengl/opengl_version/ff8/FF8Menu.hpp
Sebanisu/Field-Map-Editor
2f37986459785a78766de34e38fc3e21db8b6f14
[ "Unlicense" ]
66
2021-09-27T23:58:02.000Z
2022-01-10T20:41:36.000Z
src/opengl/opengl_version/ff8/FF8Menu.hpp
Sebanisu/Field-Map-Editor
2f37986459785a78766de34e38fc3e21db8b6f14
[ "Unlicense" ]
null
null
null
// // Created by pcvii on 11/24/2021. // #ifndef MYPROJECT_FF8MENU_HPP #define MYPROJECT_FF8MENU_HPP #include "Fields.hpp" #include "Menu.hpp" namespace ff8 { class FF8Menu { public: FF8Menu(); void OnUpdate(float) const; void OnRender() const; void OnImGuiUpdate() const; void OnEvent(const glengine::Event::Item &) const; template<glengine::Renderable T> void push_back(std::string name) const { m_menu.push_back(std::move(name), [this]() -> glengine::MenuItem { return glengine::MenuItem(std::in_place_type_t<T>{}, m_fields); }); } private: glengine::Menu m_menu{}; Fields m_fields = {}; }; }// namespace ff8 #endif// MYPROJECT_FF8MENU_HPP
19.742857
70
0.685962
Sebanisu
b2903a3e1f1af5114365a8e1f182d75499dcf3b1
3,605
cpp
C++
word_break.cpp
artureganyan/algorithms
98cd0048162b3cb1c79712a884261cd3fe31063c
[ "MIT" ]
null
null
null
word_break.cpp
artureganyan/algorithms
98cd0048162b3cb1c79712a884261cd3fe31063c
[ "MIT" ]
null
null
null
word_break.cpp
artureganyan/algorithms
98cd0048162b3cb1c79712a884261cd3fe31063c
[ "MIT" ]
null
null
null
// Problem: https://leetcode.com/problems/word-break/ #include <vector> #include <string> #include "utils.h" namespace word_break { class Solution { public: // Time: O(n^2 * d), Space: O(n), Recursion depth <= n + 2 // n - length of the string, d - length of the dictionary // // Note: The worst case looks like s = "aaaaa", dict = {"aaaab", "aaab", // "aab", "ab", "a"}, when we can split s only by the last word ("a"), but // need to compare s with the whole dictionary on each step. More // precisely, for the example above we compare s with d = dictionary.size() // words on the first step, s[2, s.size()] with d-1 words on the second // step, s[3, s.size()] with d-2 words on the third step, etc. This results // in comparing (n + n-1 + n-2 + ... + 1) characters on the first step, // (n-1 + n-2 + ... + 1) on the second one, and so on, giving O(n^2 * n) // comparisons. If d > n, the same worst case is when the dictionary // contain multiple words of the same length like {"aaaab", "aaaac", // "aaab", "aaac", ...}. Then, if d = n * k, the comparisons above are // repeated k times, giving O(n^2 * d) operations. // bool run(const std::string& s, const std::vector<std::string>& dictionary) { return canSplitByWords(s, 0, dictionary); } private: bool canSplitByWords(const std::string& s, int s_start, const std::vector<std::string>& dictionary) const { if (!s.size() || !dictionary.size()) return false; if (s_start == s.size()) return true; for (int i = 0; i < dictionary.size(); i++) { const std::string& word = dictionary[i]; if (s.compare(s_start, word.size(), word) != 0) continue; if (canSplitByWords(s, s_start + word.size(), dictionary)) return true; } return false; } }; int main() { ASSERT( Solution().run(std::string(), {}) == false ); ASSERT( Solution().run(std::string(), {std::string()}) == false ); ASSERT( Solution().run(std::string(), {"a"}) == false ); ASSERT( Solution().run("a", {}) == false ); ASSERT( Solution().run("a", {"a"}) == true ); ASSERT( Solution().run("a", {"b"}) == false ); ASSERT( Solution().run("a", {"aa"}) == false ); ASSERT( Solution().run("a", {"aa", "a"}) == true ); ASSERT( Solution().run("aa", {"a"}) == true ); ASSERT( Solution().run("aa", {"aa"}) == true ); ASSERT( Solution().run("aa", {"a", "aa"}) == true ); ASSERT( Solution().run("aa", {"a", "a"}) == true ); ASSERT( Solution().run("aa", {"a", "b"}) == true ); ASSERT( Solution().run("aa", {"b", "a"}) == true ); ASSERT( Solution().run("aa", {"aaa"}) == false ); ASSERT( Solution().run("aba", {"a", "b"}) == true ); ASSERT( Solution().run("abc", {"a", "b", "c"}) == true ); ASSERT( Solution().run("abc", {"ab", "c"}) == true ); ASSERT( Solution().run("abc", {"a", "bc"}) == true ); ASSERT( Solution().run("abc", {"abc"}) == true ); ASSERT( Solution().run("abc", {"ab", "bc"}) == false ); ASSERT( Solution().run("abacbc", {"a", "b", "c"}) == true ); ASSERT( Solution().run("abacbc", {"c", "acb", "ab"}) == true ); ASSERT( Solution().run("abacbc", {"bc", "ac", "ab"}) == true ); ASSERT( Solution().run("abacbc", {"cbc", "aba"}) == true ); ASSERT( Solution().run("abacbc", {"acbc", "abac"}) == false ); ASSERT( Solution().run("abacbc", {"acb", "ab"}) == false ); ASSERT( Solution().run("abacbc", {"ab", "cb", "c"}) == false ); return 0; } }
38.351064
109
0.533426
artureganyan
b291d6f8cb1d3d3d498aada7d7a1989ef7200683
71,350
cpp
C++
src/sim/Rasterizer/Rasterizer.cpp
attila-sim/attila-sim
a64b57240b4e10dc4df7f21eff0232b28df09532
[ "BSD-3-Clause" ]
23
2016-01-14T04:47:13.000Z
2022-01-13T14:02:08.000Z
src/sim/Rasterizer/Rasterizer.cpp
attila-sim/attila-sim
a64b57240b4e10dc4df7f21eff0232b28df09532
[ "BSD-3-Clause" ]
2
2018-03-25T14:39:20.000Z
2022-03-18T05:11:21.000Z
src/sim/Rasterizer/Rasterizer.cpp
attila-sim/attila-sim
a64b57240b4e10dc4df7f21eff0232b28df09532
[ "BSD-3-Clause" ]
17
2016-02-13T05:35:35.000Z
2022-03-24T16:05:40.000Z
/************************************************************************** * * Copyright (c) 2002 - 2011 by Computer Architecture Department, * Universitat Politecnica de Catalunya. * All rights reserved. * * The contents of this file may not be disclosed to third parties, * copied or duplicated in any form, in whole or in part, without the * prior permission of the authors, Computer Architecture Department * and Universitat Politecnica de Catalunya. * * $RCSfile: Rasterizer.cpp,v $ * $Revision: 1.25 $ * $Author: vmoya $ * $Date: 2007-01-21 18:57:45 $ * * Rasterizer class implementation file (unified version). * */ #include "Rasterizer.h" #include "RasterizerStateInfo.h" #include <cstring> #include <sstream> /** * * @file Rasterizer.cpp * * This file implements the Rasterizer class (unified shaders version). * * The Rasterizer class implements the main Rasterizer box. * */ /* Rasterizer constructor. */ using namespace gpu3d; Rasterizer::Rasterizer(RasterizerEmulator &rsEmu, u32bit trCycle, u32bit tsFIFOSize, u32bit trSetupUnits, u32bit trSetupLat, u32bit trSetupStartLat, u32bit trInputLat, u32bit trOutputLat, bool shSetup, u32bit trShQSz, u32bit stampsPerCycle, u32bit depthSamplesCycle, u32bit overWidth, u32bit overHeight, u32bit scanWidth, u32bit scanHeight, u32bit genWidth, u32bit genHeight, u32bit trBatchSz, u32bit trBatchQSz, bool recursive, bool hzDisabled, u32bit stampsBlock, u32bit hzBufferSz, u32bit hzCacheLins, u32bit hzCacheLineSz, u32bit hzQueueSz, u32bit hzBufferLat, u32bit hzUpLat, u32bit clearBCycle, u32bit numInterpolators, u32bit shInQSz, u32bit shOutQSz, u32bit shInBSz, bool shTileDistro, bool unified, u32bit nVShaders, char **vshPrefix, u32bit nFShaders, char **fshPrefix, u32bit shInCycle, u32bit shOutCycle, u32bit thGroup, u32bit fshOutLat, u32bit vInQSz, u32bit vOutQSz, u32bit trInQSz, u32bit trOutQSz, u32bit rastQSz, u32bit testQSz, u32bit intQSz, u32bit shQSz, u32bit nStampUnits, char **suPrefixes, char *name, Box *parent): /* Initializations. */ rastEmu(rsEmu), triangleSetupFIFOSize(tsFIFOSize), trianglesCycle(trCycle), triangleSetupUnits(trSetupUnits), triangleSetupLatency(trSetupLat), triangleSetupStartLat(trSetupStartLat), triangleInputLat(trInputLat), triangleOutputLat(trOutputLat), shadedSetup(shSetup), triangleShQSz(trShQSz), stampsCycle(stampsPerCycle), samplesCycle(depthSamplesCycle), overH(overHeight), overW(overWidth), scanH(scanHeight), scanW(scanWidth), genH(genHeight), genW(genWidth), trBatchSize(trBatchSz), trBatchQueueSize(trBatchQSz), recursiveMode(recursive), disableHZ(hzDisabled), blockStamps(stampsBlock), hzBufferSize(hzBufferSz), hzCacheLines(hzCacheLins), hzCacheLineSize(hzCacheLineSz), hzQueueSize(hzQueueSz), hzBufferLatency(hzBufferLat), hzUpdateLatency(hzUpLat), clearBlocksCycle(clearBCycle), interpolators(numInterpolators), shInputQSz(shInQSz), shOutputQSz(shOutQSz), shInputBatchSz(shInBSz), tiledShDistro(shTileDistro), unifiedModel(unified), numVShaders(nVShaders), numFShaders(nFShaders), shInputsCycle(shInCycle), shOutputsCycle(shOutCycle), threadGroup(thGroup), maxFShOutLat(fshOutLat), vInputQueueSz(vInQSz), vShadedQueueSz(vOutQSz), trInQueueSz(trInQSz), trOutQueueSz(trOutQSz), rastQueueSz(rastQSz), testQueueSz(testQSz), intQueueSz(intQSz), shQueueSz(shQSz), numStampUnits(nStampUnits), Box(name, parent) { u32bit genStamps; DynamicObject *defSignal[1]; /* Check parameters. */ GPU_ASSERT( if (stampsCycle < numStampUnits) panic("Rasterizer", "Rasterizer", "One stamp generated per cycle and stamp unit required."); if (shadedSetup && !unifiedModel) panic("Rasterizer", "Rasterizer", "Triangle setup in the shaders only supported for unified shader model."); ) /* Create command signal from the Command Processor. */ rastCommSignal = newInputSignal("RasterizerCommand", 1, 1, NULL); /* Create state signal to the Command Processor. */ rastStateSignal = newOutputSignal("RasterizerState", 1, 1, NULL); /* Build initial signal state. */ defSignal[0] = new RasterizerStateInfo(RAST_RESET); /* Set default state signal value. */ rastStateSignal->setData(defSignal); /* Create command signal to Triangle Setup. */ triangleSetupComm = newOutputSignal("TriangleSetupCommand", 1, 1, NULL); /* Create state signal from Triangle Setup. */ triangleSetupState = newInputSignal("TriangleSetupRasterizerState", 1, 1, NULL); /* Create command signal to Triangle Traversal. */ triangleTraversalComm = newOutputSignal("TriangleTraversalCommand", 1, 1, NULL); /* Create state signal from Triangle Traversal. */ triangleTraversalState = newInputSignal("TriangleTraversalState", 1, 1, NULL); /* Create command signal to Hierarchical Z. */ hzCommand = newOutputSignal("HZCommand", 1, 1, NULL); /* Create state sginal from Hierarchical Z. */ hzState = newInputSignal("HZState", 1, 1, NULL); /* Create command signal to Interpolator box. */ interpolatorComm = newOutputSignal("InterpolatorCommand", 1, 1, NULL); /* Create state signal from Interpolator box. */ interpolatorState = newInputSignal("InterpolatorRasterizerState", 1, 1, NULL); /* Create command signal to the Fragment FIFO. */ fFIFOCommand = newOutputSignal("FFIFOCommand", 1, 1, NULL); /* Create state signal from the Fragment FIFO. */ fFIFOState = newInputSignal("FFIFOState", 1, 1, NULL); /* Create rasterizer boxes. */ /* Create Triangle Setup box. */ triangleSetup = new TriangleSetup( rastEmu, /* Reference to the rasterizer emulator object to use. */ trianglesCycle, /* Triangles received from Clipper and sent to Triangle Traversal per cycle. */ tsFIFOSize, /* Size in triangles of the triangle FIFO. */ triangleSetupUnits, /* Number of setup units in the box. */ triangleSetupLatency, /* Latency of the setup unit. */ triangleSetupStartLat, /* Start latency of the setup unit. */ triangleInputLat, /* Latency of the bus with primitive assembly/clipper. */ 0, /* Latency of the bus with Triangle Bound unit (only in the Micropolygon rasterizer). */ triangleOutputLat, /* Latency of the bus with triangle traversal/fragment generation. */ shadedSetup, /* Performed triangle setup in the unified shaders. */ false, /* Not using the Triangle Bound unit (only in the Micropolygon rasterizer). */ false, /* Microtriangle bypass is disabled in the classic rasterizer. */ triangleShQSz, /* Size of the triangle shader queue. */ "TriangleSetup", this); /* Calculate number of stamps per generation tile. */ genStamps = stampsCycle * (genW / STAMP_WIDTH) * (genH / STAMP_HEIGHT); /* Create Triangle Traversal box. */ triangleTraversal = new TriangleTraversal( rastEmu, /* Reference to the rasterizer emulator object to be used. */ trianglesCycle, /* Triangles received from Triangle Setup per cycle. */ triangleOutputLat, /* Latency of the triangle bus from Triangle Setup. */ genStamps, /* Number of stamps to generate per cycle. */ samplesCycle, /* Number of MSAA samples to generate per fragment and cycle. */ trBatchSize, /* Number of triangles per rasterization batch. */ trBatchQueueSize, /* Number of triangles in the triangle queue. */ recursiveMode, /* Rasterization method: recursive or scanline. */ false, /* Microtriangle bypass is disabled in the classic rasterizer. */ numStampUnits, /* Number of stamp units (Z Stencil/Color Write) in the GPU. */ overW, /* Over scan tile width in scan tiles. */ overH, /* Over scan tile height in scan tiles. */ scanW, /* Scan tile height in registers. */ scanH, /* Scan tile width in registers. */ genW, /* Generation tile width in registers. */ genH, /* Generation tile height in registers. */ "TriangleTraversal", this); /* Create Hierarchical Z box. */ hierarchicalZ = new HierarchicalZ( genStamps, /* Stamps received per cycle. */ overW, /* Over scan tile width in scan tiles. */ overH, /* Over scan tile height in scan tiles. */ scanW, /* Scan tile height in registers. */ scanH, /* Scan tile width in registers. */ genW, /* Generation tile width in registers. */ genH, /* Generation tile height in registers. */ disableHZ, /* Flag that disables Hierarchical Z. */ blockStamps, /* Fragment stamps per HZ block. */ hzBufferSize, /* Size in block representatives of the Hierarchical Z Buffer. */ hzCacheLines, /* Hierarchical Z cache lines. */ hzCacheLineSize, /* Block info stored per HZ Cache line. */ hzQueueSize, /* Size of the Hierarchical Z test queue. */ hzBufferLatency, /* Access latency to the Hierarchical Z Buffer. */ hzUpdateLatency, /* Latency of the update signal from Z Stencil. */ clearBlocksCycle, /* Block representatives cleared per cycle in the HZ Buffer. */ numStampUnits, /* Number of stamp units (Z Stencil) attached to Fragment FIFO. */ suPrefixes, /* Array with the stamp unit prefixes. */ true, /* Process microtriangle fragments (enabled in the Micropolygon Rasterizer). */ 0, /* Microtriangle mode (enabled in the Micropolygon Rasterizer). */ "HierarchicalZ", this); /* Create Interpolator box. */ interpolator = new Interpolator( rastEmu, /* Reference to the rasterizer emulator to use for interpolation. */ interpolators, /* Number of attribute interpolator units. */ stampsCycle, /* Stamps received per cycle. */ numStampUnits, /* Number of stamp units in the GPU. */ "Interpolator", this); /* Create Fragment FIFO box. */ fFIFO = new FragmentFIFO( genStamps, /* Stamps received from HZ per cycle. */ stampsCycle, /* Stamps send down the pipeline per cycle. */ unifiedModel, /* Simulate an unified shader model. */ shadedSetup, /* Perform setup in the unified shaders. */ triangleSetupUnits, /* Triangles received/sent from Triangle Setup per cycle. */ triangleSetupLatency, /* Latency of the Triangle Setup triangle input/output signals. */ numVShaders, /* Number of virtual vertex shaders attached. */ numFShaders, /* Number of fragment shaders attached. */ shInputsCycle, /* Shader inputs per cycle and shader. */ shOutputsCycle, /* Shader outputs per cycle and shader. */ threadGroup, /* Threads in a shader processing group. */ maxFShOutLat, /* Maximum latency of the Shader output signal. */ interpolators, /* Number of attribute interpolators in the Interpolator. */ shInputQSz, /* Shader input queue size (per shader unit). */ shOutputQSz, /* Shader output queue size (per shader unit). */ shInputBatchSz, /* Shader input batch size. */ tiledShDistro, /* Enable/disable distribution of fragment inputs to the shader units on a tile basis. */ vInputQueueSz, /* Size of the vertex input queue. */ vShadedQueueSz, /* Size of the vertex output queue. */ trInQueueSz, /* Size of the triangle input queue. */ trOutQueueSz, /* Size of the triangle output queue. */ rastQueueSz, /* Generated stamp queue size (per stamp unit). */ testQueueSz, /* Early Z tested stamp queue size. */ intQueueSz, /* Interpolated stamp queue size. */ shQueueSz, /* Shaded stamp queue size (per stamp unit). */ vshPrefix, /* Array with the virtual vertex shaders prefixes. */ fshPrefix, /* Array with the fragment shaders prefixes. */ numStampUnits, /* Number of stamp units (Z Stencil) attached to Fragment FIFO. */ suPrefixes, /* Array with the stamp unit prefixes. */ "FragmentFIFO", this); /* Initialize the rasterizer state. */ state = RAST_RESET; /* Create first command. */ lastRastComm = new RasterizerCommand(RSCOM_RESET); } // Rasterizer destructor Rasterizer::~Rasterizer() { delete triangleSetup; delete triangleTraversal; delete hierarchicalZ; delete interpolator; delete fFIFO; } /* Rasterizer simulation function. */ void Rasterizer::clock(u64bit cycle) { RasterizerCommand *rastComm; RasterizerStateInfo *rastStateInfo; RasterizerState tsState; RasterizerState ttState; RasterizerState hierZState; RasterizerState intState; RasterizerState ffState; int i; GPU_DEBUG_BOX( printf("Rasterizer => Clock %lld\n", cycle); ) /* Clock all rasterizer boxes. */ /* Clock Triangle Setup. */ triangleSetup->clock(cycle); /* Clock Triangle Traversal. */ triangleTraversal->clock(cycle); /* Clock Hierarchical Z. */ hierarchicalZ->clock(cycle); /* Clock Interpolator. */ interpolator->clock(cycle); /* Clock Fragment FIFO. */ fFIFO->clock(cycle); /* Read state from all rasterizer boxes. */ /* Get the Triangle Setup state. */ if (triangleSetupState->read(cycle, (DynamicObject *&) rastStateInfo)) { /* Get triangle setup state. */ tsState = rastStateInfo->getState(); /* Delete rasterizer state info object. */ delete rastStateInfo; } else { panic("Rasterizer", "clock", "Missing signal from Triangle Setup."); } /* Get the Triangle Traversal state. */ if (triangleTraversalState->read(cycle, (DynamicObject *&) rastStateInfo)) { /* Get Triangle Traversal state. */ ttState = rastStateInfo->getState(); /* Delete rasterizer state info object. */ delete rastStateInfo; } else { panic("Rasterizer", "clock", "Missing signal from Triangle Traversal."); } /* Get the Hierarchical Z state. */ if (hzState->read(cycle, (DynamicObject *&) rastStateInfo)) { /* Get Hierarchical Z state. */ hierZState = rastStateInfo->getState(); /* Delete rasterizer state info object. */ delete rastStateInfo; } else { panic("Rasterizer", "clock", "Missing signal from Hierarchical Z."); } /* Read state from Interpolator. */ if (interpolatorState->read(cycle, (DynamicObject *&) rastStateInfo)) { /* Get interpolator state. */ intState = rastStateInfo->getState(); /* Delete rasterizer state info object. */ delete rastStateInfo; } else { panic("Rasterizer", "clock", "Missing signal from Interpolator."); } /* Read state from Fragment FIFO. */ if (fFIFOState->read(cycle, (DynamicObject *&) rastStateInfo)) { /* Get Fragment FIFO state. */ ffState = rastStateInfo->getState(); /* Delete rasterizer state info object. */ delete rastStateInfo; } else { panic("Rasterizer", "clock", "Missing signal from Fragment FIFO."); } /* Simulate current cycle. */ switch(state) { case RAST_RESET: /* The rasterizer is reset state. */ GPU_DEBUG_BOX( printf("Rasterizer => State RESET.\n"); ) /* Reset Rasterizer registers. */ hRes = 400; vRes = 400; d3d9PixelCoordinates = false; viewportIniX = 0; viewportIniY = 0; viewportWidth = 400; viewportHeight = 400; scissorTest = false; scissorIniX = 0; scissorIniY = 0; scissorWidth = 400; scissorHeight = 400; nearRange = 0.0; farRange = 1.0; d3d9DepthRange = false; hzEnable = TRUE; earlyZ = TRUE; modifyDepth = FALSE; clearDepth = 0x00ffffff; zBufferBitPrecission = 24; frustumClipping = TRUE; userClipPlanes = FALSE; cullMode = BACK; d3d9RasterizationRules = false; twoSidedLighting = FALSE; depthFunction = GPU_LESS; /* Set user clip plane default values. */ for(i = 0; i < MAX_USER_CLIP_PLANES; i++) userClip[i] = QuadFloat(0.0, 0.0, 0.0, 0.0); /* Set default fragment input attributes interpolation and active flags. */ for(i = 0; i < MAX_FRAGMENT_ATTRIBUTES; i++) { /* Set all fragment attributes as interpolated. */ interpolation[i] = TRUE; /* Set all fragment attributes as not active. */ fragmentAttributes[i] = FALSE; } // Reset the render target state. for(u32bit rt = 0; rt < MAX_RENDER_TARGETS; rt++) { rtEnable[rt] = false; colorMaskR[rt] = true; colorMaskG[rt] = true; colorMaskB[rt] = true; colorMaskA[rt] = true; } // Backbuffer/render target 0 enabled by default. rtEnable[0] = true; /* Change state to ready. */ state = RAST_READY; break; case RAST_READY: /* The rasterizer is ready to receive commands from the Command Processor. */ GPU_DEBUG_BOX( printf("Rasterizer => State READY.\n"); ) /* Check if there is an available rasterizer command from the Command Processor. */ if (rastCommSignal->read(cycle, (DynamicObject *&) rastComm)) { /* Process the command. */ processRasterizerCommand(rastComm, cycle); } break; case RAST_DRAWING: /* The rasterizer is drawing a batch for primitives. */ GPU_DEBUG_BOX( printf("Rasterizer => State DRAWING.\n"); ) /* Check if the rasterizer units has finished the current batch. */ if ((tsState == RAST_END) && (ttState == RAST_END) && (hierZState == RAST_END) && (intState == RAST_END) && (ffState == RAST_END)) { /* Change to END state. */ state = RAST_END; } break; case RAST_END: /* The rasterizer has finished drawing all the primitives in the current batch. Waiting for response from the Command Processor. */ GPU_DEBUG_BOX( printf("Rasterizer => State RAST_END.\n"); ) /* Check if there is an available rasterizer command from the Command Processor. */ if (rastCommSignal->read(cycle, (DynamicObject *&) rastComm)) { /* Process the command. */ processRasterizerCommand(rastComm, cycle); } case RAST_CLEAR: /* Clear state. */ GPU_DEBUG_BOX( printf("Rasterizer => State RAST_CLEAR.\n"); ) /* Wait until Hierarchical Z ends clearing the HZ buffer. */ if (hierZState == RAST_CLEAR_END) { /* Change state to end. */ state = RAST_CLEAR_END; } break; case RAST_CLEAR_END: /* The rasterizer has finished clearing the buffers. Waiting for response from the Command Processor. */ GPU_DEBUG_BOX( printf("Rasterizer => State RAST_CLEAR_END.\n"); ) /* Check if there is an available rasterizer command from the Command Processor. */ if (rastCommSignal->read(cycle, (DynamicObject *&) rastComm)) { /* Process the command. */ processRasterizerCommand(rastComm, cycle); } } /* Write state signal to the Command Processor. */ rastStateSignal->write(cycle, new RasterizerStateInfo(state)); } /* Process the rasterizer command. */ void Rasterizer::processRasterizerCommand(RasterizerCommand *rastComm, u64bit cycle) { RasterizerCommand *rastAuxComm; /* Delete previous rasterizer command. */ delete lastRastComm; /* Set new command as last command. */ lastRastComm = rastComm; /* Process command. */ switch(rastComm->getCommand()) { case RSCOM_RESET: /* Reset the rasterizer. */ GPU_DEBUG_BOX( printf("Rasterizer => RESET Command.\n"); ) /* Send reset signal to all rasterizer boxes. */ /* Send reset command to Triangle Setup. */ rastAuxComm = new RasterizerCommand(RSCOM_RESET); /* Copy cookies from original command. */ rastAuxComm->copyParentCookies(*rastComm); /* Send command to Triangle Setup. */ triangleSetupComm->write(cycle, rastAuxComm); /* Send reset command to Triangle Traversal. */ rastAuxComm = new RasterizerCommand(RSCOM_RESET); /* Copy cookies from original command. */ rastAuxComm->copyParentCookies(*rastComm); /* Send command to Triangle Traversal. */ triangleTraversalComm->write(cycle, rastAuxComm); /* Send reset command to Hierarchical Z. */ rastAuxComm = new RasterizerCommand(RSCOM_RESET); /* Copy cookies from original command. */ rastAuxComm->copyParentCookies(*rastComm); /* Send command to Hierarchical Z. */ hzCommand->write(cycle, rastAuxComm); /* Send reset command to Interpolator. */ rastAuxComm = new RasterizerCommand(RSCOM_RESET); /* Copy cookies from original command. */ rastAuxComm->copyParentCookies(*rastComm); /* Send command to Interpolator. */ interpolatorComm->write(cycle, rastAuxComm); /* Send reset command to Fragment FIFO. */ rastAuxComm = new RasterizerCommand(RSCOM_RESET); /* Copy cookies from original command. */ rastAuxComm->copyParentCookies(*rastComm); /* Send command to Fragment FIFO. */ fFIFOCommand->write(cycle, rastAuxComm); /* Change state to reset. */ state = RAST_RESET; break; case RSCOM_REG_WRITE: /* Write to a Rasterizer register. */ /* Check that current state is RAST_READY. */ GPU_ASSERT( if (state != RAST_READY) panic("Rasterizer", "processRasterizerCommand", "Rasterizer register writes can only be received in READY state."); ) GPU_DEBUG_BOX( printf("Rasterizer => REG_WRITE Command.\n"); ) /* Process the rasterizer register write. */ processRegisterWrite(rastComm->getRegister(), rastComm->getSubRegister(), rastComm->getRegisterData(), cycle); break; case RSCOM_REG_READ: panic("Rasterizer", "processRasterizerCommand", "Register read not supported."); break; case RSCOM_DRAW: /* Start drawing primitives. */ GPU_DEBUG_BOX( printf("Rasterizer => DRAW Command.\n"); ) /* Check the current state. */ GPU_ASSERT( if (state != RAST_READY) panic("Rasterizer", "processRasterizerCommand", "Rasterizer DRAW command can only be received in READY state."); ) /* Send DRAW command to Triangle Setup. */ rastAuxComm = new RasterizerCommand(RSCOM_DRAW); /* Copy cookies from original command. */ rastAuxComm->copyParentCookies(*rastComm); /* Send command to Triangle Setup. */ triangleSetupComm->write(cycle, rastAuxComm); /* Send DRAW command to Triangle Traversal. */ rastAuxComm = new RasterizerCommand(RSCOM_DRAW); /* Copy cookies from original command. */ rastAuxComm->copyParentCookies(*rastComm); /* Send command to Triangle Traversal. */ triangleTraversalComm->write(cycle, rastAuxComm); /* Send DRAW command to Hierarchical Z. */ rastAuxComm = new RasterizerCommand(RSCOM_DRAW); /* Copy cookies from original command. */ rastAuxComm->copyParentCookies(*rastComm); /* Send command to Hierarchical Z. */ hzCommand->write(cycle, rastAuxComm); /* Send DRAW command to Interpolator. */ rastAuxComm = new RasterizerCommand(RSCOM_DRAW); /* Copy cookies from original command. */ rastAuxComm->copyParentCookies(*rastComm); /* Send command to Interpolator. */ interpolatorComm->write(cycle, rastAuxComm); /* Send DRAW command to Fragment FIFO. */ rastAuxComm = new RasterizerCommand(RSCOM_DRAW); /* Copy cookies from original command. */ rastAuxComm->copyParentCookies(*rastComm); /* Send command to Fragment FIFO. */ fFIFOCommand->write(cycle, rastAuxComm); /* Change state to batch drawing. */ state = RAST_DRAWING; break; case RSCOM_END: /* End drawing primitives. */ GPU_DEBUG_BOX( printf("Rasterizer => END Command.\n"); ) /* Check current state. */ if (state == RAST_END) { /* Send END command to Triangle Setup. */ rastAuxComm = new RasterizerCommand(RSCOM_END); /* Copy cookies from original command. */ rastAuxComm->copyParentCookies(*rastComm); /* Send command to Triangle Setup. */ triangleSetupComm->write(cycle, rastAuxComm); /* Send END command to Triangle Traversal. */ rastAuxComm = new RasterizerCommand(RSCOM_END); /* Copy cookies from original command. */ rastAuxComm->copyParentCookies(*rastComm); /* Send command to Triangle Traversal. */ triangleTraversalComm->write(cycle, rastAuxComm); /* Send END command to Hierarchical Z. */ rastAuxComm = new RasterizerCommand(RSCOM_END); /* Copy cookies from original command. */ rastAuxComm->copyParentCookies(*rastComm); /* Send command to Hierarchical Z. */ hzCommand->write(cycle, rastAuxComm); /* Send END command to Interpolator. */ rastAuxComm = new RasterizerCommand(RSCOM_END); /* Copy cookies from original command. */ rastAuxComm->copyParentCookies(*rastComm); /* Send command to Interpolator. */ interpolatorComm->write(cycle, rastAuxComm); /* Send END command to Fragment FIFO. */ rastAuxComm = new RasterizerCommand(RSCOM_END); /* Copy cookies from original command. */ rastAuxComm->copyParentCookies(*rastComm); /* Send command to Fragment FIFO. */ fFIFOCommand->write(cycle, rastAuxComm); } else if (state == RAST_CLEAR_END) { /* Send END command to Hierarchical Z. */ rastAuxComm = new RasterizerCommand(RSCOM_END); /* Copy cookies from original command. */ rastAuxComm->copyParentCookies(*rastComm); /* Send command to Hierarchical Z. */ hzCommand->write(cycle, rastAuxComm); } else { panic("Rasterizer", "processRasterizerCommand", "Rasterizer END command can only be received in END state."); } /* Change state to ready. */ state = RAST_READY; break; case RSCOM_CLEAR_ZSTENCIL_BUFFER: /* Send CLEAR command to Hierarchical Z. */ rastAuxComm = new RasterizerCommand(RSCOM_CLEAR_ZSTENCIL_BUFFER); /* Copy cookies from original command. */ rastAuxComm->copyParentCookies(*rastComm); /* Send command to Hierarchical Z. */ hzCommand->write(cycle, rastAuxComm); /* Change state to clear. */ state = RAST_CLEAR; break; default: panic("Rasterizer", "processRasterizerCommand", "Unsuppored Rasterizer Command."); break; } } /* Process the register write. */ void Rasterizer::processRegisterWrite(GPURegister reg, u32bit subreg, GPURegData data, u64bit cycle) { RasterizerCommand *rastComm; /* Process the register. */ switch(reg) { case GPU_DISPLAY_X_RES: /* Write display horizontal resolution register. */ hRes = data.uintVal; GPU_DEBUG_BOX( printf("Rasterizer => Write GPU_DISPLAY_X_RES = %d.\n", hRes); ) /* Send register write to Triangle Setup. */ /* Create register write command. */ rastComm = new RasterizerCommand(reg, subreg, data); /* Copy cookies from last command. */ rastComm->copyParentCookies(*lastRastComm); /* Send register write to Triangle Setup. */ triangleSetupComm->write(cycle, rastComm); /* Send register write to Triangle Traversal. */ /* Create register write command. */ rastComm = new RasterizerCommand(reg, subreg, data); /* Copy cookies from last command. */ rastComm->copyParentCookies(*lastRastComm); /* Send register write to Triangle Traversal. */ triangleTraversalComm->write(cycle, rastComm); /* Send register write to Hierarchical Z. */ /* Create register write command. */ rastComm = new RasterizerCommand(reg, subreg, data); /* Copy cookies from last command. */ rastComm->copyParentCookies(*lastRastComm); /* Send register write to Hierarchical Z. */ hzCommand->write(cycle, rastComm); break; case GPU_DISPLAY_Y_RES: /* Write display vertical resolution register. */ vRes = data.uintVal; GPU_DEBUG_BOX( printf("Rasterizer => Write GPU_DISPLAY_Y_RES = %d.\n", vRes); ) /* Send register write to Triangle Setup. */ /* Create register write command. */ rastComm = new RasterizerCommand(reg, subreg, data); /* Copy cookies from last command. */ rastComm->copyParentCookies(*lastRastComm); /* Send register write to Triangle Setup. */ triangleSetupComm->write(cycle, rastComm); /* Send register write to Triangle Traversal. */ /* Create register write command. */ rastComm = new RasterizerCommand(reg, subreg, data); /* Copy cookies from last command. */ rastComm->copyParentCookies(*lastRastComm); /* Send register write to Triangle Traversal. */ triangleTraversalComm->write(cycle, rastComm); /* Send register write to Hierarchical Z. */ /* Create register write command. */ rastComm = new RasterizerCommand(reg, subreg, data); /* Copy cookies from last command. */ rastComm->copyParentCookies(*lastRastComm); /* Send register write to Hierarchical Z. */ hzCommand->write(cycle, rastComm); break; case GPU_D3D9_PIXEL_COORDINATES: // Write the use D3D9 pixel coordinates convention register. d3d9PixelCoordinates = data.booleanVal; GPU_DEBUG_BOX( printf("Rasterizer => GPU_D3D9_PIXEL_COORDINATES = %s\n", d3d9PixelCoordinates ? "TRUE" : "FALSE"); ) // Send register write to Triangle Setup. // Create register write command. rastComm = new RasterizerCommand(reg, subreg, data); // Copy cookies from last command. rastComm->copyParentCookies(*lastRastComm); // Send register write to Triangle Setup. triangleSetupComm->write(cycle, rastComm); break; case GPU_VIEWPORT_INI_X: /* Write the viewport initial x coordinate. */ viewportIniX = data.intVal; GPU_DEBUG_BOX( printf("Rasterizer => GPU_VIEWPORT_INI_X = %d.\n", data.intVal); ) /* Send register write to Triangle Setup. */ /* Create register write command. */ rastComm = new RasterizerCommand(reg, subreg, data); /* Copy cookies from last command. */ rastComm->copyParentCookies(*lastRastComm); /* Send register write to Triangle Setup. */ triangleSetupComm->write(cycle, rastComm); /* Send register write to Triangle Traversal. */ /* Create register write command. */ rastComm = new RasterizerCommand(reg, subreg, data); /* Copy cookies from last command. */ rastComm->copyParentCookies(*lastRastComm); /* Send register write to Triangle Traversal. */ triangleTraversalComm->write(cycle, rastComm); /* Send register write to Hierarchical Z. */ /* Create register write command. */ rastComm = new RasterizerCommand(reg, subreg, data); /* Copy cookies from last command. */ rastComm->copyParentCookies(*lastRastComm); /* Send register write to Hierarchical Z. */ hzCommand->write(cycle, rastComm); break; case GPU_VIEWPORT_INI_Y: /* Write the viewport initial y coordinate. */ viewportIniY = data.intVal; GPU_DEBUG_BOX( printf("Rasterizer => GPU_VIEWPORT_INI_Y = %d.\n", data.intVal); ) /* Send register write to Triangle Setup. */ /* Create register write command. */ rastComm = new RasterizerCommand(reg, subreg, data); /* Copy cookies from last command. */ rastComm->copyParentCookies(*lastRastComm); /* Send register write to Triangle Setup. */ triangleSetupComm->write(cycle, rastComm); /* Send register write to Triangle Traversal. */ /* Create register write command. */ rastComm = new RasterizerCommand(reg, subreg, data); /* Copy cookies from last command. */ rastComm->copyParentCookies(*lastRastComm); /* Send register write to Triangle Traversal. */ triangleTraversalComm->write(cycle, rastComm); /* Send register write to Hierarchical Z. */ /* Create register write command. */ rastComm = new RasterizerCommand(reg, subreg, data); /* Copy cookies from last command. */ rastComm->copyParentCookies(*lastRastComm); /* Send register write to Hierarchical Z. */ hzCommand->write(cycle, rastComm); break; case GPU_VIEWPORT_HEIGHT: /* Write the viewport height register. */ viewportHeight = data.uintVal; GPU_DEBUG_BOX( printf("Rasterizer => GPU_VIEWPORT_HEIGHT = %d.\n", data.uintVal); ) /* Send register write to Triangle Setup. */ /* Create register write command. */ rastComm = new RasterizerCommand(reg, subreg, data); /* Copy cookies from last command. */ rastComm->copyParentCookies(*lastRastComm); /* Send register write to Triangle Setup. */ triangleSetupComm->write(cycle, rastComm); /* Send register write to Triangle Traversal. */ /* Create register write command. */ rastComm = new RasterizerCommand(reg, subreg, data); /* Copy cookies from last command. */ rastComm->copyParentCookies(*lastRastComm); /* Send register write to Triangle Traversal. */ triangleTraversalComm->write(cycle, rastComm); /* Send register write to Hierarchical Z. */ /* Create register write command. */ rastComm = new RasterizerCommand(reg, subreg, data); /* Copy cookies from last command. */ rastComm->copyParentCookies(*lastRastComm); /* Send register write to Hierarchical Z. */ hzCommand->write(cycle, rastComm); break; case GPU_VIEWPORT_WIDTH: /* Write the viewport width register. */ viewportWidth = data.uintVal; GPU_DEBUG_BOX( printf("Rasterizer => GPU_VIEWPORT_WIDTH = %d.\n", data.uintVal); ) /* Send register write to Triangle Setup. */ /* Create register write command. */ rastComm = new RasterizerCommand(reg, subreg, data); /* Copy cookies from last command. */ rastComm->copyParentCookies(*lastRastComm); /* Send register write to Triangle Setup. */ triangleSetupComm->write(cycle, rastComm); /* Send register write to Triangle Traversal. */ /* Create register write command. */ rastComm = new RasterizerCommand(reg, subreg, data); /* Copy cookies from last command. */ rastComm->copyParentCookies(*lastRastComm); /* Send register write to Triangle Traversal. */ triangleTraversalComm->write(cycle, rastComm); /* Send register write to Hierarchical Z. */ /* Create register write command. */ rastComm = new RasterizerCommand(reg, subreg, data); /* Copy cookies from last command. */ rastComm->copyParentCookies(*lastRastComm); /* Send register write to Hierarchical Z. */ hzCommand->write(cycle, rastComm); break; case GPU_SCISSOR_TEST: /* Write the scissor test enable falg. */ scissorTest = data.booleanVal; GPU_DEBUG_BOX( printf("Rasterizer => GPU_SCISSOR_TEST = %s.\n", scissorTest?"TRUE":"FALSE"); ) /* Send register write to Triangle Setup. */ /* Create register write command. */ rastComm = new RasterizerCommand(reg, subreg, data); /* Copy cookies from last command. */ rastComm->copyParentCookies(*lastRastComm); /* Send register write to Triangle Setup. */ triangleSetupComm->write(cycle, rastComm); /* Send register write to Hierarchical Z. */ /* Create register write command. */ rastComm = new RasterizerCommand(reg, subreg, data); /* Copy cookies from last command. */ rastComm->copyParentCookies(*lastRastComm); /* Send register write to Hierarchical Z. */ hzCommand->write(cycle, rastComm); break; case GPU_SCISSOR_INI_X: /* Write the scissor initial x position register. */ scissorIniX = data.intVal; GPU_DEBUG_BOX( printf("Rasterizer => GPU_SCISSOR_INIT_X = %d.\n", data.intVal); ) /* Send register write to Triangle Setup. */ /* Create register write command. */ rastComm = new RasterizerCommand(reg, subreg, data); /* Copy cookies from last command. */ rastComm->copyParentCookies(*lastRastComm); /* Send register write to Triangle Setup. */ triangleSetupComm->write(cycle, rastComm); /* Send register write to Hierarchical Z. */ /* Create register write command. */ rastComm = new RasterizerCommand(reg, subreg, data); /* Copy cookies from last command. */ rastComm->copyParentCookies(*lastRastComm); /* Send register write to Hierarchical Z. */ hzCommand->write(cycle, rastComm); break; case GPU_SCISSOR_INI_Y: /* Write the scissor initial y position register. */ scissorIniY = data.intVal; GPU_DEBUG_BOX( printf("Rasterizer => GPU_SCISSOR_INIT_Y = %d.\n", data.intVal); ) /* Send register write to Triangle Setup. */ /* Create register write command. */ rastComm = new RasterizerCommand(reg, subreg, data); /* Copy cookies from last command. */ rastComm->copyParentCookies(*lastRastComm); /* Send register write to Triangle Setup. */ triangleSetupComm->write(cycle, rastComm); /* Send register write to Hierarchical Z. */ /* Create register write command. */ rastComm = new RasterizerCommand(reg, subreg, data); /* Copy cookies from last command. */ rastComm->copyParentCookies(*lastRastComm); /* Send register write to Hierarchical Z. */ hzCommand->write(cycle, rastComm); break; case GPU_SCISSOR_WIDTH: /* Write the scissor width register. */ scissorWidth = data.uintVal; GPU_DEBUG_BOX( printf("Rasterizer => GPU_SCISSOR_WIDTH = %d.\n", data.uintVal); ) /* Send register write to Triangle Setup. */ /* Create register write command. */ rastComm = new RasterizerCommand(reg, subreg, data); /* Copy cookies from last command. */ rastComm->copyParentCookies(*lastRastComm); /* Send register write to Triangle Setup. */ triangleSetupComm->write(cycle, rastComm); /* Send register write to Hierarchical Z. */ /* Create register write command. */ rastComm = new RasterizerCommand(reg, subreg, data); /* Copy cookies from last command. */ rastComm->copyParentCookies(*lastRastComm); /* Send register write to Hierarchical Z. */ hzCommand->write(cycle, rastComm); break; case GPU_SCISSOR_HEIGHT: /* Write the scissor height register. */ scissorHeight = data.uintVal; GPU_DEBUG_BOX( printf("Rasterizer => GPU_SCISSOR_HEIGHT = %d.\n", data.uintVal); ) /* Send register write to Triangle Setup. */ /* Create register write command. */ rastComm = new RasterizerCommand(reg, subreg, data); /* Copy cookies from last command. */ rastComm->copyParentCookies(*lastRastComm); /* Send register write to Triangle Setup. */ triangleSetupComm->write(cycle, rastComm); /* Send register write to Hierarchical Z. */ /* Create register write command. */ rastComm = new RasterizerCommand(reg, subreg, data); /* Copy cookies from last command. */ rastComm->copyParentCookies(*lastRastComm); /* Send register write to Hierarchical Z. */ hzCommand->write(cycle, rastComm); break; case GPU_DEPTH_RANGE_NEAR: /* Write the near depth range register. */ nearRange = data.f32Val; GPU_DEBUG_BOX( printf("Rasterizer => GPU_DEPTH_RANGE_NEAR = %f.\n", data.f32Val); ) /* Send register write to Triangle Setup. */ /* Create register write command. */ rastComm = new RasterizerCommand(reg, subreg, data); /* Copy cookies from last command. */ rastComm->copyParentCookies(*lastRastComm); /* Send register write to Triangle Setup. */ triangleSetupComm->write(cycle, rastComm); break; case GPU_DEPTH_RANGE_FAR: /* Write the far depth range register. */ nearRange = data.f32Val; GPU_DEBUG_BOX( printf("Rasterizer => GPU_DEPTH_RANGE_FAR = %f.\n", data.f32Val); ) /* Send register write to Triangle Setup. */ /* Create register write command. */ rastComm = new RasterizerCommand(reg, subreg, data); /* Copy cookies from last command. */ rastComm->copyParentCookies(*lastRastComm); /* Send register write to Triangle Setup. */ triangleSetupComm->write(cycle, rastComm); break; case GPU_D3D9_DEPTH_RANGE: // Write the D3D9 depth range in clip space register. d3d9DepthRange = data.booleanVal; GPU_DEBUG_BOX( printf("Rasterizer => GPU_D3D9_DEPTH_RANGE = %s.\n", data.booleanVal ? "T" : "F"); ) // Send register write to Triangle Setup. // Create register write command. rastComm = new RasterizerCommand(reg, subreg, data); // Copy cookies from last command. rastComm->copyParentCookies(*lastRastComm); // Send register write to Triangle Setup. triangleSetupComm->write(cycle, rastComm); break; case GPU_DEPTH_SLOPE_FACTOR: /* Write the depth slope factor register. */ slopeFactor = data.f32Val; GPU_DEBUG_BOX( printf("Rasterizer => GPU_DEPTH_SLOPE_FACTOR = %f.\n", data.f32Val); ) /* Send register write to Triangle Setup. */ /* Create register write command. */ rastComm = new RasterizerCommand(reg, subreg, data); /* Copy cookies from last command. */ rastComm->copyParentCookies(*lastRastComm); /* Send register write to Triangle Setup. */ triangleSetupComm->write(cycle, rastComm); break; case GPU_DEPTH_UNIT_OFFSET: /* Write the depth unit offset register. */ unitOffset = data.f32Val; GPU_DEBUG_BOX( printf("Rasterizer => GPU_DEPTH_UNIT_OFFSET = %f.\n", data.f32Val); ) /* Send register write to Triangle Setup. */ /* Create register write command. */ rastComm = new RasterizerCommand(reg, subreg, data); /* Copy cookies from last command. */ rastComm->copyParentCookies(*lastRastComm); /* Send register write to Triangle Setup. */ triangleSetupComm->write(cycle, rastComm); break; case GPU_Z_BUFFER_CLEAR: /* Write depth clear value. */ clearDepth = data.uintVal; GPU_DEBUG_BOX( printf("Rasterizer => Write GPU_Z_BUFFER_CLEAR = %x.\n", clearDepth); ) /* Send register write to Hierarchical Z. */ /* Create register write command. */ rastComm = new RasterizerCommand(reg, subreg, data); /* Copy cookies from last command. */ rastComm->copyParentCookies(*lastRastComm); /* Send register write to Hierarchical Z. */ hzCommand->write(cycle, rastComm); break; case GPU_Z_BUFFER_BIT_PRECISSION: /* Write the z buffer bit precisison register. */ zBufferBitPrecission = data.uintVal; GPU_DEBUG_BOX( printf("Rasterizer => GPU_Z_BUFFER_BIT_PRECISSION = %d.\n", data.uintVal); ) /* Send register write to Triangle Setup. */ /* Create register write command. */ rastComm = new RasterizerCommand(reg, subreg, data); /* Copy cookies from last command. */ rastComm->copyParentCookies(*lastRastComm); /* Send register write to Triangle Setup. */ triangleSetupComm->write(cycle, rastComm); /* Send register write to Hierarchical Z. */ /* Create register write command. */ rastComm = new RasterizerCommand(reg, subreg, data); /* Copy cookies from last command. */ rastComm->copyParentCookies(*lastRastComm); /* Send register write to Hierarchical Z. */ hzCommand->write(cycle, rastComm); break; case GPU_HIERARCHICALZ: /* Write HZ test enable flag. */ hzEnable = data.booleanVal; GPU_DEBUG_BOX( printf("Rasterizer => Writing register GPU_HIERARCHICALZ = %s.\n", hzEnable?"TRUE":"FALSE"); ) /* Send register write to Hierarchical Z. */ /* Create register write command. */ rastComm = new RasterizerCommand(reg, subreg, data); /* Copy cookies from last command. */ rastComm->copyParentCookies(*lastRastComm); /* Send register write to Hierarchical Z. */ hzCommand->write(cycle, rastComm); break; case GPU_EARLYZ: /* Write early Z test enable flag. */ earlyZ = data.booleanVal; GPU_DEBUG_BOX( printf("Rasterizer => Writing register GPU_EARLYZ = %s.\n", earlyZ?"TRUE":"FALSE"); ) /* Send register write to Hierarchical Z. */ /* Create register write command. */ rastComm = new RasterizerCommand(reg, subreg, data); /* Copy cookies from last command. */ rastComm->copyParentCookies(*lastRastComm); /* Send register write to Fragment FIFO. */ fFIFOCommand->write(cycle, rastComm); break; case GPU_USER_CLIP: /* Write an user clip plane register. */ userClip[subreg][0] = data.qfVal[0]; userClip[subreg][1] = data.qfVal[1]; userClip[subreg][2] = data.qfVal[2]; userClip[subreg][3] = data.qfVal[3]; GPU_DEBUG_BOX( printf("Rasterizer => GPU_USER_CLIP(%d) = (%f, %f, %f, %f).\n", subreg, data.qfVal[0], data.qfVal[1], data.qfVal[2], data.qfVal[3]); ) break; case GPU_USER_CLIP_PLANE: /* Write user clip mode enable register. */ userClipPlanes = data.booleanVal; GPU_DEBUG_BOX( printf("Rasterizer => GPU_USER_CLIP_PLANE = %s.\n", data.booleanVal?"TRUE":"FALSE"); ) break; case GPU_FACEMODE: /* Write the face mode register. */ faceMode = data.faceMode; GPU_DEBUG_BOX( printf("Rasterizer => GPU_FACEMODE = "); switch(data.culling) { case GPU_CW: printf("CW.\n"); break; case GPU_CCW: printf("CCW.\n"); break; } ) /* Send register write to Triangle Setup. */ /* Create register write command. */ rastComm = new RasterizerCommand(reg, subreg, data); /* Copy cookies from last command. */ rastComm->copyParentCookies(*lastRastComm); /* Send register write to Triangle Setup. */ triangleSetupComm->write(cycle, rastComm); break; case GPU_CULLING: /* Write the culling mode register. */ cullMode = data.culling; GPU_DEBUG_BOX( printf("Rasterizer => GPU_CULLING = "); switch(data.culling) { case NONE: printf("NONE.\n"); break; case FRONT: printf("FRONT.\n"); break; case BACK: printf("BACK.\n"); break; case FRONT_AND_BACK: printf("FRONT_AND_BACK.\n"); break; } ) /* Send register write to Triangle Setup. */ /* Create register write command. */ rastComm = new RasterizerCommand(reg, subreg, data); /* Copy cookies from last command. */ rastComm->copyParentCookies(*lastRastComm); /* Send register write to Triangle Setup. */ triangleSetupComm->write(cycle, rastComm); break; case GPU_D3D9_RASTERIZATION_RULES: // Write use D3D9 rasterization rules register. d3d9RasterizationRules = data.booleanVal; GPU_DEBUG_BOX( printf("Rasterizer => GPU_D3D9_RASTERIZATION_RULES = %s\n", data.booleanVal?"ENABLED":"DISABLED"); ) // Send register write to Triangle Setup. // Create register write command. rastComm = new RasterizerCommand(reg, subreg, data); // Copy cookies from last command. rastComm->copyParentCookies(*lastRastComm); // Send register write to Triangle Setup. triangleSetupComm->write(cycle, rastComm); break; case GPU_TWOSIDED_LIGHTING: /* Write two sided color selection register. */ twoSidedLighting = data.booleanVal; GPU_DEBUG_BOX( printf("Rasterizer => GPU_TWOSIDED_LIGHTING = %s\n", data.booleanVal?"ENABLED":"DISABLED"); ) /* Send register write to Triangle Setup. */ /* Create register write command. */ rastComm = new RasterizerCommand(reg, subreg, data); /* Copy cookies from last command. */ rastComm->copyParentCookies(*lastRastComm); /* Send register write to Triangle Setup. */ triangleSetupComm->write(cycle, rastComm); break; case GPU_MULTISAMPLING: // Write Multisampling enable flag. multisampling = data.booleanVal; GPU_DEBUG_BOX( printf("Rasterizer => Write GPU_MULTISAMPLING = %s\n", multisampling?"TRUE":"FALSE"); ) /* Send register write to Triangle Traversal. */ /* Create register write command. */ rastComm = new RasterizerCommand(reg, subreg, data); /* Copy cookies from last command. */ rastComm->copyParentCookies(*lastRastComm); /* Send register write to Triangle Traversal. */ triangleTraversalComm->write(cycle, rastComm); /* Send register write to Hierarchical Z. */ /* Create register write command. */ rastComm = new RasterizerCommand(reg, subreg, data); /* Copy cookies from last command. */ rastComm->copyParentCookies(*lastRastComm); /* Send register write to Hierarchical Z. */ hzCommand->write(cycle, rastComm); break; case GPU_MSAA_SAMPLES: // Write MSAA z samples per fragment register. msaaSamples = data.uintVal; GPU_DEBUG_BOX( printf("Rasterizer => Write GPU_MSAA_SAMPLES = %d\n", msaaSamples); ) /* Send register write to Triangle Traversal. */ /* Create register write command. */ rastComm = new RasterizerCommand(reg, subreg, data); /* Copy cookies from last command. */ rastComm->copyParentCookies(*lastRastComm); /* Send register write to Triangle Traversal. */ triangleTraversalComm->write(cycle, rastComm); /* Send register write to Hierarchical Z. */ /* Create register write command. */ rastComm = new RasterizerCommand(reg, subreg, data); /* Copy cookies from last command. */ rastComm->copyParentCookies(*lastRastComm); /* Send register write to Hierarchical Z. */ hzCommand->write(cycle, rastComm); break; case GPU_INTERPOLATION: /* Check if the attribute identifier is correct. */ GPU_ASSERT( if (subreg >= MAX_FRAGMENT_ATTRIBUTES) panic("Rasterizer", "processRegisterWrite", "Out of range fragment attribute identifier."); ) GPU_DEBUG_BOX( printf("Rasterizer => GPU_INTERPOLATION = %s.\n", data.booleanVal?"TRUE":"FALSE"); ) /* Write the interpolation mode enable register. */ interpolation[subreg] = data.booleanVal; /* Send register write to Interpolator. */ /* Create register write command. */ rastComm = new RasterizerCommand(reg, subreg, data); /* Copy cookies from last command. */ rastComm->copyParentCookies(*lastRastComm); /* Send register write to Interpolator. */ interpolatorComm->write(cycle, rastComm); break; case GPU_FRAGMENT_INPUT_ATTRIBUTES: /* Write in fragment input attribute active flags register. */ /* Check if the attribute identifier is correct. */ GPU_ASSERT( if (subreg >= MAX_FRAGMENT_ATTRIBUTES) panic("Rasterizer", "processRegisterWrite", "Out of range fragment attribute identifier."); ) /* Set fragment attribute activation flag. */ fragmentAttributes[subreg] = data.booleanVal; /* Send register write to Interpolator. */ /* Create register write command. */ rastComm = new RasterizerCommand(reg, subreg, data); /* Copy cookies from last command. */ rastComm->copyParentCookies(*lastRastComm); /* Send register write to Interpolator. */ interpolatorComm->write(cycle, rastComm); /* Send register write to Fragment FIFO. */ /* Create register write command. */ rastComm = new RasterizerCommand(reg, subreg, data); /* Copy cookies from last command. */ rastComm->copyParentCookies(*lastRastComm); /* Send register write to Fragment FIFO. */ fFIFOCommand->write(cycle, rastComm); break; case GPU_MODIFY_FRAGMENT_DEPTH: /* Write modify depth register. */ modifyDepth = data.booleanVal; GPU_DEBUG_BOX( printf("Rasterizer => Write GPU_MODIFY_FRAGMENT_DEPTH = %s\n", data.booleanVal?"TRUE":"FALSE"); ) /* Send register write to Hierarchical Z. */ /* Create register write command. */ rastComm = new RasterizerCommand(reg, subreg, data); /* Copy cookies from last command. */ rastComm->copyParentCookies(*lastRastComm); /* Send register write to Hierarchical Z. */ hzCommand->write(cycle, rastComm); break; case GPU_FRUSTUM_CLIPPING: /* Write the frustum clipping flag register. */ frustumClipping = data.booleanVal; GPU_DEBUG_BOX( printf("Rasterizer => GPU_FRUSTUM_CLIPPING = %s.\n", data.booleanVal?"ENABLE":"DISABLED"); ) break; case GPU_STENCIL_TEST: /* Write the stencil test enable flag register. */ stencilTest = data.booleanVal; GPU_DEBUG_BOX( printf("Rasterizer => GPU_STENCIL_TEST = %s.\n", data.booleanVal?"ENABLED":"DISABLED"); ) /* Send register write to Fragment FIFO. */ /* Create register write command. */ rastComm = new RasterizerCommand(reg, subreg, data); /* Copy cookies from last command. */ rastComm->copyParentCookies(*lastRastComm); /* Send register write to Fragment FIFO. */ fFIFOCommand->write(cycle, rastComm); break; case GPU_DEPTH_TEST: /* Write the depth test enable flag register. */ depthTest = data.booleanVal; GPU_DEBUG_BOX( printf("Rasterizer => GPU_DEPTH_TEST = %s.\n", data.booleanVal?"ENABLED":"DISABLED"); ) /* Send register write to Fragment FIFO. */ /* Create register write command. */ rastComm = new RasterizerCommand(reg, subreg, data); /* Copy cookies from last command. */ rastComm->copyParentCookies(*lastRastComm); /* Send register write to Fragment FIFO. */ fFIFOCommand->write(cycle, rastComm); break; case GPU_DEPTH_FUNCTION: /* Write depth compare function register. */ depthFunction = data.compare; GPU_DEBUG_BOX( printf("Rasterizer => Write GPU_DEPTH_FUNCTION = "); switch(depthFunction) { case GPU_NEVER: printf("NEVER.\n"); break; case GPU_ALWAYS: printf("ALWAYS.\n"); break; case GPU_LESS: printf("LESS.\n"); break; case GPU_LEQUAL: printf("LEQUAL.\n"); break; case GPU_EQUAL: printf("EQUAL.\n"); break; case GPU_GEQUAL: printf("GEQUAL.\n"); break; case GPU_GREATER: printf("GREATER.\n"); break; case GPU_NOTEQUAL: printf("NOTEQUAL.\n"); default: panic("Rasterizer", "processRegisterWrite", "Undefined compare function mode"); break; } ) /* Send register write to Hierarchical Z. */ /* Create register write command. */ rastComm = new RasterizerCommand(reg, subreg, data); /* Copy cookies from last command. */ rastComm->copyParentCookies(*lastRastComm); /* Send register write to Hierarchical Z. */ hzCommand->write(cycle, rastComm); break; case GPU_RENDER_TARGET_ENABLE: // Write the render target enable register. rtEnable[subreg] = data.booleanVal; GPU_DEBUG_BOX( printf("Rasterizer => GPU_RENDER_TARGET_ENABLE[%d] = %s.\n", subreg, data.booleanVal?"TRUE":"FALSE"); ) // Send register write to Fragment FIFO. // Create register write command. rastComm = new RasterizerCommand(reg, subreg, data); // Copy cookies from last command. rastComm->copyParentCookies(*lastRastComm); // Send register write to Fragment FIFO. fFIFOCommand->write(cycle, rastComm); break; case GPU_COLOR_MASK_R: // Write the red component color write mask register. colorMaskR[subreg] = data.booleanVal; GPU_DEBUG_BOX( printf("Rasterizer => GPU_COLOR_MASK_R[%d] = %s.\n", subreg, data.booleanVal?"TRUE":"FALSE"); ) // Send register write to Fragment FIFO. // Create register write command. rastComm = new RasterizerCommand(reg, subreg, data); // Copy cookies from last command. rastComm->copyParentCookies(*lastRastComm); // Send register write to Fragment FIFO. fFIFOCommand->write(cycle, rastComm); break; case GPU_COLOR_MASK_G: // Write the green component color write mask register. colorMaskG[subreg] = data.booleanVal; GPU_DEBUG_BOX( printf("Rasterizer => GPU_COLOR_MASK_G[%d] = %s.\n", subreg, data.booleanVal?"TRUE":"FALSE"); ) // Send register write to Fragment FIFO. // Create register write command. rastComm = new RasterizerCommand(reg, subreg, data); // Copy cookies from last command. rastComm->copyParentCookies(*lastRastComm); // Send register write to Fragment FIFO. fFIFOCommand->write(cycle, rastComm); break; case GPU_COLOR_MASK_B: // Write the blue component color write mask register. colorMaskB[subreg] = data.booleanVal; GPU_DEBUG_BOX( printf("Rasterizer => GPU_COLOR_MASK_B[%d] = %s.\n", subreg, data.booleanVal?"TRUE":"FALSE"); ) // Send register write to Fragment FIFO. // Create register write command. rastComm = new RasterizerCommand(reg, subreg, data); // Copy cookies from last command. rastComm->copyParentCookies(*lastRastComm); // Send register write to Fragment FIFO. fFIFOCommand->write(cycle, rastComm); break; case GPU_COLOR_MASK_A: // Write the alpha component color write mask register. colorMaskA[subreg] = data.booleanVal; GPU_DEBUG_BOX( printf("Rasterizer => GPU_COLOR_MASK_A[%d] = %s.\n", subreg, data.booleanVal?"TRUE":"FALSE"); ) // Send register write to Fragment FIFO. // Create register write command. rastComm = new RasterizerCommand(reg, subreg, data); // Copy cookies from last command. rastComm->copyParentCookies(*lastRastComm); // Send register write to Fragment FIFO. fFIFOCommand->write(cycle, rastComm); break; default: /* Unsupported register. */ panic("Rasterizer", "processRegisterWrite", "Unsupported Rasterizer register."); break; } } void Rasterizer::getState(string &stateString) { stringstream stateStream; stateStream.clear(); stateStream << " state = "; switch(state) { case RAST_RESET: stateStream << "RAST_RESET"; break; case RAST_READY: stateStream << "RAST_READY"; break; case RAST_DRAWING: stateStream << "RAST_DRAW"; break; case RAST_END: stateStream << "RAST_END"; break; case RAST_CLEAR: stateStream << "RAST_CLEAR"; break; case RAST_CLEAR_END: stateStream << "RAST_CLEAR_END"; break; default: stateStream << "undefined"; break; } stateString.assign(stateStream.str()); } void Rasterizer::saveHZBuffer() { hierarchicalZ->saveHZBuffer(); } void Rasterizer::loadHZBuffer() { hierarchicalZ->loadHZBuffer(); } void Rasterizer::detectStall(u64bit cycle, bool &active, bool &stalled) { bool detectionImplemented; bool stallDetected; active = false; stalled = false; // Detect stalls on all the boxes instantiated inside Rasterizer. triangleSetup->detectStall(cycle, detectionImplemented, stallDetected); active |= detectionImplemented; stalled |= detectionImplemented & stallDetected; triangleTraversal->detectStall(cycle, detectionImplemented, stallDetected); active |= detectionImplemented; stalled |= detectionImplemented & stallDetected; hierarchicalZ->detectStall(cycle, detectionImplemented, stallDetected); active |= detectionImplemented; stalled |= detectionImplemented & stallDetected; interpolator->detectStall(cycle, detectionImplemented, stallDetected); active |= detectionImplemented; stalled |= detectionImplemented & stallDetected; fFIFO->detectStall(cycle, detectionImplemented, stallDetected); active |= detectionImplemented; stalled |= detectionImplemented & stallDetected; } void Rasterizer::stallReport(u64bit cycle, string &stallReport) { stringstream reportStream; string report; // Obtain the stall report from all the boxes instantiated inside Rasterizer. triangleSetup->stallReport(cycle, report); reportStream << report << endl << endl; triangleTraversal->stallReport(cycle, report); reportStream << report << endl << endl; hierarchicalZ->stallReport(cycle, report); reportStream << report << endl << endl; interpolator->stallReport(cycle, report); reportStream << report << endl << endl; fFIFO->stallReport(cycle, report); reportStream << report << endl; stallReport.assign(reportStream.str()); }
34.804878
135
0.566097
attila-sim
b2936a63a6c7ffdfd568458ea8a01cb5c85fb5df
4,163
cpp
C++
register/auto_mapping_util.cpp
Ascend/metadef
9d3f0444b1e13e6a3c9d498963f8232f439a0f47
[ "Apache-2.0" ]
null
null
null
register/auto_mapping_util.cpp
Ascend/metadef
9d3f0444b1e13e6a3c9d498963f8232f439a0f47
[ "Apache-2.0" ]
null
null
null
register/auto_mapping_util.cpp
Ascend/metadef
9d3f0444b1e13e6a3c9d498963f8232f439a0f47
[ "Apache-2.0" ]
null
null
null
/** * Copyright 2020 Huawei Technologies Co., Ltd * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "register/auto_mapping_util.h" #include "graph/debug/ge_util.h" namespace ge { // Convert tensorflow property to ge property bool AutoMappingUtil::FindAttrValue(const domi::tensorflow::NodeDef *nodeDef, const string &attr_name, domi::tensorflow::AttrValue &attr_value) { GE_CHECK_NOTNULL(nodeDef); const google::protobuf::Map<std::string, domi::tensorflow::AttrValue> &attr = nodeDef->attr(); const google::protobuf::Map<std::string, domi::tensorflow::AttrValue>::const_iterator it = attr.find(attr_name); if (it != attr.end()) { attr_value = it->second; return true; } return false; } // Get the attribute shape of tensorflow void AutoMappingUtil::ConvertShape(const domi::tensorflow::TensorShapeProto &shape, vector<int64_t>& shape_dims) { shape_dims.clear(); if (!shape.unknown_rank()) { for (auto &dim : shape.dim()) { shape_dims.push_back(dim.size()); } } else { shape_dims = ge::UNKNOWN_SHAPE; } } graphStatus AutoMappingUtil::ConvertTensor(const domi::tensorflow::TensorProto &tensor, ge::GeTensorPtr &weight) { weight = ComGraphMakeShared<ge::GeTensor>(); if (weight == nullptr) { GE_LOGE("Weight is nullptr."); return GRAPH_FAILED; } domi::tensorflow::DataType tf_data_type = tensor.dtype(); ge::DataType ge_data_type = domi::TensorAssign::ConvertTensorflowDataType(tf_data_type); if (domi::TensorAssign::SetGeTensorDataType(ge_data_type, weight) != domi::SUCCESS) { GE_LOGE("Set Ge tensor data type failed."); return GRAPH_FAILED; } if (domi::TensorAssign::SetGeTensor(tensor, weight) != domi::SUCCESS) { GE_LOGE("Set Ge tensor failed."); return GRAPH_FAILED; } return GRAPH_SUCCESS; } void AutoMappingUtil::ConvertTensorList(const domi::tensorflow::AttrValue_ListValue &list, std::vector<ge::GeTensorPtr> &vec) { vec.clear(); for (auto &tensor : list.tensor()) { ge::GeTensorPtr ge_tensor = nullptr; graphStatus ret = ConvertTensor(tensor, ge_tensor); if (ret != GRAPH_SUCCESS) { GE_LOGE("Convert tensor failed."); return; } vec.push_back(ge_tensor); } } void AutoMappingUtil::ConvertFunc(const domi::tensorflow::NameAttrList& tf_func, ge::GeAttrValue::NAMED_ATTRS& ge_func) { ge_func.SetName(tf_func.name()); auto& attrs = tf_func.attr(); for (auto &item : attrs) { ConvertValue(item.first, item.second, ge_func); } } void AutoMappingUtil::ConvertDataTypeList(const domi::tensorflow::AttrValue_ListValue &list, std::vector<ge::DataType> &vec) { vec.clear(); for (auto &e : list.type()) { ge::DataType ge_data_type = domi::TensorAssign::ConvertTensorflowDataType(static_cast<uint32_t>(e)); vec.push_back(ge_data_type); } } void AutoMappingUtil::ConvertShapeList(const domi::tensorflow::AttrValue_ListValue &list, std::vector<vector<int64_t>> &vec) { vec.clear(); for (const auto &e : list.shape()) { vector<int64_t> shape_dims; ConvertShape(e, shape_dims); vec.push_back(shape_dims); } } void AutoMappingUtil::ConvertFuncList(const domi::tensorflow::AttrValue_ListValue &list, std::vector<ge::GeAttrValue::NAMED_ATTRS> &vec) { vec.clear(); for (const auto &e : list.func()) { ge::GeAttrValue::NAMED_ATTRS func; ConvertFunc(e, func); vec.push_back(func); } } } // namespace domi
34.983193
114
0.67043
Ascend
b2968f62f2e41310f5e9fe54e71802068f031bac
2,383
cpp
C++
sim/Boat/BoatTest.cpp
andyrobinson/ard-nav
8162b2c9b882393ffd44e42d3f0816d7b1090760
[ "MIT" ]
null
null
null
sim/Boat/BoatTest.cpp
andyrobinson/ard-nav
8162b2c9b882393ffd44e42d3f0816d7b1090760
[ "MIT" ]
null
null
null
sim/Boat/BoatTest.cpp
andyrobinson/ard-nav
8162b2c9b882393ffd44e42d3f0816d7b1090760
[ "MIT" ]
null
null
null
#include "gtest/gtest.h" #include "Boat.h" #include "Position.h" #include "Globe.h" #include "Utility.h" using namespace Position; using namespace Utility; namespace { position kynance_cove = {49.97480, -5.23198, 5.0}; Globe globe; class BoatTest : public ::testing::Test { protected: BoatTest() { } void SetUp() override { } angle rudder_effect(angle deflection) { return -deflection; } }; TEST_F(BoatTest, Should_start_at_provided_location) { Boat boat(&kynance_cove); EXPECT_EQ(boat.location(), kynance_cove); } TEST_F(BoatTest, Should_move_in_initial_direction) { Boat boat(&kynance_cove); boat.move(1000); position expected_position = globe.new_position(&kynance_cove, STARTING_HEADING, 1.0); EXPECT_EQ(boat.location(), expected_position); } TEST_F(BoatTest, Should_change_heading_based_on_rudder) { Boat boat(&kynance_cove); boat.rudder = 20; boat.move(1000); uangle expected_heading = uadd(STARTING_HEADING,rudder_effect(boat.rudder)); position expected_position = globe.new_position(&kynance_cove, expected_heading, 1.0); EXPECT_EQ(boat.location(), expected_position); } TEST_F(BoatTest, Should_report_stats) { Boat boat(&kynance_cove); EXPECT_EQ(boat.speed(),STARTING_SPEED); EXPECT_EQ(boat.bearing(),STARTING_HEADING); } TEST_F(BoatTest, Should_return_relative_wind) { Boat boat(&kynance_cove); angle start_wind = add(STARTING_WIND, -STARTING_HEADING); EXPECT_EQ(boat.relative_wind(), start_wind); boat.rudder = -30; boat.move(1000); angle expected_wind = add(start_wind, -rudder_effect(boat.rudder)); std::cout << expected_wind << "\n"; EXPECT_EQ(boat.relative_wind(), expected_wind); boat.rudder = 20; boat.move(1000); expected_wind = add(expected_wind, -rudder_effect(boat.rudder)); std::cout << expected_wind << "\n"; EXPECT_EQ(boat.relative_wind(), expected_wind); boat.rudder = 20; boat.move(1000); expected_wind = add(expected_wind, -rudder_effect(boat.rudder)); std::cout << expected_wind << "\n"; EXPECT_EQ(boat.relative_wind(), expected_wind); } } //namespace int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
28.710843
92
0.669744
andyrobinson
b29954233eaaef0bb8d07306e8479d91c6a20a22
4,112
hpp
C++
RobWork/src/rwlibs/pathplanners/sbl/SBLInternal.hpp
ZLW07/RobWork
e713881f809d866b9a0749eeb15f6763e64044b3
[ "Apache-2.0" ]
1
2021-12-29T14:16:27.000Z
2021-12-29T14:16:27.000Z
RobWork/src/rwlibs/pathplanners/sbl/SBLInternal.hpp
ZLW07/RobWork
e713881f809d866b9a0749eeb15f6763e64044b3
[ "Apache-2.0" ]
null
null
null
RobWork/src/rwlibs/pathplanners/sbl/SBLInternal.hpp
ZLW07/RobWork
e713881f809d866b9a0749eeb15f6763e64044b3
[ "Apache-2.0" ]
null
null
null
/******************************************************************************** * Copyright 2009 The Robotics Group, The Maersk Mc-Kinney Moller Institute, * Faculty of Engineering, University of Southern Denmark * * 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 RWLIBS_PATHPLANNERS_SBL_SBLINTERNAL_HPP #define RWLIBS_PATHPLANNERS_SBL_SBLINTERNAL_HPP /** @file SBLInternal.hpp @brief SBL path planner. */ #include "SBLSetup.hpp" namespace rw { namespace math { class Q; }} // namespace rw::math namespace rw { namespace pathplanning { class StopCriteria; }} // namespace rw::pathplanning namespace rw { namespace pathplanning { class QSampler; }} // namespace rw::pathplanning namespace rwlibs { namespace pathplanners { //! @brief Internal algorithms used by the SBLPlanner. class SBLInternal { public: //! @brief Type of a motion. typedef std::vector< rw::math::Q > Motion; /** @brief The options stored within the setup. */ static SBLOptions getOptions (const SBLSetup& setup) { return setup.options; } /** A general path planner call that (depending on the arguments) can find standard paths, approach paths, retract paths, and connection paths. The planner assumes that all of the involved configurations are normalized. The planner runs until a path is found or an external thread assigns \b stop a value of true. @param from [in] Collision free start configuration (or the empty path is returned) or NULL (fromSampler is used to compute a configuration). @param to [in] Collision free goal configuration (or the empty path is returned) or NULL (toSampler is used to compute a configuration). @param fromSamples [in] Other samples to insert for the start region. @param toSamples [in] Other samples to insert for the goal region. @param fromSampler [in] Sampler (possibly empty) for start region. @param toSampler [in] Sampler (possibly empty) for goal region. @param setup [in] Options for the SBL planner. @param stop [in] Stop the planner when this function object returns true. */ static Motion findConnection (const rw::math::Q& from, const rw::math::Q& to, const Motion& fromSamples, const Motion& toSamples, rw::pathplanning::QSampler& fromSampler, rw::pathplanning::QSampler& toSampler, const SBLOptions& setup, const rw::pathplanning::StopCriteria& stop); /** Standard path planning. */ static Motion findPath (const rw::math::Q& from, const rw::math::Q& to, const SBLOptions& setup, const rw::pathplanning::StopCriteria& stop); /** Approach planning. */ static Motion findApproach (const rw::math::Q& from, const rw::math::Q& to, const Motion& toSamples, rw::pathplanning::QSampler& toSampler, const SBLOptions& setup, const rw::pathplanning::StopCriteria& stop); }; }} // namespace rwlibs::pathplanners #endif // end include guard
38.429907
99
0.591683
ZLW07
b29db8d1c35b45ee1ca236d77d74ba0a768c66da
11,132
cpp
C++
src/graphics/dxengine/dxtools.cpp
Terebinth/freefalcon-central
c28d807183ab447ef6a801068aa3769527d55deb
[ "BSD-2-Clause" ]
117
2015-01-13T14:48:49.000Z
2022-03-16T01:38:19.000Z
src/graphics/dxengine/dxtools.cpp
darongE/freefalcon-central
c28d807183ab447ef6a801068aa3769527d55deb
[ "BSD-2-Clause" ]
4
2015-05-01T13:09:53.000Z
2017-07-22T09:11:06.000Z
src/graphics/dxengine/dxtools.cpp
darongE/freefalcon-central
c28d807183ab447ef6a801068aa3769527d55deb
[ "BSD-2-Clause" ]
78
2015-01-13T09:27:47.000Z
2022-03-18T14:39:09.000Z
#include <cISO646> #include <math.h> #include "../include/TimeMgr.h" #include "../include/ObjectInstance.h" #include "dxdefines.h" #include "DxTools.h" #include "../../falclib/include/mltrig.h" #include "dxengine.h" #ifndef DEBUG_ENGINE // This function just assign a PMatrix object to a DX Compliant Matrix void AssignPmatrixToD3DXMATRIX(D3DXMATRIX *d, Pmatrix *s) { d->m00 = s->M11; d->m01 = s->M21; d->m02 = s->M31; d->m03 = 0.0f; d->m10 = s->M12; d->m11 = s->M22; d->m12 = s->M32; d->m13 = 0.0f; d->m20 = s->M13; d->m21 = s->M23; d->m22 = s->M33; d->m23 = 0.0f; d->m30 = 0.0f; d->m31 = 0.0f; d->m32 = 0.0f; d->m33 = 1.0f; } void AssignD3DXMATRIXToPmatrix(Pmatrix *d, D3DXMATRIX *s) { d->M11 = s->m00; d->M21 = s->m01; d->M31 = s->m02; d->M12 = s->m10; d->M22 = s->m11; d->M32 = s->m12; d->M13 = s->m20; d->M23 = s->m21; d->M33 = s->m22; } #endif //////////////////////////////////////////////////////\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ ///////////////////////////////////////////// SCRIPTS MANAGEMENT \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ //////////////////////////////////////////////////////\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ static const float Seconds = 1.0f / 1000.0f; static const float Minutes = Seconds / (60.0f); static const float Hours = Minutes / (60.0f); static const float Degrees = (PI / 180.0f); static const float DegreesPerSecond = Degrees * Seconds; // the boolean return value is used by the caller to understand if the next script in the list is to be // processed, false means no more script processing bool DXScript_None(D3DVECTOR *pos, ObjectInstance *obj, DWORD *Argument) { return true; } ///////////////////////////////////////////////////////////////////////////////// // The Cycling animation, max 32 frames, timed // Argument 0 = SwitchNr to apply the animation // Argument 1 = Delay btw frames in mSecs // Argument 2 = Number of Frames bool DXScript_Animate(D3DVECTOR *pos, ObjectInstance *obj, DWORD *Argument) { // Consistency check if (obj->ParentObject->nSwitches <= 0) return true; if (Argument[0] >= (WORD) obj->ParentObject->nSwitches) return true; #ifdef DEBUG_ENGINE // Get the timings DWORD Delta = GetTickCount(); #else // Get the timings DWORD Delta = TheTimeManager.GetClockTime(); #endif // Scale it by the delay Delta /= Argument[1]; //Set accordingly the switch obj->SetSwitch(Argument[0], 1 << (Delta % Argument[2])); return true; } ///////////////////////////////////////////////////////////////////////////////// // The Rotating animation // Argument 0 = Starting Dof // Argument 1 = Nr of DOFS to apply rotation // Argument 2 = FLOAT, Degrees per second of rotation bool DXScript_Rotate(D3DVECTOR *pos, ObjectInstance *obj, DWORD *Argument) { // Consistency check if (obj->ParentObject->nDOFs <= 0) return true; // Get the Starting DOF DWORD Dof = Argument[0]; // get the number of Dofs to apply the rotation DWORD Count = Argument[1]; // consistency check and Limitation if (Dof >= (WORD) obj->ParentObject->nDOFs) return true; if ((Dof + Count) >= (WORD) obj->ParentObject->nDOFs) Count = obj->ParentObject->nDOFs - Dof - 1; #ifdef DEBUG_ENGINE // Get the timings float Delta = GetTickCount() * ((float*)Argument)[2] * DegreesPerSecond; #else // Get the timings float Delta = TheTimeManager.GetClockTime() * ((float*)Argument)[2] * DegreesPerSecond; #endif // for each DOF while (Count--) { obj->DOFValues[Dof++].rotation = Delta; } return true; } ///////////////////////////////////////////////////////////////////////////////// // The Helicopter aniamtion, up to 4 DOFs rotated with 4 different CXs // Argument 0 = Starting Dof // Argument 1 = Nr of DOFS to apply rotation // Argument 2 = FLOAT, Degrees per second of rotation bool DXScript_HelyRotate(D3DVECTOR *pos, ObjectInstance *obj, DWORD *Argument) { // Consistency check if (obj->ParentObject->nDOFs <= 0) return true; // Get the Starting DOF DWORD Dof = Argument[0]; // get the number of Dofs to apply the rotation DWORD Count = Argument[1]; // consistency check and Limitation if (Dof >= (WORD) obj->ParentObject->nDOFs) return true; if ((Dof + Count) >= (WORD) obj->ParentObject->nDOFs) Count = obj->ParentObject->nDOFs - Dof - 1; #ifdef DEBUG_ENGINE // Get the timings float Delta = GetTickCount() * ((float*)Argument)[2] * DegreesPerSecond; #else // Get the timings float Delta = TheTimeManager.GetClockTime() * ((float*)Argument)[2] * DegreesPerSecond; #endif // for each DOF if (Count--)obj->DOFValues[Dof++].rotation = Delta; if (Count--)obj->DOFValues[Dof++].rotation = Delta * 1.6f; if (Count--)obj->DOFValues[Dof++].rotation = Delta * 2.1f; if (Count--)obj->DOFValues[Dof++].rotation = Delta * 0.1f; return true; } float TestAngle; // Military rotating beacon script // Assume model has green pointing north, and two whites 30 degrees apart pointing southward // switch bits: // 1 0 degree green dim // 2 0 degree green flash // 3 0 degree green has flashed flag // 5 165 degree white dim // 6 165 degree white flash // 7 165 degree white has flashed flag // 9 195 degree white dim // 10 195 degree white flash // 11 195 degree white has flashed flag bool DXScript_Beacon(D3DVECTOR *pos, ObjectInstance *obj, DWORD *Argument) { ShiAssert(obj->ParentObject->nSwitches > 1); ShiAssert(obj->ParentObject->nDOFs > 0); if (obj->ParentObject->nDOFs <= 0) return true; if (obj->ParentObject->nSwitches <= 1) return true; DWORD sw = obj->SwitchValues[1]; #ifdef DEBUG_ENGINE // Get the timings float Delta = GetTickCount() * 36.0f * DegreesPerSecond; #else // Get the timings float Delta = TheTimeManager.GetClockTime() * 36.0f * DegreesPerSecond; #endif float RelAngle; // get the angular difference btw camera and object ALWAYS POSITIVE ( + 2PI ) if (pos->y) RelAngle = (float)atan2(pos->x, pos->y); // calculate the Beacon World Transformation D3DXVECTOR3 BeaconWorldDir(1, 0, 0); // get the Beacon world transformation D3DXMATRIX WorldVect = TheDXEngine.AppliedState; // kill any world translation, just keep rotation WorldVect.m30 = WorldVect.m31 = WorldVect.m32 = 0.0f; WorldVect.m33 = 1.0f; // transform a coordinate of x=1,y=0 D3DXVec3TransformCoord(&BeaconWorldDir, &BeaconWorldDir, &WorldVect); // calculate rotation in WORLD SPACE ALWAYS POSITIVE ( + 2PI ) float Br = Delta - (float)atan2(BeaconWorldDir.x, BeaconWorldDir.y); // subract viever relative angle and keep it ALWAYS POSITIVE Br = Br + RelAngle + PI * 2; // get the Degrees fomr the 0 < r <2PI range ) RelAngle = (fmod(Br, PI * 2) - PI) / Degrees; // All flashes OFF sw and_eq 0xFFFFF000; // All off /////// 0 degree green light if (fabs(RelAngle) <= 3.0f) sw or_eq 0x7; // Flash on, has flashed, visible if (RelAngle >= 162.0f and RelAngle <= 168.0f) sw or_eq 0x700; // Flash on, has flashed, visible if (RelAngle >= -168.0f and RelAngle <= -162.0f) sw or_eq 0x70; // Flash on, has flashed, visible // Now store the computed results obj->DOFValues[0].rotation = (float)fmod(Delta, 2.0f * PI); //obj->DOFValues[0].rotation = TestAngle*Degrees; obj->SwitchValues[1] = sw; return true; } // Approach angle apprpriate VASI light indications (FAR set) bool DXScript_VASIF(D3DVECTOR *pos, ObjectInstance *obj, DWORD *Argument) { ShiAssert(obj->ParentObject->nSwitches > 0); if (obj->ParentObject->nSwitches <= 0) return true; float angle = (float)atan2(pos->z, sqrtf(pos->y * pos->y + pos->x * pos->x)) / Degrees; if (angle > 4.0f) obj->SetSwitch(0, 2); // White else obj->SetSwitch(0, 1); // Red return true; } // Approach angle apprpriate VASI light indications (NEAR set) bool DXScript_VASIN(D3DVECTOR *pos, ObjectInstance *obj, DWORD *Argument) { ShiAssert(obj->ParentObject->nSwitches > 0); if (obj->ParentObject->nSwitches <= 0) return true; float angle = (float)atan2(pos->z, sqrtf(pos->y * pos->y + pos->x * pos->x)) / Degrees; if (angle > 2.0f) obj->SetSwitch(0, 2); // White else obj->SetSwitch(0, 1); // Red return true; } #define GS (3.0f) #define NANGLES (sizeof(angles)/sizeof(float)) const float angles[] = {GS + 2.3f, GS + 2, GS + 1.7f, GS + 1.3f, GS + 1, GS + 0.7F, GS + 0.3f, GS, GS - 0.3f, GS - 0.7f, GS - 1, GS - 1.3f, GS - 1.7f }; // Approach angle for Carrier MeatBall - 13 switches (0-12) for vertical Glide Slope bool DXScript_MeatBall(D3DVECTOR *pos, ObjectInstance *obj, DWORD *Argument) { float angle = (float)atan2(pos->z, sqrtf(pos->y * pos->y + pos->x * pos->x)) / Degrees; ShiAssert(obj->ParentObject->nSwitches >= NANGLES - 2); if (obj->ParentObject->nSwitches <= NANGLES - 2) return true; for (int i = 0; i < NANGLES - 1; i++) { if (angle < angles[i] and angle > angles[i + 1]) obj->SetSwitch(i, 1); else obj->SetSwitch(i, 0); } return true; } // Chaff animation // TODO: Should run at 10hz, not frame rate (ie be time based not frame based) bool DXScript_Chaff(D3DVECTOR *pos, ObjectInstance *obj, DWORD *Argument) { #ifdef DEBUG_ENGINE // Get the timings DWORD Delta = (GetTickCount() bitand 0xffffff) / 100; #else // Get the timings DWORD Delta = (TheTimeManager.GetClockTime() bitand 0xffffff) / 100; #endif // consistency check if (obj->ParentObject->nSwitches <= 0) return true; // if 1st frame set the starting time if ((obj->SwitchValues[0] bitand 0xffff0000) == 0x0000) obj->SwitchValues[0] = (Delta << 16) bitand 0xffff0000; // update frame number every 100 mSec if ( not (obj->SwitchValues[0] bitand 0x8000)) obj->SwitchValues[0] = (obj->SwitchValues[0] bitand 0xffff0000) bitor (1 << ((Delta bitand 0xffff) - (obj->SwitchValues[0] >> 16) bitand 0x00ffff)); return true; } bool DXScript_CollapseChute(D3DVECTOR *pos, ObjectInstance *obj, DWORD *Argument) { ShiAssert(obj->ParentObject->nSwitches > 0); if (obj->SwitchValues[0] == 0) { obj->SwitchValues[0] = 1; } else if (obj->SwitchValues[0] < 0x40) { obj->SwitchValues[0] <<= 1; } else if (obj->SwitchValues[0] == 0x40) { obj->SwitchValues[0] = 0x10000020; } else if (obj->SwitchValues[0] == 0x10000020) { obj->SwitchValues[0] = 0x10000010; } else { obj->SwitchValues[0] = 0x00000008; } return true; } bool (*DXScriptArray[])(D3DVECTOR *pos, ObjectInstance*, DWORD*) = { DXScript_None, DXScript_Animate, DXScript_Rotate, DXScript_HelyRotate, DXScript_Beacon, DXScript_VASIF, DXScript_VASIN, DXScript_MeatBall, DXScript_Chaff, DXScript_CollapseChute, };
28.690722
156
0.610402
Terebinth
b29e20939c6dde13ae288f9e4c0b0e07ae823e4c
2,644
cpp
C++
console/tests/main.cpp
rideskip/anchor
fbd52aa2b049ba210619ab9e714fa43ce43f2081
[ "MIT" ]
53
2020-02-05T19:44:58.000Z
2022-03-11T20:59:17.000Z
console/tests/main.cpp
AudigoLabs/anchor
713365f3f8126c48d0f23e03a1d76215406da6ac
[ "MIT" ]
3
2020-03-29T17:16:55.000Z
2022-01-09T20:31:46.000Z
console/tests/main.cpp
rideskip/anchor
fbd52aa2b049ba210619ab9e714fa43ce43f2081
[ "MIT" ]
13
2020-03-02T08:55:14.000Z
2022-03-19T07:40:24.000Z
#include "gtest/gtest.h" extern "C" { #include "anchor/console/console.h" }; #include <stdio.h> #define CONSOLE_COMMAND_GET_INT_ARG(NAME) ({ \ int _arg; \ const bool _res = console_command_get_int_arg(NAME, &_arg); \ ASSERT_TRUE(_res); \ _arg; \ }) #define CONSOLE_COMMAND_GET_STR_ARG(NAME) ({ \ const char* _arg; \ const bool _res = console_command_get_str_arg(NAME, &_arg); \ ASSERT_TRUE(_res); \ _arg; \ }) #define CONSOLE_COMMAND_GET_OPTIONAL_INT_ARG(NAME, DEFAULT_VALUE) ({ \ int _arg; \ const bool _res = console_command_get_int_arg(NAME, &_arg); \ _res ? _arg : DEFAULT_VALUE; \ }) CONSOLE_COMMAND_DEF(say_hi, "Says hi"); CONSOLE_COMMAND_DEF(say_bye, "Says bye"); CONSOLE_COMMAND_DEF(minimal, NULL); CONSOLE_COMMAND_DEF(add, "Add two numbers", CONSOLE_INT_ARG_DEF(num1, "First number"), CONSOLE_INT_ARG_DEF(num2, "Second number"), CONSOLE_OPTIONAL_INT_ARG_DEF(num3, "Third (optional) number") ); CONSOLE_COMMAND_DEF(stroff, "Prints a string starting from an offset", CONSOLE_STR_ARG_DEF(str, "The string"), CONSOLE_INT_ARG_DEF(offset, "Offset into the string") ); std::vector<char> g_console_write_buffer; static void write_function(const char* str) { char c; while ((c = *str++) != '\0') { g_console_write_buffer.push_back(c); } } static void say_hi_command_handler(const say_hi_args_t* args) { write_function("hi\n"); } static void say_bye_command_handler(const say_bye_args_t* args) { write_function("hi\n"); } static void minimal_command_handler(const minimal_args_t* args) { write_function("Hello world!\n"); } static void add_command_handler(const add_args_t* args) { char buffer[100]; if (args->num3 != CONSOLE_INT_ARG_DEFAULT) { snprintf(buffer, sizeof(buffer), "%ld + %ld + %ld = %ld\n", args->num1, args->num2, args->num3, args->num1 + args->num2 + args->num3); } else { snprintf(buffer, sizeof(buffer), "%ld + %ld = %ld\n", args->num1, args->num2, args->num1 + args->num2); } write_function(buffer); } static void stroff_command_handler(const stroff_args_t* args) { char buffer[100]; snprintf(buffer, sizeof(buffer), "%s\n", args->str + args->offset); write_function(buffer); } int main(int argc, char **argv) { const console_init_t init_console = { .write_function = write_function, }; console_init(&init_console); g_console_write_buffer.clear(); console_command_register(say_hi); console_command_register(say_bye); console_command_register(minimal); console_command_register(add); console_command_register(stroff); ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
27.541667
138
0.711422
rideskip
b29ed0f46ed47c191cff55bd13da622b2415330b
6,791
cpp
C++
ixlib/old_wss/src/IXWebSocketPluginSetting.cpp
algamza/ixwss
fc323df76754d9f8aa24a36a24f640378c9e86bb
[ "Unlicense" ]
1
2020-02-11T02:42:31.000Z
2020-02-11T02:42:31.000Z
ixlib/old_wss/src/IXWebSocketPluginSetting.cpp
algamza/ixwss
fc323df76754d9f8aa24a36a24f640378c9e86bb
[ "Unlicense" ]
null
null
null
ixlib/old_wss/src/IXWebSocketPluginSetting.cpp
algamza/ixwss
fc323df76754d9f8aa24a36a24f640378c9e86bb
[ "Unlicense" ]
null
null
null
/** * @file IXWebSocketPluginSetting.cpp * @author Group(SW_Browser) <gsw_browser@humaxdigital.com> * @brief Session to manage the client based on WebSocket * * (c) 2017 Humax Co., Ltd. * This program is produced by Humax Co., Ltd. ("Humax") and * the proprietary Software of Humax and its licensors. Humax provides you, as an Authorized Licensee, * non-assignable, non-transferable and non-exclusive license to use this Software. * You acknowledge that this Software contains valuable trade secrets of Humax and by using this Software * you agree to the responsibility to take all reasonable efforts to protect the any information * you receive from Humax. You are not permitted to duplicate, modify, distribute, sell or lease and * reverse engineer or extract the source code of this Software unless you have Humax's written permission to do so. * If you have no authorized license, discontinue using this Software immediately. * * THE SOFTWARE IS PROVIDED "AS IS" AND HUMAX MAKES NO PROMISES, REPRESENTATIONS OR WARRANTIES, EITHER EXPRESS, * IMPLIED OR STATUTORY, OR OTHERWISE, WITH RESPECT TO THE SOFTWARE. * IN NO EVENT SHALL HUMAX BE LIABLE FOR LOST PROFITS, REVENUES, OR DATA, FINANCIAL LOSSES OR INDIRECT, SPECIAL, * CONSEQUENTIAL, EXEMPLARTY OR PUNITIVE DAMAGES WHATSOEVER RELATING TO YOUR USE OR INABILITY TO USE THE SOFTWARE. * This License is effective until terminated. You may terminate this License at any time by destroying all copies * of the Software including all documentation. This License will terminate immediately without notice from Humax * to you if you fail to comply with any provision of this License. Upon termination, you must destroy all copies * of the Software and all documentation. * The laws of the Republic of Korea will apply to any disputes arising out of or relating to this Copyright Notice. * All claims arising out of or relating to this Copyright Notice will be litigated in the Seoul Central District Court, * in the Republic of Korea. */ #include "IXWebSocketPluginSetting.h" #include "IXLog.h" #include <fstream> #include <cstring> using namespace std; namespace ixwss { /*-------------------------------------------------------------------------------- * class IXWebSocketPluginSetting *-------------------------------------------------------------------------------*/ IXWebSocketPluginSetting::IXWebSocketPluginSetting() : m_plugin_config_path("") , m_plugin_base_path("") { } IXWebSocketPluginSetting::~IXWebSocketPluginSetting() { m_ports.clear(); m_protocols.clear(); m_plugins_path.clear(); } bool IXWebSocketPluginSetting::setPluginConfigPath(const char *path) { if ( !path ) return false; m_plugin_config_path.assign(path); if ( !setPluginConfig(m_plugin_config_path) ) return false; return true; } const char *IXWebSocketPluginSetting::getPluginFilePath(int port, const char *protocol_name) { int index = 0; for ( auto it : m_ports ) { if ( it == port ) { auto protocol = m_protocols.begin(); advance(protocol, index); string default_name = "default"; if ( protocol_name ) default_name.assign(protocol_name); if ( (*protocol).compare(default_name) == 0 ) { auto plugin = m_plugins_path.begin(); advance(plugin, index); return (*plugin).c_str(); } } ++index; } return nullptr; } bool IXWebSocketPluginSetting::setPluginConfig(std::string conf_path) { m_ports.clear(); m_protocols.clear(); m_plugins_path.clear(); char readbuffer[256]; char *token = NULL; ifstream config_file; string plugin_config_file_path(conf_path); plugin_config_file_path.append("/ixplugins.conf"); config_file.open(plugin_config_file_path.c_str(), ios_base::binary); if ( config_file.is_open() != true ) { CRITICAL("It's wrong plugin config path !!! : " << plugin_config_file_path ); return false; } while ( config_file.eof() != true ) { int port = 0; string protocol = ""; string plugin = ""; config_file.getline(readbuffer, sizeof(readbuffer)); if ( !config_file.fail() && !config_file.bad() ) { if ( readbuffer[0] == '#' ) continue; token = strtok(readbuffer, "="); if ( token == NULL ) continue; if ( strcmp(token,"plugin_path") == 0 ) { token = strtok(NULL, ":"); if ( token != NULL ) { m_plugin_base_path.assign(token); INFO("* plugin_path : " << m_plugin_base_path ); } } else if (strcmp(token,"map_port_protocol_plugin") == 0 ) { token = strtok(NULL, ":"); if ( token != NULL ) { port = atoi(token); } token = strtok(NULL, ":"); if ( token != NULL ) { /** *@note condition of ixplugins.conf */ if ( strstr(token,".so") ) { protocol = "default"; plugin.assign(m_plugin_base_path); plugin.append("/"); plugin.append(token); } else { protocol = token; token = strtok(NULL, ":"); if ( token != NULL ) { plugin.assign(m_plugin_base_path); plugin.append("/"); plugin.append(token); } else { plugin = "default.so"; } } } INFO("* port : " << port << ", sub-protocol : " << protocol << ", plugin : " << plugin ); m_ports.push_back(port); m_protocols.push_back(protocol); m_plugins_path.push_back(plugin); } else { CRITICAL("* There is wrong field : " << token ); } } } config_file.close(); return true; } } /* namespace ixwss */
34.825641
121
0.5335
algamza
b29f31c132cc72e436a08ac99e03230aa8caa214
1,761
cpp
C++
src/SourceGenerator.cpp
MadLadSquad/UVKBuildTool
a25c0fb4f2ce407289a3f79aa9418272374b7a07
[ "MIT" ]
1
2022-02-08T07:08:28.000Z
2022-02-08T07:08:28.000Z
src/SourceGenerator.cpp
MadLadSquad/UVKBuildTool
a25c0fb4f2ce407289a3f79aa9418272374b7a07
[ "MIT" ]
null
null
null
src/SourceGenerator.cpp
MadLadSquad/UVKBuildTool
a25c0fb4f2ce407289a3f79aa9418272374b7a07
[ "MIT" ]
null
null
null
#include "SourceGenerator.hpp" void UBT::generateGame() { auto game = std::ofstream(path + static_cast<std::string>("Source/Game.hpp")); game << "// Do not edit this file! This file was generated by the UVKBuildTool and will be overridden the next time you run regenerate!" << std::endl; game << "#include \"Engine/Engine.hpp\"" << std::endl; game.close(); } void UBT::generateMain(const char* startupLevelName, const char* gameName) { auto main = std::ofstream(path + static_cast<std::string>("Generated/main.cpp")); main << R"(// This is an autogenerated file, touching it is not recommended #include <Engine.hpp> #include "Source/StartupLevel.hpp")" << std::endl; main << "#include \"Source/" << gameName << "GameInstance.hpp\"" << R"( int main(int argc, char** argv) { ENABLE_FAST_IO(true); UVK::AudioManager manager; bool bUsesEditor = false; #ifndef PRODUCTION if (argv[1]) { std::string cmd = argv[1]; if (cmd == "--editor") { bUsesEditor = true; } } #endif auto* st = new UVK::StartupLevel; UVK::global.getEditor() = bUsesEditor; UVK::global.currentLevel = st;)"; main << std::endl; main << " auto* mode = new UVK::" << gameName << "GameInstance();" << R"( UVK::global.instance = mode; UVK::UVKGlobal::openLevelInternal(")" << startupLevelName << "\", true);" << std::endl; main << " UVK::Renderer(UVK::global.currentLevel, bUsesEditor);" << std::endl; main << "}" << std::endl; main.close(); } void UBT::generateDef() { std::ofstream out2(path + "Generated/BuildDef.hpp"); out2 << "// Generated file, DO NOT TOUCH!" << std::endl; out2 << "#undef PRODUCTION" << std::endl; out2.close(); }
32.018182
154
0.611584
MadLadSquad
b29f7c3ad75ec12e23921bd5c0319c1db957bb89
21,165
hpp
C++
include/util/dnn_util.hpp
Sanaxen/Statistical_analysis
ac34c0cb9be071939cb1fad745e56bb4bf4f993f
[ "MIT" ]
null
null
null
include/util/dnn_util.hpp
Sanaxen/Statistical_analysis
ac34c0cb9be071939cb1fad745e56bb4bf4f993f
[ "MIT" ]
2
2018-09-18T13:47:48.000Z
2018-09-23T14:38:59.000Z
include/util/dnn_util.hpp
Sanaxen/Statistical_analysis
ac34c0cb9be071939cb1fad745e56bb4bf4f993f
[ "MIT" ]
null
null
null
/* Copyright (c) 2018, Sanaxn All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. */ #ifndef _DNN_UTIL_HPP #define _DNN_UTIL_HPP #define NOMINMAX #pragma warning( disable : 4244) #pragma warning( disable : 4267) #pragma warning( push ) #pragma warning( disable : 4477) #pragma warning( disable : 4819) #include <algorithm> #include <random> #include <string> #include "tiny_dnn/tiny_dnn.h" #include "tiny_dnn/util/util.h" #pragma warning( pop ) //#include "util/file_util.hpp" //#include "image/Image.hpp" using fc = tiny_dnn::layers::fc; using conv = tiny_dnn::layers::conv; using ave_pool = tiny_dnn::layers::ave_pool; using max_pool = tiny_dnn::max_pooling_layer; using deconv = tiny_dnn::deconvolutional_layer; using padding = tiny_dnn::padding; using recurrent = tiny_dnn::recurrent_layer; using recurrent_params = tiny_dnn::recurrent_layer_parameters; using relu = tiny_dnn::relu_layer; using leaky_relu = tiny_dnn::leaky_relu_layer; using softmax = tiny_dnn::softmax_layer; using tiny_dnn::core::connection_table; template <typename N> inline void set_train(N &nn, const int seq_len=0, const int bptt_max = 0, tiny_dnn::core::backend_t& defaule_backend = tiny_dnn::core::backend_t::internal) { nn.set_netphase(tiny_dnn::net_phase::train); for (unsigned int i = 0; i < nn.layer_size(); i++) { try { nn.template at<tiny_dnn::dropout_layer>(i).set_context( tiny_dnn::net_phase::train); } catch (tiny_dnn::nn_error &err) { } try { nn.template at<tiny_dnn::recurrent_layer>(i).seq_len(seq_len); nn.template at<tiny_dnn::recurrent_layer>(i).bptt_max(bptt_max); nn.template at<tiny_dnn::recurrent_layer>(i).clear_state(); } catch (tiny_dnn::nn_error &err) { } } #ifdef CNN_USE_INTEL_MKL for (auto n : nn) { if (n->layer_type() == "fully-connected") { n->set_backend_type(defaule_backend); } } #endif #ifdef CNN_USE_AVX for (auto n : nn) { if (n->layer_type() == "recurrent-layer") { n->set_backend_type(defaule_backend); } if (n->layer_type() == "lstm-cell") { n->set_backend_type(defaule_backend); } } #endif } template <typename N> inline void set_test(N &nn, const int seq_len=0) { nn.set_netphase(tiny_dnn::net_phase::test); for (unsigned int i = 0; i < nn.layer_size(); i++) { try { nn.template at<tiny_dnn::dropout_layer>(i).set_context( tiny_dnn::net_phase::test); } catch (tiny_dnn::nn_error &err) { } try { nn.template at<tiny_dnn::recurrent_layer>(i).seq_len(seq_len); nn.template at<tiny_dnn::recurrent_layer>(i).bptt_max(1e9); nn.template at<tiny_dnn::recurrent_layer>(i).clear_state(); } catch (tiny_dnn::nn_error &err) { } } #ifdef CNN_USE_INTEL_MKL for (auto n : nn) { if (n->layer_type() == "fully-connected") { n->set_backend_type(tiny_dnn::core::backend_t::intel_mkl); } if (n->layer_type() == "recurrent-layer") { n->set_backend_type(tiny_dnn::core::backend_t::avx); } if (n->layer_type() == "lstm-cell") { n->set_backend_type(tiny_dnn::core::backend_t::avx); } } #endif #ifdef CNN_USE_AVX for (auto n : nn) { if (n->layer_type() == "recurrent-layer") { n->set_backend_type(tiny_dnn::core::backend_t::avx); } } #endif } template <typename N> inline void rnn_state_reset(N &nn) { for (unsigned int i = 0; i < nn.layer_size(); i++) { try { nn.template at<tiny_dnn::recurrent_layer>(i).clear_state(); } catch (tiny_dnn::nn_error &err) { } } } inline size_t deconv_out_length(size_t in_length, size_t window_size, size_t stride) { return (size_t)ceil((float_t)(in_length)*stride + window_size - 1); } inline size_t deconv_out_unpadded_length(size_t in_length, size_t window_size, size_t stride, padding pad_type) { return pad_type == padding::same ? (size_t)ceil((float_t)in_length * stride) : (size_t)ceil((float_t)(in_length)*stride + window_size - 1); } namespace tiny_dnn { template <typename NetType> class network2 : public network<NetType> { size_t input_size; public: inline void set_input_size(size_t size) { input_size = size; } inline size_t& get_input_size() { return input_size; } inline void set_netphase(net_phase phase) { network<NetType>::set_netphase(phase); } inline result test(const std::vector<vec_t> &in, const std::vector<label_t> &t) { return network<NetType>::test(in, t); } inline std::vector<vec_t> test(const std::vector<vec_t> &in) { return network<NetType>::test(in, t); } void load(const std::string &filename, content_type what = content_type::weights_and_model, file_format format = file_format::binary) { return network<NetType>::load(filename, what, format); } inline void save(const std::string &filename, content_type what = content_type::weights_and_model, file_format format = file_format::binary) const { return network<NetType>::save(filename, what, format); } /* Saving consumption memory. We are saving memory by loading necessary data as much as possible so as not to read a large amount of learning data into memory all. */ template <typename Error, typename Optimizer, typename OnBatchEnumerate, typename OnEpochEnumerate, typename LoadTensorData> bool fit2(Optimizer &optimizer, const std::vector<tensor_t> &inputs, const std::vector<tensor_t> &desired_outputs, size_t batch_size, int epoch, OnBatchEnumerate on_batch_enumerate, OnEpochEnumerate on_epoch_enumerate, LoadTensorData load_tensor_data, const bool reset_weights = false, const int n_threads = CNN_TASK_SIZE, const std::vector<tensor_t> &t_cost = std::vector<tensor_t>()) { // check_training_data(in, t); check_target_cost_matrix(desired_outputs, t_cost); set_netphase(net_phase::train); net_.setup(reset_weights); for (auto n : net_) n->set_parallelize(true); optimizer.reset(); stop_training_ = false; in_batch_.resize(batch_size); t_batch_.resize(batch_size); for (int iter = 0; iter < epoch && !stop_training_; iter++) { int k = 0; for (size_t i = 0; i < input_size && !stop_training_; i += batch_size, k += batch_size) { if (k + batch_size > inputs.size()) { load_tensor_data(); k = 0; } train_once<Error>( optimizer, &inputs[k], &desired_outputs[k], static_cast<int>(std::min(batch_size, (size_t)inputs.size() - k)), n_threads, get_target_cost_sample_pointer(t_cost, k)); on_batch_enumerate(); /* if (i % 100 == 0 && layers_.is_exploded()) { std::cout << "[Warning]Detected infinite value in weight. stop learning." << std::endl; return false; } */ } on_epoch_enumerate(); } set_netphase(net_phase::test); return true; } inline void normalize_tensor(const std::vector<tensor_t> &inputs, std::vector<tensor_t> &normalized) { network<NetType>::normalize_tensor(inputs, normalized); } inline void normalize_tensor(const std::vector<vec_t> &inputs, std::vector<tensor_t> &normalized) { network<NetType>::normalize_tensor(inputs, normalized); } inline void normalize_tensor(const std::vector<label_t> &inputs, std::vector<tensor_t> &normalized) { network<NetType>::normalize_tensor(inputs, normalized); } }; } class DNNParameter { public: size_t seq_len = 10; float_t learning_rate = 1; size_t n_train_epochs = 30; std::string data_dir_path = ""; size_t n_minibatch = 16; tiny_dnn::core::backend_t backend_type = tiny_dnn::core::default_engine(); int plot = 0; float_t on_memory_rate = 0.8f; float_t augmentation_rate = 0.2f; size_t test_sample = 30; size_t decay_iter = 100; size_t save_iter = 10; bool out_of_core = false; }; class LayerInfo { using padding = tiny_dnn::padding; size_t out_w; size_t out_h; size_t out_map; tiny_dnn::core::backend_t backend_type; size_t parame_num = 0; public: inline size_t get_parameter_num() const { return parame_num; } #define PARAMETER_NUM(l) do{\ size_t param_ = 0;\ std::vector<tiny_dnn::vec_t *> weights = l.weights(); \ for (int i = 0; i < weights.size(); i++)\ {\ tiny_dnn::vec_t &w = *weights[i]; \ parame_num += w.size(); \ param_ += w.size(); \ }\ printf("param_:%d\n", param_);\ }while(0) inline void _editInfo(size_t out_w_, size_t out_h_, size_t out_map_) { out_w = out_w_; out_h = out_h_; out_map = out_map_; } inline LayerInfo(size_t iw, size_t ih, size_t imap, tiny_dnn::core::backend_t backend_type_ = tiny_dnn::core::default_engine()) { out_w = iw; out_h = ih; out_map = imap; backend_type = backend_type_; printf("input %zdx%zd(=%zd) fmap:%zd\n", iw, ih, iw*ih, imap); } void set_backend_type(tiny_dnn::core::backend_t backend_type_ = tiny_dnn::core::default_engine()) { backend_type = backend_type_; } inline size_t out(size_t& s) const { return out_w*out_h*out_map; } #define ACTIVATIN_SYMBL(name) \ {\ if (name == "selu_layer") return selu_layer();\ if (name == "relu") return relu();\ if (name == "leaky_relu") return leaky_relu();\ if (name == "elu") return elu();\ if (name == "tanh") return tanh();\ if (name == "sigmoid") return sigmoid();\ if (name == "softmax") return softmax();\ if (name == "softplus") return softplus();\ if (name == "softsign") return softsign();\ } #define ACTIVATIN_FUNC(class_name) \ {\ size_t in_w = out_w;\ size_t in_h = out_h;\ size_t in_map = out_map;\ printf("%s %zdx%zd fmap:%zd->", #class_name, in_w, in_h, in_map);\ printf(" %zdx%zd fmap:%zd\n", out_w, out_h, out_map);\ return tiny_dnn::class_name();\ } #define ACTIVATIN_FUNC2(class_name, param) \ {\ size_t in_w = out_w;\ size_t in_h = out_h;\ size_t in_map = out_map;\ printf("%s %zdx%zd fmap:%zd->", #class_name, in_w, in_h, in_map);\ printf(" %zdx%zd fmap:%zd\n", out_w, out_h, out_map);\ return tiny_dnn::class_name(param);\ } inline tiny_dnn::selu_layer selu_layer() { ACTIVATIN_FUNC(selu_layer) } inline tiny_dnn::relu_layer relu() { ACTIVATIN_FUNC(relu_layer) } inline tiny_dnn::leaky_relu_layer leaky_relu() { ACTIVATIN_FUNC2(leaky_relu_layer, float_t(0.0001)) } inline tiny_dnn::elu_layer elu() { ACTIVATIN_FUNC(elu_layer) } inline tiny_dnn::tanh_layer tanh() { ACTIVATIN_FUNC(tanh_layer) } inline tiny_dnn::sigmoid_layer sigmoid() { ACTIVATIN_FUNC(sigmoid_layer) } inline tiny_dnn::softmax_layer softmax(int classnum) { ACTIVATIN_FUNC2(softmax_layer, classnum) } inline tiny_dnn::softplus_layer softplus() { ACTIVATIN_FUNC(softplus_layer) } inline tiny_dnn::softsign_layer softsign() { ACTIVATIN_FUNC(softsign_layer) } #if 0 inline tiny_dnn::deconvolutional_layer add_decnv( size_t out_channels = 1, size_t window_size = 1, size_t stride = 1, tiny_dnn::padding pad_type = tiny_dnn::padding::valid, bool has_bias = true ) { return add_decnv(out_channels, window_size, window_size, stride, stride, pad_type, has_bias); } inline tiny_dnn::deconvolutional_layer add_decnv( size_t out_channels = 1, size_t window_width = 1, size_t window_height = 1, size_t w_stride = 1, size_t h_stride = 1, tiny_dnn::padding pad_type = tiny_dnn::padding::valid, bool has_bias = true ) { size_t in_w = out_w; size_t in_h = out_h; size_t in_map = out_map; out_map = out_channels; size_t w_dilation = 1; size_t h_dilation = 1; tiny_dnn::deconvolutional_layer layer = tiny_dnn::deconvolutional_layer(in_w, in_h, window_width, window_height, in_map, out_map, pad_type, has_bias, w_stride, h_stride, backend_type); out_w = conv_out_length(in_w, window_width, w_stride, w_dilation, pad_type); out_h = conv_out_length(in_h, window_height, h_stride, h_dilation, pad_type); //out_w = deconv_out_length(in_w, window_width, w_stride); //out_h = deconv_out_length(in_h, window_height, h_stride); out_w = deconv_out_unpadded_length(in_w, window_width, w_stride, pad_type); out_h = deconv_out_unpadded_length(in_h, window_height, h_stride, pad_type); //out_w = layer.out_shape()[0].size(); //out_h = layer.out_shape()[1].size(); printf("deconvolutional_layer %zdx%zd filter(%zd,%zd) stride(%zd,%zd) fmap:%zd->", in_w, in_h, window_width, window_height, w_stride, h_stride, in_map); printf(" %zdx%zd fmap:%zd\n", out_w, out_h, out_map); PARAMETER_NUM(layer); return layer; } #endif inline tiny_dnn::convolutional_layer add_cnv( size_t out_channels = 1, size_t window_size = 1, size_t stride = 1, tiny_dnn::padding pad_type = tiny_dnn::padding::valid, bool has_bias = true, tiny_dnn::core::connection_table &connection_table = tiny_dnn::core::connection_table() ) { return add_cnv(out_channels, window_size, window_size, stride, stride, pad_type, has_bias, connection_table); } inline tiny_dnn::convolutional_layer add_cnv( size_t out_channels = 1, size_t window_width = 1, size_t window_height = 1, size_t w_stride = 1, size_t h_stride = 1, tiny_dnn::padding pad_type = tiny_dnn::padding::valid, bool has_bias = true, tiny_dnn::core::connection_table &connection_table = tiny_dnn::core::connection_table() ) { size_t in_w = out_w; size_t in_h = out_h; size_t in_map = out_map; out_map = out_channels; size_t w_dilation = 1; size_t h_dilation = 1; tiny_dnn::convolutional_layer layer = tiny_dnn::convolutional_layer(in_w, in_h, window_width, window_height, in_map, out_map, pad_type, has_bias, w_stride, h_stride, w_dilation, h_dilation, backend_type); out_w = conv_out_length(in_w, window_width, w_stride, w_dilation, pad_type); out_h = conv_out_length(in_h, window_height, h_stride, h_dilation, pad_type); //if (out_h <= 0 ) out_h = 1; printf("convolutional_layer %zdx%zd filter(%zd,%zd) stride(%zd,%zd) fmap:%zd->", in_w, in_h, window_width, window_height, w_stride, h_stride, in_map); printf(" %zdx%zd fmap:%zd\n", out_w, out_h, out_map); PARAMETER_NUM(layer); return layer; } inline tiny_dnn::max_pooling_layer add_maxpool( size_t pooling_size, padding pad_type = padding::valid) { return add_maxpool(pooling_size, pooling_size, pooling_size, pooling_size, pad_type); } inline tiny_dnn::max_pooling_layer add_maxpool( size_t pooling_size, size_t stride, padding pad_type = padding::valid) { return add_maxpool(pooling_size, pooling_size, stride, stride, pad_type); } inline tiny_dnn::max_pooling_layer add_maxpool( size_t pooling_size_x, size_t pooling_size_y, size_t stride_x, size_t stride_y, padding pad_type = padding::valid) { size_t in_w = out_w; size_t in_h = out_h; size_t in_map = out_map; bool ceil_mode = false; size_t dilation = 1; tiny_dnn::max_pooling_layer layer = tiny_dnn::max_pooling_layer(in_w, in_h, in_map, pooling_size_x, pooling_size_y, stride_x, stride_y, ceil_mode, pad_type, backend_type); out_w = conv_out_length(in_w, pooling_size_x, stride_x, dilation, pad_type); out_h = conv_out_length(in_h, pooling_size_y, stride_y, dilation, pad_type); //if (out_h <= 0) out_h = 1; printf("max_pooling_layer %zdx%zd filter(%zd,%zd) stride(%zd,%zd) fmap:%zd->", in_w, in_h, pooling_size_x, pooling_size_y, stride_x, stride_y, in_map); printf(" %zdx%zd fmap:%zd\n", out_w, out_h, out_map); return layer; } inline tiny_dnn::average_pooling_layer add_avepool( size_t pooling_size, padding pad_type = padding::valid) { return add_avepool(pooling_size, pooling_size, pooling_size, pooling_size, pad_type); } inline tiny_dnn::average_pooling_layer add_avepool( size_t pooling_size, size_t stride, padding pad_type = padding::valid) { return add_avepool(pooling_size, pooling_size, stride, stride, pad_type); } inline tiny_dnn::average_pooling_layer add_avepool( size_t pooling_size_x, size_t pooling_size_y, size_t stride_x, size_t stride_y, padding pad_type = padding::valid) { size_t in_w = out_w; size_t in_h = out_h; size_t in_map = out_map; size_t dilation = 1; bool ceil_mode = false; tiny_dnn::average_pooling_layer layer = tiny_dnn::average_pooling_layer(in_w, in_h, in_map, pooling_size_x, pooling_size_y, stride_x, stride_y, ceil_mode, pad_type); out_w = conv_out_length(in_w, pooling_size_x, stride_x, dilation, pad_type); out_h = conv_out_length(in_h, pooling_size_y, stride_y, dilation, pad_type); printf("average_pooling_layer %zdx%zd filter(%zd,%zd) stride(%zd,%zd) fmap:%zd->", in_w, in_h, pooling_size_x, pooling_size_y, stride_x, stride_y, in_map); printf(" %zdx%zd fmap:%zd\n", out_w, out_h, out_map); return layer; } inline tiny_dnn::batch_normalization_layer add_batnorm( tiny_dnn::layer &prev_layer, float_t epsilon = 1e-5, float_t momentum = 0.999, tiny_dnn::net_phase phase = tiny_dnn::net_phase::train ) { size_t in_w = out_w; size_t in_h = out_h; size_t in_map = out_map; tiny_dnn::batch_normalization_layer layer = tiny_dnn::batch_normalization_layer(prev_layer, epsilon, momentum, phase); printf("batch_normalization_layer %zdx%zd fmap:%zd->", in_w, in_h, in_map); printf(" %zdx%zd fmap:%zd\n", out_w, out_h, out_map); PARAMETER_NUM(layer); return layer; } inline tiny_dnn::batch_normalization_layer add_batnorm( float_t epsilon = 1e-5, float_t momentum = 0.999, tiny_dnn::net_phase phase = tiny_dnn::net_phase::train ) { size_t in_w = out_w; size_t in_h = out_h; size_t in_map = out_map; tiny_dnn::batch_normalization_layer layer = tiny_dnn::batch_normalization_layer(in_w*in_h, in_map, epsilon, momentum, phase); printf("batch_normalization_layer %zdx%zd fmap:%zd->", in_w, in_h, in_map); printf(" %zdx%zd fmap:%zd\n", out_w, out_h, out_map); PARAMETER_NUM(layer); return layer; } inline tiny_dnn::dropout_layer add_dropout( float_t dropout_rate, tiny_dnn::net_phase phase = tiny_dnn::net_phase::train ) { size_t in_w = out_w; size_t in_h = out_h; size_t in_map = out_map; size_t in_dim = in_w*in_h*in_map; tiny_dnn::dropout_layer layer = tiny_dnn::dropout_layer(in_dim, dropout_rate, phase); printf("dropout_layer %.3f %zdx%zd fmap:%zd->", dropout_rate, in_w, in_h, in_map); printf(" %zdx%d fmap:%d\n", in_dim, 1, 1); return layer; } inline tiny_dnn::linear_layer add_linear( size_t out_dim, float_t scale = float_t{ 1 }, float_t bias = float_t{ 0 } ) { size_t in_w = out_w; size_t in_h = out_h; size_t in_map = out_map; size_t in_dim = in_w*in_h*in_map; tiny_dnn::linear_layer layer = tiny_dnn::linear_layer(out_dim, scale, bias); out_w = out_dim; out_h = 1; out_map = 1; printf("linear_layer %zdx%zd fmap:%zd->", in_w, in_h, in_map); printf(" %zdx%d fmap:%d\n", out_dim, 1, 1); PARAMETER_NUM(layer); return layer; } inline tiny_dnn::input_layer add_input( size_t out_dim ) { size_t in_w = out_w; size_t in_h = out_h; size_t in_map = out_map; size_t in_dim = in_w*in_h*in_map; tiny_dnn::input_layer layer = tiny_dnn::input_layer(in_dim); out_w = out_dim; out_h = 1; out_map = 1; printf("input_layer %zdx%zd fmap:%zd->", in_w, in_h, in_map); printf(" %zdx%d fmap:%d\n", out_dim, 1, 1); PARAMETER_NUM(layer); return layer; } inline tiny_dnn::fully_connected_layer add_fc( size_t out_dim, bool has_bias = true ) { size_t in_w = out_w; size_t in_h = out_h; size_t in_map = out_map; size_t in_dim = in_w*in_h*in_map; tiny_dnn::fully_connected_layer layer = tiny_dnn::fully_connected_layer(in_dim, out_dim, has_bias, backend_type); out_w = out_dim; out_h = 1; out_map = 1; printf("fully_connected_layer %zdx%zd fmap:%zd->", in_w, in_h, in_map); printf(" %zdx%d fmap:%d\n", out_dim, 1, 1); PARAMETER_NUM(layer); return layer; } inline tiny_dnn::recurrent_layer add_rnn( std::string& rnn_type, size_t hidden_size, int seq_len, const recurrent_params& prmam ) { size_t in_w = out_w; size_t in_h = out_h; size_t in_map = out_map; size_t input_size = in_w*in_h*in_map; out_w = hidden_size; out_h = 1; out_map = 1; printf("recurrent_layer_%s %zdx%zd fmap:%zd->", rnn_type.c_str(), in_w, in_h, in_map); printf(" %zdx%d fmap:%d\n", hidden_size, 1, 1); if (rnn_type == "rnn") { tiny_dnn::recurrent_layer layer = recurrent(tiny_dnn::rnn(input_size, hidden_size), seq_len, prmam); PARAMETER_NUM(layer); return layer; } else if (rnn_type == "gru") { tiny_dnn::recurrent_layer layer = recurrent(tiny_dnn::gru(input_size, hidden_size), seq_len, prmam); PARAMETER_NUM(layer); return layer; } else if (rnn_type == "lstm") { tiny_dnn::recurrent_layer layer = recurrent(tiny_dnn::lstm(input_size, hidden_size), seq_len, prmam); PARAMETER_NUM(layer); return layer; } else { tiny_dnn::recurrent_layer layer = recurrent(tiny_dnn::rnn(input_size, hidden_size), seq_len, prmam); PARAMETER_NUM(layer); return layer; } } }; #undef ACTIVATIN_SYMBL #undef ACTIVATIN_FUNC #endif
28.993151
206
0.697094
Sanaxen
b2a1b59f044c86b4bd57ff4a82232b6281001998
464
cpp
C++
source/libraries/ArduinoJson-master/src/Arduino/String.cpp
doanthuyan/AirSniffer
44cffe8cda507a8ba112cee477a9d6e5b43e90ef
[ "MIT" ]
null
null
null
source/libraries/ArduinoJson-master/src/Arduino/String.cpp
doanthuyan/AirSniffer
44cffe8cda507a8ba112cee477a9d6e5b43e90ef
[ "MIT" ]
null
null
null
source/libraries/ArduinoJson-master/src/Arduino/String.cpp
doanthuyan/AirSniffer
44cffe8cda507a8ba112cee477a9d6e5b43e90ef
[ "MIT" ]
1
2016-01-12T07:51:18.000Z
2016-01-12T07:51:18.000Z
// Copyright Benoit Blanchon 2014-2015 // MIT License // // Arduino JSON library // https://github.com/bblanchon/ArduinoJson #ifndef ARDUINO #include "../../include/ArduinoJson/Arduino/String.hpp" #include <stdio.h> // for sprintf() String::String(double value, unsigned char digits) { char tmp[32]; sprintf(tmp, "%.*f", digits, value); *this = tmp; } String::String(long value) { char tmp[32]; sprintf(tmp, "%ld", value); *this = tmp; } #endif
17.846154
55
0.663793
doanthuyan
b2a57293585c85fe44eab62ea722bd904425b2c9
623
cpp
C++
problemsets/SPOJ/SPOJ/EASYPROB.cpp
juarezpaulino/coderemite
a4649d3f3a89d234457032d14a6646b3af339ac1
[ "Apache-2.0" ]
null
null
null
problemsets/SPOJ/SPOJ/EASYPROB.cpp
juarezpaulino/coderemite
a4649d3f3a89d234457032d14a6646b3af339ac1
[ "Apache-2.0" ]
null
null
null
problemsets/SPOJ/SPOJ/EASYPROB.cpp
juarezpaulino/coderemite
a4649d3f3a89d234457032d14a6646b3af339ac1
[ "Apache-2.0" ]
null
null
null
/** * * Author: Juarez Paulino(coderemite) * Email: juarez.paulino@gmail.com * */ #include <cstdio> using namespace std; const int NUM[] = {137, 1315, 73, 136, 255, 1384, 16385, 0}; void print(int N) { int e, p; for (e = 0, p = 1; 2*p <= N; e++, p*=2); if (e == 0) { printf("2(0)"); return; } printf("2"); if (e > 1){ printf("("); print(e); printf(")"); } N-=p; if (N) { printf("+"); print(N); } } int main() { freopen("OUT.txt", "w", stdout); for (int i = 0; NUM[i]; i++) { printf("%d=", NUM[i]); print(NUM[i]); putchar('\n'); } return 0; }
17.8
60
0.467095
juarezpaulino
b2a82eb21412fdc3aad86b07a1bed002d48f39da
8,824
cpp
C++
src/ofApp.cpp
aalto-mediacode/photosynthetic
b95896a2fee7b14071bad0c38912c8201ee3d151
[ "MIT" ]
null
null
null
src/ofApp.cpp
aalto-mediacode/photosynthetic
b95896a2fee7b14071bad0c38912c8201ee3d151
[ "MIT" ]
null
null
null
src/ofApp.cpp
aalto-mediacode/photosynthetic
b95896a2fee7b14071bad0c38912c8201ee3d151
[ "MIT" ]
null
null
null
// This project includes Wireframe extrucion from VideoGrabber, midi-controlling the mesh and screen capturing the images // Base of this code is based on Tim Gfrerer and James George OF cameraMesh -example // I used for the final version OpenFrameworks and Touchdesigner. //file for the Touchdesigner is in the bin folder: mlab_GMC_touch_points.32 // to find more of my work, visit: nikotiainen.com #include "ofApp.h" const int width = 800; const int height = 600; // these are for Syphon //-------------------------------------------------------------- void ofApp::setup(){ //________MIDI STUFF________ ofSetLogLevel(OF_LOG_VERBOSE); // print input ports to console midiIn.listInPorts(); // open port by number (you may need to change this) midiIn.openPort(0); // add ofApp as a listener midiIn.addListener(this); // print received messages to the console midiIn.setVerbose(true); // _______Syphon stuff________ mainOutputSyphonServer.setName("Screen Output"); // ______vertex stuff__________ mainMesh.setMode(OF_PRIMITIVE_LINE_STRIP_ADJACENCY); //for trying different versions //mainMesh.setMode(OF_PRIMITIVE_TRIANGLE_STRIP_ADJACENCY); //mainMesh.setMode(OF_PRIMITIVE_POINTS); ofSetFrameRate(5); ofBackground(0); //initialize the video grabber vidGrabber.setVerbose(true); vidGrabber.setDeviceID(0); //vidGrabber.setDeviceID(1); // this is for external webcam vidGrabber.setup(100, 100); //store the width and height for convenience int width = vidGrabber.getWidth(); int height = vidGrabber.getHeight(); //add one vertex to the mesh for each pixel for (int y = 0; y < height; y++){ for (int x = 0; x<width; x++){ mainMesh.addVertex(glm::vec3(x,y,0)); // mesh index = x + y*width // this replicates the pixel array within the camera bitmap... mainMesh.addColor(ofFloatColor(0,0,0)); // placeholder for colour data, we'll get this from the camera } } for (int y = 0; y<height-1; y++){ for (int x=0; x<width-1; x++){ mainMesh.addIndex(x+y*width); // 0 } } //this is an annoying thing that is used to flip the camera cam.setScale(1,-1,1); } //-------------------------------------------------------------- void ofApp::update(){ /* //_______MIDI STUFF_________ // this is the midi-setup. You need a midi-controller for using these setups. Messages are mapped for Akai LPO8 -midi-controller for(unsigned int i = 0; i < midiMessages.size(); ++i) { ofxMidiMessage &message = midiMessages[i]; int x = 10; int y = i*40 + 40; stringstream text; text << ofxMidiMessage::getStatusString(message.status); while(text.str().length() < 16) { // pad status width text << " "; } int knob1 = (message.control==1)? message.value : 0; // its 1 int knob2 = (message.control==2)? message.value : 0; int knob3 = (message.control==3)? message.value : 0; int knob4 = (message.control==4)? message.value : 0; int knob5 = (message.control==5)? message.value : 0; int knob6 = (message.control==6)? message.value : 0; int knob7 = (message.control==7)? message.value : 0; int knob8 = (message.control==8)? message.value : 0; float pad1 = (message.pitch==40)? message.velocity : 0; float pad2 = (message.pitch==41)? message.velocity : 0; float pad3 = (message.pitch==42)? message.velocity : 0; float pad4 = (message.pitch==43)? message.velocity : 0; float pad5 = (message.pitch==44)? message.velocity : 0; float pad6 = (message.pitch==45)? message.velocity : 0; float pad7 = (message.pitch==46)? message.velocity : 0; float pad8 = (message.pitch==47)? message.velocity : 0; //extrusionAmount = ofMap(knob1, 0, 127, -300, -500); // this is for controlling the extrucion thru midi //_________ */ extrusionAmount = -500; // this is for mesh extrucion vidGrabber.update(); //update the mesh if we have a new frame if (vidGrabber.isFrameNew()){ //this determines how far we extrude the mesh for (int i=0; i<vidGrabber.getWidth()*vidGrabber.getHeight(); i++){ ofFloatColor sampleColor(vidGrabber.getPixels()[i*3]/255.f, // r vidGrabber.getPixels()[i*3+1]/255.f, // g vidGrabber.getPixels()[i*3+2]/255.f); // b //now we get the vertex aat this position //we extrude the mesh based on it's brightness glm::vec3 tmpVec = mainMesh.getVertex(i); // these are for changing colors tmpVec.z = sampleColor.getHue() * extrusionAmount; // You can try these also: //tmpVec.z = sampleColor.getLightness() * extrusionAmount; //tmpVec.z = sampleColor.getBrightnes() * extrusionAmount; mainMesh.setVertex(i, tmpVec); // this is for coloring the mesh mainMesh.setColor(i, sampleColor); //B&W -version below //mainMesh.setColor(i, 100); } } //let's move the camera when you move the mouse. Fix the last two values if you want this to work float rotateAmount = ofMap(ofGetMouseY(), 0, ofGetHeight(), 0, 0); //move the camera around the mesh glm::vec3 camDirection(0,0,1); glm::vec3 centre(vidGrabber.getWidth()/2.f,vidGrabber.getHeight()/2.f, 255/2.f); glm::vec3 camDirectionRotated = glm::rotate(camDirection, rotateAmount, glm::vec3(1,0,0)); glm::vec3 camPosition = centre + camDirectionRotated * extrusionAmount; cam.setPosition(camPosition); cam.lookAt(centre); } //-------------------------------------------------------------- void ofApp::draw(){ /* this is for the gradient background ofColor colorOne(255, 0, 0); ofColor colorTwo(0, 0, 0); ofBackgroundGradient(colorOne, colorTwo, OF_GRADIENT_CIRCULAR); */ cam.begin(); mainMesh.draw(); // to draw the wireframe cam.end(); /* this is for the fading ofSetColor(0, fade+= 0.2); if(fade >270){ fade=1; } ofDrawRectangle(0, 0, ofGetWidth(), ofGetHeight()) ;*/ //____________SYPHON STUFF____________ //ofSetColor(255, 255, 255); //ofEnableAlphaBlending(); mainOutputSyphonServer.publishScreen(); } //-------------------------------------------------------------- void ofApp::keyPressed(int key){ // This is for taking generative still pictures if(key == ' '){ ofSaveFrame(); } } //-------------------------------------------------------------- void ofApp::keyReleased(int key){ } //-------------------------------------------------------------- void ofApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void ofApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseEntered(int x, int y){ } //-------------------------------------------------------------- void ofApp::mouseExited(int x, int y){ } //-------------------------------------------------------------- void ofApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void ofApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void ofApp::dragEvent(ofDragInfo dragInfo){ } void ofApp::exit() { // clean up midiIn.closePort(); midiIn.removeListener(this); } void ofApp::newMidiMessage(ofxMidiMessage& msg) { // add the latest message to the message queue midiMessages.push_back(msg); // remove any old messages if we have too many while(midiMessages.size() > maxMessages) { midiMessages.erase(midiMessages.begin()); } }
30.961404
133
0.523232
aalto-mediacode
b2a8a0021c5a31ba2df56519503fb6fd028ada58
46,277
cpp
C++
spirv_module.cpp
HansKristian-Work/DXIL2SPIRV
ea9ac33ae88c9efb0f864d473eb22c3c04d166a5
[ "MIT" ]
5
2019-11-07T13:14:56.000Z
2019-12-09T20:01:47.000Z
spirv_module.cpp
HansKristian-Work/DXIL2SPIRV
ea9ac33ae88c9efb0f864d473eb22c3c04d166a5
[ "MIT" ]
null
null
null
spirv_module.cpp
HansKristian-Work/DXIL2SPIRV
ea9ac33ae88c9efb0f864d473eb22c3c04d166a5
[ "MIT" ]
null
null
null
/* Copyright (c) 2019-2022 Hans-Kristian Arntzen for Valve Corporation * * SPDX-License-Identifier: MIT * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "spirv_module.hpp" #include "descriptor_qa.hpp" #include "SpvBuilder.h" #include "node.hpp" #include "scratch_pool.hpp" #include "logging.hpp" namespace dxil_spv { constexpr uint32_t GENERATOR = 1967215134; struct SPIRVModule::Impl : BlockEmissionInterface { Impl() : builder(GENERATOR, &build_logger) { } spv::SpvBuildLogger build_logger; spv::Builder builder; spv::Function *entry_function = nullptr; spv::Function *active_function = nullptr; spv::Instruction *entry_point = nullptr; void emit_entry_point(spv::ExecutionModel model, const char *name, bool physical_storage); bool finalize_spirv(Vector<uint32_t> &spirv); void register_block(CFGNode *node) override; void emit_basic_block(CFGNode *node) override; void emit_entry_point_function_body(CFGStructurizer &structurizer); void emit_leaf_function_body(spv::Function *func, CFGStructurizer &structurizer); static spv::Block *get_spv_block(CFGNode *node); void enable_shader_discard(bool supports_demote); void build_discard_call_early(); void build_discard_call_early_cond(spv::Id cond); void build_demote_call_cond(spv::Id cond); void build_discard_call_exit(); spv::Id build_descriptor_qa_check(SPIRVModule &module); spv::Id build_wave_match(SPIRVModule &module, spv::Id type_id); spv::Id build_wave_multi_prefix_count_bits(SPIRVModule &module); spv::Id build_wave_multi_prefix_op(SPIRVModule &module, spv::Op opcode, spv::Id type_id); spv::Id build_robust_physical_cbv_load(SPIRVModule &module, spv::Id type_id, spv::Id ptr_type_id, unsigned alignment); spv::Function *discard_function = nullptr; spv::Function *discard_function_cond = nullptr; spv::Function *demote_function_cond = nullptr; spv::Id discard_state_var_id = 0; spv::ExecutionModel execution_model = spv::ExecutionModelMax; spv::Id create_variable(spv::StorageClass storage, spv::Id type, const char *name); spv::Id create_variable_with_initializer(spv::StorageClass storage, spv::Id type, spv::Id initializer, const char *name); void register_active_variable(spv::StorageClass storage, spv::Id id); struct { bool supports_demote = false; } caps; spv::Id get_builtin_shader_input(spv::BuiltIn builtin); spv::Id get_builtin_shader_output(spv::BuiltIn builtin); bool has_builtin_shader_input(spv::BuiltIn builtin) const; bool has_builtin_shader_output(spv::BuiltIn builtin) const; void register_builtin_shader_input(spv::Id id, spv::BuiltIn builtin); bool query_builtin_shader_input(spv::Id id, spv::BuiltIn *builtin) const; void register_builtin_shader_output(spv::Id id, spv::BuiltIn builtin); bool query_builtin_shader_output(spv::Id id, spv::BuiltIn *builtin) const; UnorderedMap<spv::BuiltIn, spv::Id> builtins_input; UnorderedMap<spv::Id, spv::BuiltIn> id_to_builtin_input; UnorderedMap<spv::BuiltIn, spv::Id> builtins_output; UnorderedMap<spv::Id, spv::BuiltIn> id_to_builtin_output; spv::Id get_type_for_builtin(spv::BuiltIn builtin); ScratchPool<Operation> operation_pool; bool spirv_requires_14() const; bool builtin_requires_volatile(spv::BuiltIn builtin) const; bool execution_model_is_ray_tracing() const; bool mark_error = false; spv::Id get_helper_call_id(SPIRVModule &module, HelperCall call, spv::Id type_id); spv::Id descriptor_qa_helper_call_id = 0; spv::Id wave_multi_prefix_count_bits_id = 0; Vector<std::pair<spv::Id, spv::Id>> wave_match_call_ids; struct MultiPrefixOp { spv::Op opcode; spv::Id type_id; spv::Id func_id; }; Vector<MultiPrefixOp> wave_multi_prefix_call_ids; struct CBVOp { spv::Id type_id; spv::Id ptr_type_id; unsigned alignment; spv::Id func_id; }; Vector<CBVOp> physical_cbv_call_ids; DescriptorQAInfo descriptor_qa_info; }; spv::Id SPIRVModule::Impl::get_type_for_builtin(spv::BuiltIn builtin) { switch (builtin) { case spv::BuiltInSampleMask: return builder.makeArrayType(builder.makeUintType(32), builder.makeUintConstant(1), 0); case spv::BuiltInTessCoord: return builder.makeVectorType(builder.makeFloatType(32), 3); case spv::BuiltInLocalInvocationIndex: case spv::BuiltInSampleId: case spv::BuiltInVertexIndex: case spv::BuiltInInstanceIndex: case spv::BuiltInBaseVertex: case spv::BuiltInBaseInstance: case spv::BuiltInInvocationId: case spv::BuiltInPrimitiveId: case spv::BuiltInShadingRateKHR: case spv::BuiltInPrimitiveShadingRateKHR: case spv::BuiltInViewIndex: return builder.makeUintType(32); case spv::BuiltInSubgroupSize: case spv::BuiltInSubgroupLocalInvocationId: builder.addCapability(spv::CapabilityGroupNonUniform); return builder.makeUintType(32); case spv::BuiltInGlobalInvocationId: case spv::BuiltInLocalInvocationId: case spv::BuiltInWorkgroupId: case spv::BuiltInLaunchIdKHR: case spv::BuiltInLaunchSizeKHR: return builder.makeVectorType(builder.makeUintType(32), 3); case spv::BuiltInObjectRayOriginKHR: case spv::BuiltInWorldRayOriginKHR: case spv::BuiltInObjectRayDirectionKHR: case spv::BuiltInWorldRayDirectionKHR: return builder.makeVectorType(builder.makeFloatType(32), 3); case spv::BuiltInRayTminKHR: case spv::BuiltInRayTmaxKHR: return builder.makeFloatType(32); case spv::BuiltInWorldToObjectKHR: case spv::BuiltInObjectToWorldKHR: return builder.makeMatrixType(builder.makeFloatType(32), 4, 3); case spv::BuiltInInstanceCustomIndexKHR: case spv::BuiltInInstanceId: case spv::BuiltInRayGeometryIndexKHR: case spv::BuiltInIncomingRayFlagsKHR: case spv::BuiltInHitKindKHR: return builder.makeUintType(32); case spv::BuiltInHelperInvocation: case spv::BuiltInFullyCoveredEXT: return builder.makeBoolType(); default: return 0; } } void SPIRVModule::Impl::register_builtin_shader_input(spv::Id id, spv::BuiltIn builtin) { builtins_input[builtin] = id; id_to_builtin_input[id] = builtin; } void SPIRVModule::Impl::register_builtin_shader_output(spv::Id id, spv::BuiltIn builtin) { builtins_output[builtin] = id; id_to_builtin_output[id] = builtin; } bool SPIRVModule::Impl::query_builtin_shader_input(spv::Id id, spv::BuiltIn *builtin) const { auto itr = id_to_builtin_input.find(id); if (itr != id_to_builtin_input.end()) { *builtin = itr->second; return true; } else return false; } bool SPIRVModule::Impl::query_builtin_shader_output(spv::Id id, spv::BuiltIn *builtin) const { auto itr = id_to_builtin_output.find(id); if (itr != id_to_builtin_output.end()) { *builtin = itr->second; return true; } else return false; } bool SPIRVModule::Impl::builtin_requires_volatile(spv::BuiltIn builtin) const { if (!execution_model_is_ray_tracing()) return false; switch (builtin) { case spv::BuiltInSubgroupId: case spv::BuiltInSubgroupLocalInvocationId: case spv::BuiltInSubgroupEqMask: case spv::BuiltInSubgroupLtMask: case spv::BuiltInSubgroupLeMask: case spv::BuiltInSubgroupGtMask: case spv::BuiltInSubgroupGeMask: return true; case spv::BuiltInRayTmaxKHR: return execution_model == spv::ExecutionModelIntersectionKHR; default: return false; } } bool SPIRVModule::Impl::has_builtin_shader_input(spv::BuiltIn builtin) const { return builtins_input.count(builtin) != 0; } bool SPIRVModule::Impl::has_builtin_shader_output(spv::BuiltIn builtin) const { return builtins_output.count(builtin) != 0; } spv::Id SPIRVModule::Impl::get_builtin_shader_input(spv::BuiltIn builtin) { auto itr = builtins_input.find(builtin); if (itr != builtins_input.end()) return itr->second; spv::Id var_id = create_variable(spv::StorageClassInput, get_type_for_builtin(builtin), nullptr); builder.addDecoration(var_id, spv::DecorationBuiltIn, builtin); if (builtin_requires_volatile(builtin)) builder.addDecoration(var_id, spv::DecorationVolatile); register_builtin_shader_input(var_id, builtin); return var_id; } spv::Id SPIRVModule::Impl::get_builtin_shader_output(spv::BuiltIn builtin) { auto itr = builtins_output.find(builtin); if (itr != builtins_output.end()) return itr->second; else return 0; } spv::Block *SPIRVModule::Impl::get_spv_block(CFGNode *node) { return static_cast<spv::Block *>(node->userdata); } void SPIRVModule::Impl::emit_entry_point(spv::ExecutionModel model, const char *name, bool physical_storage) { execution_model = model; builder.addCapability(spv::Capability::CapabilityShader); if (physical_storage) { builder.setMemoryModel(spv::AddressingModel::AddressingModelPhysicalStorageBuffer64, spv::MemoryModelGLSL450); builder.addCapability(spv::CapabilityPhysicalStorageBufferAddresses); builder.addExtension("SPV_KHR_physical_storage_buffer"); } else builder.setMemoryModel(spv::AddressingModel::AddressingModelLogical, spv::MemoryModel::MemoryModelGLSL450); entry_function = builder.makeEntryPoint("main"); entry_point = builder.addEntryPoint(model, entry_function, name); if (model == spv::ExecutionModel::ExecutionModelFragment) builder.addExecutionMode(entry_function, spv::ExecutionMode::ExecutionModeOriginUpperLeft); } void SPIRVModule::Impl::enable_shader_discard(bool supports_demote) { caps.supports_demote = supports_demote; if (!discard_state_var_id && !caps.supports_demote) { auto *current_build_point = builder.getBuildPoint(); discard_state_var_id = create_variable(spv::StorageClassPrivate, builder.makeBoolType(), "discard_state"); builder.setBuildPoint(entry_function->getEntryBlock()); builder.createStore(builder.makeBoolConstant(false), discard_state_var_id); builder.setBuildPoint(current_build_point); } } void SPIRVModule::Impl::build_discard_call_early() { builder.createStore(builder.makeBoolConstant(true), discard_state_var_id); } void SPIRVModule::Impl::build_demote_call_cond(spv::Id cond) { auto *current_build_point = builder.getBuildPoint(); if (!demote_function_cond) { spv::Block *entry = nullptr; demote_function_cond = builder.makeFunctionEntry(spv::NoPrecision, builder.makeVoidType(), "demote_cond", { builder.makeBoolType() }, {}, &entry); auto *true_block = new spv::Block(builder.getUniqueId(), *demote_function_cond); auto *false_block = new spv::Block(builder.getUniqueId(), *demote_function_cond); builder.setBuildPoint(entry); builder.createSelectionMerge(false_block, 0); builder.createConditionalBranch(demote_function_cond->getParamId(0), true_block, false_block); true_block->addInstruction(std::make_unique<spv::Instruction>(spv::OpDemoteToHelperInvocationEXT)); builder.setBuildPoint(true_block); builder.createBranch(false_block); builder.setBuildPoint(false_block); builder.makeReturn(false); } builder.setBuildPoint(current_build_point); builder.createFunctionCall(demote_function_cond, { cond }); } void SPIRVModule::Impl::build_discard_call_early_cond(spv::Id cond) { auto *current_build_point = builder.getBuildPoint(); if (!discard_function_cond) { spv::Block *entry = nullptr; discard_function_cond = builder.makeFunctionEntry(spv::NoPrecision, builder.makeVoidType(), "discard_cond", { builder.makeBoolType() }, {}, &entry); auto *true_block = new spv::Block(builder.getUniqueId(), *discard_function_cond); auto *false_block = new spv::Block(builder.getUniqueId(), *discard_function_cond); builder.setBuildPoint(entry); builder.createSelectionMerge(false_block, 0); builder.createConditionalBranch(discard_function_cond->getParamId(0), true_block, false_block); builder.setBuildPoint(true_block); builder.createStore(builder.makeBoolConstant(true), discard_state_var_id); builder.createBranch(false_block); builder.setBuildPoint(false_block); builder.makeReturn(false); } builder.setBuildPoint(current_build_point); builder.createFunctionCall(discard_function_cond, { cond }); } void SPIRVModule::Impl::build_discard_call_exit() { auto *current_build_point = builder.getBuildPoint(); if (!discard_function) { spv::Block *entry = nullptr; discard_function = builder.makeFunctionEntry(spv::NoPrecision, builder.makeVoidType(), "discard_exit", {}, {}, &entry); auto *true_block = new spv::Block(builder.getUniqueId(), *discard_function); auto *false_block = new spv::Block(builder.getUniqueId(), *discard_function); builder.setBuildPoint(entry); spv::Id loaded_state = builder.createLoad(discard_state_var_id); builder.createSelectionMerge(false_block, 0); builder.createConditionalBranch(loaded_state, true_block, false_block); true_block->addInstruction(std::make_unique<spv::Instruction>(spv::OpKill)); builder.setBuildPoint(false_block); builder.makeReturn(false); } builder.setBuildPoint(current_build_point); builder.createFunctionCall(discard_function, {}); } spv::Id SPIRVModule::Impl::build_descriptor_qa_check(SPIRVModule &module) { if (!descriptor_qa_helper_call_id) descriptor_qa_helper_call_id = build_descriptor_qa_check_function(module); return descriptor_qa_helper_call_id; } static const char *opcode_to_multi_prefix_name(spv::Op opcode) { switch (opcode) { case spv::OpGroupNonUniformFAdd: case spv::OpGroupNonUniformIAdd: return "WaveMultiPrefixSum"; case spv::OpGroupNonUniformFMul: case spv::OpGroupNonUniformIMul: return "WaveMultiPrefixProduct"; case spv::OpGroupNonUniformBitwiseAnd: return "WaveMultiPrefixBitAnd"; case spv::OpGroupNonUniformBitwiseOr: return "WaveMultiPrefixBitOr"; case spv::OpGroupNonUniformBitwiseXor: return "WaveMultiPrefixBitXor"; default: return ""; } } spv::Id SPIRVModule::Impl::build_wave_multi_prefix_op(SPIRVModule &module, spv::Op opcode, spv::Id type_id) { for (auto &call : wave_multi_prefix_call_ids) if (call.opcode == opcode && call.type_id == type_id) return call.func_id; auto *current_build_point = builder.getBuildPoint(); spv::Block *entry = nullptr; spv::Id uint_type = builder.makeUintType(32); spv::Id uvec4_type = builder.makeVectorType(uint_type, 4); spv::Id bool_type = builder.makeBoolType(); spv::Id bvec4_type = builder.makeVectorType(bool_type, 4); auto *func = builder.makeFunctionEntry(spv::NoPrecision, type_id, opcode_to_multi_prefix_name(opcode), { type_id, uvec4_type }, {}, &entry); spv::Id value_id = func->getParamId(0); spv::Id mask_id = func->getParamId(1); spv::Id undef_value = builder.createUndefined(type_id); auto *header_block = new spv::Block(builder.getUniqueId(), *func); auto *body_block = new spv::Block(builder.getUniqueId(), *func); auto *merge_block = new spv::Block(builder.getUniqueId(), *func); auto *prefix_block = new spv::Block(builder.getUniqueId(), *func); auto *continue_block = new spv::Block(builder.getUniqueId(), *func); builder.setBuildPoint(entry); { auto ballot_op = std::make_unique<spv::Instruction>(builder.getUniqueId(), uvec4_type, spv::OpGroupNonUniformBallot); ballot_op->addIdOperand(builder.makeUintConstant(spv::ScopeSubgroup)); ballot_op->addIdOperand(builder.makeBoolConstant(true)); auto mask_op = std::make_unique<spv::Instruction>(builder.getUniqueId(), uvec4_type, spv::OpBitwiseAnd); mask_op->addIdOperand(ballot_op->getResultId()); mask_op->addIdOperand(mask_id); mask_id = mask_op->getResultId(); entry->addInstruction(std::move(ballot_op)); entry->addInstruction(std::move(mask_op)); builder.createBranch(header_block); } builder.setBuildPoint(header_block); { builder.createLoopMerge(merge_block, body_block, 0); builder.createBranch(body_block); } builder.setBuildPoint(body_block); spv::Id compare_reduce_id; { auto broadcast_first = std::make_unique<spv::Instruction>(builder.getUniqueId(), uvec4_type, spv::OpGroupNonUniformBroadcastFirst); broadcast_first->addIdOperand(builder.makeUintConstant(spv::ScopeSubgroup)); broadcast_first->addIdOperand(mask_id); auto compare = std::make_unique<spv::Instruction>(builder.getUniqueId(), bvec4_type, spv::OpIEqual); compare->addIdOperand(mask_id); compare->addIdOperand(broadcast_first->getResultId()); auto compare_reduce = std::make_unique<spv::Instruction>(builder.getUniqueId(), bool_type, spv::OpAll); compare_reduce->addIdOperand(compare->getResultId()); compare_reduce_id = compare_reduce->getResultId(); body_block->addInstruction(std::move(broadcast_first)); body_block->addInstruction(std::move(compare)); body_block->addInstruction(std::move(compare_reduce)); builder.createSelectionMerge(continue_block, 0); builder.createConditionalBranch(compare_reduce_id, prefix_block, continue_block); } spv::Id result_id; builder.setBuildPoint(prefix_block); { auto prefix_op = std::make_unique<spv::Instruction>(builder.getUniqueId(), type_id, opcode); prefix_op->addIdOperand(builder.makeUintConstant(spv::ScopeSubgroup)); prefix_op->addImmediateOperand(spv::GroupOperationExclusiveScan); prefix_op->addIdOperand(value_id); result_id = prefix_op->getResultId(); prefix_block->addInstruction(std::move(prefix_op)); builder.createBranch(continue_block); } builder.setBuildPoint(continue_block); { auto phi = std::make_unique<spv::Instruction>(builder.getUniqueId(), type_id, spv::OpPhi); phi->addIdOperand(result_id); phi->addIdOperand(prefix_block->getId()); phi->addIdOperand(undef_value); phi->addIdOperand(body_block->getId()); result_id = phi->getResultId(); continue_block->addInstruction(std::move(phi)); builder.createConditionalBranch(compare_reduce_id, merge_block, header_block); } builder.setBuildPoint(merge_block); builder.makeReturn(false, result_id); builder.setBuildPoint(current_build_point); builder.addCapability(spv::CapabilityGroupNonUniformBallot); builder.addCapability(spv::CapabilityGroupNonUniformArithmetic); wave_multi_prefix_call_ids.push_back({ opcode, type_id, func->getId() }); return func->getId(); } spv::Id SPIRVModule::Impl::build_wave_multi_prefix_count_bits(SPIRVModule &module) { if (wave_multi_prefix_count_bits_id) return wave_multi_prefix_count_bits_id; auto *current_build_point = builder.getBuildPoint(); spv::Id uint_type = builder.makeUintType(32); spv::Id uvec4_type = builder.makeVectorType(uint_type, 4); spv::Id bool_type = builder.makeBoolType(); spv::Id bvec4_type = builder.makeVectorType(bool_type, 4); spv::Block *entry = nullptr; auto *func = builder.makeFunctionEntry(spv::NoPrecision, uint_type, "WaveMultiPrefixCountBits", { bool_type, uvec4_type }, {}, &entry); spv::Id value_id = func->getParamId(0); spv::Id mask_id = func->getParamId(1); auto *header_block = new spv::Block(builder.getUniqueId(), *func); auto *body_block = new spv::Block(builder.getUniqueId(), *func); auto *merge_block = new spv::Block(builder.getUniqueId(), *func); builder.setBuildPoint(entry); { auto ballot_op = std::make_unique<spv::Instruction>(builder.getUniqueId(), uvec4_type, spv::OpGroupNonUniformBallot); ballot_op->addIdOperand(builder.makeUintConstant(spv::ScopeSubgroup)); ballot_op->addIdOperand(builder.makeBoolConstant(true)); auto mask_op = std::make_unique<spv::Instruction>(builder.getUniqueId(), uvec4_type, spv::OpBitwiseAnd); mask_op->addIdOperand(ballot_op->getResultId()); mask_op->addIdOperand(mask_id); mask_id = mask_op->getResultId(); entry->addInstruction(std::move(ballot_op)); entry->addInstruction(std::move(mask_op)); builder.createBranch(header_block); } builder.setBuildPoint(header_block); { builder.createLoopMerge(merge_block, body_block, 0); builder.createBranch(body_block); } spv::Id result_id; builder.setBuildPoint(body_block); { auto broadcast_first = std::make_unique<spv::Instruction>(builder.getUniqueId(), uvec4_type, spv::OpGroupNonUniformBroadcastFirst); broadcast_first->addIdOperand(builder.makeUintConstant(spv::ScopeSubgroup)); broadcast_first->addIdOperand(mask_id); auto compare = std::make_unique<spv::Instruction>(builder.getUniqueId(), bvec4_type, spv::OpIEqual); compare->addIdOperand(mask_id); compare->addIdOperand(broadcast_first->getResultId()); auto compare_reduce = std::make_unique<spv::Instruction>(builder.getUniqueId(), bool_type, spv::OpAll); compare_reduce->addIdOperand(compare->getResultId()); spv::Id compare_reduce_id = compare_reduce->getResultId(); auto prefix_input = std::make_unique<spv::Instruction>(builder.getUniqueId(), bool_type, spv::OpLogicalAnd); prefix_input->addIdOperand(compare_reduce_id); prefix_input->addIdOperand(value_id); auto modified_ballot = std::make_unique<spv::Instruction>(builder.getUniqueId(), uvec4_type, spv::OpGroupNonUniformBallot); modified_ballot->addIdOperand(builder.makeUintConstant(spv::ScopeSubgroup)); modified_ballot->addIdOperand(prefix_input->getResultId()); auto count = std::make_unique<spv::Instruction>(builder.getUniqueId(), uint_type, spv::OpGroupNonUniformBallotBitCount); count->addIdOperand(builder.makeUintConstant(spv::ScopeSubgroup)); count->addImmediateOperand(spv::GroupOperationExclusiveScan); count->addIdOperand(modified_ballot->getResultId()); result_id = count->getResultId(); body_block->addInstruction(std::move(broadcast_first)); body_block->addInstruction(std::move(compare)); body_block->addInstruction(std::move(compare_reduce)); body_block->addInstruction(std::move(prefix_input)); body_block->addInstruction(std::move(modified_ballot)); body_block->addInstruction(std::move(count)); builder.createConditionalBranch(compare_reduce_id, merge_block, header_block); } builder.setBuildPoint(merge_block); builder.makeReturn(false, result_id); builder.setBuildPoint(current_build_point); builder.addCapability(spv::CapabilityGroupNonUniformBallot); builder.addCapability(spv::CapabilityGroupNonUniformArithmetic); wave_multi_prefix_count_bits_id = func->getId(); return func->getId(); } spv::Id SPIRVModule::Impl::build_wave_match(SPIRVModule &module, spv::Id type_id) { for (auto &type : wave_match_call_ids) if (type.first == type_id) return type.second; auto *current_build_point = builder.getBuildPoint(); builder.addCapability(spv::CapabilityGroupNonUniform); builder.addCapability(spv::CapabilityGroupNonUniformBallot); spv::Block *entry = nullptr; spv::Id uint_type = builder.makeUintType(32); spv::Id uvec4_type = builder.makeVectorType(uint_type, 4); auto *func = builder.makeFunctionEntry(spv::NoPrecision, uvec4_type, "WaveMatch", { type_id }, {}, &entry); spv::Id value_id = func->getParamId(0); auto *header_block = new spv::Block(builder.getUniqueId(), *func); auto *body_block = new spv::Block(builder.getUniqueId(), *func); auto *merge_block = new spv::Block(builder.getUniqueId(), *func); builder.setBuildPoint(entry); builder.createBranch(header_block); builder.setBuildPoint(header_block); builder.createLoopMerge(merge_block, body_block, 0); builder.createBranch(body_block); auto broadcast_first = std::make_unique<spv::Instruction>(builder.getUniqueId(), type_id, spv::OpGroupNonUniformBroadcastFirst); broadcast_first->addIdOperand(builder.makeUintConstant(spv::ScopeSubgroup)); broadcast_first->addIdOperand(value_id); // We cannot scalarize floats safely due to NaNs. Caller will bitcast to uint first. assert(builder.getTypeClass(type_id) != spv::OpTypeFloat); spv::Op equal_op; if (builder.getTypeClass(type_id) == spv::OpTypeBool) equal_op = spv::OpLogicalEqual; else equal_op = spv::OpIEqual; auto compare = std::make_unique<spv::Instruction>(builder.getUniqueId(), builder.makeBoolType(), equal_op); compare->addIdOperand(value_id); compare->addIdOperand(broadcast_first->getResultId()); spv::Id compare_id = compare->getResultId(); auto ballot = std::make_unique<spv::Instruction>(builder.getUniqueId(), uvec4_type, spv::OpGroupNonUniformBallot); ballot->addIdOperand(builder.makeUintConstant(spv::ScopeSubgroup)); ballot->addIdOperand(compare->getResultId()); spv::Id ballot_id = ballot->getResultId(); builder.setBuildPoint(body_block); body_block->addInstruction(std::move(broadcast_first)); body_block->addInstruction(std::move(compare)); body_block->addInstruction(std::move(ballot)); builder.createConditionalBranch(compare_id, merge_block, header_block); builder.setBuildPoint(merge_block); builder.makeReturn(false, ballot_id); builder.setBuildPoint(current_build_point); wave_match_call_ids.emplace_back(type_id, func->getId()); return func->getId(); } spv::Id SPIRVModule::Impl::build_robust_physical_cbv_load(SPIRVModule &module, spv::Id type_id, spv::Id ptr_type_id, unsigned alignment) { for (auto &func : physical_cbv_call_ids) if (func.ptr_type_id == ptr_type_id && func.type_id == type_id && func.alignment == alignment) return func.func_id; auto *current_build_point = builder.getBuildPoint(); spv::Block *entry = nullptr; spv::Id uint_type = builder.makeUintType(32); spv::Id bda_type = builder.makeVectorType(uint_type, 2); auto *func = builder.makeFunctionEntry(spv::NoPrecision, type_id, "RobustPhysicalCBVLoad", { bda_type, uint_type }, {}, &entry); spv::Id bda_value_id = func->getParamId(0); spv::Id index_id = func->getParamId(1); auto *body_block = new spv::Block(builder.getUniqueId(), *func); auto *merge_block = new spv::Block(builder.getUniqueId(), *func); builder.setBuildPoint(entry); auto compare = std::make_unique<spv::Instruction>(builder.getUniqueId(), builder.makeBoolType(), spv::OpULessThan); compare->addIdOperand(index_id); compare->addIdOperand(builder.makeUintConstant(64 * 1024 / alignment)); spv::Id compare_id = compare->getResultId(); entry->addInstruction(std::move(compare)); builder.createSelectionMerge(merge_block, 0); builder.createConditionalBranch(compare_id, body_block, merge_block); spv::Id loaded_id; { builder.setBuildPoint(body_block); auto bitcast_op = std::make_unique<spv::Instruction>( builder.getUniqueId(), ptr_type_id, spv::OpBitcast); auto chain_op = std::make_unique<spv::Instruction>( builder.getUniqueId(), builder.makePointer(spv::StorageClassPhysicalStorageBuffer, type_id), spv::OpInBoundsAccessChain); auto load_op = std::make_unique<spv::Instruction>( builder.getUniqueId(), type_id, spv::OpLoad); bitcast_op->addIdOperand(bda_value_id); chain_op->addIdOperand(bitcast_op->getResultId()); chain_op->addIdOperand(builder.makeUintConstant(0)); chain_op->addIdOperand(index_id); load_op->addIdOperand(chain_op->getResultId()); load_op->addImmediateOperand(spv::MemoryAccessAlignedMask); load_op->addImmediateOperand(alignment); loaded_id = load_op->getResultId(); body_block->addInstruction(std::move(bitcast_op)); body_block->addInstruction(std::move(chain_op)); body_block->addInstruction(std::move(load_op)); builder.createBranch(merge_block); } builder.setBuildPoint(merge_block); auto phi_op = std::make_unique<spv::Instruction>( builder.getUniqueId(), type_id, spv::OpPhi); phi_op->addIdOperand(builder.makeNullConstant(type_id)); phi_op->addIdOperand(entry->getId()); phi_op->addIdOperand(loaded_id); phi_op->addIdOperand(body_block->getId()); spv::Id return_value = phi_op->getResultId(); merge_block->addInstruction(std::move(phi_op)); builder.makeReturn(false, return_value); builder.setBuildPoint(current_build_point); physical_cbv_call_ids.push_back({ type_id, ptr_type_id, alignment, func->getId() }); return func->getId(); } spv::Id SPIRVModule::Impl::get_helper_call_id(SPIRVModule &module, HelperCall call, spv::Id type_id) { switch (call) { case HelperCall::DescriptorQACheck: return build_descriptor_qa_check(module); case HelperCall::WaveMatch: return build_wave_match(module, type_id); case HelperCall::WaveMultiPrefixCountBits: return build_wave_multi_prefix_count_bits(module); case HelperCall::WaveMultiPrefixFAdd: return build_wave_multi_prefix_op(module, spv::OpGroupNonUniformFAdd, type_id); case HelperCall::WaveMultiPrefixIAdd: return build_wave_multi_prefix_op(module, spv::OpGroupNonUniformIAdd, type_id); case HelperCall::WaveMultiPrefixFMul: return build_wave_multi_prefix_op(module, spv::OpGroupNonUniformFMul, type_id); case HelperCall::WaveMultiPrefixIMul: return build_wave_multi_prefix_op(module, spv::OpGroupNonUniformIMul, type_id); case HelperCall::WaveMultiPrefixBitOr: return build_wave_multi_prefix_op(module, spv::OpGroupNonUniformBitwiseOr, type_id); case HelperCall::WaveMultiPrefixBitAnd: return build_wave_multi_prefix_op(module, spv::OpGroupNonUniformBitwiseAnd, type_id); case HelperCall::WaveMultiPrefixBitXor: return build_wave_multi_prefix_op(module, spv::OpGroupNonUniformBitwiseXor, type_id); default: break; } return 0; } SPIRVModule::SPIRVModule() { impl = std::make_unique<Impl>(); } void SPIRVModule::emit_entry_point(spv::ExecutionModel model, const char *name, bool physical_storage) { impl->emit_entry_point(model, name, physical_storage); } bool SPIRVModule::Impl::execution_model_is_ray_tracing() const { switch (execution_model) { case spv::ExecutionModelRayGenerationKHR: case spv::ExecutionModelAnyHitKHR: case spv::ExecutionModelIntersectionKHR: case spv::ExecutionModelMissKHR: case spv::ExecutionModelClosestHitKHR: case spv::ExecutionModelCallableKHR: return true; default: return false; } } bool SPIRVModule::Impl::spirv_requires_14() const { return execution_model_is_ray_tracing(); } bool SPIRVModule::Impl::finalize_spirv(Vector<uint32_t> &spirv) { spirv.clear(); mark_error = false; builder.dump(spirv); if (spirv.size() >= 2) { static const uint32_t Version_1_3 = 0x00010300; static const uint32_t Version_1_4 = 0x00010400; spirv[1] = spirv_requires_14() ? Version_1_4 : Version_1_3; } return !mark_error; } void SPIRVModule::Impl::register_block(CFGNode *node) { if (!node->userdata || node->id == 0) { auto *bb = new spv::Block(builder.getUniqueId(), *active_function); #if 0 if (!node->name.empty()) builder.addName(bb->getId(), node->name.c_str()); #endif active_function->addBlock(bb); node->id = bb->getId(); node->userdata = bb; } } void SPIRVModule::Impl::emit_basic_block(CFGNode *node) { auto *bb = get_spv_block(node); auto &ir = node->ir; builder.setBuildPoint(bb); spv::Block *fake_loop_block = nullptr; // Break-like loops might not have a continue block. // Infinite loops won't have merge blocks. if (node->ir.merge_info.merge_type == MergeType::Loop && (int(node->ir.merge_info.merge_block != nullptr) + int(node->ir.merge_info.continue_block != nullptr) == 1)) { fake_loop_block = new spv::Block(builder.getUniqueId(), *active_function); } // Emit phi nodes. for (auto &phi : ir.phi) { if (!phi.id) continue; auto phi_op = std::make_unique<spv::Instruction>(phi.id, phi.type_id, spv::OpPhi); for (auto &incoming : phi.incoming) { phi_op->addIdOperand(incoming.id); phi_op->addIdOperand(incoming.block->id); } if (fake_loop_block && !node->ir.merge_info.continue_block) { builder.setBuildPoint(fake_loop_block); phi_op->addIdOperand(builder.createUndefined(phi.type_id)); builder.setBuildPoint(bb); phi_op->addIdOperand(fake_loop_block->getId()); } if (phi.relaxed) builder.addDecoration(phi.id, spv::DecorationRelaxedPrecision); bb->addInstruction(std::move(phi_op)); } bool implicit_terminator = false; // Emit opcodes. for (auto *op : ir.operations) { if (implicit_terminator) break; if (op->op == spv::OpIsHelperInvocationEXT && !caps.supports_demote) { spv::Id helper_var_id = get_builtin_shader_input(spv::BuiltInHelperInvocation); if (discard_state_var_id) { auto is_helper = std::make_unique<spv::Instruction>(builder.getUniqueId(), builder.makeBoolType(), spv::OpLoad); is_helper->addIdOperand(helper_var_id); spv::Id is_helper_id = is_helper->getResultId(); bb->addInstruction(std::move(is_helper)); auto loaded_var = std::make_unique<spv::Instruction>(builder.getUniqueId(), builder.makeBoolType(), spv::OpLoad); loaded_var->addIdOperand(discard_state_var_id); spv::Id is_discard_id = loaded_var->getResultId(); bb->addInstruction(std::move(loaded_var)); auto or_inst = std::make_unique<spv::Instruction>(op->id, op->type_id, spv::OpLogicalOr); or_inst->addIdOperand(is_helper_id); or_inst->addIdOperand(is_discard_id); bb->addInstruction(std::move(or_inst)); } else { auto is_helper = std::make_unique<spv::Instruction>(op->id, op->type_id, spv::OpLoad); is_helper->addIdOperand(helper_var_id); bb->addInstruction(std::move(is_helper)); } } else if (op->op == spv::OpDemoteToHelperInvocationEXT && !caps.supports_demote) { if (op->num_arguments) build_discard_call_early_cond(op->arguments[0]); else build_discard_call_early(); } else if (op->op == spv::OpDemoteToHelperInvocationEXT && op->num_arguments) { builder.addExtension("SPV_EXT_demote_to_helper_invocation"); builder.addCapability(spv::CapabilityDemoteToHelperInvocationEXT); build_demote_call_cond(op->arguments[0]); } else { if (op->op == spv::OpDemoteToHelperInvocationEXT || op->op == spv::OpIsHelperInvocationEXT) { builder.addExtension("SPV_EXT_demote_to_helper_invocation"); builder.addCapability(spv::CapabilityDemoteToHelperInvocationEXT); } else if (op->op == spv::OpTerminateRayKHR || op->op == spv::OpIgnoreIntersectionKHR) { // In DXIL, these must be by unreachable. // There is no [[noreturn]] qualifier used for these intrinsics apparently. implicit_terminator = true; } std::unique_ptr<spv::Instruction> inst; if (op->id != 0) inst = std::make_unique<spv::Instruction>(op->id, op->type_id, op->op); else inst = std::make_unique<spv::Instruction>(op->op); unsigned literal_mask = op->get_literal_mask(); for (auto &arg : *op) { if (literal_mask & 1u) inst->addImmediateOperand(arg); else { assert(arg); inst->addIdOperand(arg); } literal_mask >>= 1u; } bb->addInstruction(std::move(inst)); } } if (implicit_terminator) { if (ir.merge_info.merge_type != MergeType::None) { LOGE("Basic block has implicit terminator, but attempts to merge execution?\n"); mark_error = true; return; } else if (ir.terminator.type != Terminator::Type::Unreachable) { LOGE("Implicitly terminated blocks must terminate with Unreachable.\n"); mark_error = true; return; } return; } // Emit structured merge information. switch (ir.merge_info.merge_type) { case MergeType::Selection: if (ir.merge_info.merge_block) { builder.createSelectionMerge(get_spv_block(ir.merge_info.merge_block), 0); } else { auto *unreachable_bb = new spv::Block(builder.getUniqueId(), *active_function); active_function->addBlock(unreachable_bb); builder.setBuildPoint(unreachable_bb); builder.createUnreachable(); builder.setBuildPoint(bb); builder.createSelectionMerge(unreachable_bb, 0); } break; case MergeType::Loop: if (ir.merge_info.merge_block && ir.merge_info.continue_block) { builder.createLoopMerge(get_spv_block(ir.merge_info.merge_block), get_spv_block(ir.merge_info.continue_block), 0); } else if (ir.merge_info.merge_block) { auto *continue_bb = fake_loop_block; active_function->addBlock(continue_bb); builder.setBuildPoint(continue_bb); builder.createBranch(get_spv_block(node)); builder.setBuildPoint(bb); builder.createLoopMerge(get_spv_block(ir.merge_info.merge_block), continue_bb, 0); } else if (ir.merge_info.continue_block) { auto *merge_bb = fake_loop_block; active_function->addBlock(merge_bb); builder.setBuildPoint(merge_bb); builder.createUnreachable(); builder.setBuildPoint(bb); builder.createLoopMerge(merge_bb, get_spv_block(ir.merge_info.continue_block), 0); } break; default: break; } // Emit terminator. switch (ir.terminator.type) { case Terminator::Type::Unreachable: { builder.createUnreachable(); break; } case Terminator::Type::Branch: { builder.createBranch(get_spv_block(ir.terminator.direct_block)); break; } case Terminator::Type::Condition: { builder.createConditionalBranch(ir.terminator.conditional_id, get_spv_block(ir.terminator.true_block), get_spv_block(ir.terminator.false_block)); break; } case Terminator::Type::Switch: { auto switch_op = std::make_unique<spv::Instruction>(spv::OpSwitch); switch_op->addIdOperand(ir.terminator.conditional_id); auto default_itr = std::find_if(ir.terminator.cases.begin(), ir.terminator.cases.end(), [](const Terminator::Case &c) { return c.is_default; }); assert(default_itr != ir.terminator.cases.end()); switch_op->addIdOperand(default_itr->node->id); get_spv_block(default_itr->node)->addPredecessor(bb); for (auto &switch_case : ir.terminator.cases) { if (switch_case.is_default) continue; switch_op->addImmediateOperand(switch_case.value); switch_op->addIdOperand(switch_case.node->id); get_spv_block(switch_case.node)->addPredecessor(bb); } bb->addInstruction(std::move(switch_op)); break; } case Terminator::Type::Kill: { auto kill_op = std::make_unique<spv::Instruction>(spv::OpKill); bb->addInstruction(std::move(kill_op)); break; } case Terminator::Type::Return: { if (discard_state_var_id) build_discard_call_exit(); builder.makeReturn(false, ir.terminator.return_value); break; } default: break; } } bool SPIRVModule::finalize_spirv(Vector<uint32_t> &spirv) const { return impl->finalize_spirv(spirv); } void SPIRVModule::Impl::emit_entry_point_function_body(CFGStructurizer &structurizer) { active_function = entry_function; { structurizer.traverse(*this); builder.setBuildPoint(active_function->getEntryBlock()); builder.createBranch(get_spv_block(structurizer.get_entry_block())); builder.leaveFunction(); } active_function = nullptr; } void SPIRVModule::Impl::emit_leaf_function_body(spv::Function *func, CFGStructurizer &structurizer) { active_function = func; { structurizer.traverse(*this); builder.setBuildPoint(active_function->getEntryBlock()); builder.createBranch(get_spv_block(structurizer.get_entry_block())); builder.leaveFunction(); } active_function = nullptr; } void SPIRVModule::Impl::register_active_variable(spv::StorageClass storage, spv::Id id) { bool register_entry_point; // In SPIR-V 1.4, any global variable is part of the interface. if (spirv_requires_14()) register_entry_point = storage != spv::StorageClassFunction; else register_entry_point = storage == spv::StorageClassOutput || storage == spv::StorageClassInput; if (register_entry_point) entry_point->addIdOperand(id); } spv::Id SPIRVModule::Impl::create_variable(spv::StorageClass storage, spv::Id type, const char *name) { spv::Id id = builder.createVariable(storage, type, name); register_active_variable(storage, id); return id; } spv::Id SPIRVModule::Impl::create_variable_with_initializer(spv::StorageClass storage, spv::Id type, spv::Id initializer, const char *name) { spv::Id id = builder.createVariableWithInitializer(storage, type, initializer, name); register_active_variable(storage, id); return id; } void SPIRVModule::emit_entry_point_function_body(CFGStructurizer &structurizer) { impl->emit_entry_point_function_body(structurizer); } void SPIRVModule::emit_leaf_function_body(spv::Function *func, CFGStructurizer &structurizer) { impl->emit_leaf_function_body(func, structurizer); } spv::Builder &SPIRVModule::get_builder() { return impl->builder; } spv::Instruction *SPIRVModule::get_entry_point() { return impl->entry_point; } spv::Function *SPIRVModule::get_entry_function() { return impl->entry_function; } uint32_t SPIRVModule::allocate_id() { return impl->builder.getUniqueId(); } uint32_t SPIRVModule::allocate_ids(uint32_t count) { return impl->builder.getUniqueIds(count); } void SPIRVModule::enable_shader_discard(bool supports_demote) { impl->enable_shader_discard(supports_demote); } spv::Id SPIRVModule::get_builtin_shader_input(spv::BuiltIn builtin) { return impl->get_builtin_shader_input(builtin); } spv::Id SPIRVModule::get_builtin_shader_output(spv::BuiltIn builtin) { return impl->get_builtin_shader_output(builtin); } bool SPIRVModule::has_builtin_shader_input(spv::BuiltIn builtin) const { return impl->has_builtin_shader_input(builtin); } bool SPIRVModule::has_builtin_shader_output(spv::BuiltIn builtin) const { return impl->has_builtin_shader_output(builtin); } void SPIRVModule::register_builtin_shader_input(spv::Id id, spv::BuiltIn builtin) { impl->register_builtin_shader_input(id, builtin); } void SPIRVModule::register_builtin_shader_output(spv::Id id, spv::BuiltIn builtin) { impl->register_builtin_shader_output(id, builtin); } bool SPIRVModule::query_builtin_shader_input(spv::Id id, spv::BuiltIn *builtin) const { return impl->query_builtin_shader_input(id, builtin); } bool SPIRVModule::query_builtin_shader_output(spv::Id id, spv::BuiltIn *builtin) const { return impl->query_builtin_shader_output(id, builtin); } Operation *SPIRVModule::allocate_op() { return impl->operation_pool.allocate(); } Operation *SPIRVModule::allocate_op(spv::Op op) { return impl->operation_pool.allocate(op); } Operation *SPIRVModule::allocate_op(spv::Op op, spv::Id id, spv::Id type_id) { return impl->operation_pool.allocate(op, id, type_id); } spv::Id SPIRVModule::create_variable(spv::StorageClass storage, spv::Id type, const char *name) { return impl->create_variable(storage, type, name); } spv::Id SPIRVModule::create_variable_with_initializer(spv::StorageClass storage, spv::Id type, spv::Id initializer, const char *name) { return impl->create_variable_with_initializer(storage, type, initializer, name); } spv::Id SPIRVModule::get_helper_call_id(HelperCall call, spv::Id type_id) { return impl->get_helper_call_id(*this, call, type_id); } spv::Id SPIRVModule::get_robust_physical_cbv_load_call_id(spv::Id type_id, spv::Id ptr_type_id, unsigned alignment) { return impl->build_robust_physical_cbv_load(*this, type_id, ptr_type_id, alignment); } void SPIRVModule::set_descriptor_qa_info(const DescriptorQAInfo &info) { impl->descriptor_qa_info = info; } const DescriptorQAInfo &SPIRVModule::get_descriptor_qa_info() const { return impl->descriptor_qa_info; } bool SPIRVModule::opcode_is_control_dependent(spv::Op opcode) { // An opcode is considered control dependent if it is affected by other invocations in the subgroup. switch (opcode) { // Anything derivatives case spv::OpDPdx: case spv::OpDPdxCoarse: case spv::OpDPdxFine: case spv::OpDPdy: case spv::OpDPdyCoarse: case spv::OpDPdyFine: case spv::OpFwidth: case spv::OpFwidthCoarse: case spv::OpFwidthFine: // Anything implicit LOD case spv::OpImageSampleImplicitLod: case spv::OpImageSampleDrefImplicitLod: case spv::OpImageSampleProjImplicitLod: case spv::OpImageSampleProjDrefImplicitLod: case spv::OpImageSparseSampleImplicitLod: case spv::OpImageSparseSampleDrefImplicitLod: case spv::OpImageSparseSampleProjImplicitLod: case spv::OpImageSparseSampleProjDrefImplicitLod: case spv::OpImageQueryLod: case spv::OpImageDrefGather: case spv::OpImageGather: case spv::OpImageSparseDrefGather: case spv::OpImageSparseGather: // Anything subgroups case spv::OpGroupNonUniformElect: case spv::OpGroupNonUniformAll: case spv::OpGroupNonUniformAny: case spv::OpGroupNonUniformAllEqual: case spv::OpGroupNonUniformBroadcast: case spv::OpGroupNonUniformBroadcastFirst: case spv::OpGroupNonUniformBallot: case spv::OpGroupNonUniformInverseBallot: case spv::OpGroupNonUniformBallotBitExtract: case spv::OpGroupNonUniformBallotBitCount: case spv::OpGroupNonUniformBallotFindLSB: case spv::OpGroupNonUniformBallotFindMSB: case spv::OpGroupNonUniformShuffle: case spv::OpGroupNonUniformShuffleXor: case spv::OpGroupNonUniformShuffleUp: case spv::OpGroupNonUniformShuffleDown: case spv::OpGroupNonUniformIAdd: case spv::OpGroupNonUniformFAdd: case spv::OpGroupNonUniformIMul: case spv::OpGroupNonUniformFMul: case spv::OpGroupNonUniformSMin: case spv::OpGroupNonUniformUMin: case spv::OpGroupNonUniformFMin: case spv::OpGroupNonUniformSMax: case spv::OpGroupNonUniformUMax: case spv::OpGroupNonUniformFMax: case spv::OpGroupNonUniformBitwiseAnd: case spv::OpGroupNonUniformBitwiseOr: case spv::OpGroupNonUniformBitwiseXor: case spv::OpGroupNonUniformLogicalAnd: case spv::OpGroupNonUniformLogicalOr: case spv::OpGroupNonUniformLogicalXor: case spv::OpGroupNonUniformQuadBroadcast: case spv::OpGroupNonUniformQuadSwap: // Control barriers case spv::OpControlBarrier: return true; default: return false; } } SPIRVModule::~SPIRVModule() { } } // namespace dxil_spv
33.197274
133
0.758584
HansKristian-Work
b2a9cbb6e2a458661793b49755dd9eab470c0be5
2,694
cpp
C++
tests/std/tests/GH_001123_random_cast_out_of_range/test.cpp
isra-fel/STL
6ae9a578b4f52193dc523922c943a2214a873577
[ "Apache-2.0" ]
8,232
2019-09-16T22:51:24.000Z
2022-03-31T03:55:39.000Z
tests/std/tests/GH_001123_random_cast_out_of_range/test.cpp
isra-fel/STL
6ae9a578b4f52193dc523922c943a2214a873577
[ "Apache-2.0" ]
2,263
2019-09-17T05:19:55.000Z
2022-03-31T21:05:47.000Z
tests/std/tests/GH_001123_random_cast_out_of_range/test.cpp
isra-fel/STL
6ae9a578b4f52193dc523922c943a2214a873577
[ "Apache-2.0" ]
1,276
2019-09-16T22:51:40.000Z
2022-03-31T03:30:05.000Z
// Copyright (c) Microsoft Corporation. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception #include <cassert> #include <cmath> #include <cstdint> #include <limits> #include <random> #pragma warning(disable : 4984) // if constexpr is a C++17 language extension #ifdef __clang__ #pragma clang diagnostic ignored "-Wc++17-extensions" #endif // __clang__ template <class T> using lim = std::numeric_limits<T>; template <class IntType, class FltType> void CheckUpperBound(IntType i, FltType fmax) { const auto x{std::_Float_upper_bound<FltType>(i)}; const auto y{std::nextafter(x, FltType{0})}; // lower bound, <= i assert(y < fmax); assert(static_cast<IntType>(y) <= i); assert(x <= fmax); if (x < fmax) { assert(static_cast<IntType>(x) > i); } } template <class IntType, class FltType> void TestUpperBoundExhaustive() { const auto fmax{exp2(static_cast<FltType>(lim<IntType>::digits))}; IntType i{0}; do { CheckUpperBound(i, fmax); } while (++i != IntType{0}); } template <class T> constexpr T FillLsb(int n) { if (n <= 0) { return 0; } T x{T{1} << (n - 1)}; return (x - 1) ^ x; } template <class IntType, class FltType> void TestUpperBoundSelective() { const auto fmax{exp2(static_cast<FltType>(lim<IntType>::digits))}; CheckUpperBound(IntType{0}, fmax); CheckUpperBound(IntType{1}, fmax); CheckUpperBound(lim<IntType>::max(), fmax); constexpr int diff{lim<IntType>::digits - lim<FltType>::digits}; if constexpr (diff > 0) { // crossover from ulp < 1 to ulp = 1 constexpr auto a{FillLsb<IntType>(lim<FltType>::digits - 1)}; CheckUpperBound(a - 1, fmax); CheckUpperBound(a, fmax); // crossover from ulp = 1 to ulp > 1 constexpr auto b{FillLsb<IntType>(lim<FltType>::digits)}; CheckUpperBound(b, fmax); CheckUpperBound(b + 1, fmax); CheckUpperBound(b + 2, fmax); // saturation at the largest representable IntType constexpr auto c{FillLsb<IntType>(lim<FltType>::digits) << diff}; CheckUpperBound(c - 1, fmax); CheckUpperBound(c, fmax); CheckUpperBound(c + 1, fmax); } } int main() { TestUpperBoundExhaustive<std::uint8_t, float>(); TestUpperBoundExhaustive<std::uint16_t, float>(); TestUpperBoundSelective<std::uint32_t, float>(); TestUpperBoundExhaustive<unsigned short, double>(); TestUpperBoundSelective<unsigned int, double>(); TestUpperBoundSelective<unsigned long, double>(); TestUpperBoundSelective<unsigned long long, double>(); }
30.965517
78
0.632146
isra-fel
b2acbf5de86263ad5b5136016bd78f9d6875e740
850
hpp
C++
SDK/ARKSurvivalEvolved_ProjDragonFireBall_parameters.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
10
2020-02-17T19:08:46.000Z
2021-07-31T11:07:19.000Z
SDK/ARKSurvivalEvolved_ProjDragonFireBall_parameters.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
9
2020-02-17T18:15:41.000Z
2021-06-06T19:17:34.000Z
SDK/ARKSurvivalEvolved_ProjDragonFireBall_parameters.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
3
2020-07-22T17:42:07.000Z
2021-06-19T17:16:13.000Z
#pragma once // ARKSurvivalEvolved (329.9) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "ARKSurvivalEvolved_ProjDragonFireBall_classes.hpp" namespace sdk { //--------------------------------------------------------------------------- //Parameters //--------------------------------------------------------------------------- // Function ProjDragonFireBall.ProjDragonFireBall_C.UserConstructionScript struct AProjDragonFireBall_C_UserConstructionScript_Params { }; // Function ProjDragonFireBall.ProjDragonFireBall_C.ExecuteUbergraph_ProjDragonFireBall struct AProjDragonFireBall_C_ExecuteUbergraph_ProjDragonFireBall_Params { int EntryPoint; // (Parm, ZeroConstructor, IsPlainOldData) }; } #ifdef _MSC_VER #pragma pack(pop) #endif
25.757576
152
0.588235
2bite
b2b05dd50468e1ad6d7148a1ec504c5fe9dedad3
12,519
cpp
C++
src/ViewModel.cpp
cojomojo/opengl_skybox_game
8ef503bd41e2e51e5f9dbfd81fb99d21b5103580
[ "MIT" ]
null
null
null
src/ViewModel.cpp
cojomojo/opengl_skybox_game
8ef503bd41e2e51e5f9dbfd81fb99d21b5103580
[ "MIT" ]
null
null
null
src/ViewModel.cpp
cojomojo/opengl_skybox_game
8ef503bd41e2e51e5f9dbfd81fb99d21b5103580
[ "MIT" ]
null
null
null
//FileName: ViewModel.cpp //Programmer: Dan Cliburn, Cody Balos //Date: 11/15/2015 //Purpose: Define the methods for the World ViewModel class. //The Init() method needs to set up OpenGL and GLEW and prepare all objects (and their shaders) to be rendered. //The Draw() method positions and renders all objects in the scene and activates the appropriate shader(s). #include <glew.h> //glew.h is supposed to be included before gl.h. To be safe, you can just include glew.h instead #include <iostream> #include <string> #include <glm.hpp> #include <gtc/matrix_transform.hpp> #include <gtc/type_ptr.hpp> #include <detail/type_mat.hpp> #include "ViewModel.h" #include "config.inl" #include "LightProperties.h" #include "Transformation.h" using namespace glm; using namespace std; Transformation ViewModel::transform = { mat4(1.0f), mat4(1.0f), mat4(1.0f) }; GLuint ViewModel::transform_id = 0; GLuint ViewModel::transform_binding = 35; GLuint ViewModel::lights_binding = 0; ViewModel::ViewModel() : initialized{false}, level{game::GALAXY}, score_manager{std::make_unique<ScoreManager>()} { } bool ViewModel::InitGLEW() { //Next initialize GLEW GLenum err = glewInit(); if (GLEW_OK != err) { cout << "Error initializing GLEW: " << glewGetErrorString(err) << endl; return false; } //The following code was adapted from the OpenGL 4.0 Shading Language Cookbook, by David Wolff //to provide information about the hardware and supported versions of OpenGL and GLSL. const GLubyte *renderer = glGetString(GL_RENDERER); const GLubyte *vendor = glGetString(GL_VENDOR); const GLubyte *version = glGetString(GL_VERSION); const GLubyte *glslVersion = glGetString(GL_SHADING_LANGUAGE_VERSION); cout << "GL Vendor: " << vendor << endl; cout << "GL Renderer: " << renderer << endl; cout << "GL Version: " << version << endl; cout << "GLSL Version: " << glslVersion << endl << endl; return true; } // This method sets up all the shaders used in the game. This includes loading, compiling, // linking, activating, getting uniform names, etc. bool ViewModel::SetupShaders() { // Rules to follow: // Uniforms -> Pascal Case (ThisIsPascal) // Textures -> Pascal Case // Attributes -> Camel Case (thisIsCamelCase) energizer_shader = make_shared<ShaderProgram>(); energizer_shader->initFromFiles(SHADER_PATH + "/energizer.vert", SHADER_PATH + "/energizer.frag"); energizer_shader->addAttribute("vertexPosition"); energizer_shader->addAttribute("vertexColor"); energizer_shader->addAttribute("vertexNormal"); energizer_shader->addAttribute("vertexShininess"); skybox_shader = make_shared<ShaderProgram>(); skybox_shader->initFromFiles(SHADER_PATH + "/skybox.vert", SHADER_PATH + "/skybox.frag"); skybox_shader->addAttribute("vertexPosition"); skybox_shader->addUniform("CubeTexture"); default_shader = make_shared<ShaderProgram>(); default_shader->initFromFiles(SHADER_PATH + "/phong.vert", SHADER_PATH + "/phong.frag"); default_shader->addAttribute("vertexPosition"); default_shader->addAttribute("vertexColor"); default_shader->addAttribute("vertexNormal"); default_shader->addAttribute("vertexShininess"); return true; } /** * \brief This method sets up global lighting for the world. */ void ViewModel::SetUpLights() const { //IMPORTANT - If you change this structure in any way you need to change it in all fragment shader(s) as well!!! struct Lights { LightProperties lights[4]; vec3 globalAmbientLight; int totalLights; } lightInfo; //Now, set up the lights for the scene lightInfo.totalLights = 4; lightInfo.globalAmbientLight = vec3(0.3, 0.3, 0.3); lightInfo.lights[0].color = vec4(1.0, 0.0, 0.0, 1.0); lightInfo.lights[0].position = vec4(-4.0, 0.0, -4.0, 1.0); lightInfo.lights[0].spotLightValues = vec4(0.0, 0.0, 0.0, 0.0); lightInfo.lights[0].constantAttenuation = 2.0; lightInfo.lights[0].linearAttenuation = 0.0; lightInfo.lights[0].quadraticAttenuation = 0.0; lightInfo.lights[0].isEnabled = 1; lightInfo.lights[1].color = vec4(0.0, 1.0, 0.0, 1.0); lightInfo.lights[1].position = vec4(0.0, 3.0, 0.0, 1.0); //positional light since w = 1 lightInfo.lights[1].spotLightValues = vec4(0.0, 0.0, 0.0, 0.0); lightInfo.lights[1].constantAttenuation = 2.0; lightInfo.lights[1].linearAttenuation = 0.0; lightInfo.lights[1].quadraticAttenuation = 0.0; lightInfo.lights[1].isEnabled = 1; lightInfo.lights[2].color = vec4(0.0, 0.0, 1.0, 1.0); lightInfo.lights[2].position = vec4(5.0, 2.5, 0.0, 1.0); //positional light since w = 1 lightInfo.lights[2].spotLightValues = vec4(0.0, 0.0, 0.0, 0.0); lightInfo.lights[2].constantAttenuation = 2.0; lightInfo.lights[2].linearAttenuation = 0.0; lightInfo.lights[2].quadraticAttenuation = 0.0; lightInfo.lights[2].isEnabled = 1; lightInfo.lights[3].color = vec4(1.0, 1.0, 1.0, 1.0); lightInfo.lights[3].position = vec4(3.5, 1.75, -3.5, 1.0); //positional light since w = 1 lightInfo.lights[3].spotLightValues = vec4(1.0, 0.95, 4.0, 0.0); //If the first parameter to spotLightValues is > 0, then this is a spotlight //The second parameter to spotLightValues is the Spot Cosine Cutoff //The third parameter to spotLightValues is the Spotlight Exponent //The fourth parameter to spotLightValues is unused lightInfo.lights[3].spotConeDirection = vec4(0.25, -1.0, -0.25, 0.0); lightInfo.lights[3].constantAttenuation = 0.5; lightInfo.lights[3].linearAttenuation = 0.0; lightInfo.lights[3].quadraticAttenuation = 0.0; lightInfo.lights[3].isEnabled = 1; //Pass the light info to the shaders in a Uniform Buffer Object. //This allows ALL shaders to be able to access the light information. GLuint lightsLoc; glGenBuffers(1, &lightsLoc); glBindBuffer(GL_UNIFORM_BUFFER, lightsLoc); glBufferData(GL_UNIFORM_BUFFER, sizeof lightInfo, &lightInfo, GL_STATIC_DRAW); glBindBufferBase(GL_UNIFORM_BUFFER, lights_binding, lightsLoc); //The 0 needs to match the number used in the shaders for the lights } /** * \brief Initialize the game objects. * \return Returns true if intiailization of all objects was successful. */ bool ViewModel::Init(game::Levels level) { this->level = level; if (InitGLEW() == false) throw std::runtime_error("Could not initialize GLEW"); // Initialize OpenGL global settings glClearColor(0.05f, 0.05f, 0.05f, 1.0f); glEnable(GL_DEPTH_TEST); if (SetupShaders() == false) throw std::runtime_error("Could not setup shaders."); //////////////////////////////////////////////////////// // Setup the bounding box for the player/glman/camera // //////////////////////////////////////////////////////// std::vector<glm::vec3> glman_vertices = { {PLAYER_BOX_SIZE, 0.0f, 0.0f}, {PLAYER_BOX_SIZE, 0.0f, 0.0f}, // 0, 1 {0.0f, PLAYER_BOX_SIZE, 0.0f}, {PLAYER_BOX_SIZE, PLAYER_BOX_SIZE, 0.0f}, // 2, 3 {0.0f, 0.0f, PLAYER_BOX_SIZE}, {PLAYER_BOX_SIZE, 0.0f, PLAYER_BOX_SIZE}, // 4, 5 {0.0f, PLAYER_BOX_SIZE, PLAYER_BOX_SIZE}, {PLAYER_BOX_SIZE, PLAYER_BOX_SIZE, PLAYER_BOX_SIZE} // 6, 7 }; glman_aabb.Init(glman_vertices); // setup visible bounding box for glman if in debug mode if (__DEBUG__) { glman_bounding_box_renderable.getObject()->DefineVertices(&glman_aabb); glman_bounding_box_renderable.Init(default_shader); origin.Init(default_shader); } ////////////////////////////////////////////////////// ///// End setup for glman ///// ////////////////////////////////////////////////////// //////////////////////////////////////////////////////// //// Init tiles & energizers //// //////////////////////////////////////////////////////// // first loads the .obj so we dont have to for any other EnergizerModel first = EnergizerModel(glm::vec3(0.0f), energizer_shader); tiles = std::make_unique<Tiles>(Tiles(ONE_UNIT)); for (auto i = 0; i < tiles->tiles.size(); ++i) { for (auto j = 0; j < tiles->tiles[i].size(); ++j) { Tile *tile = tiles->tiles[i][j].get(); if (tile != nullptr) tile->energizer = std::make_shared<EnergizerModel>(EnergizerModel(first, tile->center, energizer_shader)); } } //////////////////////////////////////////////////////// //// End Init tiles/energizers //// //////////////////////////////////////////////////////// //////////////////////////////////////////////////////// //// Init environment //// //////////////////////////////////////////////////////// //if (stage.Init(default_shader) == false) // cout << "ERROR: Count not Init stage" << endl; if (level == game::DAYTIME) { std::string filenames[6] = { "/Daylight_Box_Back.bmp", "/Daylight_Box_Front.bmp", "/Daylight_Box_Top.bmp", "/Daylight_Box_Bottom.bmp", "/Daylight_Box_Left.bmp", "/Daylight_Box_Right.bmp" }; skybox.getObject()->Init(skybox_shader, filenames); } else if (level == game::CITY) { std::string filenames[6] = { "/city_negz.bmp", "/city_posz.bmp", "/city_posy.bmp", "/city_negy.bmp", "/city_negx.bmp", "/city_posx.bmp" }; skybox.getObject()->Init(skybox_shader, filenames); } if (skybox.Init(skybox_shader) == false) cout << "ERROR: Count not Init skybox" << endl; // Set up the uniform buffer objects that hold data that all of the shaders share. In this // application we have two uniform buffer objects: one for the lights and one for the matrices. // The lights don't change as the program runs so we can set them here as well. SetUpLights(); glGenBuffers(1, &transform_id); glBindBuffer(GL_UNIFORM_BUFFER, transform_id); //////////////////////////////////////////////////////// //// End Init environment //// //////////////////////////////////////////////////////// //Since the projection matrix will not change during the program we can calculate it here //transform.projection_matrix = frustum(-0.2f, 0.2f, -0.1f, 0.1f, 0.1f, 100.0f); transform.projection_matrix = perspectiveFov(radians(90.0f), static_cast<float>(WINDOWWIDTH), static_cast<float>(WINDOWHEIGHT), 0.1f, 500.0f); initialized = true; return true; } /** * \brief Updates the game world and things in the game world which should change independents * of input from the human playing the game. * * \returns True if game should continue. */ bool ViewModel::OnTick() { // redghost.OnTick(); // purpleghost.OnTick(); // blueghost.OnTick(); // orangeghost.OnTick(); // collision check with the energizers // TODO: this nullcount thing is so hacky lol auto nullcount = 0, loopcount= 0; for (auto i = 0; i < tiles->tiles.size(); ++i) { for (auto j = 0; j < tiles->tiles[i].size(); ++j) { loopcount++; auto tile = tiles->tiles[i][j].get(); if (tile == nullptr || tile->energizer == nullptr) { nullcount++; continue; } tile->energizer->OnTick(); if (glman_aabb.AABBtoAABB(*tile->energizer->GetAABB().get())) { tile->energizer->OnCollide(); tile->energizer = nullptr; score_manager->IncrementScore(); } } } if (nullcount == loopcount) return false; // all energizers collected, so quit // collision.Check(glman, redghost); // collision.Check(glman, purpleghost); // collision.Check(glman, blueghost); // collision.Check(glman, orangeghost); return true; } void ViewModel::DoMovement(vec3 displacement) { this->displacement += displacement; // move player glman_aabb.Move(displacement); } void ViewModel::Draw() { if (initialized == false) { cout << "ERROR: Cannot render a ViewModel object before it has been initialized." << endl; return; } glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // draw skybox first! skybox.Draw(); // draw energizers for (auto i = 0; i < tiles->tiles.size(); ++i) { for (auto j = 0; j < tiles->tiles[i].size(); ++j) { Tile *tile = tiles->tiles[i][j].get(); if (tile != nullptr && tile->energizer != nullptr) tile->energizer->OnDraw(); } } // Show bounding box for player if debugging, and show axes/origin. if (__DEBUG__) { //origin.Draw(vec4(1.0f, 1.0f, 0.0f, 1.0f)); //transform.model_matrix = translate(mat4(1.0), displacement); //UpdateTransform(); //glman_bounding_box_renderable.Draw(); } glFlush(); } void ViewModel::UpdateTransform() { //Pass the matrix info to the shaders in a Uniform Buffer Object. //This allows ALL shaders to be able to access the matrix information. glBufferData(GL_UNIFORM_BUFFER, sizeof(transform), &transform, GL_DYNAMIC_DRAW);//use GL_DYNAMIC_DRAW since it changes a lot glBindBufferBase(GL_UNIFORM_BUFFER, transform_binding, transform_id); //The 35 needs to match the number used in the shaders for the matrices }
34.871866
143
0.667785
cojomojo
b2b0be6ccdbedf093d981a1f85b4465554d0a2fa
3,156
hpp
C++
include/Renderer.hpp
SudoCpp/simplexsdl
23b44f5a29f5f24f6bb323062130e3b01ecb33eb
[ "Zlib" ]
null
null
null
include/Renderer.hpp
SudoCpp/simplexsdl
23b44f5a29f5f24f6bb323062130e3b01ecb33eb
[ "Zlib" ]
null
null
null
include/Renderer.hpp
SudoCpp/simplexsdl
23b44f5a29f5f24f6bb323062130e3b01ecb33eb
[ "Zlib" ]
null
null
null
/* BSD 3-Clause License Copyright (c) 2022, SudoCpp All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef SIMPLEX_SDL_RENDERER_HPP #define SIMPLEX_SDL_RENDERER_HPP #include "CMYColor.hpp" #include "RGBColor.hpp" #include "Rectangle.hpp" #include "Texture.hpp" #include "Surface.hpp" #include "Font.hpp" class SDL_Renderer; namespace simplex::sdl { class Renderer { SDL_Renderer* renderer; public: Renderer(SDL_Renderer* renderer); ~Renderer(); Renderer& setColor(RGBColor color); Renderer& clear(); Renderer& present(); Renderer& drawLine(int point1x, int point1y, int point2x, int point2y); Renderer& fillRect(const Rectangle& rectangle); Renderer& fillRect(int xPoint, int yPoint, int width, int height); Renderer& fillRect(); Renderer& drawRect(const Rectangle& rectangle); Renderer& drawRect(int xPoint, int yPoint, int width, int height); Renderer& drawPoint(int xPoint, int yPoint); Renderer& setTarget(Texture& texture); Renderer& setTarget(); Renderer& copyTexture(Texture& texture); //Will not stretch Renderer& copyTexture(Texture& texture, int destinationXPosition, int destinationYPosition); Renderer& copyTexture(Texture& texture, const Rectangle& sourceRectangle, const Rectangle& destinationRectangle); Renderer& drawText(RGBColor& color, Font& font, int x, int y, simplex::string text); Texture* createTexture(int width, int height); Texture* createTextureFromSurface(Surface& surface); }; } #endif //SIMPLEX_SDL_RENDERER_HPP
40.987013
121
0.724335
SudoCpp
b2b18c0c8bc6a164f31a2ca108e20f460a08044b
4,770
cpp
C++
depends/work/build/i686-w64-mingw32/qt/5.9.7-f2560c1efa6/qtbase/src/gui/util/qlayoutpolicy.cpp
GrinCash/Grinc-core
1377979453ba84082f70f9c128be38e57b65a909
[ "MIT" ]
null
null
null
depends/work/build/i686-w64-mingw32/qt/5.9.7-f2560c1efa6/qtbase/src/gui/util/qlayoutpolicy.cpp
GrinCash/Grinc-core
1377979453ba84082f70f9c128be38e57b65a909
[ "MIT" ]
null
null
null
depends/work/build/i686-w64-mingw32/qt/5.9.7-f2560c1efa6/qtbase/src/gui/util/qlayoutpolicy.cpp
GrinCash/Grinc-core
1377979453ba84082f70f9c128be38e57b65a909
[ "MIT" ]
null
null
null
/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the Qt Quick Layouts module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 3 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL3 included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 3 requirements ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 2.0 or (at your option) the GNU General ** Public license version 3 or any later version approved by the KDE Free ** Qt Foundation. The licenses are as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-2.0.html and ** https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qlayoutpolicy_p.h" #include <QtCore/qdebug.h> #include <QtCore/qdatastream.h> QT_BEGIN_NAMESPACE void QLayoutPolicy::setControlType(ControlType type) { /* The control type is a flag type, with values 0x1, 0x2, 0x4, 0x8, 0x10, etc. In memory, we pack it onto the available bits (CTSize) in setControlType(), and unpack it here. Example: 0x00000001 maps to 0 0x00000002 maps to 1 0x00000004 maps to 2 0x00000008 maps to 3 etc. */ int i = 0; while (true) { if (type & (0x1 << i)) { bits.ctype = i; return; } ++i; } } QLayoutPolicy::ControlType QLayoutPolicy::controlType() const { return QLayoutPolicy::ControlType(1 << bits.ctype); } #ifndef QT_NO_DATASTREAM /*! \relates QLayoutPolicy Writes the size \a policy to the data stream \a stream. \sa{Serializing Qt Data Types}{Format of the QDataStream operators} */ QDataStream &operator<<(QDataStream &stream, const QLayoutPolicy &policy) { // The order here is for historical reasons. (compatibility with Qt4) quint32 data = (policy.bits.horPolicy | // [0, 3] policy.bits.verPolicy << 4 | // [4, 7] policy.bits.hfw << 8 | // [8] policy.bits.ctype << 9 | // [9, 13] policy.bits.wfh << 14 | // [14] //policy.bits.padding << 15 | // [15] policy.bits.verStretch << 16 | // [16, 23] policy.bits.horStretch << 24); // [24, 31] return stream << data; } #define VALUE_OF_BITS(data, bitstart, bitcount) ((data >> bitstart) & ((1 << bitcount) -1)) /*! \relates QLayoutPolicy Reads the size \a policy from the data stream \a stream. \sa{Serializing Qt Data Types}{Format of the QDataStream operators} */ QDataStream &operator>>(QDataStream &stream, QLayoutPolicy &policy) { quint32 data; stream >> data; policy.bits.horPolicy = VALUE_OF_BITS(data, 0, 4); policy.bits.verPolicy = VALUE_OF_BITS(data, 4, 4); policy.bits.hfw = VALUE_OF_BITS(data, 8, 1); policy.bits.ctype = VALUE_OF_BITS(data, 9, 5); policy.bits.wfh = VALUE_OF_BITS(data, 14, 1); policy.bits.padding = 0; policy.bits.verStretch = VALUE_OF_BITS(data, 16, 8); policy.bits.horStretch = VALUE_OF_BITS(data, 24, 8); return stream; } #endif // QT_NO_DATASTREAM #ifndef QT_NO_DEBUG_STREAM QDebug operator<<(QDebug dbg, const QLayoutPolicy &p) { QDebugStateSaver saver(dbg); dbg.nospace() << "QLayoutPolicy(horizontalPolicy = " << p.horizontalPolicy() << ", verticalPolicy = " << p.verticalPolicy() << ')'; return dbg; } #endif QT_END_NAMESPACE
35.073529
91
0.636059
GrinCash
b2b55d53b0c20e812861431c6a02f15046ba3d6b
13,690
cpp
C++
Motor2D/j1EntityElementsScene.cpp
NontendoSL/Zelda-a-Link-to-the-Past-TRIBUTE
8676c7fc70b6dea54cd173b42c5006f34ab82404
[ "Apache-2.0" ]
11
2017-02-16T18:30:43.000Z
2021-08-07T11:40:49.000Z
Motor2D/j1EntityElementsScene.cpp
NontendoSL/Zelda-a-Link-to-the-Past-TRIBUTE
8676c7fc70b6dea54cd173b42c5006f34ab82404
[ "Apache-2.0" ]
81
2017-02-16T18:27:02.000Z
2017-06-07T20:23:40.000Z
Motor2D/j1EntityElementsScene.cpp
NontendoSL/Zelda-a-Link-to-the-Past-TRIBUTE
8676c7fc70b6dea54cd173b42c5006f34ab82404
[ "Apache-2.0" ]
5
2017-03-01T14:49:24.000Z
2021-08-07T11:40:51.000Z
#include "j1EntityElementsScene.h" #include "Soldier.h" #include "j1Item.h" #include "j1Player.h" #include "j1DynamicObjects.h" #include "j1Scene.h" #include "j1App.h" #include "j1Input.h" #include "p2Log.h" #include "Geodude.h" #include "Sudowoodo.h" #include "Golem.h" #include "PokeTrainer.h" #include "j1Textures.h" #include "j1Audio.h" #include "j1Collision.h" #include "j1Render.h" #include "j1Window.h" #include "j1FileSystem.h" #include "BCTrooper.h" #include "j1Weapon.h" #include "Villager.h" #include "Ganon.h" #include "GreenMinion.h" #include "RedMinion.h" #include "FireBat.h" j1EntityElementScene::j1EntityElementScene() { name = "entityelement"; } j1EntityElementScene::~j1EntityElementScene() { } bool j1EntityElementScene::Awake(pugi::xml_node &config) { /*std::list<SceneElement*>::iterator item = elementscene.begin(); while (item != elementscene.end()) { item++; }*/ file_tex_dynobjects = config.child("textDynObjects").attribute("file").as_string(""); file_tex_trainer = config.child("textBrendan").attribute("file").as_string(""); return true; } bool j1EntityElementScene::Start() { bool ret = true; std::list<SceneElement*>::iterator item = elementscene.begin(); while (item != elementscene.end()) { //item._Ptr->_Myval->Start(); item++; } texture_dynobjects = App->tex->Load(file_tex_dynobjects.c_str()); texture_trainer = App->tex->Load(file_tex_trainer.c_str()); text_vase_bush = App->tex->Load("textures/AnimationsAndEffects.png"); hookshot_chain = App->tex->Load("Particles/bctrooperl.png"); char* buf; int size = App->fs->Load("config.xml", &buf); XML.load_buffer(buf, size); return ret; } bool j1EntityElementScene::PreUpdate() { BROFILER_CATEGORY("DoPreUpdate_EntityElementsScene", Profiler::Color::Silver); if (App->scene->combat == false && App->scene->waitVideo == false) { std::list<SceneElement*>::iterator item = elementscene.begin(); while (item != elementscene.end()) { //Comprovate if elements is not to_delete == true if (item._Ptr->_Myval->to_delete) { if (bct != nullptr) { if (((BCTrooper*)item._Ptr->_Myval)->GetState() == BC_DYING) { //TODO -> if animation finished, then delete. App->entity_elements->DeleteBCTrooper((BCTrooper*)item._Ptr->_Myval); // Delete Dynobject App->audio->PlayFx(17); item++; continue; } } if (item._Ptr->_Myval->type == DYNOBJECT) { DeleteDynObject((DynamicObjects*)item._Ptr->_Myval); } if (item._Ptr->_Myval->type == CREATURE) { DeleteCreature((Creature*)item._Ptr->_Myval); } } item++; } } return true; } bool j1EntityElementScene::Update(float dt) { bool ret = true; BROFILER_CATEGORY("DoUpdate_EntityElementsScene", Profiler::Color::MediumOrchid); if (App->scene->combat == false && App->scene->waitVideo == false) { std::list<SceneElement*>::iterator item = elementscene.begin(); while (item != elementscene.end()) { item._Ptr->_Myval->Update(dt); item++; } } return ret; } bool j1EntityElementScene::PostUpdate() { BROFILER_CATEGORY("Draw_Elements", Profiler::Color::Green) if (App->scene->combat == false && App->scene->waitVideo == false) { std::list<SceneElement*>::iterator item = elementscene.end(); item--; while (item != elementscene.begin()) { item._Ptr->_Myval->Draw(); item--; } if (elementscene.size() > 0) { item._Ptr->_Myval->Draw(); } } //Draw Floor 2----------------------- App->map->Draw(true); return true; } bool j1EntityElementScene::CleanUp() { bool ret = true; std::list<SceneElement*>::iterator item = elementscene.begin(); while (item != elementscene.end()) { item._Ptr->_Myval->CleanUp(); elementscene.remove(item._Ptr->_Myval); delete item._Ptr->_Myval; item++; } texture_dynobjects = nullptr; texture_trainer = nullptr; text_vase_bush = nullptr; hookshot_chain = nullptr; return ret; } bool j1EntityElementScene::DelteWeapons() { std::list<SceneElement*>::iterator item = elementscene.end(); item--; { while (item != elementscene.begin()) { if (item._Ptr->_Myval->type == WEAPON) { delete item._Ptr->_Myval; elementscene.erase(item); } item--; } } return true; } bool j1EntityElementScene::DelteElements() { App->collision->waittodelete = true; std::list<SceneElement*>::iterator item = elementscene.end(); item--; if (elementscene.begin()._Ptr->_Myval->name != "Link") { std::list<SceneElement*>::iterator temp = elementscene.begin(); while (temp != elementscene.end()) { if (temp._Ptr->_Myval->name == "Link") { std::swap(temp._Ptr->_Myval, elementscene.begin()._Ptr->_Myval); } temp++; } } if (elementscene.size() > 1) { while (item != elementscene.begin()) { if (item._Ptr->_Myval->type != WEAPON) { elementscene.remove(item._Ptr->_Myval); delete item._Ptr->_Myval; } item--; } } return true; } void j1EntityElementScene::CreateSoldier(uint id, pugi::xml_node& config) { Soldier* element = new Soldier(); element->Awake(config, id); if (element->Start()) { LOG("Soldier Created"); } elementscene.push_back(element); } bool j1EntityElementScene::DeleteEnemy(Soldier* enemy) { if (enemy != nullptr) { elementscene.remove(enemy); enemy->collision_feet->to_delete = true; enemy->collision_feet = nullptr; delete enemy; enemy = nullptr; } return true; } bool j1EntityElementScene::DeleteDynObject(DynamicObjects* dynobject) { elementscene.remove(dynobject); if (dynobject->collision != nullptr) { dynobject->collision->to_delete = true; } dynobject->collision = nullptr; delete dynobject; dynobject = nullptr; return true; } bool j1EntityElementScene::DeleteItem(Item* item) { elementscene.remove(item); item->collision->to_delete = true; item->collision = nullptr; delete item; item = nullptr; return true; } bool j1EntityElementScene::DeletePokemon(Pokemon* pokemon) { if (pokemon != nullptr) { elementscene.remove(pokemon); pokemon->collision_feet->to_delete = true; pokemon->collision_feet = nullptr; delete pokemon; pokemon = nullptr; } return false; } bool j1EntityElementScene::DeleteBCTrooper(BCTrooper* bctrooper) { if (bctrooper != nullptr) { elementscene.remove(bctrooper); bctrooper->collision_feet->to_delete = true; for (uint i = 0; i < bctrooper->GetMazeSize(); i++) { if (bctrooper->GetColliderMaze(i) != nullptr) { bctrooper->GetColliderMaze(i)->to_delete = true; } } bct = nullptr; delete bctrooper; bctrooper = nullptr; } return true; } bool j1EntityElementScene::DeleteElement(std::string name) { std::list<SceneElement*>::iterator item = elementscene.begin(); while (item != elementscene.end()) { if (item._Ptr->_Myval->name == name) { if (item._Ptr->_Myval->type == DYNOBJECT) { DeleteDynObject((DynamicObjects*)item._Ptr->_Myval); } } item++; } return true; } bool j1EntityElementScene::DeletePlayer(Player* player) { if (player != nullptr) { elementscene.remove(player); //delete App->scene->player; App->scene->player = nullptr; player->collision_feet->to_delete = true; //player = nullptr; //delete player; return true; } return false; } bool j1EntityElementScene::DeleteVilager(Villager* vilager) { if (vilager != nullptr) { elementscene.remove(vilager); vilager->collision_feet->to_delete = true; vilager->collision_feet = nullptr; delete vilager; vilager = nullptr; return true; } return false; } bool j1EntityElementScene::DeleteCreature(Creature* creature) { if (creature != nullptr) { elementscene.remove(creature); if (creature->collision_feet != nullptr) { creature->collision_feet->to_delete = true; creature->collision_feet = nullptr; } delete creature; creature = nullptr; } return true; } void j1EntityElementScene::SwapObject(SceneElement* obj) { if (obj != nullptr) { if (obj != elementscene.begin()._Ptr->_Myval) { std::list<SceneElement*>::iterator temp = elementscene.begin(); for (;temp != elementscene.end();temp++) { if (temp._Ptr->_Myval == obj) { std::swap(temp._Ptr->_Myval, elementscene.begin()._Ptr->_Myval); break; } } if (elementscene.begin()._Ptr->_Myval != App->scene->player) { for (temp = elementscene.begin(); temp != elementscene.end(); temp++) { if (temp._Ptr->_Myval == App->scene->player) { std::swap(temp._Ptr->_Myval, elementscene.begin()._Ptr->_Next->_Myval); break; } } } } } } void j1EntityElementScene::SwapGanon() { if (App->scene->player != nullptr && App->entity_elements->ganon != nullptr) { if (App->entity_elements->ganon != elementscene.begin()._Ptr->_Myval) { std::list<SceneElement*>::iterator temp = elementscene.begin(); for (; temp != elementscene.end(); temp++) { if (temp._Ptr->_Myval == App->entity_elements->ganon) { std::swap(temp._Ptr->_Myval, elementscene.begin()._Ptr->_Myval); break; } } } } } void j1EntityElementScene::SwapPlayer() { if (App->scene->player != nullptr && App->entity_elements->ganon != nullptr) { if (App->scene->player != elementscene.begin()._Ptr->_Myval) { std::list<SceneElement*>::iterator temp = elementscene.begin(); for (; temp != elementscene.end(); temp++) { if (temp._Ptr->_Myval == App->scene->player) { std::swap(temp._Ptr->_Myval, elementscene.begin()._Ptr->_Myval); break; } } } } } void j1EntityElementScene::CreateItem(uint id, iPoint position) { if (id != 0) { Item* element = new Item(); pugi::xml_document config_file; pugi::xml_node config; config = LoadConfig(config_file); element->Awake(config.child(element->name.c_str()), id, position); element->Start(); elementscene.push_front(element); } } Hookshot* j1EntityElementScene::CreateHookshot() { Hookshot* hook = new Hookshot(true); hook->name = "hookshot"; hook->Start(); elementscene.push_back(hook); return hook; } Bow* j1EntityElementScene::CreateBow() { Bow* bow = new Bow(true); bow->name = "bow"; bow->Start(); elementscene.push_back(bow); return bow; } void j1EntityElementScene::DeleteArrows() { std::list<SceneElement*>::iterator temp = elementscene.begin(); while (temp != elementscene.end()) { if (temp._Ptr->_Myval->name == "bow") { Bow* bow = (Bow*)temp._Ptr->_Myval; bow->DestroyArrows(); break; } temp++; } } BombContainer* j1EntityElementScene::CreateBombContainer() { BombContainer* element = new BombContainer(); element->name = "bomb"; elementscene.push_back(element); return element; } void j1EntityElementScene::CreatePokemon(pugi::xml_node& conf, uint id, iPoint pos) { if (id == 1) { Golem* temp = new Golem(); temp->Awake(conf, id); temp->Start(); elementscene.push_back(temp); } else if (id == 2) { Geodude* temp = new Geodude(); temp->Awake(conf, id, pos); temp->Start(); elementscene.push_back(temp); } else if (id == 3) { Sudowoodo* temp = new Sudowoodo(); temp->Awake(conf, id); temp->Start(); elementscene.push_back(temp); } } void j1EntityElementScene::CreateBCTrooper(pugi::xml_node& conf) { BCTrooper* temp = new BCTrooper(); temp->Awake(conf, 1); temp->Start(); elementscene.push_back(temp); bct = (BCTrooper*)elementscene.back(); } void j1EntityElementScene::CreateGanon(pugi::xml_node& conf) { Ganon* temp = new Ganon(); temp->Awake(conf, 1); temp->Start(); elementscene.push_back(temp); ganon = (Ganon*)elementscene.back(); } void j1EntityElementScene::CreateVillager(pugi::xml_node& conf) { Villager* temp = new Villager(); temp->Awake(conf); temp->Start(); elementscene.push_back(temp); } void j1EntityElementScene::CreateGMinion(iPoint pos) { GreenMinion* temp = new GreenMinion(); temp->Start(pos); elementscene.push_back(temp); } void j1EntityElementScene::CreateRMinion(iPoint pos) { RedMinion* temp = new RedMinion(); temp->Start(pos); elementscene.push_back(temp); } void j1EntityElementScene::CreateFireBat() { FireBat* temp = new FireBat(); temp->Start(); elementscene.push_back(temp); } void j1EntityElementScene::CreateDynObject(iPoint pos, uint id, uint id_map, bool isSign, pugi::xml_node& special_config) { DynamicObjects* element = new DynamicObjects(); if (isSign) { element->Awake(special_config, id, pos, isSign); element->Start(); elementscene.push_back(element); } else { pugi::xml_document config_file; pugi::xml_node config; config = LoadConfig(config_file); bool stop_rearch = false; LOG("Create DynObjects"); config = config.child("maps").child("map"); for (; stop_rearch == false; config = config.next_sibling()) { if (config.attribute("n").as_int(0) == id_map) { element->Awake(config, id, pos); element->Start(); elementscene.push_back(element); LOG("Created!!"); stop_rearch = true; } } } } Player* j1EntityElementScene::CreatePlayer() { Player* element = new Player(); pugi::xml_document config_file; pugi::xml_node config; config = LoadConfig(config_file); element->Awake(config.child(element->name.c_str())); elementscene.push_back(element); element->Start(); return element; } // --------------------------------------------- pugi::xml_node j1EntityElementScene::LoadConfig(pugi::xml_document& config_file) const { pugi::xml_node ret; char* buf; int size = App->fs->Load("Levels.xml", &buf); pugi::xml_parse_result result = config_file.load_buffer(buf, size); RELEASE(buf); if (result == NULL) LOG("Could not load map xml file config.xml. pugi error: %s", result.description()); else ret = config_file.child("levels"); return ret; }
21.974318
121
0.673703
NontendoSL
b2be7f66ea73bb466fe20289daa828ac0bebd4d6
11,923
cpp
C++
pla/tests/scaling.cpp
JBPennington/PLA
60ff7952a8549e5272fb3c2aa9a469553a026727
[ "MIT" ]
4
2018-02-04T22:16:05.000Z
2021-02-18T23:51:20.000Z
pla/tests/scaling.cpp
JBPennington/PLA
60ff7952a8549e5272fb3c2aa9a469553a026727
[ "MIT" ]
null
null
null
pla/tests/scaling.cpp
JBPennington/PLA
60ff7952a8549e5272fb3c2aa9a469553a026727
[ "MIT" ]
null
null
null
extern "C" { #include "../pla.h" } #include <gtest/gtest.h> #include <iostream> class Linear_Algebra_Scale_ : public testing::Test { void SetUp() {} void TearDown() {} public: const float tolerance = 0.00000001f; mat2x2 Mat2_zero {{0,0},{0,0}}; mat3x3 Mat3_zero {{0,0,0},{0,0,0},{0,0,0}}; mat4x4 Mat4_zero {{0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0}}; mat5x5 Mat5_zero {{0,0,0,0,0},{0,0,0,0,0},{0,0,0,0,0},{0,0,0,0,0},{0,0,0,0,0}}; mat6x6 Mat6_zero {{0,0,0,0,0,0},{0,0,0,0,0,0},{0,0,0,0,0,0},{0,0,0,0,0,0},{0,0,0,0,0,0},{0,0,0,0,0,0}}; mat2x2 Mat2A {{0,1},{2,3}}; mat3x3 Mat3A {{0,1,2},{3,4,5},{6,7,8}}; mat4x4 Mat4A {{0,1,2,3},{4,5,6,7},{8,9,10,11},{12,13,14,15}}; mat5x5 Mat5A {{0,1,2,3,4},{5,6,7,8,9},{10,11,12,13,14},{15,16,17,18,19},{20,21,22,23,24}}; mat6x6 Mat6A {{0,1,2,3,4,5},{6,7,8,9,10,11},{12,13,14,15,16,17},{18,19,20,21,22,23},{24,25,26,27,28,29},{30,31,32,33,34,35}}; mat2x2 Mat2B {{0,1},{2,3}}; mat3x3 Mat3B {{0,1,2},{3,4,5},{6,7,8}}; mat4x4 Mat4B {{0,1,2,3},{4,5,6,7},{8,9,10,11},{12,13,14,15}}; mat5x5 Mat5B {{0,1,2,3,4},{5,6,7,8,9},{10,11,12,13,14},{15,16,17,18,19},{20,21,22,23,24}}; mat6x6 Mat6B {{0,1,2,3,4,5},{6,7,8,9,10,11},{12,13,14,15,16,17},{18,19,20,21,22,23},{24,25,26,27,28,29},{30,31,32,33,34,35}}; }; TEST_F(Linear_Algebra_Scale_, Scale_Two_Vec2_Test) { vec2 a = {0, 1}; float b = 7; vec2 result = {0, 0}; vec2_scale_n(result, a, b); vec2 expect = {0, 7}; uint32_t iter; for (iter=0; iter<2; ++iter) { EXPECT_EQ(expect[iter], result[iter]); } } TEST_F(Linear_Algebra_Scale_, Scale_Two_Vec3_Test) { vec3 a = {0, 1, 2}; float b = 7; vec3 result = {0, 0, 0}; vec3_scale_n(result, a, b); vec3 expect = {0, 7, 14}; uint32_t iter; for (iter=0; iter<3; ++iter) { EXPECT_EQ(expect[iter], result[iter]); } } TEST_F(Linear_Algebra_Scale_, Scale_Two_Vec4_Test) { vec4 a = {0, 1, 2, 3}; float b = 7; vec4 result = {0, 0, 0, 0}; vec4_scale_n(result, a, b); vec4 expect = {0, 7, 14, 21}; uint32_t iter; for (iter=0; iter<4; ++iter) { EXPECT_EQ(expect[iter], result[iter]); } } TEST_F(Linear_Algebra_Scale_, Scale_Two_Vec5_Test) { vec5 a = {0, 1, 2, 3, 4}; float b = 7; vec5 result = {0, 0, 0, 0, 0}; vec5_scale_n(result, a, b); vec5 expect = {0, 7, 14, 21, 28}; uint32_t iter; for (iter=0; iter<5; ++iter) { EXPECT_EQ(expect[iter], result[iter]); } } TEST_F(Linear_Algebra_Scale_, Scale_Two_Vec6_Test) { vec6 a = {0, 1, 2, 3, 4, 5}; float b = 7; vec6 result = {0, 0, 0, 0, 0, 0}; vec6_scale_n(result, a, b); vec6 expect = {0, 7, 14, 21, 28, 35}; uint32_t iter; for (iter=0; iter<6; ++iter) { EXPECT_EQ(expect[iter], result[iter]); } } TEST_F(Linear_Algebra_Scale_, Scale_Two_Vec2_In_Place_Test) { vec2 a = {0, 1}; float b = 7; vec2_scale(a, b); vec2 expect = {0, 7}; uint32_t iter; for (iter=0; iter<2; ++iter) { EXPECT_EQ(expect[iter], a[iter]); } } TEST_F(Linear_Algebra_Scale_, Scale_Two_Vec3_In_Place_Test) { vec3 a = {0, 1, 2}; float b = 7; vec3_scale(a, b); vec3 expect = {0, 7, 14}; uint32_t iter; for (iter=0; iter<3; ++iter) { EXPECT_EQ(expect[iter], a[iter]); } } TEST_F(Linear_Algebra_Scale_, Scale_Two_Vec4_In_Place_Test) { vec4 a = {0, 1, 2, 3}; float b = 7; vec4_scale(a, b); vec4 expect = {0, 7, 14, 21}; uint32_t iter; for (iter=0; iter<4; ++iter) { EXPECT_EQ(expect[iter], a[iter]); } } TEST_F(Linear_Algebra_Scale_, Scale_Two_Vec5_In_Place_Test) { vec5 a = {0, 1, 2, 3, 4}; float b = 7; vec5_scale(a, b); vec5 expect = {0, 7, 14, 21, 28}; uint32_t iter; for (iter=0; iter<5; ++iter) { EXPECT_EQ(expect[iter], a[iter]); } } TEST_F(Linear_Algebra_Scale_, Scale_Two_Vec6_In_Place_Test) { vec6 a = {0, 1, 2, 3, 4, 5}; float b = 7; vec6_scale(a, b); vec6 expect = {0, 7, 14, 21, 28, 35}; uint32_t iter; for (iter=0; iter<6; ++iter) { EXPECT_EQ(expect[iter], a[iter]); } } TEST_F(Linear_Algebra_Scale_, Scale_Return_Two_Vec2_Test) { vec2 a = {0, 1}; float b = 7; float * result = vec2_scale_r(a, b); vec2 expect = {0, 7}; uint32_t iter; for (iter=0; iter<2; ++iter) { EXPECT_EQ(expect[iter], result[iter]); } } TEST_F(Linear_Algebra_Scale_, Scale_Return_Two_Vec3_Test) { vec3 a = {0, 1, 2}; float b = 7; float * result = vec3_scale_r(a, b); vec3 expect = {0, 7, 14}; uint32_t iter; for (iter=0; iter<3; ++iter) { EXPECT_EQ(expect[iter], result[iter]); } } TEST_F(Linear_Algebra_Scale_, Scale_Return_Two_Vec4_Test) { vec4 a = {0, 1, 2, 3}; float b = 7; float * result = vec4_scale_r(a, b); vec4 expect = {0, 7, 14, 21}; uint32_t iter; for (iter=0; iter<4; ++iter) { EXPECT_EQ(expect[iter], result[iter]); } } TEST_F(Linear_Algebra_Scale_, Scale_Return_Two_Vec5_Test) { vec5 a = {0, 1, 2, 3, 4}; float b = 7; float * result = vec5_scale_r(a, b); vec5 expect = {0, 7, 14, 21, 28}; uint32_t iter; for (iter=0; iter<5; ++iter) { EXPECT_EQ(expect[iter], result[iter]); } } TEST_F(Linear_Algebra_Scale_, Scale_Return_Two_Vec6_Test) { vec6 a = {0, 1, 2, 3, 4, 5}; float b = 7; float * result = vec6_scale_r(a, b); vec6 expect = {0, 7, 14, 21, 28, 35}; uint32_t iter; for (iter=0; iter<6; ++iter) { EXPECT_EQ(expect[iter], result[iter]); } } TEST_F(Linear_Algebra_Scale_, Two_Through_Six_Square_Mat_Scale_to_New_Mat_Test) { mat2x2 Mat2_expected {{0,.5},{1,1.5}}; mat3x3 Mat3_expected {{0,.5,1},{1.5,2,2.5},{3,3.5,4}}; mat4x4 Mat4_expected {{0,.5,1,1.5},{2,2.5,3,3.5},{4,4.5,5,5.5},{6,6.5,7,7.5}}; mat5x5 Mat5_expected {{0,.5,1,1.5,2},{2.5,3,3.5,4,4.5},{5,5.5,6,6.5,7},{7.5,8,8.5,9,9.5},{10,10.5,11,11.5,12}}; mat6x6 Mat6_expected {{0,.5,1,1.5,2,2.5},{3,3.5,4,4.5,5,5.5},{6,6.5,7,7.5,8,8.5},{9,9.5,10,10.5,11,11.5},{12,12.5,13,13.5,14,14.5},{15,15.5,16,16.5,17,17.5}}; mat2x2 Mat2_result; mat2x2_copy(Mat2_result, Mat2_zero); mat3x3 Mat3_result; mat3x3_copy(Mat3_result, Mat3_zero); mat4x4 Mat4_result; mat4x4_copy(Mat4_result, Mat4_zero); mat5x5 Mat5_result; mat5x5_copy(Mat5_result, Mat5_zero); mat6x6 Mat6_result; mat6x6_copy(Mat6_result, Mat6_zero); for (std::size_t size = 2; size<7; ++size) { if (size == 2) mat2x2_scale_n(Mat2_result, Mat2A, 0.5f); if (size == 3) mat3x3_scale_n(Mat3_result, Mat3A, 0.5f); if (size == 4) mat4x4_scale_n(Mat4_result, Mat4A, 0.5f); if (size == 5) mat5x5_scale_n(Mat5_result, Mat5A, 0.5f); if (size == 6) mat6x6_scale_n(Mat6_result, Mat6A, 0.5f); for (std::size_t row = 0; row < size; ++row) { for (std::size_t col = 0; col < size; ++col) { if (size == 2) EXPECT_NEAR(Mat2_expected[row][col], Mat2_result[row][col], tolerance) << "Matrix: " << size << " Row: " << row << " Col: " << col; if (size == 3) EXPECT_NEAR(Mat3_expected[row][col], Mat3_result[row][col], tolerance) << "Matrix: " << size << " Row: " << row << " Col: " << col; if (size == 4) EXPECT_NEAR(Mat4_expected[row][col], Mat4_result[row][col], tolerance) << "Matrix: " << size << " Row: " << row << " Col: " << col; if (size == 5) EXPECT_NEAR(Mat5_expected[row][col], Mat5_result[row][col], tolerance) << "Matrix: " << size << " Row: " << row << " Col: " << col; if (size == 6) EXPECT_NEAR(Mat6_expected[row][col], Mat6_result[row][col], tolerance) << "Matrix: " << size << " Row: " << row << " Col: " << col; } } } } TEST_F(Linear_Algebra_Scale_, Two_Through_Six_Square_Mat_Scale_In_Place_Test) { mat2x2 Mat2_expected {{0,.5},{1,1.5}}; mat3x3 Mat3_expected {{0,.5,1},{1.5,2,2.5},{3,3.5,4}}; mat4x4 Mat4_expected {{0,.5,1,1.5},{2,2.5,3,3.5},{4,4.5,5,5.5},{6,6.5,7,7.5}}; mat5x5 Mat5_expected {{0,.5,1,1.5,2},{2.5,3,3.5,4,4.5},{5,5.5,6,6.5,7},{7.5,8,8.5,9,9.5},{10,10.5,11,11.5,12}}; mat6x6 Mat6_expected {{0,.5,1,1.5,2,2.5},{3,3.5,4,4.5,5,5.5},{6,6.5,7,7.5,8,8.5},{9,9.5,10,10.5,11,11.5},{12,12.5,13,13.5,14,14.5},{15,15.5,16,16.5,17,17.5}}; mat2x2 Mat2_result; mat2x2_copy(Mat2_result, Mat2A); mat3x3 Mat3_result; mat3x3_copy(Mat3_result, Mat3A); mat4x4 Mat4_result; mat4x4_copy(Mat4_result, Mat4A); mat5x5 Mat5_result; mat5x5_copy(Mat5_result, Mat5A); mat6x6 Mat6_result; mat6x6_copy(Mat6_result, Mat6A); for (std::size_t size = 2; size<7; ++size) { if (size == 2) mat2x2_scale(Mat2_result, 0.5f); if (size == 3) mat3x3_scale(Mat3_result, 0.5f); if (size == 4) mat4x4_scale(Mat4_result, 0.5f); if (size == 5) mat5x5_scale(Mat5_result, 0.5f); if (size == 6) mat6x6_scale(Mat6_result, 0.5f); for (std::size_t row = 0; row < size; ++row) { for (std::size_t col = 0; col < size; ++col) { if (size == 2) EXPECT_NEAR(Mat2_expected[row][col], Mat2_result[row][col], tolerance) << "Matrix: " << size << " Row: " << row << " Col: " << col; if (size == 3) EXPECT_NEAR(Mat3_expected[row][col], Mat3_result[row][col], tolerance) << "Matrix: " << size << " Row: " << row << " Col: " << col; if (size == 4) EXPECT_NEAR(Mat4_expected[row][col], Mat4_result[row][col], tolerance) << "Matrix: " << size << " Row: " << row << " Col: " << col; if (size == 5) EXPECT_NEAR(Mat5_expected[row][col], Mat5_result[row][col], tolerance) << "Matrix: " << size << " Row: " << row << " Col: " << col; if (size == 6) EXPECT_NEAR(Mat6_expected[row][col], Mat6_result[row][col], tolerance) << "Matrix: " << size << " Row: " << row << " Col: " << col; } } } } TEST_F(Linear_Algebra_Scale_, Two_Through_Six_Square_Mat_Scale_In_Place_And_Return_Test) { mat2x2 Mat2_expected {{0,.5},{1,1.5}}; mat3x3 Mat3_expected {{0,.5,1},{1.5,2,2.5},{3,3.5,4}}; mat4x4 Mat4_expected {{0,.5,1,1.5},{2,2.5,3,3.5},{4,4.5,5,5.5},{6,6.5,7,7.5}}; mat5x5 Mat5_expected {{0,.5,1,1.5,2},{2.5,3,3.5,4,4.5},{5,5.5,6,6.5,7},{7.5,8,8.5,9,9.5},{10,10.5,11,11.5,12}}; mat6x6 Mat6_expected {{0,.5,1,1.5,2,2.5},{3,3.5,4,4.5,5,5.5},{6,6.5,7,7.5,8,8.5},{9,9.5,10,10.5,11,11.5},{12,12.5,13,13.5,14,14.5},{15,15.5,16,16.5,17,17.5}}; vec2 * Mat2_result = mat2x2_scale_r(Mat2A, 0.5f); vec3 * Mat3_result = mat3x3_scale_r(Mat3A, 0.5f); vec4 * Mat4_result = mat4x4_scale_r(Mat4A, 0.5f); vec5 * Mat5_result = mat5x5_scale_r(Mat5A, 0.5f); vec6 * Mat6_result = mat6x6_scale_r(Mat6A, 0.5f); for (std::size_t size = 2; size<7; ++size) { for (std::size_t row = 0; row < size; ++row) { for (std::size_t col = 0; col < size; ++col) { if (size == 2) EXPECT_NEAR(Mat2_expected[row][col], Mat2_result[row][col], tolerance) << "Matrix: " << size << " Row: " << row << " Col: " << col; if (size == 3) EXPECT_NEAR(Mat3_expected[row][col], Mat3_result[row][col], tolerance) << "Matrix: " << size << " Row: " << row << " Col: " << col; if (size == 4) EXPECT_NEAR(Mat4_expected[row][col], Mat4_result[row][col], tolerance) << "Matrix: " << size << " Row: " << row << " Col: " << col; if (size == 5) EXPECT_NEAR(Mat5_expected[row][col], Mat5_result[row][col], tolerance) << "Matrix: " << size << " Row: " << row << " Col: " << col; if (size == 6) EXPECT_NEAR(Mat6_expected[row][col], Mat6_result[row][col], tolerance) << "Matrix: " << size << " Row: " << row << " Col: " << col; } } } }
35.379822
162
0.556487
JBPennington
b2bf412cbf53b73e507354a4d55c49279c232463
19,329
cpp
C++
view-cmake/src/plotNormal.cpp
limeng12/GenomeBrowser-CPlusPlus
63d41a55d013cee9208e244cf154901461e12a30
[ "BSD-3-Clause-Attribution" ]
2
2019-10-14T09:29:38.000Z
2021-04-25T00:16:40.000Z
view-cmake/src/plotNormal.cpp
limeng12/GenomeBrowser-CPlusPlus
63d41a55d013cee9208e244cf154901461e12a30
[ "BSD-3-Clause-Attribution" ]
null
null
null
view-cmake/src/plotNormal.cpp
limeng12/GenomeBrowser-CPlusPlus
63d41a55d013cee9208e244cf154901461e12a30
[ "BSD-3-Clause-Attribution" ]
null
null
null
#include "plotNormal.h" PlotNormal::PlotNormal(DataFactory* tdata,BamData* tbdata,wxSize tcavanseSize,std::vector<bool>* tvector) :PlotBase(tdata,tbdata,tcavanseSize,tvector){ //posNulciedTable=new char[200];// //200是一行染色体可能的最多的数目 minHeight=3; } PlotNormal::~PlotNormal(){ } void PlotNormal::NucliedSizeChange(){ } void PlotNormal::canvasSizeChange(wxSize changedSize){ } void PlotNormal::plotMain(wxDC& dc,std::string chr,int chrPos,int leftPos,int rightPos,int upPos,int downPos){ //for snp frequence drawing int begPos=(int)(chrPos-rightPos/plotNucliedSize/2); int endPos=(int)(chrPos+rightPos/plotNucliedSize/2); if(begPos<0){ begPos=0; endPos=begPos+rightPos/plotNucliedSize; } if(endPos>mdata->chrAndLength[chr]){ endPos=mdata->chrAndLength[chr]; begPos=endPos-rightPos/plotNucliedSize; } height=(plotNucliedSize>minHeight?plotNucliedSize:minHeight); pairendTable.clear(); pipeLine=0;unsigned int i=0; pipeLine+=plotCoor(dc,chr,chrPos,begPos,endPos,0); dc.SetFont(wxFont(1*(height-1),wxFONTFAMILY_TELETYPE,wxFONTSTYLE_NORMAL,wxFONTWEIGHT_NORMAL)); if(mdata->getFastaFile()!=wxEmptyString){ if(viewVector->at(i++)){ // pipeLine+=plotChr(dc,chr,chrPos,begPos,endPos,0); viewFaFlag=true; }else viewFaFlag=false; } //dc.SetFont(wscut.pen9Pix); for(size_t j=0;j<mdata->getGtfCount();++j,++i){ if(viewVector->at(i)){ //gffTable.clear(); dc.SetTextForeground(*wxBLACK); pipeLine+=plotGTFExon(dc,chr,chrPos,begPos,endPos,j);///also use plot gff//fixed me pipeLine+=plotGTFCds(dc,chr,chrPos,begPos,endPos,j);///also use plot gff } } for(size_t j=0;j<mdata->getGffCount();++j,++i){ if(viewVector->at(i)){ //gffTable.clear(); dc.SetTextForeground(*wxBLACK); dc.SetBrush(*wxGREEN_BRUSH); pipeLine+=plotGff(dc,chr,chrPos,begPos,endPos,j);///also use plot gff } } for(size_t j=0;j<mdata->getBedCount();++j,++i){ if(viewVector->at(i)){ dc.SetTextForeground(*wxBLACK); pipeLine+=plotBed(dc,chr,chrPos,begPos,endPos,j);///also use plot gff //fixed me } } for(size_t j=0;j<mdata->getVcfCount();++j,++i){ if(viewVector->at(i)){ dc.SetTextForeground(wscut.wxColourVector[j]); pipeLine+=plotVcf(dc,chr,chrPos,begPos,endPos,j); } } if(viewVector->at(i)){ pipeLine+=plotNucliedSize*2; plotBam(dc,chr,chrPos,begPos,endPos,0); // pipeLine-=20; // plotSNP(dc,chr,chrPos,begPos,endPos,0); } } int PlotNormal::MbamHelp(bam1_t* b,wxDC& dc,int beg, int end,int &maxLine,int& lastPos,int &lastLine){ int tlastLine=0; if(maxLine>=99) return maxLine; switch(b->core.flag&0x0001){ case 0: tlastLine=MbamHelpSingleEnd(b,dc,beg,end,maxLine,lastPos,lastLine); break; case 1: tlastLine=MbamHelpPairEnd(b,dc,beg,end,maxLine,lastPos,lastLine); break; } if(tlastLine>maxLine) maxLine=tlastLine; return maxLine; } int PlotNormal::MbamHelpSingleEnd(bam1_t* b,wxDC& dc,int beg, int end,int& maxLine,int& lastPos,int &lastLine){ if(!mdata->bamfilter->operator()(b)) return lastLine; int relativePos=(b)->core.pos-beg>0?(b)->core.pos-beg:0; unsigned int length=(b)->core.l_qseq; //if(relativePos>2) //{ // int xx=1201; // relativePos=relativePos; //} if(((b)->core.flag)&0x10) dc.SetBrush(*wxBLUE_BRUSH);//complentary else dc.SetBrush(*wxYELLOW_BRUSH); std::vector<std::pair<int,char> > drawSnp; int sum=0; int nOper=0; int nDeleteInsert=0;//xulie de chang du uint32_t *cigar = bam1_cigar(b); for (size_t i = 0; i < b->core.n_cigar; ++i) { nOper=bam1_cigar(b)[i]>>BAM_CIGAR_SHIFT; while(nOper-->0){ //cigarArray<<bam_cigar_opchr(cigar[i]); char curOper=bam_cigar_opchr(cigar[i]); int backnDeleteInsert=nDeleteInsert; switch(curOper){ case 'I': nDeleteInsert--;break; case 'D': nDeleteInsert++;break; case 'S':break; case 'N':nDeleteInsert++;break; case 'M': break; } if(b->core.pos+sum>end) goto End; if(b->core.pos+sum>=beg){ //int indexRelativePos=b->core.pos+sum-beg; int seqPos=sum-backnDeleteInsert; if(seqPos>=length) goto End; //char tstr=bam_nt16_rev_table[bam1_seqi(bam1_seq(b),seqPos)]; switch(curOper){ case 'I': //drawSnp.push_back(std::make_pair(indexRelativePos,'I')); ;break; case 'D': //drawSnp.push_back(std::make_pair(indexRelativePos,'D')); break; case 'S': //drawSnp.push_back(std::make_pair(indexRelativePos,'S'));break; case 'N': //drawSnp.push_back(std::make_pair(indexRelativePos,'N')); break; case 'X': //drawSnp.push_back(std::make_pair(indexRelativePos,'X'));break; case 'M': // frequencyTable.at(convertTable.at(tstr)*cavansNucliced+indexRelativePos)++; // freQuenctSumTable[indexRelativePos]++; // if(tstr!=posNulciedTable[indexRelativePos]&&tstr!=posNulciedTable[indexRelativePos]-32&&tstr!=posNulciedTable[indexRelativePos]+32){ // drawSnp.push_back(std::make_pair(indexRelativePos,tstr)); // } break; } } sum++; } } End: length+=nDeleteInsert; //if(lastLine>=99) // return lastLine; /* if(lastPos==(b)->core.pos){ lastLine++; int ttmp=(beg)>((b)->core.pos)?(beg-(b)->core.pos):0;//the rectangle length dc.DrawRectangle(relativePos*plotNucliedSize,lastLine*plotNucliedSize*2+pipeLine,(length-ttmp)*(plotNucliedSize),plotNucliedSize*2.005); for(size_t j=0;j<drawSnp.size();++j) dc.DrawText(drawSnp[j].second,(drawSnp[j].first)*(plotNucliedSize),lastLine*plotNucliedSize*2+pipeLine); curEndPos[lastLine]=b->core.pos+length-beg; return lastLine; } */ for(int i=1;i<100;++i) if(curEndPos[i]<=relativePos){ int ttmp=(beg)>((b)->core.pos)?(beg-(b)->core.pos):0;//the rectangle length dc.DrawRectangle(relativePos*plotNucliedSize,i*height*2+pipeLine,(length-ttmp)*(plotNucliedSize),(height)*2.005); // for(size_t j=0;j<drawSnp.size();++j) // dc.DrawText(drawSnp[j].second,(drawSnp[j].first)*(plotNucliedSize),i*plotNucliedSize*2+pipeLine); curEndPos[i]=b->core.pos+length-beg; //if(i==99) // overPos=curEndPos[i]; lastPos=(b)->core.pos; lastLine=i; break; } return lastLine; } int PlotNormal::MbamHelpPairEnd(bam1_t* b,wxDC& dc,int beg, int end,int& maxLine,int& lastPos,int &lastLine){ if(!mdata->bamfilter->operator()(b)) return lastLine; int relativePos=(b)->core.pos-beg>0?(b)->core.pos-beg:0; unsigned int length=(b)->core.l_qseq; if(((b)->core.flag)&0x10) dc.SetBrush(*wxBLUE_BRUSH);//complentary else dc.SetBrush(*wxYELLOW_BRUSH); std::vector<std::pair<int,char> > drawSnp; int sum=0; int nOper=0; int nDeleteInsert=0;//xulie de chang du uint32_t *cigar = bam1_cigar(b); for (size_t i = 0; i < b->core.n_cigar; ++i) { nOper=bam1_cigar(b)[i]>>BAM_CIGAR_SHIFT; while(nOper-->0){ //cigarArray<<bam_cigar_opchr(cigar[i]); char curOper=bam_cigar_opchr(cigar[i]); int backnDeleteInsert=nDeleteInsert; switch(curOper){ case 'I': nDeleteInsert--;break; case 'D': nDeleteInsert++;break; case 'S':break; case 'N':nDeleteInsert++;break; case 'M': break; } if(b->core.pos+sum>end) goto End; if(b->core.pos+sum>=beg){ //int indexRelativePos=b->core.pos+sum-beg; int seqPos=sum-backnDeleteInsert; if(seqPos>=length) goto End; //char tstr=bam_nt16_rev_table[bam1_seqi(bam1_seq(b),seqPos)]; switch(curOper){ case 'I': //drawSnp.push_back(std::make_pair(indexRelativePos,'I')) ;break; case 'D': // drawSnp.push_back(std::make_pair(indexRelativePos,'D')); break; case 'S': // drawSnp.push_back(std::make_pair(indexRelativePos,'S'));break; case 'N': // drawSnp.push_back(std::make_pair(indexRelativePos,'N')); break; case 'X': // drawSnp.push_back(std::make_pair(indexRelativePos,'X'));break; case 'M':break; // frequencyTable.at(convertTable.at(tstr)*cavansNucliced+indexRelativePos)++; // freQuenctSumTable[indexRelativePos]++; // if(tstr!=posNulciedTable[indexRelativePos]&&tstr!=posNulciedTable[indexRelativePos]-32&&tstr!=posNulciedTable[indexRelativePos]+32){ // drawSnp.push_back(std::make_pair(indexRelativePos,tstr)); // } // break; } } sum++; } } End: length+=nDeleteInsert; //if(lastLine>=99) // return lastLine; int mateSize=b->core.isize; int matePos=b->core.mpos;//+mateSize; int line=0; if(pairendTable.find(std::string(bam1_qname(b)))!=pairendTable.end()){ line=pairendTable[std::string(bam1_qname(b))]; if(b->core.pos==matePos) return lastLine; int ttmp=(beg)>((b)->core.pos)?(beg-(b)->core.pos):0;//the rectangle length dc.DrawRectangle(relativePos*plotNucliedSize,line*height*2+pipeLine,(length-ttmp)*(plotNucliedSize),(height)*2.005); //dc.DrawText(wxString(bam1_qname(b)),relativePos*plotNucliedSize,line*plotNucliedSize*2+pipeLine); //for(size_t j=0;j<drawSnp.size();++j) // dc.DrawText(drawSnp[j].second,(drawSnp[j].first)*(plotNucliedSize),line*plotNucliedSize*2+pipeLine); //dc.DrawLine(curEndPos[line]*plotNucliedSize,line*plotNucliedSize*2+pipeLine+10,relativePos*plotNucliedSize,line*plotNucliedSize*2+pipeLine+10); //dc.DrawLine(((b->core.pos-beg)>0?b->core.pos-beg:0)*plotNucliedSize,line*plotNucliedSize*2+pipeLine+10,relativePos*plotNucliedSize,line*plotNucliedSize*2+pipeLine+10); if(matePos+b->core.l_qseq-beg<relativePos)//这里使用了当前序列长度来代替mate序列长度 dc.DrawLine((matePos+b->core.l_qseq-beg)*plotNucliedSize,line*height*2+pipeLine+height,relativePos*plotNucliedSize,line*height*2+pipeLine+height);//这里使用了当前序列长度来代替mate序列长度 curEndPos[line]=b->core.pos+length-beg;//>end-beg?end-beg:relativePos+length; return lastLine; } //这里设计的有问题,妈的 if(mateSize<0){ maxLine++; if(maxLine>100) return maxLine; pairendTable[std::string(bam1_qname(b))]=maxLine; int ttmp=(beg)>((b)->core.pos)?(beg-(b)->core.pos):0;//the rectangle length dc.DrawRectangle(relativePos*plotNucliedSize,maxLine*height*2+pipeLine,(length-ttmp)*(plotNucliedSize),(height)*2.005); //for(size_t j=0;j<drawSnp.size();++j) // dc.DrawText(drawSnp[j].second,(drawSnp[j].first)*(plotNucliedSize),line*plotNucliedSize*2+pipeLine); if(beg<b->core.pos){ int lineBegin=beg>matePos+b->core.l_qseq?beg:matePos+b->core.l_qseq;//这里使用了当前序列长度来代替mate序列长度 //if(lineBegin-beg<relativePos) dc.DrawLine((lineBegin-beg)*plotNucliedSize,maxLine*height*2+pipeLine+height,relativePos*plotNucliedSize,maxLine*height*2+pipeLine+height); //curEndPos[lastLine]+=length-(beg-(b)->core.pos); } curEndPos[maxLine]=b->core.pos+length-beg; lastLine=maxLine; lastPos=b->core.pos; return lastLine; } /* if(lastPos==(b)->core.pos){ lastLine++; pairendTable[std::string(bam1_qname(b))]=lastLine; int ttmp=(beg)>((b)->core.pos)?(beg-(b)->core.pos):0;//the rectangle length dc.DrawRectangle(relativePos*plotNucliedSize,lastLine*plotNucliedSize*2+pipeLine,(length-ttmp)*(plotNucliedSize),plotNucliedSize*2.005); if(mateSize>0){ if(end>b->core.pos+length){ //int lineEnd=end<matePos?end:matePos; //if(relativePos+length<lineEnd-beg) dc.DrawLine((b->core.pos+length-beg)*plotNucliedSize,lastLine*plotNucliedSize*2+pipeLine+10,(matePos-beg)*plotNucliedSize,lastLine*plotNucliedSize*2+pipeLine+10); //if(lineEnd-beg+101>b->core.pos+length-beg) curEndPos[lastLine]=matePos-beg+101; //else // curEndPos[lastLine]=b->core.pos+length-beg; } } else if(mateSize==0){ //curEndPos[lastLine]+=length-(beg-(b)->core.pos); curEndPos[lastLine]=b->core.pos+length-beg; } for(size_t j=0;j<drawSnp.size();++j) dc.DrawText(drawSnp[j].second,(drawSnp[j].first)*(plotNucliedSize),lastLine*plotNucliedSize*2+pipeLine); return lastLine; } */ for(int i=1;i<100;++i) if(curEndPos[i]<=relativePos){ pairendTable[std::string(bam1_qname(b))]=i; int ttmp=(beg)>((b)->core.pos)?(beg-(b)->core.pos):0;//the rectangle length easy erro here be carefull dc.DrawRectangle(relativePos*plotNucliedSize,i*height*2+pipeLine,(length-ttmp)*(plotNucliedSize),(height)*2.005); //dc.DrawText(wxString(bam1_qname(b)),relativePos*plotNucliedSize,i*plotNucliedSize*2+pipeLine); if(mateSize>0){ if(end>b->core.pos+length){ //int lineEnd=end<matePos?end:matePos; //if(relativePos+length<lineEnd-beg) if(b->core.pos+length-beg<matePos-beg) { dc.DrawLine((b->core.pos+length-beg)*plotNucliedSize,i*height*2+pipeLine+height,(matePos-beg)*plotNucliedSize,i*height*2+pipeLine+height); } //if(lineEnd+101-beg>b->core.pos+length-beg) //else // curEndPos[i]=b->core.pos+length-beg; } if(matePos-beg+length<=b->core.pos+length-beg){//这里使用了当前序列长度来代替mate序列长度 curEndPos[i]=b->core.pos+length-beg; }else{ curEndPos[i]=matePos-beg+length;//这里使用了当前序列长度来代替mate序列长度 //curEndPos[i]=b->core.pos+length-beg; } } else if(mateSize==0){ curEndPos[i]=b->core.pos+length-beg; }else curEndPos[i]=b->core.pos+length-beg; //for(size_t j=0;j<drawSnp.size();++j) // dc.DrawText(drawSnp[j].second,(drawSnp[j].first)*(plotNucliedSize),i*plotNucliedSize*2+pipeLine); lastPos=(b)->core.pos; lastLine=i; break; } return lastLine; } int PlotNormal::MbamHelpNOFa(bam1_t* b,wxDC& dc,int beg, int end,int& maxLine,int& lastPos,int &lastLine){ int relativePos=(b)->core.pos-beg>0?(b)->core.pos-beg:0; unsigned int length=(b)->core.l_qseq; //if(relativePos<overPos) // return ; if(((b)->core.flag)&0x10) dc.SetBrush(*wxBLUE_BRUSH);//complentary else dc.SetBrush(*wxYELLOW_BRUSH); //std::string name=bam1_qname(b); int sum=0; int nOper=0; int nDeleteInsert=0;//xulie de chang du wxString printString; for (size_t i = 0; i < b->core.n_cigar; ++i) { nOper=bam1_cigar(b)[i]>>BAM_CIGAR_SHIFT; uint32_t *cigar = bam1_cigar(b); while(nOper-->0){ //cigarArray<<bam_cigar_opchr(cigar[i]); char curOper=bam_cigar_opchr(cigar[i]); int backnDeleteInsert=nDeleteInsert; switch(curOper){ case 'I': nDeleteInsert--;break; case 'D': nDeleteInsert++;break; case 'S':break; case 'N':nDeleteInsert++;break; case 'M': break; } if(b->core.pos+sum>end) goto End; if(b->core.pos+sum>=beg){ //int indexRelativePos=b->core.pos+sum-beg; int seqPos=sum-backnDeleteInsert; if(seqPos>=length) goto End; char tstr=bam_nt16_rev_table[bam1_seqi(bam1_seq(b),seqPos)]; switch(curOper){ case 'I': tstr=0;break; case 'D': printString<<'D';break; case 'S': printString<<tstr-32;break; case 'N': printString<<'N';break; case 'X': break; case 'M': // frequencyTable.at(convertTable.at(tstr)*cavansNucliced+indexRelativePos)++; // freQuenctSumTable[indexRelativePos]++; printString<<tstr; // if(tstr!=posNulciedTable[indexRelativePos]){ // drawSnp.push_back(std::make_pair(indexRelativePos,tstr)); // } break; } } sum++; } } End: length+=nDeleteInsert; //printString<<" "<<bam1_qname(b); //if(lastLine==100) // return lastLine; if(lastPos==(b)->core.pos){ lastLine++; int ttmp=(beg)>((b)->core.pos)?(beg-(b)->core.pos):0;//the rectangle length dc.DrawRectangle(relativePos*plotNucliedSize,lastLine*plotNucliedSize*2+pipeLine,(length-ttmp)*(plotNucliedSize),(height)*2.005); //dc.DrawText(printString,relativePos*plotNucliedSize,lastLine*plotNucliedSize*2+pipeLine); } for(int i=0;i<100;++i) if(curEndPos[i]<=relativePos){ int ttmp=(beg)>((b)->core.pos)?(beg-(b)->core.pos):0;//the rectangle length dc.DrawRectangle(relativePos*plotNucliedSize,i*plotNucliedSize*2+pipeLine,(length-ttmp)*(plotNucliedSize),height*2.005); //dc.DrawText(printString,relativePos*plotNucliedSize,i*plotNucliedSize*2+pipeLine); curEndPos[i]+=length-(beg-(b)->core.pos); //if(i==99) // overPos=curEndPos[i]; lastPos=(b)->core.pos; lastLine=i; break; } }
31.791118
182
0.561902
limeng12
b2c15fbb96b416bcf02671cff7b56ec353352b0b
10,761
cpp
C++
01_Develop/libXMCocos2D-v3/Source/shaders/CCShaderCache.cpp
mcodegeeks/OpenKODE-Framework
d4382d781da7f488a0e7667362a89e8e389468dd
[ "MIT" ]
2
2017-08-03T07:15:00.000Z
2018-06-18T10:32:53.000Z
01_Develop/libXMCocos2D-v3/Source/shaders/CCShaderCache.cpp
mcodegeeks/OpenKODE-Framework
d4382d781da7f488a0e7667362a89e8e389468dd
[ "MIT" ]
null
null
null
01_Develop/libXMCocos2D-v3/Source/shaders/CCShaderCache.cpp
mcodegeeks/OpenKODE-Framework
d4382d781da7f488a0e7667362a89e8e389468dd
[ "MIT" ]
2
2019-03-04T22:57:42.000Z
2020-03-06T01:32:26.000Z
/* ----------------------------------------------------------------------------------- * * File CCShaderCache.cpp * Ported By Young-Hwan Mun * Contact xmsoft77@gmail.com * * ----------------------------------------------------------------------------------- * * Copyright (c) 2010-2014 XMSoft * Copyright (c) 2010-2013 cocos2d-x.org * Copyright (c) 2011 Ricardo Quesada * Copyright (c) 2011 Zynga Inc. * * http://www.cocos2d-x.org * * ----------------------------------------------------------------------------------- * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * --------------------------------------------------------------------------------- */ #include "shaders/CCShaderCache.h" #include "shaders/CCGLProgram.h" #include "ccMacros.h" #include "shaders/ccShaders.h" NS_CC_BEGIN enum { kShaderType_PositionTextureColor, kShaderType_PositionTextureColorAlphaTest, kShaderType_PositionColor, kShaderType_PositionTexture, kShaderType_PositionTexture_uColor, kShaderType_PositionTextureA8Color, kShaderType_Position_uColor, kShaderType_PositionLengthTexureColor, kShaderType_MAX, }; static ShaderCache *_sharedShaderCache = 0; ShaderCache* ShaderCache::getInstance() { if (!_sharedShaderCache) { _sharedShaderCache = new ShaderCache(); if (!_sharedShaderCache->init()) { CC_SAFE_DELETE(_sharedShaderCache); } } return _sharedShaderCache; } void ShaderCache::destroyInstance() { CC_SAFE_RELEASE(_sharedShaderCache); } ShaderCache::ShaderCache() : m_aPrograms() { } ShaderCache::~ShaderCache() { for( auto it = m_aPrograms.begin(); it != m_aPrograms.end(); ++it ) { (it->second)->release(); } CCLOGINFO("deallocing ShaderCache: %p", this); } bool ShaderCache::init() { loadDefaultShaders(); return true; } void ShaderCache::loadDefaultShaders() { // Position Texture Color shader GLProgram *p = new GLProgram(); loadDefaultShader(p, kShaderType_PositionTextureColor); m_aPrograms.insert( std::make_pair( GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR, p ) ); // Position Texture Color alpha test p = new GLProgram(); loadDefaultShader(p, kShaderType_PositionTextureColorAlphaTest); m_aPrograms.insert( std::make_pair(GLProgram::SHADER_NAME_POSITION_TEXTURE_ALPHA_TEST, p) ); // // Position, Color shader // p = new GLProgram(); loadDefaultShader(p, kShaderType_PositionColor); m_aPrograms.insert( std::make_pair(GLProgram::SHADER_NAME_POSITION_COLOR, p) ); // // Position Texture shader // p = new GLProgram(); loadDefaultShader(p, kShaderType_PositionTexture); m_aPrograms.insert( std::make_pair( GLProgram::SHADER_NAME_POSITION_TEXTURE, p) ); // // Position, Texture attribs, 1 Color as uniform shader // p = new GLProgram(); loadDefaultShader(p, kShaderType_PositionTexture_uColor); m_aPrograms.insert( std::make_pair( GLProgram::SHADER_NAME_POSITION_TEXTURE_U_COLOR, p) ); // // Position Texture A8 Color shader // p = new GLProgram(); loadDefaultShader(p, kShaderType_PositionTextureA8Color); m_aPrograms.insert( std::make_pair(GLProgram::SHADER_NAME_POSITION_TEXTURE_A8_COLOR, p) ); // // Position and 1 color passed as a uniform (to simulate glColor4ub ) // p = new GLProgram(); loadDefaultShader(p, kShaderType_Position_uColor); m_aPrograms.insert( std::make_pair(GLProgram::SHADER_NAME_POSITION_U_COLOR, p) ); // // Position, Legth(TexCoords, Color (used by Draw Node basically ) // p = new GLProgram(); loadDefaultShader(p, kShaderType_PositionLengthTexureColor); m_aPrograms.insert( std::make_pair(GLProgram::SHADER_NAME_POSITION_LENGTH_TEXTURE_COLOR, p) ); } void ShaderCache::reloadDefaultShaders() { // reset all programs and reload them // Position Texture Color shader GLProgram *p = getProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR); p->reset(); loadDefaultShader(p, kShaderType_PositionTextureColor); // Position Texture Color alpha test p = getProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE_ALPHA_TEST); p->reset(); loadDefaultShader(p, kShaderType_PositionTextureColorAlphaTest); // // Position, Color shader // p = getProgram(GLProgram::SHADER_NAME_POSITION_COLOR); p->reset(); loadDefaultShader(p, kShaderType_PositionColor); // // Position Texture shader // p = getProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE); p->reset(); loadDefaultShader(p, kShaderType_PositionTexture); // // Position, Texture attribs, 1 Color as uniform shader // p = getProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE_U_COLOR); p->reset(); loadDefaultShader(p, kShaderType_PositionTexture_uColor); // // Position Texture A8 Color shader // p = getProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE_A8_COLOR); p->reset(); loadDefaultShader(p, kShaderType_PositionTextureA8Color); // // Position and 1 color passed as a uniform (to simulate glColor4ub ) // p = getProgram(GLProgram::SHADER_NAME_POSITION_U_COLOR); p->reset(); loadDefaultShader(p, kShaderType_Position_uColor); // // Position, Legth(TexCoords, Color (used by Draw Node basically ) // p = getProgram(GLProgram::SHADER_NAME_POSITION_LENGTH_TEXTURE_COLOR); p->reset(); loadDefaultShader(p, kShaderType_PositionLengthTexureColor); } void ShaderCache::loadDefaultShader(GLProgram *p, int type) { switch (type) { case kShaderType_PositionTextureColor: p->initWithVertexShaderByteArray(ccPositionTextureColor_vert, ccPositionTextureColor_frag); p->addAttribute(GLProgram::ATTRIBUTE_NAME_POSITION, GLProgram::VERTEX_ATTRIB_POSITION); p->addAttribute(GLProgram::ATTRIBUTE_NAME_COLOR, GLProgram::VERTEX_ATTRIB_COLOR); p->addAttribute(GLProgram::ATTRIBUTE_NAME_TEX_COORD, GLProgram::VERTEX_ATTRIB_TEX_COORDS); break; case kShaderType_PositionTextureColorAlphaTest: p->initWithVertexShaderByteArray(ccPositionTextureColor_vert, ccPositionTextureColorAlphaTest_frag); p->addAttribute(GLProgram::ATTRIBUTE_NAME_POSITION, GLProgram::VERTEX_ATTRIB_POSITION); p->addAttribute(GLProgram::ATTRIBUTE_NAME_COLOR, GLProgram::VERTEX_ATTRIB_COLOR); p->addAttribute(GLProgram::ATTRIBUTE_NAME_TEX_COORD, GLProgram::VERTEX_ATTRIB_TEX_COORDS); break; case kShaderType_PositionColor: p->initWithVertexShaderByteArray(ccPositionColor_vert ,ccPositionColor_frag); p->addAttribute(GLProgram::ATTRIBUTE_NAME_POSITION, GLProgram::VERTEX_ATTRIB_POSITION); p->addAttribute(GLProgram::ATTRIBUTE_NAME_COLOR, GLProgram::VERTEX_ATTRIB_COLOR); break; case kShaderType_PositionTexture: p->initWithVertexShaderByteArray(ccPositionTexture_vert ,ccPositionTexture_frag); p->addAttribute(GLProgram::ATTRIBUTE_NAME_POSITION, GLProgram::VERTEX_ATTRIB_POSITION); p->addAttribute(GLProgram::ATTRIBUTE_NAME_TEX_COORD, GLProgram::VERTEX_ATTRIB_TEX_COORDS); break; case kShaderType_PositionTexture_uColor: p->initWithVertexShaderByteArray(ccPositionTexture_uColor_vert, ccPositionTexture_uColor_frag); p->addAttribute(GLProgram::ATTRIBUTE_NAME_POSITION, GLProgram::VERTEX_ATTRIB_POSITION); p->addAttribute(GLProgram::ATTRIBUTE_NAME_TEX_COORD, GLProgram::VERTEX_ATTRIB_TEX_COORDS); break; case kShaderType_PositionTextureA8Color: p->initWithVertexShaderByteArray(ccPositionTextureA8Color_vert, ccPositionTextureA8Color_frag); p->addAttribute(GLProgram::ATTRIBUTE_NAME_POSITION, GLProgram::VERTEX_ATTRIB_POSITION); p->addAttribute(GLProgram::ATTRIBUTE_NAME_COLOR, GLProgram::VERTEX_ATTRIB_COLOR); p->addAttribute(GLProgram::ATTRIBUTE_NAME_TEX_COORD, GLProgram::VERTEX_ATTRIB_TEX_COORDS); break; case kShaderType_Position_uColor: p->initWithVertexShaderByteArray(ccPosition_uColor_vert, ccPosition_uColor_frag); p->addAttribute("aVertex", GLProgram::VERTEX_ATTRIB_POSITION); break; case kShaderType_PositionLengthTexureColor: p->initWithVertexShaderByteArray(ccPositionColorLengthTexture_vert, ccPositionColorLengthTexture_frag); p->addAttribute(GLProgram::ATTRIBUTE_NAME_POSITION, GLProgram::VERTEX_ATTRIB_POSITION); p->addAttribute(GLProgram::ATTRIBUTE_NAME_TEX_COORD, GLProgram::VERTEX_ATTRIB_TEX_COORDS); p->addAttribute(GLProgram::ATTRIBUTE_NAME_COLOR, GLProgram::VERTEX_ATTRIB_COLOR); break; default: CCLOG("cocos2d: %s:%d, error shader type", __FUNCTION__, __LINE__); return; } p->link(); p->updateUniforms(); CHECK_GL_ERROR_DEBUG(); } GLProgram* ShaderCache::getProgram(const std::string &key) { auto it = m_aPrograms.find(key); if( it != m_aPrograms.end() ) return it->second; return nullptr; } void ShaderCache::addProgram(GLProgram* program, const std::string &key) { program->retain(); m_aPrograms.insert( std::make_pair( key, program) ); } NS_CC_END
36.110738
115
0.675216
mcodegeeks
b2c215dd6158f8eef501dfc0ca47fe46a63268e7
1,165
hpp
C++
simtools/factory.hpp
dcrete/simtools
82be6de79a490cdfe9079d643cd88dff2a5ae3aa
[ "MIT" ]
null
null
null
simtools/factory.hpp
dcrete/simtools
82be6de79a490cdfe9079d643cd88dff2a5ae3aa
[ "MIT" ]
null
null
null
simtools/factory.hpp
dcrete/simtools
82be6de79a490cdfe9079d643cd88dff2a5ae3aa
[ "MIT" ]
null
null
null
#ifndef SIMTOOLS_FACTORY_HPP #define SIMTOOLS_FACTORY_HPP #include <array> #include <vector> #include "simtools_config.hpp" #include "matrix.hpp" #include "tuple_math.hpp" namespace simtools::factory { template<dim_t N> constexpr inline matrix<N> make_matrix(std::vector<dim_t>::const_iterator it) { if constexpr (N == 1) { return matrix<1>(*it); } else { return matrix<N>(*it, make_matrix<N - 1>(it + 1)); } } template<dim_t N> constexpr inline matrix<N> make_matrix(std::array<dim_t, N> sizes) { auto v = std::vector<dim_t>(sizes.begin(), sizes.end()); return make_matrix<N>(v.begin()); } template<typename T, dim_t N> constexpr inline std::array<T, N> make_array(std::function<T(dim_t)> func) { auto result = std::array<T, N>(); for (auto i = 0U; i < N; ++i) { result[i] = func(i); } return result; } template<typename T1, typename... T2> constexpr inline std::array<T1, sizeof...(T2)> make_array(T2... vars) { return { static_cast<T1>(vars)... }; } } #endif // SIMTOOLS_FACTORY_HPP
26.477273
83
0.592275
dcrete
b2c338cd33dd3230720781f0eaf86a6384c469f6
2,283
cpp
C++
third_party/WebKit/Source/core/dom/NodeIteratorBase.cpp
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
third_party/WebKit/Source/core/dom/NodeIteratorBase.cpp
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
third_party/WebKit/Source/core/dom/NodeIteratorBase.cpp
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
/* * Copyright (C) 1999 Lars Knoll (knoll@kde.org) * Copyright (C) 2000 Frederik Holljen (frederik.holljen@hig.no) * Copyright (C) 2001 Peter Kelly (pmk@post.com) * Copyright (C) 2006 Samuel Weinig (sam.weinig@gmail.com) * Copyright (C) 2004, 2008 Apple Inc. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. * */ #include "core/dom/NodeIteratorBase.h" #include "bindings/core/v8/ExceptionState.h" #include "bindings/core/v8/V8NodeFilterCondition.h" #include "core/dom/Node.h" #include "core/dom/NodeFilter.h" namespace blink { NodeIteratorBase::NodeIteratorBase(void* child_this, Node* root_node, unsigned what_to_show, V8NodeFilterCondition* node_filter) : root_(root_node), what_to_show_(what_to_show), filter_(child_this, node_filter) {} unsigned NodeIteratorBase::AcceptNode(Node* node, ExceptionState& exception_state) const { // The bit twiddling here is done to map DOM node types, which are given as // integers from 1 through 14, to whatToShow bit masks. if (!(((1 << (node->getNodeType() - 1)) & what_to_show_))) return NodeFilter::kFilterSkip; if (!filter_) return NodeFilter::kFilterAccept; return filter_->acceptNode(node, exception_state); } DEFINE_TRACE(NodeIteratorBase) { visitor->Trace(root_); visitor->Trace(filter_); } DEFINE_TRACE_WRAPPERS(NodeIteratorBase) { visitor->TraceWrappers(filter_); } } // namespace blink
36.238095
78
0.696014
metux
b2c4a39c6ed814139f4dc07737c3dac709dacae3
448
cpp
C++
assets/slides/ies/C++ Examples/DefaultDelete/main.cpp
william-taylor/Slides
eff5b827ca61dd51420111ef0de23f18056abfa6
[ "MIT" ]
null
null
null
assets/slides/ies/C++ Examples/DefaultDelete/main.cpp
william-taylor/Slides
eff5b827ca61dd51420111ef0de23f18056abfa6
[ "MIT" ]
null
null
null
assets/slides/ies/C++ Examples/DefaultDelete/main.cpp
william-taylor/Slides
eff5b827ca61dd51420111ef0de23f18056abfa6
[ "MIT" ]
null
null
null
#include <iostream> class Point { int x; int y; public: Point(int a, int b){ x = a; y = b;} //Point() = default; }; class NumberWrapper { int * ptr; public: NumberWrapper(int num): ptr(new int{num}){} ~NumberWrapper() { delete ptr; } //NumberWrapper(const NumberWrapper& w) = delete; }; int main() { NumberWrapper number{52}; { NumberWrapper copy = number; } //Point point; return 0; }
14.933333
53
0.573661
william-taylor
b2c572acb83e9654fa28a93e2a37c5d2e5df4f06
2,185
cpp
C++
samples/01_system/08_json/src/main.cpp
SiminBadri/Wolf.Engine
3da04471ec26e162e1cbb7cc88c7ce37ee32c954
[ "BSL-1.0", "Apache-2.0", "libpng-2.0" ]
1
2020-07-15T13:14:26.000Z
2020-07-15T13:14:26.000Z
samples/01_system/08_json/src/main.cpp
foroughmajidi/Wolf.Engine
f08a8cbd519ca2c70b1c8325250dc9af7ac4c498
[ "BSL-1.0", "Apache-2.0", "libpng-2.0" ]
null
null
null
samples/01_system/08_json/src/main.cpp
foroughmajidi/Wolf.Engine
f08a8cbd519ca2c70b1c8325250dc9af7ac4c498
[ "BSL-1.0", "Apache-2.0", "libpng-2.0" ]
null
null
null
/* Project : Wolf Engine. Copyright(c) Pooya Eimandar (http://PooyaEimandar.com) . All rights reserved. Source : Please direct any bug to https://github.com/PooyaEimandar/Wolf.Engine/issues Website : http://WolfSource.io Name : main.cpp Description : This sample shows how to interact lua as script engine of Wolf Engine Comment : Read more information about this sample on http://wolfsource.io/gpunotes/wolfengine/ */ #include "pch.h" //namespaces using namespace wolf; using namespace wolf::system; //Entry point of program WOLF_MAIN() { w_logger_config _log_config; _log_config.app_name = L"08_json"; _log_config.log_path = wolf::system::io::get_current_directoryW(); #ifdef __WIN32 _log_config.log_to_std_out = false; #else _log_config.log_to_std_out = true; #endif logger.initialize(_log_config); //use rapid json to make json using namespace rapidjson; StringBuffer _string_buffer; Writer<StringBuffer> _writer(_string_buffer); _writer.StartObject(); { _writer.Key("name"); _writer.String("pooya"); _writer.Key("male"); _writer.Bool(true); _writer.Key("age"); _writer.Uint(31); _writer.Key("friends"); _writer.StartArray(); _writer.String("ray"); _writer.String("rayan"); _writer.String("sib"); _writer.String("barf"); _writer.EndArray(); _writer.Key("NULL"); _writer.Null(); } _writer.EndObject(); //output json auto _size = _string_buffer.GetSize(); auto _str = _string_buffer.GetString(); logger.write(_str); //read it again Document _doc; auto _buffer = new char[_size]; memcpy(&_buffer[0], &_str[0], _size); auto _parse = &_doc.Parse<rapidjson::kParseStopWhenDoneFlag>(_buffer); if (_parse->HasParseError()) { logger.error("error on parsing json. error code: {}", _parse->GetParseError()); } else { if(_doc.HasMember("name")) { if (_doc["name"].IsString()) { logger.write(_doc["name"].GetString()); } } } logger.release(); return EXIT_SUCCESS; }
25.406977
104
0.637071
SiminBadri
b2c5827cd04fdd2d18f089248ac6085e4cc32f1d
289
cpp
C++
src/0231.cpp
killf/leetcode_cpp
d1f308a9c3da55ae5416ea28ec2e7a3146533ae9
[ "MIT" ]
null
null
null
src/0231.cpp
killf/leetcode_cpp
d1f308a9c3da55ae5416ea28ec2e7a3146533ae9
[ "MIT" ]
null
null
null
src/0231.cpp
killf/leetcode_cpp
d1f308a9c3da55ae5416ea28ec2e7a3146533ae9
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <vector> #include <sstream> #include <algorithm> #include <map> #include <hash_map> #include <hash_set> #include <queue> using namespace std; class Solution { public: bool isPowerOfTwo(int n) { return (n > 0) && !(n & (n - 1)); } };
16.055556
37
0.657439
killf
b2c8b307709618db3e05abe14991075c69d4558c
570
cpp
C++
acmicpc.net/source/1436.cpp
tdm1223/Algorithm
994149afffa21a81e38b822afcfc01f677d9e430
[ "MIT" ]
7
2019-06-26T07:03:32.000Z
2020-11-21T16:12:51.000Z
acmicpc.net/source/1436.cpp
tdm1223/Algorithm
994149afffa21a81e38b822afcfc01f677d9e430
[ "MIT" ]
null
null
null
acmicpc.net/source/1436.cpp
tdm1223/Algorithm
994149afffa21a81e38b822afcfc01f677d9e430
[ "MIT" ]
9
2019-02-28T03:34:54.000Z
2020-12-18T03:02:40.000Z
// 1436. 영화감독 숌 // 2020.07.03 // 탐색 #include<iostream> using namespace std; bool check(int num) { while (num != 0) { if (num % 1000 == 666) { return true; } num /= 10; } return false; } int main() { int num = 666; int cnt = 0; int n; bool flag; cin >> n; while (1) { flag = false; if (check(num)) { cnt++; } if (cnt == n) { break; } num++; } cout << num << endl; return 0; }
11.875
30
0.37193
tdm1223
b2ca06975455fc9f0c1bc995fa6d26e67ba4dfd2
2,064
cpp
C++
Pinball/ModulePlayer.cpp
yeraytm/Pinball
f39b8d7b0e1b793ae7f3f992caec1a2960c1923c
[ "MIT" ]
null
null
null
Pinball/ModulePlayer.cpp
yeraytm/Pinball
f39b8d7b0e1b793ae7f3f992caec1a2960c1923c
[ "MIT" ]
null
null
null
Pinball/ModulePlayer.cpp
yeraytm/Pinball
f39b8d7b0e1b793ae7f3f992caec1a2960c1923c
[ "MIT" ]
null
null
null
#include "Globals.h" #include "Application.h" #include "ModulePlayer.h" #include "ModuleTextures.h" #include "ModulePhysics.h" #include "ModuleRender.h" #include "ModuleInput.h" #include "ModuleAudio.h" #include "ModuleSceneIntro.h" ModulePlayer::ModulePlayer(Application* app, bool start_enabled) : Module(app, start_enabled) {} ModulePlayer::~ModulePlayer() {} // Load assets bool ModulePlayer::Start() { LOG("Loading player"); ballRect = { 16, 31, 18, 18 }; ball = App->physics->CreateCircle(SCREEN_WIDTH-23, SCREEN_HEIGHT/2+215, 9); ball->body->SetBullet(true); ball->listener = this; lifes = 5; return true; } // Update: draw background update_status ModulePlayer::Update() { if (ball != nullptr && ball->pendingToDelete == true) { ball->pendingToDelete = false; b2Vec2 position; position.Set(PIXEL_TO_METERS(65.0f), PIXEL_TO_METERS(455.0f)); ball->body->SetTransform(position, ball->GetRotation()); b2Vec2 velocity; velocity.Set(1.0f, 1.0f); ball->body->SetLinearVelocity(velocity); } if (ball != nullptr && ball->pendingToDelete2 == true) { ball->pendingToDelete2 = false; b2Vec2 position; position.Set(PIXEL_TO_METERS(310.0f), PIXEL_TO_METERS(520.0f)); ball->body->SetTransform(position, ball->GetRotation()); b2Vec2 velocity; velocity.Set(-1.0f, 1.0f); ball->body->SetLinearVelocity(velocity); } if (ball != nullptr && ball->pendingToDelete3 == true) { ball->pendingToDelete3 = false; b2Vec2 position; position.Set(PIXEL_TO_METERS(float(SCREEN_WIDTH - 23)), PIXEL_TO_METERS(float(SCREEN_HEIGHT / 2+215))); ball->body->SetTransform(position, ball->GetRotation()); b2Vec2 velocity; velocity.Set(1.0f, 1.0f); ball->body->SetLinearVelocity(velocity); } int x, y; ball->GetPosition(x, y); App->renderer->Blit(App->scene_intro->spritesheetTex, x, y, &ballRect, 1.0f, ball->GetRotation()); return UPDATE_CONTINUE; } // Unload assets bool ModulePlayer::CleanUp() { LOG("Unloading player"); ball = nullptr; App->textures->Unload(App->scene_intro->spritesheetTex); return true; }
23.724138
105
0.71124
yeraytm
b2cc417185be34061429a5f49df485bc574b33e8
442
cpp
C++
AtCoder/ABC113/b.cpp
Takumi1122/data-structure-algorithm
6b9f26e4dbba981f034518a972ecfc698b86d837
[ "MIT" ]
null
null
null
AtCoder/ABC113/b.cpp
Takumi1122/data-structure-algorithm
6b9f26e4dbba981f034518a972ecfc698b86d837
[ "MIT" ]
null
null
null
AtCoder/ABC113/b.cpp
Takumi1122/data-structure-algorithm
6b9f26e4dbba981f034518a972ecfc698b86d837
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define rep(i, n) for (int i = 0; i < (n); ++i) using namespace std; using ll = long long; using P = pair<int, int>; int main() { int n, t, a; cin >> n >> t >> a; vector<int> h(n); rep(i, n) cin >> h[i]; int ans = 0; double mn = 1e9; rep(i, n) { double tem = t - h[i] * 0.006; if (abs(a - tem) < mn) { ans = i + 1; mn = abs(a - tem); } } cout << ans << endl; return 0; }
17.68
47
0.470588
Takumi1122
b2ce76b1304512a0044bed4597b708f8ae2a4217
1,296
cc
C++
test/tile_test.cc
zhihengq/2048
cfe0ee202cc10b1157a01f0675ff1fa4bb666bc6
[ "MIT" ]
null
null
null
test/tile_test.cc
zhihengq/2048
cfe0ee202cc10b1157a01f0675ff1fa4bb666bc6
[ "MIT" ]
null
null
null
test/tile_test.cc
zhihengq/2048
cfe0ee202cc10b1157a01f0675ff1fa4bb666bc6
[ "MIT" ]
null
null
null
#include "tile.h" #include <gtest/gtest.h> #include <sstream> #include <stdexcept> namespace { class TileTest : public testing::Test { protected: _2048::Tile tile_0_; _2048::Tile tile_2_; _2048::Tile tile_2048_; void SetUp() override { tile_0_ = _2048::Tile(); tile_2_ = _2048::Tile(1); tile_2048_ = _2048::Tile(11); } }; TEST_F(TileTest, Empty) { EXPECT_TRUE(tile_0_.empty()); EXPECT_FALSE(tile_2_.empty()); EXPECT_FALSE(tile_2048_.empty()); } TEST_F(TileTest, PreIncrement) { EXPECT_THROW(++tile_0_, std::logic_error); EXPECT_EQ(++tile_2_, _2048::Tile(2)); EXPECT_EQ(++tile_2048_, _2048::Tile(12)); } TEST_F(TileTest, PostIncrement) { EXPECT_THROW(tile_0_++, std::logic_error); EXPECT_EQ(tile_2_++, _2048::Tile(1)); EXPECT_EQ(tile_2_, _2048::Tile(2)); EXPECT_EQ(tile_2048_++, _2048::Tile(11)); EXPECT_EQ(tile_2048_, _2048::Tile(12)); } TEST_F(TileTest, Print) { { std::ostringstream oss; oss << tile_0_; EXPECT_EQ(oss.str(), ""); } { std::ostringstream oss; oss << tile_2_; EXPECT_EQ(oss.str(), "2"); } { std::ostringstream oss; oss << tile_2048_; EXPECT_EQ(oss.str(), "2048"); } } } // namespace
20.571429
46
0.600309
zhihengq
b2d4c71cd9a04189a978a35f6a289bbd25a27164
11,609
cpp
C++
base/cluster/mgmt/cluscfg/middletier/standardinfo.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
base/cluster/mgmt/cluscfg/middletier/standardinfo.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
base/cluster/mgmt/cluscfg/middletier/standardinfo.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2000-2001 Microsoft Corporation // // Module Name: // StandardInfo.cpp // // Description: // CStandardInfo implementation. // // Maintained By: // Galen Barbee (GalenB) 02-FEB-2000 // ////////////////////////////////////////////////////////////////////////////// #include "Pch.h" #include "StandardInfo.h" DEFINE_THISCLASS("CStandardInfo") // ************************************************************************ // // Constructor / Destructor // // ************************************************************************ ////////////////////////////////////////////////////////////////////////////// //++ // // HRESULT // CStandardInfo::S_HrCreateInstance( // IUnknown ** ppunkOut // ) // //-- ////////////////////////////////////////////////////////////////////////////// HRESULT CStandardInfo::S_HrCreateInstance( IUnknown ** ppunkOut ) { TraceFunc( "" ); HRESULT hr = S_OK; CStandardInfo * psi = NULL; Assert( ppunkOut != NULL ); if ( ppunkOut == NULL ) { hr = THR( E_POINTER ); goto Cleanup; } psi = new CStandardInfo; if ( psi == NULL ) { hr = THR( E_OUTOFMEMORY ); goto Cleanup; } hr = THR( psi->HrInit() ); if ( FAILED( hr ) ) { goto Cleanup; } hr = THR( psi->TypeSafeQI( IUnknown, ppunkOut ) ); if ( FAILED( hr ) ) { goto Cleanup; } Cleanup: if ( psi != NULL ) { psi->Release(); } HRETURN( hr ); } //*** CStandardInfo::S_HrCreateInstance ////////////////////////////////////////////////////////////////////////////// //++ // // CStandardInfo::CStandardInfo // //-- ////////////////////////////////////////////////////////////////////////////// CStandardInfo::CStandardInfo( void ) : m_cRef( 1 ) { TraceFunc( "" ); InterlockedIncrement( &g_cObjects ); TraceFuncExit(); } //*** CStandardInfo::CStandardInfo ////////////////////////////////////////////////////////////////////////////// //++ // // CStandardInfo::CStandardInfo( // CLSID * pclsidTypeIn, // OBJECTCOOKIE cookieParentIn, // BSTR bstrNameIn // ) // //-- ////////////////////////////////////////////////////////////////////////////// CStandardInfo::CStandardInfo( CLSID * pclsidTypeIn, OBJECTCOOKIE cookieParentIn, BSTR bstrNameIn ) : m_cRef( 1 ) { TraceFunc( "" ); InterlockedIncrement( &g_cObjects ); //THR( HrInit() ); m_clsidType = *pclsidTypeIn; m_cookieParent = cookieParentIn; m_bstrName = bstrNameIn; TraceFuncExit(); } //*** CStandardInfo::CStandardInfo( ... ) ////////////////////////////////////////////////////////////////////////////// //++ // // STDMETHODIMP // CStandardInfo::HrInit( void ) // //-- ////////////////////////////////////////////////////////////////////////////// STDMETHODIMP CStandardInfo::HrInit( void ) { TraceFunc( "" ); HRESULT hr = S_OK; // IUnknown stuff Assert( m_cRef == 1 ); // IStandardInfo Assert( m_clsidType == IID_NULL ); Assert( m_cookieParent == 0 ); Assert( m_bstrName == NULL ); Assert( m_hrStatus == 0 ); Assert( m_pci == NULL ); Assert( m_pExtObjList == NULL ); HRETURN( hr ); } //*** CStandardInfo::HrInit ////////////////////////////////////////////////////////////////////////////// //++ // // CStandardInfo::~CStandardInfo // //-- ////////////////////////////////////////////////////////////////////////////// CStandardInfo::~CStandardInfo( void ) { TraceFunc( "" ); if ( m_bstrName != NULL ) { TraceSysFreeString( m_bstrName ); } if ( m_pci != NULL ) { m_pci->Release(); } while ( m_pExtObjList != NULL ) { ExtObjectEntry * pnext = m_pExtObjList->pNext; m_pExtObjList->punk->Release(); TraceFree( m_pExtObjList ); m_pExtObjList = pnext; } InterlockedDecrement( &g_cObjects ); TraceFuncExit(); } //*** CStandardInfo::~CStandardInfo // ************************************************************************ // // IUnknown // // ************************************************************************ ////////////////////////////////////////////////////////////////////////////// //++ // // CStandardInfo::QueryInterface // // Description: // Query this object for the passed in interface. // // Arguments: // riidIn // Id of interface requested. // // ppvOut // Pointer to the requested interface. // // Return Value: // S_OK // If the interface is available on this object. // // E_NOINTERFACE // If the interface is not available. // // E_POINTER // ppvOut was NULL. // // Remarks: // None. // //-- ////////////////////////////////////////////////////////////////////////////// STDMETHODIMP CStandardInfo::QueryInterface( REFIID riidIn , LPVOID * ppvOut ) { TraceQIFunc( riidIn, ppvOut ); HRESULT hr = S_OK; // // Validate arguments. // Assert( ppvOut != NULL ); if ( ppvOut == NULL ) { hr = THR( E_POINTER ); goto Cleanup; } // // Handle known interfaces. // if ( IsEqualIID( riidIn, IID_IUnknown ) ) { *ppvOut = static_cast< IStandardInfo * >( this ); } // if: IUnknown else if ( IsEqualIID( riidIn, IID_IStandardInfo ) ) { *ppvOut = TraceInterface( __THISCLASS__, IStandardInfo, this, 0 ); } // else if: IStandardInfo else { *ppvOut = NULL; hr = E_NOINTERFACE; } // // Add a reference to the interface if successful. // if ( SUCCEEDED( hr ) ) { ((IUnknown *) *ppvOut)->AddRef(); } // if: success Cleanup: QIRETURN_IGNORESTDMARSHALLING( hr, riidIn ); } //*** CStandardInfo::QueryInterface ////////////////////////////////////////////////////////////////////////////// //++ // // STDMETHODIMP_( ULONG ) // CStandardInfo::AddRef // //-- ////////////////////////////////////////////////////////////////////////////// STDMETHODIMP_( ULONG ) CStandardInfo::AddRef( void ) { TraceFunc( "[IUnknown]" ); InterlockedIncrement( &m_cRef ); CRETURN( m_cRef ); } //*** CStandardInfo::AddRef ////////////////////////////////////////////////////////////////////////////// //++ // // STDMETHODIMP_( ULONG ) // CStandardInfo::Release // //-- ////////////////////////////////////////////////////////////////////////////// STDMETHODIMP_( ULONG ) CStandardInfo::Release( void ) { TraceFunc( "[IUnknown]" ); LONG cRef; cRef = InterlockedDecrement( &m_cRef ); if ( cRef == 0 ) { TraceDo( delete this ); } CRETURN( cRef ); } //*** CStandardInfo::Release //**************************************************************************** // // IStandardInfo // //**************************************************************************** ////////////////////////////////////////////////////////////////////////////// //++ // // STDMETHODIMP // CStandardInfo::GetType( // CLSID * pclsidTypeOut // ) // //-- ////////////////////////////////////////////////////////////////////////////// STDMETHODIMP CStandardInfo::GetType( CLSID * pclsidTypeOut ) { TraceFunc( "[IStandardInfo]" ); HRESULT hr = S_OK; if ( pclsidTypeOut == NULL ) { hr = THR( E_POINTER ); goto Cleanup; } CopyMemory( pclsidTypeOut, &m_clsidType, sizeof( *pclsidTypeOut ) ); Cleanup: HRETURN( hr ); } //*** CStandardInfo::GetType ////////////////////////////////////////////////////////////////////////////// //++ // // STDMETHODIMP // CStandardInfo::GetName( // BSTR * pbstrNameOut // ) // //-- ////////////////////////////////////////////////////////////////////////////// STDMETHODIMP CStandardInfo::GetName( BSTR * pbstrNameOut ) { TraceFunc( "[IStandardInfo]" ); HRESULT hr = S_OK; if ( pbstrNameOut == NULL ) { hr = THR( E_POINTER ); goto Cleanup; } *pbstrNameOut = SysAllocString( m_bstrName ); if ( *pbstrNameOut == NULL ) { hr = THR( E_OUTOFMEMORY ); goto Cleanup; } Cleanup: HRETURN( hr ); } //*** CStandardInfo::GetName ////////////////////////////////////////////////////////////////////////////// //++ // // STDMETHODIMP // CStandardInfo::SetName( // LPCWSTR pcszNameIn // ) // //-- ////////////////////////////////////////////////////////////////////////////// STDMETHODIMP CStandardInfo::SetName( LPCWSTR pcszNameIn ) { TraceFunc1( "[IStandardInfo] pcszNameIn = '%ws'", pcszNameIn == NULL ? L"<null>" : pcszNameIn ); HRESULT hr = S_OK; BSTR bstrNew; if ( pcszNameIn == NULL ) { hr = THR( E_INVALIDARG ); goto Cleanup; } bstrNew = TraceSysAllocString( pcszNameIn ); if ( bstrNew == NULL ) { hr = THR( E_OUTOFMEMORY ); goto Cleanup; } if ( m_bstrName != NULL ) { TraceSysFreeString( m_bstrName ); } m_bstrName = bstrNew; Cleanup: HRETURN( hr ); } //*** CStandardInfo::SetName ////////////////////////////////////////////////////////////////////////////// //++ // // STDMETHODIMP // CStandardInfo::GetParent( // OBJECTCOOKIE * pcookieOut // ) // //-- ////////////////////////////////////////////////////////////////////////////// STDMETHODIMP CStandardInfo::GetParent( OBJECTCOOKIE * pcookieOut ) { TraceFunc( "[IStandardInfo]" ); HRESULT hr = S_OK; if ( pcookieOut == NULL ) { hr = THR( E_POINTER ); goto Cleanup; } *pcookieOut = m_cookieParent; if ( m_cookieParent == NULL ) { hr = S_FALSE; } Cleanup: HRETURN( hr ); } //*** CStandardInfo::GetParent ////////////////////////////////////////////////////////////////////////////// //++ // // STDMETHODIMP // CStandardInfo::GetStatus( // HRESULT * phrOut // ) // //-- ////////////////////////////////////////////////////////////////////////////// STDMETHODIMP CStandardInfo::GetStatus( HRESULT * phrStatusOut ) { TraceFunc( "[IStandardInfo]" ); HRESULT hr = S_OK; if ( phrStatusOut == NULL ) { hr = THR( E_POINTER ); goto Cleanup; } *phrStatusOut = m_hrStatus; Cleanup: HRETURN( hr ); } //*** CStandardInfo::GetStatus ////////////////////////////////////////////////////////////////////////////// //++ // // STDMETHODIMP // CStandardInfo::SetStatus( // HRESULT hrIn // ) // //-- ////////////////////////////////////////////////////////////////////////////// STDMETHODIMP CStandardInfo::SetStatus( HRESULT hrIn ) { TraceFunc1( "[IStandardInfo] hrIn = %#08x", hrIn ); HRESULT hr = S_OK; m_hrStatus = hrIn; HRETURN( hr ); } //*** CStandardInfo::SetStatus
20.804659
101
0.394005
npocmaka
b2d7efd18515f8e01dc39854d0c28429107974a5
595
cpp
C++
Luogu/Float/P1422.cpp
shuye02/C-Algorithms
a2aaf927d8c8e0d89140a34d115ac49c0f489066
[ "MIT" ]
null
null
null
Luogu/Float/P1422.cpp
shuye02/C-Algorithms
a2aaf927d8c8e0d89140a34d115ac49c0f489066
[ "MIT" ]
null
null
null
Luogu/Float/P1422.cpp
shuye02/C-Algorithms
a2aaf927d8c8e0d89140a34d115ac49c0f489066
[ "MIT" ]
null
null
null
// P1422 小玉家的电费 // https://www.luogu.org/problemnew/show/P1422 #include <iostream> using namespace std; int main(){ // Input Quantity int quantity; cin >> quantity; double price; // Calculate Price if(quantity <= 150) { price = quantity * 0.4463; } else if (quantity > 150 && quantity <= 400) { price = 150 * 0.4463 + (quantity - 150) * 0.4663; } else { price = 150 * 0.4463 + (400 - 150) * 0.4663 + (quantity - 400) * 0.5663; } // Round to 10^-1 and Output price = int(price*10 + 0.5) / 10.0; cout << price << endl; }
22.884615
80
0.552941
shuye02
b2d97d40517125fc1248befaaad6c0a416940e92
685
cpp
C++
src/s3/mouse.cpp
sarahkittyy/s3
53a5a06227526f0296f39e03dfb1dc55c66b42e9
[ "MIT" ]
null
null
null
src/s3/mouse.cpp
sarahkittyy/s3
53a5a06227526f0296f39e03dfb1dc55c66b42e9
[ "MIT" ]
null
null
null
src/s3/mouse.cpp
sarahkittyy/s3
53a5a06227526f0296f39e03dfb1dc55c66b42e9
[ "MIT" ]
null
null
null
#include "s3/mouse.hpp" #include <s3/window.hpp> namespace s3 { mouse::mouse(window& w) : m_window(w) { } glm::vec2 mouse::get_pos() { double xp, yp; glfwGetCursorPos(m_window.handle(), &xp, &yp); return glm::vec2(xp, yp); } mouse::state mouse::left_btn() { return (state)glfwGetMouseButton(m_window.handle(), GLFW_MOUSE_BUTTON_LEFT); } mouse::state mouse::right_btn() { return (state)glfwGetMouseButton(m_window.handle(), GLFW_MOUSE_BUTTON_RIGHT); } mouse::state mouse::middle_btn() { return (state)glfwGetMouseButton(m_window.handle(), GLFW_MOUSE_BUTTON_MIDDLE); } mouse::state mouse::btn(button b) { return (state)glfwGetMouseButton(m_window.handle(), (int)b); } }
20.147059
79
0.721168
sarahkittyy
b2da1ed0c332bbec4a9ba6cbbef1684879d0e43e
90,237
cpp
C++
src/plugPikiKando/collInfo.cpp
doldecomp/pikmin
8c8c20721ecb2a19af8e50a4bdebdba90c9a27ed
[ "Unlicense" ]
27
2021-09-28T00:33:11.000Z
2021-11-18T19:38:40.000Z
src/plugPikiKando/collInfo.cpp
doldecomp/pikmin
8c8c20721ecb2a19af8e50a4bdebdba90c9a27ed
[ "Unlicense" ]
null
null
null
src/plugPikiKando/collInfo.cpp
doldecomp/pikmin
8c8c20721ecb2a19af8e50a4bdebdba90c9a27ed
[ "Unlicense" ]
null
null
null
#include "types.h" /* * --INFO-- * Address: ........ * Size: 00009C */ void _Error(char*, ...) { // UNUSED FUNCTION } /* * --INFO-- * Address: ........ * Size: 0000F4 */ void _Print(char*, ...) { // UNUSED FUNCTION } /* * --INFO-- * Address: 80086CC4 * Size: 0002DC */ void Cylinder::get2dDist(Vector3f&) { /* .loc_0x0: mflr r0 stw r0, 0x4(r1) stwu r1, -0x190(r1) stfd f31, 0x188(r1) stfd f30, 0x180(r1) stfd f29, 0x178(r1) stfd f28, 0x170(r1) stfd f27, 0x168(r1) stfd f26, 0x160(r1) stw r31, 0x15C(r1) mr r31, r4 stw r30, 0x158(r1) mr r30, r3 lfs f3, 0x10(r3) lfs f2, 0x4(r3) lfs f1, 0xC(r3) fsubs f30, f3, f2 lfs f0, 0x0(r3) lfs f2, 0x14(r3) fsubs f31, f1, f0 lfs f0, 0x8(r3) fsubs f29, f2, f0 fmr f27, f30 fmr f28, f31 fmr f26, f29 fmuls f0, f27, f27 fmuls f1, f28, f28 fmuls f2, f26, f26 fadds f0, f1, f0 fadds f1, f2, f0 bl -0x790FC lfs f0, -0x75C0(r2) fcmpu cr0, f0, f1 beq- .loc_0x94 fdivs f28, f28, f1 fdivs f27, f27, f1 fdivs f26, f26, f1 .loc_0x94: lfs f8, 0x0(r31) lfs f9, 0x0(r30) lfs f5, 0x8(r31) lfs f6, 0x8(r30) fsubs f0, f8, f9 lfs f4, 0x4(r31) lfs f7, 0x4(r30) fsubs f3, f5, f6 lfs f2, -0x75C0(r2) stfs f0, 0xC0(r1) fsubs f0, f4, f7 fmuls f4, f26, f3 lfs f3, 0xC0(r1) fmuls f0, f27, f0 fmuls f3, f28, f3 fadds f0, f3, f0 fadds f0, f4, f0 fdivs f3, f0, f1 fcmpo cr0, f3, f2 bge- .loc_0x15C fsubs f0, f6, f5 fsubs f1, f9, f8 fmuls f0, f0, f0 fmuls f1, f1, f1 fadds f1, f1, f0 fcmpo cr0, f1, f2 ble- .loc_0x2AC fsqrte f2, f1 lfd f4, -0x75B8(r2) lfd f3, -0x75B0(r2) fmul f0, f2, f2 fmul f2, f4, f2 fmul f0, f1, f0 fsub f0, f3, f0 fmul f2, f2, f0 fmul f0, f2, f2 fmul f2, f4, f2 fmul f0, f1, f0 fsub f0, f3, f0 fmul f2, f2, f0 fmul f0, f2, f2 fmul f2, f4, f2 fmul f0, f1, f0 fsub f0, f3, f0 fmul f0, f2, f0 fmul f0, f1, f0 frsp f0, f0 stfs f0, 0xBC(r1) lfs f1, 0xBC(r1) b .loc_0x2AC .loc_0x15C: lfs f0, -0x75A8(r2) fcmpo cr0, f3, f0 ble- .loc_0x1E8 lfs f1, 0x14(r30) lfs f0, 0xC(r30) fsubs f1, f1, f5 fsubs f3, f0, f8 fmuls f0, f1, f1 fmuls f1, f3, f3 fadds f1, f1, f0 fcmpo cr0, f1, f2 ble- .loc_0x2AC fsqrte f2, f1 lfd f4, -0x75B8(r2) lfd f3, -0x75B0(r2) fmul f0, f2, f2 fmul f2, f4, f2 fmul f0, f1, f0 fsub f0, f3, f0 fmul f2, f2, f0 fmul f0, f2, f2 fmul f2, f4, f2 fmul f0, f1, f0 fsub f0, f3, f0 fmul f2, f2, f0 fmul f0, f2, f2 fmul f2, f4, f2 fmul f0, f1, f0 fsub f0, f3, f0 fmul f0, f2, f0 fmul f0, f1, f0 frsp f0, f0 stfs f0, 0xB8(r1) lfs f1, 0xB8(r1) b .loc_0x2AC .loc_0x1E8: fmuls f2, f29, f3 addi r6, r1, 0x94 fmuls f1, f30, f3 addi r5, r1, 0x90 fmuls f0, f31, f3 stfs f2, 0x94(r1) addi r4, r1, 0x8C addi r3, r1, 0xCC stfs f1, 0x90(r1) stfs f0, 0x8C(r1) bl -0x4FDB8 lfs f3, 0xD4(r1) lfs f2, 0x8(r30) lfs f1, 0xCC(r1) fadds f4, f3, f2 lfs f0, 0x0(r30) lfs f3, 0x8(r31) fadds f2, f1, f0 lfs f1, 0x0(r31) fsubs f3, f4, f3 lfs f0, -0x75C0(r2) fsubs f2, f2, f1 fmuls f1, f3, f3 fmuls f2, f2, f2 fadds f1, f2, f1 fcmpo cr0, f1, f0 ble- .loc_0x2AC fsqrte f2, f1 lfd f4, -0x75B8(r2) lfd f3, -0x75B0(r2) fmul f0, f2, f2 fmul f2, f4, f2 fmul f0, f1, f0 fsub f0, f3, f0 fmul f2, f2, f0 fmul f0, f2, f2 fmul f2, f4, f2 fmul f0, f1, f0 fsub f0, f3, f0 fmul f2, f2, f0 fmul f0, f2, f2 fmul f2, f4, f2 fmul f0, f1, f0 fsub f0, f3, f0 fmul f0, f2, f0 fmul f0, f1, f0 frsp f0, f0 stfs f0, 0xB0(r1) lfs f1, 0xB0(r1) .loc_0x2AC: lwz r0, 0x194(r1) lfd f31, 0x188(r1) lfd f30, 0x180(r1) lfd f29, 0x178(r1) lfd f28, 0x170(r1) lfd f27, 0x168(r1) lfd f26, 0x160(r1) lwz r31, 0x15C(r1) lwz r30, 0x158(r1) addi r1, r1, 0x190 mtlr r0 blr */ } /* * --INFO-- * Address: 80086FA0 * Size: 0003C0 */ void Cylinder::collide(const Sphere&, Vector3f&, float&) { /* .loc_0x0: mflr r0 stw r0, 0x4(r1) stwu r1, -0x190(r1) stfd f31, 0x188(r1) stfd f30, 0x180(r1) stfd f29, 0x178(r1) stfd f28, 0x170(r1) stfd f27, 0x168(r1) stfd f26, 0x160(r1) stw r31, 0x15C(r1) mr r31, r6 stw r30, 0x158(r1) mr r30, r5 stw r29, 0x154(r1) mr r29, r4 stw r28, 0x150(r1) mr r28, r3 lfs f3, 0x10(r3) lfs f2, 0x4(r3) lfs f1, 0xC(r3) fsubs f27, f3, f2 lfs f0, 0x0(r3) lfs f2, 0x14(r3) fsubs f28, f1, f0 lfs f0, 0x8(r3) fsubs f26, f2, f0 fmr f30, f27 fmr f31, f28 fmr f29, f26 fmuls f0, f30, f30 fmuls f1, f31, f31 fadds f0, f1, f0 fmuls f1, f29, f29 fadds f1, f1, f0 bl -0x793E8 lfs f0, -0x75C0(r2) fcmpu cr0, f0, f1 beq- .loc_0xA4 fdivs f31, f31, f1 fdivs f30, f30, f1 fdivs f29, f29, f1 .loc_0xA4: lfs f3, 0x0(r29) addi r6, r1, 0x88 lfs f0, 0x0(r28) addi r5, r1, 0x84 lfs f2, -0x75A4(r2) fsubs f3, f3, f0 lfs f0, -0x75C0(r2) fmuls f5, f2, f1 addi r4, r1, 0x80 addi r3, r1, 0xF0 stfs f3, 0xC4(r1) lfs f6, 0xC4(r1) lfs f4, 0x4(r29) lfs f3, 0x4(r28) fmuls f6, f31, f6 lfs f8, 0x8(r29) fsubs f3, f4, f3 lfs f7, 0x8(r28) lfs f4, 0xC(r29) fsubs f7, f8, f7 stfs f0, 0x12C(r1) fmuls f3, f30, f3 stfs f0, 0x128(r1) fmuls f7, f29, f7 stfs f0, 0x124(r1) fadds f0, f6, f3 fadds f0, f7, f0 fdivs f29, f0, f1 fsubs f0, f29, f2 fmuls f3, f26, f29 fmuls f2, f27, f29 fabs f6, f0 fmuls f0, f28, f29 stfs f3, 0x88(r1) fmuls f1, f1, f6 stfs f2, 0x84(r1) stfs f0, 0x80(r1) fsubs f0, f1, f4 fsubs f30, f5, f0 bl -0x4FFC4 lfs f2, 0xF0(r1) lfs f1, 0x0(r28) lfs f0, 0x0(r29) fadds f1, f2, f1 lfs f3, 0x8(r28) lfs f4, 0xF8(r1) lfs f2, 0x4(r28) fsubs f0, f1, f0 lfs f1, 0xF4(r1) fadds f3, f4, f3 stfs f0, 0x124(r1) fadds f1, f1, f2 lfs f0, 0x4(r29) fsubs f0, f1, f0 stfs f0, 0x128(r1) lfs f0, 0x8(r29) fsubs f0, f3, f0 stfs f0, 0x12C(r1) lfs f1, 0x124(r1) lfs f0, 0x128(r1) fmuls f2, f1, f1 lfs f3, 0x12C(r1) fmuls f1, f0, f0 lfs f0, -0x75C0(r2) fmuls f3, f3, f3 fadds f1, f2, f1 fadds f4, f3, f1 fcmpo cr0, f4, f0 ble- .loc_0x210 fsqrte f1, f4 lfd f3, -0x75B8(r2) lfd f2, -0x75B0(r2) fmul f0, f1, f1 fmul f1, f3, f1 fmul f0, f4, f0 fsub f0, f2, f0 fmul f1, f1, f0 fmul f0, f1, f1 fmul f1, f3, f1 fmul f0, f4, f0 fsub f0, f2, f0 fmul f1, f1, f0 fmul f0, f1, f1 fmul f1, f3, f1 fmul f0, f4, f0 fsub f0, f2, f0 fmul f0, f1, f0 fmul f0, f4, f0 frsp f0, f0 stfs f0, 0x90(r1) lfs f4, 0x90(r1) .loc_0x210: lfs f0, -0x75C0(r2) lfs f2, 0xC(r29) lfs f1, 0x18(r28) fcmpo cr0, f30, f0 fadds f1, f2, f1 fsubs f31, f1, f4 cror 2, 0x1, 0x2 bne- .loc_0x298 fcmpo cr0, f30, f31 bge- .loc_0x298 fcmpo cr0, f31, f0 cror 2, 0x1, 0x2 bne- .loc_0x298 lfs f0, -0x75A4(r2) fcmpo cr0, f29, f0 bge- .loc_0x254 fneg f30, f30 .loc_0x254: fmuls f2, f28, f30 li r3, 0x1 fmuls f1, f27, f30 fmuls f0, f26, f30 stfs f2, 0xAC(r1) lfs f2, 0xAC(r1) stfs f2, 0xE4(r1) stfs f1, 0xE8(r1) stfs f0, 0xEC(r1) lwz r4, 0xE4(r1) lwz r0, 0xE8(r1) stw r4, 0x0(r30) stw r0, 0x4(r30) lwz r0, 0xEC(r1) stw r0, 0x8(r30) stfs f29, 0x0(r31) b .loc_0x388 .loc_0x298: lfs f1, -0x75C0(r2) fcmpo cr0, f29, f1 cror 2, 0x1, 0x2 bne- .loc_0x384 lfs f0, -0x75A8(r2) fcmpo cr0, f29, f0 cror 2, 0, 0x2 bne- .loc_0x384 fcmpo cr0, f31, f1 cror 2, 0x1, 0x2 bne- .loc_0x384 lwz r3, 0x124(r1) lwz r0, 0x128(r1) stw r3, 0x0(r30) stw r0, 0x4(r30) lwz r0, 0x12C(r1) stw r0, 0x8(r30) lfs f1, 0x0(r30) lfs f0, 0x4(r30) lfs f2, 0x8(r30) fmuls f1, f1, f1 fmuls f0, f0, f0 fmuls f2, f2, f2 fadds f0, f1, f0 fadds f1, f2, f0 bl -0x7965C lfs f0, -0x75C0(r2) fcmpu cr0, f0, f1 beq- .loc_0x330 lfs f0, 0x0(r30) fdivs f0, f0, f1 stfs f0, 0x0(r30) lfs f0, 0x4(r30) fdivs f0, f0, f1 stfs f0, 0x4(r30) lfs f0, 0x8(r30) fdivs f0, f0, f1 stfs f0, 0x8(r30) .loc_0x330: fneg f1, f31 lfs f0, 0x0(r30) li r3, 0x1 fmuls f0, f0, f1 stfs f0, 0x9C(r1) lfs f0, 0x9C(r1) stfs f0, 0xD8(r1) lfs f0, 0x4(r30) fmuls f0, f0, f1 stfs f0, 0xDC(r1) lfs f0, 0x8(r30) fmuls f0, f0, f1 stfs f0, 0xE0(r1) lwz r4, 0xD8(r1) lwz r0, 0xDC(r1) stw r4, 0x0(r30) stw r0, 0x4(r30) lwz r0, 0xE0(r1) stw r0, 0x8(r30) stfs f29, 0x0(r31) b .loc_0x388 .loc_0x384: li r3, 0 .loc_0x388: lwz r0, 0x194(r1) lfd f31, 0x188(r1) lfd f30, 0x180(r1) lfd f29, 0x178(r1) lfd f28, 0x170(r1) lfd f27, 0x168(r1) lfd f26, 0x160(r1) lwz r31, 0x15C(r1) lwz r30, 0x158(r1) lwz r29, 0x154(r1) lwz r28, 0x150(r1) addi r1, r1, 0x190 mtlr r0 blr */ } /* * --INFO-- * Address: 80087360 * Size: 00002C */ void Tube::getYRatio(float) { /* .loc_0x0: lfs f2, 0x10(r3) lfs f3, 0x4(r3) lfs f0, -0x75C0(r2) fsubs f2, f2, f3 fcmpu cr0, f0, f2 beq- .loc_0x24 fsubs f0, f1, f3 fdivs f1, f0, f2 blr .loc_0x24: lfs f1, -0x75A0(r2) blr */ } /* * --INFO-- * Address: 8008738C * Size: 00033C */ void Tube::collide(const Sphere&, Vector3f&, float&) { /* .loc_0x0: mflr r0 stw r0, 0x4(r1) stwu r1, -0x178(r1) stfd f31, 0x170(r1) stfd f30, 0x168(r1) stfd f29, 0x160(r1) stfd f28, 0x158(r1) stfd f27, 0x150(r1) stfd f26, 0x148(r1) stw r31, 0x144(r1) mr r31, r6 stw r30, 0x140(r1) mr r30, r5 stw r29, 0x13C(r1) mr r29, r4 stw r28, 0x138(r1) mr r28, r3 lfs f3, 0x10(r3) lfs f2, 0x4(r3) lfs f1, 0xC(r3) fsubs f27, f3, f2 lfs f0, 0x0(r3) lfs f2, 0x14(r3) fsubs f28, f1, f0 lfs f0, 0x8(r3) fsubs f26, f2, f0 fmr f30, f27 fmr f31, f28 fmr f29, f26 fmuls f0, f30, f30 fmuls f1, f31, f31 fadds f0, f1, f0 fmuls f1, f29, f29 fadds f1, f1, f0 bl -0x797D4 lfs f0, -0x75C0(r2) fcmpu cr0, f0, f1 beq- .loc_0xA4 fdivs f31, f31, f1 fdivs f30, f30, f1 fdivs f29, f29, f1 .loc_0xA4: lfs f2, 0x0(r29) addi r6, r1, 0x80 lfs f0, 0x0(r28) addi r5, r1, 0x7C addi r4, r1, 0x78 fsubs f2, f2, f0 lfs f0, -0x75C0(r2) addi r3, r1, 0xD0 stfs f2, 0xB0(r1) lfs f3, 0x4(r29) lfs f2, 0x4(r28) lfs f4, 0xB0(r1) fsubs f2, f3, f2 lfs f6, 0x8(r29) lfs f5, 0x8(r28) fmuls f3, f31, f4 fsubs f4, f6, f5 fmuls f2, f30, f2 stfs f0, 0x110(r1) stfs f0, 0x10C(r1) fmuls f4, f29, f4 fadds f2, f3, f2 stfs f0, 0x108(r1) fadds f0, f4, f2 fdivs f29, f0, f1 fmuls f2, f26, f29 fmuls f1, f27, f29 fmuls f0, f28, f29 stfs f2, 0x80(r1) stfs f1, 0x7C(r1) stfs f0, 0x78(r1) bl -0x50390 lfs f2, 0xD0(r1) lfs f1, 0x0(r28) lfs f0, 0x0(r29) fadds f1, f2, f1 lfs f3, 0x8(r28) lfs f4, 0xD8(r1) lfs f2, 0x4(r28) fsubs f0, f1, f0 lfs f1, 0xD4(r1) fadds f3, f4, f3 stfs f0, 0x108(r1) fadds f1, f1, f2 lfs f0, 0x4(r29) fsubs f0, f1, f0 stfs f0, 0x10C(r1) lfs f0, 0x8(r29) fsubs f0, f3, f0 stfs f0, 0x110(r1) lfs f1, 0x108(r1) lfs f0, 0x10C(r1) fmuls f2, f1, f1 lfs f3, 0x110(r1) fmuls f1, f0, f0 lfs f0, -0x75C0(r2) fmuls f3, f3, f3 fadds f1, f2, f1 fadds f6, f3, f1 fcmpo cr0, f6, f0 ble- .loc_0x1F0 fsqrte f1, f6 lfd f3, -0x75B8(r2) lfd f2, -0x75B0(r2) fmul f0, f1, f1 fmul f1, f3, f1 fmul f0, f6, f0 fsub f0, f2, f0 fmul f1, f1, f0 fmul f0, f1, f1 fmul f1, f3, f1 fmul f0, f6, f0 fsub f0, f2, f0 fmul f1, f1, f0 fmul f0, f1, f1 fmul f1, f3, f1 fmul f0, f6, f0 fsub f0, f2, f0 fmul f0, f1, f0 fmul f0, f6, f0 frsp f0, f0 stfs f0, 0x88(r1) lfs f6, 0x88(r1) .loc_0x1F0: lfs f4, -0x75A8(r2) lfs f1, 0x1C(r28) fsubs f3, f4, f29 lfs f2, 0x18(r28) lfs f0, -0x75C0(r2) fmuls f1, f1, f29 lfs f5, 0xC(r29) fmuls f2, f3, f2 fcmpo cr0, f29, f0 fadds f1, f2, f1 fadds f1, f5, f1 cror 2, 0x1, 0x2 fsubs f26, f1, f6 bne- .loc_0x300 fcmpo cr0, f29, f4 cror 2, 0, 0x2 bne- .loc_0x300 fcmpo cr0, f26, f0 cror 2, 0x1, 0x2 bne- .loc_0x300 lwz r3, 0x108(r1) lwz r0, 0x10C(r1) stw r3, 0x0(r30) stw r0, 0x4(r30) lwz r0, 0x110(r1) stw r0, 0x8(r30) lfs f1, 0x0(r30) lfs f0, 0x4(r30) lfs f2, 0x8(r30) fmuls f1, f1, f1 fmuls f0, f0, f0 fmuls f2, f2, f2 fadds f0, f1, f0 fadds f1, f2, f0 bl -0x799C4 lfs f0, -0x75C0(r2) fcmpu cr0, f0, f1 beq- .loc_0x2AC lfs f0, 0x0(r30) fdivs f0, f0, f1 stfs f0, 0x0(r30) lfs f0, 0x4(r30) fdivs f0, f0, f1 stfs f0, 0x4(r30) lfs f0, 0x8(r30) fdivs f0, f0, f1 stfs f0, 0x8(r30) .loc_0x2AC: fneg f1, f26 lfs f0, 0x0(r30) li r3, 0x1 fmuls f0, f0, f1 stfs f0, 0x94(r1) lfs f0, 0x94(r1) stfs f0, 0xC4(r1) lfs f0, 0x4(r30) fmuls f0, f0, f1 stfs f0, 0xC8(r1) lfs f0, 0x8(r30) fmuls f0, f0, f1 stfs f0, 0xCC(r1) lwz r4, 0xC4(r1) lwz r0, 0xC8(r1) stw r4, 0x0(r30) stw r0, 0x4(r30) lwz r0, 0xCC(r1) stw r0, 0x8(r30) stfs f29, 0x0(r31) b .loc_0x304 .loc_0x300: li r3, 0 .loc_0x304: lwz r0, 0x17C(r1) lfd f31, 0x170(r1) lfd f30, 0x168(r1) lfd f29, 0x160(r1) lfd f28, 0x158(r1) lfd f27, 0x150(r1) lfd f26, 0x148(r1) lwz r31, 0x144(r1) lwz r30, 0x140(r1) lwz r29, 0x13C(r1) lwz r28, 0x138(r1) addi r1, r1, 0x178 mtlr r0 blr */ } /* * --INFO-- * Address: 800876C8 * Size: 0000E4 */ void Cylinder::getPosRatio(const Vector3f&) { /* .loc_0x0: mflr r0 stw r0, 0x4(r1) stwu r1, -0xC0(r1) stfd f31, 0xB8(r1) stfd f30, 0xB0(r1) stfd f29, 0xA8(r1) stw r31, 0xA4(r1) mr r31, r4 stw r30, 0xA0(r1) mr r30, r3 lfs f3, 0xC(r3) lfs f2, 0x0(r3) lfs f1, 0x10(r3) lfs f0, 0x4(r3) fsubs f31, f3, f2 lfs f2, 0x14(r3) fsubs f30, f1, f0 lfs f0, 0x8(r3) fmuls f1, f31, f31 fsubs f29, f2, f0 fmuls f0, f30, f30 fmuls f2, f29, f29 fadds f0, f1, f0 fadds f1, f2, f0 bl -0x79AE8 lfs f0, -0x75C0(r2) fcmpu cr0, f0, f1 beq- .loc_0x7C fdivs f31, f31, f1 fdivs f30, f30, f1 fdivs f29, f29, f1 .loc_0x7C: lfs f2, 0x0(r31) lfs f0, 0x0(r30) fsubs f0, f2, f0 stfs f0, 0x54(r1) lfs f2, 0x4(r31) lfs f0, 0x4(r30) lfs f3, 0x54(r1) fsubs f0, f2, f0 lfs f5, 0x8(r31) lfs f4, 0x8(r30) fmuls f2, f31, f3 fsubs f3, f5, f4 fmuls f0, f30, f0 fmuls f3, f29, f3 fadds f0, f2, f0 fadds f0, f3, f0 fdivs f1, f0, f1 lwz r0, 0xC4(r1) lfd f31, 0xB8(r1) lfd f30, 0xB0(r1) lfd f29, 0xA8(r1) lwz r31, 0xA4(r1) lwz r30, 0xA0(r1) addi r1, r1, 0xC0 mtlr r0 blr */ } /* * --INFO-- * Address: 800877AC * Size: 0000E4 */ void Tube::getPosRatio(const Vector3f&) { /* .loc_0x0: mflr r0 stw r0, 0x4(r1) stwu r1, -0xC0(r1) stfd f31, 0xB8(r1) stfd f30, 0xB0(r1) stfd f29, 0xA8(r1) stw r31, 0xA4(r1) mr r31, r4 stw r30, 0xA0(r1) mr r30, r3 lfs f3, 0xC(r3) lfs f2, 0x0(r3) lfs f1, 0x10(r3) lfs f0, 0x4(r3) fsubs f31, f3, f2 lfs f2, 0x14(r3) fsubs f30, f1, f0 lfs f0, 0x8(r3) fmuls f1, f31, f31 fsubs f29, f2, f0 fmuls f0, f30, f30 fmuls f2, f29, f29 fadds f0, f1, f0 fadds f1, f2, f0 bl -0x79BCC lfs f0, -0x75C0(r2) fcmpu cr0, f0, f1 beq- .loc_0x7C fdivs f31, f31, f1 fdivs f30, f30, f1 fdivs f29, f29, f1 .loc_0x7C: lfs f2, 0x0(r31) lfs f0, 0x0(r30) fsubs f0, f2, f0 stfs f0, 0x54(r1) lfs f2, 0x4(r31) lfs f0, 0x4(r30) lfs f3, 0x54(r1) fsubs f0, f2, f0 lfs f5, 0x8(r31) lfs f4, 0x8(r30) fmuls f2, f31, f3 fsubs f3, f5, f4 fmuls f0, f30, f0 fmuls f3, f29, f3 fadds f0, f2, f0 fadds f0, f3, f0 fdivs f1, f0, f1 lwz r0, 0xC4(r1) lfd f31, 0xB8(r1) lfd f30, 0xB0(r1) lfd f29, 0xA8(r1) lwz r31, 0xA4(r1) lwz r30, 0xA0(r1) addi r1, r1, 0xC0 mtlr r0 blr */ } /* * --INFO-- * Address: ........ * Size: 000020 */ void Tube::getRatioRadius(float) { // UNUSED FUNCTION } /* * --INFO-- * Address: 80087890 * Size: 000238 */ void Tube::getPosGradient(Vector3f&, float, Vector3f&, Vector3f&) { /* .loc_0x0: mflr r0 stw r0, 0x4(r1) stwu r1, -0x170(r1) stfd f31, 0x168(r1) stfd f30, 0x160(r1) stfd f29, 0x158(r1) stfd f28, 0x150(r1) stfd f27, 0x148(r1) stfd f26, 0x140(r1) stfd f25, 0x138(r1) fmr f25, f1 stw r31, 0x134(r1) addi r31, r6, 0 stw r30, 0x130(r1) addi r30, r5, 0 stw r29, 0x12C(r1) addi r29, r4, 0 stw r28, 0x128(r1) addi r28, r3, 0 addi r4, r28, 0 addi r3, r1, 0xEC bl .loc_0x238 lfs f26, 0xEC(r1) lfs f1, 0x0(r29) lfs f27, 0xF0(r1) lfs f0, 0x4(r29) fsubs f31, f1, f26 lfs f28, 0xF4(r1) fsubs f30, f0, f27 lfs f0, 0x8(r29) fmuls f1, f31, f31 fsubs f29, f0, f28 fmuls f0, f30, f30 fmuls f2, f29, f29 fadds f0, f1, f0 fadds f1, f2, f0 bl -0x79CE0 lfs f0, -0x75C0(r2) fcmpu cr0, f0, f1 beq- .loc_0xAC fdivs f31, f31, f1 fdivs f30, f30, f1 fdivs f29, f29, f1 .loc_0xAC: lfs f4, 0x1C(r28) addi r6, r1, 0x6C lfs f1, -0x75A8(r2) addi r5, r1, 0x68 fmuls f0, f29, f4 lfs f3, 0x18(r28) fsubs f2, f1, f25 fmuls f1, f4, f25 addi r4, r1, 0x64 stfs f0, 0x6C(r1) fmuls f2, f3, f2 addi r3, r1, 0xC8 lfs f0, 0x1C(r28) fadds f25, f2, f1 fmuls f0, f30, f0 stfs f0, 0x68(r1) lfs f0, 0x1C(r28) fmuls f0, f31, f0 stfs f0, 0x64(r1) bl -0x5086C fmuls f2, f31, f25 lfs f8, 0x14(r28) fmuls f1, f30, f25 lfs f7, 0xD0(r1) fmuls f0, f29, f25 fadds f2, f26, f2 lfs f6, 0x10(r28) lfs f4, 0xC(r28) fadds f1, f27, f1 lfs f5, 0xCC(r1) stfs f2, 0x94(r1) fadds f0, f28, f0 lfs f3, 0xC8(r1) fadds f5, f6, f5 lfs f2, 0x94(r1) fadds f3, f4, f3 stfs f2, 0xBC(r1) fadds f2, f8, f7 stfs f1, 0xC0(r1) stfs f0, 0xC4(r1) lwz r3, 0xBC(r1) lwz r0, 0xC0(r1) stw r3, 0x0(r30) stw r0, 0x4(r30) lwz r0, 0xC4(r1) stw r0, 0x8(r30) lfs f0, 0x0(r30) fsubs f0, f3, f0 stfs f0, 0x88(r1) lfs f0, 0x88(r1) stfs f0, 0xB0(r1) lfs f0, 0x4(r30) fsubs f0, f5, f0 stfs f0, 0xB4(r1) lfs f0, 0x8(r30) fsubs f0, f2, f0 stfs f0, 0xB8(r1) lwz r3, 0xB0(r1) lwz r0, 0xB4(r1) stw r3, 0x0(r31) stw r0, 0x4(r31) lwz r0, 0xB8(r1) stw r0, 0x8(r31) lfs f1, 0x0(r31) lfs f0, 0x4(r31) lfs f2, 0x8(r31) fmuls f1, f1, f1 fmuls f0, f0, f0 fmuls f2, f2, f2 fadds f0, f1, f0 fadds f1, f2, f0 bl -0x79E18 lfs f0, -0x75C0(r2) fcmpu cr0, f0, f1 beq- .loc_0x1FC lfs f0, 0x0(r31) fdivs f0, f0, f1 stfs f0, 0x0(r31) lfs f0, 0x4(r31) fdivs f0, f0, f1 stfs f0, 0x4(r31) lfs f0, 0x8(r31) fdivs f0, f0, f1 stfs f0, 0x8(r31) .loc_0x1FC: lwz r0, 0x174(r1) lfd f31, 0x168(r1) lfd f30, 0x160(r1) lfd f29, 0x158(r1) lfd f28, 0x150(r1) lfd f27, 0x148(r1) lfd f26, 0x140(r1) lfd f25, 0x138(r1) lwz r31, 0x134(r1) lwz r30, 0x130(r1) lwz r29, 0x12C(r1) lwz r28, 0x128(r1) addi r1, r1, 0x170 mtlr r0 blr .loc_0x238: */ } /* * --INFO-- * Address: 80087AC8 * Size: 0000F8 */ void Tube::setPos(float) { /* .loc_0x0: mflr r0 stw r0, 0x4(r1) stwu r1, -0x88(r1) stfd f31, 0x80(r1) addi r0, r1, 0x28 addi r6, r1, 0x30 stfd f30, 0x78(r1) addi r5, r1, 0x2C stfd f29, 0x70(r1) stfd f28, 0x68(r1) fmr f28, f1 stw r31, 0x64(r1) addi r31, r3, 0 addi r3, r1, 0x38 lfs f30, 0x8(r4) lfs f0, 0x14(r4) lfs f29, 0x0(r4) fsubs f0, f0, f30 lfs f31, 0x4(r4) stfs f0, 0x30(r1) lfs f1, 0x10(r4) lfs f0, 0x4(r4) fsubs f0, f1, f0 stfs f0, 0x2C(r1) lfs f1, 0xC(r4) lfs f0, 0x0(r4) mr r4, r0 fsubs f0, f1, f0 stfs f0, 0x28(r1) bl -0x50A20 lfs f2, 0x40(r1) addi r6, r1, 0x24 lfs f1, 0x3C(r1) addi r5, r1, 0x20 lfs f0, 0x38(r1) fmuls f2, f2, f28 addi r4, r1, 0x1C fmuls f1, f1, f28 addi r3, r1, 0x44 fmuls f0, f0, f28 stfs f2, 0x24(r1) stfs f1, 0x20(r1) stfs f0, 0x1C(r1) bl -0x50A58 lfs f0, 0x44(r1) lfs f1, 0x48(r1) fadds f0, f29, f0 lfs f2, 0x4C(r1) fadds f3, f31, f1 fadds f1, f30, f2 stfs f0, 0x0(r31) stfs f3, 0x4(r31) stfs f1, 0x8(r31) lwz r0, 0x8C(r1) lfd f31, 0x80(r1) lfd f30, 0x78(r1) lfd f29, 0x70(r1) lfd f28, 0x68(r1) lwz r31, 0x64(r1) addi r1, r1, 0x88 mtlr r0 blr */ } /* * --INFO-- * Address: ........ * Size: 00007C */ void CollPartUpdater::updateCollPart(CollPart*) { // UNUSED FUNCTION } /* * --INFO-- * Address: 80087BC0 * Size: 000124 */ void CollPart::isStickable() { /* .loc_0x0: mflr r0 stw r0, 0x4(r1) stwu r1, -0x50(r1) stw r31, 0x4C(r1) mr r31, r3 lbz r0, 0x51(r3) cmplwi r0, 0 bne- .loc_0x28 li r3, 0 b .loc_0x110 .loc_0x28: lbz r3, 0x5C(r31) cmplwi r3, 0x3 bne- .loc_0xB4 addi r3, r1, 0x3C addi r4, r31, 0 bl 0x2E0 lis r4, 0x632A addi r3, r1, 0x3C addi r4, r4, 0x2A2A li r5, 0x2A bl -0x43D28 rlwinm. r0,r3,0,24,31 beq- .loc_0x7C addi r3, r1, 0x30 addi r4, r31, 0 bl 0x2B8 addi r3, r1, 0x24 addi r4, r31, 0 bl 0x270 li r3, 0 b .loc_0x110 .loc_0x7C: addi r3, r1, 0x18 addi r4, r31, 0 bl 0x298 lis r4, 0x732A addi r3, r1, 0x18 addi r4, r4, 0x2A2A li r5, 0x2A bl -0x43D70 rlwinm. r0,r3,0,24,31 bne- .loc_0xAC li r3, 0 b .loc_0x110 .loc_0xAC: li r3, 0x1 b .loc_0x110 .loc_0xB4: subi r0, r3, 0x5 rlwinm r0,r0,0,24,31 cmplwi r0, 0x1 li r0, 0x1 ble- .loc_0xCC li r0, 0 .loc_0xCC: rlwinm. r0,r0,0,24,31 bne- .loc_0xDC cmplwi r3, 0 bne- .loc_0x10C .loc_0xDC: addi r3, r1, 0xC addi r4, r31, 0 bl 0x238 lis r4, 0x732A addi r3, r1, 0xC addi r4, r4, 0x2A2A li r5, 0x2A bl -0x43DD0 rlwinm. r0,r3,0,24,31 beq- .loc_0x10C li r3, 0x1 b .loc_0x110 .loc_0x10C: li r3, 0 .loc_0x110: lwz r0, 0x54(r1) lwz r31, 0x4C(r1) addi r1, r1, 0x50 mtlr r0 blr */ } /* * --INFO-- * Address: 80087CE4 * Size: 00005C */ void CollPart::isClimbable() { /* .loc_0x0: mflr r0 mr r4, r3 stw r0, 0x4(r1) stwu r1, -0x18(r1) lbz r0, 0x5C(r3) cmplwi r0, 0x3 bne- .loc_0x48 addi r3, r1, 0xC bl 0x1D8 lis r4, 0x632A addi r3, r1, 0xC addi r4, r4, 0x2A2A li r5, 0x2A bl -0x43E30 rlwinm. r0,r3,0,24,31 beq- .loc_0x48 li r3, 0x1 b .loc_0x4C .loc_0x48: li r3, 0 .loc_0x4C: lwz r0, 0x1C(r1) addi r1, r1, 0x18 mtlr r0 blr */ } /* * --INFO-- * Address: ........ * Size: 000008 */ void CollPart::isDamagable() { // UNUSED FUNCTION } /* * --INFO-- * Address: 80087D40 * Size: 000050 */ void CollPart::isBouncy() { /* .loc_0x0: mflr r0 addi r4, r3, 0 stw r0, 0x4(r1) stwu r1, -0x18(r1) addi r3, r1, 0xC bl 0x188 lis r4, 0x622A addi r3, r1, 0xC addi r4, r4, 0x2A2A li r5, 0x2A bl -0x43E80 rlwinm. r0,r3,0,24,31 beq- .loc_0x3C li r3, 0x1 b .loc_0x40 .loc_0x3C: li r3, 0 .loc_0x40: lwz r0, 0x1C(r1) addi r1, r1, 0x18 mtlr r0 blr */ } /* * --INFO-- * Address: 80087D90 * Size: 000034 */ void CollPart::getChildCount() { /* .loc_0x0: mflr r0 stw r0, 0x4(r1) stwu r1, -0x8(r1) lwz r3, 0x58(r3) cmplwi r3, 0 beq- .loc_0x20 bl -0x47728 b .loc_0x24 .loc_0x20: li r3, -0x1 .loc_0x24: lwz r0, 0xC(r1) addi r1, r1, 0x8 mtlr r0 blr */ } /* * --INFO-- * Address: 80087DC4 * Size: 000028 */ void CollPart::getChild() { /* .loc_0x0: lha r0, 0x54(r3) cmpwi r0, -0x1 beq- .loc_0x20 lwz r3, 0x60(r3) mulli r0, r0, 0x68 lwz r3, 0x4(r3) add r3, r3, r0 blr .loc_0x20: li r3, 0 blr */ } /* * --INFO-- * Address: 80087DEC * Size: 00005C */ void CollPart::getChildAt(int) { /* .loc_0x0: cmpwi r4, 0 lha r0, 0x54(r3) mtctr r4 ble- .loc_0x38 .loc_0x10: cmpwi r0, -0x1 bne- .loc_0x20 li r3, 0 blr .loc_0x20: mulli r4, r0, 0x68 lwz r5, 0x60(r3) lwz r5, 0x4(r5) addi r0, r4, 0x52 lhax r0, r5, r0 bdnz+ .loc_0x10 .loc_0x38: cmpwi r0, -0x1 bne- .loc_0x48 li r3, 0 blr .loc_0x48: lwz r3, 0x60(r3) mulli r0, r0, 0x68 lwz r3, 0x4(r3) add r3, r3, r0 blr */ } /* * --INFO-- * Address: ........ * Size: 000028 */ void CollPart::getNext() { // UNUSED FUNCTION } /* * --INFO-- * Address: 80087E48 * Size: 00003C */ CollPart::CollPart() { /* .loc_0x0: lfs f0, -0x75C0(r2) li r5, 0x1 li r4, -0x1 stfs f0, 0xC(r3) li r0, 0 stfs f0, 0x8(r3) stfs f0, 0x4(r3) stb r5, 0x50(r3) sth r4, 0x54(r3) sth r4, 0x52(r3) stw r0, 0x58(r3) stw r0, 0x60(r3) stw r0, 0x64(r3) stb r5, 0x51(r3) blr */ } /* * --INFO-- * Address: 80087E84 * Size: 00001C */ void CollPart::getTypeString() { /* .loc_0x0: lbz r4, 0x5C(r3) lis r3, 0x802B subi r0, r3, 0xFAC rlwinm r3,r4,2,0,29 add r3, r0, r3 lwz r3, 0x0(r3) blr */ } /* * --INFO-- * Address: 80087EA0 * Size: 00003C */ void CollPart::getID() { /* .loc_0x0: mflr r0 addi r6, r3, 0 stw r0, 0x4(r1) addi r3, r6, 0x4 li r5, 0x5 stwu r1, -0x8(r1) lwz r4, 0x58(r4) lwzu r0, 0x14(r4) stw r0, 0x0(r6) addi r4, r4, 0x4 bl 0x18CAFC lwz r0, 0xC(r1) addi r1, r1, 0x8 mtlr r0 blr */ } /* * --INFO-- * Address: 80087EDC * Size: 00003C */ void CollPart::getCode() { /* .loc_0x0: mflr r0 addi r6, r3, 0 stw r0, 0x4(r1) addi r3, r6, 0x4 li r5, 0x5 stwu r1, -0x8(r1) lwz r4, 0x58(r4) lwzu r0, 0x20(r4) stw r0, 0x0(r6) addi r4, r4, 0x4 bl 0x18CAC0 lwz r0, 0xC(r1) addi r1, r1, 0x8 mtlr r0 blr */ } /* * --INFO-- * Address: 80087F18 * Size: 000164 */ void CollPart::getMatrix() { /* .loc_0x0: mflr r0 stw r0, 0x4(r1) stwu r1, -0xA0(r1) stw r31, 0x9C(r1) mr r31, r4 stw r30, 0x98(r1) addi r30, r3, 0 lwz r6, 0x10(r4) lis r4, 0x803D lwz r5, 0x14(r31) addi r0, r4, 0x15B0 mr r3, r0 stw r6, 0x58(r1) addi r4, r1, 0x58 stw r5, 0x5C(r1) addi r5, r1, 0x18 lwz r6, 0x18(r31) lwz r0, 0x1C(r31) stw r6, 0x60(r1) stw r0, 0x64(r1) lwz r6, 0x20(r31) lwz r0, 0x24(r31) stw r6, 0x68(r1) stw r0, 0x6C(r1) lwz r6, 0x28(r31) lwz r0, 0x2C(r31) stw r6, 0x70(r1) stw r0, 0x74(r1) lwz r6, 0x30(r31) lwz r0, 0x34(r31) stw r6, 0x78(r1) stw r0, 0x7C(r1) lwz r6, 0x38(r31) lwz r0, 0x3C(r31) stw r6, 0x80(r1) stw r0, 0x84(r1) lwz r6, 0x40(r31) lwz r0, 0x44(r31) stw r6, 0x88(r1) stw r0, 0x8C(r1) lwz r6, 0x48(r31) lwz r0, 0x4C(r31) stw r6, 0x90(r1) stw r0, 0x94(r1) bl -0x49EF4 lfs f0, 0x4(r31) stfs f0, 0x24(r1) lfs f0, 0x8(r31) stfs f0, 0x34(r1) lfs f0, 0xC(r31) stfs f0, 0x44(r1) lwz r3, 0x18(r1) lwz r0, 0x1C(r1) stw r3, 0x0(r30) stw r0, 0x4(r30) lwz r3, 0x20(r1) lwz r0, 0x24(r1) stw r3, 0x8(r30) stw r0, 0xC(r30) lwz r3, 0x28(r1) lwz r0, 0x2C(r1) stw r3, 0x10(r30) stw r0, 0x14(r30) lwz r3, 0x30(r1) lwz r0, 0x34(r1) stw r3, 0x18(r30) stw r0, 0x1C(r30) lwz r3, 0x38(r1) lwz r0, 0x3C(r1) stw r3, 0x20(r30) stw r0, 0x24(r30) lwz r3, 0x40(r1) lwz r0, 0x44(r1) stw r3, 0x28(r30) stw r0, 0x2C(r30) lwz r3, 0x48(r1) lwz r0, 0x4C(r1) stw r3, 0x30(r30) stw r0, 0x34(r30) lwz r3, 0x50(r1) lwz r0, 0x54(r1) stw r3, 0x38(r30) stw r0, 0x3C(r30) lwz r0, 0xA4(r1) lwz r31, 0x9C(r1) lwz r30, 0x98(r1) addi r1, r1, 0xA0 mtlr r0 blr */ } /* * --INFO-- * Address: 8008807C * Size: 0004A4 */ void CollPart::update(Graphics&, bool) { /* .loc_0x0: mflr r0 stw r0, 0x4(r1) stwu r1, -0x48(r1) stw r31, 0x44(r1) addi r31, r5, 0 stw r30, 0x40(r1) addi r30, r4, 0 stw r29, 0x3C(r1) mr r29, r3 stw r28, 0x38(r1) lbz r0, 0x50(r3) cmplwi r0, 0 beq- .loc_0x484 lbz r0, 0x5C(r29) cmplwi r0, 0x3 beq- .loc_0x484 lwz r28, 0x64(r29) cmplwi r28, 0 beq- .loc_0x98 lwz r12, 0x0(r28) mr r4, r28 addi r3, r1, 0x14 lwz r12, 0x8(r12) mtlr r12 blrl lwz r4, 0x14(r1) mr r3, r28 lwz r0, 0x18(r1) stw r4, 0x4(r29) stw r0, 0x8(r29) lwz r0, 0x1C(r1) stw r0, 0xC(r29) lwz r12, 0x0(r28) lwz r12, 0xC(r12) mtlr r12 blrl stfs f1, 0x0(r29) b .loc_0x1F8 .loc_0x98: lwz r5, 0x58(r29) addi r4, r30, 0 addi r6, r29, 0x4 lwz r3, 0x34(r5) lwz r0, 0x38(r5) stw r3, 0x4(r29) stw r0, 0x8(r29) lwz r0, 0x3C(r5) stw r0, 0xC(r29) lwz r5, 0x58(r29) lwz r3, 0x44(r5) lwz r5, 0x30(r5) bl -0x52880 lwz r5, 0x58(r29) lis r3, 0x803D addi r4, r3, 0x15B0 lfs f0, 0x40(r5) fmuls f0, f1, f0 stfs f0, 0x0(r29) lwz r5, 0x2E4(r30) lwz r3, 0x220(r5) lwz r0, 0x224(r5) stw r3, 0x0(r4) stw r0, 0x4(r4) lwz r3, 0x228(r5) lwz r0, 0x22C(r5) stw r3, 0x8(r4) stw r0, 0xC(r4) lwz r3, 0x230(r5) lwz r0, 0x234(r5) stw r3, 0x10(r4) stw r0, 0x14(r4) lwz r3, 0x238(r5) lwz r0, 0x23C(r5) stw r3, 0x18(r4) stw r0, 0x1C(r4) lwz r3, 0x240(r5) lwz r0, 0x244(r5) stw r3, 0x20(r4) stw r0, 0x24(r4) lwz r3, 0x248(r5) lwz r0, 0x24C(r5) stw r3, 0x28(r4) stw r0, 0x2C(r4) lwz r3, 0x250(r5) lwz r0, 0x254(r5) stw r3, 0x30(r4) stw r0, 0x34(r4) lwz r3, 0x258(r5) lwz r0, 0x25C(r5) stw r3, 0x38(r4) stw r0, 0x3C(r4) lwz r4, 0x58(r29) lwz r3, 0x44(r4) lwz r4, 0x30(r4) bl -0x53208 lwz r4, 0x0(r3) lwz r0, 0x4(r3) stw r4, 0x10(r29) stw r0, 0x14(r29) lwz r4, 0x8(r3) lwz r0, 0xC(r3) stw r4, 0x18(r29) stw r0, 0x1C(r29) lwz r4, 0x10(r3) lwz r0, 0x14(r3) stw r4, 0x20(r29) stw r0, 0x24(r29) lwz r4, 0x18(r3) lwz r0, 0x1C(r3) stw r4, 0x28(r29) stw r0, 0x2C(r29) lwz r4, 0x20(r3) lwz r0, 0x24(r3) stw r4, 0x30(r29) stw r0, 0x34(r29) lwz r4, 0x28(r3) lwz r0, 0x2C(r3) stw r4, 0x38(r29) stw r0, 0x3C(r29) lwz r4, 0x30(r3) lwz r0, 0x34(r3) stw r4, 0x40(r29) stw r0, 0x44(r29) lwz r4, 0x38(r3) lwz r0, 0x3C(r3) stw r4, 0x48(r29) stw r0, 0x4C(r29) .loc_0x1F8: rlwinm. r0,r31,0,24,31 beq- .loc_0x484 mr r3, r30 lwz r12, 0x3B4(r30) li r4, 0 li r5, 0 lwz r12, 0xCC(r12) mtlr r12 blrl mr r3, r30 lwz r12, 0x3B4(r30) li r4, 0 li r5, 0 lwz r12, 0x30(r12) mtlr r12 blrl lbz r0, 0x5C(r29) addi r31, r3, 0 cmpwi r0, 0x3 beq- .loc_0x35C bge- .loc_0x264 cmpwi r0, 0x1 beq- .loc_0x278 bge- .loc_0x320 cmpwi r0, 0 bge- .loc_0x2B0 b .loc_0x394 .loc_0x264: cmpwi r0, 0x7 bge- .loc_0x394 cmpwi r0, 0x5 bge- .loc_0x2E8 b .loc_0x394 .loc_0x278: li r6, 0xFF stb r6, 0x30(r1) li r0, 0xB4 addi r4, r1, 0x30 stb r0, 0x31(r1) mr r3, r30 li r5, 0x1 stb r0, 0x32(r1) stb r6, 0x33(r1) lwz r12, 0x3B4(r30) lwz r12, 0xA8(r12) mtlr r12 blrl b .loc_0x394 .loc_0x2B0: li r6, 0xFF stb r6, 0x2C(r1) li r0, 0 addi r4, r1, 0x2C stb r0, 0x2D(r1) mr r3, r30 li r5, 0x1 stb r0, 0x2E(r1) stb r6, 0x2F(r1) lwz r12, 0x3B4(r30) lwz r12, 0xA8(r12) mtlr r12 blrl b .loc_0x394 .loc_0x2E8: li r6, 0xFF stb r6, 0x28(r1) li r0, 0 addi r4, r1, 0x28 stb r0, 0x29(r1) mr r3, r30 li r5, 0x1 stb r6, 0x2A(r1) stb r6, 0x2B(r1) lwz r12, 0x3B4(r30) lwz r12, 0xA8(r12) mtlr r12 blrl b .loc_0x394 .loc_0x320: li r6, 0xFF stb r6, 0x24(r1) li r0, 0xD7 addi r4, r1, 0x24 stb r0, 0x25(r1) li r0, 0x14 addi r3, r30, 0 stb r0, 0x26(r1) li r5, 0x1 stb r6, 0x27(r1) lwz r12, 0x3B4(r30) lwz r12, 0xA8(r12) mtlr r12 blrl b .loc_0x394 .loc_0x35C: li r0, 0x32 stb r0, 0x20(r1) li r0, 0x96 addi r4, r1, 0x20 stb r0, 0x21(r1) li r0, 0xFF addi r3, r30, 0 stb r0, 0x22(r1) li r5, 0x1 stb r0, 0x23(r1) lwz r12, 0x3B4(r30) lwz r12, 0xA8(r12) mtlr r12 blrl .loc_0x394: mr r3, r30 lwz r4, 0x2E4(r30) lwz r12, 0x3B4(r30) li r5, 0 addi r4, r4, 0x1E0 lwz r12, 0x74(r12) mtlr r12 blrl lbz r0, 0x5C(r29) cmplwi r0, 0x5 bne- .loc_0x404 lha r0, 0x52(r29) cmpwi r0, -0x1 beq- .loc_0x3E0 lwz r3, 0x60(r29) mulli r0, r0, 0x68 lwz r3, 0x4(r3) add r5, r3, r0 b .loc_0x3E4 .loc_0x3E0: li r5, 0 .loc_0x3E4: lwz r6, 0x2E4(r30) mr r3, r30 lfs f1, 0x0(r29) addi r4, r29, 0x4 addi r5, r5, 0x4 addi r6, r6, 0x1E0 bl -0x5F2C4 b .loc_0x468 .loc_0x404: cmplwi r0, 0x6 bne- .loc_0x450 lha r0, 0x54(r29) cmpwi r0, -0x1 beq- .loc_0x42C lwz r3, 0x60(r29) mulli r0, r0, 0x68 lwz r3, 0x4(r3) add r5, r3, r0 b .loc_0x430 .loc_0x42C: li r5, 0 .loc_0x430: lwz r6, 0x2E4(r30) mr r3, r30 lfs f1, 0x0(r29) addi r4, r29, 0x4 addi r5, r5, 0x4 addi r6, r6, 0x1E0 bl -0x5F310 b .loc_0x468 .loc_0x450: lwz r5, 0x2E4(r30) mr r3, r30 lfs f1, 0x0(r29) addi r4, r29, 0x4 addi r5, r5, 0x1E0 bl -0x5F070 .loc_0x468: mr r3, r30 lwz r12, 0x3B4(r30) addi r4, r31, 0 li r5, 0 lwz r12, 0x30(r12) mtlr r12 blrl .loc_0x484: lwz r0, 0x4C(r1) lwz r31, 0x44(r1) lwz r30, 0x40(r1) lwz r29, 0x3C(r1) lwz r28, 0x38(r1) addi r1, r1, 0x48 mtlr r0 blr */ } /* * --INFO-- * Address: ........ * Size: 0001A4 */ void CollPart::collide(Creature*, Vector3f&) { // UNUSED FUNCTION } /* * --INFO-- * Address: ........ * Size: 000158 */ void CollPart::collide(Vector3f&, float, Vector3f&) { // UNUSED FUNCTION } /* * --INFO-- * Address: 80088520 * Size: 00066C */ void CollPart::collide(CollPart*, Vector3f&) { /* .loc_0x0: mflr r0 stw r0, 0x4(r1) li r0, 0x1 stwu r1, -0x1D8(r1) stw r31, 0x1D4(r1) addi r31, r5, 0 stw r30, 0x1D0(r1) addi r30, r4, 0 stw r29, 0x1CC(r1) mr r29, r3 lbz r3, 0x5C(r3) cmplwi r3, 0x1 beq- .loc_0x40 cmplwi r3, 0 beq- .loc_0x40 li r0, 0 .loc_0x40: rlwinm. r0,r0,0,24,31 beq- .loc_0x17C lbz r4, 0x5C(r30) li r0, 0x1 cmplwi r4, 0x1 beq- .loc_0x64 cmplwi r4, 0 beq- .loc_0x64 li r0, 0 .loc_0x64: rlwinm. r0,r0,0,24,31 beq- .loc_0x17C lfs f1, 0x4(r30) lfs f0, 0x4(r29) lfs f3, 0x8(r30) lfs f2, 0x8(r29) fsubs f0, f1, f0 lfs f4, 0xC(r30) lfs f1, 0xC(r29) fsubs f2, f3, f2 stfs f0, 0x1BC(r1) fsubs f0, f4, f1 stfs f2, 0x1C0(r1) stfs f0, 0x1C4(r1) lfs f1, 0x1BC(r1) lfs f0, 0x1C0(r1) lfs f2, 0x1C4(r1) fmuls f1, f1, f1 fmuls f0, f0, f0 fmuls f2, f2, f2 fadds f0, f1, f0 fadds f1, f2, f0 bl -0x7A99C lfs f0, -0x75C0(r2) fcmpu cr0, f0, f1 beq- .loc_0xF0 lfs f0, 0x1BC(r1) fdivs f0, f0, f1 stfs f0, 0x1BC(r1) lfs f0, 0x1C0(r1) fdivs f0, f0, f1 stfs f0, 0x1C0(r1) lfs f0, 0x1C4(r1) fdivs f0, f0, f1 stfs f0, 0x1C4(r1) .loc_0xF0: lfs f2, 0x0(r29) lfs f0, 0x0(r30) fadds f0, f2, f0 fcmpo cr0, f1, f0 cror 2, 0, 0x2 bne- .loc_0x64C lwz r4, 0x1BC(r1) li r3, 0x1 lwz r0, 0x1C0(r1) stw r4, 0x0(r31) stw r0, 0x4(r31) lwz r0, 0x1C4(r1) stw r0, 0x8(r31) lfs f3, 0x0(r29) lfs f2, 0x0(r30) lfs f0, 0x0(r31) fadds f2, f3, f2 fsubs f1, f2, f1 fmuls f0, f0, f1 stfs f0, 0x74(r1) lfs f0, 0x74(r1) stfs f0, 0xA0(r1) lfs f0, 0x4(r31) fmuls f0, f0, f1 stfs f0, 0xA4(r1) lfs f0, 0x8(r31) fmuls f0, f0, f1 stfs f0, 0xA8(r1) lwz r4, 0xA0(r1) lwz r0, 0xA4(r1) stw r4, 0x0(r31) stw r0, 0x4(r31) lwz r0, 0xA8(r1) stw r0, 0x8(r31) b .loc_0x650 .loc_0x17C: cmplwi r3, 0x4 bne- .loc_0x270 lbz r4, 0x5C(r30) li r0, 0x1 cmplwi r4, 0x1 beq- .loc_0x1A0 cmplwi r4, 0 beq- .loc_0x1A0 li r0, 0 .loc_0x1A0: rlwinm. r0,r0,0,24,31 beq- .loc_0x270 lha r0, 0x54(r29) cmpwi r0, -0x1 beq- .loc_0x1C8 lwz r3, 0x60(r29) mulli r0, r0, 0x68 lwz r3, 0x4(r3) add r7, r3, r0 b .loc_0x1CC .loc_0x1C8: li r7, 0 .loc_0x1CC: lfs f2, 0x0(r29) addi r3, r1, 0x198 lfs f1, 0x4(r29) addi r4, r1, 0x188 lfs f0, -0x75C0(r2) stfs f1, 0x198(r1) addi r5, r1, 0x17C addi r6, r1, 0x178 lfs f1, 0x8(r29) stfs f1, 0x19C(r1) lfs f1, 0xC(r29) stfs f1, 0x1A0(r1) lfs f1, 0x4(r7) stfs f1, 0x1A4(r1) lfs f1, 0x8(r7) stfs f1, 0x1A8(r1) lfs f1, 0xC(r7) stfs f1, 0x1AC(r1) stfs f2, 0x1B0(r1) lfs f2, 0x0(r30) lfs f1, 0x4(r30) stfs f1, 0x188(r1) lfs f1, 0x8(r30) stfs f1, 0x18C(r1) lfs f1, 0xC(r30) stfs f0, 0x184(r1) stfs f1, 0x190(r1) stfs f0, 0x180(r1) stfs f2, 0x194(r1) stfs f0, 0x17C(r1) bl -0x17C4 rlwinm. r0,r3,0,24,31 beq- .loc_0x64C lwz r4, 0x17C(r1) li r3, 0x1 lwz r0, 0x180(r1) stw r4, 0x0(r31) stw r0, 0x4(r31) lwz r0, 0x184(r1) stw r0, 0x8(r31) b .loc_0x650 .loc_0x270: cmplwi r3, 0x1 li r0, 0x1 ble- .loc_0x280 li r0, 0 .loc_0x280: rlwinm. r0,r0,0,24,31 beq- .loc_0x38C lbz r0, 0x5C(r30) cmplwi r0, 0x4 bne- .loc_0x38C lha r0, 0x54(r30) cmpwi r0, -0x1 beq- .loc_0x2B4 lwz r3, 0x60(r30) mulli r0, r0, 0x68 lwz r3, 0x4(r3) add r7, r3, r0 b .loc_0x2B8 .loc_0x2B4: li r7, 0 .loc_0x2B8: lfs f2, 0x0(r30) addi r3, r1, 0x158 lfs f1, 0x4(r30) addi r4, r1, 0x148 lfs f0, -0x75C0(r2) stfs f1, 0x158(r1) addi r5, r1, 0x13C addi r6, r1, 0x138 lfs f1, 0x8(r30) stfs f1, 0x15C(r1) lfs f1, 0xC(r30) stfs f1, 0x160(r1) lfs f1, 0x4(r7) stfs f1, 0x164(r1) lfs f1, 0x8(r7) stfs f1, 0x168(r1) lfs f1, 0xC(r7) stfs f1, 0x16C(r1) stfs f2, 0x170(r1) lfs f2, 0x0(r29) lfs f1, 0x4(r29) stfs f1, 0x148(r1) lfs f1, 0x8(r29) stfs f1, 0x14C(r1) lfs f1, 0xC(r29) stfs f1, 0x150(r1) stfs f2, 0x154(r1) stfs f0, 0x144(r1) stfs f0, 0x140(r1) stfs f0, 0x13C(r1) bl -0x18B0 rlwinm. r0,r3,0,24,31 beq- .loc_0x64C lfs f0, 0x13C(r1) li r3, 0x1 lfs f1, -0x5E50(r13) fmuls f0, f0, f1 stfs f0, 0x68(r1) lfs f0, 0x68(r1) stfs f0, 0x94(r1) lfs f0, 0x140(r1) fmuls f0, f0, f1 stfs f0, 0x98(r1) lfs f0, 0x144(r1) fmuls f0, f0, f1 stfs f0, 0x9C(r1) lwz r4, 0x94(r1) lwz r0, 0x98(r1) stw r4, 0x0(r31) stw r0, 0x4(r31) lwz r0, 0x9C(r1) stw r0, 0x8(r31) b .loc_0x650 .loc_0x38C: subi r0, r3, 0x5 rlwinm r0,r0,0,24,31 cmplwi r0, 0x1 li r0, 0x1 ble- .loc_0x3A4 li r0, 0 .loc_0x3A4: rlwinm. r0,r0,0,24,31 beq- .loc_0x4D8 lbz r4, 0x5C(r30) li r0, 0x1 cmplwi r4, 0x1 beq- .loc_0x3C8 cmplwi r4, 0 beq- .loc_0x3C8 li r0, 0 .loc_0x3C8: rlwinm. r0,r0,0,24,31 beq- .loc_0x4D8 cmplwi r3, 0x5 bne- .loc_0x404 lha r0, 0x52(r29) cmpwi r0, -0x1 beq- .loc_0x3F8 lwz r3, 0x60(r29) mulli r0, r0, 0x68 lwz r3, 0x4(r3) add r0, r3, r0 b .loc_0x3FC .loc_0x3F8: li r0, 0 .loc_0x3FC: mr r7, r0 b .loc_0x42C .loc_0x404: lha r0, 0x54(r29) cmpwi r0, -0x1 beq- .loc_0x424 lwz r3, 0x60(r29) mulli r0, r0, 0x68 lwz r3, 0x4(r3) add r0, r3, r0 b .loc_0x428 .loc_0x424: li r0, 0 .loc_0x428: mr r7, r0 .loc_0x42C: lfs f3, 0x0(r7) addi r3, r1, 0x118 lfs f2, 0x0(r29) addi r4, r1, 0x108 lfs f1, 0x4(r29) lfs f0, -0x75C0(r2) addi r5, r1, 0xFC stfs f1, 0x118(r1) addi r6, r1, 0xF8 lfs f1, 0x8(r29) stfs f1, 0x11C(r1) lfs f1, 0xC(r29) stfs f1, 0x120(r1) lfs f1, 0x4(r7) stfs f1, 0x124(r1) lfs f1, 0x8(r7) stfs f1, 0x128(r1) lfs f1, 0xC(r7) stfs f1, 0x12C(r1) stfs f2, 0x130(r1) stfs f3, 0x134(r1) lfs f2, 0x0(r30) lfs f1, 0x4(r30) stfs f1, 0x108(r1) lfs f1, 0x8(r30) stfs f1, 0x10C(r1) lfs f1, 0xC(r30) stfs f0, 0x104(r1) stfs f1, 0x110(r1) stfs f0, 0x100(r1) stfs f2, 0x114(r1) stfs f0, 0xFC(r1) bl -0x1640 rlwinm. r0,r3,0,24,31 beq- .loc_0x64C lwz r4, 0xFC(r1) li r3, 0x1 lwz r0, 0x100(r1) stw r4, 0x0(r31) stw r0, 0x4(r31) lwz r0, 0x104(r1) stw r0, 0x8(r31) b .loc_0x650 .loc_0x4D8: cmplwi r3, 0x1 li r0, 0x1 ble- .loc_0x4E8 li r0, 0 .loc_0x4E8: rlwinm. r0,r0,0,24,31 beq- .loc_0x64C lbz r3, 0x5C(r30) li r0, 0x1 cmplwi r3, 0x5 beq- .loc_0x50C cmplwi r3, 0x6 beq- .loc_0x50C li r0, 0 .loc_0x50C: rlwinm. r0,r0,0,24,31 beq- .loc_0x64C cmplwi r3, 0x5 bne- .loc_0x548 lha r0, 0x52(r30) cmpwi r0, -0x1 beq- .loc_0x53C lwz r3, 0x60(r30) mulli r0, r0, 0x68 lwz r3, 0x4(r3) add r0, r3, r0 b .loc_0x540 .loc_0x53C: li r0, 0 .loc_0x540: mr r7, r0 b .loc_0x570 .loc_0x548: lha r0, 0x54(r30) cmpwi r0, -0x1 beq- .loc_0x568 lwz r3, 0x60(r30) mulli r0, r0, 0x68 lwz r3, 0x4(r3) add r0, r3, r0 b .loc_0x56C .loc_0x568: li r0, 0 .loc_0x56C: mr r7, r0 .loc_0x570: lfs f3, 0x0(r7) addi r3, r1, 0xD8 lfs f2, 0x0(r30) addi r4, r1, 0xC8 lfs f1, 0x4(r30) lfs f0, -0x75C0(r2) addi r5, r1, 0xBC stfs f1, 0xD8(r1) addi r6, r1, 0xB8 lfs f1, 0x8(r30) stfs f1, 0xDC(r1) lfs f1, 0xC(r30) stfs f1, 0xE0(r1) lfs f1, 0x4(r7) stfs f1, 0xE4(r1) lfs f1, 0x8(r7) stfs f1, 0xE8(r1) lfs f1, 0xC(r7) stfs f1, 0xEC(r1) stfs f2, 0xF0(r1) stfs f3, 0xF4(r1) lfs f2, 0x0(r29) lfs f1, 0x4(r29) stfs f1, 0xC8(r1) lfs f1, 0x8(r29) stfs f1, 0xCC(r1) lfs f1, 0xC(r29) stfs f1, 0xD0(r1) stfs f2, 0xD4(r1) stfs f0, 0xC4(r1) stfs f0, 0xC0(r1) stfs f0, 0xBC(r1) bl -0x1784 rlwinm. r0,r3,0,24,31 beq- .loc_0x64C lfs f0, 0xBC(r1) li r3, 0x1 lfs f1, -0x5E4C(r13) fmuls f0, f0, f1 stfs f0, 0x5C(r1) lfs f0, 0x5C(r1) stfs f0, 0x88(r1) lfs f0, 0xC0(r1) fmuls f0, f0, f1 stfs f0, 0x8C(r1) lfs f0, 0xC4(r1) fmuls f0, f0, f1 stfs f0, 0x90(r1) lwz r4, 0x88(r1) lwz r0, 0x8C(r1) stw r4, 0x0(r31) stw r0, 0x4(r31) lwz r0, 0x90(r1) stw r0, 0x8(r31) b .loc_0x650 .loc_0x64C: li r3, 0 .loc_0x650: lwz r0, 0x1DC(r1) lwz r31, 0x1D4(r1) lwz r30, 0x1D0(r1) lwz r29, 0x1CC(r1) addi r1, r1, 0x1D8 mtlr r0 blr */ } /* * --INFO-- * Address: 80088B8C * Size: 0000A4 */ void CollPart::makeTube(Tube&) { /* .loc_0x0: lbz r0, 0x5C(r3) cmplwi r0, 0x5 bne- .loc_0x38 lha r0, 0x52(r3) cmpwi r0, -0x1 beq- .loc_0x2C lwz r5, 0x60(r3) mulli r0, r0, 0x68 lwz r5, 0x4(r5) add r0, r5, r0 b .loc_0x30 .loc_0x2C: li r0, 0 .loc_0x30: mr r6, r0 b .loc_0x60 .loc_0x38: lha r0, 0x54(r3) cmpwi r0, -0x1 beq- .loc_0x58 lwz r5, 0x60(r3) mulli r0, r0, 0x68 lwz r5, 0x4(r5) add r0, r5, r0 b .loc_0x5C .loc_0x58: li r0, 0 .loc_0x5C: mr r6, r0 .loc_0x60: lwz r5, 0x4(r3) lwz r0, 0x8(r3) stw r5, 0x0(r4) stw r0, 0x4(r4) lwz r0, 0xC(r3) stw r0, 0x8(r4) lfs f0, 0x0(r3) stfs f0, 0x18(r4) lwz r3, 0x4(r6) lwz r0, 0x8(r6) stw r3, 0xC(r4) stw r0, 0x10(r4) lwz r0, 0xC(r6) stw r0, 0x14(r4) lfs f0, 0x0(r6) stfs f0, 0x1C(r4) blr */ } /* * --INFO-- * Address: ........ * Size: 000024 */ void CollPart::makeSphere(Sphere&) { // UNUSED FUNCTION } /* * --INFO-- * Address: ........ * Size: 000004 */ void CollPart::makeCylinder(Cylinder&) { // UNUSED FUNCTION } /* * --INFO-- * Address: ........ * Size: 000048 */ void CollPart::samePlatShape(Shape*) { // UNUSED FUNCTION } /* * --INFO-- * Address: 80088C30 * Size: 0000A0 */ CollInfo::CollInfo(int) { /* .loc_0x0: mflr r0 cmpwi r4, 0 stw r0, 0x4(r1) li r0, 0 stwu r1, -0x28(r1) stw r31, 0x24(r1) stw r30, 0x20(r1) addi r30, r3, 0 stw r0, 0x10(r3) sth r0, 0xC(r3) bne- .loc_0x40 li r0, 0xA sth r0, 0xE(r30) li r0, 0x1 stb r0, 0x0(r30) b .loc_0x84 .loc_0x40: sth r4, 0xE(r30) stb r0, 0x0(r30) lhz r31, 0xE(r30) mulli r3, r31, 0x68 addi r3, r3, 0x8 bl -0x41C80 lis r4, 0x8008 addi r4, r4, 0x7E48 addi r7, r31, 0 li r5, 0 li r6, 0x68 bl 0x18BF8C stw r3, 0x4(r30) lhz r0, 0xE(r30) rlwinm r3,r0,2,0,29 bl -0x41CA8 stw r3, 0x8(r30) .loc_0x84: mr r3, r30 lwz r0, 0x2C(r1) lwz r31, 0x24(r1) lwz r30, 0x20(r1) addi r1, r1, 0x28 mtlr r0 blr */ } /* * --INFO-- * Address: 80088CD0 * Size: 000034 */ void CollInfo::enableStick() { /* .loc_0x0: li r7, 0 li r6, 0 li r5, 0x1 b .loc_0x24 .loc_0x10: lwz r4, 0x4(r3) addi r0, r6, 0x51 addi r7, r7, 0x1 stbx r5, r4, r0 addi r6, r6, 0x68 .loc_0x24: lhz r0, 0xC(r3) cmpw r7, r0 blt+ .loc_0x10 blr */ } /* * --INFO-- * Address: 80088D04 * Size: 000034 */ void CollInfo::disableStick() { /* .loc_0x0: li r6, 0 addi r5, r6, 0 li r7, 0 b .loc_0x24 .loc_0x10: lwz r4, 0x4(r3) addi r0, r6, 0x51 addi r7, r7, 0x1 stbx r5, r4, r0 addi r6, r6, 0x68 .loc_0x24: lhz r0, 0xC(r3) cmpw r7, r0 blt+ .loc_0x10 blr */ } /* * --INFO-- * Address: ........ * Size: 000048 */ void CollInfo::startUpdate(unsigned long) { // UNUSED FUNCTION } /* * --INFO-- * Address: ........ * Size: 0001A8 */ void CollInfo::startUpdateRec(int) { // UNUSED FUNCTION } /* * --INFO-- * Address: ........ * Size: 000048 */ void CollInfo::stopUpdate(unsigned long) { // UNUSED FUNCTION } /* * --INFO-- * Address: ........ * Size: 0001A8 */ void CollInfo::stopUpdateRec(int) { // UNUSED FUNCTION } /* * --INFO-- * Address: 80088D38 * Size: 0001C0 */ void CollInfo::checkCollisionSpecial(Vector3f&, float, CndCollPart*) { /* .loc_0x0: mflr r0 stw r0, 0x4(r1) stwu r1, -0xC0(r1) stfd f31, 0xB8(r1) stfd f30, 0xB0(r1) fmr f30, f1 stmw r23, 0x8C(r1) mr r24, r3 addi r25, r4, 0 addi r26, r5, 0 addi r31, r1, 0x34 addi r30, r1, 0x30 addi r29, r1, 0x2C li r27, 0 li r28, 0 lfs f31, -0x75C0(r2) stfs f31, 0x80(r1) stfs f31, 0x7C(r1) b .loc_0x194 .loc_0x4C: lwz r0, 0x4(r24) add r3, r0, r28 lbz r0, 0x5C(r3) addi r23, r3, 0 cmplwi r0, 0x2 bne- .loc_0x18C cmplwi r26, 0 beq- .loc_0x8C mr r3, r26 lwz r12, 0x0(r26) mr r4, r23 lwz r12, 0x8(r12) mtlr r12 blrl rlwinm. r0,r3,0,24,31 beq- .loc_0x18C .loc_0x8C: lbz r0, 0x5C(r23) cmplwi r0, 0x4 beq- .loc_0x178 lfs f1, 0x8(r25) mr r4, r29 lfs f0, 0xC(r23) addi r5, r30, 0 addi r6, r31, 0 fsubs f0, f1, f0 addi r3, r1, 0x5C stfs f0, 0x34(r1) lfs f1, 0x4(r25) lfs f0, 0x8(r23) fsubs f0, f1, f0 stfs f0, 0x30(r1) lfs f1, 0x0(r25) lfs f0, 0x4(r23) fsubs f0, f1, f0 stfs f0, 0x2C(r1) bl -0x51CF4 lfs f1, 0x5C(r1) lfs f0, 0x60(r1) stfs f1, 0x4C(r1) stfs f0, 0x50(r1) lfs f0, 0x64(r1) stfs f0, 0x54(r1) lfs f1, 0x4C(r1) lfs f0, 0x50(r1) fmuls f1, f1, f1 lfs f2, 0x54(r1) fmuls f0, f0, f0 fmuls f2, f2, f2 fadds f0, f1, f0 fadds f1, f2, f0 bl -0x7B20C fcmpu cr0, f31, f1 beq- .loc_0x144 lfs f0, 0x4C(r1) fdivs f0, f0, f1 stfs f0, 0x4C(r1) lfs f0, 0x50(r1) fdivs f0, f0, f1 stfs f0, 0x50(r1) lfs f0, 0x54(r1) fdivs f0, f0, f1 stfs f0, 0x54(r1) .loc_0x144: lfs f0, 0x0(r23) fadds f0, f0, f30 fcmpo cr0, f1, f0 cror 2, 0, 0x2 bne- .loc_0x178 lwz r0, 0x4C(r1) li r4, 0x1 lwz r3, 0x50(r1) stw r0, 0x78(r1) lwz r0, 0x54(r1) stw r3, 0x7C(r1) stw r0, 0x80(r1) b .loc_0x17C .loc_0x178: li r4, 0 .loc_0x17C: rlwinm. r0,r4,0,24,31 beq- .loc_0x18C mr r3, r23 b .loc_0x1A4 .loc_0x18C: addi r28, r28, 0x68 addi r27, r27, 0x1 .loc_0x194: lhz r0, 0xC(r24) cmpw r27, r0 blt+ .loc_0x4C li r3, 0 .loc_0x1A4: lmw r23, 0x8C(r1) lwz r0, 0xC4(r1) lfd f31, 0xB8(r1) lfd f30, 0xB0(r1) addi r1, r1, 0xC0 mtlr r0 blr */ } /* * --INFO-- * Address: 80088EF8 * Size: 000008 */ u32 CndCollPart::satisfy(CollPart*) { return 0x0; } /* * --INFO-- * Address: ........ * Size: 000008 */ void CollInfo::checkCollisionSpecialRec(int, Vector3f&, float, CndCollPart*) { // UNUSED FUNCTION } /* * --INFO-- * Address: 80088F00 * Size: 000028 */ void CollInfo::checkCollision(Creature*, Vector3f&) { /* .loc_0x0: mflr r0 addi r6, r5, 0 stw r0, 0x4(r1) li r5, 0 stwu r1, -0x8(r1) bl .loc_0x28 lwz r0, 0xC(r1) addi r1, r1, 0x8 mtlr r0 blr .loc_0x28: */ } /* * --INFO-- * Address: 80088F28 * Size: 000624 */ void CollInfo::checkCollisionRec(Creature*, int, Vector3f&) { /* .loc_0x0: mflr r0 stw r0, 0x4(r1) stwu r1, -0x160(r1) stfd f31, 0x158(r1) stmw r27, 0x144(r1) addi r27, r5, 0 addi r29, r3, 0 mulli r0, r27, 0x68 addi r30, r4, 0 addi r31, r6, 0 lwz r3, 0x4(r3) add r3, r3, r0 lbz r0, 0x5C(r3) addi r28, r3, 0 cmplwi r0, 0x4 beq- .loc_0x1B8 mr r4, r30 lwz r12, 0x0(r30) addi r3, r1, 0x128 lwz r12, 0x58(r12) mtlr r12 blrl lfs f1, 0x130(r1) addi r6, r1, 0x7C lfs f0, 0xC(r28) addi r5, r1, 0x78 lfs f2, 0x12C(r1) fsubs f0, f1, f0 lfs f1, 0x128(r1) addi r4, r1, 0x74 addi r3, r1, 0x11C stfs f0, 0x7C(r1) lfs f0, 0x8(r28) fsubs f0, f2, f0 stfs f0, 0x78(r1) lfs f0, 0x4(r28) fsubs f0, f1, f0 stfs f0, 0x74(r1) bl -0x51EA4 lfs f1, 0x11C(r1) lfs f0, 0x120(r1) stfs f1, 0x10C(r1) stfs f0, 0x110(r1) lfs f0, 0x124(r1) stfs f0, 0x114(r1) lfs f1, 0x10C(r1) lfs f0, 0x110(r1) fmuls f1, f1, f1 lfs f2, 0x114(r1) fmuls f0, f0, f0 fmuls f2, f2, f2 fadds f0, f1, f0 fadds f1, f2, f0 bl -0x7B3BC fmr f31, f1 lfs f0, -0x75C0(r2) fcmpu cr0, f0, f31 beq- .loc_0x10C lfs f0, 0x10C(r1) fdivs f0, f0, f31 stfs f0, 0x10C(r1) lfs f0, 0x110(r1) fdivs f0, f0, f31 stfs f0, 0x110(r1) lfs f0, 0x114(r1) fdivs f0, f0, f31 stfs f0, 0x114(r1) .loc_0x10C: mr r3, r30 lwz r12, 0x0(r30) lwz r12, 0x3C(r12) mtlr r12 blrl lfs f0, 0x0(r28) fadds f0, f0, f1 fcmpo cr0, f31, f0 cror 2, 0, 0x2 bne- .loc_0x1B8 lwz r4, 0x10C(r1) mr r3, r30 lwz r0, 0x110(r1) stw r4, 0x0(r31) stw r0, 0x4(r31) lwz r0, 0x114(r1) stw r0, 0x8(r31) lwz r12, 0x0(r30) lwz r12, 0x3C(r12) mtlr r12 blrl lfs f2, 0x0(r28) li r4, 0x1 lfs f0, 0x0(r31) fadds f1, f2, f1 fsubs f1, f1, f31 fmuls f0, f0, f1 stfs f0, 0xF8(r1) lfs f0, 0xF8(r1) stfs f0, 0x134(r1) lfs f0, 0x4(r31) fmuls f0, f0, f1 stfs f0, 0x138(r1) lfs f0, 0x8(r31) fmuls f0, f0, f1 stfs f0, 0x13C(r1) lwz r3, 0x134(r1) lwz r0, 0x138(r1) stw r3, 0x0(r31) stw r0, 0x4(r31) lwz r0, 0x13C(r1) stw r0, 0x8(r31) b .loc_0x1BC .loc_0x1B8: li r4, 0 .loc_0x1BC: rlwinm. r0,r4,0,24,31 beq- .loc_0x3F0 lbz r0, 0x5C(r28) cmplwi r0, 0x1 beq- .loc_0x1D8 mr r3, r28 b .loc_0x60C .loc_0x1D8: cmplwi r0, 0x4 bne- .loc_0x1E8 li r3, 0 b .loc_0x60C .loc_0x1E8: lha r28, 0x54(r28) lwz r3, 0x4(r29) mulli r0, r28, 0x68 add r27, r3, r0 lbz r0, 0x5C(r27) cmplwi r0, 0x4 beq- .loc_0x370 mr r4, r30 lwz r12, 0x0(r30) addi r3, r1, 0xE0 lwz r12, 0x58(r12) mtlr r12 blrl lfs f1, 0xE8(r1) addi r6, r1, 0x4C lfs f0, 0xC(r27) addi r5, r1, 0x48 lfs f2, 0xE4(r1) fsubs f0, f1, f0 lfs f1, 0xE0(r1) addi r4, r1, 0x44 addi r3, r1, 0xD4 stfs f0, 0x4C(r1) lfs f0, 0x8(r27) fsubs f0, f2, f0 stfs f0, 0x48(r1) lfs f0, 0x4(r27) fsubs f0, f1, f0 stfs f0, 0x44(r1) bl -0x52068 lfs f1, 0xD4(r1) lfs f0, 0xD8(r1) stfs f1, 0xC4(r1) stfs f0, 0xC8(r1) lfs f0, 0xDC(r1) stfs f0, 0xCC(r1) lfs f1, 0xC4(r1) lfs f0, 0xC8(r1) fmuls f1, f1, f1 lfs f2, 0xCC(r1) fmuls f0, f0, f0 fmuls f2, f2, f2 fadds f0, f1, f0 fadds f1, f2, f0 bl -0x7B580 fmr f31, f1 lfs f0, -0x75C0(r2) fcmpu cr0, f0, f31 beq- .loc_0x2B8 addi r3, r1, 0xC4 fmr f1, f31 bl .loc_0x624 .loc_0x2B8: mr r3, r30 lwz r12, 0x0(r30) lwz r12, 0x3C(r12) mtlr r12 blrl lfs f0, 0x0(r27) fadds f0, f0, f1 fcmpo cr0, f31, f0 cror 2, 0, 0x2 bne- .loc_0x370 lwz r4, 0xC4(r1) mr r3, r30 lwz r0, 0xC8(r1) stw r4, 0x0(r31) stw r0, 0x4(r31) lwz r0, 0xCC(r1) stw r0, 0x8(r31) lwz r12, 0x0(r30) lwz r12, 0x3C(r12) mtlr r12 blrl lfs f2, 0x0(r27) addi r6, r1, 0x68 lfs f0, 0x8(r31) addi r5, r1, 0x64 fadds f1, f2, f1 addi r4, r1, 0x60 addi r3, r1, 0xEC fsubs f1, f1, f31 fmuls f0, f0, f1 stfs f0, 0x68(r1) lfs f0, 0x4(r31) fmuls f0, f0, f1 stfs f0, 0x64(r1) lfs f0, 0x0(r31) fmuls f0, f0, f1 stfs f0, 0x60(r1) bl -0x52158 lwz r3, 0xEC(r1) li r4, 0x1 lwz r0, 0xF0(r1) stw r3, 0x0(r31) stw r0, 0x4(r31) lwz r0, 0xF4(r1) stw r0, 0x8(r31) b .loc_0x374 .loc_0x370: li r4, 0 .loc_0x374: rlwinm. r0,r4,0,24,31 beq- .loc_0x3B8 lbz r0, 0x5C(r27) cmplwi r0, 0x1 beq- .loc_0x38C b .loc_0x3E8 .loc_0x38C: cmplwi r0, 0x4 bne- .loc_0x39C li r27, 0 b .loc_0x3E8 .loc_0x39C: lha r5, 0x54(r27) addi r3, r29, 0 addi r4, r30, 0 addi r6, r31, 0 bl .loc_0x0 mr r27, r3 b .loc_0x3E8 .loc_0x3B8: cmpwi r28, 0 beq- .loc_0x3E4 lha r5, 0x52(r27) cmpwi r5, -0x1 beq- .loc_0x3E4 addi r3, r29, 0 addi r4, r30, 0 addi r6, r31, 0 bl .loc_0x0 mr r27, r3 b .loc_0x3E8 .loc_0x3E4: li r27, 0 .loc_0x3E8: mr r3, r27 b .loc_0x60C .loc_0x3F0: cmpwi r27, 0 beq- .loc_0x608 lha r28, 0x52(r28) cmpwi r28, -0x1 beq- .loc_0x608 mulli r0, r28, 0x68 lwz r3, 0x4(r29) add r27, r3, r0 lbz r0, 0x5C(r27) cmplwi r0, 0x4 beq- .loc_0x588 mr r4, r30 lwz r12, 0x0(r30) addi r3, r1, 0xA4 lwz r12, 0x58(r12) mtlr r12 blrl lfs f1, 0xAC(r1) addi r6, r1, 0x40 lfs f0, 0xC(r27) addi r5, r1, 0x3C lfs f2, 0xA8(r1) fsubs f0, f1, f0 lfs f1, 0xA4(r1) addi r4, r1, 0x38 addi r3, r1, 0x98 stfs f0, 0x40(r1) lfs f0, 0x8(r27) fsubs f0, f2, f0 stfs f0, 0x3C(r1) lfs f0, 0x4(r27) fsubs f0, f1, f0 stfs f0, 0x38(r1) bl -0x52280 lfs f1, 0x98(r1) lfs f0, 0x9C(r1) stfs f1, 0x88(r1) stfs f0, 0x8C(r1) lfs f0, 0xA0(r1) stfs f0, 0x90(r1) lfs f1, 0x88(r1) lfs f0, 0x8C(r1) fmuls f1, f1, f1 lfs f2, 0x90(r1) fmuls f0, f0, f0 fmuls f2, f2, f2 fadds f0, f1, f0 fadds f1, f2, f0 bl -0x7B798 fmr f31, f1 lfs f0, -0x75C0(r2) fcmpu cr0, f0, f31 beq- .loc_0x4D0 addi r3, r1, 0x88 fmr f1, f31 bl .loc_0x624 .loc_0x4D0: mr r3, r30 lwz r12, 0x0(r30) lwz r12, 0x3C(r12) mtlr r12 blrl lfs f0, 0x0(r27) fadds f0, f0, f1 fcmpo cr0, f31, f0 cror 2, 0, 0x2 bne- .loc_0x588 lwz r4, 0x88(r1) mr r3, r30 lwz r0, 0x8C(r1) stw r4, 0x0(r31) stw r0, 0x4(r31) lwz r0, 0x90(r1) stw r0, 0x8(r31) lwz r12, 0x0(r30) lwz r12, 0x3C(r12) mtlr r12 blrl lfs f2, 0x0(r27) addi r6, r1, 0x58 lfs f0, 0x8(r31) addi r5, r1, 0x54 fadds f1, f2, f1 addi r4, r1, 0x50 addi r3, r1, 0xB0 fsubs f1, f1, f31 fmuls f0, f0, f1 stfs f0, 0x58(r1) lfs f0, 0x4(r31) fmuls f0, f0, f1 stfs f0, 0x54(r1) lfs f0, 0x0(r31) fmuls f0, f0, f1 stfs f0, 0x50(r1) bl -0x52370 lwz r3, 0xB0(r1) li r4, 0x1 lwz r0, 0xB4(r1) stw r3, 0x0(r31) stw r0, 0x4(r31) lwz r0, 0xB8(r1) stw r0, 0x8(r31) b .loc_0x58C .loc_0x588: li r4, 0 .loc_0x58C: rlwinm. r0,r4,0,24,31 beq- .loc_0x5D0 lbz r0, 0x5C(r27) cmplwi r0, 0x1 beq- .loc_0x5A4 b .loc_0x600 .loc_0x5A4: cmplwi r0, 0x4 bne- .loc_0x5B4 li r27, 0 b .loc_0x600 .loc_0x5B4: lha r5, 0x54(r27) addi r3, r29, 0 addi r4, r30, 0 addi r6, r31, 0 bl .loc_0x0 mr r27, r3 b .loc_0x600 .loc_0x5D0: cmpwi r28, 0 beq- .loc_0x5FC lha r5, 0x52(r27) cmpwi r5, -0x1 beq- .loc_0x5FC addi r3, r29, 0 addi r4, r30, 0 addi r6, r31, 0 bl .loc_0x0 mr r27, r3 b .loc_0x600 .loc_0x5FC: li r27, 0 .loc_0x600: mr r3, r27 b .loc_0x60C .loc_0x608: li r3, 0 .loc_0x60C: lmw r27, 0x144(r1) lwz r0, 0x164(r1) lfd f31, 0x158(r1) addi r1, r1, 0x160 mtlr r0 blr .loc_0x624: */ } /* * --INFO-- * Address: 8008954C * Size: 000028 */ void Vector3f::div(float) { /* .loc_0x0: lfs f0, 0x0(r3) fdivs f0, f0, f1 stfs f0, 0x0(r3) lfs f0, 0x4(r3) fdivs f0, f0, f1 stfs f0, 0x4(r3) lfs f0, 0x8(r3) fdivs f0, f0, f1 stfs f0, 0x8(r3) blr */ } /* * --INFO-- * Address: 80089574 * Size: 000034 */ void CollInfo::checkCollision(CollInfo*, CollPart**, CollPart**, Vector3f&) { /* .loc_0x0: mflr r0 addi r9, r7, 0 stw r0, 0x4(r1) addi r7, r5, 0 addi r8, r6, 0 stwu r1, -0x8(r1) li r5, 0 li r6, 0 bl .loc_0x34 lwz r0, 0xC(r1) addi r1, r1, 0x8 mtlr r0 blr .loc_0x34: */ } /* * --INFO-- * Address: 800895A8 * Size: 000160 */ void CollInfo::checkCollisionRec(CollInfo*, int, int, CollPart**, CollPart**, Vector3f&) { /* .loc_0x0: mflr r0 stw r0, 0x4(r1) stwu r1, -0x50(r1) stmw r23, 0x2C(r1) addi r31, r5, 0 addi r23, r6, 0 addi r30, r4, 0 mulli r4, r31, 0x68 mulli r0, r23, 0x68 addi r29, r3, 0 addi r26, r9, 0 lwz r5, 0x4(r3) addi r24, r7, 0 lwz r3, 0x4(r30) addi r25, r8, 0 add r28, r5, r4 add r27, r3, r0 addi r3, r28, 0 addi r4, r27, 0 addi r5, r26, 0 bl -0x10D8 rlwinm. r0,r3,0,24,31 beq- .loc_0xD4 lbz r3, 0x5C(r28) cmplwi r3, 0x1 beq- .loc_0x84 lbz r0, 0x5C(r27) cmplwi r0, 0x1 beq- .loc_0x84 stw r28, 0x0(r24) li r3, 0x1 stw r27, 0x0(r25) b .loc_0x14C .loc_0x84: cmplwi r3, 0x1 bne- .loc_0xB0 lha r5, 0x54(r28) addi r3, r29, 0 addi r4, r30, 0 addi r6, r23, 0 addi r7, r24, 0 addi r8, r25, 0 addi r9, r26, 0 bl .loc_0x0 b .loc_0x14C .loc_0xB0: lha r6, 0x54(r27) addi r3, r29, 0 addi r4, r30, 0 addi r5, r31, 0 addi r7, r24, 0 addi r8, r25, 0 addi r9, r26, 0 bl .loc_0x0 b .loc_0x14C .loc_0xD4: cmpwi r31, 0 beq- .loc_0x108 lha r5, 0x52(r28) cmpwi r5, -0x1 beq- .loc_0x108 addi r3, r29, 0 addi r4, r30, 0 addi r6, r23, 0 addi r7, r24, 0 addi r8, r25, 0 addi r9, r26, 0 bl .loc_0x0 b .loc_0x14C .loc_0x108: cmpwi r23, 0 beq- .loc_0x13C lha r6, 0x52(r27) cmpwi r6, -0x1 beq- .loc_0x13C addi r3, r29, 0 addi r4, r30, 0 addi r5, r31, 0 addi r7, r24, 0 addi r8, r25, 0 addi r9, r26, 0 bl .loc_0x0 b .loc_0x14C .loc_0x13C: li r0, 0 stw r0, 0x0(r24) li r3, 0 stw r0, 0x0(r25) .loc_0x14C: lmw r23, 0x2C(r1) lwz r0, 0x54(r1) addi r1, r1, 0x50 mtlr r0 blr */ } /* * --INFO-- * Address: 80089708 * Size: 000008 */ void CollInfo::getBoundingSphere() { /* .loc_0x0: lwz r3, 0x4(r3) blr */ } /* * --INFO-- * Address: 80089710 * Size: 000060 */ void CollInfo::getSphere(unsigned long) { /* .loc_0x0: mflr r0 stw r0, 0x4(r1) stwu r1, -0x28(r1) stw r31, 0x24(r1) addi r31, r4, 0 stw r30, 0x20(r1) addi r30, r3, 0 bl 0x7C0 cmpwi r3, -0x1 bne- .loc_0x3C addi r3, r1, 0x10 addi r4, r31, 0 bl -0x458AC li r3, 0 b .loc_0x48 .loc_0x3C: mulli r0, r3, 0x68 lwz r3, 0x4(r30) add r3, r3, r0 .loc_0x48: lwz r0, 0x2C(r1) lwz r31, 0x24(r1) lwz r30, 0x20(r1) addi r1, r1, 0x28 mtlr r0 blr */ } /* * --INFO-- * Address: 80089770 * Size: 00017C */ void CollInfo::getNearestCollPart(Vector3f&, unsigned long) { /* .loc_0x0: mflr r0 stw r0, 0x4(r1) stwu r1, -0xA8(r1) stfd f31, 0xA0(r1) stfd f30, 0x98(r1) stfd f29, 0x90(r1) stfd f28, 0x88(r1) stmw r23, 0x64(r1) mr r23, r3 mr r24, r4 addi r25, r5, 0 addi r29, r1, 0x48 addi r31, r1, 0x44 li r28, 0 li r27, 0 li r30, 0 lfs f28, -0x759C(r2) lfs f29, -0x75C0(r2) lfd f30, -0x75B8(r2) lfd f31, -0x75B0(r2) b .loc_0x148 .loc_0x54: lwz r0, 0x4(r23) add r3, r0, r30 lbz r0, 0x5C(r3) addi r26, r3, 0 cmplwi r0, 0x3 beq- .loc_0x140 lwz r4, 0x58(r26) addi r3, r29, 0 lwzu r0, 0x20(r4) li r5, 0x5 stw r0, 0x44(r1) addi r4, r4, 0x4 bl 0x18B1D0 addi r3, r31, 0 addi r4, r25, 0 li r5, 0x2A bl -0x4591C rlwinm. r0,r3,0,24,31 beq- .loc_0x140 lfs f3, 0x4(r24) lfs f2, 0x8(r26) lfs f1, 0x0(r24) lfs f0, 0x4(r26) fsubs f3, f3, f2 lfs f2, 0x8(r24) fsubs f4, f1, f0 lfs f1, 0xC(r26) fmuls f0, f3, f3 fsubs f2, f2, f1 fmuls f1, f4, f4 fmuls f2, f2, f2 fadds f0, f1, f0 fadds f2, f2, f0 fcmpo cr0, f2, f29 ble- .loc_0x130 fsqrte f1, f2 fmul f0, f1, f1 fmul f1, f30, f1 fmul f0, f2, f0 fsub f0, f31, f0 fmul f1, f1, f0 fmul f0, f1, f1 fmul f1, f30, f1 fmul f0, f2, f0 fsub f0, f31, f0 fmul f1, f1, f0 fmul f0, f1, f1 fmul f1, f30, f1 fmul f0, f2, f0 fsub f0, f31, f0 fmul f0, f1, f0 fmul f0, f2, f0 frsp f0, f0 stfs f0, 0x34(r1) lfs f2, 0x34(r1) .loc_0x130: fcmpo cr0, f28, f2 ble- .loc_0x140 fmr f28, f2 mr r28, r26 .loc_0x140: addi r30, r30, 0x68 addi r27, r27, 0x1 .loc_0x148: lhz r0, 0xC(r23) cmpw r27, r0 blt+ .loc_0x54 mr r3, r28 lmw r23, 0x64(r1) lwz r0, 0xAC(r1) lfd f31, 0xA0(r1) lfd f30, 0x98(r1) lfd f29, 0x90(r1) lfd f28, 0x88(r1) addi r1, r1, 0xA8 mtlr r0 blr */ } /* * --INFO-- * Address: 800898EC * Size: 000130 */ void CollInfo::getRandomCollPart(unsigned long) { /* .loc_0x0: mflr r0 stw r0, 0x4(r1) stwu r1, -0x270(r1) stmw r23, 0x24C(r1) addi r28, r3, 0 addi r29, r4, 0 addi r24, r1, 0x1C addi r26, r1, 0x18 addi r27, r1, 0x2C li r31, 0 li r30, 0 li r25, 0 b .loc_0x98 .loc_0x34: lwz r0, 0x4(r28) add r23, r0, r25 lbz r0, 0x5C(r23) cmplwi r0, 0x3 beq- .loc_0x90 lwz r4, 0x58(r23) addi r3, r24, 0 lwzu r0, 0x20(r4) li r5, 0x5 stw r0, 0x18(r1) addi r4, r4, 0x4 bl 0x18B078 addi r3, r26, 0 addi r4, r29, 0 li r5, 0x2A bl -0x45A74 rlwinm. r0,r3,0,24,31 beq- .loc_0x90 cmpwi r31, 0x80 bge- .loc_0x90 rlwinm r0,r31,2,0,29 stwx r23, r27, r0 addi r31, r31, 0x1 .loc_0x90: addi r25, r25, 0x68 addi r30, r30, 0x1 .loc_0x98: lhz r0, 0xC(r28) cmpw r30, r0 blt+ .loc_0x34 cmpwi r31, 0 ble- .loc_0x118 bl 0x18E6D8 xoris r0, r3, 0x8000 lfd f4, -0x7590(r2) stw r0, 0x244(r1) lis r4, 0x4330 xoris r0, r31, 0x8000 lfs f0, -0x7598(r2) stw r4, 0x240(r1) lfs f2, -0x75A8(r2) addi r3, r1, 0x2C lfd f1, 0x240(r1) stw r0, 0x23C(r1) fsubs f3, f1, f4 lfs f1, -0x7594(r2) stw r4, 0x238(r1) fdivs f3, f3, f0 lfd f0, 0x238(r1) fmuls f2, f2, f3 fsubs f0, f0, f4 fmuls f0, f0, f2 fmuls f0, f1, f0 fctiwz f0, f0 stfd f0, 0x230(r1) lwz r0, 0x234(r1) rlwinm r0,r0,2,0,29 lwzx r3, r3, r0 b .loc_0x11C .loc_0x118: li r3, 0 .loc_0x11C: lmw r23, 0x24C(r1) lwz r0, 0x274(r1) addi r1, r1, 0x270 mtlr r0 blr */ } /* * --INFO-- * Address: 80089A1C * Size: 0000D0 */ void CollInfo::getPlatform(DynCollObject*) { /* .loc_0x0: mflr r0 stw r0, 0x4(r1) stwu r1, -0x18(r1) stw r31, 0x14(r1) addi r31, r3, 0 addi r3, r4, 0 lwz r12, 0x0(r4) lwz r12, 0x3C(r12) mtlr r12 blrl cmplwi r3, 0 bne- .loc_0x38 li r3, 0 b .loc_0xBC .loc_0x38: lhz r0, 0xC(r31) li r9, 0 li r6, 0 cmpwi r0, 0 mtctr r0 ble- .loc_0xB8 .loc_0x50: lwz r8, 0x4(r31) li r5, 0 addi r4, r5, 0 add r7, r8, r6 lbz r0, 0x5C(r7) cmplwi r0, 0x3 bne- .loc_0x7C lwz r0, 0x58(r7) cmplwi r0, 0 beq- .loc_0x7C li r4, 0x1 .loc_0x7C: rlwinm. r0,r4,0,24,31 beq- .loc_0x98 lwz r4, 0x58(r7) lwz r0, 0x48(r4) cmplw r0, r3 bne- .loc_0x98 li r5, 0x1 .loc_0x98: rlwinm. r0,r5,0,24,31 beq- .loc_0xAC mulli r0, r9, 0x68 add r3, r8, r0 b .loc_0xBC .loc_0xAC: addi r6, r6, 0x68 addi r9, r9, 0x1 bdnz+ .loc_0x50 .loc_0xB8: li r3, 0 .loc_0xBC: lwz r0, 0x1C(r1) lwz r31, 0x14(r1) addi r1, r1, 0x18 mtlr r0 blr */ } /* * --INFO-- * Address: 80089AEC * Size: 000064 */ void CollInfo::updateInfo(Graphics&, bool) { /* .loc_0x0: mflr r0 stw r0, 0x4(r1) stwu r1, -0x30(r1) stmw r27, 0x1C(r1) li r30, 0 mulli r31, r30, 0x68 addi r27, r3, 0 addi r28, r4, 0 addi r29, r5, 0 b .loc_0x44 .loc_0x28: lwz r0, 0x4(r27) addi r4, r28, 0 addi r5, r29, 0 add r3, r0, r31 bl -0x1AA8 addi r31, r31, 0x68 addi r30, r30, 0x1 .loc_0x44: lhz r0, 0xC(r27) cmpw r30, r0 blt+ .loc_0x28 lmw r27, 0x1C(r1) lwz r0, 0x34(r1) addi r1, r1, 0x30 mtlr r0 blr */ } /* * --INFO-- * Address: 80089B50 * Size: 000014 */ void CollInfo::hasInfo() { /* .loc_0x0: lhz r0, 0xC(r3) neg r3, r0 subic r0, r3, 0x1 subfe r3, r0, r3 blr */ } /* * --INFO-- * Address: 80089B64 * Size: 0000A4 */ void CollInfo::initInfo(Shape*, CollPart*, unsigned long*) { /* .loc_0x0: mflr r0 stw r0, 0x4(r1) stwu r1, -0x20(r1) stw r31, 0x1C(r1) mr r31, r3 lbz r0, 0x0(r3) cmplwi r0, 0 beq- .loc_0x3C stw r5, 0x4(r31) stw r6, 0x8(r31) lwz r0, 0x4(r31) cmplwi r0, 0 beq- .loc_0x3C lwz r0, 0x8(r31) cmplwi r0, 0 .loc_0x3C: li r6, 0 li r5, 0 b .loc_0x5C .loc_0x48: lwz r3, 0x4(r31) addi r0, r5, 0x60 addi r6, r6, 0x1 stwx r31, r3, r0 addi r5, r5, 0x68 .loc_0x5C: lhz r0, 0xE(r31) cmpw r6, r0 blt+ .loc_0x48 stw r4, 0x10(r31) li r0, 0 addi r3, r31, 0 lwz r4, 0xF8(r4) li r5, 0 li r6, 0x1 sth r0, 0xC(r31) bl 0x148 mr r3, r31 bl 0x340 lwz r0, 0x24(r1) lwz r31, 0x1C(r1) addi r1, r1, 0x20 mtlr r0 blr */ } /* * --INFO-- * Address: ........ * Size: 0000DC */ void CollInfo::dumpInfo() { // UNUSED FUNCTION } /* * --INFO-- * Address: ........ * Size: 0000B0 */ void CollInfo::makeTubes(unsigned long, int) { // UNUSED FUNCTION } /* * --INFO-- * Address: 80089C08 * Size: 0000B0 */ void CollInfo::makeTubesChild(unsigned long, int) { /* .loc_0x0: mflr r0 stw r0, 0x4(r1) stwu r1, -0x38(r1) stw r31, 0x34(r1) addi r31, r5, 0 stw r30, 0x30(r1) addi r30, r4, 0 stw r29, 0x2C(r1) addi r29, r3, 0 bl 0x2C0 cmpwi r3, -0x1 bne- .loc_0x44 addi r3, r1, 0x14 addi r4, r30, 0 bl -0x45DAC li r0, 0 b .loc_0x50 .loc_0x44: mulli r0, r3, 0x68 lwz r3, 0x4(r29) add r0, r3, r0 .loc_0x50: cmpwi r31, 0 mtctr r31 mr r5, r0 li r0, 0x6 ble- .loc_0x94 .loc_0x64: lha r3, 0x54(r5) cmpwi r3, -0x1 beq- .loc_0x84 lwz r4, 0x60(r5) mulli r3, r3, 0x68 lwz r4, 0x4(r4) add r3, r4, r3 b .loc_0x88 .loc_0x84: li r3, 0 .loc_0x88: stb r0, 0x5C(r5) mr r5, r3 bdnz+ .loc_0x64 .loc_0x94: lwz r0, 0x3C(r1) lwz r31, 0x34(r1) lwz r30, 0x30(r1) lwz r29, 0x2C(r1) addi r1, r1, 0x38 mtlr r0 blr */ } /* * --INFO-- * Address: 80089CB8 * Size: 000078 */ void CollInfo::setUpdater(unsigned long, CollPartUpdater*) { /* .loc_0x0: mflr r0 stw r0, 0x4(r1) stwu r1, -0x38(r1) stw r31, 0x34(r1) addi r31, r5, 0 stw r30, 0x30(r1) addi r30, r4, 0 stw r29, 0x2C(r1) addi r29, r3, 0 bl 0x210 cmpwi r3, -0x1 bne- .loc_0x44 addi r3, r1, 0x14 addi r4, r30, 0 bl -0x45E5C li r3, 0 b .loc_0x50 .loc_0x44: mulli r0, r3, 0x68 lwz r3, 0x4(r29) add r3, r3, r0 .loc_0x50: cmplwi r3, 0 beq- .loc_0x5C stw r31, 0x64(r3) .loc_0x5C: lwz r0, 0x3C(r1) lwz r31, 0x34(r1) lwz r30, 0x30(r1) lwz r29, 0x2C(r1) addi r1, r1, 0x38 mtlr r0 blr */ } /* * --INFO-- * Address: 80089D30 * Size: 0001BC */ void CollInfo::createPart(ObjCollInfo*, int, bool) { /* .loc_0x0: mflr r0 stw r0, 0x4(r1) stwu r1, -0x28(r1) stw r31, 0x24(r1) stw r30, 0x20(r1) addi r30, r5, 0 stw r29, 0x1C(r1) mr. r29, r4 stw r28, 0x18(r1) addi r28, r3, 0 beq- .loc_0x19C lwz r0, 0x2C(r29) cmplwi r0, 0x2 bne- .loc_0x8C lhz r3, 0xC(r28) li r0, 0x3 lwz r4, 0x4(r28) mulli r3, r3, 0x68 add r8, r4, r3 stw r29, 0x58(r8) lhz r3, 0xC(r28) lwz r7, 0x14(r29) lwz r5, 0x8(r28) addi r4, r3, 0x1 rlwinm r3,r3,2,0,29 sth r4, 0xC(r28) stwx r7, r5, r3 stb r0, 0x5C(r8) lwz r4, 0xC(r29) cmplwi r4, 0 beq- .loc_0x19C addi r3, r28, 0 addi r5, r30, 0 bl .loc_0x0 b .loc_0x19C .loc_0x8C: lhz r3, 0xC(r28) lhz r0, 0xE(r28) cmplw r3, r0 blt- .loc_0xA0 b .loc_0x19C .loc_0xA0: mulli r0, r3, 0x68 lwz r3, 0x4(r28) add r31, r3, r0 stw r29, 0x58(r31) cmpwi r30, 0 lhz r4, 0xC(r28) lwz r7, 0x14(r29) lwz r5, 0x8(r28) addi r3, r4, 0x1 rlwinm r0,r4,2,0,29 sth r3, 0xC(r28) stwx r7, r5, r0 bne- .loc_0xEC lhz r0, 0xC(r28) cmplwi r0, 0x1 ble- .loc_0xEC li r0, 0x2 stb r0, 0x5C(r31) b .loc_0x144 .loc_0xEC: lwz r0, 0x10(r29) cmplwi r0, 0 beq- .loc_0x12C lis r4, 0x6379 addi r3, r29, 0x14 addi r4, r4, 0x6C2A li r5, 0x2A bl -0x45F50 rlwinm. r0,r3,0,24,31 beq- .loc_0x120 li r0, 0x4 stb r0, 0x5C(r31) b .loc_0x144 .loc_0x120: li r0, 0x1 stb r0, 0x5C(r31) b .loc_0x144 .loc_0x12C: cmpwi r30, 0 bgt- .loc_0x13C rlwinm. r0,r6,0,24,31 beq- .loc_0x144 .loc_0x13C: li r0, 0 stb r0, 0x5C(r31) .loc_0x144: lwz r4, 0x10(r29) cmplwi r4, 0 beq- .loc_0x180 lbz r0, 0x5C(r31) cmplwi r0, 0x2 bne- .loc_0x170 addi r3, r28, 0 addi r5, r30, 0 li r6, 0 bl .loc_0x0 b .loc_0x180 .loc_0x170: addi r3, r28, 0 addi r5, r30, 0x1 li r6, 0 bl .loc_0x0 .loc_0x180: lwz r4, 0xC(r29) cmplwi r4, 0 beq- .loc_0x19C addi r3, r28, 0 addi r5, r30, 0 li r6, 0 bl .loc_0x0 .loc_0x19C: lwz r0, 0x2C(r1) lwz r31, 0x24(r1) lwz r30, 0x20(r1) lwz r29, 0x1C(r1) lwz r28, 0x18(r1) addi r1, r1, 0x28 mtlr r0 blr */ } /* * --INFO-- * Address: 80089EEC * Size: 000044 */ void CollInfo::getId2Index(unsigned long) { /* .loc_0x0: lhz r0, 0xC(r3) li r7, 0 li r6, 0 cmpwi r0, 0 mtctr r0 ble- .loc_0x3C .loc_0x18: lwz r5, 0x8(r3) lwzx r0, r5, r6 cmplw r4, r0 bne- .loc_0x30 mr r3, r7 blr .loc_0x30: addi r6, r6, 0x4 addi r7, r7, 0x1 bdnz+ .loc_0x18 .loc_0x3C: li r3, -0x1 blr */ } /* * --INFO-- * Address: ........ * Size: 000048 */ void CollInfo::getIndex(ObjCollInfo*) { // UNUSED FUNCTION } /* * --INFO-- * Address: 80089F30 * Size: 0000F8 */ void CollInfo::makeTree() { /* .loc_0x0: li r4, 0 li r8, 0 b .loc_0xE8 .loc_0xC: lwz r10, 0x4(r3) add r11, r10, r8 lwz r9, 0x58(r11) lwz r5, 0xC(r9) cmplwi r5, 0 beq- .loc_0x68 cmpwi r0, 0 mtctr r0 li r6, 0 addi r7, r6, 0 ble- .loc_0x58 .loc_0x38: addi r0, r7, 0x58 lwzx r0, r10, r0 cmplw r0, r5 bne- .loc_0x4C b .loc_0x5C .loc_0x4C: addi r7, r7, 0x68 addi r6, r6, 0x1 bdnz+ .loc_0x38 .loc_0x58: li r6, -0x1 .loc_0x5C: extsh r0, r6 sth r0, 0x52(r11) b .loc_0x70 .loc_0x68: li r0, -0x1 sth r0, 0x52(r11) .loc_0x70: lwz r9, 0x10(r9) cmplwi r9, 0 beq- .loc_0xD0 lhz r0, 0xC(r3) li r6, 0 addi r7, r6, 0 cmpwi r0, 0 mtctr r0 ble- .loc_0xB8 .loc_0x94: lwz r5, 0x4(r3) addi r0, r7, 0x58 lwzx r0, r5, r0 cmplw r0, r9 bne- .loc_0xAC b .loc_0xBC .loc_0xAC: addi r7, r7, 0x68 addi r6, r6, 0x1 bdnz+ .loc_0x94 .loc_0xB8: li r6, -0x1 .loc_0xBC: lwz r5, 0x4(r3) extsh r6, r6 addi r0, r8, 0x54 sthx r6, r5, r0 b .loc_0xE0 .loc_0xD0: lwz r5, 0x4(r3) addi r0, r8, 0x54 li r6, -0x1 sthx r6, r5, r0 .loc_0xE0: addi r8, r8, 0x68 addi r4, r4, 0x1 .loc_0xE8: lhz r0, 0xC(r3) cmpw r4, r0 blt+ .loc_0xC blr */ } /* * --INFO-- * Address: 8008A028 * Size: 000004 */ void __sinit_collInfo_cpp(void) { }
20.401764
88
0.455057
doldecomp
b2dcd3b8f9252d53d633698b445e9f3890ae0b0c
1,562
cc
C++
stack/leetcode-155/soluction.cc
hello-chenchen/leet-code-algorithms
432132b8fa0a1f9575a9764743fbb79a01620102
[ "WTFPL" ]
null
null
null
stack/leetcode-155/soluction.cc
hello-chenchen/leet-code-algorithms
432132b8fa0a1f9575a9764743fbb79a01620102
[ "WTFPL" ]
null
null
null
stack/leetcode-155/soluction.cc
hello-chenchen/leet-code-algorithms
432132b8fa0a1f9575a9764743fbb79a01620102
[ "WTFPL" ]
null
null
null
#include <vector> #include <list> #include <iostream> using namespace std; class MinStack { public: /** initialize your data structure here. */ MinStack() { _M_val = new list<int>(); _M_min_val = new list<int>(); } ~MinStack() { delete _M_val; _M_val = NULL; delete _M_min_val; _M_min_val = NULL; } void push(int x) { if(0 == _M_val->size()) { _M_min_val->push_back(x); } else{ int minTop = _M_min_val->back(); if(x < minTop) { _M_min_val->push_back(x); } else { _M_min_val->push_back(minTop); } } _M_val->push_back(x); } void pop() { _M_val->pop_back(); _M_min_val->pop_back(); } int top() { return _M_val->back(); } int getMin() { return _M_min_val->back(); } private: list<int>* _M_val; list<int>* _M_min_val; }; /** * Your MinStack object will be instantiated and called as such: * MinStack* obj = new MinStack(); * obj->push(x); * obj->pop(); * int param_3 = obj->top(); * int param_4 = obj->getMin(); */ int main(int argc, char const *argv[]) { /* code */ MinStack minStack; minStack.push(-2); minStack.push(0); minStack.push(-3); // minStack.pop(); int a = minStack.getMin(); int b = minStack.top(); cout << a << endl; cout << b << endl; return 0; }
19.283951
65
0.486556
hello-chenchen
b2e033e72f62613d5fba612930bfb16fd8814d61
1,545
cpp
C++
Visual/Diploma/dialoglogenter.cpp
float-cat/diploma
e33d7ae173745e413d374c5b664e295491ac7b55
[ "Apache-2.0" ]
null
null
null
Visual/Diploma/dialoglogenter.cpp
float-cat/diploma
e33d7ae173745e413d374c5b664e295491ac7b55
[ "Apache-2.0" ]
null
null
null
Visual/Diploma/dialoglogenter.cpp
float-cat/diploma
e33d7ae173745e413d374c5b664e295491ac7b55
[ "Apache-2.0" ]
null
null
null
#include "dialoglogenter.h" #include "ui_dialoglogenter.h" #include "dialogreg.h" #include "ui_dialogreg.h" #include "ui_mainwindow.h" #include "mainwindow.h" DialogLogEnter::DialogLogEnter(QWidget *parent) : QDialog(parent), ui(new Ui::DialogLogEnter) { ui->setupUi(this); connect(ui->pushButton,SIGNAL(clicked(bool)),this,SLOT(DialogRegShow())); // connect(this,SIGNAL(Qsignal(QString)),parent,SLOT(MainWindow::Qslot)); nick[0] = 0; ui->lineEdit_2->setEchoMode(QLineEdit::Password); } DialogLogEnter::~DialogLogEnter() { delete ui; } char * DialogLogEnter::GetNick(void) { return nick; } void DialogLogEnter::DialogRegShow() { DialogReg *dr = new DialogReg(this); // f->close(); dr->open(); // close(); } void DialogLogEnter::on_pushButton_clicked() { this->setVisible(false); } void DialogLogEnter::on_pushButton_2_clicked() { //emit Qsignal(ui->lineEdit->text()); //emit close(); RegData forsend; forsend.fname[0] = 0; forsend.sname[0] = 0; forsend.hash[0] = 0; strcpy(forsend.nick, ui->lineEdit->text().toStdString().c_str()); core1->RegLog(forsend, 0); // strcpy(nick, ui->lineEdit->text().toStdString().c_str()); close(); } void DialogLogEnter::on_pushButton_3_clicked() { close(); // which affect? exit(0); } void DialogLogEnter::on_lineEdit_2_textChanged(const QString &arg1) { //ui->lineEdit_2->setEchoMode(QLineEdit::Password); // every change! }
22.071429
78
0.641424
float-cat
b2e6c2441fd190f123b9bf7c56f2c01bebabce85
673
hpp
C++
leetCode/872.Leaf-Similiar Trees.hpp
CainHsu/ProgramStudy-leetcode
23653e8927902aed64ba13a23a1d6c983b7ea5d5
[ "Apache-2.0" ]
1
2019-12-08T06:21:57.000Z
2019-12-08T06:21:57.000Z
leetCode/872.Leaf-Similiar Trees.hpp
CainHsu/ProgramStudy-leetcode
23653e8927902aed64ba13a23a1d6c983b7ea5d5
[ "Apache-2.0" ]
null
null
null
leetCode/872.Leaf-Similiar Trees.hpp
CainHsu/ProgramStudy-leetcode
23653e8927902aed64ba13a23a1d6c983b7ea5d5
[ "Apache-2.0" ]
null
null
null
// // Created by xuche on 2020/4/27. // #ifndef PROGRAMSTUDY_LEETCODE_872_LEAF_SIMILIAR_TREES_HPP #define PROGRAMSTUDY_LEETCODE_872_LEAF_SIMILIAR_TREES_HPP #include "../SourceCode/structs.hpp" #include "vector" using namespace std; vector<int> v1; void goDeeper(TreeNode* root){ if(!root) return; if(root->left) goDeeper(root->left); if(root->right) goDeeper(root->right); if(!root->left && !root->right) v1.emplace_back(root->val); } bool leafSimilar(TreeNode* root1, TreeNode* root2) { goDeeper(root1); vector<int> v2(v1); v1.clear(); goDeeper(root2); return v2 == v1; } #endif //PROGRAMSTUDY_LEETCODE_872_LEAF_SIMILIAR_TREES_HPP
23.206897
63
0.716196
CainHsu
b2ea86e461b7b0ef80b4709f573eb34e4cde9ff6
11,999
cpp
C++
NPSVisor/tools/svMaker/source/pProperty/svmPropertyPlotXY.cpp
NPaolini/NPS_OpenSource
0c7da066b02b57ce282a1903a3901a563d04a28f
[ "Unlicense" ]
null
null
null
NPSVisor/tools/svMaker/source/pProperty/svmPropertyPlotXY.cpp
NPaolini/NPS_OpenSource
0c7da066b02b57ce282a1903a3901a563d04a28f
[ "Unlicense" ]
null
null
null
NPSVisor/tools/svMaker/source/pProperty/svmPropertyPlotXY.cpp
NPaolini/NPS_OpenSource
0c7da066b02b57ce282a1903a3901a563d04a28f
[ "Unlicense" ]
null
null
null
//--------------- svmPropertyPlotXY.cpp ----------------------- //----------------------------------------------------------- #include "precHeader.h" //----------------------------------------------------------- #include <stdio.h> #include <stdlib.h> #include "svmPropertyPlotXY.h" #include "macro_utils.h" #include "PListBox.h" #include "POwnBtn.h" #include "PStatic.h" //----------------------------------------------------------- //----------------------------------------------------------- inline void chgBit(DWORD& bit, DWORD reset, DWORD set) { bit &= ~set; bit |= reset; } //----------------------------------------------------------- #define USE_COLOR_DW(dw,c) (!(dw & (1 << xScopeColors::c))) //---------------------------------------------------------------------------- #define USE_COLOR(c) USE_COLOR_DW(RefColors.notUseBit, c) //---------------------------------------------------------------------------- //----------------------------------------------------------- PropertyPlotXY::~PropertyPlotXY() { } //----------------------------------------------------------- void PropertyPlotXY::clone(const Property& other) { baseClass::clone(other); const PropertyPlotXY* po = dynamic_cast<const PropertyPlotXY*>(&other); if(po && po != this) { xScopeColor = po->getColors(); for(uint i = 0; i < SIZE_A(DataPrf); ++i) DataPrf[i] = po->DataPrf[i]; relativeBlock_Y = po->relativeBlock_Y; relativeBlock_X = po->relativeBlock_X; } } //----------------------------------------------------------- void PropertyPlotXY::cloneMinusProperty(const Property& other) { clone(other); } //----------------------------------------------------------- static ids Ids[] = { { IDC_COMBOBOX_PERIF_INIT_X, IDC_EDIT_ADDR_INIT_X, IDC_COMBOBOX_TYPEVAL_INIT_X, IDC_EDIT_NORMALIZ_INIT_X }, { IDC_COMBOBOX_PERIF_CURR_X, IDC_EDIT_ADDR_CURR_X_V, IDC_COMBOBOX_TYPEVAL_CURR_X_V, IDC_EDIT_NORMALIZ_CURR_X }, { IDC_COMBOBOX_PERIF_ENABLE_READ, IDC_EDIT_ADDR6, IDC_COMBOBOX_TYPEVAL6, IDC_EDIT_NORMALIZ6 }, }; //----------------------------------------------------------- static ids IdsEx[] = { { IDC_COMBOBOX_PERIF_MIN_Y, IDC_EDIT_ADDR_PXY_MIN_Y, IDC_COMBOBOX_TYPEVAL_PXY_MIN_Y, IDC_EDIT_NORMALIZ_PXY_MIN_Y }, { IDC_COMBOBOX_PERIF_MAX_Y, IDC_EDIT_ADDR_PXY_MAX_Y, IDC_COMBOBOX_TYPEVAL_PXY_MAX_Y, IDC_EDIT_NORMALIZ_PXY_MAX_Y }, { IDC_COMBOBOX_PERIF_MIN_X, IDC_EDIT_ADDR_PXY_MIN_X, IDC_COMBOBOX_TYPEVAL_PXY_MIN_X, IDC_EDIT_NORMALIZ_PXY_MIN_X }, { IDC_COMBOBOX_PERIF_MAX_X, IDC_EDIT_ADDR_PXY_MAX_X, IDC_COMBOBOX_TYPEVAL_PXY_MAX_X, IDC_EDIT_NORMALIZ_PXY_MAX_X }, { IDC_COMBOBOX_PERIF_NUM_DATA, IDC_EDIT_ADDR3, IDC_COMBOBOX_TYPEVAL3, IDC_EDIT_NORMALIZ3 }, }; //----------------------------------------------------------- void svmDialogPlotXY::check_const_prph(uint ids) { uint idcs[] = { IDC_BUTTON_NORMALIZ_PXY_MIN_Y, IDC_BUTTON_NORMALIZ_PXY_MAX_Y, IDC_BUTTON_NORMALIZ_PXY_MIN_X, IDC_BUTTON_NORMALIZ_PXY_MAX_X, IDC_BUTTON_NORMALIZ3 }; uint idlabel[] = { IDC_STATIC_XY_MINY, IDC_STATIC_XY_MAXY, IDC_STATIC_XY_MINX, IDC_STATIC_XY_MAXX, IDC_STATIC_XY_NDATA }; HWND hwnd = GetDlgItem(*this, ids); int sel = SendMessage(hwnd, CB_GETCURSEL, 0, 0); bool enableAll = PRPH_4_CONST_CB_SEL != sel; for(uint i = 0; i < SIZE_A(IdsEx); ++i) { if(IdsEx[i].idPrph == ids) { ENABLE(IdsEx[i].idNorm, enableAll); ENABLE(IdsEx[i].idType, true /*enableAll*/); ENABLE(idcs[i], enableAll); if(enableAll) SET_TEXT(idlabel[i], _T("Addr")); else SET_TEXT(idlabel[i], _T("Value")); break; } } } //----------------------------------------------------------- extern void invalidateSample(PWin* win); //----------------------------------------------------------- bool svmDialogPlotXY::create() { sxs = new sampleXScope(this, IDC_SAMPLE_XSCOPE); if(!baseClass::create()) return false; if(!(Prop->style & Property::FILL) && !(Prop->style & Property::TRANSP)) SET_CHECK(IDC_RADIOBUTTON_NO_BKG_PANEL); PropertyPlotXY* pt = dynamic_cast<PropertyPlotXY*>(tmpProp); sxs->setColors(pt->getColors()); invalidateSample(sxs); for(uint i = 0; i < SIZE_A(Ids); ++i) fillData(Ids[i], pt->DataPrf[i]); for(uint i = 0, j = SIZE_A(Ids); i < SIZE_A(IdsEx); ++i, ++j) fillDataEx(IdsEx[i], pt->DataPrf[j]); SET_INT(IDC_EDIT_NUM_ROW_XSCOPE, Prop->type1); SET_INT(IDC_EDIT_NUM_COL_XSCOPE, Prop->type2); DWORD notUseBit = pt->getColors().notUseBit; if(USE_COLOR_DW(notUseBit, cBkg)) SET_CHECK(IDC_CHECK_COL_BKG); if(USE_COLOR_DW(notUseBit, cGrid)) SET_CHECK(IDC_CHECK_COL_GRID); if(USE_COLOR_DW(notUseBit, cAxe)) SET_CHECK(IDC_CHECK_COL_AXES); checkEnableColor(); if(pt->relativeBlock_X) SET_CHECK(IDC_CHECK_AXES_X_REL); if(pt->relativeBlock_Y) SET_CHECK(IDC_CHECK_AXES_Y_REL); for(uint i = 0; i < SIZE_A(IdsEx); ++i) check_const_prph(IdsEx[i].idPrph); return true; } //----------------------------------------------------------- #define MAKE_COL_BIT(t) (1 << (DWORD)xScopeColors::t) //----------------------------------------------------------- void svmDialogPlotXY::chgBit(DWORD reset, DWORD set) { PropertyPlotXY* pt = dynamic_cast<PropertyPlotXY*>(tmpProp); xScopeColors& colors = pt->getColors(); ::chgBit(colors.notUseBit, reset, set); sxs->chgBit(reset, set); } //----------------------------------------------------------- void svmDialogPlotXY::setBitsColor(DWORD idc, bool alsoRadio) { bool active = IS_CHECKED(idc); DWORD value = 0; switch(idc) { case IDC_CHECK_COL_AXES: value = MAKE_COL_BIT(cAxe); break; case IDC_CHECK_COL_GRID: value = MAKE_COL_BIT(cGrid); break; case IDC_CHECK_COL_BKG: value = MAKE_COL_BIT(cBkg); if(alsoRadio) { SET_CHECK_SET(IDC_RADIOBUTTON_FILL_PANEL, active); SET_CHECK_SET(IDC_RADIOBUTTON_NO_BKG_PANEL, !active); } break; } if(value) { if(active) chgBit(0, value); else chgBit(value, 0); checkEnableColor(); invalidateSample(sxs); } } //----------------------------------------------------------- void svmDialogPlotXY::checkEnableColor() { bool enable = IS_CHECKED(IDC_CHECK_COL_BKG); EnableWindow(GetDlgItem(*this, IDC_BUTTON_XSCOPE_BKG), enable); enable = IS_CHECKED(IDC_CHECK_COL_GRID); EnableWindow(GetDlgItem(*this, IDC_BUTTON_XSCOPE_GRID), enable); enable = IS_CHECKED(IDC_CHECK_COL_AXES); EnableWindow(GetDlgItem(*this, IDC_BUTTON_XSCOPE_AXES), enable); } //----------------------------------------------------------- void svmDialogPlotXY::fillData(const ids& Ids, const dataPrf& DataPrf) { HWND hwnd = ::GetDlgItem(*this, Ids.idPrph); fillCBPerif(hwnd, DataPrf.perif); SET_INT(Ids.idAddr, DataPrf.addr); hwnd = ::GetDlgItem(*this, Ids.idType); fillCBTypeVal(hwnd, DataPrf.typeVal); SET_INT(Ids.idNorm, DataPrf.normaliz); } //----------------------------------------------------------- void svmDialogPlotXY::fillDataEx(const ids& Ids, const dataPrf& DataPrf) { HWND hwnd = ::GetDlgItem(*this, Ids.idPrph); int prph = DataPrf.perif; if(PRPH_4_CONST == prph) prph = PRPH_4_CONST_CB_SEL; fillCBPerifEx(hwnd, prph, true); setConstValue(GetDlgItem(*this, Ids.idAddr), DataPrf.addr, DataPrf.perif, DataPrf.typeVal); hwnd = ::GetDlgItem(*this, Ids.idType); fillCBTypeVal(hwnd, DataPrf.typeVal); SET_INT(Ids.idNorm, DataPrf.normaliz); } //----------------------------------------------------------- #define CHECK_NORM(a) \ case IDC_BUTTON_NORMALIZ##a: \ chooseNormaliz(IDC_EDIT_NORMALIZ##a); \ break //----------------------------------------------------------- LRESULT svmDialogPlotXY::windowProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) { switch(message) { case WM_COMMAND: switch(LOWORD(wParam)) { case IDC_BUTTON_XSCOPE_BKG: case IDC_BUTTON_XSCOPE_GRID: case IDC_BUTTON_XSCOPE_AXES: case IDC_BUTTON_XSCOPE_LINE1: case IDC_BUTTON_XSCOPE_LINE2: if(chooseColor(LOWORD(wParam))) drawColors(); break; case IDC_CHECK_COL_BKG: case IDC_CHECK_COL_GRID: case IDC_CHECK_COL_AXES: setBitsColor(LOWORD(wParam)); break; case IDC_RADIOBUTTON_FILL_PANEL: SET_CHECK(IDC_CHECK_COL_BKG); setBitsColor(IDC_CHECK_COL_BKG, false); break; case IDC_RADIOBUTTON_NO_BKG_PANEL: SET_CHECK_SET(IDC_CHECK_COL_BKG, false); setBitsColor(IDC_CHECK_COL_BKG, false); break; CHECK_NORM(_PXY_MIN_Y); CHECK_NORM(_PXY_MAX_Y); CHECK_NORM(_PXY_MIN_X); CHECK_NORM(_PXY_MAX_X); CHECK_NORM(_INIT_X); // CHECK_NORM(2); CHECK_NORM(3); case IDC_BUTTON_NORMALIZ_CURR_X_V: chooseNormaliz(IDC_EDIT_NORMALIZ_CURR_X); break; case IDC_COMBOBOX_PERIF_MIN_Y: case IDC_COMBOBOX_PERIF_MAX_Y: case IDC_COMBOBOX_PERIF_MIN_X: case IDC_COMBOBOX_PERIF_MAX_X: case IDC_COMBOBOX_PERIF_NUM_DATA: switch(HIWORD(wParam)) { case CBN_SELCHANGE: check_const_prph(LOWORD(wParam)); break; } break; } break; } return baseClass::windowProc(hwnd, message, wParam, lParam); } //----------------------------------------------------------- bool svmDialogPlotXY::chooseColor(uint idc) { PropertyPlotXY* pt = dynamic_cast<PropertyPlotXY*>(tmpProp); xScopeColors& colors = pt->getColors(); uint ix = 0; switch(idc) { case IDC_BUTTON_XSCOPE_BKG: break; case IDC_BUTTON_XSCOPE_GRID: ix = 1; break; case IDC_BUTTON_XSCOPE_AXES: ix = 2; break; case IDC_BUTTON_XSCOPE_LINE1: ix = 3; break; case IDC_BUTTON_XSCOPE_LINE2: ix = 4; break; } return choose_Color(*this, colors.Color[ix]); } //----------------------------------------------------------- void svmDialogPlotXY::drawColors() { PropertyPlotXY* pt = dynamic_cast<PropertyPlotXY*>(tmpProp); sxs->setColors(pt->getColors()); invalidateSample(sxs); } //----------------------------------------------------------- void svmDialogPlotXY::unfillData(const ids& Ids, dataPrf& DataPrf) { HWND hwnd = ::GetDlgItem(*this, Ids.idPrph); DataPrf.perif = SendMessage(hwnd, CB_GETCURSEL, 0, 0); GET_INT(Ids.idAddr, DataPrf.addr); hwnd = ::GetDlgItem(*this, Ids.idType); DataPrf.typeVal = SendMessage(hwnd, CB_GETCURSEL, 0, 0); GET_INT(Ids.idNorm, DataPrf.normaliz); } //----------------------------------------------------------- void svmDialogPlotXY::unfillDataEx(const ids& Ids, dataPrf& DataPrf) { HWND hwnd = ::GetDlgItem(*this, Ids.idPrph); DataPrf.perif = SendMessage(hwnd, CB_GETCURSEL, 0, 0); hwnd = ::GetDlgItem(*this, Ids.idType); if(PRPH_4_CONST_CB_SEL == DataPrf.perif) { DataPrf.perif = PRPH_4_CONST; TCHAR t[128]; GET_TEXT(Ids.idAddr, t); zeroTrim(t); DWORD v; DataPrf.typeVal = SendMessage(hwnd, CB_GETCURSEL, 0, 0); //4;//prfData::tDWData; bool isReal = getConstValue(t, v, DataPrf.typeVal); DataPrf.addr = v; DataPrf.normaliz = 0; } else { GET_INT(Ids.idAddr, DataPrf.addr); DataPrf.typeVal = SendMessage(hwnd, CB_GETCURSEL, 0, 0); GET_INT(Ids.idNorm, DataPrf.normaliz); } } //----------------------------------------------------------- void svmDialogPlotXY::CmOk() { PropertyPlotXY* pt = dynamic_cast<PropertyPlotXY*>(tmpProp); if(pt) { for(uint i = 0; i < SIZE_A(Ids); ++i) unfillData(Ids[i], pt->DataPrf[i]); for(uint i = 0, j = SIZE_A(Ids); i < SIZE_A(IdsEx); ++i, ++j) unfillDataEx(IdsEx[i], pt->DataPrf[j]); } GET_INT(IDC_EDIT_NUM_ROW_XSCOPE, tmpProp->type1); GET_INT(IDC_EDIT_NUM_COL_XSCOPE, tmpProp->type2); pt->relativeBlock_X = IS_CHECKED(IDC_CHECK_AXES_X_REL); pt->relativeBlock_Y = IS_CHECKED(IDC_CHECK_AXES_Y_REL); baseClass::CmOk(); } //-----------------------------------------------------------
33.330556
165
0.586632
NPaolini
b2ebc689200fcd6cb7335ce69aef5760e9d0085f
8,278
hpp
C++
lib/dmitigr/pgfe/sql_string.hpp
thevojacek/pgfe
22e85d4039c347dc4bb61bde8bdb0c4eeea860cf
[ "Zlib" ]
null
null
null
lib/dmitigr/pgfe/sql_string.hpp
thevojacek/pgfe
22e85d4039c347dc4bb61bde8bdb0c4eeea860cf
[ "Zlib" ]
null
null
null
lib/dmitigr/pgfe/sql_string.hpp
thevojacek/pgfe
22e85d4039c347dc4bb61bde8bdb0c4eeea860cf
[ "Zlib" ]
null
null
null
// -*- C++ -*- // Copyright (C) Dmitry Igrishin // For conditions of distribution and use, see files LICENSE.txt or pgfe.hpp #ifndef DMITIGR_PGFE_SQL_STRING_HPP #define DMITIGR_PGFE_SQL_STRING_HPP #include "dmitigr/pgfe/basics.hpp" #include "dmitigr/pgfe/dll.hpp" #include "dmitigr/pgfe/parameterizable.hpp" #include <memory> #include <string> namespace dmitigr::pgfe { /** * @ingroup utilities * * @brief A preparsed SQL strings. * * A dollar sign ("$") followed by digits is used to denote a parameter * with explicitly specified position. A colon (":") followed by alphanumerics * is used to denote a named parameter with automatically assignable position. * Currently the valid parameter positions are in range [1, 65535] and the * parameter_count() is always less than or equal to 65536. * * Examples of valid SQL strings: * * - the SQL string without parameters: * @code{sql} SELECT 1 @endcode * * - the SQL string with the positional and named parameters: * @code{sql} SELECT 2, $1::int, :name::text @endcode * * - the SQL string with named parameter: * @code{sql} WHERE :name = 'Dmitry Igrishin' @endcode */ class Sql_string : public Parameterizable { public: /// @name Constructors /// @{ /** * @returns A new instance of this class. * * @param input - the normal SQL input, which may contain multiple * commands and comments. Comments can contain an associated extra data. * * @remarks While the SQL input may contain multiple commands, the parser * stops on either semicolon or zero character. * * @see extra(). */ static DMITIGR_PGFE_API std::unique_ptr<Sql_string> make(const std::string& input); /** * @returns The copy of this instance. */ virtual std::unique_ptr<Sql_string> to_sql_string() const = 0; /// @} /** * @returns `true` if this SQL string is empty, or `false` otherwise. */ virtual bool is_empty() const = 0; /** * @returns `true` if this SQL string is consists only from comments and * blank line(-s), or `false` otherwise. */ virtual bool is_query_empty() const = 0; /** * @returns `false` if the parameter at specified `index` is missing, or * `true` otherwise. For example, the SQL string * @code{sql} SELECT :p, $3 @endcode * has two missing parameters at indexes `0` and `1`. * * @par Requires * `(index < positional_parameter_count())`. * * @remarks Missing parameters can only be eliminated by using append() * or replace_parameter(). Thus, by replacing the parameter `p` with `$2, $1` * in the example above, missing parameters will be eliminated because the * statement will become the following: * @code{sql} SELECT $2, $1, $3 @endcode */ virtual bool is_parameter_missing(std::size_t index) const = 0; /** * @returns `true` if this SQL string has a positional parameter with an index * `i` such that `(is_parameter_missing(i) == false)`, or `false` otherwise. * * @see is_parameter_missing(). */ virtual bool has_missing_parameters() const = 0; /** * @brief Appends the specified SQL string to this instance. * * @par Requires * `(appendix != nullptr)`. * * @par Effects * This instance contains the given `appendix`. If `(is_query_empty() == true)` * before calling this method, then extra data of `appendix` is appended to the * extra data of this instance. * * @par Exception safety guarantee * Strong. */ virtual void append(const Sql_string* appendix) = 0; /** * @overload */ virtual void append(const std::string& appendix) = 0; /** * @brief Replaces the parameter named by the `name` with the specified * `sql_string`. * * @par Requires * `(has_parameter(name) && replacement)`. * * @par Effects * This instance contains the given `replacement` instead of the parameter * named by the `name`. The extra data will *not* be affected. * * @par Exception safety guarantee * Strong. * * @see has_parameter(). */ virtual void replace_parameter(const std::string& name, const Sql_string* replacement) = 0; /** * @overload */ virtual void replace_parameter(const std::string& name, const std::string& replacement) = 0; /** * @returns The result of conversion of this instance to the instance of type `std::string`. */ virtual std::string to_string() const = 0; /** * @returns The query string that's actually passed to a PostgreSQL server. */ virtual std::string to_query_string() const = 0; /// @returns The extra data associated with this instance. /// /// An any data can be associated with an object of type Sql_string. The /// initial associations can be specified in the *related comments*. The /// related comments - are comments that have no more than one newline /// character in between themselves and the content following them. The /// content following the related comments should be neither named parameter /// nor positional parameter nor consisting only of spaces nor empty. /// /// Consider the example of the SQL input: /// @code{sql} /// -- This is the unrelated comment (because 2 new line feeds follows after it). /// -- $id$unrelated$id$ /// /// -- This is the related one line comment 1 /// -- $id$select-all$id$ /// /* $where$ /// * num > 0 /// * AND num < :num /// * $where$ /// */ /// -- This is the related one line comment 2 /// SELECT * FROM table WHERE :where; /// @endcode /// The SQL code above contains just one actual query: /// @code{sql}SELECT * FROM table WHERE :where@endcode /// This query has seven related comments and two unrelated comments (at the /// beginning) because there are two newline characters following them. Next, /// there are two data associations specified as a dollar-quoted string /// constants tagged as `id` and `where`. The valid characters of the tags /// are: alphanumerics, the underscore character and the dash. /// Please, note, that the content in between the named tags might consist to /// multiple lines. In such a cases there are rules of the content formatting: /// 1. The leading and trailing newline characters are always ignored and other /// newline characters are always preserved; /// 2. If the content begins with non newline character, then the content is /// associated exactly as provided, i.e. all indentations are preserved; /// 3. If the content begins with a newline character then the following lines /// will be left-aligned relative the *most left non space character*. In case /// of the sequence of one-line comments, the most left non space character are /// always follows the one-line comment marker ("--"). In case of the multi-line /// comment, the most left non space character can be a character that follows the /// asterisk with a space ("* "), or just the most left character. /// /// Examples: /// /// Example 1. The misaligned content of the association specified in the multi-line comment /// /// @code{sql} /// /* /// * $text1$ /// * one /// * two /// * three /// * $text1$ /// */ /// SELECT 1, 2, 3 /// @endcode /// /// The content of the `text1` association is "one\n * two\nthree". /// /// Example 2. The aligned content of the association specified in the multi-line comment /// /// @code{sql} /// /* /// * $text2$ /// * one /// * two /// * three /// * $text2$ /// */ /// SELECT 1, 2, 3 /// @endcode /// /// The content of the `text2` association is "one\ntwo\nthree". /// /// Example 3. The content of the association specified in the sequence of one-line comments /// /// @code{sql} /// -- $text3$ /// --one /// -- two /// -- three /// -- $text3$ /// SELECT 1, 2, 3 /// @endcode /// /// The content of the `text3` association is "one\n two\n three". virtual Composite* extra() = 0; /** * @overload */ virtual const Composite* extra() const = 0; private: friend detail::iSql_string; Sql_string() = default; }; } // namespace dmitigr::pgfe #ifdef DMITIGR_PGFE_HEADER_ONLY #include "dmitigr/pgfe/sql_string.cpp" #endif #endif // DMITIGR_PGFE_SQL_STRING_HPP
31.59542
94
0.656439
thevojacek
b2ec221905d5475066ee252865ca116c735e0729
742
hpp
C++
libs/common/include/common/time_utils.hpp
kiril-kirov/cpp-project
6078b337e4e9e62d5e3d2675e2a53f6e8d98eb19
[ "MIT" ]
1
2022-03-31T16:58:54.000Z
2022-03-31T16:58:54.000Z
libs/common/include/common/time_utils.hpp
kiril-kirov/cpp-project
6078b337e4e9e62d5e3d2675e2a53f6e8d98eb19
[ "MIT" ]
null
null
null
libs/common/include/common/time_utils.hpp
kiril-kirov/cpp-project
6078b337e4e9e62d5e3d2675e2a53f6e8d98eb19
[ "MIT" ]
null
null
null
#ifndef CPP_PROJECT_COMMON_TIME_UTILS_H #define CPP_PROJECT_COMMON_TIME_UTILS_H #include <chrono> #include <functional> namespace cpp_project::common { template<typename precision = std::chrono::microseconds, typename clock = std::chrono::high_resolution_clock> precision time_since(const typename clock::time_point& since) { return std::chrono::duration_cast<precision>(clock::now() - since); } template<typename precision = std::chrono::microseconds, typename clock = std::chrono::high_resolution_clock> precision measure_execution_time(const std::function<void()>& op) { const auto start = clock::now(); op(); return time_since<precision, clock>(start); } } // namespace cpp_project::common #endif
25.586207
71
0.745283
kiril-kirov
b2ed0d90b3c7517c7b704029dcfada319c6405be
1,251
hpp
C++
src/FrgCommon.hpp
Sourin-chatterjee/SpinParser
23fa90c327b8a4543e5afac1b64d18df40975182
[ "MIT" ]
18
2021-06-03T16:03:02.000Z
2022-02-28T00:48:53.000Z
src/FrgCommon.hpp
Sourin-chatterjee/SpinParser
23fa90c327b8a4543e5afac1b64d18df40975182
[ "MIT" ]
3
2021-10-08T15:51:51.000Z
2022-03-31T22:20:01.000Z
src/FrgCommon.hpp
Sourin-chatterjee/SpinParser
23fa90c327b8a4543e5afac1b64d18df40975182
[ "MIT" ]
2
2022-02-10T17:15:05.000Z
2022-02-11T19:54:27.000Z
/** * @file FrgCommon.hpp * @author Finn Lasse Buessen * @brief Hub for central objects in pf-FRG calculations. * * @copyright Copyright (c) 2020 */ #pragma once #include "FrequencyDiscretization.hpp" #include "CutoffDiscretization.hpp" #include "Lattice.hpp" /** * @brief Hub for central objects in pf-FRG calculations. */ struct FrgCommon { friend class SpinParser; public: /** * @brief Retrieve the lattice representation. * * @return const Lattice& Lattice representation. */ static const Lattice &lattice() { return *_lattice; } /** * @brief Retrieve the Matsubara frequency discretization. * * @return const FrequencyDiscretization& Matsubara frequency discretization. */ static const FrequencyDiscretization &frequency() { return *_frequency; } /** * @brief Retrieve the frequency cutoff discretization. * * @return const CutoffDiscretization& Frequency cutoff discretization. */ static const CutoffDiscretization &cutoff() { return *_cutoff; } private: static Lattice *_lattice; ///< Lattice representation. static FrequencyDiscretization *_frequency; ///< Matsubara frequency discretization. static CutoffDiscretization *_cutoff; ///< Frequency cutoff discretization. };
22.745455
86
0.724221
Sourin-chatterjee
b2ed260d49da6c5697fe711ba7b52ac67e956d68
59
cc
C++
experiments/foo.cc
maciekgajewski/exceptions-under-the-hood
b42e66f4f0b4f9c9e4fdf3ae56130fe5f6d26608
[ "MIT" ]
null
null
null
experiments/foo.cc
maciekgajewski/exceptions-under-the-hood
b42e66f4f0b4f9c9e4fdf3ae56130fe5f6d26608
[ "MIT" ]
null
null
null
experiments/foo.cc
maciekgajewski/exceptions-under-the-hood
b42e66f4f0b4f9c9e4fdf3ae56130fe5f6d26608
[ "MIT" ]
null
null
null
void baz(bool); void foo(bool t) { if (t) baz(t); }
8.428571
18
0.508475
maciekgajewski
b2f2c49651bcb0a460a307c4f3c716d414e758c1
4,888
cpp
C++
TopTestWidgets/privateSource/axisanimation.cpp
cy15196/xxxxRsmTest
36577173ef2cdfc3c3d4cadd3933849d29d5b3d9
[ "MIT" ]
1
2020-02-12T03:20:37.000Z
2020-02-12T03:20:37.000Z
TopTestWidgets/privateSource/axisanimation.cpp
cy15196/xxxxRsmTest
36577173ef2cdfc3c3d4cadd3933849d29d5b3d9
[ "MIT" ]
null
null
null
TopTestWidgets/privateSource/axisanimation.cpp
cy15196/xxxxRsmTest
36577173ef2cdfc3c3d4cadd3933849d29d5b3d9
[ "MIT" ]
1
2019-04-14T09:58:50.000Z
2019-04-14T09:58:50.000Z
/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the Qt Charts module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:GPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3 or (at your option) any later version ** approved by the KDE Free Qt Foundation. The licenses are as published by ** the Free Software Foundation and appearing in the file LICENSE.GPL3 ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <private/axisanimation_p.h> #include <private/chartaxiselement_p.h> #include <private/qabstractaxis_p.h> Q_DECLARE_METATYPE(QVector<qreal>) QT_CHARTS_BEGIN_NAMESPACE AxisAnimation::AxisAnimation(ChartAxisElement *axis, int duration, QEasingCurve &curve) : ChartAnimation(axis), m_axis(axis), m_type(DefaultAnimation) { setDuration(duration); setEasingCurve(curve); } AxisAnimation::~AxisAnimation() { } void AxisAnimation::setAnimationType(Animation type) { if (state() != QAbstractAnimation::Stopped) stop(); m_type = type; } void AxisAnimation::setAnimationPoint(const QPointF &point) { if (state() != QAbstractAnimation::Stopped) stop(); m_point = point; } void AxisAnimation::setValues(QVector<qreal> &oldLayout, QVector<qreal> &newLayout) { if (state() != QAbstractAnimation::Stopped) stop(); switch (m_type) { case ZoomOutAnimation: { QRectF rect = m_axis->gridGeometry(); oldLayout.resize(newLayout.count()); for (int i = 0, j = oldLayout.count() - 1; i < (oldLayout.count() + 1) / 2; ++i, --j) { oldLayout[i] = m_axis->axis()->orientation() == Qt::Horizontal ? rect.left() : rect.bottom(); oldLayout[j] = m_axis->axis()->orientation() == Qt::Horizontal ? rect.right() : rect.top(); } } break; case ZoomInAnimation: { int index = qMin(oldLayout.count() * (m_axis->axis()->orientation() == Qt::Horizontal ? m_point.x() : (1 - m_point.y())), newLayout.count() - (qreal)1.0); oldLayout.resize(newLayout.count()); if (index < 0) break; for (int i = 0; i < oldLayout.count(); i++) oldLayout[i] = oldLayout[index]; } break; case MoveForwardAnimation: { oldLayout.resize(newLayout.count()); for (int i = 0, j = i + 1; i < oldLayout.count() - 1; ++i, ++j) oldLayout[i] = oldLayout[j]; } break; case MoveBackwordAnimation: { oldLayout.resize(newLayout.count()); for (int i = oldLayout.count() - 1, j = i - 1; i > 0; --i, --j) oldLayout[i] = oldLayout[j]; } break; default: { oldLayout.resize(newLayout.count()); QRectF rect = m_axis->gridGeometry(); for (int i = 0, j = oldLayout.count() - 1; i < oldLayout.count(); ++i, --j) oldLayout[i] = m_axis->axis()->orientation() == Qt::Horizontal ? rect.left() : rect.top(); } break; } QVariantAnimation::KeyValues value; setKeyValues(value); //workaround for wrong interpolation call setKeyValueAt(0.0, qVariantFromValue(oldLayout)); setKeyValueAt(1.0, qVariantFromValue(newLayout)); } QVariant AxisAnimation::interpolated(const QVariant &start, const QVariant &end, qreal progress) const { QVector<qreal> startVector = qvariant_cast<QVector<qreal> >(start); QVector<qreal> endVecotr = qvariant_cast<QVector<qreal> >(end); QVector<qreal> result; Q_ASSERT(startVector.count() == endVecotr.count()) ; for (int i = 0; i < startVector.count(); i++) { qreal value = startVector[i] + ((endVecotr[i] - startVector[i]) * progress); result << value; } return qVariantFromValue(result); } void AxisAnimation::updateCurrentValue(const QVariant &value) { if (state() != QAbstractAnimation::Stopped) { //workaround QVector<qreal> vector = qvariant_cast<QVector<qreal> >(value); m_axis->setLayout(vector); m_axis->updateGeometry(); } } QT_CHARTS_END_NAMESPACE
33.251701
162
0.637275
cy15196
b2f352f381838149f0919f368e151c3db9dca1d0
4,469
cpp
C++
Engine/Source/Hect/IO/Path.cpp
colinhect/hect
2ef89be60ba9d450c5b56f5be6cef9803cc1855a
[ "MIT" ]
2
2015-01-17T00:56:34.000Z
2015-12-01T07:02:47.000Z
Engine/Source/Hect/IO/Path.cpp
colinhect/hect
2ef89be60ba9d450c5b56f5be6cef9803cc1855a
[ "MIT" ]
63
2015-01-06T17:42:22.000Z
2017-09-10T00:21:52.000Z
Engine/Source/Hect/IO/Path.cpp
colinhect/hect
2ef89be60ba9d450c5b56f5be6cef9803cc1855a
[ "MIT" ]
null
null
null
/////////////////////////////////////////////////////////////////////////////// // This source file is part of Hect. // // Copyright (c) 2016 Colin Hill // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. /////////////////////////////////////////////////////////////////////////////// #include "Path.h" #include "Hect/IO/Decoder.h" #include "Hect/IO/Encoder.h" using namespace hect; namespace { const char _path_delimiter = '/'; } Path::Path() { } Path::Path(const char* path) { set_raw_path(path); } Path::Path(const std::string& path) { set_raw_path(path.data()); } Path::Path(Name path) { set_raw_path(path.data()); } std::string Path::extension() const { // Find the position of the first '.' starting from the right size_t i = _raw_path.size(); for (; i > 0; --i) { if (_raw_path[i] == '.') { break; } } // Never found a '.' so there is no file extension if (i == 0) { return ""; } // Return the extension return _raw_path.substr(i + 1, _raw_path.size() - i - 1); } Path Path::parent_directory() const { // Find the position of the first '/' starting from the right size_t i = _raw_path.size(); for (; i > 0; --i) { if (_raw_path[i] == _path_delimiter) { break; } } // Never found a '/' so there is no parent directory if (i == 0) { return Path(); } // Return the parent directory return _raw_path.substr(0, i); } bool Path::empty() const { return _raw_path.empty(); } Path Path::operator+(const Path& path) const { Path result(*this); // Only add if the right-hand side is not empty if (!path._raw_path.empty()) { // Add a delimiter between the paths if the left-hand side is not // empty and the right-hand side does not start with a delimeter if (!result._raw_path.empty() && path._raw_path[0] != _path_delimiter) { result._raw_path += _path_delimiter; } result._raw_path.append(path._raw_path); } return result; } Path& Path::operator+=(const Path& path) { // Only add if the right-hand side is not empty if (!path._raw_path.empty()) { // Don't add the delimiter if this path is empty if (!_raw_path.empty()) { _raw_path += _path_delimiter; } _raw_path.append(path._raw_path); } return *this; } const std::string& Path::as_string() const { return _raw_path; } Name Path::as_name() const { return Name(_raw_path); } bool Path::operator<(const Path& path) const { return _raw_path < path._raw_path; } bool Path::operator==(const Path& path) const { return _raw_path == path._raw_path; } bool Path::operator!=(const Path& path) const { return _raw_path != path._raw_path; } void Path::set_raw_path(const char* raw_path) { _raw_path = std::string(raw_path); std::string delimiter(" /"); // Trim trailing delimiter size_t end = _raw_path.find_last_not_of(delimiter); _raw_path = _raw_path.substr(0, end + 1); } namespace hect { Encoder& operator<<(Encoder& encoder, const Path& path) { encoder << encode_value(path.as_string()); return encoder; } Decoder& operator>>(Decoder& decoder, Path& path) { std::string raw_path; decoder >> decode_value(raw_path); path = Path(raw_path); return decoder; } }
23.15544
79
0.620944
colinhect
b2f81003eea3d750a27c1a168ebb1777270dff14
3,018
cpp
C++
erizo/src/examples/pc/Observer.cpp
aalonsog/licode
0602a50a59e36f9435448d647e145137191b8397
[ "MIT" ]
1,766
2017-02-04T05:30:58.000Z
2022-03-30T08:20:40.000Z
erizo/src/examples/pc/Observer.cpp
ThePolarNight/licode
667b3cc9a353f6e2b9ad9c464971ab07f678991c
[ "MIT" ]
544
2017-02-02T11:27:08.000Z
2022-03-02T11:21:57.000Z
erizo/src/examples/pc/Observer.cpp
ThePolarNight/licode
667b3cc9a353f6e2b9ad9c464971ab07f678991c
[ "MIT" ]
617
2017-02-07T11:25:50.000Z
2022-03-18T02:33:18.000Z
/* * Observer.cpp */ #include <time.h> #include <boost/regex.hpp> #include "Observer.h" Observer::Observer(std::string name, SDPReceiver *receiver) : pc_(new PC(name)), name_(name), receiver_(receiver) { this->init(); } Observer::~Observer() { } void Observer::wait() { m_Thread_.join(); } void Observer::init() { m_Thread_ = boost::thread(&Observer::start, this); } void Observer::start() { pc_->RegisterObserver(this); pc_->Connect(name_); printf("Connected\n"); while (true) { pc_->OnHangingGetConnect(); pc_->OnHangingGetRead(); sleep(1); } } void Observer::processMessage(int peer_id, const std::string& message) { printf("Processing Message %d, %s", peer_id, message.c_str()); printf("OFFER1\n"); std::string roap = message; // Pillar el OffererId // Generar AnswererId if (name_ == "publisher") { if (!receiver_->createPublisher(peer_id)) return; } else { if (!receiver_->createSubscriber(peer_id)) return; } std::string sdp = receiver_->getLocalSDP(peer_id); std::string sdp2 = Observer::Match(roap, "^.*sdp\":\"(.*)\",.*$"); Observer::Replace(sdp2, "\\\\r\\\\n", "\\n"); printf("sdp OFFER!!!!!!!!!!!!\n%s\n", sdp2.c_str()); receiver_->setRemoteSDP(peer_id, sdp2); Observer::Replace(sdp, "\n", "\\\\r\\\\n"); std::string answererSessionId = "106"; // std::string offererSessionId = Observer::Match(roap, "^.*offererSessionId\":(.{32,32}).*$"); std::string offererSessionId = Observer::Match(roap, "^.*offererSessionId\":(...).*$"); std::string answer1("\n{\n \"messageType\":\"ANSWER\",\n"); printf("sdp ANSWEEEER!!!!!!! %s\n", sdp.c_str()); answer1.append(" \"sdp\":\"").append(sdp).append("\",\n"); answer1.append(" \"offererSessionId\":").append(offererSessionId).append( ",\n"); answer1.append(" \"answererSessionId\":").append(answererSessionId).append( ",\n"); answer1.append(" \"seq\" : 1\n}\n"); pc_->SendToPeer(peer_id, answer1); } void Observer::OnSignedIn() { } void Observer::OnDisconnected() { pthread_exit(0); } void Observer::OnPeerConnected(int id, const std::string& name) { } void Observer::OnPeerDisconnected(int peer_id) { receiver_->peerDisconnected(peer_id); } void Observer::OnMessageFromPeer(int peer_id, const std::string& message) { printf("OnMessageFromPeer\n"); printf("message : %s\n", message.c_str()); std::string roap = message; if (roap.find("OFFER") != std::string::npos) { boost::thread theThread(&Observer::processMessage, this, peer_id, message); } } void Observer::OnMessageSent(int err) { } void Observer::Replace(std::string& text, const std::string& pattern, const std::string& replace) { boost::regex regex_pattern(pattern, boost::regex_constants::perl); text = boost::regex_replace(text, regex_pattern, replace); } std::string Observer::Match(const std::string& text, const std::string& pattern) { boost::regex regex_pattern(pattern); boost::cmatch what; boost::regex_match(text.c_str(), what, regex_pattern); return (std::string(what[1].first, what[1].second)); }
26.946429
95
0.668655
aalonsog
b2f8895745e400b9d28131865f1f0d21ef9c5f61
310
hpp
C++
yugong/yugong-debug.hpp
microvm/libyugong
4828796b65100d11192926f16e314d29eb6fd702
[ "MIT" ]
4
2018-03-19T16:28:20.000Z
2018-11-30T13:50:17.000Z
yugong/yugong-debug.hpp
microvm/libyugong
4828796b65100d11192926f16e314d29eb6fd702
[ "MIT" ]
null
null
null
yugong/yugong-debug.hpp
microvm/libyugong
4828796b65100d11192926f16e314d29eb6fd702
[ "MIT" ]
null
null
null
#ifndef __YUGONG_DEBUG__ #define __YUGONG_DEBUG__ #include <cstdio> #define YG_DEBUG #ifdef YG_DEBUG #define yg_debug(fmt, ...) fprintf(stdout, "YG DEBUG [%s:%d:%s] " fmt,\ __FILE__, __LINE__, __func__, ## __VA_ARGS__) #else #define yg_debug(fmt, ...) #endif // YG_DEBUG #endif // __YUGONG_DEBUG__
19.375
71
0.7
microvm
b2fa2a549be13cf8e45d8582d3e8f5cf413a5b3c
4,486
cpp
C++
src_code/AdvancedQt/censusvisualizer/main.cpp
yanrong/book_demo
20cd13f3c3507a11e826ebbf22bd1c7bcb36e06f
[ "Apache-2.0" ]
null
null
null
src_code/AdvancedQt/censusvisualizer/main.cpp
yanrong/book_demo
20cd13f3c3507a11e826ebbf22bd1c7bcb36e06f
[ "Apache-2.0" ]
null
null
null
src_code/AdvancedQt/censusvisualizer/main.cpp
yanrong/book_demo
20cd13f3c3507a11e826ebbf22bd1c7bcb36e06f
[ "Apache-2.0" ]
null
null
null
/* Copyright (c) 2009-10 Qtrac Ltd. All rights reserved. This program or module 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. It is provided for educational purposes and 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. */ #include "censusvisualizer.hpp" #include <QAction> #include <QApplication> #include <QMainWindow> #include <QMenu> #include <QMenuBar> #include <QTableView> #include <QSplitter> #include <QStandardItemModel> #include <QStatusBar> void populateModel(QStandardItemModel *model) { const int Rows = 23; const int Columns = 3; int irish_census[Rows][Columns] = { // Year Males Females {1841, 3222485, 3306314}, {1851, 2494478, 2617079}, {1861, 2169042, 2233069}, {1871, 1992468, 2060719}, {1881, 1912438, 1957582}, {1891, 1728601, 1740093}, {1901, 1610085, 1611738}, {1911, 1589509, 1550179}, {1926, 1506889, 1465103}, {1936, 1520454, 1447966}, {1946, 1494877, 1460230}, {1951, 1506597, 1453996}, {1956, 1462928, 1435336}, {1961, 1416549, 1401792}, {1966, 1449032, 1434970}, {1971, 1495760, 1482488}, {1979, 1693272, 1674945}, {1981, 1729354, 1714051}, {1986, 1769690, 1770953}, {1991, 1753418, 1772301}, {1996, 1800232, 1825855}, {2002, 1946164, 1971039}, {2006, 2121171, 2118677}, }; QStandardItem *item; for (int row = 0; row < Rows; ++row) { QList<QStandardItem*> items; for (int column = 0; column <= Columns; ++column) { int number = column == Columns ? irish_census[row][1] + irish_census[row][2] : irish_census[row][column]; QString text = column == 0 ? QString::number(number) : QString("%L1").arg(number); item = new QStandardItem(text); item->setTextAlignment(Qt::AlignVCenter|Qt::AlignRight); items << item; } model->appendRow(items); } model->setHorizontalHeaderLabels(QStringList() << model->tr("Year") << model->tr("Males") << model->tr("Females") << model->tr("Total")); } int main(int argc, char *argv[]) { QApplication app(argc, argv); app.setApplicationName(app.translate("main", "Census Visualizer")); #ifdef Q_WS_MAC app.setCursorFlashTime(0); #endif QStandardItemModel *model = new QStandardItemModel; populateModel(model); CensusVisualizer *censusVisualizer = new CensusVisualizer; censusVisualizer->setModel(model); QTableView *tableView = new QTableView; tableView->setModel(model); tableView->resizeColumnsToContents(); QMainWindow *window = new QMainWindow; QMenu *fileMenu = window->menuBar()->addMenu( app.translate("main", "&File")); QAction *quitAction = fileMenu->addAction( app.translate("main", "&Quit")); QSplitter *splitter = new QSplitter; splitter->addWidget(tableView); splitter->addWidget(censusVisualizer); window->statusBar()->clearMessage(); // create statusbar + useful size grip window->setCentralWidget(splitter); window->resize(800, 350); window->setWindowTitle(app.translate("main", "%1 - Ireland") .arg(app.applicationName())); window->show(); window->connect(quitAction, SIGNAL(triggered()), window, SLOT(close())); window->connect(censusVisualizer, SIGNAL(clicked(const QModelIndex&)), tableView, SLOT(setCurrentIndex(const QModelIndex&))); // this connection is why the first item in the CensusVisualizer is // selected as startup window->connect(tableView->selectionModel(), SIGNAL(currentChanged(const QModelIndex&, const QModelIndex&)), censusVisualizer, SLOT(setCurrentIndex(const QModelIndex&))); int result = app.exec(); delete window; delete model; return result; }
35.603175
79
0.615247
yanrong
b2fc9f9c5609c9048368dd880a7f8db6c1b94107
5,335
cpp
C++
clang/lib/3C/ABounds.cpp
Machiry/checkedc-clang
ab9360d8be0a737cb5e09051f3a0051adc4b3e47
[ "BSD-Source-Code" ]
null
null
null
clang/lib/3C/ABounds.cpp
Machiry/checkedc-clang
ab9360d8be0a737cb5e09051f3a0051adc4b3e47
[ "BSD-Source-Code" ]
null
null
null
clang/lib/3C/ABounds.cpp
Machiry/checkedc-clang
ab9360d8be0a737cb5e09051f3a0051adc4b3e47
[ "BSD-Source-Code" ]
null
null
null
//=--ABounds.cpp--------------------------------------------------*- C++-*-===// // // 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 // //===----------------------------------------------------------------------===// // // This file contains the implementation of the methods in ABounds.h. // //===----------------------------------------------------------------------===// #include "clang/3C/ABounds.h" #include "clang/3C/AVarBoundsInfo.h" ABounds *ABounds::getBoundsInfo(AVarBoundsInfo *ABInfo, BoundsExpr *BExpr, const ASTContext &C) { ABounds *Ret = nullptr; CountBoundsExpr *CBE = dyn_cast<CountBoundsExpr>(BExpr->IgnoreParenCasts()); BoundsKey VK; if (CBE && !CBE->isCompilerGenerated()) { if (ABInfo->tryGetVariable(CBE->getCountExpr()->IgnoreParenCasts(), C, VK)) { ProgramVar *PV = ABInfo->getProgramVar(VK); if (PV->isNumConstant() && PV->getConstantVal() == 0) { // Invalid bounds. This is for functions like free. // Where the bounds is 0. Ret = nullptr; } else if (BExpr->isElementCount()) { Ret = new CountBound(VK); } else if (BExpr->isByteCount()) { Ret = new ByteBound(VK); } } } return Ret; } std::string ABounds::getBoundsKeyStr(BoundsKey BK, AVarBoundsInfo *ABI, Decl *D) { ProgramVar *PV = ABI->getProgramVar(BK); assert(PV != nullptr && "No Valid program var"); std::string BKStr = PV->getVarName(); unsigned PIdx = 0; auto *PVD = dyn_cast_or_null<ParmVarDecl>(D); // Does this belong to a function parameter? if (PVD && ABI->isFuncParamBoundsKey(BK, PIdx)) { // Then get the corresponding parameter in context of the given // Function and get its name. const FunctionDecl *FD = dyn_cast<FunctionDecl>(PVD->getDeclContext()); if (FD->getNumParams() > PIdx) { auto *NewPVD = FD->getParamDecl(PIdx); BKStr = NewPVD->getNameAsString(); // If the parameter in the new declaration does not have a name? // then use the old name. if (BKStr.empty()) BKStr = PV->getVarName(); } } return BKStr; } std::string ABounds::mkString(AVarBoundsInfo *ABI, clang::Decl *D, BoundsKey BK) { if (LowerBoundKey != 0 && LowerBoundKey != BK) return mkStringWithLowerBound(ABI, D); return mkStringWithoutLowerBound(ABI, D); } std::string CountBound::mkStringWithLowerBound(AVarBoundsInfo *ABI, clang::Decl *D) { std::string LowerBound = ABounds::getBoundsKeyStr(LowerBoundKey, ABI, D); // Assume that LowerBound is the same pointer type as this pointer this bound // acts on, so pointer arithmetic works as expected. return "bounds(" + LowerBound + ", " + LowerBound + " + " + ABounds::getBoundsKeyStr(LengthKey, ABI, D) + ")"; } std::string CountBound::mkStringWithoutLowerBound(AVarBoundsInfo *ABI, clang::Decl *D) { return "count(" + ABounds::getBoundsKeyStr(LengthKey, ABI, D) + ")"; } bool CountBound::areSame(ABounds *O, AVarBoundsInfo *ABI) { if (O != nullptr) { if (CountBound *OT = dyn_cast<CountBound>(O)) return ABI->areSameProgramVar(this->LengthKey, OT->LengthKey); } return false; } ABounds *CountBound::makeCopy(BoundsKey NK) { return new CountBound(NK); } std::string CountPlusOneBound::mkStringWithLowerBound(AVarBoundsInfo *ABI, clang::Decl *D) { std::string LowerBound = ABounds::getBoundsKeyStr(LowerBoundKey, ABI, D); return "bounds(" + LowerBound + ", " + LowerBound + " + " + ABounds::getBoundsKeyStr(LengthKey, ABI, D) + " + 1)"; } std::string CountPlusOneBound::mkStringWithoutLowerBound(AVarBoundsInfo *ABI, clang::Decl *D) { return "count(" + ABounds::getBoundsKeyStr(LengthKey, ABI, D) + " + 1)"; } bool CountPlusOneBound::areSame(ABounds *O, AVarBoundsInfo *ABI) { if (CountPlusOneBound *OT = dyn_cast_or_null<CountPlusOneBound>(O)) return ABI->areSameProgramVar(this->LengthKey, OT->LengthKey); return false; } std::string ByteBound::mkStringWithLowerBound(AVarBoundsInfo *ABI, clang::Decl *D) { std::string LowerBound = ABounds::getBoundsKeyStr(LowerBoundKey, ABI, D); // LowerBound will be a pointer to some type that is not necessarily char, so // pointer arithmetic will not give the behavior needed for a byte count. // First cast the pointer to a char pointer, and then add byte count. return "bounds(((_Array_ptr<char>)" + LowerBound + "), ((_Array_ptr<char>)" + LowerBound + ") + " + ABounds::getBoundsKeyStr(LengthKey, ABI, D) + ")"; } std::string ByteBound::mkStringWithoutLowerBound(AVarBoundsInfo *ABI, clang::Decl *D) { return "byte_count(" + ABounds::getBoundsKeyStr(LengthKey, ABI, D) + ")"; } bool ByteBound::areSame(ABounds *O, AVarBoundsInfo *ABI) { if (ByteBound *BB = dyn_cast_or_null<ByteBound>(O)) return ABI->areSameProgramVar(this->LengthKey, BB->LengthKey); return false; } ABounds *ByteBound::makeCopy(BoundsKey NK) { return new ByteBound(NK); }
39.518519
81
0.619869
Machiry
6504f994fbccbd93cff4aa1f4dbdce94ce9323f0
5,256
cpp
C++
filters/filtertool.cpp
NorbertWychowski/FilterApp-Qt
cf12b66b09212c768dca7b1740381beb34985b3e
[ "MIT" ]
null
null
null
filters/filtertool.cpp
NorbertWychowski/FilterApp-Qt
cf12b66b09212c768dca7b1740381beb34985b3e
[ "MIT" ]
null
null
null
filters/filtertool.cpp
NorbertWychowski/FilterApp-Qt
cf12b66b09212c768dca7b1740381beb34985b3e
[ "MIT" ]
null
null
null
#include "filtertool.h" #include "gaussianblur.h" #include "boxblur.h" #include <QtMath> #include <QtConcurrent/QtConcurrent> #include <QFutureSynchronizer> QImage FilterTool::splot(QImage &img, FILTER choose, Matrix userKernel) { Matrix kernel; QImage res; switch (choose) { case LAPLACE_FILTER: kernel = Matrix::getLaplaceKernel(); break; case HIGHPASS_FILTER: kernel = Matrix::getHighPassKernel(); break; case USER_FILTER: kernel = userKernel; break; default: break; } int N = kernel.getNDimension(); int M = kernel.getMDimension(); double norm = Matrix::getNorm(kernel); if (img.format() != QImage::Format_RGB32) img = img.convertToFormat(QImage::Format_RGB32); res = QImage(img.width() - N + 1, img.height() - N + 1, img.format()); auto f = [&](int start, int end) { int r = 0; int g = 0; int b = 0; QRgb color; if (start == 0) start += N / 2; if (end == img.height()) end -= N / 2; for (int y = start; y < end; ++y) { for (int x = N / 2; x < img.width() - N / 2; ++x) { for (int i = 0; i < M; ++i) { QRgb *imgLine = reinterpret_cast<QRgb *>(img.scanLine(y - N / 2 + i)); for (int j = 0; j < N; ++j) { color = imgLine[x - N + j]; r += kernel[i][j] * qRed(color); g += kernel[i][j] * qGreen(color); b += kernel[i][j] * qBlue(color); } } if (norm != 0.0) { r = qBound(0, int(r / norm), 255); g = qBound(0, int(g / norm), 255); b = qBound(0, int(b / norm), 255); } else { r = qBound(0, r, 255); g = qBound(0, g, 255); b = qBound(0, b, 255); } res.setPixel(x - N / 2, y - N / 2, qRgb(r, g, b)); r = g = b = 0; } } }; int maxThreads = QThread::idealThreadCount(); QFutureSynchronizer<void> futures; for (int i = 0; i < maxThreads; ++i) futures.addFuture(QtConcurrent::run(f, i * img.height() / maxThreads, (i + 1)*img.height() / maxThreads)); futures.waitForFinished(); return res; } QImage FilterTool::splot(QImage &img, FILTER choose, qint8 **selectedTab, Matrix userKernel) { Matrix kernel; QImage res; switch (choose) { case LAPLACE_FILTER: kernel = Matrix::getLaplaceKernel(); break; case HIGHPASS_FILTER: kernel = Matrix::getHighPassKernel(); break; case USER_FILTER: kernel = userKernel; break; default: break; } int N = kernel.getNDimension(); int M = kernel.getMDimension(); double norm = Matrix::getNorm(kernel); if (img.format() != QImage::Format_RGB32) img = img.convertToFormat(QImage::Format_RGB32); res = QImage(img.width() - N + 1, img.height() - N + 1, img.format()); int maxThreads = QThread::idealThreadCount(); QFutureSynchronizer<void> futures; auto f = [&](int start, int end) { int r = 0; int g = 0; int b = 0; QRgb color; if (start == 0) start += N / 2; if (end == img.height()) end -= N / 2; for (int y = start; y < end; ++y) { for (int x = N / 2; x < img.width() - N / 2; ++x) { if (selectedTab[y][x] == 1) { for (int i = 0; i < M; ++i) { QRgb *imgLine = reinterpret_cast<QRgb *>(img.scanLine(y - N / 2 + i)); for (int j = 0; j < N; ++j) { color = imgLine[x - N / 2 + j]; r += kernel[i][j] * qRed(color); g += kernel[i][j] * qGreen(color); b += kernel[i][j] * qBlue(color); } } if (norm != 0.0) { r = qBound(0, int(r / norm), 255); g = qBound(0, int(g / norm), 255); b = qBound(0, int(b / norm), 255); } else { r = qBound(0, r, 255); g = qBound(0, g, 255); b = qBound(0, b, 255); } res.setPixel(x - M / 2, y - N / 2, qRgb(r, g, b)); r = g = b = 0; } else { res.setPixel(x - M / 2, y - N / 2, img.pixel(x, y)); } } } }; for (int i = 0; i < maxThreads; ++i) futures.addFuture(QtConcurrent::run(f, i * img.height() / maxThreads, (i + 1)*img.height() / maxThreads)); futures.waitForFinished(); return res; } QImage FilterTool::gaussianFilter(QImage &image, int radius, qint8 **selectedTab) { return GaussianBlur(image).blur(radius, selectedTab); } QImage FilterTool::lowPassFilter(QImage &image, int radius, qint8 **selectedTab) { return BoxBlur(image).blur(radius, selectedTab); }
29.363128
114
0.457953
NorbertWychowski
6505144a1748c3fb3f092ba2fb848f15d81a13a4
2,388
hh
C++
include/token/crypto/provider.hh
tcsantanello/tokengov
1351f2358e9cce75c431f94b9086f285d0ea0072
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
include/token/crypto/provider.hh
tcsantanello/tokengov
1351f2358e9cce75c431f94b9086f285d0ea0072
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
include/token/crypto/provider.hh
tcsantanello/tokengov
1351f2358e9cce75c431f94b9086f285d0ea0072
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
#ifndef __TOKENIZATION_PROVIDER_HH__ #define __TOKENIZATION_PROVIDER_HH__ #include "token/crypto/base.hh" #include "token/crypto/encryption_key.hh" #include "token/crypto/hmac_key.hh" #include <boost/program_options.hpp> #include <map> #include <memory> #include <string> namespace token { namespace crypto { /** Encryption provider interface */ struct Provider { /** * @brief Get the encryption key * @param name encryption key name * @return encryption key */ virtual EncKey getEncKey( std::string name ) = 0; /** * @brief Get the hashing key * @param name hashing key name * @return hash key */ virtual MacKey getMacKey( std::string name ) = 0; /** * @brief Create and get an encryption key * @param name key name * @param parameters encryption key parameters * @return encryption key */ virtual EncKey createEncKey( std::string name, std::map< std::string, std::string > parameters ) { return nullptr; } /** * @brief Create and get a hash key * @param name key name * @param parameters hash key parameters * @return hash key */ virtual MacKey createMacKey( std::string name, std::map< std::string, std::string > parameters ) { return nullptr; } /** * @brief Fill the variable with random bytes * @param v variable */ template < typename T > void random( T *v ) { random( v, sizeof( *v ) ); } /** * @brief Fill the block up to length with random bytes * @param block memory block to fill * @param length number of bytes to fill */ virtual void random( void *block, size_t length ) = 0; /** * @brief Set the command line options * @param encOptions encryption options * @param macOptions hmac options */ virtual void cmdArgs( boost::program_options::options_description &encOptions, boost::program_options::options_description &macOptions ) {} /** * @brief String representation of the provider * @return string representation */ virtual operator std::string( ) { return ""; }; }; } // namespace crypto } // namespace token #endif //__TOKENIZATION_PROVIDER_HH__
27.767442
104
0.602178
tcsantanello
650ac1a6080d0d23eb64e11d18234479dab47922
1,240
hxx
C++
OCC/opencascade-7.2.0/x64/debug/inc/IntImp_ComputeTangence.hxx
jiaguobing/FastCAE
2348ab87e83fe5c704e4c998cf391229c25ac5d5
[ "BSD-3-Clause" ]
2
2020-02-21T01:04:35.000Z
2020-02-21T03:35:37.000Z
OCC/opencascade-7.2.0/x64/debug/inc/IntImp_ComputeTangence.hxx
Sunqia/FastCAE
cbc023fe07b6e306ceefae8b8bd7c12bc1562acb
[ "BSD-3-Clause" ]
1
2020-03-06T04:49:42.000Z
2020-03-06T04:49:42.000Z
OCC/opencascade-7.2.0/x64/debug/inc/IntImp_ComputeTangence.hxx
Sunqia/FastCAE
cbc023fe07b6e306ceefae8b8bd7c12bc1562acb
[ "BSD-3-Clause" ]
1
2021-11-21T13:03:26.000Z
2021-11-21T13:03:26.000Z
// Copyright (c) 1995-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #include <gp_Vec.hxx> #include <IntImp_ConstIsoparametric.hxx> #if !defined(_WIN32) || defined(__ApproxInt_DLL) || defined(__IntImp_DLL) || defined(__IntWalk_DLL) || defined(__GeomInt_DLL) || defined(__IntPatch_DLL) Standard_EXPORTEXTERN const IntImp_ConstIsoparametric *ChoixRef; #else Standard_IMPORT const IntImp_ConstIsoparametric *ChoixRef; #endif Standard_EXPORT Standard_Boolean IntImp_ComputeTangence(const gp_Vec DPuv[], const Standard_Real EpsUV[], Standard_Real Tgduv[], IntImp_ConstIsoparametric TabIso[]);
35.428571
152
0.775806
jiaguobing
650da005bbd0df57855baa602a16653cbabedd7b
4,946
cpp
C++
files/soko1/qutim_0.1.1/protocol/oscar/icq/privacylistwindow.cpp
truebsdorg/truebsdorg.github.io
8663d8f6fae3b1bb1e2fb29614677f2863521951
[ "BSD-4-Clause-UC" ]
null
null
null
files/soko1/qutim_0.1.1/protocol/oscar/icq/privacylistwindow.cpp
truebsdorg/truebsdorg.github.io
8663d8f6fae3b1bb1e2fb29614677f2863521951
[ "BSD-4-Clause-UC" ]
null
null
null
files/soko1/qutim_0.1.1/protocol/oscar/icq/privacylistwindow.cpp
truebsdorg/truebsdorg.github.io
8663d8f6fae3b1bb1e2fb29614677f2863521951
[ "BSD-4-Clause-UC" ]
null
null
null
/* privacyListWindow Copyright (c) 2008 by Rustam Chakin <qutim.develop@gmail.com> *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * *************************************************************************** */ #include "privacylistwindow.h" privacyListWindow::privacyListWindow(const QString &uin, QWidget *parent) : QWidget(parent), accountUin(uin) { ui.setupUi(this); setWindowTitle(tr("Privacy lists")); setWindowIcon(QIcon(":/icons/crystal_project/privacylist.png")); move(desktopCenter()); ui.visibleTreeWidget->setColumnWidth(2,22); ui.visibleTreeWidget->setColumnWidth(3,22); ui.visibleTreeWidget->setColumnWidth(1,200); ui.invisibleTreeWidget->setColumnWidth(2,22); ui.invisibleTreeWidget->setColumnWidth(3,22); ui.invisibleTreeWidget->setColumnWidth(1,200); ui.ignoreTreeWidget->setColumnWidth(2,22); ui.ignoreTreeWidget->setColumnWidth(3,22); ui.ignoreTreeWidget->setColumnWidth(1,200); createLists(); } privacyListWindow::~privacyListWindow() { } void privacyListWindow::rellocateDialogToCenter(QWidget *widget) { QDesktopWidget desktop; // Get current screen num int curScreen = desktop.screenNumber(widget); // Get available geometry of the screen QRect screenGeom = desktop.availableGeometry(curScreen); // Let's calculate point to move dialog QPoint moveTo(screenGeom.left(), screenGeom.top()); moveTo.setX(moveTo.x() + screenGeom.width() / 2); moveTo.setY(moveTo.y() + screenGeom.height() / 2); moveTo.setX(moveTo.x() - this->size().width() / 2); moveTo.setY(moveTo.y() - this->size().height() / 2); this->move(moveTo); } QPoint privacyListWindow::desktopCenter() { QDesktopWidget desktop; return QPoint(desktop.width() / 2 - size().width() / 2, desktop.height() / 2 - size().height() / 2); } void privacyListWindow::createLists() { QSettings contacts(QSettings::IniFormat, QSettings::UserScope, "qutim/ICQ."+accountUin, "contacts"); ui.visibleTreeWidget->clear(); QStringList visibleList = contacts.value("list/visible").toStringList(); foreach(QString uin, visibleList) { QTreeWidgetItem *buddy = new QTreeWidgetItem(ui.visibleTreeWidget); buddy->setText(0,uin); buddy->setText(1, contacts.value(uin + "/nickname", "").toString()); buddy->setIcon(2,QIcon(":/icons/crystal_project/contactinfo.png")); buddy->setIcon(3,QIcon(":/icons/crystal_project/delete_user.png")); } ui.invisibleTreeWidget->clear(); QStringList invisibleList = contacts.value("list/invisible").toStringList(); foreach(QString uin, invisibleList) { QTreeWidgetItem *buddy = new QTreeWidgetItem(ui.invisibleTreeWidget); buddy->setText(0,uin); buddy->setText(1, contacts.value(uin + "/nickname", "").toString()); buddy->setIcon(2,QIcon(":/icons/crystal_project/contactinfo.png")); buddy->setIcon(3,QIcon(":/icons/crystal_project/delete_user.png")); } ui.ignoreTreeWidget->clear(); QStringList ignoreList = contacts.value("list/ignore").toStringList(); foreach(QString uin, ignoreList) { QTreeWidgetItem *buddy = new QTreeWidgetItem(ui.ignoreTreeWidget); buddy->setText(0,uin); buddy->setText(1, contacts.value(uin + "/nickname", "").toString()); buddy->setIcon(2,QIcon(":/icons/crystal_project/contactinfo.png")); buddy->setIcon(3,QIcon(":/icons/crystal_project/delete_user.png")); } } void privacyListWindow::setOnline(bool online) { ui.ignoreTreeWidget->setColumnHidden(2, !online); ui.visibleTreeWidget->setColumnHidden(2, !online); ui.invisibleTreeWidget->setColumnHidden(2, !online); ui.ignoreTreeWidget->setColumnHidden(3, !online); ui.visibleTreeWidget->setColumnHidden(3, !online); ui.invisibleTreeWidget->setColumnHidden(3, !online); } void privacyListWindow::on_visibleTreeWidget_itemClicked(QTreeWidgetItem * item, int column) { if ( column == 2) emit openInfo(item->text(0), item->text(1), "", ""); if ( column == 3) { emit deleteFromPrivacyList(item->text(0), 0); delete item; } } void privacyListWindow::on_invisibleTreeWidget_itemClicked(QTreeWidgetItem * item, int column) { if ( column == 2) { emit openInfo(item->text(0), item->text(1), "", ""); } if ( column == 3) { emit deleteFromPrivacyList(item->text(0), 1); delete item; } } void privacyListWindow::on_ignoreTreeWidget_itemClicked(QTreeWidgetItem * item, int column) { if ( column == 2) emit openInfo(item->text(0), item->text(1), "", ""); if ( column == 3) { emit deleteFromPrivacyList(item->text(0), 2); delete item; } }
30.720497
101
0.671452
truebsdorg
650f3a9a5fd83c3c7ea9ce153bb6f71bc4682f3d
1,657
hpp
C++
include/simulator.hpp
brenov/caus
1c872de34871a228bfa556a3c4d97c13a54fbd9a
[ "MIT" ]
null
null
null
include/simulator.hpp
brenov/caus
1c872de34871a228bfa556a3c4d97c13a54fbd9a
[ "MIT" ]
null
null
null
include/simulator.hpp
brenov/caus
1c872de34871a228bfa556a3c4d97c13a54fbd9a
[ "MIT" ]
null
null
null
/* This file is part of CAUS. Copyright (c) 2019 by Breno Viana CAUS is a free software; you can redistribute it and/or modify it under the terms of the MIT License. */ #ifndef __CAUS_SIMULATOR_HPP__ #define __CAUS_SIMULATOR_HPP__ #include <iostream> #include <memory> #include <random> #include <string> #include <unistd.h> #include <vector> #include "cellular-automaton.hpp" #include "printer.hpp" #include "world.hpp" /*! * This class represents a Cellular Automata Simulator. */ class Simulator { private: std::shared_ptr<World> world; //< World std::unique_ptr<CellularAutomata> ca; //< Cellular Automata size_t max; //< Maximum number of generations std::vector<World> history; //< Evolution history public: /*! * Simulator constructor. * * \param max_ Maximum number of generations. * \param world_ World. * \param ca_ Cellular Automata. */ Simulator(size_t max_, std::shared_ptr<World> world_, std::unique_ptr<CellularAutomata> ca_); /*! * Get the world. * * \return World. */ World get_world(); /*! * Get the simulation history. * * \return List of worlds. */ std::vector<World> get_history(); /*! * Run simulation. */ void run(); /*! * Check if the simulation reaches stability. * * \return True if the simulation reaches stability and false otherwise. */ bool is_stable(); /*! * Generate a random world. * * \param world_ World. */ static void generate_world(std::shared_ptr<World> world_); }; #endif /* __CAUS_SIMULATOR_HPP__ */
20.974684
77
0.634279
brenov
6512d1062b959bbe3a200450ee59ce580fae26ce
8,757
cpp
C++
third_party/WebKit/Source/bindings/tests/results/core/V8TestCallbackInterface.cpp
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
third_party/WebKit/Source/bindings/tests/results/core/V8TestCallbackInterface.cpp
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
third_party/WebKit/Source/bindings/tests/results/core/V8TestCallbackInterface.cpp
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2014 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. // This file has been auto-generated by code_generator_v8.py. // DO NOT MODIFY! // This file has been generated from the Jinja2 template in // third_party/WebKit/Source/bindings/templates/callback_interface.cpp.tmpl // clang-format off #include "V8TestCallbackInterface.h" #include "bindings/core/v8/IDLTypes.h" #include "bindings/core/v8/NativeValueTraitsImpl.h" #include "bindings/core/v8/ScriptController.h" #include "bindings/core/v8/V8BindingForCore.h" #include "bindings/core/v8/V8TestInterfaceEmpty.h" #include "core/dom/ExecutionContext.h" #include "platform/wtf/Assertions.h" #include "platform/wtf/GetPtr.h" #include "platform/wtf/RefPtr.h" namespace blink { V8TestCallbackInterface::V8TestCallbackInterface(v8::Local<v8::Function> callback, ScriptState* scriptState) : script_state_(scriptState) { callback_.Set(scriptState->GetIsolate(), callback); } V8TestCallbackInterface::~V8TestCallbackInterface() {} DEFINE_TRACE(V8TestCallbackInterface) { TestCallbackInterface::Trace(visitor); } void V8TestCallbackInterface::voidMethod() { if (!script_state_->ContextIsValid()) return; ExecutionContext* executionContext = ExecutionContext::From(script_state_.Get()); DCHECK(!executionContext->IsContextSuspended()); if (!executionContext || executionContext->IsContextDestroyed()) return; ScriptState::Scope scope(script_state_.Get()); v8::Local<v8::Value> *argv = 0; v8::Isolate* isolate = script_state_->GetIsolate(); V8ScriptRunner::CallFunction(callback_.NewLocal(isolate), ExecutionContext::From(script_state_.Get()), v8::Undefined(isolate), 0, argv, isolate); } bool V8TestCallbackInterface::booleanMethod() { if (!script_state_->ContextIsValid()) return true; ExecutionContext* executionContext = ExecutionContext::From(script_state_.Get()); DCHECK(!executionContext->IsContextSuspended()); if (!executionContext || executionContext->IsContextDestroyed()) return true; ScriptState::Scope scope(script_state_.Get()); v8::Local<v8::Value> *argv = 0; v8::Isolate* isolate = script_state_->GetIsolate(); v8::TryCatch exceptionCatcher(isolate); exceptionCatcher.SetVerbose(true); V8ScriptRunner::CallFunction(callback_.NewLocal(isolate), executionContext, v8::Undefined(isolate), 0, argv, isolate); return !exceptionCatcher.HasCaught(); } void V8TestCallbackInterface::voidMethodBooleanArg(bool boolArg) { if (!script_state_->ContextIsValid()) return; ExecutionContext* executionContext = ExecutionContext::From(script_state_.Get()); DCHECK(!executionContext->IsContextSuspended()); if (!executionContext || executionContext->IsContextDestroyed()) return; ScriptState::Scope scope(script_state_.Get()); v8::Local<v8::Value> boolArgHandle = v8::Boolean::New(script_state_->GetIsolate(), boolArg); v8::Local<v8::Value> argv[] = { boolArgHandle }; v8::Isolate* isolate = script_state_->GetIsolate(); V8ScriptRunner::CallFunction(callback_.NewLocal(isolate), ExecutionContext::From(script_state_.Get()), v8::Undefined(isolate), 1, argv, isolate); } void V8TestCallbackInterface::voidMethodSequenceArg(const HeapVector<Member<TestInterfaceEmpty>>& sequenceArg) { if (!script_state_->ContextIsValid()) return; ExecutionContext* executionContext = ExecutionContext::From(script_state_.Get()); DCHECK(!executionContext->IsContextSuspended()); if (!executionContext || executionContext->IsContextDestroyed()) return; ScriptState::Scope scope(script_state_.Get()); v8::Local<v8::Value> sequenceArgHandle = ToV8(sequenceArg, script_state_->GetContext()->Global(), script_state_->GetIsolate()); v8::Local<v8::Value> argv[] = { sequenceArgHandle }; v8::Isolate* isolate = script_state_->GetIsolate(); V8ScriptRunner::CallFunction(callback_.NewLocal(isolate), ExecutionContext::From(script_state_.Get()), v8::Undefined(isolate), 1, argv, isolate); } void V8TestCallbackInterface::voidMethodFloatArg(float floatArg) { if (!script_state_->ContextIsValid()) return; ExecutionContext* executionContext = ExecutionContext::From(script_state_.Get()); DCHECK(!executionContext->IsContextSuspended()); if (!executionContext || executionContext->IsContextDestroyed()) return; ScriptState::Scope scope(script_state_.Get()); v8::Local<v8::Value> floatArgHandle = v8::Number::New(script_state_->GetIsolate(), floatArg); v8::Local<v8::Value> argv[] = { floatArgHandle }; v8::Isolate* isolate = script_state_->GetIsolate(); V8ScriptRunner::CallFunction(callback_.NewLocal(isolate), ExecutionContext::From(script_state_.Get()), v8::Undefined(isolate), 1, argv, isolate); } void V8TestCallbackInterface::voidMethodTestInterfaceEmptyArg(TestInterfaceEmpty* testInterfaceEmptyArg) { if (!script_state_->ContextIsValid()) return; ExecutionContext* executionContext = ExecutionContext::From(script_state_.Get()); DCHECK(!executionContext->IsContextSuspended()); if (!executionContext || executionContext->IsContextDestroyed()) return; ScriptState::Scope scope(script_state_.Get()); v8::Local<v8::Value> testInterfaceEmptyArgHandle = ToV8(testInterfaceEmptyArg, script_state_->GetContext()->Global(), script_state_->GetIsolate()); v8::Local<v8::Value> argv[] = { testInterfaceEmptyArgHandle }; v8::Isolate* isolate = script_state_->GetIsolate(); V8ScriptRunner::CallFunction(callback_.NewLocal(isolate), ExecutionContext::From(script_state_.Get()), v8::Undefined(isolate), 1, argv, isolate); } void V8TestCallbackInterface::voidMethodTestInterfaceEmptyStringArg(TestInterfaceEmpty* testInterfaceEmptyArg, const String& stringArg) { if (!script_state_->ContextIsValid()) return; ExecutionContext* executionContext = ExecutionContext::From(script_state_.Get()); DCHECK(!executionContext->IsContextSuspended()); if (!executionContext || executionContext->IsContextDestroyed()) return; ScriptState::Scope scope(script_state_.Get()); v8::Local<v8::Value> testInterfaceEmptyArgHandle = ToV8(testInterfaceEmptyArg, script_state_->GetContext()->Global(), script_state_->GetIsolate()); v8::Local<v8::Value> stringArgHandle = V8String(script_state_->GetIsolate(), stringArg); v8::Local<v8::Value> argv[] = { testInterfaceEmptyArgHandle, stringArgHandle }; v8::Isolate* isolate = script_state_->GetIsolate(); V8ScriptRunner::CallFunction(callback_.NewLocal(isolate), ExecutionContext::From(script_state_.Get()), v8::Undefined(isolate), 2, argv, isolate); } void V8TestCallbackInterface::callbackWithThisValueVoidMethodStringArg(ScriptValue thisValue, const String& stringArg) { if (!script_state_->ContextIsValid()) return; ExecutionContext* executionContext = ExecutionContext::From(script_state_.Get()); DCHECK(!executionContext->IsContextSuspended()); if (!executionContext || executionContext->IsContextDestroyed()) return; ScriptState::Scope scope(script_state_.Get()); v8::Local<v8::Value> thisHandle = thisValue.V8Value(); v8::Local<v8::Value> stringArgHandle = V8String(script_state_->GetIsolate(), stringArg); v8::Local<v8::Value> argv[] = { stringArgHandle }; v8::Isolate* isolate = script_state_->GetIsolate(); V8ScriptRunner::CallFunction(callback_.NewLocal(isolate), ExecutionContext::From(script_state_.Get()), thisHandle, 1, argv, isolate); } } // namespace blink
38.92
149
0.651365
metux
6512e4f9e76d0d40864da76d28d4bc429145a569
579
hpp
C++
rill/syntax_analysis/make_syntax_tree.hpp
rhysd/rill
cb16e511c6bdd4ea0b2bcbec51bd43724cc7ddcb
[ "BSL-1.0" ]
null
null
null
rill/syntax_analysis/make_syntax_tree.hpp
rhysd/rill
cb16e511c6bdd4ea0b2bcbec51bd43724cc7ddcb
[ "BSL-1.0" ]
null
null
null
rill/syntax_analysis/make_syntax_tree.hpp
rhysd/rill
cb16e511c6bdd4ea0b2bcbec51bd43724cc7ddcb
[ "BSL-1.0" ]
null
null
null
// // Copyright yutopp 2013 - . // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // #ifndef RILL_SYNTAX_ANALYSIS_MAKE_SYNTAX_TREE_HPP #define RILL_SYNTAX_ANALYSIS_MAKE_SYNTAX_TREE_HPP #include "../ast/ast.hpp" namespace rill { namespace syntax_analysis { auto make_syntax_tree( ast::native_string_t const& source ) -> ast::statements_ptr; } // namespace syntax_analysis } // namespace rill #endif /*RILL_SYNTAX_ANALYSIS_MAKE_SYNTAX_TREE_HPP*/
23.16
91
0.747841
rhysd
6514b131a02b23408a54ea8adc7d2ccd4bb57f80
3,706
cpp
C++
src/loottableeditordock.cpp
IoeCmcomc/MCDatapacker
5099d6ac2e0b15f4d61235b5b5ec41a847f588a1
[ "Apache-2.0" ]
2
2021-08-17T14:06:53.000Z
2022-01-29T14:14:59.000Z
src/loottableeditordock.cpp
IoeCmcomc/MCDatapacker
5099d6ac2e0b15f4d61235b5b5ec41a847f588a1
[ "Apache-2.0" ]
1
2021-06-20T20:12:10.000Z
2021-06-24T03:22:53.000Z
src/loottableeditordock.cpp
IoeCmcomc/MCDatapacker
5099d6ac2e0b15f4d61235b5b5ec41a847f588a1
[ "Apache-2.0" ]
null
null
null
#include "loottableeditordock.h" #include "ui_loottableeditordock.h" #include "mainwindow.h" #include "loottablepool.h" #include "loottablefunction.h" #include "globalhelpers.h" #include <QDebug> #include <QJsonArray> #include <QAction> #include <QItemSelection> #include <QJsonDocument> #include <QListView> LootTableEditorDock::LootTableEditorDock(QWidget *parent) : QDockWidget(parent), ui(new Ui::LootTableEditorDock) { ui->setupUi(this); if (MainWindow::getCurGameVersion() < QVersionNumber(1, 16)) { if (auto *view = qobject_cast<QListView *>(ui->lootTableTypeCombo->view())) { const auto &&model = static_cast<QStandardItemModel*>(ui->lootTableTypeCombo->model()); for (int i = 8; i < view->model()->rowCount(); ++i) { view->setRowHidden(i, true); model->item(i, 0)->setEnabled(false); } } } connect(ui->writeLootTableBtn, &QPushButton::clicked, this, &LootTableEditorDock::writeJson); connect(ui->readLootTableBtn, &QPushButton::clicked, this, &LootTableEditorDock::readJson); connect(ui->poolsInterface, &DataWidgetInterface::entriesCountChanged, this, &LootTableEditorDock::updatePoolsTab); connect(ui->functionsInterface, &DataWidgetInterface::entriesCountChanged, this, &LootTableEditorDock::updateFunctionsTab); auto *pool = new LootTablePool(); ui->poolsInterface->setupMainWidget(pool); auto *func = new LootTableFunction(); ui->functionsInterface->setupMainWidget(func); } LootTableEditorDock::~LootTableEditorDock() { delete ui; } void LootTableEditorDock::writeJson() { QJsonObject root; root.insert("type", "minecraft:" + types[ui->lootTableTypeCombo->currentIndex()]); QJsonArray pools = ui->poolsInterface->json(); if (!pools.isEmpty()) root.insert("pools", pools); QJsonArray functions = ui->functionsInterface->json(); if (!functions.isEmpty()) root.insert("functions", functions); qobject_cast<MainWindow*>(parent())-> setCodeEditorText(QJsonDocument(root).toJson()); } void LootTableEditorDock::readJson() { QString input = qobject_cast<MainWindow*>(parent())->getCodeEditorText(); QJsonDocument json_doc = QJsonDocument::fromJson(input.toUtf8()); if (json_doc.isNull() || (!json_doc.isObject())) return; QJsonObject root = json_doc.object(); if (root.isEmpty() || !root.contains("pools")) { return; } QString type = root.value("type").toString(); Glhp::removePrefix(type, "minecraft:"); const int index = types.indexOf(type); if (index > -1) { const auto &&model = static_cast<QStandardItemModel*>(ui->lootTableTypeCombo->model()); const auto &&item = model->item(index, 0); if (!item->isEnabled()) return; ui->lootTableTypeCombo->setCurrentIndex(index); } ui->poolsInterface->setJson(root.value("pools").toArray()); ui->functionsInterface->setJson(root.value("functions").toArray()); } void LootTableEditorDock::changeEvent(QEvent *event) { QDockWidget::changeEvent(event); if (event->type() == QEvent::LanguageChange) { ui->retranslateUi(this); updatePoolsTab(ui->poolsInterface->entriesCount()); updateFunctionsTab(ui->functionsInterface->entriesCount()); } } void LootTableEditorDock::updatePoolsTab(int size) { ui->tabWidget->setTabText(0, tr("Pools (%1)").arg(size)); } void LootTableEditorDock::updateFunctionsTab(int size) { ui->tabWidget->setTabText(1, tr("Functions (%1)").arg(size)); }
31.40678
82
0.655963
IoeCmcomc
6514e09f2f1ab3811fb77811406862aad6b829c0
992
cpp
C++
leaky.cpp
kienme/NetworksLab
d361cd29a0b5339d53560729c233bcba621ef441
[ "MIT" ]
null
null
null
leaky.cpp
kienme/NetworksLab
d361cd29a0b5339d53560729c233bcba621ef441
[ "MIT" ]
null
null
null
leaky.cpp
kienme/NetworksLab
d361cd29a0b5339d53560729c233bcba621ef441
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> using namespace std; int min(int a, int b) { return a < b ? a : b; } int main() { int cap; cout << "Enter bucket capacity: "; cin >> cap; int bw; cout << "Enter output bandwidth: "; cin >> bw; int time; cout << "Enter burst time: "; cin >> time; vector<int> in(time); cout << "\nEnter number of packets: \n"; for(int i = 0; i < time; ++i) { cout << "Time " << i << ": "; cin >> in[i]; } int bucket = 0, drop, t; cout << "\nTime\tIncoming\tOutgoing\tBucket\tDrop\n"; for(t = 0; t < time; ++t) { bucket += in[t]; if(bucket > cap) { drop = bucket - cap; bucket = cap; } else drop = 0; int send = min(bucket, bw); bucket -= send; cout << t << "\t" << in[t] << "\t\t" << send << "\t\t" << bucket << "\t" << drop << "\n"; } for(; bucket > 0; ++t) { int send = min(bucket, bw); bucket -= send; cout << t << "\t" << 0 << "\t\t" << send << "\t\t" << bucket << "\t" << 0 << "\n"; } return 0; }
16.262295
91
0.49496
kienme
6516e0ac9713a8a5782ecf75d9e983afd0d5406e
1,117
cpp
C++
ladder/src/ThreadPool.cpp
zoujiaqing/ladder
a4cee94d8032ef52bc1f04e386fa9150e11c7349
[ "BSD-3-Clause" ]
null
null
null
ladder/src/ThreadPool.cpp
zoujiaqing/ladder
a4cee94d8032ef52bc1f04e386fa9150e11c7349
[ "BSD-3-Clause" ]
4
2021-11-25T06:36:47.000Z
2022-02-19T15:13:41.000Z
ladder/src/ThreadPool.cpp
zoujiaqing/ladder
a4cee94d8032ef52bc1f04e386fa9150e11c7349
[ "BSD-3-Clause" ]
1
2022-01-24T02:38:54.000Z
2022-01-24T02:38:54.000Z
#include <ThreadPool.h> namespace ladder { ThreadPool::ThreadPool(size_t capacity) : capacity_(capacity), stopped_(false) { Init(); } void ThreadPool::Init() { for (size_t i = 0; i < capacity_; ++i) threads_.emplace_back(std::thread([this]() { Callback cur_task; while (1) { { std::unique_lock<std::mutex> lock(mutex_); condition_.wait(lock, [this]() { return stopped_ || !tasks_.empty(); }); if (stopped_ && tasks_.empty()) { break; } cur_task = std::move(tasks_.front()); tasks_.pop(); } cur_task(); } })); } ThreadPool::~ThreadPool() { { std::unique_lock<std::mutex> lock(mutex_); stopped_ = true; } condition_.notify_all(); for (size_t i = 0; i < threads_.size(); ++i) { threads_[i].join(); } } void ThreadPool::emplace(Callback&& f) { auto task = std::make_shared<Callback>(f); { std::unique_lock<std::mutex> lock(mutex_); tasks_.emplace([task]() { (*task)(); }); } condition_.notify_one(); } } // namespace ladder
22.34
80
0.550582
zoujiaqing
6517bf8bbff557e14fb5dd8d4be8ee169f253a62
693
cpp
C++
lib/test/TempPrivKeyFile.cpp
apastor/ads-chain-cpp-library
323d9c731f14031532dc072703d24e237d0a252e
[ "Apache-2.0" ]
2
2020-05-15T11:45:13.000Z
2020-05-20T17:26:43.000Z
lib/test/TempPrivKeyFile.cpp
apastor/ads-chain-cpp-library
323d9c731f14031532dc072703d24e237d0a252e
[ "Apache-2.0" ]
null
null
null
lib/test/TempPrivKeyFile.cpp
apastor/ads-chain-cpp-library
323d9c731f14031532dc072703d24e237d0a252e
[ "Apache-2.0" ]
null
null
null
#include <cstdio> #include "TempPrivKeyFile.h" TempPrivKeyFile::TempPrivKeyFile() : fileName(std::tmpnam(nullptr)), file(fileName, "w") { file << "-----BEGIN EC PARAMETERS-----" << '\n'; file << "BggqhkjOPQMBBw==" << '\n'; file << "-----END EC PARAMETERS-----" << '\n'; file << "-----BEGIN EC PRIVATE KEY-----" << '\n'; file << "MHcCAQEEIE4lZm6toHaabSxG6v9sCXT2E8IrYDx0QDYb67n5Ld/2oAoGCCqGSM49" << '\n'; file << "AwEHoUQDQgAEWXQk8rlGgf9prSod+VQf6CMpZmAO6b6Mqjmo4GUQfmowbiMr9l6/" << '\n'; file << "yfDW3AmdF75yY+4TCO8kgsqIRKEnq3Oj8Q==" << '\n'; file << "-----END EC PRIVATE KEY-----" << '\n'; }; TempPrivKeyFile::~TempPrivKeyFile() { std::remove(fileName.c_str()); };
38.5
85
0.621934
apastor
6517fae1186d2e9304125391f8927742df70f652
1,449
hpp
C++
include/physicsengine/Constraints.hpp
ThePythonator/Rocket-Manager
61489a9df2ac25b96ac337afd5cb58375533c748
[ "MIT" ]
2
2022-03-17T18:11:07.000Z
2022-03-17T19:55:35.000Z
include/physicsengine/Constraints.hpp
ThePythonator/Rocket-Manager
61489a9df2ac25b96ac337afd5cb58375533c748
[ "MIT" ]
null
null
null
include/physicsengine/Constraints.hpp
ThePythonator/Rocket-Manager
61489a9df2ac25b96ac337afd5cb58375533c748
[ "MIT" ]
null
null
null
#pragma once #include "PhysicsEngineMath.hpp" #include "RigidBody.hpp" namespace PhysicsEngine { extern const phyflt MINIMUM_NATURAL_LENGTH; // These constraints are treated as having no mass or volume, and cannot collide with any objects class Constraint { public: Constraint(); Constraint(RigidBody* _a, RigidBody* _b, phyvec _offset_a = PHYVEC_NULL, phyvec _offset_b = PHYVEC_NULL); virtual phyvec calculate_force() = 0; void apply_force(); bool is_broken(); RigidBody* a = nullptr; RigidBody* b = nullptr; phyvec offset_a; phyvec offset_b; // IDs can be used to: // - look up sprites and corresponding offsets to render at // - group rigidbodies when searching std::vector<uint32_t> ids; protected: bool broken = false; }; class Spring : public Constraint { public: Spring(RigidBody* _a, RigidBody* _b, phyvec _offset_a = PHYVEC_NULL, phyvec _offset_b = PHYVEC_NULL, phyflt _natural_length = 1.0, phyflt _modulus_of_elasticity = 1.0, phyflt max_extension = 1.0); phyvec calculate_force(); protected: const phyflt natural_length = 1.0; const phyflt modulus_of_elasticity = 1.0; const phyflt max_length = 2.0; }; class String : public Spring { public: String(RigidBody* _a, RigidBody* _b, phyvec _offset_a = PHYVEC_NULL, phyvec _offset_b = PHYVEC_NULL, phyflt _natural_length = 1.0, phyflt _modulus_of_elasticity = 1.0, phyflt max_extension = 1.0); phyvec calculate_force(); }; }
28.98
198
0.73637
ThePythonator
fb94466310e8a61e19b0ec8e751a02986cd9c224
5,502
cpp
C++
pin-3.22-98547-g7a303a835-gcc-linux/source/tools/Memory/malloc_stress.cpp
ArthasZhang007/15418FinalProject
a71f698ea48ebbc446111734c198f16a55633669
[ "MIT" ]
null
null
null
pin-3.22-98547-g7a303a835-gcc-linux/source/tools/Memory/malloc_stress.cpp
ArthasZhang007/15418FinalProject
a71f698ea48ebbc446111734c198f16a55633669
[ "MIT" ]
null
null
null
pin-3.22-98547-g7a303a835-gcc-linux/source/tools/Memory/malloc_stress.cpp
ArthasZhang007/15418FinalProject
a71f698ea48ebbc446111734c198f16a55633669
[ "MIT" ]
null
null
null
/* * Copyright (C) 2016-2021 Intel Corporation. * SPDX-License-Identifier: MIT */ #include <assert.h> #include <iostream> #include <fstream> #include "pin.H" using std::cerr; using std::cout; using std::endl; using std::flush; using std::string; /* ===================================================================== */ /* Commandline Switches */ /* ===================================================================== */ KNOB< string > KnobOutputFile(KNOB_MODE_WRITEONCE, "pintool", "o", "", "specify trace file name"); KNOB< UINT32 > KnobNumThreads(KNOB_MODE_WRITEONCE, "pintool", "n", "8", "Numbr Of Threads"); /* ===================================================================== */ /* Global Variables */ /* ===================================================================== */ std::ostream* TraceFile = 0; PIN_LOCK pinLock; struct Allocation { CHAR* Addr; UINT32 Size; PIN_THREAD_UID ThreadUid; BOOL ThreadStarted; Allocation() : Addr(0), Size(0), ThreadUid(INVALID_PIN_THREAD_UID), ThreadStarted(FALSE) {} }; std::vector< Allocation > allocations; /* ===================================================================== */ static void AbortProcess(const string& msg) { THREADID myTid = PIN_ThreadId(); PIN_GetLock(&pinLock, myTid + 1); *TraceFile << "malloc_stress test aborted: " << msg << "." << endl << flush; PIN_ReleaseLock(&pinLock); PIN_WriteErrorMessage(msg.c_str(), 1002, PIN_ERR_FATAL, 0); } static VOID SetNextSize(UINT32& currSize) { static const UINT32 SIZES_LENGTH = 6; static UINT32 sizes[SIZES_LENGTH] = {100, 4000, 30, 20, 6000, 24000}; for (UINT32 i = 0; i < SIZES_LENGTH; ++i) { if (currSize == sizes[i]) { ++i; currSize = sizes[i % SIZES_LENGTH]; return; } } if (currSize == 0) { currSize = sizes[0]; } } static VOID AllocateAndCheck(ADDRINT id) { if (allocations.at(id).Addr) { for (UINT32 i = 0; i < allocations.at(id).Size; ++i) { if (allocations.at(id).Addr[i] != CHAR(id)) { AbortProcess("Data corruption detected on allocated buffer"); } } free(allocations.at(id).Addr); } SetNextSize(allocations.at(id).Size); allocations.at(id).Addr = (CHAR*)malloc(allocations.at(id).Size); if (!allocations.at(id).Addr) { AbortProcess("Allocation failed"); } for (UINT32 i = 0; i < allocations.at(id).Size; ++i) { allocations.at(id).Addr[i] = id; } } VOID ThreadFunc(VOID* arg) { allocations.at((ADDRINT)arg).ThreadStarted = TRUE; static const UINT32 ALLOCATIONS_PER_THREAD = 10000; for (UINT32 j = 0; j < ALLOCATIONS_PER_THREAD; ++j) { AllocateAndCheck((ADDRINT)arg); } } VOID CheckFreeOfZero() { free(0); } VOID SpawnThreads() { allocations.resize(KnobNumThreads.Value()); for (ADDRINT threads_started = 0; threads_started < KnobNumThreads.Value(); ++threads_started) { PIN_THREAD_UID threadUid; *TraceFile << "Creating thread " << endl; if (PIN_SpawnInternalThread(ThreadFunc, (VOID*)threads_started, 0, &threadUid) == INVALID_THREADID) { AbortProcess("PIN_SpawnInternalThread failed"); } allocations.at(threads_started).ThreadUid = threadUid; } } /* ===================================================================== */ static VOID PrepareForFini(VOID* v) { for (UINT32 i = 0; i < KnobNumThreads.Value(); ++i) { if (!allocations.at(i).ThreadStarted) { *TraceFile << "Tool's thread " << i << " did not started" << endl; continue; } INT32 threadExitCode; INT32 MaxTimeToWait = 100000; BOOL waitStatus = PIN_WaitForThreadTermination(allocations.at(i).ThreadUid, MaxTimeToWait, &threadExitCode); if (!waitStatus) { AbortProcess("PIN_WaitForThreadTermination failed"); } if (threadExitCode != 0) { AbortProcess("Tool's thread exited abnormally"); } } *TraceFile << "All threads joined" << endl; } /* ===================================================================== */ /* Print Help Message */ /* ===================================================================== */ INT32 Usage() { cerr << "This tool test for malloc_stress" << endl; cerr << endl << KNOB_BASE::StringKnobSummary() << endl; return 1; } /* ===================================================================== */ /* Main */ /* ===================================================================== */ int main(int argc, char* argv[]) { PIN_InitLock(&pinLock); PIN_InitSymbols(); if (PIN_Init(argc, argv)) { return Usage(); } // Write to a file since cout and cerr maybe closed by the application TraceFile = KnobOutputFile.Value().empty() ? &cout : new std::ofstream(KnobOutputFile.Value().c_str()); CheckFreeOfZero(); PIN_AddPrepareForFiniFunction(PrepareForFini, 0); SpawnThreads(); *TraceFile << "All Threads Created" << endl; PIN_StartProgram(); return 0; } /* ===================================================================== */ /* eof */ /* ===================================================================== */
28.360825
120
0.497637
ArthasZhang007
fb95759360e5851e7ef46ae60d415b7a70ba0431
3,631
cpp
C++
src/libs/blueprint/c/conduit_blueprint_mcarray_c.cpp
adrienbernede/conduit
38379643d570941164b4fad76e269d2862f0e47b
[ "BSD-3-Clause" ]
120
2015-12-09T00:58:22.000Z
2022-03-25T00:14:39.000Z
src/libs/blueprint/c/conduit_blueprint_mcarray_c.cpp
adrienbernede/conduit
38379643d570941164b4fad76e269d2862f0e47b
[ "BSD-3-Clause" ]
808
2016-02-27T22:25:15.000Z
2022-03-30T23:42:12.000Z
src/libs/blueprint/c/conduit_blueprint_mcarray_c.cpp
adrienbernede/conduit
38379643d570941164b4fad76e269d2862f0e47b
[ "BSD-3-Clause" ]
49
2016-02-12T17:19:16.000Z
2022-02-01T14:36:21.000Z
// Copyright (c) Lawrence Livermore National Security, LLC and other Conduit // Project developers. See top-level LICENSE AND COPYRIGHT files for dates and // other details. No copyright assignment is required to contribute to Conduit. //----------------------------------------------------------------------------- /// /// file: conduit_blueprint_mcarray_c.cpp /// //----------------------------------------------------------------------------- #include "conduit_blueprint_mcarray.h" #include "conduit.hpp" #include "conduit_blueprint.hpp" #include "conduit_cpp_to_c.hpp" //----------------------------------------------------------------------------- // -- begin extern C //----------------------------------------------------------------------------- extern "C" { using namespace conduit; //----------------------------------------------------------------------------- /// Verify passed node confirms to the blueprint mcarray protocol. //----------------------------------------------------------------------------- int conduit_blueprint_mcarray_verify(const conduit_node *cnode, conduit_node *cinfo) { const Node &n = cpp_node_ref(cnode); Node &info = cpp_node_ref(cinfo); return (int)blueprint::mcarray::verify(n,info); } //----------------------------------------------------------------------------- /// Verify passed node confirms to given blueprint mcarray sub protocol. //----------------------------------------------------------------------------- int conduit_blueprint_mcarray_verify_sub_protocol(const char *protocol, const conduit_node *cnode, conduit_node *cinfo) { const Node &n = cpp_node_ref(cnode); Node &info = cpp_node_ref(cinfo); return (int)blueprint::mcarray::verify(std::string(protocol),n,info); } //---------------------------------------------------------------------------- int conduit_blueprint_mcarray_is_interleaved(const conduit_node *cnode) { const Node &n = cpp_node_ref(cnode); return (int)blueprint::mcarray::is_interleaved(n); } //----------------------------------------------------------------------------- int conduit_blueprint_mcarray_to_contiguous(const conduit_node *cnode, conduit_node *cdest) { const Node &n = cpp_node_ref(cnode); Node &dest = cpp_node_ref(cdest); return (int)blueprint::mcarray::to_contiguous(n,dest); } //----------------------------------------------------------------------------- int conduit_blueprint_mcarray_to_interleaved(const conduit_node *cnode, conduit_node *cdest) { const Node &n = cpp_node_ref(cnode); Node &dest = cpp_node_ref(cdest); return (int)blueprint::mcarray::to_interleaved(n,dest); } //----------------------------------------------------------------------------- /// Interface to generate example data //----------------------------------------------------------------------------- void conduit_blueprint_mcarray_examples_xyz(const char *mcarray_type, conduit_index_t npts, conduit_node *cres) { Node &res = cpp_node_ref(cres); blueprint::mcarray::examples::xyz(std::string(mcarray_type), npts, res); } } //----------------------------------------------------------------------------- // -- end extern C //-----------------------------------------------------------------------------
35.252427
79
0.426604
adrienbernede
fb9a0d4f15e3a4d25f8e46ee19331384304c156a
3,896
cpp
C++
programs/radialutils/radial-stat.cpp
nd-nuclear-theory/shell
7458fbd10416f6e1550a3d669cd2a10fc9c49e0c
[ "MIT" ]
5
2019-11-15T01:09:24.000Z
2021-02-02T20:23:34.000Z
programs/radialutils/radial-stat.cpp
nd-nuclear-theory/shell
7458fbd10416f6e1550a3d669cd2a10fc9c49e0c
[ "MIT" ]
8
2019-06-03T19:53:54.000Z
2021-06-14T00:40:04.000Z
programs/radialutils/radial-stat.cpp
nd-nuclear-theory/shell
7458fbd10416f6e1550a3d669cd2a10fc9c49e0c
[ "MIT" ]
null
null
null
/**************************************************************************/ /** @file radial-stat.cpp produce annotated radial files Syntax: ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ radial-stat input_file output_file ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @author Patrick J. Fasano University of Notre Dame + 08/11/17 (pjf): Created, based on radial-compose.cpp. + 10/12/17 (pjf): Update for changes to radial_io. + 11/28/17 (pjf): Print header with version. ******************************************************************************/ #include <sys/stat.h> #include <iostream> #include <iomanip> #include <string> #include <vector> #include "mcutils/profiling.h" #include "basis/nlj_orbital.h" #include "basis/nlj_operator.h" #include "obme/obme_io.h" //////////////////////////////////////////////////////////////// // process arguments ///////////////////////////////////////////////////////////////// // Stores simple parameters for run struct RunParameters { // filenames std::string input_filename; std::string output_filename; }; void PrintUsage(const char *argv[]) { std::cout << "Usage: " << argv[0] << " input_file output_file" << std::endl; } void ProcessArguments(const int argc, const char *argv[], RunParameters& run_parameters) { // argument counter int arg = 0; // usage message if (argc-1 != 2) { PrintUsage(argv); std::cerr << "ERROR: Wrong number of arguments." << std::endl; std::exit(EXIT_FAILURE); } // input file { std::istringstream parameter_stream(argv[++arg]); parameter_stream >> run_parameters.input_filename; if (!parameter_stream) { PrintUsage(argv); std::cerr << "ERROR: Invalid input filename." << std::endl; std::exit(EXIT_FAILURE); } struct stat st; if (stat(run_parameters.input_filename.c_str(), &st) != 0) { std::cerr << "ERROR: file " << run_parameters.input_filename << " does not exist!" << std::endl; std::exit(EXIT_FAILURE); } } // output file { std::istringstream parameter_stream(argv[++arg]); parameter_stream >> run_parameters.output_filename; if (!parameter_stream) { PrintUsage(argv); std::cerr << "ERROR: Invalid output filename." << std::endl; std::exit(EXIT_FAILURE); } struct stat st; if (stat(run_parameters.output_filename.c_str(), &st) == 0) { std::cerr << "WARN: overwriting file " << run_parameters.output_filename << std::endl; } } } int main(int argc, const char *argv[]) { // header std::cout << std::endl; std::cout << "radial-stat -- radial matrix element file statistics" << std::endl; std::cout << "version: " VCS_REVISION << std::endl; std::cout << std::endl; RunParameters run_parameters; ProcessArguments(argc, argv, run_parameters); // Read input shell::InOBMEStream inputs(run_parameters.input_filename); // get indexing basis::OrbitalSpaceLJPN bra_space, ket_space; basis::OrbitalSectorsLJPN sectors; basis::OneBodyOperatorType operator_type = inputs.operator_type(); shell::RadialOperatorType radial_operator_type = inputs.radial_operator_type(); int operator_power = inputs.radial_operator_power(); inputs.SetToIndexing(bra_space, ket_space, sectors); // Eigen initialization basis::OperatorBlocks<double> matrices; inputs.Read(matrices); inputs.Close(); // write out to file std::cout << "INFO: Writing to file " << run_parameters.output_filename << std::endl; shell::OutOBMEStream os(run_parameters.output_filename, bra_space, ket_space, sectors, operator_type, radial_operator_type, operator_power, true); // verbose_mode = true os.Write(matrices); os.Close(); return EXIT_SUCCESS; }
29.969231
102
0.588809
nd-nuclear-theory
fb9a6262fd49dcd5d10f6296719ea674e929d1e8
10,072
cpp
C++
src/main.cpp
shiinamiyuki/Accurate-Large-Scale-Ferrofluids
b39565ee94043b6ae19f14318af20f7489bc9312
[ "MIT" ]
12
2020-12-22T04:19:23.000Z
2021-11-08T15:47:32.000Z
src/main.cpp
shiinamiyuki/Accurate-Large-Scale-Ferrofluids
b39565ee94043b6ae19f14318af20f7489bc9312
[ "MIT" ]
null
null
null
src/main.cpp
shiinamiyuki/Accurate-Large-Scale-Ferrofluids
b39565ee94043b6ae19f14318af20f7489bc9312
[ "MIT" ]
4
2020-12-22T03:39:31.000Z
2021-11-03T04:42:16.000Z
#include "reconstruction.h" #include "simulation.h" #include <Eigen/Core> #include <atomic> #include <chrono> #include <igl/opengl/glfw/Viewer.h> #include <igl/writeOBJ.h> #include <iostream> #include <random> #include <thread> #include <atomic> #include <mutex> #include <condition_variable> #include <sstream> double reconstruction_iso = 0.5; Eigen::Vector3i reconstruction_res(200, 200, 200); Simulation setup_ferro_success() { std::vector<vec3> particles; { std::random_device rd; std::uniform_real_distribution<float> dist; for (float x = 0.3; x < 0.7; x += 0.02) { for (float z = 0.3; z < 0.7; z += 0.02) { for (float y = 0.0; y < 0.1; y += 0.01) { particles.emplace_back(x, y, z); } } } } Simulation sim(particles); sim.enable_ferro = true; sim.enable_gravity = false; sim.enable_interparticle_magnetization = false; sim.enable_interparticle_force = true; sim.dt = 0.0004; { sim.lower.x = 0.3; sim.lower.z = 0.3; sim.upper.x = 0.7; sim.upper.z = 0.7; } reconstruction_iso = 3.2; reconstruction_res = Eigen::Vector3i(150, 80, 150); return sim; } Simulation setup_ferro_with_gravity_success() { // gravity makes it more stable but makes spikes shorter std::vector<vec3> particles; { std::random_device rd; std::uniform_real_distribution<float> dist; for (float x = 0.3; x < 0.7; x += 0.02) { for (float z = 0.3; z < 0.7; z += 0.02) { for (float y = 0.0; y < 0.1; y += 0.01) { particles.emplace_back(x, y, z); } } } } Simulation sim(particles); sim.enable_ferro = true; sim.enable_gravity = true; sim.enable_interparticle_magnetization = false; sim.enable_interparticle_force = true; // sim.alpha = 10.0; sim.dt = 0.0004; { sim.lower.x = 0.3; sim.lower.z = 0.3; sim.upper.x = 0.7; sim.upper.z = 0.7; } reconstruction_iso = 3.2; reconstruction_res = Eigen::Vector3i(150, 80, 150); return sim; } Simulation setup_ferro_no_interparticle() { std::vector<vec3> particles; { std::random_device rd; std::uniform_real_distribution<float> dist; for (float x = 0.3; x < 0.7; x += 0.02) { for (float z = 0.3; z < 0.7; z += 0.02) { for (float y = 0.0; y < 0.1; y += 0.01) { particles.emplace_back(x, y, z); } } } } Simulation sim(particles); sim.alpha = 4.0; // sim.alpha = 1 makes the fluid really funny sim.enable_ferro = true; sim.enable_gravity = false; sim.enable_interparticle_magnetization = false; sim.enable_interparticle_force = false; sim.dt = 0.0001; { sim.lower.x = 0.3; sim.lower.z = 0.3; sim.upper.x = 0.7; sim.upper.z = 0.7; } reconstruction_iso = 0.5; reconstruction_res = Eigen::Vector3i(150, 80, 150); return sim; } Simulation setup_ferro_no_magnetic() { std::vector<vec3> particles; { std::random_device rd; std::uniform_real_distribution<float> dist; for (float x = 0.3; x < 0.7; x += 0.02) { for (float z = 0.3; z < 0.7; z += 0.02) { for (float y = 0.0; y < 0.1; y += 0.01) { particles.emplace_back(x, y, z); } } } } Simulation sim(particles); sim.alpha = 4.0; // sim.alpha = 1 makes the fluid really funny sim.enable_ferro = false; sim.enable_gravity = true; sim.enable_interparticle_magnetization = false; sim.enable_interparticle_force = false; sim.dt = 0.0001; { sim.lower.x = 0.3; sim.lower.z = 0.3; sim.upper.x = 0.7; sim.upper.z = 0.7; } reconstruction_iso = 0.5; reconstruction_res = Eigen::Vector3i(150, 80, 150); return sim; } Simulation setup_sph_fluid_crown() { std::vector<vec3> particles; { std::random_device rd; std::uniform_real_distribution<float> dist; for (float x = 0.3; x < 0.7; x += 0.02) { for (float z = 0.3; z < 0.7; z += 0.02) { for (float y = 0.0; y < 0.2; y += 0.01) { particles.emplace_back(x, y, z); } } } for (float x = 0.4; x < 0.6; x += 0.02) { for (float z = 0.4; z < 0.6; z += 0.02) { for (float y = 0.7; y < 0.9; y += 0.02) { vec3 c(0.5, 0.8, 0.5); if (length(vec3(x, y, z) - vec3(c)) < 0.1) particles.emplace_back(x, y, z); } } } } Simulation sim(particles); sim.enable_ferro = false; sim.enable_gravity = true; sim.enable_interparticle_magnetization = false; sim.enable_interparticle_force = false; sim.dt = 0.0002; { sim.lower.x = 0.3; sim.lower.z = 0.3; sim.upper.x = 0.7; sim.upper.z = 0.7; } sim.alpha = 0.4; sim.tension = 1000.0; reconstruction_iso = 4.0; reconstruction_res = Eigen::Vector3i(150, 80, 150); return sim; } Simulation setup_sph_wave_impact() { std::vector<vec3> particles; std::vector<vec3> velocity; { std::random_device rd; std::uniform_real_distribution<float> dist; for (float x = 0.0; x < 0.99; x += 0.02) { for (float z = 0.0; z < 0.99; z += 0.02) { for (float y = 0.0; y < 0.15; y += 0.02) { particles.emplace_back(x, y, z); vec3 p = vec3(x, y, z); vec3 v = (vec3(0.5, y, 0.5) - p); velocity.emplace_back(v); } } } } Simulation sim(particles, velocity); sim.enable_ferro = false; sim.enable_gravity = true; sim.enable_interparticle_magnetization = false; sim.enable_interparticle_force = false; sim.dt = 0.0003; sim.alpha = 0.04; sim.tension = 100; sim.c0 = 30; reconstruction_iso = 0.3; reconstruction_res = Eigen::Vector3i(150, 150, 150); return sim; } bool write_obj_sequence = false; int main(int argc, char **argv) { if (argc > 1) { if (std::strcmp(argv[1], "-s") == 0) { write_obj_sequence = true; } } std::atomic_bool run_sim(true); std::atomic_bool sim_ready(false); auto sim = setup_ferro_success(); // auto sim = setup_ferro_with_gravity_success(); // auto sim = setup_sph_wave_impact(); // auto sim = setup_sph_fluid_crown(); // auto sim = setup_ferro_no_interparticle(); // auto sim = setup_ferro_no_magnetic(); Eigen::MatrixXd PP; Eigen::MatrixXi PI; sim.visualize_field(PP, PI); bool flag = true; Eigen::MatrixXd P; P.resize(0, 3); std::mutex sim_lk; auto write_obj = [&] { Eigen::VectorXd mass, density; { std::lock_guard<std::mutex> lk(sim_lk); mass.resize(sim.num_particles); density.resize(sim.num_particles); mass.setConstant(sim.mass); for (size_t i = 0; i < sim.num_particles; i++) { density[i] = sim.pointers.density[i]; } } Eigen::MatrixXd V; Eigen::MatrixXi F; reconstruct(V, F, P, reconstruction_res, mass, density, sim.h, reconstruction_iso); std::time_t result = std::time(nullptr); std::ostringstream os; os << "sim-" << result << ".obj"; igl::writeOBJ(os.str(), V, F); }; auto write_obj_seq = [&](size_t iter) { Eigen::VectorXd mass, density; { std::lock_guard<std::mutex> lk(sim_lk); mass.resize(sim.num_particles); density.resize(sim.num_particles); mass.setConstant(sim.mass); for (size_t i = 0; i < sim.num_particles; i++) { density[i] = sim.pointers.density[i]; } } Eigen::MatrixXd V; Eigen::MatrixXi F; reconstruct(V, F, P, reconstruction_res, mass, density, sim.h, reconstruction_iso); printf("============== WRITE OBJ SEQUENCE =================\n"); std::ostringstream os; std::time_t result = std::time(nullptr); os << "sim-" << result << "-iter-" << sim.n_iter << ".obj"; igl::writeOBJ(os.str(), V, F); }; P.resize(sim.buffers.num_particles, 3); std::thread sim_thd([&] { while (flag) { if (!run_sim) { std::this_thread::sleep_for(std::chrono::milliseconds(100)); } else { { std::lock_guard<std::mutex> lk(sim_lk); sim.run_step(); sim_ready = true; } if (write_obj_sequence && sim.n_iter % 100 == 0) { write_obj_seq(sim.n_iter); } } } }); using Viewer = igl::opengl::glfw::Viewer; igl::opengl::glfw::Viewer viewer; viewer.data().set_edges(PP, PI, Eigen::RowVector3d(1, 0.47, 0.45)); viewer.callback_post_draw = [&](Viewer &) -> bool { if (sim_ready) { sim_ready = false; for (size_t i = 0; i < sim.buffers.num_particles; i++) { auto p = sim.buffers.particle_position[i]; P.row(i) = Eigen::RowVector3d(p.x, p.y, p.z); } viewer.data().point_size = 5; viewer.data().set_points(P, Eigen::RowVector3d(1, 1, 1)); } return false; }; viewer.callback_key_pressed = [&](Viewer &, unsigned int key, int) -> bool { if (key == ' ') { run_sim = !run_sim; } else if (key == 's') { write_obj(); } return false; }; viewer.core().is_animating = true; viewer.launch(); flag = false; sim_thd.join(); }
31.573668
104
0.524424
shiinamiyuki
fb9f6935cb45e29e4053d14c6c61786c6c01e5af
5,363
hpp
C++
foedus_code/foedus-core/include/foedus/cxx11.hpp
sam1016yu/cicada-exp-sigmod2017
64e582370076b2923d37b279d1c32730babc15f8
[ "Apache-2.0" ]
null
null
null
foedus_code/foedus-core/include/foedus/cxx11.hpp
sam1016yu/cicada-exp-sigmod2017
64e582370076b2923d37b279d1c32730babc15f8
[ "Apache-2.0" ]
null
null
null
foedus_code/foedus-core/include/foedus/cxx11.hpp
sam1016yu/cicada-exp-sigmod2017
64e582370076b2923d37b279d1c32730babc15f8
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2014-2015, Hewlett-Packard Development Company, LP. * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. You should have received a copy of the GNU General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * HP designates this particular file as subject to the "Classpath" exception * as provided by HP in the LICENSE.txt file that accompanied this code. */ #ifndef FOEDUS_CXX11_HPP_ #define FOEDUS_CXX11_HPP_ /** * @defgroup CXX11 C++11 Keywords in Public Headers * @ingroup IDIOMS * @brief Defines macros for hiding C++11 features in public headers for clients that use C++98. * @details * @par C++11 in libfoedus * We basically \b do \b assume \b C++11 and our library provides the best flexibility when the * client program enables C++11. For example, the client program can simply contain foedus-core * as a subfolder and statically link to it if C++11 is enabled. * However, some client program might have to stick to C++98. In that case, we provide our library * as an external shared library which comes with public headers that at least compile in C++98. * Thus, we will make sure C++11 keywords and classes do not directly appear in public header files. * The macros defined in this file are for that switching. * * @par DISABLE_CXX11_IN_PUBLIC_HEADERS macro * This macro is defined if __cplusplus < 201103L, meaning the compiler option for the programs * that include this header file (note: which is different from compiler option for libfoedus) * disables C++11. * If defined, our public headers must hide all C++11 dependent APIs. * So, there are several ifdefs on this macro in public headers. * * @par stdint.h vs cstdint * For the same reason, we include stdint.h rather than cstdint. * cstdint is a C++11 extension, which defines those integer types in std namespace * (eg std::int32_t). The integer types in global namespace are more concise to use, too. * * @par C++11 in cpp and non-public headers * Remember, this is only for public headers. We anyway compile our library with C++11. * We can freely use C++11 keywords/features in cpp and non-public header files, such as * xxx_impl.hpp, and xxx_pimpl.hpp. In other words, client programs must not include * them unless they turn on C++11. Also, impl/pimpl header files often include too much details * for client programs to rely on. They might change in next versions. */ #if __cplusplus < 201103L #ifndef NO_FOEDUS_CXX11_WARNING #pragma message("C++11 is disabled. libfoedus-core can be used without C++11,") #pragma message(" but enabling C++11 allows more flexible use of the library.") #pragma message(" To suppress this warning without enabling C++11, set -DNO_FOEDUS_CXX11_WARNING.") #endif // NO_FOEDUS_CXX11_WARNING /** * @def DISABLE_CXX11_IN_PUBLIC_HEADERS * @ingroup CXX11 * @brief If defined, our public headers must hide all C++11 dependent APIs. */ #define DISABLE_CXX11_IN_PUBLIC_HEADERS #endif // __cplusplus < 201103L /** * @def CXX11_FUNC_DELETE * @ingroup CXX11 * @brief Used in public headers in place of " = delete" of C++11. * @note C++98 : nothing. */ /** * @def CXX11_FUNC_DEFAULT * @ingroup CXX11 * @brief Used in public headers in place of " = default" of C++11. * @note C++98 : nothing. */ /** * @def CXX11_CONSTEXPR * @ingroup CXX11 * @brief Used in public headers in place of "constexpr" of C++11. * @note C++98 : nothing. */ /** * @def CXX11_FINAL * @ingroup CXX11 * @brief Used in public headers in place of "final" of C++11. * @note C++98 : nothing. */ /** * @def CXX11_NULLPTR * @ingroup CXX11 * @brief Used in public headers in place of "nullptr" of C++11. * @note C++98 : NULL. */ /** * @def CXX11_NOEXCEPT * @ingroup CXX11 * @brief Used in public headers in place of "noexcept" of C++11. * @note C++98 : nothing. */ /** * @def CXX11_OVERRIDE * @ingroup CXX11 * @brief Used in public headers in place of "override" of C++11. * @note C++98 : nothing. */ /** * @def CXX11_STATIC_ASSERT * @ingroup CXX11 * @brief Used in public headers in place of "static_assert" of C++11. * @note C++98 : nothing. */ #ifdef DISABLE_CXX11_IN_PUBLIC_HEADERS #include <cstddef> // for NULL #define CXX11_FUNC_DELETE #define CXX11_FUNC_DEFAULT #define CXX11_CONSTEXPR #define CXX11_FINAL #define CXX11_NULLPTR NULL #define CXX11_NOEXCEPT #define CXX11_OVERRIDE #define CXX11_STATIC_ASSERT(expr, message) #else // DISABLE_CXX11_IN_PUBLIC_HEADERS #define CXX11_FUNC_DELETE = delete #define CXX11_FUNC_DEFAULT = default #define CXX11_CONSTEXPR constexpr #define CXX11_FINAL final #define CXX11_NULLPTR nullptr #define CXX11_NOEXCEPT noexcept #define CXX11_OVERRIDE override #define CXX11_STATIC_ASSERT(expr, message) static_assert(expr, message) #endif // DISABLE_CXX11_IN_PUBLIC_HEADERS #endif // FOEDUS_CXX11_HPP_
38.582734
100
0.739511
sam1016yu
fb9fe42b73ba31654fc74d97fb8203b30e38e4cc
11,529
cpp
C++
Arduino/dist_control.cpp
gonced8/SCDTR-Project
ec0a54039704b90665284cd4f1d0386df4b78452
[ "MIT" ]
null
null
null
Arduino/dist_control.cpp
gonced8/SCDTR-Project
ec0a54039704b90665284cd4f1d0386df4b78452
[ "MIT" ]
null
null
null
Arduino/dist_control.cpp
gonced8/SCDTR-Project
ec0a54039704b90665284cd4f1d0386df4b78452
[ "MIT" ]
null
null
null
// Implementation of distributed control related functions #include "dist_control.h" /*-------Variable definition--------*/ // LDR calibration const float m[3] = {-0.67, -0.72, -0.718}; // LDR calibration float b[3] = {1.763, 1.763, 1.763}; // LDR calibration float k[3] = {0.0, 0.0, 0.0}; // Gains // Control related variables float luxRefUnocc = 30; float luxRefOcc = 70; bool deskOccupancy = false; // Optimization const float infinity = 1.0 / 0.0; // Actuation float measuredLux = 0; extern float u_pid; extern float u_con; extern float u; extern PID pid; /*--------Function definition--------*/ float getLux(int measurement) { float Vldr, Rldr, lux; measurement = map(measurement, 0, 1023, 0, 5000); Vldr = Vcc - measurement; Rldr = (float) Vldr * R1 / (Vcc - Vldr); lux = pow(10, (float) (log10(Rldr) - b[nodeId - 1]) / m[nodeId - 1]); return lux; } void LedConsensus::init(byte _nodeId, byte _nNodes, float _rho, byte _c_i) { nodeId = _nodeId; nNodes = _nNodes; // Consensus setup rho = _rho; c_i = _c_i; remainingIters = maxIters; for (int i = 0; i < nNodes; i++) { y[i] = 0; c[i] = 0; dNode[i] = 0; dNodeOverall[i] = 0; dAvg[i] = 0; dColumn[i] = 0; } c[nodeId - 1] = c_i; // Ref setup if (deskOccupancy) { setLocalL(luxRefOcc); } else { setLocalL(luxRefUnocc); } // Comms setup last_time = millis(); state = 3; first = true; } byte LedConsensus::getState() { return state; } bool LedConsensus::detectChanges() { if (abs(u_pid) > threshold || changedLuxRef || changedCost) { //if (changedLuxRef || changedCost) { changedLuxRef = false; changedCost = false; return true; } else return false; } void LedConsensus::ziCalc(float* zi) { for (byte i = 0; i < nNodes; i++) zi[i] = rho * dAvg[i] - c[i] - y[i]; } float LedConsensus::dotProd(float x[5], float y[5]) { // Calculates the dot product of two vectors float aux_sum = 0; for (byte i = 0; i < nNodes; i++) aux_sum = aux_sum + x[i] * y[i]; return aux_sum; } bool LedConsensus::f_iCalc(float* d) { return (d[nodeId - 1] <= 100 + tol && d[nodeId - 1] >= 0 - tol && dotProd(k, d) >= L_i - o_i - tol); } void LedConsensus::setLocalC(float _c_i) { c_i = _c_i; c[nodeId - 1] = c_i; changedCost = true; } void LedConsensus::setLocalO(float _o_i) { o_i = _o_i; } void LedConsensus::setLocalL(float _L_i) { L_i = _L_i; changedLuxRef = true; } float LedConsensus::calcExpectedLux() { return dotProd(k, dNodeOverall); } float LedConsensus::evaluateCost(float* local_d) { float local_cost = 0; for (byte i = 0; i < nNodes; i++) local_cost += (y[i] * (local_d[i] - dAvg[i]) + (rho / 2) * (local_d[i] - dAvg[i]) * (local_d[i] - dAvg[i])); local_cost += c_i * local_d[nodeId - 1]; return local_cost; } void LedConsensus::findMinima() { // OUTPUTS: // dNode: array with local optimal led duty cycles (note: only need the own node duty cycle) // bool: true if feasible, false if unfeasible float d_temp[maxNodes]; float d_best[maxNodes]; float cost_best = infinity; float cost_temp; float zi[maxNodes]; for (byte i = 0; i < nNodes; i++) zi[i] = rho * dAvg[i] - y[i]; zi[nodeId - 1] -= c_i; // First we will try to find the solution in the interior for (byte i = 0; i < nNodes; i++) d_temp[i] = zi[i] / rho; // Now we check if this first solution is feasible if (f_iCalc(d_temp)) { // Solution is feasible memcpy(d_best, d_temp, nNodes * sizeof(float)); cost_best = evaluateCost(d_temp); //Serial.println("Interior is feasible"); } else { // Else continue looking for solutions on the borders float aux; float aux2; // Solution 1 aux = (1 / dotProd(k, k)) * (o_i - L_i + (1 / rho) * dotProd(k, zi)); for (byte i = 0; i < nNodes; i++) d_temp[i] = (1 / rho) * zi[i] - k[i] * aux; if (f_iCalc(d_temp)) { // Solution is feasible cost_temp = evaluateCost(d_temp); //Serial.print("Solution 1 cost "); Serial.println(cost_temp); if (cost_temp < cost_best) { memcpy(d_best, d_temp, nNodes * sizeof(float)); cost_best = cost_temp; } } // Solution 2 for (byte i = 0; i < nNodes; i++) d_temp[i] = zi[i] / rho; d_temp[nodeId - 1] = 0; if (f_iCalc(d_temp)) { // Solution is feasible cost_temp = evaluateCost(d_temp); //Serial.print("Solution 2 cost "); Serial.println(cost_temp); if (cost_temp < cost_best) { memcpy(d_best, d_temp, nNodes * sizeof(float)); cost_best = cost_temp; } } // Solution 3 // Other terms are already calculated from solution2 loop d_temp[nodeId - 1] = 100; if (f_iCalc(d_temp)) { // Solution is feasible cost_temp = evaluateCost(d_temp); //Serial.print("Solution 3 cost "); Serial.println(cost_temp); if (cost_temp < cost_best) { memcpy(d_best, d_temp, nNodes * sizeof(float)); cost_best = cost_temp; } } //Solution 4 aux = dotProd(k, k) - k[nodeId - 1] * k[nodeId - 1]; aux2 = k[nodeId - 1] * zi[nodeId - 1] - dotProd(k, zi); for (byte i = 0; i < nNodes; i++) d_temp[i] = zi[i] / rho - (k[i] / aux) * (o_i - L_i) + (1 / rho / aux) * k[i] * aux2; d_temp[nodeId - 1] = 0; if (f_iCalc(d_temp)) { // Solution is feasible cost_temp = evaluateCost(d_temp); //Serial.print("Solution 4 cost "); Serial.println(cost_temp); if (cost_temp < cost_best) { memcpy(d_best, d_temp, nNodes * sizeof(float)); cost_best = cost_temp; } } //Solution 5 for (byte i = 0; i < nNodes; i++) d_temp[i] = d_temp[i] - (100 * k[i] * k[nodeId - 1]) / aux; d_temp[nodeId - 1] = 100; if (f_iCalc(d_temp)) { // Solution is feasible cost_temp = evaluateCost(d_temp); //Serial.print("Solution 5 cost "); Serial.println(cost_temp); if (cost_temp < cost_best) { memcpy(d_best, d_temp, nNodes * sizeof(float)); cost_best = cost_temp; } } } if (cost_best != infinity) { memcpy(dNode, d_best, nNodes * sizeof(float)); dColumn[nodeId - 1] = d_best[nodeId - 1]; } if (remainingIters == 1) { Serial.print("Cons sol:"); for (byte ii = 0; ii < nNodes; ii++) { Serial.print(" "); Serial.print(dNode[ii]); } Serial.println(" "); } } void LedConsensus::calcMeanVector() { dColumn[nodeId - 1] = dNode[nodeId - 1]; dAvg[nodeId - 1] = 0; for (byte i = 0; i < nNodes; i++) { dAvg[nodeId - 1] += dColumn[i]; } dAvg[nodeId - 1] /= nNodes; } void LedConsensus::calcLagrangeMult() { for (byte i = 0; i < nNodes; i++) { y[i] = y[i] + rho * (dNode[i] - dAvg[i]); //Serial.print("y"); Serial.print(i); Serial.print(" is "); Serial.println(y[i]); } } void LedConsensus::resetConsensus() { for (int i = 0; i < nNodes; i++) { y[i] = 0; dAvg[i] = 0; } remainingIters = maxIters; } void LedConsensus::run() { //Serial.println(state); switch (state) { // See if need to start new consensus case 0: if (detectChanges()) state++; break; // Tell others to start case 1: ask(); break; // Receive d real case 2: pid.on = false; ask(); break; // Measure lux case 3: Serial.println("Consensus started"); dNodeOverall[nodeId - 1] = u; measuredLux = getLux(analogRead(ldrPin)); Serial.print("Measured lux is "); Serial.println(measuredLux); setLocalO(measuredLux - calcExpectedLux()); Serial.print("New o is "); Serial.println(o_i); //o_i = 0; resetConsensus(); state++; break; // Find minima case 4: findMinima(); state++; break; // Receive duty cycles case 5: ask(); break; // Compute average case 6: calcMeanVector(); pid.on = true; state++; break; // Receive means case 7: ask(); break; // Calculate y case 8: calcLagrangeMult(); remainingIters--; //Serial.print("Remaining iterations: "); Serial.println(remainingIters); if (remainingIters > 0) state = 9; else { u_con = dAvg[nodeId - 1]; pid.ip = 0; state = 0; } break; case 9: ask(); break; } } void LedConsensus::ask() { unsigned long current_time = millis(); if (state == 5) { if (first || current_time - last_time >= timeout) { for (byte i = 1; i <= nNodes; i++) { if (i != nodeId && !boolArray[i - 1]) { write(i, duty_cycle_ask, dNode[i - 1]); } } last_time = current_time; first = false; } } else { char code; float value; switch (state) { case 1: code = start_ask; break; case 2: code = real_ask; value = u; break; case 7: code = mean_ask; value = dAvg[nodeId - 1]; break; case 9: code = wait_ask; value = remainingIters; break; } if (first) { write(0, code, value); last_time = current_time; first = false; } else if (current_time - last_time >= timeout) { for (byte i = 1; i <= nNodes; i++) { if (i != nodeId && !boolArray[i - 1]) { write(i, code, value); } } last_time = current_time; } } } void LedConsensus::ans(byte senderId, char code, float value) { bool valid = false; char ans_code; float ans_value; switch (code) { case start_ask: valid = (state <= 2); ans_code = start_ans; break; case real_ask: valid = (state >= 2 && state <= 5); ans_code = real_ans; ans_value = u; break; case duty_cycle_ask: valid = (state >= 5 && state <= 7); ans_code = duty_cycle_ans; ans_value = dNode[senderId - 1]; break; case mean_ask: valid = (state >= 7 && state <= 9 || state <= 2); ans_code = mean_ans; ans_value = dAvg[nodeId - 1]; break; case wait_ask: valid = (state == 9 || state == 4 || state == 5); ans_code = wait_ans; ans_value = remainingIters; break; } if (valid) { write(senderId, ans_code, ans_value); if (code == start_ask && state == 0) { state = 2; return; } rcv(senderId, ans_code, value); } } void LedConsensus::rcv(byte senderId, char code, float value) { if (!boolArray[senderId - 1]) { bool valid = false; float *variable; switch (code) { case start_ans: valid = (state == 1); break; case real_ans: valid = (state == 2); variable = &(dNodeOverall[senderId - 1]); break; case duty_cycle_ans: valid = (state == 5); variable = &(dColumn[senderId - 1]); break; case mean_ans: valid = (state == 7); variable = &(dAvg[senderId - 1]); break; case wait_ans: valid = (state == 9); break; } if (valid) { boolArray[senderId - 1] = true; nBool++; if (code != start_ans && code != wait_ans) *variable = value; if (nBool == nNodes - 1) { if (state == 9) { state = 4; } else { state++; } resetBool(); } } } } void LedConsensus::resetBool() { for (byte i = 0; i < nNodes; i++) { boolArray[i] = false; } nBool = 0; first = true; }
23.528571
112
0.555556
gonced8
fba8616942ba54639eaaaac9b1664c6e7d8dfc89
7,547
cxx
C++
Plugins/vnsInstallData.cxx
spacebel/MAJA
3e5d20bc9c744c610e608cfcf1f4c5c738d4de9e
[ "Apache-2.0" ]
57
2020-09-30T08:51:22.000Z
2021-12-19T20:28:30.000Z
Plugins/vnsInstallData.cxx
spacebel/MAJA
3e5d20bc9c744c610e608cfcf1f4c5c738d4de9e
[ "Apache-2.0" ]
34
2020-09-29T21:27:22.000Z
2022-02-03T09:56:45.000Z
Plugins/vnsInstallData.cxx
spacebel/MAJA
3e5d20bc9c744c610e608cfcf1f4c5c738d4de9e
[ "Apache-2.0" ]
14
2020-10-11T13:17:59.000Z
2022-03-09T15:58:19.000Z
/* * Copyright (C) 2020 Centre National d'Etudes Spatiales (CNES) * * 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. * */ /************************************************************************************************************ * * * ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo * * o * * o * * o * * o * * o ooooooo ooooooo o o oo * * o o o o o o o o o o * * o o o o o o o o o o * * o o o o o o o o o o * * o o o oooo o o o o o o * * o o o o o o o o o * * o o o o o o o o o o * * oo oooooooo o o o oooooo o oooo * * o * * o * * o o * * o o oooo o o oooo * * o o o o o o * * o o ooo o o ooo * * o o o o o * * ooooo oooo o ooooo oooo * * o * * * ************************************************************************************************************ * * * Author: CS Systemes d'Information (France) * * * ************************************************************************************************************ * HISTORIQUE * * * * VERSION : 2.0.0 : FA : LAIG-FA-MAJA-152790-CS : 23 fevrier 2017 : Correction qualite taux de commentaire * * VERSION : 1.0.0 : FA : LAIG-FA-MAC-1988-CNES : 14 octobre 2016 : Correction qualite (code mort) * * VERSION : 5-1-0 : FA : LAIG-FA-MAC-145739-CS : 5 aout 2016 : Audit code - variable const * * VERSION : 4-4-0 : FA : LAIG-FA-MAC-127944-CS : 3 juin 2015 : Correction code pour la qualite * * VERSION : 1-0-0 : <TypeFT> : <NumFT> : 1 janvier 2010 : Creation * * * FIN-HISTORIQUE * * * * $Id: vnsSystemRasterize.cxx 3746 2012-01-31 15:51:20Z tfeuvrie $ * * ************************************************************************************************************/ #include <string> #include <iostream> #include <cstdlib> #include <fstream> #include "vnsSystem.h" #include <itksys/SystemTools.hxx> int main(int argc, char * argv[]) { if (argc != 3) { std::cout << "Usage : " << argv[0] << std::endl; return -1; } const std::string inputFilename(argv[1]); const std::string outputFilename(argv[2]); // The first argv is the input filename (full path) : it could be a .EEF or .HDR files or a .DBL.DIR directory // The second is the output directory to install the output file // The output file et the .EEF or the .HDR file and for the DBL.DIR, its the DBL compress file or the directory DBL.DIR. int code_return(0); // if not a directory, then it is a file if (itksys::SystemTools::FileIsDirectory(inputFilename.c_str()) == false) { // Try to copy const bool bresult = itksys::SystemTools::CopyFileAlways(inputFilename.c_str(), outputFilename.c_str()); if (bresult == false) { // if failed trace it and update the return code std::cout << "Error while copy the inputfilename <" << inputFilename << "> to the destination filename <" << outputFilename << "> !!" << std::endl; code_return = 1; } } else { // it is a directory //Check if it's a DBL.DIR extention // Compress the directory in output directory const std::string basePath = itksys::SystemTools::GetFilenamePath(inputFilename); // base module is YYY.DBL.DIR const std::string baseModule = itksys::SystemTools::GetFilenameName(inputFilename); // add the outputdirectory + YYY.DBL const vns::System::ReturnStatus result = vns::System::CallCommandBasic( "tar -cjf " + outputFilename + " -C " + basePath + " " + baseModule + " --exclude '.svn'"); if (result.first != 0) { // if failed trace it and update the return code std::cout << "Error while compress the inputfilename <" << outputFilename << "> from the directory <" << inputFilename << "> !!, Log of execution :"<<result.second << std::endl; code_return = 2; } } return code_return; }
62.371901
175
0.327945
spacebel
fbaa7473bbad0cd599566900430a722f694c91f9
33,371
cpp
C++
nntrainer/layers/lstm.cpp
songgot/nntrainer
d977cbbd14eba9ee89b432be0ad6939056c3f256
[ "Apache-2.0" ]
null
null
null
nntrainer/layers/lstm.cpp
songgot/nntrainer
d977cbbd14eba9ee89b432be0ad6939056c3f256
[ "Apache-2.0" ]
null
null
null
nntrainer/layers/lstm.cpp
songgot/nntrainer
d977cbbd14eba9ee89b432be0ad6939056c3f256
[ "Apache-2.0" ]
null
null
null
// SPDX-License-Identifier: Apache-2.0 /** * Copyright (C) 2020 Jijoong Moon <jijoong.moon@samsung.com> * * @file lstm.cpp * @date 17 March 2021 * @brief This is Long Short-Term Memory Layer Class of Neural Network * @see https://github.com/nnstreamer/nntrainer * @author Jijoong Moon <jijoong.moon@samsung.com> * @bug No known bugs except for NYI items * */ #include <layer_context.h> #include <lstm.h> #include <lstmcell_core.h> #include <nntrainer_error.h> #include <nntrainer_log.h> #include <node_exporter.h> namespace nntrainer { static constexpr size_t SINGLE_INOUT_IDX = 0; enum LSTMParams { weight_ih, weight_hh, bias_h, bias_ih, bias_hh, hidden_state, cell_state, ifgo, reverse_weight_ih, reverse_weight_hh, reverse_bias_h, reverse_bias_ih, reverse_bias_hh, reverse_hidden_state, reverse_cell_state, reverse_ifgo, dropout_mask }; /** * @brief run lstm fowarding for batch_first input * * @param NUM_GATE Number of gate which is 4 for lstm * @param batch_size batch size * @param feature_size feature size * @param disable_bias whether to disable bias or not * @param unit number of output neurons * @param integrate_bias integrate bias_ih, bias_hh to bias_h * @param acti_func activation function for memory cell, cell state * @param recurrent_acti_func activation function for input/output/forget * gate * @param enable_dropout whether to apply dropout * @param dropout_rate dropout rate * @param max_timestep maximum timestep for lstm * @param reverse indicate forward/backward direction for input in bidirectional * lstm * @param input_ input * @param weight_ih weight for input to hidden * @param weight_hh weight for hidden to hidden * @param bias_h bias for input and hidden. * @param bias_ih bias for input * @param bias_hh bias for hidden * @param hidden_state_ hidden state * @param cell_state_ cell state * @param ifgo_ input gate, forget gate, memory cell, output gate * @param mask_ dropout mask */ static void batch_first_forwarding( unsigned int NUM_GATE, const unsigned int batch_size, const unsigned int feature_size, const bool disable_bias, const unsigned int unit, const bool integrate_bias, ActiFunc &acti_func, ActiFunc &recurrent_acti_func, const bool enable_dropout, const float dropout_rate, const unsigned int max_timestep, const bool reverse, const Tensor &input_, const Tensor &weight_ih, const Tensor &weight_hh, const Tensor &bias_h, const Tensor &bias_ih, const Tensor &bias_hh, Tensor &hidden_state_, Tensor &cell_state_, Tensor &ifgo_, const Tensor &mask_) { hidden_state_.setZero(); cell_state_.setZero(); for (unsigned int batch = 0; batch < batch_size; ++batch) { const Tensor input_sample = input_.getBatchSlice(batch, 1); Tensor hidden_state_sample = hidden_state_.getBatchSlice(batch, 1); Tensor cell_state_sample = cell_state_.getBatchSlice(batch, 1); Tensor ifgo_sample = ifgo_.getBatchSlice(batch, 1); for (unsigned int t = 0; t < max_timestep; ++t) { Tensor input = input_sample.getSharedDataTensor( {feature_size}, (reverse ? max_timestep - 1 - t : t) * feature_size); Tensor prev_hidden_state; if (!t) { prev_hidden_state = Tensor(unit); prev_hidden_state.setZero(); } else { prev_hidden_state = hidden_state_sample.getSharedDataTensor( {unit}, (reverse ? (max_timestep - t) : (t - 1)) * unit); } Tensor hidden_state = hidden_state_sample.getSharedDataTensor( {unit}, (reverse ? max_timestep - 1 - t : t) * unit); Tensor prev_cell_state; if (!t) { prev_cell_state = Tensor(unit); prev_cell_state.setZero(); } else { prev_cell_state = cell_state_sample.getSharedDataTensor( {unit}, (reverse ? (max_timestep - t) : (t - 1)) * unit); } Tensor cell_state = cell_state_sample.getSharedDataTensor( {unit}, (reverse ? max_timestep - 1 - t : t) * unit); Tensor ifgo = ifgo_sample.getSharedDataTensor( {NUM_GATE * unit}, (reverse ? max_timestep - 1 - t : t) * NUM_GATE * unit); lstmcell_forwarding(1, unit, disable_bias, integrate_bias, acti_func, recurrent_acti_func, input, prev_hidden_state, prev_cell_state, hidden_state, cell_state, weight_ih, weight_hh, bias_h, bias_ih, bias_hh, ifgo); if (enable_dropout) { Tensor mask_sample = mask_.getBatchSlice(batch, 1); Tensor mask = mask_sample.getSharedDataTensor({unit}, t * unit); mask.dropout_mask(dropout_rate); hidden_state.multiply_i(mask); } } } } /** * @brief calculate lstm gradient for batch_first input * * @param NUM_GATE Number of gate which is 4 for lstm * @param batch_size batch size * @param feature_size feature size * @param disable_bias whether to disable bias or not * @param unit number of output neurons * @param integrate_bias integrate bias_ih, bias_hh to bias_h * @param acti_func activation function for memory cell, cell state * @param recurrent_acti_func activation function for input/output/forget * gate * @param return_sequences return sequeces * @param bidirectional bidirectional lstm * @param enable_dropout whether to apply dropout * @param dropout_rate dropout rate * @param max_timestep maximum timestep for lstm * @param reverse indicate forward/backward direction for input in bidirectional * lstm * @param input_ input * @param incoming_derivative derivative for output which is incoming derivative * @param d_weight_ih weight_ih(weight for input to hidden) gradient * @param weight_hh weight for hidden to hidden * @param d_weight_hh weight_hh(weight for hidden to hidden) gradient * @param d_bias_h bias_h(bias for input and hidden) gradient * @param d_bias_ih bias_ih(bias for input) gradient * @param d_bias_hh bias_hh(bias for hidden) gradient * @param hidden_state_ hidden state * @param d_hidden_state_ hidden state gradient * @param cell_state_ cell state * @param d_cell_state_ cell state gradient * @param ifgo_ input gate, forget gate, memory cell, output gate * @param d_ifgo_ gradient for input gate, forget gate, memory cell, output gate * @param mask_ dropout mask */ void batch_first_calcGradient( unsigned int NUM_GATE, const unsigned int batch_size, const unsigned int feature_size, const bool disable_bias, const unsigned int unit, const bool integrate_bias, ActiFunc &acti_func, ActiFunc &recurrent_acti_func, const bool return_sequences, const bool bidirectional, const bool enable_dropout, const float dropout_rate, const unsigned int max_timestep, const bool reverse, const Tensor &input_, const Tensor &incoming_derivative, Tensor &d_weight_ih, const Tensor &weight_hh, Tensor &d_weight_hh, Tensor &d_bias_h, Tensor &d_bias_ih, Tensor &d_bias_hh, const Tensor &hidden_state_, Tensor &d_hidden_state_, const Tensor &cell_state_, Tensor &d_cell_state_, const Tensor &ifgo_, Tensor &d_ifgo_, const Tensor &mask_) { const unsigned int bidirectional_constant = bidirectional ? 2 : 1; d_weight_ih.setZero(); d_weight_hh.setZero(); if (!disable_bias) { if (integrate_bias) { d_bias_h.setZero(); } else { d_bias_ih.setZero(); d_bias_hh.setZero(); } } d_cell_state_.setZero(); d_hidden_state_.setZero(); if (return_sequences && !bidirectional && !reverse) { std::copy(incoming_derivative.getData(), incoming_derivative.getData() + incoming_derivative.size(), d_hidden_state_.getData()); } else { unsigned int end_timestep = return_sequences ? max_timestep : 1; for (unsigned int batch = 0; batch < batch_size; ++batch) { for (unsigned int timestep = 0; timestep < end_timestep; ++timestep) { Tensor d_hidden_state_sample = d_hidden_state_.getSharedDataTensor( {unit}, batch * max_timestep * unit + (return_sequences ? 0 : max_timestep - 1) * unit + timestep * unit); Tensor incoming_derivative_sample = incoming_derivative.getSharedDataTensor( {unit}, batch * (return_sequences ? max_timestep : 1) * bidirectional_constant * unit + timestep * bidirectional_constant * unit + (reverse ? unit : 0)); d_hidden_state_sample.add_i(incoming_derivative_sample); } } } if (enable_dropout) { d_hidden_state_.multiply_i(mask_); } for (unsigned int batch = 0; batch < batch_size; ++batch) { const Tensor input_sample = input_.getBatchSlice(batch, 1); const Tensor hidden_state_sample = hidden_state_.getBatchSlice(batch, 1); Tensor d_hidden_state_sample = d_hidden_state_.getBatchSlice(batch, 1); const Tensor cell_state_sample = cell_state_.getBatchSlice(batch, 1); Tensor d_cell_state_sample = d_cell_state_.getBatchSlice(batch, 1); const Tensor ifgo_sample = ifgo_.getBatchSlice(batch, 1); Tensor d_ifgo_sample = d_ifgo_.getBatchSlice(batch, 1); Tensor input; Tensor prev_hidden_state; Tensor d_prev_hidden_state; Tensor prev_cell_state; Tensor d_prev_cell_state; Tensor d_hidden_state; Tensor cell_state; Tensor d_cell_state; for (int t = max_timestep - 1; t > -1; t--) { input = input_sample.getSharedDataTensor( {feature_size}, (reverse ? max_timestep - 1 - t : t) * feature_size); if (!t) { prev_hidden_state = Tensor(unit); prev_hidden_state.setZero(); d_prev_hidden_state = Tensor(unit); d_prev_hidden_state.setZero(); } else { prev_hidden_state = hidden_state_sample.getSharedDataTensor( {unit}, (reverse ? (max_timestep - t) : (t - 1)) * unit); d_prev_hidden_state = d_hidden_state_sample.getSharedDataTensor( {unit}, (reverse ? (max_timestep - t) : (t - 1)) * unit); } d_hidden_state = d_hidden_state_sample.getSharedDataTensor( {unit}, (reverse ? max_timestep - 1 - t : t) * unit); if (!t) { prev_cell_state = Tensor(unit); prev_cell_state.setZero(); d_prev_cell_state = Tensor(unit); d_prev_cell_state.setZero(); } else { prev_cell_state = cell_state_sample.getSharedDataTensor( {unit}, (reverse ? (max_timestep - t) : (t - 1)) * unit); d_prev_cell_state = d_cell_state_sample.getSharedDataTensor( {unit}, (reverse ? (max_timestep - t) : (t - 1)) * unit); } cell_state = cell_state_sample.getSharedDataTensor( {unit}, (reverse ? max_timestep - 1 - t : t) * unit); d_cell_state = d_cell_state_sample.getSharedDataTensor( {unit}, (reverse ? max_timestep - 1 - t : t) * unit); Tensor ifgo = ifgo_sample.getSharedDataTensor( {NUM_GATE * unit}, (reverse ? max_timestep - 1 - t : t) * NUM_GATE * unit); Tensor d_ifgo = d_ifgo_sample.getSharedDataTensor( {NUM_GATE * unit}, (reverse ? max_timestep - 1 - t : t) * NUM_GATE * unit); // Temporary variable for d_prev_hidden_state. d_prev_hidden_state already // have precalculated values from incomming derivatives Tensor d_prev_hidden_state_temp; lstmcell_calcGradient(1, unit, disable_bias, integrate_bias, acti_func, recurrent_acti_func, input, prev_hidden_state, d_prev_hidden_state_temp, prev_cell_state, d_prev_cell_state, d_hidden_state, cell_state, d_cell_state, d_weight_ih, weight_hh, d_weight_hh, d_bias_h, d_bias_ih, d_bias_hh, ifgo, d_ifgo); d_prev_hidden_state.add_i(d_prev_hidden_state_temp); } } } LSTMLayer::LSTMLayer() : LayerImpl(), lstm_props(props::Unit(), props::IntegrateBias(), props::HiddenStateActivation() = ActivationType::ACT_TANH, props::RecurrentActivation() = ActivationType::ACT_SIGMOID, props::ReturnSequences(), props::Bidirectional(), props::DropOutRate(), props::MaxTimestep()), acti_func(ActivationType::ACT_NONE, true), recurrent_acti_func(ActivationType::ACT_NONE, true), epsilon(1e-3) { wt_idx.fill(std::numeric_limits<unsigned>::max()); } void LSTMLayer::finalize(InitLayerContext &context) { const Tensor::Initializer weight_initializer = std::get<props::WeightInitializer>(*layer_impl_props).get(); const Tensor::Initializer bias_initializer = std::get<props::BiasInitializer>(*layer_impl_props).get(); const nntrainer::WeightRegularizer weight_regularizer = std::get<props::WeightRegularizer>(*layer_impl_props).get(); const float weight_regularizer_constant = std::get<props::WeightRegularizerConstant>(*layer_impl_props).get(); auto &weight_decay = std::get<props::WeightDecay>(*layer_impl_props); auto &bias_decay = std::get<props::BiasDecay>(*layer_impl_props); const bool disable_bias = std::get<props::DisableBias>(*layer_impl_props).get(); NNTR_THROW_IF(std::get<props::Unit>(lstm_props).empty(), std::invalid_argument) << "unit property missing for lstm layer"; const unsigned int unit = std::get<props::Unit>(lstm_props).get(); const bool integrate_bias = std::get<props::IntegrateBias>(lstm_props).get(); const ActivationType hidden_state_activation_type = std::get<props::HiddenStateActivation>(lstm_props).get(); const ActivationType recurrent_activation_type = std::get<props::RecurrentActivation>(lstm_props).get(); const bool return_sequences = std::get<props::ReturnSequences>(lstm_props).get(); const bool bidirectional = std::get<props::Bidirectional>(lstm_props).get(); const float dropout_rate = std::get<props::DropOutRate>(lstm_props).get(); if (context.getNumInputs() != 1) { throw std::invalid_argument("LSTM layer takes only one input"); } // input_dim = [ batch_size, 1, time_iteration, feature_size ] const TensorDim &input_dim = context.getInputDimensions()[SINGLE_INOUT_IDX]; if (input_dim.channel() != 1) { throw std::invalid_argument( "Input must be single channel dimension for LSTM (shape should be " "[batch_size, 1, time_iteration, feature_size])"); } const unsigned int batch_size = input_dim.batch(); unsigned int max_timestep = input_dim.height(); if (!std::get<props::MaxTimestep>(lstm_props).empty()) max_timestep = std::max(max_timestep, std::get<props::MaxTimestep>(lstm_props).get()); std::get<props::MaxTimestep>(lstm_props).set(max_timestep); const unsigned int feature_size = input_dim.width(); // output_dim = [ batch_size, 1, return_sequences ? time_iteration : 1, // bidirectional ? 2 * unit : unit ] const TensorDim output_dim(batch_size, 1, return_sequences ? max_timestep : 1, bidirectional ? 2 * unit : unit); context.setOutputDimensions({output_dim}); // weight_initializer can be set seperately. weight_ih initializer, // weight_hh initializer kernel initializer & recurrent_initializer in // keras for now, it is set same way. // weight_ih ( input to hidden ) : [ 1, 1, feature_size, NUM_GATE * unit ] // -> i, f, g, o const TensorDim weight_ih_dim({feature_size, NUM_GATE * unit}); wt_idx[LSTMParams::weight_ih] = context.requestWeight( weight_ih_dim, weight_initializer, weight_regularizer, weight_regularizer_constant, weight_decay, "weight_ih", true); // weight_hh ( hidden to hidden ) : [ 1, 1, unit, NUM_GATE * unit ] -> i, // f, g, o const TensorDim weight_hh_dim({unit, NUM_GATE * unit}); wt_idx[LSTMParams::weight_hh] = context.requestWeight( weight_hh_dim, weight_initializer, weight_regularizer, weight_regularizer_constant, weight_decay, "weight_hh", true); if (!disable_bias) { if (integrate_bias) { // bias_h ( input bias, hidden bias are integrate to 1 bias ) : [ 1, // 1, 1, NUM_GATE * unit ] -> i, f, g, o const TensorDim bias_h_dim({NUM_GATE * unit}); wt_idx[LSTMParams::bias_h] = context.requestWeight( bias_h_dim, bias_initializer, WeightRegularizer::NONE, 1.0f, bias_decay, "bias_h", true); } else { // bias_ih ( input bias ) : [ 1, 1, 1, NUM_GATE * unit ] -> i, f, g, o const TensorDim bias_ih_dim({NUM_GATE * unit}); wt_idx[LSTMParams::bias_ih] = context.requestWeight( bias_ih_dim, bias_initializer, WeightRegularizer::NONE, 1.0f, bias_decay, "bias_ih", true); // bias_hh ( hidden bias ) : [ 1, 1, 1, NUM_GATE * unit ] -> i, f, g, o wt_idx[LSTMParams::bias_hh] = context.requestWeight( bias_ih_dim, bias_initializer, WeightRegularizer::NONE, 1.0f, bias_decay, "bias_hh", true); } } // hidden_state_dim : [ batch_size, 1, max_timestep, unit ] const TensorDim hidden_state_dim(batch_size, 1, max_timestep, unit); wt_idx[LSTMParams::hidden_state] = context.requestTensor( hidden_state_dim, "hidden_state", Tensor::Initializer::NONE, true, TensorLifespan::ITERATION_LIFESPAN); // cell_state_dim : [ batch_size, 1, max_timestep, unit ] const TensorDim cell_state_dim(batch_size, 1, max_timestep, unit); wt_idx[LSTMParams::cell_state] = context.requestTensor( cell_state_dim, "cell_state", Tensor::Initializer::NONE, true, TensorLifespan::ITERATION_LIFESPAN); // ifgo_dim : [ batch_size, 1, max_timestep, NUM_GATE * unit ] const TensorDim ifgo_dim(batch_size, 1, max_timestep, NUM_GATE * unit); wt_idx[LSTMParams::ifgo] = context.requestTensor(ifgo_dim, "ifgo", Tensor::Initializer::NONE, true, TensorLifespan::ITERATION_LIFESPAN); if (bidirectional) { // weight_initializer can be set seperately. weight_ih initializer, // weight_hh initializer kernel initializer & recurrent_initializer in // keras for now, it is set same way. // reverse_weight_ih ( input to hidden ) : [ 1, 1, feature_size, // NUM_GATE * unit ] -> i, f, g, o const TensorDim reverse_weight_ih_dim({feature_size, NUM_GATE * unit}); wt_idx[LSTMParams::reverse_weight_ih] = context.requestWeight( reverse_weight_ih_dim, weight_initializer, weight_regularizer, weight_regularizer_constant, weight_decay, "reverse_weight_ih", true); // reverse_weight_hh ( hidden to hidden ) : [ 1, 1, unit, NUM_GATE * // unit ] // -> i, f, g, o const TensorDim reverse_weight_hh_dim({unit, NUM_GATE * unit}); wt_idx[LSTMParams::reverse_weight_hh] = context.requestWeight( reverse_weight_hh_dim, weight_initializer, weight_regularizer, weight_regularizer_constant, weight_decay, "reverse_weight_hh", true); if (!disable_bias) { if (integrate_bias) { // reverse_bias_h ( input bias, hidden bias are integrate to 1 bias // ) : [ 1, 1, 1, NUM_GATE * unit ] -> i, f, g, o const TensorDim reverse_bias_h_dim({NUM_GATE * unit}); wt_idx[LSTMParams::reverse_bias_h] = context.requestWeight( reverse_bias_h_dim, bias_initializer, WeightRegularizer::NONE, 1.0f, bias_decay, "reverse_bias_h", true); } else { // reverse_bias_ih ( input bias ) : [ 1, 1, 1, NUM_GATE * unit ] -> // i, f, g, o const TensorDim reverse_bias_ih_dim({NUM_GATE * unit}); wt_idx[LSTMParams::reverse_bias_ih] = context.requestWeight( reverse_bias_ih_dim, bias_initializer, WeightRegularizer::NONE, 1.0f, bias_decay, "reverse_bias_ih", true); // reverse_bias_hh ( hidden bias ) : [ 1, 1, 1, NUM_GATE * unit ] -> // i, f, g, o const TensorDim reverse_bias_hh_dim({NUM_GATE * unit}); wt_idx[LSTMParams::reverse_bias_hh] = context.requestWeight( reverse_bias_hh_dim, bias_initializer, WeightRegularizer::NONE, 1.0f, bias_decay, "reverse_bias_hh", true); } } // reverse_hidden_state_dim : [ batch_size, 1, max_timestep, unit ] const TensorDim reverse_hidden_state_dim(batch_size, 1, max_timestep, unit); wt_idx[LSTMParams::reverse_hidden_state] = context.requestTensor( reverse_hidden_state_dim, "reverse_hidden_state", Tensor::Initializer::NONE, true, TensorLifespan::ITERATION_LIFESPAN); // reverse_cell_state_dim : [ batch_size, 1, max_timestep, unit ] const TensorDim reverse_cell_state_dim(batch_size, 1, max_timestep, unit); wt_idx[LSTMParams::reverse_cell_state] = context.requestTensor( reverse_cell_state_dim, "reverse_cell_state", Tensor::Initializer::NONE, true, TensorLifespan::ITERATION_LIFESPAN); // reverse_ifgo_dim : [ batch_size, 1, max_timestep, NUM_GATE * unit ] const TensorDim reverse_ifgo_dim(batch_size, 1, max_timestep, NUM_GATE * unit); wt_idx[LSTMParams::reverse_ifgo] = context.requestTensor( reverse_ifgo_dim, "reverse_ifgo", Tensor::Initializer::NONE, true, TensorLifespan::ITERATION_LIFESPAN); } if (dropout_rate > epsilon) { // dropout_mask_dim = [ batch, 1, time_iteration, unit ] const TensorDim dropout_mask_dim(batch_size, 1, max_timestep, unit); wt_idx[LSTMParams::dropout_mask] = context.requestTensor( dropout_mask_dim, "dropout_mask", Tensor::Initializer::NONE, false, TensorLifespan::ITERATION_LIFESPAN); } acti_func.setActiFunc(hidden_state_activation_type); recurrent_acti_func.setActiFunc(recurrent_activation_type); } void LSTMLayer::setProperty(const std::vector<std::string> &values) { const std::vector<std::string> &remain_props = loadProperties(values, lstm_props); LayerImpl::setProperty(remain_props); } void LSTMLayer::exportTo(Exporter &exporter, const ml::train::ExportMethods &method) const { LayerImpl::exportTo(exporter, method); exporter.saveResult(lstm_props, method, this); } void LSTMLayer::forwarding(RunLayerContext &context, bool training) { const bool disable_bias = std::get<props::DisableBias>(*layer_impl_props).get(); const unsigned int unit = std::get<props::Unit>(lstm_props).get(); const bool integrate_bias = std::get<props::IntegrateBias>(lstm_props).get(); const bool return_sequences = std::get<props::ReturnSequences>(lstm_props).get(); const bool bidirectional = std::get<props::Bidirectional>(lstm_props).get(); const float dropout_rate = std::get<props::DropOutRate>(lstm_props).get(); const unsigned int max_timestep = std::get<props::MaxTimestep>(lstm_props).get(); const unsigned int bidirectional_constant = bidirectional ? 2 : 1; bool enable_dropout = dropout_rate > epsilon && training; const Tensor &input = context.getInput(SINGLE_INOUT_IDX); const TensorDim input_dim = input.getDim(); const unsigned int batch_size = input_dim.batch(); const unsigned int feature_size = input_dim.width(); Tensor &output = context.getOutput(SINGLE_INOUT_IDX); const Tensor &weight_ih = context.getWeight(wt_idx[LSTMParams::weight_ih]); const Tensor &weight_hh = context.getWeight(wt_idx[LSTMParams::weight_hh]); Tensor empty; const Tensor &bias_h = !disable_bias && integrate_bias ? context.getWeight(wt_idx[LSTMParams::bias_h]) : empty; const Tensor &bias_ih = !disable_bias && !integrate_bias ? context.getWeight(wt_idx[LSTMParams::bias_ih]) : empty; const Tensor &bias_hh = !disable_bias && !integrate_bias ? context.getWeight(wt_idx[LSTMParams::bias_hh]) : empty; Tensor &hidden_state = context.getTensor(wt_idx[LSTMParams::hidden_state]); Tensor &cell_state = context.getTensor(wt_idx[LSTMParams::cell_state]); Tensor &ifgo = context.getTensor(wt_idx[LSTMParams::ifgo]); Tensor &mask = enable_dropout ? context.getTensor(wt_idx[LSTMParams::dropout_mask]) : empty; batch_first_forwarding(NUM_GATE, batch_size, feature_size, disable_bias, unit, integrate_bias, acti_func, recurrent_acti_func, enable_dropout, dropout_rate, max_timestep, false, input, weight_ih, weight_hh, bias_h, bias_ih, bias_hh, hidden_state, cell_state, ifgo, mask); if (bidirectional) { const Tensor &reverse_weight_ih = context.getWeight(wt_idx[LSTMParams::reverse_weight_ih]); const Tensor &reverse_weight_hh = context.getWeight(wt_idx[LSTMParams::reverse_weight_hh]); const Tensor &reverse_bias_h = !disable_bias && integrate_bias ? context.getWeight(wt_idx[LSTMParams::reverse_bias_h]) : empty; const Tensor &reverse_bias_ih = !disable_bias && !integrate_bias ? context.getWeight(wt_idx[LSTMParams::reverse_bias_ih]) : empty; const Tensor &reverse_bias_hh = !disable_bias && !integrate_bias ? context.getWeight(wt_idx[LSTMParams::reverse_bias_hh]) : empty; Tensor &reverse_hidden_state = context.getTensor(wt_idx[LSTMParams::reverse_hidden_state]); Tensor &reverse_cell_state = context.getTensor(wt_idx[LSTMParams::reverse_cell_state]); Tensor &reverse_ifgo = context.getTensor(wt_idx[LSTMParams::reverse_ifgo]); batch_first_forwarding( NUM_GATE, batch_size, feature_size, disable_bias, unit, integrate_bias, acti_func, recurrent_acti_func, enable_dropout, dropout_rate, max_timestep, true, input, reverse_weight_ih, reverse_weight_hh, reverse_bias_h, reverse_bias_ih, reverse_bias_hh, reverse_hidden_state, reverse_cell_state, reverse_ifgo, mask); } if (return_sequences && !bidirectional) { std::copy(hidden_state.getData(), hidden_state.getData() + hidden_state.size(), output.getData()); } else { unsigned int end_timestep = return_sequences ? max_timestep : 1; for (unsigned int batch = 0; batch < batch_size; ++batch) { for (unsigned int timestep = 0; timestep < end_timestep; ++timestep) { float *hidden_state_data = hidden_state.getAddress( batch * max_timestep * unit + (return_sequences ? 0 : (max_timestep - 1) * unit) + timestep * unit); float *output_data = output.getAddress(batch * (return_sequences ? max_timestep : 1) * bidirectional_constant * unit + timestep * bidirectional_constant * unit); std::copy(hidden_state_data, hidden_state_data + unit, output_data); if (bidirectional) { Tensor &reverse_hidden_state = context.getTensor(wt_idx[LSTMParams::reverse_hidden_state]); float *reverse_hidden_state_data = reverse_hidden_state.getAddress( batch * max_timestep * unit + (return_sequences ? 0 : (max_timestep - 1) * unit) + timestep * unit); std::copy(reverse_hidden_state_data, reverse_hidden_state_data + unit, output_data + unit); } } } } } void LSTMLayer::calcDerivative(RunLayerContext &context) { const bool bidirectional = std::get<props::Bidirectional>(lstm_props).get(); Tensor &outgoing_derivative = context.getOutgoingDerivative(SINGLE_INOUT_IDX); const Tensor &weight_ih = context.getWeight(wt_idx[LSTMParams::weight_ih]); const Tensor &d_ifgos = context.getTensorGrad(wt_idx[LSTMParams::ifgo]); lstmcell_calcDerivative(outgoing_derivative, weight_ih, d_ifgos); if (bidirectional) { const Tensor &reverse_weight_ih = context.getWeight(wt_idx[LSTMParams::reverse_weight_ih]); const Tensor &reverse_d_ifgos = context.getTensorGrad(wt_idx[LSTMParams::reverse_ifgo]); lstmcell_calcDerivative(outgoing_derivative, reverse_weight_ih, reverse_d_ifgos, 1.0f); } } void LSTMLayer::calcGradient(RunLayerContext &context) { const bool disable_bias = std::get<props::DisableBias>(*layer_impl_props).get(); const unsigned int unit = std::get<props::Unit>(lstm_props).get(); const bool integrate_bias = std::get<props::IntegrateBias>(lstm_props).get(); const bool return_sequences = std::get<props::ReturnSequences>(lstm_props).get(); const bool bidirectional = std::get<props::Bidirectional>(lstm_props).get(); const float dropout_rate = std::get<props::DropOutRate>(lstm_props).get(); const unsigned int max_timestep = std::get<props::MaxTimestep>(lstm_props).get(); bool enable_dropout = dropout_rate > epsilon; const Tensor &input = context.getInput(SINGLE_INOUT_IDX); const Tensor &incoming_derivative = context.getIncomingDerivative(SINGLE_INOUT_IDX); const TensorDim input_dim = input.getDim(); const unsigned int batch_size = input_dim.batch(); const unsigned int feature_size = input_dim.width(); Tensor &d_weight_ih = context.getWeightGrad(wt_idx[LSTMParams::weight_ih]); const Tensor &weight_hh = context.getWeight(wt_idx[LSTMParams::weight_hh]); Tensor &d_weight_hh = context.getWeightGrad(wt_idx[LSTMParams::weight_hh]); Tensor empty; Tensor &d_bias_h = !disable_bias && integrate_bias ? context.getWeightGrad(wt_idx[LSTMParams::bias_h]) : empty; Tensor &d_bias_ih = !disable_bias && !integrate_bias ? context.getWeightGrad(wt_idx[LSTMParams::bias_ih]) : empty; Tensor &d_bias_hh = !disable_bias && !integrate_bias ? context.getWeightGrad(wt_idx[LSTMParams::bias_hh]) : empty; const Tensor &hidden_state = context.getTensor(wt_idx[LSTMParams::hidden_state]); Tensor &d_hidden_state = context.getTensorGrad(wt_idx[LSTMParams::hidden_state]); const Tensor &cell_state = context.getTensor(wt_idx[LSTMParams::cell_state]); Tensor &d_cell_state = context.getTensorGrad(wt_idx[LSTMParams::cell_state]); const Tensor &ifgo = context.getTensor(wt_idx[LSTMParams::ifgo]); Tensor &d_ifgo = context.getTensorGrad(wt_idx[LSTMParams::ifgo]); const Tensor &mask = enable_dropout ? context.getTensor(wt_idx[LSTMParams::dropout_mask]) : empty; batch_first_calcGradient( NUM_GATE, batch_size, feature_size, disable_bias, unit, integrate_bias, acti_func, recurrent_acti_func, return_sequences, bidirectional, enable_dropout, dropout_rate, max_timestep, false, input, incoming_derivative, d_weight_ih, weight_hh, d_weight_hh, d_bias_h, d_bias_ih, d_bias_hh, hidden_state, d_hidden_state, cell_state, d_cell_state, ifgo, d_ifgo, mask); if (bidirectional) { Tensor &reverse_d_weight_ih = context.getWeightGrad(wt_idx[LSTMParams::reverse_weight_ih]); const Tensor &reverse_weight_hh = context.getWeight(wt_idx[LSTMParams::reverse_weight_hh]); Tensor &reverse_d_weight_hh = context.getWeightGrad(wt_idx[LSTMParams::reverse_weight_hh]); Tensor &reverse_d_bias_h = !disable_bias && integrate_bias ? context.getWeightGrad(wt_idx[LSTMParams::reverse_bias_h]) : empty; Tensor &reverse_d_bias_ih = !disable_bias && !integrate_bias ? context.getWeightGrad(wt_idx[LSTMParams::reverse_bias_ih]) : empty; Tensor &reverse_d_bias_hh = !disable_bias && !integrate_bias ? context.getWeightGrad(wt_idx[LSTMParams::reverse_bias_hh]) : empty; const Tensor &reverse_hidden_state = context.getTensor(wt_idx[LSTMParams::reverse_hidden_state]); Tensor &reverse_d_hidden_state = context.getTensorGrad(wt_idx[LSTMParams::reverse_hidden_state]); const Tensor &reverse_cell_state = context.getTensor(wt_idx[LSTMParams::reverse_cell_state]); Tensor &reverse_d_cell_state = context.getTensorGrad(wt_idx[LSTMParams::reverse_cell_state]); const Tensor &reverse_ifgo = context.getTensor(wt_idx[LSTMParams::reverse_ifgo]); Tensor &reverse_d_ifgo = context.getTensorGrad(wt_idx[LSTMParams::reverse_ifgo]); batch_first_calcGradient( NUM_GATE, batch_size, feature_size, disable_bias, unit, integrate_bias, acti_func, recurrent_acti_func, return_sequences, bidirectional, enable_dropout, dropout_rate, max_timestep, true, input, incoming_derivative, reverse_d_weight_ih, reverse_weight_hh, reverse_d_weight_hh, reverse_d_bias_h, reverse_d_bias_ih, reverse_d_bias_hh, reverse_hidden_state, reverse_d_hidden_state, reverse_cell_state, reverse_d_cell_state, reverse_ifgo, reverse_d_ifgo, mask); } } void LSTMLayer::setBatch(RunLayerContext &context, unsigned int batch) { const bool bidirectional = std::get<props::Bidirectional>(lstm_props).get(); const float dropout_rate = std::get<props::DropOutRate>(lstm_props).get(); context.updateTensor(wt_idx[LSTMParams::hidden_state], batch); context.updateTensor(wt_idx[LSTMParams::cell_state], batch); context.updateTensor(wt_idx[LSTMParams::ifgo], batch); if (bidirectional) { context.updateTensor(wt_idx[LSTMParams::reverse_hidden_state], batch); context.updateTensor(wt_idx[LSTMParams::reverse_cell_state], batch); context.updateTensor(wt_idx[LSTMParams::reverse_ifgo], batch); } if (dropout_rate > epsilon) { context.updateTensor(wt_idx[LSTMParams::dropout_mask], batch); } } } // namespace nntrainer
43.793963
80
0.697132
songgot
fbac3d7849c61be68e581c48d97056d275d0df6b
217
cpp
C++
tests/operations/actions/TerminateIf.cpp
amlalejini/signalgp-lite
f4ebe7580dc3610fca0a51d1ad743b0dbc21b6e9
[ "MIT" ]
null
null
null
tests/operations/actions/TerminateIf.cpp
amlalejini/signalgp-lite
f4ebe7580dc3610fca0a51d1ad743b0dbc21b6e9
[ "MIT" ]
null
null
null
tests/operations/actions/TerminateIf.cpp
amlalejini/signalgp-lite
f4ebe7580dc3610fca0a51d1ad743b0dbc21b6e9
[ "MIT" ]
null
null
null
#define CATCH_CONFIG_MAIN #include "Catch/single_include/catch2/catch.hpp" #include "sgpl/operations/actions/TerminateIf.hpp" TEST_CASE("Test TerminateIf") { // TODO flesh out stub test sgpl::TerminateIf{}; }
18.083333
50
0.75576
amlalejini
fbadcddc50103e860edee4715de41e04b20e00f5
1,781
cpp
C++
uppdev/NewXmlRpc/main.cpp
dreamsxin/ultimatepp
41d295d999f9ff1339b34b43c99ce279b9b3991c
[ "BSD-2-Clause" ]
2
2016-04-07T07:54:26.000Z
2020-04-14T12:37:34.000Z
uppdev/NewXmlRpc/main.cpp
dreamsxin/ultimatepp
41d295d999f9ff1339b34b43c99ce279b9b3991c
[ "BSD-2-Clause" ]
null
null
null
uppdev/NewXmlRpc/main.cpp
dreamsxin/ultimatepp
41d295d999f9ff1339b34b43c99ce279b9b3991c
[ "BSD-2-Clause" ]
null
null
null
#include "XmlRpc.h" using namespace Upp; void Compute(XmlRpcData& rpc) { int n1, n2; String op; rpc >> n1 >> op >> n2; DUMP(n1); DUMP(op); DUMP(n2); switch(*op) { case '+': rpc << n1 + n2; break; case '-': rpc << n1 - n2; break; } } struct TestMap { String a; int b; String ToString() const { return a + AsString(b); } void Map(ValueMapper& m) { m("first", a)("second", b); } }; CONSOLE_APP_MAIN { Register("compute", callback(Compute)); String r = LoadFile(GetDataFile("request.txt")); DDUMP(XmlRpcExecute(r)); XmlRpcData d; d << "12" << "-" << 22; DDUMP(XmlRpcCall("compute", d)); int res; d >> res; DDUMP(res); DDUMP(FormatXmlRpcError(101, "error")); ValueArray va; va.Add("Hello"); va.Add("world"); Array<String> a; ValueGet(a, va); DUMPC(a); Vector<String> b; ValueGet(b, va); DUMPC(b); ValueMap m; m.Add("first", "Number is "); m.Add("second", 123); TestMap tm; ValueGet(tm, m); DUMP(tm.a); DUMP(tm.b); va.Clear(); for(int i = 0; i < 10; i++) { ValueMap m; m.Add("first", "Number is "); m.Add("second", i); va.Add(m); } Array<TestMap> tmm; ValueGet(tmm, va); DUMPC(tmm); /* XmlRpcRequest qq; qq.va.Add(123); qq.va.Add(va); int x; qq >> x >> tmm; DUMP(x); DUMPC(tmm); */ ValueArray param; String result; DUMP(param); XmlRpcData rpc; rpc.in = param; if(0) { int n1, n2; String text; Time d; Vector<int> vi; TestMap tm; rpc >> n1 >> text >> n2; DUMP(n1); DUMP(text); DUMP(n2); rpc >> d >> vi >> tm; DUMP(d); DUMPC(vi); DUMP(tm); } DDUMP(FormatXmlRpcParams(param)); LOG("Result: " << result); }
14.023622
53
0.527793
dreamsxin
fbaf2bb60ba0a5f38d1e2169146fb2e3a553b36d
1,782
hpp
C++
AdvancedOgreFramework/AdvancedOgreFramework.hpp
screwt/advancedogreframework
751f9d8a56e844479b23e72ef47aca1dc77d1132
[ "MIT" ]
null
null
null
AdvancedOgreFramework/AdvancedOgreFramework.hpp
screwt/advancedogreframework
751f9d8a56e844479b23e72ef47aca1dc77d1132
[ "MIT" ]
null
null
null
AdvancedOgreFramework/AdvancedOgreFramework.hpp
screwt/advancedogreframework
751f9d8a56e844479b23e72ef47aca1dc77d1132
[ "MIT" ]
null
null
null
//||||||||||||||||||||||||||||||||||||||||||||||| #ifndef OGRE_FRAMEWORK_HPP #define OGRE_FRAMEWORK_HPP //||||||||||||||||||||||||||||||||||||||||||||||| #include <OgreCamera.h> #include <OgreEntity.h> #include <OgreLogManager.h> #include <OgreOverlay.h> #include <OgreOverlayElement.h> #include <OgreOverlayManager.h> #include <OgreRoot.h> #include <OgreViewport.h> #include <OgreSceneManager.h> #include <OgreRenderWindow.h> #include <OgreConfigFile.h> #include <OISEvents.h> #include <OISInputManager.h> #include <OISKeyboard.h> #include <OISMouse.h> #include <SdkTrays.h> //||||||||||||||||||||||||||||||||||||||||||||||| class OgreFramework : public Ogre::Singleton<OgreFramework>, OIS::KeyListener, OIS::MouseListener { public: OgreFramework(); ~OgreFramework(); bool initOgre(Ogre::String wndTitle, OIS::KeyListener *pKeyListener = 0, OIS::MouseListener *pMouseListener = 0); void updateOgre(double timeSinceLastFrame); bool keyPressed(const OIS::KeyEvent &keyEventRef); bool keyReleased(const OIS::KeyEvent &keyEventRef); bool mouseMoved(const OIS::MouseEvent &evt); bool mousePressed(const OIS::MouseEvent &evt, OIS::MouseButtonID id); bool mouseReleased(const OIS::MouseEvent &evt, OIS::MouseButtonID id); Ogre::Root* m_pRoot; Ogre::RenderWindow* m_pRenderWnd; Ogre::Viewport* m_pViewport; Ogre::Log* m_pLog; Ogre::Timer* m_pTimer; OIS::InputManager* m_pInputMgr; OIS::Keyboard* m_pKeyboard; OIS::Mouse* m_pMouse; Ogre::OverlaySystem* m_pOverlaySystem; OgreBites::SdkTrayManager* m_pTrayMgr; private: OgreFramework(const OgreFramework&); OgreFramework& operator= (const OgreFramework&); }; //||||||||||||||||||||||||||||||||||||||||||||||| #endif //|||||||||||||||||||||||||||||||||||||||||||||||
26.597015
114
0.644781
screwt
fbaf935e17ce8e99a1c2b0dee504c543843a9db6
2,932
cpp
C++
Source/ScsCommon.cpp
JamesBoer/Scs
44a10276c2dd34424205fe3eee1f17ab37fde984
[ "MIT" ]
4
2020-05-28T00:23:45.000Z
2021-12-15T20:12:34.000Z
Source/ScsCommon.cpp
JamesBoer/Scs
44a10276c2dd34424205fe3eee1f17ab37fde984
[ "MIT" ]
null
null
null
Source/ScsCommon.cpp
JamesBoer/Scs
44a10276c2dd34424205fe3eee1f17ab37fde984
[ "MIT" ]
3
2019-03-09T07:27:51.000Z
2021-12-27T12:58:22.000Z
/* The MIT License (MIT) Copyright (c) 2018 James Boer Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "ScsInternal.h" using namespace Scs; static_assert(sizeof(MessageHeader) == 8, "Message header is incompatible size."); const size_t BufferSize = 1024; static InitParams s_params; static std::mutex s_mutex; static void DefaultWriteLine(const char * output) { printf("%s", output); } void * DefaultAlloc(size_t bytes) { return malloc(bytes); } void * DefaultRealloc(void * ptr, size_t bytes) { return realloc(ptr, bytes); } void DefaultFree(void * ptr) { free(ptr); } BufferPtr Scs::CreateBuffer() { return std::allocate_shared<Buffer>(Allocator<Buffer>()); } void Scs::InitializeInternal(const InitParams & params) { s_params = params; if (!s_params.logFn) s_params.logFn = &DefaultWriteLine; if (!s_params.allocFn || !s_params.reallocFn || !s_params.freeFn) { // You must define all memory functions or none assert(!s_params.allocFn && !s_params.reallocFn && !s_params.freeFn); s_params.allocFn = &DefaultAlloc; s_params.reallocFn = &DefaultRealloc; s_params.freeFn = &DefaultFree; } } void Scs::LogWriteLine(const char * format, ...) { std::unique_lock<std::mutex> lock(s_mutex); va_list argptr; va_start(argptr, format); char buffer[BufferSize]; #if defined(SCS_WINDOWS) _vsnprintf_s(buffer, BufferSize, _TRUNCATE, format, argptr); #else vsnprintf(buffer, BufferSize, format, argptr); #endif size_t len = strlen(buffer); if (len < BufferSize - 2) { buffer[len] = '\n'; buffer[len + 1] = 0; } s_params.logFn(buffer); va_end(argptr); } void * Scs::Alloc(size_t bytes) { // Initialize must be called before library is used assert(s_params.allocFn); return s_params.allocFn(bytes); } void * Scs::Realloc(void * ptr, size_t bytes) { assert(s_params.reallocFn); return s_params.reallocFn(ptr, bytes); } void Scs::Free(void * ptr) { assert(s_params.freeFn); s_params.freeFn(ptr); }
25.059829
82
0.746248
JamesBoer
fbb198a28576cc25a305b0dcdc2cc4240a5f260f
1,443
hpp
C++
gearoenix/core/gx-cr-allocator.hpp
Hossein-Noroozpour/gearoenix
c8fa8b8946c03c013dad568d6d7a97d81097c051
[ "BSD-Source-Code" ]
35
2018-01-07T02:34:38.000Z
2022-02-09T05:19:03.000Z
gearoenix/core/gx-cr-allocator.hpp
Hossein-Noroozpour/gearoenix
c8fa8b8946c03c013dad568d6d7a97d81097c051
[ "BSD-Source-Code" ]
111
2017-09-20T09:12:36.000Z
2020-12-27T12:52:03.000Z
gearoenix/core/gx-cr-allocator.hpp
Hossein-Noroozpour/gearoenix
c8fa8b8946c03c013dad568d6d7a97d81097c051
[ "BSD-Source-Code" ]
5
2020-02-11T11:17:37.000Z
2021-01-08T17:55:43.000Z
#ifndef GEAROENIX_CORE_ALLOCATOR_HPP #define GEAROENIX_CORE_ALLOCATOR_HPP #include "gx-cr-static.hpp" #include <map> #include <memory> #include <optional> namespace gearoenix::core { class Allocator final { /// size, offset (within itself) typedef std::pair<std::size_t, std::size_t> SizeOffset; /// allocator that is before free space, allocator that is after space typedef std::pair<Allocator*, Allocator*> Range; GX_GET_CVAL_PRV(std::size_t, size) /// It is the offset from the direct parent not the origin parent GX_GET_CVAL_PRV(std::size_t, offset) /// It is the offset from the root GX_GET_CVAL_PRV(std::size_t, root_offset) private: GX_CREATE_GUARD(this) std::map<SizeOffset, Range> ranges; std::weak_ptr<Allocator> self; std::shared_ptr<Allocator> parent; std::optional<SizeOffset> previous_key = std::nullopt; std::optional<SizeOffset> next_key = std::nullopt; Allocator* previous = nullptr; Allocator* next = nullptr; Allocator* first_child = nullptr; Allocator(std::size_t size, std::size_t offset, std::size_t root_offset) noexcept; void deallocate(const Allocator* child) noexcept; public: [[nodiscard]] static std::shared_ptr<Allocator> construct(std::size_t size, std::size_t offset, std::size_t root_offset) noexcept; ~Allocator() noexcept; [[nodiscard]] std::shared_ptr<Allocator> allocate(std::size_t size) noexcept; }; } #endif
35.195122
134
0.723493
Hossein-Noroozpour
fbb3e0531bddc5c80fa3b93449c86a86b2b5a9ec
1,514
cpp
C++
CodeForces/RoadMap_A2OJ/B_Airport.cpp
ItsJavito/CP-Problems
0b30bb80a47824ab0590d683b8b5e6f715bbec84
[ "MIT" ]
null
null
null
CodeForces/RoadMap_A2OJ/B_Airport.cpp
ItsJavito/CP-Problems
0b30bb80a47824ab0590d683b8b5e6f715bbec84
[ "MIT" ]
null
null
null
CodeForces/RoadMap_A2OJ/B_Airport.cpp
ItsJavito/CP-Problems
0b30bb80a47824ab0590d683b8b5e6f715bbec84
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; #define gc getchar_unlocked #define fastio \ ios_base::sync_with_stdio(false); \ cin.tie(NULL) #define endl "\n" #define ll long long #define PI 3.1415926535897932384626 #define deb(x) cout << #x << " = " << x << endl; #define deb2(x, y) cout << #x << " = " << x << ", " << #y << " = " << y << endl; #define pb push_back #define F first #define S second #define all(x) x.begin(), x.end() #define rall(x) x.rbegin(), x.rend() #define clr(x) memset(x, 0, sizeof(x)) #define sortall(x) sort(all(x)) #define FOR(i,n) for(int (i)=0;(i)<(n);++(i)) #define FOREACH(i,t) for (typeof(t.begin()) i=t.begin(); i!=t.end(); i++) #define REP(i,a,b) for(int (i)=(a);(i)<=(b);++i) typedef pair<int, int> pii; typedef pair<ll, ll> pl; typedef vector<int> vi; typedef vector<ll> vl; typedef vector<pii> vpii; typedef vector<pl> vpl; typedef vector<vi> vvi; typedef vector<vl> vvl; const int mod = 1'000'000'007; const int N = 3e5; int main() { fastio; int n, m , min = 0 , max = 0; cin >> n >> m; priority_queue<int> pq; priority_queue<int , vi , greater<int>> min_pq; FOR(i , m){ int num; cin >> num; pq.push(num); min_pq.push(num); } FOR(i, n){ int a , b; a = min_pq.top();min_pq.pop(); min += a--; if(a > 0) min_pq.push(a); b = pq.top(); pq.pop(); max += b--; if(b > 0)pq.push(b); } cout << max << " " << min << endl; return 0; }
26.561404
80
0.546235
ItsJavito
fbb431665877dcbd9e508b13467a954b06a02f0c
3,699
cpp
C++
csacademy/32/F.cpp
metaflow/contests
5e9ffcb72c3e7da54b5e0818b1afa59f5778ffa2
[ "MIT" ]
1
2019-05-12T23:41:00.000Z
2019-05-12T23:41:00.000Z
csacademy/32/F.cpp
metaflow/contests
5e9ffcb72c3e7da54b5e0818b1afa59f5778ffa2
[ "MIT" ]
null
null
null
csacademy/32/F.cpp
metaflow/contests
5e9ffcb72c3e7da54b5e0818b1afa59f5778ffa2
[ "MIT" ]
null
null
null
#if defined(LOCAL) // #define RANDOM_TEST #define PROBLEM_NAME "F" const double _max_double_error = 1e-9; #include "testutils.h" #endif #include <bits/stdc++.h> using namespace std; using vi = vector<int>; using vvi = vector<vi>; using ii = pair<int,int>; using vii = vector<ii>; using l = long long; using vl = vector<l>; using vvl = vector<vl>; using ll = pair<l,l>; using vll = vector<ll>; using vvll = vector<vll>; using lu = unsigned long long; using vb = vector<bool>; using vvb = vector<vb>; using vd = vector<double>; using vvd = vector<vd>; using mll = unordered_map<l, l>; const l INF = numeric_limits<int>::max(); const double EPS = 1e-10; static constexpr auto PI = acos(-1); const l e0=1, e3=1000, e5=100000, e6=10*e5, e7=10*e6, e8=10*e7, e9=10*e8; const char lf = '\n'; #define all(x) begin(x), end(x) #define F(a,b,c) for (l a = l(b); a < l(c); a++) #define B(a,b,c) for (l a = l(b); a > l(c); a--) #if defined(LOCAL) bool local = true; #define L(x...) debug(x) #else bool local = false; #define L(x, ...) (x) #endif struct VoidStream { void operator&(std::ostream&) { } }; #define LOG !(local) ? (void) 0 : VoidStream() & cerr struct BIT { vi tree; l max_p; BIT(size_t n) { max_p = n; tree.resize(n + 1); }; void reset(size_t n) { max_p = n; tree.clear(); tree.resize(n + 1); } // sum of [1, p], O(log(max)) l get(l p) { l sum = 0; while (p) { sum += tree[p]; p -= (p & -p); } return sum; } l at(l p) { return get(p) - get(p - 1); } // O(log(max)) void add(l p, l value) { while (p <= max_p) { tree[p] += value; p += (p & -p); } } // find lowest index with given sum, -1 if not found O(log(max)) l find(l sum) { l mask = max_p; while (true) { l lower = (mask & -mask); if (lower == mask) break; mask -= lower; } l p = 0; l top = -1; while (mask != 0) { l m = p + mask; if (m <= max_p) { if (sum == tree[m]) top = m; if (sum > tree[m]) { p = m; sum -= tree[m]; } } mask >>= 1; } if (sum != 0) return top; return p; } }; struct RandGen { int x, y, z; int nextInt() { int t = x ^ (x << 11); x = y; y = z; z ^= (z >> 19) ^ t ^ (t >> 8); return z; } int random(int N) { return nextInt() % N; } }; const l MAX = 50 * e6; bitset<MAX> bits; const l B = e6; BIT bt(B); void init(int N, int M) { bits.reset(); M++; N++; } int addr(int p) { return p / 50 + 1; } void flipPosition(int p) { bool v = bits[p]; bt.add(addr(p), v ? -1 : +1); bits[p] = not v; } int getCount(int st, int fn) { int r = 0; l ps = addr(st), pf = addr(fn); l a = ps; l b = pf - 1; if (b > a) { r += bt.get(b) - bt.get(a); l i = st; while (addr(i) == ps) { if (bits[i]) r++; i++; } i = fn; while (addr(i) == pf) { if (bits[i]) r++; i--; } } else { F(i, st, fn + 1) if (bits[i]) r++; } return r; } void solve(istream& cin, ostream& cout) { int N, M; RandGen rng; cin >> N >> M >> rng.x >> rng.y >> rng.z; init(N, M); long long hashSol = 0; for (long long i = 0; i < M; i++) { if (rng.random(2) == 0) { const int poz = rng.random(N); flipPosition(poz); } else { int st = rng.random(N), fn = rng.random(N); if (st > fn) { swap(st, fn); } hashSol ^= i * getCount(st, fn); } } cout << hashSol << "\n"; } int main() { ios_base::sync_with_stdio(false); cin.tie(0); cout << fixed << setprecision(15); #if defined(LOCAL) maybe_run_tests(cin, cout); #else solve(cin, cout); #endif }
19.468421
73
0.506623
metaflow
fbbbe6b181130b377631fa03f046e862bc5e3644
1,299
cpp
C++
Sources/World/Systems/ScriptSystem.cpp
carloshgsilva/VoxelEngine
5ba308d3573805437124f32d407306776c1d66d6
[ "MIT" ]
1
2022-01-20T15:53:31.000Z
2022-01-20T15:53:31.000Z
Sources/World/Systems/ScriptSystem.cpp
carloshgsilva/VoxelEngine
5ba308d3573805437124f32d407306776c1d66d6
[ "MIT" ]
null
null
null
Sources/World/Systems/ScriptSystem.cpp
carloshgsilva/VoxelEngine
5ba308d3573805437124f32d407306776c1d66d6
[ "MIT" ]
null
null
null
#include "ScriptSystem.h" #include "World/Components.h" #include "Script/ScriptLib_Core.h" #include "Mod/ModLoader.h" void ScriptSystem::OnScriptUpdated(entt::registry& r, entt::entity e) { auto& scriptAsset = r.get<Script>(e).Asset; if (!scriptAsset.IsValid()) { return; } std::string scriptPath = "Mods/"; scriptPath += ModLoader::Get().GetAssetPath(scriptAsset->GetGUID()); scriptPath = scriptPath.substr(0, scriptPath.find_last_of('.')); std::string scriptName = scriptPath.substr(scriptPath.find_last_of('/')+1); if (!vm->HasModule(scriptPath)) { vm->RunModule(scriptPath); } Handle c_rotatingCube = vm->GetVariable(scriptPath, scriptName); if(vm->Call(c_rotatingCube, ctx->m_new)){ Handle script = vm->GetHandle(); Handle newForeign = ctx->wrapEntity(e); if (vm->Call(script, ctx->s_e, newForeign)) { _Scripts.push_back(script); } } } void ScriptSystem::OnCreate() { { vm = NewUnique<ScriptVM>(); ScriptLib_Core::Import(*vm); ctx = new WorldCtx(W, vm.get()); vm->SetUserData(ctx); } R->on_construct<Script>().connect<&ScriptSystem::OnScriptUpdated>(this); R->on_update<Script>().connect<&ScriptSystem::OnScriptUpdated>(this); } void ScriptSystem::OnUpdate(DeltaTime dt) { for (auto& s : _Scripts) { vm->Call(s, ctx->m_update); } }
23.196429
76
0.692071
carloshgsilva
fbbec304e47f83bb92011559ada8928752cb5863
1,910
cpp
C++
src/ripple/basics/impl/UptimeClock.cpp
yinchengtsinghua/RippleCPPChinese
a32a38a374547bdc5eb0fddcd657f45048aaad6a
[ "BSL-1.0" ]
5
2019-01-23T04:36:03.000Z
2020-02-04T07:10:39.000Z
src/ripple/basics/impl/UptimeClock.cpp
yinchengtsinghua/RippleCPPChinese
a32a38a374547bdc5eb0fddcd657f45048aaad6a
[ "BSL-1.0" ]
null
null
null
src/ripple/basics/impl/UptimeClock.cpp
yinchengtsinghua/RippleCPPChinese
a32a38a374547bdc5eb0fddcd657f45048aaad6a
[ "BSL-1.0" ]
2
2019-05-14T07:26:59.000Z
2020-06-15T07:25:01.000Z
//此源码被清华学神尹成大魔王专业翻译分析并修改 //尹成QQ77025077 //尹成微信18510341407 //尹成所在QQ群721929980 //尹成邮箱 yinc13@mails.tsinghua.edu.cn //尹成毕业于清华大学,微软区块链领域全球最有价值专家 //https://mvp.microsoft.com/zh-cn/PublicProfile/4033620 //———————————————————————————————————————————————————————————————————————————————————————————————————————————————— /* 此文件是Rippled的一部分:https://github.com/ripple/rippled 版权所有(c)2012,2013 Ripple Labs Inc. 使用、复制、修改和/或分发本软件的权限 特此授予免费或不收费的目的,前提是 版权声明和本许可声明出现在所有副本中。 本软件按“原样”提供,作者不作任何保证。 关于本软件,包括 适销性和适用性。在任何情况下,作者都不对 任何特殊、直接、间接或后果性损害或任何损害 因使用、数据或利润损失而导致的任何情况,无论是在 合同行为、疏忽或其他侵权行为 或与本软件的使用或性能有关。 **/ //============================================================== #include <ripple/basics/UptimeClock.h> namespace ripple { std::atomic<UptimeClock::rep> UptimeClock::now_{0}; //启动后的秒数 std::atomic<bool> UptimeClock::stop_{false}; //停止更新线程 //在波纹状关闭时,取消并等待更新线程 UptimeClock::update_thread::~update_thread() { if (joinable()) { stop_ = true; //此join()可能需要1个,但只会发生 //一次在波纹停机。 join(); } } //启动更新线程 UptimeClock::update_thread UptimeClock::start_clock() { return update_thread{[] { using namespace std; using namespace std::chrono; //每秒钟醒来,立即更新\u auto next = system_clock::now() + 1s; while (!stop_) { this_thread::sleep_until(next); next += 1s; ++now_; } }}; } //这实际上测量的是从第一次使用开始的时间,而不是从波纹开始的时间。 //然而,这两个时代之间的差别只有一小部分时间 //不重要。 UptimeClock::time_point UptimeClock::now() { //第一次使用时启动更新线程 static const auto init = start_clock(); //返回自波纹启动后的秒数 return time_point{duration{now_}}; } } //涟漪
23.012048
114
0.513089
yinchengtsinghua