blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
905 values
visit_date
timestamp[us]date
2015-08-09 11:21:18
2023-09-06 10:45:07
revision_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-17 19:19:19
committer_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-06 06:22:19
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-07 00:51:45
2023-09-14 21:58:39
gha_created_at
timestamp[us]date
2008-03-27 23:40:48
2023-08-21 23:17:38
gha_language
stringclasses
141 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
115 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
7725f63276574c396cdc6a239ed02bba4e7b3515
2abe8354cb3cdc99a981501516f0f6132b296821
/2021-7-26/Fudan_U3/src/c.cpp
6a6f913f2e29c4d5a7b3334d383606baffbb7257
[]
no_license
maZymaZe/acm-remote
ddacdc367669707cd08527af2c7d5824b9308bd3
594b1836a1e1673b0afa1ee96e7cef7ef4fd8210
refs/heads/master
2023-07-21T19:27:33.180085
2021-08-28T03:42:08
2021-08-28T03:42:08
330,306,957
0
0
null
null
null
null
UTF-8
C++
false
false
3,667
cpp
#include <algorithm> #include <cmath> #include <cstdio> #include <cstdlib> #include <cstring> #include <iostream> #define int long long //哈哈哈#define真好用 using namespace std; int fastRead() { int f = 1, r = 0; char c = getchar(); while (c > '9' || c < '0') { if (c == '-') { f = -1; } c = getchar(); } while (c >= '0' && c <= '9') { r = r * 10 + c - '0'; c = getchar(); } return f * r; } void fastWrite(int x) { if (x > 9) { fastWrite(x / 10); } putchar(x % 10 + '0'); } int a, b, c, n, m; void process1() { for (int i = 1; i <= a - c; i++) { printf("%c", 'a'); } for (int i = 1; i <= c; i++) { printf("%c", 'b'); } for (int i = 1; i <= n - a; i++) { printf("%c", 'e'); } puts(""); for (int i = 1; i <= a - c; i++) { printf("%c", 'a'); } for (int i = 1; i <= c; i++) { printf("%c", 'b'); } for (int i = 1; i <= b - c; i++) { printf("%c", 'c'); } for (int i = 1; i <= n - a - b + c; i++) { printf("%c", 'f'); } puts(""); for (int i = 1; i <= a - c; i++) { printf("%c", 'g'); } for (int i = 1; i <= c; i++) { printf("%c", 'b'); } for (int i = 1; i <= b - c; i++) { printf("%c", 'c'); } for (int i = 1; i <= n - a - b + c; i++) { printf("%c", 'h'); } } void process2() { for (int i = 1; i <= b - a; i++) { printf("%c", 'm'); } for (int i = 1; i <= a; i++) { printf("%c", 'a'); } for (int i = 1; i <= c - a; i++) { printf("%c", 'c'); } for (int i = 1; i <= n - c - b + a; i++) { printf("%c", 'q'); } puts(""); for (int i = 1; i <= b - a; i++) { printf("%c", 'b'); } for (int i = 1; i <= a; i++) { printf("%c", 'a'); } for (int i = 1; i <= n - b; i++) { printf("%c", 'u'); } puts(""); for (int i = 1; i <= b - a; i++) { printf("%c", 'b'); } for (int i = 1; i <= a; i++) { printf("%c", 'a'); } for (int i = 1; i <= c - a; i++) { printf("%c", 'c'); } for (int i = 1; i <= n - c - b + a; i++) { printf("%c", 'h'); } } void process3() { for (int i = 1; i <= a - b; i++) { printf("%c", 'a'); } for (int i = 1; i <= b; i++) { printf("%c", 'b'); } for (int i = 1; i <= c - b; i++) { printf("%c", 'c'); } for (int i = 1; i <= n - a - c + b; i++) { printf("%c", 'q'); } puts(""); for (int i = 1; i <= a - b; i++) { printf("%c", 'a'); } for (int i = 1; i <= b; i++) { printf("%c", 'b'); } for (int i = 1; i <= n - a; i++) { printf("%c", 'u'); } puts(""); for (int i = 1; i <= a - b; i++) { printf("%c", 'x'); } for (int i = 1; i <= b; i++) { printf("%c", 'b'); } for (int i = 1; i <= c - b; i++) { printf("%c", 'c'); } for (int i = 1; i <= n - a - c + b; i++) { printf("%c", 'h'); } } signed main() { //这里相应的也要改成signed a = fastRead(), b = fastRead(), c = fastRead(), n = fastRead(); m = min(a, b); m = min(m, c); if (a + b + c - 2 * m > n) { puts("NO"); return 0; } if (c == m) { process1(); } else if (a == m) { process2(); } else { process3(); } return 0; }
[ "782618517@qq.com" ]
782618517@qq.com
fd2390be68ee0e62fb194681a056caf318967d46
4e1188866e4b786fae1dec085594b398cc8c9a2e
/friendtoolbox.h
3b45bc0a26f4e8b642671ed5d70da86197990f53
[]
no_license
lsj754039701/QQ
2f33b988385226786be124c7b4839cff24023147
134d4ac96084ae48933ec7f0404528bd55770630
refs/heads/master
2021-01-17T17:10:01.906937
2016-06-05T14:52:43
2016-06-05T14:52:43
60,465,337
1
0
null
null
null
null
UTF-8
C++
false
false
280
h
#ifndef FRIENDTOOLBOX_H #define FRIENDTOOLBOX_H #include <QToolBox> class friendToolBox:public QToolBox { Q_OBJECT public: friendToolBox(QWidget *parent=0); protected slots: void slotIndexChange(int index); private: int curIndex; }; #endif // FRIENDTOOLBOX_H
[ "754039701@qq.com" ]
754039701@qq.com
3fa814e2624b12b3a466e544f8b79f190ac459aa
646f2d559c6739e282f2c0142fef56aa154d55b8
/src/test/rpc_tests.cpp
afddca5c4a8b63d7d80c99c4a12d7f8e3b5abadc
[ "MIT" ]
permissive
Cyprella/suc
72ed31971249e5dd688e664eff18c24eb0a42876
7c62b7f1c786dbbda3b93febefe8c818486d0e82
refs/heads/master
2021-04-27T18:26:08.619581
2018-02-23T06:03:29
2018-02-23T06:03:29
121,935,379
0
0
null
null
null
null
UTF-8
C++
false
false
16,688
cpp
// Copyright (c) 2012-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "rpcserver.h" #include "rpcclient.h" #include "base58.h" #include "netbase.h" #include "test/test_suc.h" #include <boost/algorithm/string.hpp> #include <boost/test/unit_test.hpp> #include <univalue.h> using namespace std; UniValue createArgs(int nRequired, const char* address1=NULL, const char* address2=NULL) { UniValue result(UniValue::VARR); result.push_back(nRequired); UniValue addresses(UniValue::VARR); if (address1) addresses.push_back(address1); if (address2) addresses.push_back(address2); result.push_back(addresses); return result; } UniValue CallRPC(string args) { vector<string> vArgs; boost::split(vArgs, args, boost::is_any_of(" \t")); string strMethod = vArgs[0]; vArgs.erase(vArgs.begin()); UniValue params = RPCConvertValues(strMethod, vArgs); rpcfn_type method = tableRPC[strMethod]->actor; try { UniValue result = (*method)(params, false); return result; } catch (const UniValue& objError) { throw runtime_error(find_value(objError, "message").get_str()); } } BOOST_FIXTURE_TEST_SUITE(rpc_tests, TestingSetup) BOOST_AUTO_TEST_CASE(rpc_rawparams) { // Test raw transaction API argument handling UniValue r; BOOST_CHECK_THROW(CallRPC("getrawtransaction"), runtime_error); BOOST_CHECK_THROW(CallRPC("getrawtransaction not_hex"), runtime_error); BOOST_CHECK_THROW(CallRPC("getrawtransaction a3b807410df0b60fcb9736768df5823938b2f838694939ba45f3c0a1bff150ed not_int"), runtime_error); BOOST_CHECK_THROW(CallRPC("createrawtransaction"), runtime_error); BOOST_CHECK_THROW(CallRPC("createrawtransaction null null"), runtime_error); BOOST_CHECK_THROW(CallRPC("createrawtransaction not_array"), runtime_error); BOOST_CHECK_THROW(CallRPC("createrawtransaction [] []"), runtime_error); BOOST_CHECK_THROW(CallRPC("createrawtransaction {} {}"), runtime_error); BOOST_CHECK_NO_THROW(CallRPC("createrawtransaction [] {}")); BOOST_CHECK_THROW(CallRPC("createrawtransaction [] {} extra"), runtime_error); BOOST_CHECK_THROW(CallRPC("decoderawtransaction"), runtime_error); BOOST_CHECK_THROW(CallRPC("decoderawtransaction null"), runtime_error); BOOST_CHECK_THROW(CallRPC("decoderawtransaction DEADBEEF"), runtime_error); string rawtx = "0100000001a15d57094aa7a21a28cb20b59aab8fc7d1149a3bdbcddba9c622e4f5f6a99ece010000006c493046022100f93bb0e7d8db7bd46e40132d1f8242026e045f03a0efe71bbb8e3f475e970d790221009337cd7f1f929f00cc6ff01f03729b069a7c21b59b1736ddfee5db5946c5da8c0121033b9b137ee87d5a812d6f506efdd37f0affa7ffc310711c06c7f3e097c9447c52ffffffff0100e1f505000000001976a9140389035a9225b3839e2bbf32d826a1e222031fd888ac00000000"; BOOST_CHECK_NO_THROW(r = CallRPC(string("decoderawtransaction ")+rawtx)); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "size").get_int(), 193); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "version").get_int(), 1); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "locktime").get_int(), 0); BOOST_CHECK_THROW(r = CallRPC(string("decoderawtransaction ")+rawtx+" extra"), runtime_error); BOOST_CHECK_THROW(CallRPC("signrawtransaction"), runtime_error); BOOST_CHECK_THROW(CallRPC("signrawtransaction null"), runtime_error); BOOST_CHECK_THROW(CallRPC("signrawtransaction ff00"), runtime_error); BOOST_CHECK_NO_THROW(CallRPC(string("signrawtransaction ")+rawtx)); BOOST_CHECK_NO_THROW(CallRPC(string("signrawtransaction ")+rawtx+" null null NONE|ANYONECANPAY")); BOOST_CHECK_NO_THROW(CallRPC(string("signrawtransaction ")+rawtx+" [] [] NONE|ANYONECANPAY")); BOOST_CHECK_THROW(CallRPC(string("signrawtransaction ")+rawtx+" null null badenum"), runtime_error); // Only check failure cases for sendrawtransaction, there's no network to send to... BOOST_CHECK_THROW(CallRPC("sendrawtransaction"), runtime_error); BOOST_CHECK_THROW(CallRPC("sendrawtransaction null"), runtime_error); BOOST_CHECK_THROW(CallRPC("sendrawtransaction DEADBEEF"), runtime_error); BOOST_CHECK_THROW(CallRPC(string("sendrawtransaction ")+rawtx+" extra"), runtime_error); } BOOST_AUTO_TEST_CASE(rpc_rawsign) { UniValue r; // input is a 1-of-2 multisig (so is output): string prevout = "[{\"txid\":\"b4cc287e58f87cdae59417329f710f3ecd75a4ee1d2872b7248f50977c8493f3\"," "\"vout\":1,\"scriptPubKey\":\"a914b10c9df5f7edf436c697f02f1efdba4cf399615187\"," "\"redeemScript\":\"512103debedc17b3df2badbcdd86d5feb4562b86fe182e5998abd8bcd4f122c6155b1b21027e940bb73ab8732bfdf7f9216ecefca5b94d6df834e77e108f68e66f126044c052ae\"}]"; r = CallRPC(string("createrawtransaction ")+prevout+" "+ "{\"7iYoULd4BAqRsRt1UbD5qqna88JvKRU3SL\":11}"); string notsigned = r.get_str(); string privkey1 = "\"XEwTRsCX3CiWSQf8YmKMTeb84KyTbibkUv9mDTZHQ5MwuKG2ZzES\""; string privkey2 = "\"XDmZ7LjGd94Q81eUBjb2h6uV5Y14s7fmeXWEGYabfBJP8RVpprBu\""; r = CallRPC(string("signrawtransaction ")+notsigned+" "+prevout+" "+"[]"); BOOST_CHECK(find_value(r.get_obj(), "complete").get_bool() == false); r = CallRPC(string("signrawtransaction ")+notsigned+" "+prevout+" "+"["+privkey1+","+privkey2+"]"); BOOST_CHECK(find_value(r.get_obj(), "complete").get_bool() == true); } BOOST_AUTO_TEST_CASE(rpc_createraw_op_return) { BOOST_CHECK_NO_THROW(CallRPC("createrawtransaction [{\"txid\":\"a3b807410df0b60fcb9736768df5823938b2f838694939ba45f3c0a1bff150ed\",\"vout\":0}] {\"data\":\"68656c6c6f776f726c64\"}")); // Allow more than one data transaction output BOOST_CHECK_NO_THROW(CallRPC("createrawtransaction [{\"txid\":\"a3b807410df0b60fcb9736768df5823938b2f838694939ba45f3c0a1bff150ed\",\"vout\":0}] {\"data\":\"68656c6c6f776f726c64\",\"data\":\"68656c6c6f776f726c64\"}")); // Key not "data" (bad address) BOOST_CHECK_THROW(CallRPC("createrawtransaction [{\"txid\":\"a3b807410df0b60fcb9736768df5823938b2f838694939ba45f3c0a1bff150ed\",\"vout\":0}] {\"somedata\":\"68656c6c6f776f726c64\"}"), runtime_error); // Bad hex encoding of data output BOOST_CHECK_THROW(CallRPC("createrawtransaction [{\"txid\":\"a3b807410df0b60fcb9736768df5823938b2f838694939ba45f3c0a1bff150ed\",\"vout\":0}] {\"data\":\"12345\"}"), runtime_error); BOOST_CHECK_THROW(CallRPC("createrawtransaction [{\"txid\":\"a3b807410df0b60fcb9736768df5823938b2f838694939ba45f3c0a1bff150ed\",\"vout\":0}] {\"data\":\"12345g\"}"), runtime_error); // Data 81 bytes long BOOST_CHECK_NO_THROW(CallRPC("createrawtransaction [{\"txid\":\"a3b807410df0b60fcb9736768df5823938b2f838694939ba45f3c0a1bff150ed\",\"vout\":0}] {\"data\":\"010203040506070809101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081\"}")); } BOOST_AUTO_TEST_CASE(rpc_format_monetary_values) { BOOST_CHECK(ValueFromAmount(0LL).write() == "0.00000000"); BOOST_CHECK(ValueFromAmount(1LL).write() == "0.00000001"); BOOST_CHECK(ValueFromAmount(17622195LL).write() == "0.17622195"); BOOST_CHECK(ValueFromAmount(50000000LL).write() == "0.50000000"); BOOST_CHECK(ValueFromAmount(89898989LL).write() == "0.89898989"); BOOST_CHECK(ValueFromAmount(100000000LL).write() == "1.00000000"); BOOST_CHECK(ValueFromAmount(2099999999999990LL).write() == "20999999.99999990"); BOOST_CHECK(ValueFromAmount(2099999999999999LL).write() == "20999999.99999999"); BOOST_CHECK_EQUAL(ValueFromAmount(0).write(), "0.00000000"); BOOST_CHECK_EQUAL(ValueFromAmount((COIN/10000)*123456789).write(), "12345.67890000"); BOOST_CHECK_EQUAL(ValueFromAmount(-COIN).write(), "-1.00000000"); BOOST_CHECK_EQUAL(ValueFromAmount(-COIN/10).write(), "-0.10000000"); BOOST_CHECK_EQUAL(ValueFromAmount(COIN*100000000).write(), "100000000.00000000"); BOOST_CHECK_EQUAL(ValueFromAmount(COIN*10000000).write(), "10000000.00000000"); BOOST_CHECK_EQUAL(ValueFromAmount(COIN*1000000).write(), "1000000.00000000"); BOOST_CHECK_EQUAL(ValueFromAmount(COIN*100000).write(), "100000.00000000"); BOOST_CHECK_EQUAL(ValueFromAmount(COIN*10000).write(), "10000.00000000"); BOOST_CHECK_EQUAL(ValueFromAmount(COIN*1000).write(), "1000.00000000"); BOOST_CHECK_EQUAL(ValueFromAmount(COIN*100).write(), "100.00000000"); BOOST_CHECK_EQUAL(ValueFromAmount(COIN*10).write(), "10.00000000"); BOOST_CHECK_EQUAL(ValueFromAmount(COIN).write(), "1.00000000"); BOOST_CHECK_EQUAL(ValueFromAmount(COIN/10).write(), "0.10000000"); BOOST_CHECK_EQUAL(ValueFromAmount(COIN/100).write(), "0.01000000"); BOOST_CHECK_EQUAL(ValueFromAmount(COIN/1000).write(), "0.00100000"); BOOST_CHECK_EQUAL(ValueFromAmount(COIN/10000).write(), "0.00010000"); BOOST_CHECK_EQUAL(ValueFromAmount(COIN/100000).write(), "0.00001000"); BOOST_CHECK_EQUAL(ValueFromAmount(COIN/1000000).write(), "0.00000100"); BOOST_CHECK_EQUAL(ValueFromAmount(COIN/10000000).write(), "0.00000010"); BOOST_CHECK_EQUAL(ValueFromAmount(COIN/100000000).write(), "0.00000001"); } static UniValue ValueFromString(const std::string &str) { UniValue value; BOOST_CHECK(value.setNumStr(str)); return value; } BOOST_AUTO_TEST_CASE(rpc_parse_monetary_values) { BOOST_CHECK_THROW(AmountFromValue(ValueFromString("-0.00000001")), UniValue); BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString("0")), 0LL); BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString("0.00000000")), 0LL); BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString("0.00000001")), 1LL); BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString("0.17622195")), 17622195LL); BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString("0.5")), 50000000LL); BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString("0.50000000")), 50000000LL); BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString("0.89898989")), 89898989LL); BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString("1.00000000")), 100000000LL); BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString("20999999.9999999")), 2099999999999990LL); BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString("20999999.99999999")), 2099999999999999LL); BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString("1e-8")), COIN/100000000); BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString("0.1e-7")), COIN/100000000); BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString("0.01e-6")), COIN/100000000); BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString("0.0000000000000000000000000000000000000000000000000000000000000000000000000001e+68")), COIN/100000000); BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString("10000000000000000000000000000000000000000000000000000000000000000e-64")), COIN); BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString("0.000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000e64")), COIN); BOOST_CHECK_THROW(AmountFromValue(ValueFromString("1e-9")), UniValue); //should fail BOOST_CHECK_THROW(AmountFromValue(ValueFromString("0.000000019")), UniValue); //should fail BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString("0.00000001000000")), 1LL); //should pass, cut trailing 0 BOOST_CHECK_THROW(AmountFromValue(ValueFromString("19e-9")), UniValue); //should fail BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString("0.19e-6")), 19); //should pass, leading 0 is present BOOST_CHECK_THROW(AmountFromValue(ValueFromString("92233720368.54775808")), UniValue); //overflow error BOOST_CHECK_THROW(AmountFromValue(ValueFromString("1e+11")), UniValue); //overflow error BOOST_CHECK_THROW(AmountFromValue(ValueFromString("1e11")), UniValue); //overflow error signless BOOST_CHECK_THROW(AmountFromValue(ValueFromString("93e+9")), UniValue); //overflow error } BOOST_AUTO_TEST_CASE(json_parse_errors) { // Valid BOOST_CHECK_EQUAL(ParseNonRFCJSONValue("1.0").get_real(), 1.0); // Valid, with leading or trailing whitespace BOOST_CHECK_EQUAL(ParseNonRFCJSONValue(" 1.0").get_real(), 1.0); BOOST_CHECK_EQUAL(ParseNonRFCJSONValue("1.0 ").get_real(), 1.0); BOOST_CHECK_THROW(AmountFromValue(ParseNonRFCJSONValue(".19e-6")), std::runtime_error); //should fail, missing leading 0, therefore invalid JSON BOOST_CHECK_EQUAL(AmountFromValue(ParseNonRFCJSONValue("0.00000000000000000000000000000000000001e+30 ")), 1); // Invalid, initial garbage BOOST_CHECK_THROW(ParseNonRFCJSONValue("[1.0"), std::runtime_error); BOOST_CHECK_THROW(ParseNonRFCJSONValue("a1.0"), std::runtime_error); // Invalid, trailing garbage BOOST_CHECK_THROW(ParseNonRFCJSONValue("1.0sds"), std::runtime_error); BOOST_CHECK_THROW(ParseNonRFCJSONValue("1.0]"), std::runtime_error); // BTC addresses should fail parsing BOOST_CHECK_THROW(ParseNonRFCJSONValue("175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W"), std::runtime_error); BOOST_CHECK_THROW(ParseNonRFCJSONValue("3J98t1WpEZ73CNmQviecrnyiWrnqRhWNL"), std::runtime_error); } BOOST_AUTO_TEST_CASE(rpc_ban) { BOOST_CHECK_NO_THROW(CallRPC(string("clearbanned"))); UniValue r; BOOST_CHECK_NO_THROW(r = CallRPC(string("setban 127.0.0.0 add"))); BOOST_CHECK_THROW(r = CallRPC(string("setban 127.0.0.0:8334")), runtime_error); //portnumber for setban not allowed BOOST_CHECK_NO_THROW(r = CallRPC(string("listbanned"))); UniValue ar = r.get_array(); UniValue o1 = ar[0].get_obj(); UniValue adr = find_value(o1, "address"); BOOST_CHECK_EQUAL(adr.get_str(), "127.0.0.0/32"); BOOST_CHECK_NO_THROW(CallRPC(string("setban 127.0.0.0 remove")));; BOOST_CHECK_NO_THROW(r = CallRPC(string("listbanned"))); ar = r.get_array(); BOOST_CHECK_EQUAL(ar.size(), 0); BOOST_CHECK_NO_THROW(r = CallRPC(string("setban 127.0.0.0/24 add 1607731200 true"))); BOOST_CHECK_NO_THROW(r = CallRPC(string("listbanned"))); ar = r.get_array(); o1 = ar[0].get_obj(); adr = find_value(o1, "address"); UniValue banned_until = find_value(o1, "banned_until"); BOOST_CHECK_EQUAL(adr.get_str(), "127.0.0.0/24"); BOOST_CHECK_EQUAL(banned_until.get_int64(), 1607731200); // absolute time check BOOST_CHECK_NO_THROW(CallRPC(string("clearbanned"))); BOOST_CHECK_NO_THROW(r = CallRPC(string("setban 127.0.0.0/24 add 200"))); BOOST_CHECK_NO_THROW(r = CallRPC(string("listbanned"))); ar = r.get_array(); o1 = ar[0].get_obj(); adr = find_value(o1, "address"); banned_until = find_value(o1, "banned_until"); BOOST_CHECK_EQUAL(adr.get_str(), "127.0.0.0/24"); int64_t now = GetTime(); BOOST_CHECK(banned_until.get_int64() > now); BOOST_CHECK(banned_until.get_int64()-now <= 200); // must throw an exception because 127.0.0.1 is in already banned suubnet range BOOST_CHECK_THROW(r = CallRPC(string("setban 127.0.0.1 add")), runtime_error); BOOST_CHECK_NO_THROW(CallRPC(string("setban 127.0.0.0/24 remove")));; BOOST_CHECK_NO_THROW(r = CallRPC(string("listbanned"))); ar = r.get_array(); BOOST_CHECK_EQUAL(ar.size(), 0); BOOST_CHECK_NO_THROW(r = CallRPC(string("setban 127.0.0.0/255.255.0.0 add"))); BOOST_CHECK_THROW(r = CallRPC(string("setban 127.0.1.1 add")), runtime_error); BOOST_CHECK_NO_THROW(CallRPC(string("clearbanned"))); BOOST_CHECK_NO_THROW(r = CallRPC(string("listbanned"))); ar = r.get_array(); BOOST_CHECK_EQUAL(ar.size(), 0); BOOST_CHECK_THROW(r = CallRPC(string("setban test add")), runtime_error); //invalid IP //IPv6 tests BOOST_CHECK_NO_THROW(r = CallRPC(string("setban FE80:0000:0000:0000:0202:B3FF:FE1E:8329 add"))); BOOST_CHECK_NO_THROW(r = CallRPC(string("listbanned"))); ar = r.get_array(); o1 = ar[0].get_obj(); adr = find_value(o1, "address"); BOOST_CHECK_EQUAL(adr.get_str(), "fe80::202:b3ff:fe1e:8329/128"); BOOST_CHECK_NO_THROW(CallRPC(string("clearbanned"))); BOOST_CHECK_NO_THROW(r = CallRPC(string("setban 2001:db8::/ffff:fffc:0:0:0:0:0:0 add"))); BOOST_CHECK_NO_THROW(r = CallRPC(string("listbanned"))); ar = r.get_array(); o1 = ar[0].get_obj(); adr = find_value(o1, "address"); BOOST_CHECK_EQUAL(adr.get_str(), "2001:db8::/30"); BOOST_CHECK_NO_THROW(CallRPC(string("clearbanned"))); BOOST_CHECK_NO_THROW(r = CallRPC(string("setban 2001:4d48:ac57:400:cacf:e9ff:fe1d:9c63/128 add"))); BOOST_CHECK_NO_THROW(r = CallRPC(string("listbanned"))); ar = r.get_array(); o1 = ar[0].get_obj(); adr = find_value(o1, "address"); BOOST_CHECK_EQUAL(adr.get_str(), "2001:4d48:ac57:400:cacf:e9ff:fe1d:9c63/128"); } BOOST_AUTO_TEST_SUITE_END()
[ "dharshan.rasiah@gmail.com" ]
dharshan.rasiah@gmail.com
79e8f8ca8dea145d905ee6531b7db47f8883d66b
5667daf99e88353f63c7d1241da5f3c62679273a
/Examples_3/Unit_Tests/src/10_PixelProjectedReflections/10_PixelProjectedReflections.cpp
64387b5b025ddde21ba5b719da3211ff732cd4a8
[ "Apache-2.0" ]
permissive
GeneralGDA/The-Forge
f5516ae9fe2e07904061450494d020deebd6da5b
6e70720da6bf2dee53a47094ecef8dae9ccf68a1
refs/heads/master
2020-04-04T15:39:04.735469
2018-11-18T11:33:06
2018-11-18T11:33:06
156,046,068
0
0
null
2018-11-04T03:33:17
2018-11-04T03:33:17
null
UTF-8
C++
false
false
95,207
cpp
/* * * Copyright (c) 2018 Confetti Interactive Inc. * * This file is part of The-Forge * (see https://github.com/ConfettiFX/The-Forge). * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ // Unit Test for testing materials and pbr. //asimp importer #include "../../../../Common_3/Tools/AssimpImporter/AssimpImporter.h" //tiny stl #include "../../../../Common_3/ThirdParty/OpenSource/TinySTL/vector.h" #include "../../../../Common_3/ThirdParty/OpenSource/TinySTL/string.h" //Interfaces #include "../../../../Common_3/OS/Interfaces/ICameraController.h" #include "../../../../Common_3/OS/Interfaces/ILogManager.h" #include "../../../../Common_3/OS/Interfaces/IFileSystem.h" #include "../../../../Common_3/OS/Interfaces/ITimeManager.h" #include "../../../../Middleware_3/UI/AppUI.h" #include "../../../../Common_3/OS/Core/DebugRenderer.h" #include "../../../../Common_3/Renderer/IRenderer.h" #include "../../../../Common_3/Renderer/ResourceLoader.h" #include "../../../../Common_3/OS/Interfaces/IApp.h" //Renderer #include "../../../../Common_3/Renderer/GpuProfiler.h" //Math #include "../../../../Common_3/OS/Math/MathTypes.h" //ui #include "../../../../Middleware_3/UI/AppUI.h" #include "../../../../Common_3/OS/Core/DebugRenderer.h" //Input #include "../../../../Middleware_3/Input/InputSystem.h" #include "../../../../Middleware_3/Input/InputMappings.h" #include "../../../../Common_3/OS/Interfaces/IMemoryManager.h" const char* pszBases[] = { "../../../src/10_PixelProjectedReflections/", // FSR_BinShaders "../../../src/10_PixelProjectedReflections/", // FSR_SrcShaders "", // FSR_BinShaders_Common "", // FSR_SrcShaders_Common "../../../../../Art/Sponza/", // FSR_Textures "../../../../../Art/Sponza/", // FSR_Meshes "../../../UnitTestResources/", // FSR_Builtin_Fonts "../../../src/10_PixelProjectedReflections/", // FSR_GpuConfig "", // FSR_OtherFiles }; LogManager gLogManager; #define MAX_IN_ROW 4 #define TOTAL_SPHERE 16 #define DEFERRED_RT_COUNT 3 #define LOAD_MATERIAL_BALL #define MAX_PLANES 4 #define DegToRad 0.01745329251994329576923690768489f; struct Vertex { float3 mPos; float3 mNormal; float2 mUv; }; // Have a uniform for camera data struct UniformCamData { mat4 mProjectView; vec3 mCamPos; }; // Have a uniform for extended camera data struct UniformExtendedCamData { mat4 mViewMat; mat4 mProjMat; mat4 mViewProjMat; mat4 mInvViewProjMat; vec4 mCameraWorldPos; vec4 mViewPortSize; }; // Have a uniform for PPR properties struct UniformPPRProData { uint renderMode; float useHolePatching; float useExpensiveHolePatching; float useNormalMap; float intensity; float useFadeEffect; float padding01; float padding02; }; // Have a uniform for object data struct UniformObjData { mat4 mWorldMat; float mRoughness = 0.04f; float mMetallic = 0.0f; int pbrMaterials = -1; }; struct Light { vec4 mPos; vec4 mCol; float mRadius; float mIntensity; float _pad0; float _pad1; }; struct UniformLightData { // Used to tell our shaders how many lights are currently present Light mLights[16]; // array of lights seem to be broken so just a single light for now int mCurrAmountOfLights = 0; }; struct DirectionalLight { vec4 mPos; vec4 mCol; //alpha is the intesity vec4 mDir; }; struct UniformDirectionalLightData { // Used to tell our shaders how many lights are currently present DirectionalLight mLights[16]; // array of lights seem to be broken so just a single light for now int mCurrAmountOfDLights = 0; }; struct PlaneInfo { mat4 rotMat; vec4 centerPoint; vec4 size; }; struct UniformPlaneInfoData { PlaneInfo planeInfo[MAX_PLANES]; uint32_t numPlanes; uint32_t pad00; uint32_t pad01; uint32_t pad02; }; enum { SCENE_ONLY = 0, PPR_ONLY = 1, SCENE_WITH_PPR = 2, SCENE_EXCLU_PPR = 3, }; static bool gUseHolePatching = true; static bool gUseExpensiveHolePatching = true; static bool gUseNormalMap = false; static bool gUseFadeEffect = true; static uint32_t gRenderMode = SCENE_WITH_PPR; static uint32_t gPlaneNumber = 1; static float gPlaneSize = 75.0f; static float gRRP_Intensity = 0.2f; const char* pMaterialImageFileNames[] = { "SponzaPBR_Textures/ao.png", "SponzaPBR_Textures/ao.png", "SponzaPBR_Textures/ao.png", "SponzaPBR_Textures/ao.png", "SponzaPBR_Textures/ao.png", //common "SponzaPBR_Textures/ao.png", "SponzaPBR_Textures/Dielectric_metallic.tga", "SponzaPBR_Textures/Metallic_metallic.tga", "SponzaPBR_Textures/gi_flag.png", //Background "SponzaPBR_Textures/Background/Background_Albedo.tga", "SponzaPBR_Textures/Background/Background_Normal.tga", "SponzaPBR_Textures/Background/Background_Roughness.tga", //ChainTexture "SponzaPBR_Textures/ChainTexture/ChainTexture_Albedo.tga", "SponzaPBR_Textures/ChainTexture/ChainTexture_Metallic.tga", "SponzaPBR_Textures/ChainTexture/ChainTexture_Normal.tga", "SponzaPBR_Textures/ChainTexture/ChainTexture_Roughness.tga", //Lion "SponzaPBR_Textures/Lion/Lion_Albedo.tga", "SponzaPBR_Textures/Lion/Lion_Normal.tga", "SponzaPBR_Textures/Lion/Lion_Roughness.tga", //Sponza_Arch "SponzaPBR_Textures/Sponza_Arch/Sponza_Arch_diffuse.tga", "SponzaPBR_Textures/Sponza_Arch/Sponza_Arch_normal.tga", "SponzaPBR_Textures/Sponza_Arch/Sponza_Arch_roughness.tga", //Sponza_Bricks "SponzaPBR_Textures/Sponza_Bricks/Sponza_Bricks_a_Albedo.tga", "SponzaPBR_Textures/Sponza_Bricks/Sponza_Bricks_a_Normal.tga", "SponzaPBR_Textures/Sponza_Bricks/Sponza_Bricks_a_Roughness.tga", //Sponza_Ceiling "SponzaPBR_Textures/Sponza_Ceiling/Sponza_Ceiling_diffuse.tga", "SponzaPBR_Textures/Sponza_Ceiling/Sponza_Ceiling_normal.tga", "SponzaPBR_Textures/Sponza_Ceiling/Sponza_Ceiling_roughness.tga", //Sponza_Column "SponzaPBR_Textures/Sponza_Column/Sponza_Column_a_diffuse.tga", "SponzaPBR_Textures/Sponza_Column/Sponza_Column_a_normal.tga", "SponzaPBR_Textures/Sponza_Column/Sponza_Column_a_roughness.tga", "SponzaPBR_Textures/Sponza_Column/Sponza_Column_b_diffuse.tga", "SponzaPBR_Textures/Sponza_Column/Sponza_Column_b_normal.tga", "SponzaPBR_Textures/Sponza_Column/Sponza_Column_b_roughness.tga", "SponzaPBR_Textures/Sponza_Column/Sponza_Column_c_diffuse.tga", "SponzaPBR_Textures/Sponza_Column/Sponza_Column_c_normal.tga", "SponzaPBR_Textures/Sponza_Column/Sponza_Column_c_roughness.tga", //Sponza_Curtain "SponzaPBR_Textures/Sponza_Curtain/Sponza_Curtain_Blue_diffuse.tga", "SponzaPBR_Textures/Sponza_Curtain/Sponza_Curtain_Blue_normal.tga", "SponzaPBR_Textures/Sponza_Curtain/Sponza_Curtain_Green_diffuse.tga", "SponzaPBR_Textures/Sponza_Curtain/Sponza_Curtain_Green_normal.tga", "SponzaPBR_Textures/Sponza_Curtain/Sponza_Curtain_Red_diffuse.tga", "SponzaPBR_Textures/Sponza_Curtain/Sponza_Curtain_Red_normal.tga", "SponzaPBR_Textures/Sponza_Curtain/Sponza_Curtain_metallic.tga", "SponzaPBR_Textures/Sponza_Curtain/Sponza_Curtain_roughness.tga", //Sponza_Details "SponzaPBR_Textures/Sponza_Details/Sponza_Details_diffuse.tga", "SponzaPBR_Textures/Sponza_Details/Sponza_Details_metallic.tga", "SponzaPBR_Textures/Sponza_Details/Sponza_Details_normal.tga", "SponzaPBR_Textures/Sponza_Details/Sponza_Details_roughness.tga", //Sponza_Fabric "SponzaPBR_Textures/Sponza_Fabric/Sponza_Fabric_Blue_diffuse.tga", "SponzaPBR_Textures/Sponza_Fabric/Sponza_Fabric_Blue_normal.tga", "SponzaPBR_Textures/Sponza_Fabric/Sponza_Fabric_Green_diffuse.tga", "SponzaPBR_Textures/Sponza_Fabric/Sponza_Fabric_Green_normal.tga", "SponzaPBR_Textures/Sponza_Fabric/Sponza_Fabric_metallic.tga", "SponzaPBR_Textures/Sponza_Fabric/Sponza_Fabric_roughness.tga", "SponzaPBR_Textures/Sponza_Fabric/Sponza_Fabric_Red_diffuse.tga", "SponzaPBR_Textures/Sponza_Fabric/Sponza_Fabric_Red_normal.tga", //Sponza_FlagPole "SponzaPBR_Textures/Sponza_FlagPole/Sponza_FlagPole_diffuse.tga", "SponzaPBR_Textures/Sponza_FlagPole/Sponza_FlagPole_normal.tga", "SponzaPBR_Textures/Sponza_FlagPole/Sponza_FlagPole_roughness.tga", //Sponza_Floor "SponzaPBR_Textures/Sponza_Floor/Sponza_Floor_diffuse.tga", "SponzaPBR_Textures/Sponza_Floor/Sponza_Floor_normal.tga", "SponzaPBR_Textures/Sponza_Floor/Sponza_Floor_roughness.tga", //Sponza_Roof "SponzaPBR_Textures/Sponza_Roof/Sponza_Roof_diffuse.tga", "SponzaPBR_Textures/Sponza_Roof/Sponza_Roof_normal.tga", "SponzaPBR_Textures/Sponza_Roof/Sponza_Roof_roughness.tga", //Sponza_Thorn "SponzaPBR_Textures/Sponza_Thorn/Sponza_Thorn_diffuse.tga", "SponzaPBR_Textures/Sponza_Thorn/Sponza_Thorn_normal.tga", "SponzaPBR_Textures/Sponza_Thorn/Sponza_Thorn_roughness.tga", //Vase "SponzaPBR_Textures/Vase/Vase_diffuse.tga", "SponzaPBR_Textures/Vase/Vase_normal.tga", "SponzaPBR_Textures/Vase/Vase_roughness.tga", //VaseHanging "SponzaPBR_Textures/VaseHanging/VaseHanging_diffuse.tga", "SponzaPBR_Textures/VaseHanging/VaseHanging_normal.tga", "SponzaPBR_Textures/VaseHanging/VaseHanging_roughness.tga", //VasePlant "SponzaPBR_Textures/VasePlant/VasePlant_diffuse.tga", "SponzaPBR_Textures/VasePlant/VasePlant_normal.tga", "SponzaPBR_Textures/VasePlant/VasePlant_roughness.tga", //VaseRound "SponzaPBR_Textures/VaseRound/VaseRound_diffuse.tga", "SponzaPBR_Textures/VaseRound/VaseRound_normal.tga", "SponzaPBR_Textures/VaseRound/VaseRound_roughness.tga", "lion/lion_albedo.png", "lion/lion_specular.png", "lion/lion_normal.png", }; // PBR Texture values (these values are mirrored on the shaders). const uint32_t gBRDFIntegrationSize = 512; const uint32_t gSkyboxSize = 1024; const uint32_t gSkyboxMips = 11; const uint32_t gIrradianceSize = 32; const uint32_t gSpecularSize = 128; const uint32_t gSpecularMips = 5; const uint32_t gImageCount = 3; bool gToggleVSync = false; Renderer* pRenderer = NULL; UIApp gAppUI; Queue* pGraphicsQueue = NULL; CmdPool* pCmdPool = NULL; Cmd** ppCmds = NULL; CmdPool* pPreCmdPool = NULL; Cmd** pPrepCmds = NULL; CmdPool* pBrdfCmdPool = NULL; Cmd** pBrdfCmds = NULL; CmdPool* pPPR_ProjectionCmdPool = NULL; Cmd** pPPR_ProjectionCmds = NULL; CmdPool* pPPR_ReflectionCmdPool = NULL; Cmd** pPPR_ReflectionCmds = NULL; SwapChain* pSwapChain = NULL; RenderTarget* pRenderTargetDeferredPass[DEFERRED_RT_COUNT] = { nullptr }; RenderTarget* pSceneBuffer = NULL; RenderTarget* pReflectionBuffer = NULL; RenderTarget* pDepthBuffer = NULL; Fence* pRenderCompleteFences[gImageCount] = { NULL }; Semaphore* pImageAcquiredSemaphore = NULL; Semaphore* pRenderCompleteSemaphores[gImageCount] = { NULL }; Shader* pShaderBRDF = NULL; Pipeline* pPipelineBRDF = NULL; RootSignature* pRootSigBRDF = NULL; Buffer* pSkyboxVertexBuffer = NULL; Shader* pSkyboxShader = NULL; Pipeline* pSkyboxPipeline = NULL; RootSignature* pSkyboxRootSignature = NULL; Shader* pPPR_ProjectionShader = NULL; RootSignature* pPPR_ProjectionRootSignature = NULL; Pipeline* pPPR_ProjectionPipeline = NULL; #ifdef METAL //used to clear compute shader buffer Shader* pClearBufferShader = NULL; RootSignature* pClearBufferRootSignature = NULL; Pipeline* pClearBufferPipeline = NULL; #endif Shader* pPPR_ReflectionShader = NULL; RootSignature* pPPR_ReflectionRootSignature = NULL; Pipeline* pPPR_ReflectionPipeline = NULL; Shader* pPPR_HolePatchingShader = NULL; RootSignature* pPPR_HolePatchingRootSignature = NULL; Pipeline* pPPR_HolePatchingPipeline = NULL; Buffer* pScreenQuadVertexBuffer = NULL; Shader* pShaderGbuffers = NULL; Pipeline* pPipelineGbuffers = NULL; RootSignature* pRootSigGbuffers = NULL; Texture* pSkybox = NULL; Texture* pBRDFIntegrationMap = NULL; Texture* pIrradianceMap = NULL; Texture* pSpecularMap = NULL; Buffer* pIntermediateBuffer = NULL; #define TOTAL_IMGS 84 Texture* pMaterialTextures[TOTAL_IMGS]; tinystl::vector<int> gSponzaTextureIndexforMaterial; //For clearing Intermediate Buffer tinystl::vector<uint32_t> gInitializeVal; #ifdef TARGET_IOS VirtualJoystickUI gVirtualJoystick; #endif UniformObjData pUniformDataMVP; /************************************************************************/ // Vertex buffers for the model /************************************************************************/ //Sponza tinystl::vector<Buffer*> pSponzaVertexBufferPosition; tinystl::vector<Buffer*> pSponzaIndexBuffer; Buffer* pSponzaBuffer; tinystl::vector<int> gSponzaMaterialID; //Lion Buffer* pLionVertexBufferPosition; Buffer* pLionIndexBuffer; Buffer* pLionBuffer; Buffer* pBufferUniformCamera[gImageCount] = { NULL }; UniformCamData pUniformDataCamera; UniformCamData gUniformDataSky; Buffer* pBufferUniformExtendedCamera[gImageCount] = { NULL }; UniformExtendedCamData pUniformDataExtenedCamera; Buffer* pBufferUniformCameraSky[gImageCount] = { NULL }; Buffer* pBufferUniformPPRPro[gImageCount] = { NULL }; UniformPPRProData pUniformPPRProData; Buffer* pBufferUniformLights = NULL; UniformLightData pUniformDataLights; Buffer* pBufferUniformDirectionalLights = NULL; UniformDirectionalLightData pUniformDataDirectionalLights; Buffer* pBufferUniformPlaneInfo[gImageCount] = { NULL }; UniformPlaneInfoData pUniformDataPlaneInfo; Shader* pShaderPostProc = NULL; Pipeline* pPipelinePostProc = NULL; DepthState* pDepth = NULL; RasterizerState* pRasterstateDefault = NULL; Sampler* pSamplerBilinear = NULL; Sampler* pSamplerLinear = NULL; Sampler* pSamplerNearest = NULL; uint32_t gFrameIndex = 0; GpuProfiler* pGpuProfiler = NULL; BlendState* pBlendStateOneZero = nullptr; tinystl::vector<Buffer*> gSphereBuffers; ICameraController* pCameraController = NULL; TextDrawDesc gFrameTimeDraw = TextDrawDesc(0, 0xff00ffff, 18); tinystl::vector<int> gSponzaIndicesArray; tinystl::vector<int> gLionIndicesArray; GuiComponent* pGui; const char* pTextureName[] = { "albedoMap", "normalMap", "metallicMap", "roughnessMap", "aoMap" }; const char* gModel_Sponza = "sponza.obj"; const char* gModel_Lion = "lion.obj"; void transitionRenderTargets() { // Transition render targets to desired state const uint32_t numBarriers = gImageCount + 1; TextureBarrier rtBarriers[numBarriers] = {}; for (uint32_t i = 0; i < gImageCount; ++i) rtBarriers[i] = { pSwapChain->ppSwapchainRenderTargets[i]->pTexture, RESOURCE_STATE_RENDER_TARGET }; rtBarriers[numBarriers - 1] = { pDepthBuffer->pTexture, RESOURCE_STATE_DEPTH_WRITE }; beginCmd(ppCmds[0]); cmdResourceBarrier(ppCmds[0], 0, 0, numBarriers, rtBarriers, false); endCmd(ppCmds[0]); queueSubmit(pGraphicsQueue, 1, &ppCmds[0], pRenderCompleteFences[0], 0, NULL, 0, NULL); waitForFences(pGraphicsQueue, 1, &pRenderCompleteFences[0], false); } // Compute PBR maps (skybox, BRDF Integration Map, Irradiance Map and Specular Map). void computePBRMaps() { // Temporary resources that will be loaded on PBR preprocessing. Texture* pPanoSkybox = NULL; Shader* pPanoToCubeShader = NULL; RootSignature* pPanoToCubeRootSignature = NULL; Pipeline* pPanoToCubePipeline = NULL; Shader* pBRDFIntegrationShader = NULL; RootSignature* pBRDFIntegrationRootSignature = NULL; Pipeline* pBRDFIntegrationPipeline = NULL; Shader* pIrradianceShader = NULL; RootSignature* pIrradianceRootSignature = NULL; Pipeline* pIrradiancePipeline = NULL; Shader* pSpecularShader = NULL; RootSignature* pSpecularRootSignature = NULL; Pipeline* pSpecularPipeline = NULL; Sampler* pSkyboxSampler = NULL; SamplerDesc samplerDesc = { FILTER_LINEAR, FILTER_LINEAR, MIPMAP_MODE_LINEAR, ADDRESS_MODE_REPEAT, ADDRESS_MODE_REPEAT, ADDRESS_MODE_REPEAT, 0, 16 }; addSampler(pRenderer, &samplerDesc, &pSkyboxSampler); // Load the skybox panorama texture. TextureLoadDesc panoDesc = {}; panoDesc.mRoot = FSR_Textures; panoDesc.mUseMipmaps = true; panoDesc.pFilename = "LA_Helipad.hdr"; panoDesc.ppTexture = &pPanoSkybox; addResource(&panoDesc); TextureDesc skyboxImgDesc = {}; skyboxImgDesc.mArraySize = 6; skyboxImgDesc.mDepth = 1; skyboxImgDesc.mFormat = ImageFormat::RGBA32F; skyboxImgDesc.mHeight = gSkyboxSize; skyboxImgDesc.mWidth = gSkyboxSize; skyboxImgDesc.mMipLevels = gSkyboxMips; skyboxImgDesc.mSampleCount = SAMPLE_COUNT_1; skyboxImgDesc.mSrgb = false; skyboxImgDesc.mStartState = RESOURCE_STATE_UNORDERED_ACCESS; skyboxImgDesc.mDescriptors = DESCRIPTOR_TYPE_TEXTURE_CUBE | DESCRIPTOR_TYPE_RW_TEXTURE; skyboxImgDesc.pDebugName = L"skyboxImgBuff"; TextureLoadDesc skyboxLoadDesc = {}; skyboxLoadDesc.pDesc = &skyboxImgDesc; skyboxLoadDesc.ppTexture = &pSkybox; addResource(&skyboxLoadDesc); TextureDesc irrImgDesc = {}; irrImgDesc.mArraySize = 6; irrImgDesc.mDepth = 1; irrImgDesc.mFormat = ImageFormat::RGBA32F; irrImgDesc.mHeight = gIrradianceSize; irrImgDesc.mWidth = gIrradianceSize; irrImgDesc.mMipLevels = 1; irrImgDesc.mSampleCount = SAMPLE_COUNT_1; irrImgDesc.mSrgb = false; irrImgDesc.mStartState = RESOURCE_STATE_UNORDERED_ACCESS; irrImgDesc.mDescriptors = DESCRIPTOR_TYPE_TEXTURE_CUBE | DESCRIPTOR_TYPE_RW_TEXTURE; irrImgDesc.pDebugName = L"irrImgBuff"; TextureLoadDesc irrLoadDesc = {}; irrLoadDesc.pDesc = &irrImgDesc; irrLoadDesc.ppTexture = &pIrradianceMap; addResource(&irrLoadDesc); TextureDesc specImgDesc = {}; specImgDesc.mArraySize = 6; specImgDesc.mDepth = 1; specImgDesc.mFormat = ImageFormat::RGBA32F; specImgDesc.mHeight = gSpecularSize; specImgDesc.mWidth = gSpecularSize; specImgDesc.mMipLevels = gSpecularMips; specImgDesc.mSampleCount = SAMPLE_COUNT_1; specImgDesc.mSrgb = false; specImgDesc.mStartState = RESOURCE_STATE_UNORDERED_ACCESS; specImgDesc.mDescriptors = DESCRIPTOR_TYPE_TEXTURE_CUBE | DESCRIPTOR_TYPE_RW_TEXTURE; specImgDesc.pDebugName = L"specImgBuff"; TextureLoadDesc specImgLoadDesc = {}; specImgLoadDesc.pDesc = &specImgDesc; specImgLoadDesc.ppTexture = &pSpecularMap; addResource(&specImgLoadDesc); // Create empty texture for BRDF integration map. TextureLoadDesc brdfIntegrationLoadDesc = {}; TextureDesc brdfIntegrationDesc = {}; brdfIntegrationDesc.mWidth = gBRDFIntegrationSize; brdfIntegrationDesc.mHeight = gBRDFIntegrationSize; brdfIntegrationDesc.mDepth = 1; brdfIntegrationDesc.mArraySize = 1; brdfIntegrationDesc.mMipLevels = 1; brdfIntegrationDesc.mFormat = ImageFormat::RG32F; brdfIntegrationDesc.mDescriptors = DESCRIPTOR_TYPE_TEXTURE | DESCRIPTOR_TYPE_RW_TEXTURE; brdfIntegrationDesc.mSampleCount = SAMPLE_COUNT_1; brdfIntegrationDesc.mHostVisible = false; brdfIntegrationLoadDesc.pDesc = &brdfIntegrationDesc; brdfIntegrationLoadDesc.ppTexture = &pBRDFIntegrationMap; addResource(&brdfIntegrationLoadDesc); // Load pre-processing shaders. ShaderLoadDesc panoToCubeShaderDesc = {}; panoToCubeShaderDesc.mStages[0] = { "panoToCube.comp", NULL, 0, FSR_SrcShaders }; GPUPresetLevel presetLevel = pRenderer->pActiveGpuSettings->mGpuVendorPreset.mPresetLevel; uint32_t importanceSampleCounts[GPUPresetLevel::GPU_PRESET_COUNT] = { 0, 0, 64, 128, 256, 1024 }; uint32_t importanceSampleCount = importanceSampleCounts[presetLevel]; ShaderMacro importanceSampleMacro = { "IMPORTANCE_SAMPLE_COUNT", tinystl::string::format("%u", importanceSampleCount) }; ShaderLoadDesc brdfIntegrationShaderDesc = {}; brdfIntegrationShaderDesc.mStages[0] = { "BRDFIntegration.comp", &importanceSampleMacro, 1, FSR_SrcShaders }; ShaderLoadDesc irradianceShaderDesc = {}; irradianceShaderDesc.mStages[0] = { "computeIrradianceMap.comp", NULL, 0, FSR_SrcShaders }; ShaderLoadDesc specularShaderDesc = {}; specularShaderDesc.mStages[0] = { "computeSpecularMap.comp", &importanceSampleMacro, 1, FSR_SrcShaders }; addShader(pRenderer, &panoToCubeShaderDesc, &pPanoToCubeShader); addShader(pRenderer, &brdfIntegrationShaderDesc, &pBRDFIntegrationShader); addShader(pRenderer, &irradianceShaderDesc, &pIrradianceShader); addShader(pRenderer, &specularShaderDesc, &pSpecularShader); const char* pStaticSamplerNames[] = { "skyboxSampler" }; RootSignatureDesc panoRootDesc = { &pPanoToCubeShader, 1 }; panoRootDesc.mStaticSamplerCount = 1; panoRootDesc.ppStaticSamplerNames = pStaticSamplerNames; panoRootDesc.ppStaticSamplers = &pSkyboxSampler; RootSignatureDesc brdfRootDesc = { &pBRDFIntegrationShader, 1 }; brdfRootDesc.mStaticSamplerCount = 1; brdfRootDesc.ppStaticSamplerNames = pStaticSamplerNames; brdfRootDesc.ppStaticSamplers = &pSkyboxSampler; RootSignatureDesc irradianceRootDesc = { &pIrradianceShader, 1 }; irradianceRootDesc.mStaticSamplerCount = 1; irradianceRootDesc.ppStaticSamplerNames = pStaticSamplerNames; irradianceRootDesc.ppStaticSamplers = &pSkyboxSampler; RootSignatureDesc specularRootDesc = { &pSpecularShader, 1 }; specularRootDesc.mStaticSamplerCount = 1; specularRootDesc.ppStaticSamplerNames = pStaticSamplerNames; specularRootDesc.ppStaticSamplers = &pSkyboxSampler; addRootSignature(pRenderer, &panoRootDesc, &pPanoToCubeRootSignature); addRootSignature(pRenderer, &brdfRootDesc, &pBRDFIntegrationRootSignature); addRootSignature(pRenderer, &irradianceRootDesc, &pIrradianceRootSignature); addRootSignature(pRenderer, &specularRootDesc, &pSpecularRootSignature); ComputePipelineDesc pipelineSettings = { 0 }; pipelineSettings.pShaderProgram = pPanoToCubeShader; pipelineSettings.pRootSignature = pPanoToCubeRootSignature; addComputePipeline(pRenderer, &pipelineSettings, &pPanoToCubePipeline); pipelineSettings.pShaderProgram = pBRDFIntegrationShader; pipelineSettings.pRootSignature = pBRDFIntegrationRootSignature; addComputePipeline(pRenderer, &pipelineSettings, &pBRDFIntegrationPipeline); pipelineSettings.pShaderProgram = pIrradianceShader; pipelineSettings.pRootSignature = pIrradianceRootSignature; addComputePipeline(pRenderer, &pipelineSettings, &pIrradiancePipeline); pipelineSettings.pShaderProgram = pSpecularShader; pipelineSettings.pRootSignature = pSpecularRootSignature; addComputePipeline(pRenderer, &pipelineSettings, &pSpecularPipeline); // Since this happens on iniatilization, use the first cmd/fence pair available. Cmd* cmd = ppCmds[0]; Fence* pRenderCompleteFence = pRenderCompleteFences[0]; // Compute the BRDF Integration map. beginCmd(cmd); TextureBarrier uavBarriers[4] = { { pSkybox, RESOURCE_STATE_UNORDERED_ACCESS }, { pIrradianceMap, RESOURCE_STATE_UNORDERED_ACCESS }, { pSpecularMap, RESOURCE_STATE_UNORDERED_ACCESS }, { pBRDFIntegrationMap, RESOURCE_STATE_UNORDERED_ACCESS }, }; cmdResourceBarrier(cmd, 0, NULL, 4, uavBarriers, false); cmdBindPipeline(cmd, pBRDFIntegrationPipeline); DescriptorData params[2] = {}; params[0].pName = "dstTexture"; params[0].ppTextures = &pBRDFIntegrationMap; cmdBindDescriptors(cmd, pBRDFIntegrationRootSignature, 1, params); const uint32_t* pThreadGroupSize = pBRDFIntegrationShader->mReflection.mStageReflections[0].mNumThreadsPerGroup; cmdDispatch(cmd, gBRDFIntegrationSize / pThreadGroupSize[0], gBRDFIntegrationSize / pThreadGroupSize[1], pThreadGroupSize[2]); TextureBarrier srvBarrier[1] = { { pBRDFIntegrationMap, RESOURCE_STATE_SHADER_RESOURCE } }; cmdResourceBarrier(cmd, 0, NULL, 1, srvBarrier, true); // Store the panorama texture inside a cubemap. cmdBindPipeline(cmd, pPanoToCubePipeline); params[0].pName = "srcTexture"; params[0].ppTextures = &pPanoSkybox; cmdBindDescriptors(cmd, pPanoToCubeRootSignature, 1, params); struct Data { uint mip; uint textureSize; } data = { 0, gSkyboxSize }; for (int i = 0; i < (int)gSkyboxMips; i++) { data.mip = i; params[0].pName = "RootConstant"; params[0].pRootConstant = &data; params[1].pName = "dstTexture"; params[1].ppTextures = &pSkybox; params[1].mUAVMipSlice = i; cmdBindDescriptors(cmd, pPanoToCubeRootSignature, 2, params); pThreadGroupSize = pPanoToCubeShader->mReflection.mStageReflections[0].mNumThreadsPerGroup; cmdDispatch(cmd, max(1u, (uint32_t)(data.textureSize >> i) / pThreadGroupSize[0]), max(1u, (uint32_t)(data.textureSize >> i) / pThreadGroupSize[1]), 6); } TextureBarrier srvBarriers[1] = { { pSkybox, RESOURCE_STATE_SHADER_RESOURCE } }; cmdResourceBarrier(cmd, 0, NULL, 1, srvBarriers, false); /************************************************************************/ // Compute sky irradiance /************************************************************************/ params[0] = {}; params[1] = {}; cmdBindPipeline(cmd, pIrradiancePipeline); params[0].pName = "srcTexture"; params[0].ppTextures = &pSkybox; params[1].pName = "dstTexture"; params[1].ppTextures = &pIrradianceMap; cmdBindDescriptors(cmd, pIrradianceRootSignature, 2, params); pThreadGroupSize = pIrradianceShader->mReflection.mStageReflections[0].mNumThreadsPerGroup; cmdDispatch(cmd, gIrradianceSize / pThreadGroupSize[0], gIrradianceSize / pThreadGroupSize[1], 6); /************************************************************************/ // Compute specular sky /************************************************************************/ cmdBindPipeline(cmd, pSpecularPipeline); params[0].pName = "srcTexture"; params[0].ppTextures = &pSkybox; cmdBindDescriptors(cmd, pSpecularRootSignature, 1, params); struct PrecomputeSkySpecularData { uint mipSize; float roughness; }; for (int i = 0; i < (int)gSpecularMips; i++) { PrecomputeSkySpecularData data = {}; data.roughness = (float)i / (float)(gSpecularMips - 1); data.mipSize = gSpecularSize >> i; params[0].pName = "RootConstant"; params[0].pRootConstant = &data; params[1].pName = "dstTexture"; params[1].ppTextures = &pSpecularMap; params[1].mUAVMipSlice = i; cmdBindDescriptors(cmd, pSpecularRootSignature, 2, params); pThreadGroupSize = pIrradianceShader->mReflection.mStageReflections[0].mNumThreadsPerGroup; cmdDispatch(cmd, max(1u, (gSpecularSize >> i) / pThreadGroupSize[0]), max(1u, (gSpecularSize >> i) / pThreadGroupSize[1]), 6); } /************************************************************************/ /************************************************************************/ TextureBarrier srvBarriers2[2] = { { pIrradianceMap, RESOURCE_STATE_SHADER_RESOURCE }, { pSpecularMap, RESOURCE_STATE_SHADER_RESOURCE } }; cmdResourceBarrier(cmd, 0, NULL, 2, srvBarriers2, false); endCmd(cmd); queueSubmit(pGraphicsQueue, 1, &cmd, pRenderCompleteFence, 0, 0, 0, 0); waitForFences(pGraphicsQueue, 1, &pRenderCompleteFence, false); // Remove temporary resources. removePipeline(pRenderer, pSpecularPipeline); removeRootSignature(pRenderer, pSpecularRootSignature); removeShader(pRenderer, pSpecularShader); removePipeline(pRenderer, pIrradiancePipeline); removeRootSignature(pRenderer, pIrradianceRootSignature); removeShader(pRenderer, pIrradianceShader); removePipeline(pRenderer, pBRDFIntegrationPipeline); removeRootSignature(pRenderer, pBRDFIntegrationRootSignature); removeShader(pRenderer, pBRDFIntegrationShader); removePipeline(pRenderer, pPanoToCubePipeline); removeRootSignature(pRenderer, pPanoToCubeRootSignature); removeShader(pRenderer, pPanoToCubeShader); removeResource(pPanoSkybox); removeSampler(pRenderer, pSkyboxSampler); } void assignSponzaTextures(); //loadModels bool loadModels() { //Load Sponza Model sponza; tinystl::string sceneFullPath = FileSystem::FixPath(gModel_Sponza, FSRoot::FSR_Meshes); if (!AssimpImporter::ImportModel(sceneFullPath.c_str(), &sponza)) { ErrorMsg("Failed to load %s", FileSystem::GetFileNameAndExtension(sceneFullPath).c_str()); return false; } size_t sponza_meshCount = sponza.mMeshArray.size(); size_t sponza_matCount = sponza.mMaterialList.size(); for (size_t i = 0; i < sponza_meshCount; i++) { Mesh subMesh = sponza.mMeshArray[i]; gSponzaMaterialID.push_back(subMesh.mMaterialId); size_t size_Sponza = subMesh.mIndices.size(); tinystl::vector<Vertex> sponzaVertices; tinystl::vector<uint> sponzaIndices; size_t vertexSize = subMesh.mPositions.size(); for (size_t j = 0; j < vertexSize; j++) { Vertex toAdd = { subMesh.mPositions[j],subMesh.mNormals[j], subMesh.mUvs[j] }; sponzaVertices.push_back(toAdd); } for (size_t j = 0; j < size_Sponza; j++) { sponzaIndices.push_back(subMesh.mIndices[j]); } // Vertex position buffer for the scene BufferLoadDesc vbPosDesc_Sponza = {}; vbPosDesc_Sponza.mDesc.mDescriptors = DESCRIPTOR_TYPE_VERTEX_BUFFER; vbPosDesc_Sponza.mDesc.mMemoryUsage = RESOURCE_MEMORY_USAGE_GPU_ONLY; vbPosDesc_Sponza.mDesc.mVertexStride = sizeof(Vertex); vbPosDesc_Sponza.mDesc.mSize = sponzaVertices.size() * vbPosDesc_Sponza.mDesc.mVertexStride; vbPosDesc_Sponza.pData = sponzaVertices.data(); Buffer* localBuffer = NULL; vbPosDesc_Sponza.ppBuffer = &localBuffer; vbPosDesc_Sponza.mDesc.pDebugName = L"Vertex Position Buffer Desc for Sponza"; addResource(&vbPosDesc_Sponza); pSponzaVertexBufferPosition.push_back(localBuffer); // Index buffer for the scene BufferLoadDesc ibDesc_Sponza = {}; ibDesc_Sponza.mDesc.mDescriptors = DESCRIPTOR_TYPE_INDEX_BUFFER; ibDesc_Sponza.mDesc.mMemoryUsage = RESOURCE_MEMORY_USAGE_GPU_ONLY; ibDesc_Sponza.mDesc.mIndexType = INDEX_TYPE_UINT32; ibDesc_Sponza.mDesc.mSize = sizeof(uint32_t) * (uint32_t)sponzaIndices.size(); ibDesc_Sponza.pData = sponzaIndices.data(); gSponzaIndicesArray.push_back((int)sponzaIndices.size()); Buffer* localIndexBuffer = NULL; ibDesc_Sponza.ppBuffer = &localIndexBuffer; ibDesc_Sponza.mDesc.pDebugName = L"Index Buffer Desc for Sponza"; addResource(&ibDesc_Sponza); pSponzaIndexBuffer.push_back(localIndexBuffer); } Model lion; sceneFullPath = FileSystem::FixPath(gModel_Lion, FSRoot::FSR_Meshes); if (!AssimpImporter::ImportModel(sceneFullPath.c_str(), &lion)) { ErrorMsg("Failed to load %s", FileSystem::GetFileNameAndExtension(sceneFullPath).c_str()); return false; } size_t lion_meshCount = lion.mMeshArray.size(); size_t lion_matCount = lion.mMaterialList.size(); Mesh subMesh = lion.mMeshArray[0]; size_t size_Lion = subMesh.mIndices.size(); int vertexSize = (int)subMesh.mPositions.size(); tinystl::vector<Vertex> lionVertices; tinystl::vector<uint> lionIndices; for (int i = 0; i < vertexSize; i++) { Vertex toAdd = { subMesh.mPositions[i],subMesh.mNormals[i], subMesh.mUvs[i] }; lionVertices.push_back(toAdd); } for (int i = 0; i < size_Lion; i++) { lionIndices.push_back(subMesh.mIndices[i]); } // Vertex position buffer for the scene BufferLoadDesc vbPosDesc_Lion = {}; vbPosDesc_Lion.mDesc.mDescriptors = DESCRIPTOR_TYPE_VERTEX_BUFFER; vbPosDesc_Lion.mDesc.mMemoryUsage = RESOURCE_MEMORY_USAGE_GPU_ONLY; vbPosDesc_Lion.mDesc.mVertexStride = sizeof(Vertex); vbPosDesc_Lion.mDesc.mSize = lionVertices.size() * vbPosDesc_Lion.mDesc.mVertexStride; vbPosDesc_Lion.pData = lionVertices.data(); vbPosDesc_Lion.ppBuffer = &pLionVertexBufferPosition; vbPosDesc_Lion.mDesc.pDebugName = L"Vertex Position Buffer Desc for Lion"; addResource(&vbPosDesc_Lion); // Index buffer for the scene BufferLoadDesc ibDesc_Lion = {}; ibDesc_Lion.mDesc.mDescriptors = DESCRIPTOR_TYPE_INDEX_BUFFER; ibDesc_Lion.mDesc.mMemoryUsage = RESOURCE_MEMORY_USAGE_GPU_ONLY; ibDesc_Lion.mDesc.mIndexType = INDEX_TYPE_UINT32; ibDesc_Lion.mDesc.mSize = sizeof(uint32_t) * (uint32_t)lionIndices.size(); ibDesc_Lion.pData = lionIndices.data(); gLionIndicesArray.push_back((int)lionIndices.size()); ibDesc_Lion.ppBuffer = &pLionIndexBuffer; ibDesc_Lion.mDesc.pDebugName = L"Index Buffer Desc for Lion"; addResource(&ibDesc_Lion); //assinged right textures for each mesh assignSponzaTextures(); return true; } class MaterialPlayground : public IApp { public: bool Init() { RendererDesc settings = { 0 }; initRenderer(GetName(), &settings, &pRenderer); //check for init success if (!pRenderer) return false; QueueDesc queueDesc = {}; queueDesc.mType = CMD_POOL_DIRECT; addQueue(pRenderer, &queueDesc, &pGraphicsQueue); // Create command pool and create a cmd buffer for each swapchain image addCmdPool(pRenderer, pGraphicsQueue, false, &pCmdPool); addCmd_n(pCmdPool, false, gImageCount, &ppCmds); addCmdPool(pRenderer, pGraphicsQueue, false, &pPreCmdPool); addCmd_n(pPreCmdPool, false, gImageCount, &pPrepCmds); addCmdPool(pRenderer, pGraphicsQueue, false, &pBrdfCmdPool); addCmd_n(pBrdfCmdPool, false, gImageCount, &pBrdfCmds); addCmdPool(pRenderer, pGraphicsQueue, false, &pPPR_ProjectionCmdPool); addCmd_n(pPPR_ProjectionCmdPool, false, gImageCount, &pPPR_ProjectionCmds); addCmdPool(pRenderer, pGraphicsQueue, false, &pPPR_ReflectionCmdPool); addCmd_n(pPPR_ReflectionCmdPool, false, gImageCount, &pPPR_ReflectionCmds); for (uint32_t i = 0; i < gImageCount; ++i) { addFence(pRenderer, &pRenderCompleteFences[i]); addSemaphore(pRenderer, &pRenderCompleteSemaphores[i]); } addSemaphore(pRenderer, &pImageAcquiredSemaphore); initResourceLoaderInterface(pRenderer, DEFAULT_MEMORY_BUDGET, true); initDebugRendererInterface(pRenderer, "TitilliumText/TitilliumText-Bold.otf", FSR_Builtin_Fonts); //tinystl::vector<Image> toLoad(TOTAL_IMGS); //adding material textures for (int i = 0; i <TOTAL_IMGS; ++i) { TextureLoadDesc textureDesc = {}; textureDesc.mRoot = FSR_Textures; textureDesc.mUseMipmaps = true; textureDesc.pFilename = pMaterialImageFileNames[i]; textureDesc.ppTexture = &pMaterialTextures[i]; addResource(&textureDesc, true); } #ifdef TARGET_IOS if (!gVirtualJoystick.Init(pRenderer, "circlepad.png", FSR_Textures)) return false; #endif addGpuProfiler(pRenderer, pGraphicsQueue, &pGpuProfiler); computePBRMaps(); SamplerDesc samplerDesc = { FILTER_LINEAR, FILTER_LINEAR, MIPMAP_MODE_LINEAR, ADDRESS_MODE_REPEAT, ADDRESS_MODE_REPEAT, ADDRESS_MODE_REPEAT }; addSampler(pRenderer, &samplerDesc, &pSamplerBilinear); SamplerDesc nearstSamplerDesc = { FILTER_NEAREST, FILTER_NEAREST, MIPMAP_MODE_NEAREST, ADDRESS_MODE_REPEAT, ADDRESS_MODE_REPEAT, ADDRESS_MODE_REPEAT }; addSampler(pRenderer, &nearstSamplerDesc, &pSamplerNearest); // GBuffer ShaderLoadDesc gBuffersShaderDesc = {}; gBuffersShaderDesc.mStages[0] = { "fillGbuffers.vert", NULL, 0, FSR_SrcShaders }; #ifndef TARGET_IOS gBuffersShaderDesc.mStages[1] = { "fillGbuffers.frag", NULL, 0, FSR_SrcShaders }; #else gBuffersShaderDesc.mStages[1] = { "fillGbuffers_iOS.frag", NULL, 0, FSR_SrcShaders }; #endif addShader(pRenderer, &gBuffersShaderDesc, &pShaderGbuffers); const char* pStaticSamplerNames[] = { "defaultSampler" }; Sampler* pStaticSamplers[] = { pSamplerBilinear }; RootSignatureDesc gBuffersRootDesc = { &pShaderGbuffers, 1 }; gBuffersRootDesc.mStaticSamplerCount = 1; gBuffersRootDesc.ppStaticSamplerNames = pStaticSamplerNames; gBuffersRootDesc.ppStaticSamplers = pStaticSamplers; #ifndef TARGET_IOS gBuffersRootDesc.mMaxBindlessTextures = TOTAL_IMGS; #endif addRootSignature(pRenderer, &gBuffersRootDesc, &pRootSigGbuffers); ShaderLoadDesc skyboxShaderDesc = {}; skyboxShaderDesc.mStages[0] = { "skybox.vert", NULL, 0, FSR_SrcShaders }; skyboxShaderDesc.mStages[1] = { "skybox.frag", NULL, 0, FSR_SrcShaders }; addShader(pRenderer, &skyboxShaderDesc, &pSkyboxShader); const char* pSkyboxamplerName = "skyboxSampler"; RootSignatureDesc skyboxRootDesc = { &pSkyboxShader, 1 }; skyboxRootDesc.mStaticSamplerCount = 1; skyboxRootDesc.ppStaticSamplerNames = &pSkyboxamplerName; skyboxRootDesc.ppStaticSamplers = &pSamplerBilinear; addRootSignature(pRenderer, &skyboxRootDesc, &pSkyboxRootSignature); //BRDF ShaderLoadDesc brdfRenderSceneShaderDesc = {}; brdfRenderSceneShaderDesc.mStages[0] = { "renderSceneBRDF.vert", NULL, 0, FSR_SrcShaders }; brdfRenderSceneShaderDesc.mStages[1] = { "renderSceneBRDF.frag", NULL, 0, FSR_SrcShaders }; addShader(pRenderer, &brdfRenderSceneShaderDesc, &pShaderBRDF); const char* pStaticSampler2Names[] = { "envSampler", "defaultSampler" }; Sampler* pStaticSamplers2[] = { pSamplerBilinear, pSamplerNearest }; RootSignatureDesc brdfRootDesc = { &pShaderBRDF, 1 }; brdfRootDesc.mStaticSamplerCount = 2; brdfRootDesc.ppStaticSamplerNames = pStaticSampler2Names; brdfRootDesc.ppStaticSamplers = pStaticSamplers2; addRootSignature(pRenderer, &brdfRootDesc, &pRootSigBRDF); //PPR_Projection ShaderLoadDesc PPR_ProjectionShaderDesc = {}; PPR_ProjectionShaderDesc.mStages[0] = { "PPR_Projection.comp", NULL, 0, FSR_SrcShaders }; addShader(pRenderer, &PPR_ProjectionShaderDesc, &pPPR_ProjectionShader); RootSignatureDesc PPR_PRootDesc = { &pPPR_ProjectionShader, 1 }; addRootSignature(pRenderer, &PPR_PRootDesc, &pPPR_ProjectionRootSignature); #ifdef METAL //temporary fix on AMD //PPR_Projection ShaderLoadDesc ClearBufferShaderDesc = {}; ClearBufferShaderDesc.mStages[0] = { "ClearBuffer.comp", NULL, 0, FSR_SrcShaders }; addShader(pRenderer, &ClearBufferShaderDesc, &pClearBufferShader); RootSignatureDesc PClearBufferRootDesc = { &pClearBufferShader, 1 }; addRootSignature(pRenderer, &PClearBufferRootDesc, &pClearBufferRootSignature); #endif //PPR_Reflection ShaderLoadDesc PPR_ReflectionShaderDesc = {}; PPR_ReflectionShaderDesc.mStages[0] = { "PPR_Reflection.vert", NULL, 0, FSR_SrcShaders }; PPR_ReflectionShaderDesc.mStages[1] = { "PPR_Reflection.frag", NULL, 0, FSR_SrcShaders }; addShader(pRenderer, &PPR_ReflectionShaderDesc, &pPPR_ReflectionShader); RootSignatureDesc PPR_RRootDesc = { &pPPR_ReflectionShader, 1 }; PPR_RRootDesc.mStaticSamplerCount = 1; PPR_RRootDesc.ppStaticSamplerNames = pStaticSamplerNames; PPR_RRootDesc.ppStaticSamplers = pStaticSamplers; addRootSignature(pRenderer, &PPR_RRootDesc, &pPPR_ReflectionRootSignature); //PPR_HolePatching ShaderLoadDesc PPR_HolePatchingShaderDesc = {}; PPR_HolePatchingShaderDesc.mStages[0] = { "PPR_Holepatching.vert", NULL, 0, FSR_SrcShaders }; PPR_HolePatchingShaderDesc.mStages[1] = { "PPR_Holepatching.frag", NULL, 0, FSR_SrcShaders }; addShader(pRenderer, &PPR_HolePatchingShaderDesc, &pPPR_HolePatchingShader); const char* pStaticSamplerforHolePatchingNames[] = { "nearestSampler", "bilinearSampler" }; Sampler* pStaticSamplersforHolePatching[] = { pSamplerNearest, pSamplerBilinear }; RootSignatureDesc PPR_HolePatchingRootDesc = { &pPPR_HolePatchingShader, 1 }; PPR_HolePatchingRootDesc.mStaticSamplerCount = 2; PPR_HolePatchingRootDesc.ppStaticSamplerNames = pStaticSamplerforHolePatchingNames; PPR_HolePatchingRootDesc.ppStaticSamplers = pStaticSamplersforHolePatching; addRootSignature(pRenderer, &PPR_HolePatchingRootDesc, &pPPR_HolePatchingRootSignature); // Create depth state and rasterizer state DepthStateDesc depthStateDesc = {}; depthStateDesc.mDepthTest = true; depthStateDesc.mDepthWrite = true; depthStateDesc.mDepthFunc = CMP_LEQUAL; addDepthState(pRenderer, &depthStateDesc, &pDepth); RasterizerStateDesc rasterizerStateDesc = {}; rasterizerStateDesc.mCullMode = CULL_MODE_NONE; addRasterizerState(pRenderer, &rasterizerStateDesc, &pRasterstateDefault); if (!loadModels()) { finishResourceLoading(); return false; } BufferLoadDesc sponza_buffDesc = {}; sponza_buffDesc.mDesc.mDescriptors = DESCRIPTOR_TYPE_UNIFORM_BUFFER; sponza_buffDesc.mDesc.mMemoryUsage = RESOURCE_MEMORY_USAGE_CPU_TO_GPU; sponza_buffDesc.mDesc.mSize = sizeof(UniformObjData); sponza_buffDesc.mDesc.mFlags = BUFFER_CREATION_FLAG_PERSISTENT_MAP_BIT; sponza_buffDesc.pData = NULL; sponza_buffDesc.ppBuffer = &pSponzaBuffer; addResource(&sponza_buffDesc); BufferLoadDesc lion_buffDesc = {}; lion_buffDesc.mDesc.mDescriptors = DESCRIPTOR_TYPE_UNIFORM_BUFFER; lion_buffDesc.mDesc.mMemoryUsage = RESOURCE_MEMORY_USAGE_CPU_TO_GPU; lion_buffDesc.mDesc.mSize = sizeof(UniformObjData); lion_buffDesc.mDesc.mFlags = BUFFER_CREATION_FLAG_PERSISTENT_MAP_BIT; lion_buffDesc.pData = NULL; lion_buffDesc.ppBuffer = &pLionBuffer; addResource(&lion_buffDesc); //Generate sky box vertex buffer float skyBoxPoints[] = { 0.5f, -0.5f, -0.5f,1.0f, // -z -0.5f, -0.5f, -0.5f,1.0f, -0.5f, 0.5f, -0.5f,1.0f, -0.5f, 0.5f, -0.5f,1.0f, 0.5f, 0.5f, -0.5f,1.0f, 0.5f, -0.5f, -0.5f,1.0f, -0.5f, -0.5f, 0.5f,1.0f, //-x -0.5f, -0.5f, -0.5f,1.0f, -0.5f, 0.5f, -0.5f,1.0f, -0.5f, 0.5f, -0.5f,1.0f, -0.5f, 0.5f, 0.5f,1.0f, -0.5f, -0.5f, 0.5f,1.0f, 0.5f, -0.5f, -0.5f,1.0f, //+x 0.5f, -0.5f, 0.5f,1.0f, 0.5f, 0.5f, 0.5f,1.0f, 0.5f, 0.5f, 0.5f,1.0f, 0.5f, 0.5f, -0.5f,1.0f, 0.5f, -0.5f, -0.5f,1.0f, -0.5f, -0.5f, 0.5f,1.0f, // +z -0.5f, 0.5f, 0.5f,1.0f, 0.5f, 0.5f, 0.5f,1.0f, 0.5f, 0.5f, 0.5f,1.0f, 0.5f, -0.5f, 0.5f,1.0f, -0.5f, -0.5f, 0.5f,1.0f, -0.5f, 0.5f, -0.5f, 1.0f, //+y 0.5f, 0.5f, -0.5f,1.0f, 0.5f, 0.5f, 0.5f,1.0f, 0.5f, 0.5f, 0.5f,1.0f, -0.5f, 0.5f, 0.5f,1.0f, -0.5f, 0.5f, -0.5f,1.0f, 0.5f, -0.5f, 0.5f, 1.0f, //-y 0.5f, -0.5f, -0.5f,1.0f, -0.5f, -0.5f, -0.5f,1.0f, -0.5f, -0.5f, -0.5f,1.0f, -0.5f, -0.5f, 0.5f,1.0f, 0.5f, -0.5f, 0.5f,1.0f, }; uint64_t skyBoxDataSize = 4 * 6 * 6 * sizeof(float); BufferLoadDesc skyboxVbDesc = {}; skyboxVbDesc.mDesc.mDescriptors = DESCRIPTOR_TYPE_VERTEX_BUFFER; skyboxVbDesc.mDesc.mMemoryUsage = RESOURCE_MEMORY_USAGE_GPU_ONLY; skyboxVbDesc.mDesc.mSize = skyBoxDataSize; skyboxVbDesc.mDesc.mVertexStride = sizeof(float) * 4; skyboxVbDesc.pData = skyBoxPoints; skyboxVbDesc.ppBuffer = &pSkyboxVertexBuffer; addResource(&skyboxVbDesc); float screenQuadPoints[] = { -1.0f, 3.0f, 0.5f, 0.0f, -1.0f, -1.0f, -1.0f, 0.5f, 0.0f, 1.0f, 3.0f, -1.0f, 0.5f, 2.0f, 1.0f, }; uint64_t screenQuadDataSize = 5 * 3 * sizeof(float); BufferLoadDesc screenQuadVbDesc = {}; screenQuadVbDesc.mDesc.mDescriptors = DESCRIPTOR_TYPE_VERTEX_BUFFER; screenQuadVbDesc.mDesc.mMemoryUsage = RESOURCE_MEMORY_USAGE_GPU_ONLY; screenQuadVbDesc.mDesc.mSize = screenQuadDataSize; screenQuadVbDesc.mDesc.mVertexStride = sizeof(float) * 5; screenQuadVbDesc.pData = screenQuadPoints; screenQuadVbDesc.ppBuffer = &pScreenQuadVertexBuffer; addResource(&screenQuadVbDesc); // Uniform buffer for camera data BufferLoadDesc ubCamDesc = {}; ubCamDesc.mDesc.mDescriptors = DESCRIPTOR_TYPE_UNIFORM_BUFFER; ubCamDesc.mDesc.mMemoryUsage = RESOURCE_MEMORY_USAGE_CPU_TO_GPU; ubCamDesc.mDesc.mSize = sizeof(UniformCamData); ubCamDesc.mDesc.mFlags = BUFFER_CREATION_FLAG_PERSISTENT_MAP_BIT; ubCamDesc.pData = NULL; for (uint32_t i = 0; i < gImageCount; ++i) { ubCamDesc.ppBuffer = &pBufferUniformCamera[i]; addResource(&ubCamDesc); ubCamDesc.ppBuffer = &pBufferUniformCameraSky[i]; addResource(&ubCamDesc); } //temporary fix Needed on AMD for memory type otherwise we have issues. // Uniform buffer for extended camera data BufferLoadDesc ubECamDesc = {}; ubECamDesc.mDesc.mDescriptors = DESCRIPTOR_TYPE_UNIFORM_BUFFER; ubECamDesc.mDesc.mMemoryUsage = RESOURCE_MEMORY_USAGE_GPU_ONLY; ubECamDesc.mDesc.mSize = sizeof(UniformExtendedCamData); ubECamDesc.mDesc.mFlags = BUFFER_CREATION_FLAG_OWN_MEMORY_BIT | BUFFER_CREATION_FLAG_PERSISTENT_MAP_BIT; ubECamDesc.pData = NULL; for (uint32_t i = 0; i < gImageCount; ++i) { ubECamDesc.ppBuffer = &pBufferUniformExtendedCamera[i]; addResource(&ubECamDesc); } // Uniform buffer for PPR's properties BufferLoadDesc ubPPR_ProDesc = {}; ubPPR_ProDesc.mDesc.mDescriptors = DESCRIPTOR_TYPE_UNIFORM_BUFFER; ubPPR_ProDesc.mDesc.mMemoryUsage = RESOURCE_MEMORY_USAGE_CPU_TO_GPU; ubPPR_ProDesc.mDesc.mSize = sizeof(UniformPPRProData); ubPPR_ProDesc.mDesc.mFlags = BUFFER_CREATION_FLAG_PERSISTENT_MAP_BIT; ubPPR_ProDesc.pData = NULL; for (uint32_t i = 0; i < gImageCount; ++i) { ubPPR_ProDesc.ppBuffer = &pBufferUniformPPRPro[i]; addResource(&ubPPR_ProDesc); } // Uniform buffer for light data BufferLoadDesc ubLightsDesc = {}; ubLightsDesc.mDesc.mDescriptors = DESCRIPTOR_TYPE_UNIFORM_BUFFER; ubLightsDesc.mDesc.mMemoryUsage = RESOURCE_MEMORY_USAGE_CPU_TO_GPU; ubLightsDesc.mDesc.mSize = sizeof(UniformLightData); ubLightsDesc.mDesc.mFlags = BUFFER_CREATION_FLAG_PERSISTENT_MAP_BIT; ubLightsDesc.pData = NULL; ubLightsDesc.ppBuffer = &pBufferUniformLights; addResource(&ubLightsDesc); // Uniform buffer for DirectionalLight data BufferLoadDesc ubDLightsDesc = {}; ubDLightsDesc.mDesc.mDescriptors = DESCRIPTOR_TYPE_UNIFORM_BUFFER; ubDLightsDesc.mDesc.mMemoryUsage = RESOURCE_MEMORY_USAGE_CPU_TO_GPU; ubDLightsDesc.mDesc.mSize = sizeof(UniformDirectionalLightData); ubDLightsDesc.mDesc.mFlags = BUFFER_CREATION_FLAG_PERSISTENT_MAP_BIT; ubDLightsDesc.pData = NULL; ubDLightsDesc.ppBuffer = &pBufferUniformDirectionalLights; addResource(&ubDLightsDesc); // Uniform buffer for extended camera data BufferLoadDesc ubPlaneInfoDesc = {}; ubPlaneInfoDesc.mDesc.mDescriptors = DESCRIPTOR_TYPE_UNIFORM_BUFFER; ubPlaneInfoDesc.mDesc.mMemoryUsage = RESOURCE_MEMORY_USAGE_CPU_TO_GPU; ubPlaneInfoDesc.mDesc.mSize = sizeof(UniformPlaneInfoData); ubPlaneInfoDesc.mDesc.mFlags = BUFFER_CREATION_FLAG_PERSISTENT_MAP_BIT; ubPlaneInfoDesc.pData = NULL; for (uint32_t i = 0; i < gImageCount; ++i) { ubPlaneInfoDesc.ppBuffer = &pBufferUniformPlaneInfo[i]; addResource(&ubPlaneInfoDesc); } finishResourceLoading(); // prepare resources // Update the uniform buffer for the objects mat4 sponza_modelmat = mat4::translation(vec3(0.0f, -6.0f, 0.0f)) * mat4::scale(vec3(0.02f, 0.02f, 0.02f)); pUniformDataMVP.mWorldMat = sponza_modelmat; pUniformDataMVP.mMetallic = 0; pUniformDataMVP.mRoughness = 0.5f; pUniformDataMVP.pbrMaterials = 1; BufferUpdateDesc sponza_objBuffUpdateDesc = { pSponzaBuffer, &pUniformDataMVP }; updateResource(&sponza_objBuffUpdateDesc); // Update the uniform buffer for the objects mat4 lion_modelmat = mat4::translation(vec3(0.0f, -6.0f, 1.0f)) * mat4::rotationY(-1.5708f) * mat4::scale(vec3(0.2f, 0.2f, 0.2f)); pUniformDataMVP.mWorldMat = lion_modelmat; pUniformDataMVP.mMetallic = 0; pUniformDataMVP.mRoughness = 0.5f; pUniformDataMVP.pbrMaterials = 1; BufferUpdateDesc lion_objBuffUpdateDesc = { pLionBuffer, &pUniformDataMVP }; updateResource(&lion_objBuffUpdateDesc); // Add light to scene //Point light Light light; light.mCol = vec4(1.0f, 0.5f, 0.1f, 0.0f); light.mPos = vec4(-12.5f, -3.5f, 4.7f, 0.0f); light.mRadius = 10.0f; light.mIntensity = 400.0f; pUniformDataLights.mLights[0] = light; light.mCol = vec4(1.0f, 0.5f, 0.1f, 0.0f); light.mPos = vec4(-12.5f, -3.5f, -3.7f, 0.0f); light.mRadius = 10.0f; light.mIntensity = 400.0f; pUniformDataLights.mLights[1] = light; // Add light to scene light.mCol = vec4(1.0f, 0.5f, 0.1f, 0.0f); light.mPos = vec4(9.5f, -3.5f, 4.7f, 0.0f); light.mRadius = 10.0f; light.mIntensity = 400.0f; pUniformDataLights.mLights[2] = light; light.mCol = vec4(1.0f, 0.5f, 0.1f, 0.0f); light.mPos = vec4(9.5f, -3.5f, -3.7f, 0.0f); light.mRadius = 10.0f; light.mIntensity = 400.0f; pUniformDataLights.mLights[3] = light; pUniformDataLights.mCurrAmountOfLights = 4; BufferUpdateDesc lightBuffUpdateDesc = { pBufferUniformLights, &pUniformDataLights }; updateResource(&lightBuffUpdateDesc); //Directional light DirectionalLight dLight; dLight.mCol = vec4(1.0f, 1.0f, 1.0f, 5.0f); dLight.mPos = vec4(0.0f, 0.0f, 0.0f, 0.0f); dLight.mDir = vec4(-1.0f, -1.5f, 1.0f, 0.0f); pUniformDataDirectionalLights.mLights[0] = dLight; pUniformDataDirectionalLights.mCurrAmountOfDLights = 1; BufferUpdateDesc directionalLightBuffUpdateDesc = { pBufferUniformDirectionalLights, &pUniformDataDirectionalLights }; updateResource(&directionalLightBuffUpdateDesc); // Create UI if (!gAppUI.Init(pRenderer)) return false; gAppUI.LoadFont("TitilliumText/TitilliumText-Bold.otf", FSR_Builtin_Fonts); GuiDesc guiDesc = {}; guiDesc.mStartSize = vec2(370.0f, 320.0f); guiDesc.mStartPosition = vec2(0.0f, guiDesc.mStartSize.getY()); pGui = gAppUI.AddGuiComponent("Pixel-Projected Reflections", &guiDesc); static const uint32_t enumRenderModes[] = { SCENE_ONLY, PPR_ONLY, SCENE_WITH_PPR, SCENE_EXCLU_PPR, 0 }; static const char* enumRenderModeNames[] = { "Render Scene Only", "Render PPR Only", "Render Scene with PPR ", "Render Scene with exclusive PPR", NULL }; #if !defined(TARGET_IOS) && !defined(_DURANGO) pGui->AddWidget(CheckboxWidget("Toggle VSync", &gToggleVSync)); #endif pGui->AddWidget(DropdownWidget("Render Mode", &gRenderMode, enumRenderModeNames, enumRenderModes, 4)); pGui->AddWidget(CheckboxWidget("Use Holepatching", &gUseHolePatching)); pGui->AddWidget(CheckboxWidget("Use Expensive Holepatching", &gUseExpensiveHolePatching)); //pGui->AddWidget(CheckboxWidget("Use Normalmap", &gUseNormalMap)); pGui->AddWidget(CheckboxWidget("Use Fade Effect", &gUseFadeEffect)); pGui->AddWidget(SliderFloatWidget("Intensity of PPR", &gRRP_Intensity, 0.0f, 1.0f)); pGui->AddWidget(SliderUintWidget("Number of Planes", &gPlaneNumber, 1, 4)); pGui->AddWidget(SliderFloatWidget("Size of Main Plane", &gPlaneSize, 5.0f, 100.0f)); CameraMotionParameters camParameters{ 100.0f, 150.0f, 300.0f }; vec3 camPos{ 20.0f, -2.0f, 0.9f }; vec3 lookat{ 0.0f, -2.0f, 0.9f }; pCameraController = createFpsCameraController(camPos, lookat); requestMouseCapture(true); pCameraController->setMotionParameters(camParameters); InputSystem::RegisterInputEvent(cameraInputEvent); return true; } void Exit() { waitForFences(pGraphicsQueue, 1, &pRenderCompleteFences[gFrameIndex], true); destroyCameraController(pCameraController); removeDebugRendererInterface(); for (uint32_t i = 0; i < gImageCount; ++i) { removeFence(pRenderer, pRenderCompleteFences[i]); removeSemaphore(pRenderer, pRenderCompleteSemaphores[i]); } removeSemaphore(pRenderer, pImageAcquiredSemaphore); removeResource(pSpecularMap); removeResource(pIrradianceMap); removeResource(pSkybox); removeResource(pBRDFIntegrationMap); #ifdef TARGET_IOS gVirtualJoystick.Exit(); #endif removeGpuProfiler(pRenderer, pGpuProfiler); for (uint32_t i = 0; i < gImageCount; ++i) { removeResource(pBufferUniformPlaneInfo[i]); removeResource(pBufferUniformPPRPro[i]); removeResource(pBufferUniformExtendedCamera[i]); removeResource(pBufferUniformCameraSky[i]); removeResource(pBufferUniformCamera[i]); } removeResource(pBufferUniformLights); removeResource(pBufferUniformDirectionalLights); removeResource(pSkyboxVertexBuffer); removeResource(pScreenQuadVertexBuffer); removeResource(pSponzaBuffer); removeResource(pLionBuffer); for (size_t i = 0; i<pSponzaVertexBufferPosition.size(); i++) removeResource(pSponzaVertexBufferPosition[i]); for (size_t i = 0; i<pSponzaIndexBuffer.size(); i++) removeResource(pSponzaIndexBuffer[i]); removeResource(pLionVertexBufferPosition); removeResource(pLionIndexBuffer); gAppUI.Exit(); #ifdef METAL //Temporary fix removeShader(pRenderer, pClearBufferShader); #endif removeShader(pRenderer, pPPR_HolePatchingShader); removeShader(pRenderer, pPPR_ReflectionShader); removeShader(pRenderer, pPPR_ProjectionShader); removeShader(pRenderer, pShaderBRDF); removeShader(pRenderer, pSkyboxShader); removeShader(pRenderer, pShaderGbuffers); removeDepthState(pDepth); removeRasterizerState(pRasterstateDefault); removeSampler(pRenderer, pSamplerBilinear); removeSampler(pRenderer, pSamplerNearest); #ifdef METAL //Temporary fix removeRootSignature(pRenderer, pClearBufferRootSignature); #endif removeRootSignature(pRenderer, pPPR_HolePatchingRootSignature); removeRootSignature(pRenderer, pPPR_ReflectionRootSignature); removeRootSignature(pRenderer, pPPR_ProjectionRootSignature); removeRootSignature(pRenderer, pRootSigBRDF); removeRootSignature(pRenderer, pSkyboxRootSignature); removeRootSignature(pRenderer, pRootSigGbuffers); // Remove commands and command pool& removeCmd_n(pCmdPool, gImageCount, ppCmds); removeCmdPool(pRenderer, pCmdPool); removeQueue(pGraphicsQueue); removeCmd_n(pPreCmdPool, gImageCount, pPrepCmds); removeCmdPool(pRenderer, pPreCmdPool); removeCmd_n(pBrdfCmdPool, gImageCount, pBrdfCmds); removeCmdPool(pRenderer, pBrdfCmdPool); removeCmd_n(pPPR_ProjectionCmdPool, gImageCount, pPPR_ProjectionCmds); removeCmdPool(pRenderer, pPPR_ProjectionCmdPool); removeCmd_n(pPPR_ReflectionCmdPool, gImageCount, pPPR_ReflectionCmds); removeCmdPool(pRenderer, pPPR_ReflectionCmdPool); for (uint i = 0; i < TOTAL_IMGS; ++i) removeResource(pMaterialTextures[i]); // Remove resource loader and renderer removeResourceLoaderInterface(pRenderer); removeRenderer(pRenderer); } bool Load() { if (!addSwapChain()) return false; if (!addSceneBuffer()) return false; if (!addReflectionBuffer()) return false; if (!addGBuffers()) return false; if (!addDepthBuffer()) return false; if (!addIntermeditateBuffer()) return false; if (!gAppUI.Load(pSwapChain->ppSwapchainRenderTargets)) return false; #ifdef TARGET_IOS if (!gVirtualJoystick.Load(pSwapChain->ppSwapchainRenderTargets[0], 0)) return false; #endif // fill Gbuffers // Create vertex layout VertexLayout vertexLayoutSphere = {}; vertexLayoutSphere.mAttribCount = 3; vertexLayoutSphere.mAttribs[0].mSemantic = SEMANTIC_POSITION; vertexLayoutSphere.mAttribs[0].mFormat = ImageFormat::RGB32F; vertexLayoutSphere.mAttribs[0].mBinding = 0; vertexLayoutSphere.mAttribs[0].mLocation = 0; vertexLayoutSphere.mAttribs[0].mOffset = 0; //normals vertexLayoutSphere.mAttribs[1].mSemantic = SEMANTIC_NORMAL; vertexLayoutSphere.mAttribs[1].mFormat = ImageFormat::RGB32F; vertexLayoutSphere.mAttribs[1].mLocation = 1; vertexLayoutSphere.mAttribs[1].mBinding = 0; vertexLayoutSphere.mAttribs[1].mOffset = 3 * sizeof(float); //texture vertexLayoutSphere.mAttribs[2].mSemantic = SEMANTIC_TEXCOORD0; vertexLayoutSphere.mAttribs[2].mFormat = ImageFormat::RG32F; vertexLayoutSphere.mAttribs[2].mLocation = 2; vertexLayoutSphere.mAttribs[2].mBinding = 0; vertexLayoutSphere.mAttribs[2].mOffset = 6 * sizeof(float); // first attribute contains 3 floats /************************************************************************/ // Setup the resources needed for the Deferred Pass Pipeline /************************************************************************/ ImageFormat::Enum deferredFormats[DEFERRED_RT_COUNT] = {}; bool deferredSrgb[DEFERRED_RT_COUNT] = {}; for (uint32_t i = 0; i < DEFERRED_RT_COUNT; ++i) { deferredFormats[i] = pRenderTargetDeferredPass[i]->mDesc.mFormat; deferredSrgb[i] = pRenderTargetDeferredPass[i]->mDesc.mSrgb; } GraphicsPipelineDesc deferredPassPipelineSettings = {}; deferredPassPipelineSettings.mPrimitiveTopo = PRIMITIVE_TOPO_TRI_LIST; deferredPassPipelineSettings.mRenderTargetCount = DEFERRED_RT_COUNT; deferredPassPipelineSettings.pDepthState = pDepth; deferredPassPipelineSettings.pColorFormats = deferredFormats; deferredPassPipelineSettings.pSrgbValues = deferredSrgb; deferredPassPipelineSettings.mSampleCount = pRenderTargetDeferredPass[0]->mDesc.mSampleCount; deferredPassPipelineSettings.mSampleQuality = pRenderTargetDeferredPass[0]->mDesc.mSampleQuality; deferredPassPipelineSettings.mDepthStencilFormat = pDepthBuffer->mDesc.mFormat; deferredPassPipelineSettings.pRootSignature = pRootSigGbuffers; deferredPassPipelineSettings.pShaderProgram = pShaderGbuffers; deferredPassPipelineSettings.pVertexLayout = &vertexLayoutSphere; deferredPassPipelineSettings.pRasterizerState = pRasterstateDefault; addPipeline(pRenderer, &deferredPassPipelineSettings, &pPipelineGbuffers); //layout and pipeline for skybox draw VertexLayout vertexLayoutSkybox = {}; vertexLayoutSkybox.mAttribCount = 1; vertexLayoutSkybox.mAttribs[0].mSemantic = SEMANTIC_POSITION; vertexLayoutSkybox.mAttribs[0].mFormat = ImageFormat::RGBA32F; vertexLayoutSkybox.mAttribs[0].mBinding = 0; vertexLayoutSkybox.mAttribs[0].mLocation = 0; vertexLayoutSkybox.mAttribs[0].mOffset = 0; deferredPassPipelineSettings = {}; deferredPassPipelineSettings.mPrimitiveTopo = PRIMITIVE_TOPO_TRI_LIST; deferredPassPipelineSettings.mRenderTargetCount = DEFERRED_RT_COUNT; deferredPassPipelineSettings.pDepthState = NULL; deferredPassPipelineSettings.pColorFormats = deferredFormats; deferredPassPipelineSettings.pSrgbValues = deferredSrgb; deferredPassPipelineSettings.mSampleCount = pRenderTargetDeferredPass[0]->mDesc.mSampleCount; deferredPassPipelineSettings.mSampleQuality = pRenderTargetDeferredPass[0]->mDesc.mSampleQuality; deferredPassPipelineSettings.mDepthStencilFormat = pDepthBuffer->mDesc.mFormat; deferredPassPipelineSettings.pRootSignature = pSkyboxRootSignature; deferredPassPipelineSettings.pShaderProgram = pSkyboxShader; deferredPassPipelineSettings.pVertexLayout = &vertexLayoutSkybox; deferredPassPipelineSettings.pRasterizerState = pRasterstateDefault; addPipeline(pRenderer, &deferredPassPipelineSettings, &pSkyboxPipeline); // BRDF //Position VertexLayout vertexLayoutScreenQuad = {}; vertexLayoutScreenQuad.mAttribCount = 2; vertexLayoutScreenQuad.mAttribs[0].mSemantic = SEMANTIC_POSITION; vertexLayoutScreenQuad.mAttribs[0].mFormat = ImageFormat::RGB32F; vertexLayoutScreenQuad.mAttribs[0].mBinding = 0; vertexLayoutScreenQuad.mAttribs[0].mLocation = 0; vertexLayoutScreenQuad.mAttribs[0].mOffset = 0; //Uv vertexLayoutScreenQuad.mAttribs[1].mSemantic = SEMANTIC_TEXCOORD0; vertexLayoutScreenQuad.mAttribs[1].mFormat = ImageFormat::RG32F; vertexLayoutScreenQuad.mAttribs[1].mLocation = 1; vertexLayoutScreenQuad.mAttribs[1].mBinding = 0; vertexLayoutScreenQuad.mAttribs[1].mOffset = 3 * sizeof(float); // first attribute contains 3 floats GraphicsPipelineDesc pipelineSettings = { 0 }; pipelineSettings.mPrimitiveTopo = PRIMITIVE_TOPO_TRI_LIST; pipelineSettings.mRenderTargetCount = 1; pipelineSettings.pDepthState = NULL; pipelineSettings.pColorFormats = &pSceneBuffer->mDesc.mFormat; pipelineSettings.pSrgbValues = &pSceneBuffer->mDesc.mSrgb; pipelineSettings.mSampleCount = pSceneBuffer->mDesc.mSampleCount; pipelineSettings.mSampleQuality = pSceneBuffer->mDesc.mSampleQuality; // pipelineSettings.pDepthState is NULL, pipelineSettings.mDepthStencilFormat should be NONE pipelineSettings.mDepthStencilFormat = ImageFormat::NONE; pipelineSettings.pRootSignature = pRootSigBRDF; pipelineSettings.pShaderProgram = pShaderBRDF; pipelineSettings.pVertexLayout = &vertexLayoutScreenQuad; pipelineSettings.pRasterizerState = pRasterstateDefault; addPipeline(pRenderer, &pipelineSettings, &pPipelineBRDF); //PPR_Projection ComputePipelineDesc cpipelineSettings = { 0 }; cpipelineSettings.pShaderProgram = pPPR_ProjectionShader; cpipelineSettings.pRootSignature = pPPR_ProjectionRootSignature; addComputePipeline(pRenderer, &cpipelineSettings, &pPPR_ProjectionPipeline); //PPR_Reflection pipelineSettings = { 0 }; pipelineSettings.mPrimitiveTopo = PRIMITIVE_TOPO_TRI_LIST; pipelineSettings.mRenderTargetCount = 1; pipelineSettings.pDepthState = NULL; pipelineSettings.pColorFormats = &pReflectionBuffer->mDesc.mFormat; pipelineSettings.pSrgbValues = &pReflectionBuffer->mDesc.mSrgb; pipelineSettings.mSampleCount = pReflectionBuffer->mDesc.mSampleCount; pipelineSettings.mSampleQuality = pReflectionBuffer->mDesc.mSampleQuality; pipelineSettings.mDepthStencilFormat = ImageFormat::NONE; pipelineSettings.pRootSignature = pPPR_ReflectionRootSignature; pipelineSettings.pShaderProgram = pPPR_ReflectionShader; pipelineSettings.pVertexLayout = &vertexLayoutScreenQuad; pipelineSettings.pRasterizerState = pRasterstateDefault; addPipeline(pRenderer, &pipelineSettings, &pPPR_ReflectionPipeline); #ifdef METAL //temporary fix //clear compute buffers pipeline ComputePipelineDesc mClearBufferpipelineSettings = { 0 }; mClearBufferpipelineSettings.pShaderProgram = pClearBufferShader; mClearBufferpipelineSettings.pRootSignature = pClearBufferRootSignature; addComputePipeline(pRenderer, &mClearBufferpipelineSettings, &pClearBufferPipeline); #endif //PPR_HolePatching -> Present pipelineSettings = { 0 }; pipelineSettings.mPrimitiveTopo = PRIMITIVE_TOPO_TRI_LIST; pipelineSettings.mRenderTargetCount = 1; pipelineSettings.pDepthState = NULL; pipelineSettings.pColorFormats = &pSwapChain->ppSwapchainRenderTargets[0]->mDesc.mFormat; pipelineSettings.pSrgbValues = &pSwapChain->ppSwapchainRenderTargets[0]->mDesc.mSrgb; pipelineSettings.mSampleCount = pSwapChain->ppSwapchainRenderTargets[0]->mDesc.mSampleCount; pipelineSettings.mSampleQuality = pSwapChain->ppSwapchainRenderTargets[0]->mDesc.mSampleQuality; pipelineSettings.mDepthStencilFormat = ImageFormat::NONE; pipelineSettings.pRootSignature = pPPR_HolePatchingRootSignature; pipelineSettings.pShaderProgram = pPPR_HolePatchingShader; pipelineSettings.pVertexLayout = &vertexLayoutScreenQuad; pipelineSettings.pRasterizerState = pRasterstateDefault; addPipeline(pRenderer, &pipelineSettings, &pPPR_HolePatchingPipeline); #if defined(VULKAN) transitionRenderTargets(); #endif return true; } void Unload() { waitForFences(pGraphicsQueue, 1, &pRenderCompleteFences[gFrameIndex], true); gAppUI.Unload(); #ifdef TARGET_IOS gVirtualJoystick.Unload(); #endif removePipeline(pRenderer, pPipelineBRDF); removePipeline(pRenderer, pSkyboxPipeline); removePipeline(pRenderer, pPPR_ProjectionPipeline); removePipeline(pRenderer, pPPR_ReflectionPipeline); removePipeline(pRenderer, pPPR_HolePatchingPipeline); removePipeline(pRenderer, pPipelineGbuffers); #ifdef METAL //temporary fix removePipeline(pRenderer, pClearBufferPipeline); #endif removeRenderTarget(pRenderer, pDepthBuffer); removeRenderTarget(pRenderer, pSceneBuffer); removeRenderTarget(pRenderer, pReflectionBuffer); removeResource(pIntermediateBuffer); for (uint32_t i = 0; i < DEFERRED_RT_COUNT; ++i) removeRenderTarget(pRenderer, pRenderTargetDeferredPass[i]); removeSwapChain(pRenderer, pSwapChain); } void Update(float deltaTime) { #if !defined(TARGET_IOS) && !defined(_DURANGO) if (pSwapChain->mDesc.mEnableVsync != gToggleVSync) { ::toggleVSync(pRenderer, &pSwapChain); } #endif if (getKeyDown(KEY_BUTTON_X)) { RecenterCameraView(170.0f); } pCameraController->update(deltaTime); // Update camera mat4 viewMat = pCameraController->getViewMatrix(); const float aspectInverse = (float)mSettings.mHeight / (float)mSettings.mWidth; const float horizontal_fov = PI / 2.0f; mat4 projMat = mat4::perspective(horizontal_fov, aspectInverse, 0.1f, 1000.0f); mat4 ViewProjMat = projMat * viewMat; pUniformDataCamera.mProjectView = ViewProjMat; pUniformDataCamera.mCamPos = pCameraController->getViewPosition(); viewMat.setTranslation(vec3(0)); gUniformDataSky = pUniformDataCamera; gUniformDataSky.mProjectView = projMat * viewMat; //data uniforms pUniformDataExtenedCamera.mCameraWorldPos = vec4(pCameraController->getViewPosition(), 1.0); pUniformDataExtenedCamera.mViewMat = pCameraController->getViewMatrix(); pUniformDataExtenedCamera.mProjMat = projMat; pUniformDataExtenedCamera.mViewProjMat = ViewProjMat; pUniformDataExtenedCamera.mInvViewProjMat = inverse(ViewProjMat); pUniformDataExtenedCamera.mViewPortSize = vec4(static_cast<float>(mSettings.mWidth), static_cast<float>(mSettings.mHeight), 0.0, 0.0); //projection uniforms pUniformPPRProData.renderMode = gRenderMode; pUniformPPRProData.useHolePatching = gUseHolePatching == true ? 1.0f : 0.0f; pUniformPPRProData.useExpensiveHolePatching = gUseExpensiveHolePatching == true ? 1.0f : 0.0f; pUniformPPRProData.useNormalMap = gUseNormalMap == true ? 1.0f : 0.0f; pUniformPPRProData.useFadeEffect = gUseFadeEffect == true ? 1.0f : 0.0f; pUniformPPRProData.intensity = gRRP_Intensity; //Planes pUniformDataPlaneInfo.numPlanes = gPlaneNumber; pUniformDataPlaneInfo.planeInfo[0].centerPoint = vec4(0.0, -6.0f, 0.9f, 0.0); pUniformDataPlaneInfo.planeInfo[0].size = vec4(gPlaneSize); pUniformDataPlaneInfo.planeInfo[1].centerPoint = vec4(10.0, -5.0f, -1.25f, 0.0); pUniformDataPlaneInfo.planeInfo[1].size = vec4(9.0f, 2.0f, 0.0f, 0.0f); pUniformDataPlaneInfo.planeInfo[2].centerPoint = vec4(10.0, -5.0f, 3.0f, 0.0); pUniformDataPlaneInfo.planeInfo[2].size = vec4(9.0f, 2.0f, 0.0f, 0.0f); pUniformDataPlaneInfo.planeInfo[3].centerPoint = vec4(10.0, 1.0f, 0.9f, 0.0); pUniformDataPlaneInfo.planeInfo[3].size = vec4(10.0f); mat4 basicMat; basicMat[0] = vec4(1.0, 0.0, 0.0, 0.0); //tan basicMat[1] = vec4(0.0, 0.0, -1.0, 0.0); //bitan basicMat[2] = vec4(0.0, 1.0, 0.0, 0.0); //normal basicMat[3] = vec4(0.0, 0.0, 0.0, 1.0); pUniformDataPlaneInfo.planeInfo[0].rotMat = basicMat; pUniformDataPlaneInfo.planeInfo[1].rotMat = basicMat.rotationX(0.01745329251994329576923690768489f * -80.0f); pUniformDataPlaneInfo.planeInfo[2].rotMat = basicMat.rotationX(0.01745329251994329576923690768489f * -100.0f); pUniformDataPlaneInfo.planeInfo[3].rotMat = basicMat.rotationX(0.01745329251994329576923690768489f * 90.0f);; #if defined(DIRECT3D12) || defined(_DURANGO) // Need to check why this should be transposed on DX12 // Even view or proj matrices work well.... pUniformDataPlaneInfo.planeInfo[0].rotMat = transpose(pUniformDataPlaneInfo.planeInfo[0].rotMat); pUniformDataPlaneInfo.planeInfo[1].rotMat = transpose(pUniformDataPlaneInfo.planeInfo[1].rotMat); pUniformDataPlaneInfo.planeInfo[2].rotMat = transpose(pUniformDataPlaneInfo.planeInfo[2].rotMat); pUniformDataPlaneInfo.planeInfo[3].rotMat = transpose(pUniformDataPlaneInfo.planeInfo[3].rotMat); #endif /************************************************************************/ // Update GUI /************************************************************************/ gAppUI.Update(deltaTime); } void Draw() { // This will acquire the next swapchain image acquireNextImage(pRenderer, pSwapChain, pImageAcquiredSemaphore, NULL, &gFrameIndex); Semaphore* pRenderCompleteSemaphore = pRenderCompleteSemaphores[gFrameIndex]; Fence* pRenderCompleteFence = pRenderCompleteFences[gFrameIndex]; // Stall if CPU is running "Swap Chain Buffer Count" frames ahead of GPU FenceStatus fenceStatus; getFenceStatus(pRenderer, pRenderCompleteFence, &fenceStatus); if (fenceStatus == FENCE_STATUS_INCOMPLETE) waitForFences(pGraphicsQueue, 1, &pRenderCompleteFence, false); tinystl::vector<Cmd*> allCmds; BufferUpdateDesc camBuffUpdateDesc = { pBufferUniformCamera[gFrameIndex], &pUniformDataCamera }; updateResource(&camBuffUpdateDesc); BufferUpdateDesc skyboxViewProjCbv = { pBufferUniformCameraSky[gFrameIndex], &gUniformDataSky }; updateResource(&skyboxViewProjCbv); BufferUpdateDesc CbvExtendedCamera = { pBufferUniformExtendedCamera[gFrameIndex], &pUniformDataExtenedCamera }; updateResource(&CbvExtendedCamera); BufferUpdateDesc CbPPR_Prop = { pBufferUniformPPRPro[gFrameIndex], &pUniformPPRProData }; updateResource(&CbPPR_Prop); BufferUpdateDesc planeInfoBuffUpdateDesc = { pBufferUniformPlaneInfo[gFrameIndex], &pUniformDataPlaneInfo }; updateResource(&planeInfoBuffUpdateDesc); // Draw G-buffers Cmd* cmd = pPrepCmds[gFrameIndex]; beginCmd(cmd); cmdBeginGpuFrameProfile(cmd, pGpuProfiler); //Clear G-buffers and Depth buffer LoadActionsDesc loadActions = {}; for (uint32_t i = 0; i < DEFERRED_RT_COUNT; ++i) { loadActions.mLoadActionsColor[i] = LOAD_ACTION_CLEAR; loadActions.mClearColorValues[i] = pRenderTargetDeferredPass[i]->mDesc.mClearValue; } loadActions.mLoadActionDepth = LOAD_ACTION_CLEAR; loadActions.mClearDepth = { 1.0f, 0.0f }; // Clear depth to the far plane and stencil to 0 // Transfer G-buffers to render target state for each buffer TextureBarrier barrier; for (uint32_t i = 0; i < DEFERRED_RT_COUNT; ++i) { barrier = { pRenderTargetDeferredPass[i]->pTexture, RESOURCE_STATE_RENDER_TARGET }; cmdResourceBarrier(cmd, 0, NULL, 1, &barrier, false); } // Transfer DepthBuffer to a DephtWrite State barrier = { pDepthBuffer->pTexture, RESOURCE_STATE_DEPTH_WRITE }; cmdResourceBarrier(cmd, 0, NULL, 1, &barrier, false); cmdBindRenderTargets(cmd, DEFERRED_RT_COUNT, pRenderTargetDeferredPass, pDepthBuffer, &loadActions, NULL, NULL, -1, -1); cmdSetViewport(cmd, 0.0f, 0.0f, (float)pRenderTargetDeferredPass[0]->mDesc.mWidth, (float)pRenderTargetDeferredPass[0]->mDesc.mHeight, 0.0f, 1.0f); cmdSetScissor(cmd, 0, 0, pRenderTargetDeferredPass[0]->mDesc.mWidth, pRenderTargetDeferredPass[0]->mDesc.mHeight); // Draw the skybox. cmdBeginGpuTimestampQuery(cmd, pGpuProfiler, "Render SkyBox", true); cmdBindPipeline(cmd, pSkyboxPipeline); DescriptorData skyParams[2] = {}; skyParams[0].pName = "uniformBlock"; skyParams[0].ppBuffers = &pBufferUniformCameraSky[gFrameIndex]; skyParams[1].pName = "skyboxTex"; skyParams[1].ppTextures = &pSkybox; cmdBindDescriptors(cmd, pSkyboxRootSignature, 2, skyParams); cmdBindVertexBuffer(cmd, 1, &pSkyboxVertexBuffer, NULL); cmdDraw(cmd, 36, 0); cmdEndGpuTimestampQuery(cmd, pGpuProfiler); // Draw Sponza cmdBeginGpuTimestampQuery(cmd, pGpuProfiler, "Fill GBuffers", true); //The default code path we have if not iOS uses an array of texture of size 81 //iOS only supports 31 max texture units in a fragment shader for most devices. //so fallback to binding every texture for every draw call (max of 5 textures) #ifdef TARGET_IOS cmdBindPipeline(cmd, pPipelineGbuffers); DescriptorData params[8] = {}; params[0].pName = "cbCamera"; params[0].ppBuffers = &pBufferUniformCamera[gFrameIndex]; for (int i = 0; i < pSponzaVertexBufferPosition.size(); i++) { Buffer* pSponzaVertexBuffers[] = { pSponzaVertexBufferPosition[i] }; cmdBindVertexBuffer(cmd, 1, pSponzaVertexBuffers, NULL); cmdBindIndexBuffer(cmd, pSponzaIndexBuffer[i], NULL); params[1].pName = "cbObject"; params[1].ppBuffers = &pSponzaBuffer; int materialID = gSponzaMaterialID[i]; materialID *= 5; //because it uses 5 basic textures for redering BRDF for (int j = 0; j <5; ++j) { //added params[2 + j].pName = pTextureName[j]; params[2 + j].ppTextures = &pMaterialTextures[gSponzaTextureIndexforMaterial[materialID + j]]; } cmdBindDescriptors(cmd, pRootSigGbuffers, 7, params); cmdDrawIndexed(cmd, gSponzaIndicesArray[i], 0, 0); } #else cmdBindPipeline(cmd, pPipelineGbuffers); DescriptorData params[8] = {}; params[0].pName = "cbCamera"; params[0].ppBuffers = &pBufferUniformCamera[gFrameIndex]; params[1].pName = "cbObject"; params[1].ppBuffers = &pSponzaBuffer; params[2].pName = "textureMaps"; params[2].ppTextures = pMaterialTextures; params[2].mCount = TOTAL_IMGS; cmdBindDescriptors(cmd, pRootSigGbuffers, 3, params); struct MaterialMaps { uint mapIDs[5]; } data; for (uint32_t i = 0; i < (uint32_t)pSponzaVertexBufferPosition.size(); ++i) { Buffer* pSponzaVertexBuffers[] = { pSponzaVertexBufferPosition[i] }; cmdBindVertexBuffer(cmd, 1, pSponzaVertexBuffers, NULL); cmdBindIndexBuffer(cmd, pSponzaIndexBuffer[i], 0); int materialID = gSponzaMaterialID[i]; materialID *= 5; //because it uses 5 basic textures for redering BRDF for (int j = 0; j < 5; ++j) { //added data.mapIDs[j] = gSponzaTextureIndexforMaterial[materialID + j]; } params[0].pName = "cbTextureRootConstants"; params[0].pRootConstant = &data; cmdBindDescriptors(cmd, pRootSigGbuffers, 1, params); cmdDrawIndexed(cmd, gSponzaIndicesArray[i], 0, 0); } #endif //Draw Lion cmdBindVertexBuffer(cmd, 1, &pLionVertexBufferPosition, NULL); cmdBindIndexBuffer(cmd, pLionIndexBuffer, 0); #ifdef TARGET_IOS params[0].pName = "cbCamera"; params[0].ppBuffers = &pBufferUniformCamera[gFrameIndex]; params[1].pName = "cbObject"; params[1].ppBuffers = &pLionBuffer; params[2].pName = pTextureName[0]; params[2].ppTextures = &pMaterialTextures[81]; params[3].pName = pTextureName[1]; params[3].ppTextures = &pMaterialTextures[83]; params[4].pName = pTextureName[2]; params[4].ppTextures = &pMaterialTextures[6]; params[5].pName = pTextureName[3]; params[5].ppTextures = &pMaterialTextures[6]; params[6].pName = pTextureName[4]; params[6].ppTextures = &pMaterialTextures[0]; cmdBindDescriptors(cmd, pRootSigGbuffers, 7, params); #else data.mapIDs[0] = 81; data.mapIDs[1] = 83; data.mapIDs[2] = 6; data.mapIDs[3] = 6; data.mapIDs[4] = 0; params[0].pName = "cbObject"; params[0].ppBuffers = &pLionBuffer; params[1].pName = "cbTextureRootConstants"; params[1].pRootConstant = &data; cmdBindDescriptors(cmd, pRootSigGbuffers, 2, params); #endif cmdDrawIndexed(cmd, gLionIndicesArray[0], 0, 0); cmdEndGpuTimestampQuery(cmd, pGpuProfiler); endCmd(cmd); allCmds.push_back(cmd); // Render BRDF cmd = pBrdfCmds[gFrameIndex]; beginCmd(cmd); // Transfer G-buffers to a Shader resource state for (uint32_t i = 0; i < DEFERRED_RT_COUNT; ++i) { barrier = { pRenderTargetDeferredPass[i]->pTexture, RESOURCE_STATE_SHADER_RESOURCE }; cmdResourceBarrier(cmd, 0, NULL, 1, &barrier, false); } // Transfer current render target to a render target state barrier = { pSceneBuffer->pTexture, RESOURCE_STATE_RENDER_TARGET }; cmdResourceBarrier(cmd, 0, NULL, 1, &barrier, false); // Transfer DepthBuffer to a Shader resource state barrier = { pDepthBuffer->pTexture, RESOURCE_STATE_SHADER_RESOURCE }; cmdResourceBarrier(cmd, 0, NULL, 1, &barrier, false); loadActions = {}; loadActions.mLoadActionsColor[0] = LOAD_ACTION_CLEAR; loadActions.mClearColorValues[0] = pSceneBuffer->mDesc.mClearValue; cmdBindRenderTargets(cmd, 1, &pSceneBuffer, NULL, &loadActions, NULL, NULL, -1, -1); cmdSetViewport(cmd, 0.0f, 0.0f, (float)pSceneBuffer->mDesc.mWidth, (float)pSceneBuffer->mDesc.mHeight, 0.0f, 1.0f); cmdSetScissor(cmd, 0, 0, pSceneBuffer->mDesc.mWidth, pSceneBuffer->mDesc.mHeight); cmdBeginGpuTimestampQuery(cmd, pGpuProfiler, "Render BRDF", false); cmdBindPipeline(cmd, pPipelineBRDF); DescriptorData BRDFParams[12] = {}; BRDFParams[0].pName = "cbExtendCamera"; BRDFParams[0].ppBuffers = &pBufferUniformExtendedCamera[gFrameIndex]; BRDFParams[1].pName = "cbLights"; BRDFParams[1].ppBuffers = &pBufferUniformLights; BRDFParams[2].pName = "cbDLights"; BRDFParams[2].ppBuffers = &pBufferUniformDirectionalLights; BRDFParams[3].pName = "brdfIntegrationMap"; BRDFParams[3].ppTextures = &pBRDFIntegrationMap; BRDFParams[4].pName = "irradianceMap"; BRDFParams[4].ppTextures = &pIrradianceMap; BRDFParams[5].pName = "specularMap"; BRDFParams[5].ppTextures = &pSpecularMap; BRDFParams[6].pName = "AlbedoTexture"; BRDFParams[6].ppTextures = &pRenderTargetDeferredPass[0]->pTexture; BRDFParams[7].pName = "NormalTexture"; BRDFParams[7].ppTextures = &pRenderTargetDeferredPass[1]->pTexture; BRDFParams[8].pName = "RoughnessTexture"; BRDFParams[8].ppTextures = &pRenderTargetDeferredPass[2]->pTexture; BRDFParams[9].pName = "DepthTexture"; BRDFParams[9].ppTextures = &pDepthBuffer->pTexture; cmdBindVertexBuffer(cmd, 1, &pScreenQuadVertexBuffer, NULL); cmdBindDescriptors(cmd, pRootSigBRDF, 10, BRDFParams); cmdDraw(cmd, 3, 0); cmdEndGpuTimestampQuery(cmd, pGpuProfiler); endCmd(cmd); allCmds.push_back(cmd); // PixelProjectReflections_ProjectionPass cmd = pPPR_ProjectionCmds[gFrameIndex]; beginCmd(cmd); #ifdef METAL //temporary fix cmdBindRenderTargets(cmd, 0, NULL, NULL, NULL, NULL, NULL, -1, -1); cmdBeginGpuTimestampQuery(cmd, pGpuProfiler, "Clear Compute Buffer", false); cmdBindPipeline(cmd, pClearBufferPipeline); DescriptorData ClearBufferParams[1] = {}; ClearBufferParams[0].pName = "IntermediateBuffer"; ClearBufferParams[0].ppBuffers = &pIntermediateBuffer; cmdBindDescriptors(cmd, pClearBufferRootSignature, 1, ClearBufferParams); const uint32_t* pThreadGroupSize_Clear = cmd->pShader->mReflection.mStageReflections[0].mNumThreadsPerGroup; cmdDispatch(cmd, (mSettings.mWidth * mSettings.mHeight/ pThreadGroupSize_Clear[0]) + 1, 1, 1); cmdEndGpuTimestampQuery(cmd, pGpuProfiler); cmdBindRenderTargets(cmd, 0, NULL, NULL, NULL, NULL, NULL, -1, -1); #endif cmdBeginGpuTimestampQuery(cmd, pGpuProfiler, "Pixel-Projected Reflections", false); cmdBeginGpuTimestampQuery(cmd, pGpuProfiler, "ProjectionPass", true); cmdBindPipeline(cmd, pPPR_ProjectionPipeline); DescriptorData PPR_ProjectionParams[5] = {}; PPR_ProjectionParams[0].pName = "cbExtendCamera"; PPR_ProjectionParams[0].ppBuffers = &pBufferUniformExtendedCamera[gFrameIndex]; PPR_ProjectionParams[1].pName = "IntermediateBuffer"; PPR_ProjectionParams[1].ppBuffers = &pIntermediateBuffer; PPR_ProjectionParams[2].pName = "DepthTexture"; PPR_ProjectionParams[2].ppTextures = &pDepthBuffer->pTexture; PPR_ProjectionParams[3].pName = "planeInfoBuffer"; PPR_ProjectionParams[3].ppBuffers = &pBufferUniformPlaneInfo[gFrameIndex]; cmdBindDescriptors(cmd, pPPR_ProjectionRootSignature, 4, PPR_ProjectionParams); const uint32_t* pThreadGroupSize = pPPR_ProjectionShader->mReflection.mStageReflections[0].mNumThreadsPerGroup; cmdDispatch(cmd, (mSettings.mWidth * mSettings.mHeight / pThreadGroupSize[0]) + 1, 1, 1); cmdEndGpuTimestampQuery(cmd, pGpuProfiler); endCmd(cmd); allCmds.push_back(cmd); // PixelProjectReflections_ReflectionPass cmd = pPPR_ReflectionCmds[gFrameIndex]; beginCmd(cmd); RenderTarget* pRenderTarget = pReflectionBuffer; barrier = { pSceneBuffer->pTexture, RESOURCE_STATE_SHADER_RESOURCE }; cmdResourceBarrier(cmd, 0, NULL, 1, &barrier, false); // Transfer current render target to a render target state barrier = { pRenderTarget->pTexture, RESOURCE_STATE_RENDER_TARGET }; cmdResourceBarrier(cmd, 0, NULL, 1, &barrier, false); loadActions = {}; loadActions.mLoadActionsColor[0] = LOAD_ACTION_CLEAR; loadActions.mClearColorValues[0] = pRenderTarget->mDesc.mClearValue; cmdBindRenderTargets(cmd, 1, &pRenderTarget, NULL, &loadActions, NULL, NULL, -1, -1); cmdSetViewport(cmd, 0.0f, 0.0f, (float)pRenderTarget->mDesc.mWidth, (float)pRenderTarget->mDesc.mHeight, 0.0f, 1.0f); cmdSetScissor(cmd, 0, 0, pRenderTarget->mDesc.mWidth, pRenderTarget->mDesc.mHeight); cmdBeginGpuTimestampQuery(cmd, pGpuProfiler, "ReflectionPass", true); cmdBindPipeline(cmd, pPPR_ReflectionPipeline); DescriptorData PPR_ReflectionParams[7] = {}; PPR_ReflectionParams[0].pName = "cbExtendCamera"; PPR_ReflectionParams[0].ppBuffers = &pBufferUniformExtendedCamera[gFrameIndex]; PPR_ReflectionParams[1].pName = "SceneTexture"; PPR_ReflectionParams[1].ppTextures = &pSceneBuffer->pTexture; PPR_ReflectionParams[2].pName = "planeInfoBuffer"; PPR_ReflectionParams[2].ppBuffers = &pBufferUniformPlaneInfo[gFrameIndex]; PPR_ReflectionParams[3].pName = "IntermediateBuffer"; PPR_ReflectionParams[3].ppBuffers = &pIntermediateBuffer; PPR_ReflectionParams[4].pName = "DepthTexture"; PPR_ReflectionParams[4].ppTextures = &pDepthBuffer->pTexture; PPR_ReflectionParams[5].pName = "cbProperties"; PPR_ReflectionParams[5].ppBuffers = &pBufferUniformPPRPro[gFrameIndex]; cmdBindDescriptors(cmd, pPPR_ReflectionRootSignature, 6, PPR_ReflectionParams); cmdBindVertexBuffer(cmd, 1, &pScreenQuadVertexBuffer, NULL); cmdDraw(cmd, 3, 0); //End ReflectionPass cmdEndGpuTimestampQuery(cmd, pGpuProfiler); endCmd(cmd); allCmds.push_back(cmd); //Present cmd = ppCmds[gFrameIndex]; beginCmd(cmd); pRenderTarget = pSwapChain->ppSwapchainRenderTargets[gFrameIndex]; barrier = { pReflectionBuffer->pTexture, RESOURCE_STATE_SHADER_RESOURCE }; cmdResourceBarrier(cmd, 0, NULL, 1, &barrier, false); barrier = { pRenderTarget->pTexture, RESOURCE_STATE_RENDER_TARGET }; cmdResourceBarrier(cmd, 0, NULL, 1, &barrier, false); loadActions = {}; loadActions.mLoadActionsColor[0] = LOAD_ACTION_CLEAR; loadActions.mClearColorValues[0] = pRenderTarget->mDesc.mClearValue; cmdBindRenderTargets(cmd, 1, &pRenderTarget, NULL, &loadActions, NULL, NULL, -1, -1); cmdSetViewport(cmd, 0.0f, 0.0f, (float)pRenderTarget->mDesc.mWidth, (float)pRenderTarget->mDesc.mHeight, 0.0f, 1.0f); cmdSetScissor(cmd, 0, 0, pRenderTarget->mDesc.mWidth, pRenderTarget->mDesc.mHeight); cmdBeginGpuTimestampQuery(cmd, pGpuProfiler, "HolePatching", true); cmdBindPipeline(cmd, pPPR_HolePatchingPipeline); DescriptorData PPR_HolePatchingParams[6] = {}; PPR_HolePatchingParams[0].pName = "cbExtendCamera"; PPR_HolePatchingParams[0].ppBuffers = &pBufferUniformExtendedCamera[gFrameIndex]; PPR_HolePatchingParams[1].pName = "SceneTexture"; PPR_HolePatchingParams[1].ppTextures = &pSceneBuffer->pTexture; PPR_HolePatchingParams[2].pName = "SSRTexture"; PPR_HolePatchingParams[2].ppTextures = &pReflectionBuffer->pTexture; PPR_HolePatchingParams[3].pName = "cbProperties"; PPR_HolePatchingParams[3].ppBuffers = &pBufferUniformPPRPro[gFrameIndex]; cmdBindDescriptors(cmd, pPPR_HolePatchingRootSignature, 4, PPR_HolePatchingParams); cmdBindVertexBuffer(cmd, 1, &pScreenQuadVertexBuffer, NULL); cmdDraw(cmd, 3, 0); cmdEndGpuTimestampQuery(cmd, pGpuProfiler); //End Pixel-Projected Reflections cmdEndGpuTimestampQuery(cmd, pGpuProfiler); static HiresTimer gTimer; gTimer.GetUSec(true); #ifdef TARGET_IOS gVirtualJoystick.Draw(cmd, pCameraController, { 1.0f, 1.0f, 1.0f, 1.0f }); #endif drawDebugText(cmd, 8, 15, tinystl::string::format("CPU %f ms", gTimer.GetUSecAverage() / 1000.0f), &gFrameTimeDraw); #ifndef METAL // Metal doesn't support GPU profilers drawDebugText(cmd, 8, 40, tinystl::string::format("GPU %f ms", (float)pGpuProfiler->mCumulativeTime * 1000.0f), &gFrameTimeDraw); drawDebugGpuProfile(cmd, 8, 65, pGpuProfiler, NULL); #endif #ifndef TARGET_IOS gAppUI.Gui(pGui); #endif gAppUI.Draw(cmd); cmdBindRenderTargets(cmd, 0, NULL, NULL, NULL, NULL, NULL, -1, -1); // Transition our texture to present state barrier = { pRenderTarget->pTexture, RESOURCE_STATE_PRESENT }; cmdResourceBarrier(cmd, 0, NULL, 1, &barrier, true); cmdEndGpuFrameProfile(cmd, pGpuProfiler); endCmd(cmd); allCmds.push_back(cmd); queueSubmit(pGraphicsQueue, (uint32_t)allCmds.size(), allCmds.data(), pRenderCompleteFence, 1, &pImageAcquiredSemaphore, 1, &pRenderCompleteSemaphore); queuePresent(pGraphicsQueue, pSwapChain, gFrameIndex, 1, &pRenderCompleteSemaphore); } tinystl::string GetName() { return "10_PixelProjectedReflections"; } bool addSwapChain() { SwapChainDesc swapChainDesc = {}; swapChainDesc.pWindow = pWindow; swapChainDesc.mPresentQueueCount = 1; swapChainDesc.ppPresentQueues = &pGraphicsQueue; swapChainDesc.mWidth = mSettings.mWidth; swapChainDesc.mHeight = mSettings.mHeight; swapChainDesc.mImageCount = gImageCount; swapChainDesc.mSampleCount = SAMPLE_COUNT_1; swapChainDesc.mColorFormat = getRecommendedSwapchainFormat(true); swapChainDesc.mEnableVsync = false; ::addSwapChain(pRenderer, &swapChainDesc, &pSwapChain); return pSwapChain != NULL; } bool addSceneBuffer() { RenderTargetDesc sceneRT = {}; sceneRT.mArraySize = 1; sceneRT.mClearValue = { 0.0f, 0.0f, 0.0f, 0.0f }; sceneRT.mDepth = 1; sceneRT.mFormat = ImageFormat::RGBA8; sceneRT.mHeight = mSettings.mHeight; sceneRT.mWidth = mSettings.mWidth; sceneRT.mSampleCount = SAMPLE_COUNT_1; sceneRT.mSampleQuality = 0; sceneRT.pDebugName = L"Scene Buffer"; addRenderTarget(pRenderer, &sceneRT, &pSceneBuffer); return pSceneBuffer != NULL; } bool addReflectionBuffer() { RenderTargetDesc RT = {}; RT.mArraySize = 1; RT.mClearValue = { 0.0f, 0.0f, 0.0f, 0.0f }; RT.mDepth = 1; RT.mFormat = ImageFormat::RGBA8; RT.mHeight = mSettings.mHeight; RT.mWidth = mSettings.mWidth; RT.mSampleCount = SAMPLE_COUNT_1; RT.mSampleQuality = 0; RT.pDebugName = L"Reflection Buffer"; addRenderTarget(pRenderer, &RT, &pReflectionBuffer); return pReflectionBuffer != NULL; } bool addGBuffers() { ClearValue optimizedColorClearBlack = { 0.0f, 0.0f, 0.0f, 0.0f }; /************************************************************************/ // Deferred pass render targets /************************************************************************/ RenderTargetDesc deferredRTDesc = {}; deferredRTDesc.mArraySize = 1; deferredRTDesc.mClearValue = optimizedColorClearBlack; deferredRTDesc.mDepth = 1; deferredRTDesc.mWidth = mSettings.mWidth; deferredRTDesc.mHeight = mSettings.mHeight; deferredRTDesc.mSampleCount = SAMPLE_COUNT_1; deferredRTDesc.mSampleQuality = 0; deferredRTDesc.pDebugName = L"G-Buffer RTs"; for (uint32_t i = 0; i < DEFERRED_RT_COUNT; ++i) { if (i == 1 || i == 2) deferredRTDesc.mFormat = ImageFormat::RGBA16F; else deferredRTDesc.mFormat = ImageFormat::RGBA8; addRenderTarget(pRenderer, &deferredRTDesc, &pRenderTargetDeferredPass[i]); } return pRenderTargetDeferredPass[0] != NULL; } bool addDepthBuffer() { // Add depth buffer RenderTargetDesc depthRT = {}; depthRT.mArraySize = 1; depthRT.mClearValue = { 1.0f, 0 }; depthRT.mDepth = 1; depthRT.mFormat = ImageFormat::D32F; depthRT.mHeight = mSettings.mHeight; depthRT.mSampleCount = SAMPLE_COUNT_1; depthRT.mSampleQuality = 0; depthRT.mWidth = mSettings.mWidth; addRenderTarget(pRenderer, &depthRT, &pDepthBuffer); return pDepthBuffer != NULL; } bool addIntermeditateBuffer() { // Add Intermediate buffer BufferLoadDesc IntermediateBufferDesc = {}; IntermediateBufferDesc.mDesc.mDescriptors = DESCRIPTOR_TYPE_RW_BUFFER | DESCRIPTOR_TYPE_BUFFER; IntermediateBufferDesc.mDesc.mElementCount = mSettings.mWidth * mSettings.mHeight; IntermediateBufferDesc.mDesc.mStructStride = sizeof(uint32_t); IntermediateBufferDesc.mDesc.mMemoryUsage = RESOURCE_MEMORY_USAGE_GPU_ONLY; #ifdef METAL //temporary fix IntermediateBufferDesc.mDesc.mFlags =BUFFER_CREATION_FLAG_OWN_MEMORY_BIT | BUFFER_CREATION_FLAG_PERSISTENT_MAP_BIT; #endif IntermediateBufferDesc.mDesc.mSize = IntermediateBufferDesc.mDesc.mStructStride * IntermediateBufferDesc.mDesc.mElementCount; gInitializeVal.clear(); for (int i = 0; i < mSettings.mWidth * mSettings.mHeight; i++) { gInitializeVal.push_back(UINT32_MAX); } IntermediateBufferDesc.pData = gInitializeVal.data(); IntermediateBufferDesc.ppBuffer = &pIntermediateBuffer; addResource(&IntermediateBufferDesc); return pIntermediateBuffer != NULL; } void RecenterCameraView(float maxDistance, vec3 lookAt = vec3(0)) { vec3 p = pCameraController->getViewPosition(); vec3 d = p - lookAt; float lenSqr = lengthSqr(d); if (lenSqr > (maxDistance * maxDistance)) { d *= (maxDistance / sqrtf(lenSqr)); } p = d + lookAt; pCameraController->moveTo(p); pCameraController->lookAt(lookAt); } static bool cameraInputEvent(const ButtonData* data) { pCameraController->onInputEvent(data); return true; } }; void assignSponzaTextures() { int AO = 5; int NoMetallic = 6; int Metallic = 7; //00 : leaf gSponzaTextureIndexforMaterial.push_back(66); gSponzaTextureIndexforMaterial.push_back(67); gSponzaTextureIndexforMaterial.push_back(NoMetallic); gSponzaTextureIndexforMaterial.push_back(68); gSponzaTextureIndexforMaterial.push_back(AO); //01 : vase_round gSponzaTextureIndexforMaterial.push_back(78); gSponzaTextureIndexforMaterial.push_back(79); gSponzaTextureIndexforMaterial.push_back(NoMetallic); gSponzaTextureIndexforMaterial.push_back(80); gSponzaTextureIndexforMaterial.push_back(AO); //02 : Material__57 (Plant) gSponzaTextureIndexforMaterial.push_back(75); gSponzaTextureIndexforMaterial.push_back(76); gSponzaTextureIndexforMaterial.push_back(NoMetallic); gSponzaTextureIndexforMaterial.push_back(77); gSponzaTextureIndexforMaterial.push_back(AO); // 03 : Material__298 gSponzaTextureIndexforMaterial.push_back(9); gSponzaTextureIndexforMaterial.push_back(10); gSponzaTextureIndexforMaterial.push_back(NoMetallic); gSponzaTextureIndexforMaterial.push_back(11); gSponzaTextureIndexforMaterial.push_back(AO); // 04 : 16___Default (gi_flag) gSponzaTextureIndexforMaterial.push_back(8); gSponzaTextureIndexforMaterial.push_back(8); // !!!!!! gSponzaTextureIndexforMaterial.push_back(NoMetallic); gSponzaTextureIndexforMaterial.push_back(8); // !!!!! gSponzaTextureIndexforMaterial.push_back(AO); // 05 : bricks gSponzaTextureIndexforMaterial.push_back(22); gSponzaTextureIndexforMaterial.push_back(23); gSponzaTextureIndexforMaterial.push_back(NoMetallic); gSponzaTextureIndexforMaterial.push_back(24); gSponzaTextureIndexforMaterial.push_back(AO); // 06 : arch gSponzaTextureIndexforMaterial.push_back(19); gSponzaTextureIndexforMaterial.push_back(20); gSponzaTextureIndexforMaterial.push_back(NoMetallic); gSponzaTextureIndexforMaterial.push_back(21); gSponzaTextureIndexforMaterial.push_back(AO); // 07 : ceiling gSponzaTextureIndexforMaterial.push_back(25); gSponzaTextureIndexforMaterial.push_back(26); gSponzaTextureIndexforMaterial.push_back(NoMetallic); gSponzaTextureIndexforMaterial.push_back(27); gSponzaTextureIndexforMaterial.push_back(AO); // 08 : column_a gSponzaTextureIndexforMaterial.push_back(28); gSponzaTextureIndexforMaterial.push_back(29); gSponzaTextureIndexforMaterial.push_back(NoMetallic); gSponzaTextureIndexforMaterial.push_back(30); gSponzaTextureIndexforMaterial.push_back(AO); // 09 : Floor gSponzaTextureIndexforMaterial.push_back(60); gSponzaTextureIndexforMaterial.push_back(61); gSponzaTextureIndexforMaterial.push_back(NoMetallic); gSponzaTextureIndexforMaterial.push_back(62); gSponzaTextureIndexforMaterial.push_back(AO); // 10 : column_c gSponzaTextureIndexforMaterial.push_back(34); gSponzaTextureIndexforMaterial.push_back(35); gSponzaTextureIndexforMaterial.push_back(NoMetallic); gSponzaTextureIndexforMaterial.push_back(36); gSponzaTextureIndexforMaterial.push_back(AO); // 11 : details gSponzaTextureIndexforMaterial.push_back(45); gSponzaTextureIndexforMaterial.push_back(47); gSponzaTextureIndexforMaterial.push_back(46); gSponzaTextureIndexforMaterial.push_back(48); gSponzaTextureIndexforMaterial.push_back(AO); // 12 : column_b gSponzaTextureIndexforMaterial.push_back(31); gSponzaTextureIndexforMaterial.push_back(32); gSponzaTextureIndexforMaterial.push_back(NoMetallic); gSponzaTextureIndexforMaterial.push_back(33); gSponzaTextureIndexforMaterial.push_back(AO); // 13 : Material__47 - it seems missing gSponzaTextureIndexforMaterial.push_back(19); gSponzaTextureIndexforMaterial.push_back(20); gSponzaTextureIndexforMaterial.push_back(NoMetallic); gSponzaTextureIndexforMaterial.push_back(21); gSponzaTextureIndexforMaterial.push_back(AO); // 14 : flagpole gSponzaTextureIndexforMaterial.push_back(57); gSponzaTextureIndexforMaterial.push_back(58); gSponzaTextureIndexforMaterial.push_back(NoMetallic); gSponzaTextureIndexforMaterial.push_back(59); gSponzaTextureIndexforMaterial.push_back(AO); // 15 : fabric_e (green) gSponzaTextureIndexforMaterial.push_back(51); gSponzaTextureIndexforMaterial.push_back(52); gSponzaTextureIndexforMaterial.push_back(53); gSponzaTextureIndexforMaterial.push_back(54); gSponzaTextureIndexforMaterial.push_back(AO); // 16 : fabric_d (blue) gSponzaTextureIndexforMaterial.push_back(49); gSponzaTextureIndexforMaterial.push_back(50); gSponzaTextureIndexforMaterial.push_back(53); gSponzaTextureIndexforMaterial.push_back(54); gSponzaTextureIndexforMaterial.push_back(AO); // 17 : fabric_a (red) gSponzaTextureIndexforMaterial.push_back(55); gSponzaTextureIndexforMaterial.push_back(56); gSponzaTextureIndexforMaterial.push_back(53); gSponzaTextureIndexforMaterial.push_back(54); gSponzaTextureIndexforMaterial.push_back(AO); // 18 : fabric_g (curtain_blue) gSponzaTextureIndexforMaterial.push_back(37); gSponzaTextureIndexforMaterial.push_back(38); gSponzaTextureIndexforMaterial.push_back(43); gSponzaTextureIndexforMaterial.push_back(44); gSponzaTextureIndexforMaterial.push_back(AO); // 19 : fabric_c (curtain_red) gSponzaTextureIndexforMaterial.push_back(41); gSponzaTextureIndexforMaterial.push_back(42); gSponzaTextureIndexforMaterial.push_back(43); gSponzaTextureIndexforMaterial.push_back(44); gSponzaTextureIndexforMaterial.push_back(AO); // 20 : fabric_f (curtain_green) gSponzaTextureIndexforMaterial.push_back(39); gSponzaTextureIndexforMaterial.push_back(40); gSponzaTextureIndexforMaterial.push_back(43); gSponzaTextureIndexforMaterial.push_back(44); gSponzaTextureIndexforMaterial.push_back(AO); // 21 : chain gSponzaTextureIndexforMaterial.push_back(12); gSponzaTextureIndexforMaterial.push_back(14); gSponzaTextureIndexforMaterial.push_back(13); gSponzaTextureIndexforMaterial.push_back(15); gSponzaTextureIndexforMaterial.push_back(AO); // 22 : vase_hanging gSponzaTextureIndexforMaterial.push_back(72); gSponzaTextureIndexforMaterial.push_back(73); gSponzaTextureIndexforMaterial.push_back(NoMetallic); gSponzaTextureIndexforMaterial.push_back(74); gSponzaTextureIndexforMaterial.push_back(AO); // 23 : vase gSponzaTextureIndexforMaterial.push_back(69); gSponzaTextureIndexforMaterial.push_back(70); gSponzaTextureIndexforMaterial.push_back(NoMetallic); gSponzaTextureIndexforMaterial.push_back(71); gSponzaTextureIndexforMaterial.push_back(AO); // 24 : Material__25 (lion) gSponzaTextureIndexforMaterial.push_back(16); gSponzaTextureIndexforMaterial.push_back(17); gSponzaTextureIndexforMaterial.push_back(NoMetallic); gSponzaTextureIndexforMaterial.push_back(18); gSponzaTextureIndexforMaterial.push_back(AO); // 25 : roof gSponzaTextureIndexforMaterial.push_back(63); gSponzaTextureIndexforMaterial.push_back(64); gSponzaTextureIndexforMaterial.push_back(NoMetallic); gSponzaTextureIndexforMaterial.push_back(65); gSponzaTextureIndexforMaterial.push_back(AO); } DEFINE_APPLICATION_MAIN(MaterialPlayground)
[ "jenkins@conffx.com" ]
jenkins@conffx.com
166c9bc9eca4139bc6328b0d2b47d76774b0e469
a722faf9fb50c794555861bb4858c3ed8a7a25f3
/contest/atcoder/abc061/A/main.cpp
8bfc270f11555c678822dc3dd336538a5735c8ab
[]
no_license
ar90n/lab
31e5d2c320de5618bc37572011596fee8923255d
6d035e12f743e9ba984e79bfe660967b9ca8716b
refs/heads/main
2023-07-25T17:29:57.960915
2023-07-22T12:08:18
2023-07-22T12:08:18
77,883,405
4
0
null
2023-07-17T08:45:14
2017-01-03T04:15:49
Jupyter Notebook
UTF-8
C++
false
false
392
cpp
#include <bits/stdc++.h> using namespace std; const string YES = "Yes"; const string NO = "No"; auto solve(long long A, long long B, long long C) { return ((A <= C) && (C <= B)) ? YES : NO; } int main() { long long A; scanf("%lld", &A); long long B; scanf("%lld", &B); long long C; scanf("%lld", &C); auto result = solve(A, B, C); cout << result << endl; return 0; }
[ "argon.argon.argon@gmail.com" ]
argon.argon.argon@gmail.com
b84b7ae4546d76a5ffb05ffef236f16c072eb71a
74a9456b605da15cbce5eefcfc22b2c049925d24
/mimosa/rpc/service.hh
308af70a6a577ba8356f4b28319ba86381ec442d
[ "MIT" ]
permissive
abique/mimosa
195ae693e2270fbfe9129b95b981946fab780d4e
87fff4dfce5f5a792bd7b93db3f3337e477aae76
refs/heads/master
2022-06-30T16:32:55.355008
2022-06-07T11:38:47
2022-06-07T11:38:47
2,087,313
27
8
MIT
2018-01-16T07:20:04
2011-07-22T05:40:03
C++
UTF-8
C++
false
false
893
hh
#pragma once # include <string> # include "../ref-countable.hh" # include "basic-call.hh" # include "protocol.hh" namespace mimosa { namespace rpc { class Channel; class Service : public RefCountable<Service>, private NonCopyable, private NonMovable { public: enum CallMethodStatus { kSucceed = rpc::kSucceed, kMethodNotFound = rpc::kMethodNotFound, kNotImplemented = rpc::kNotImplemented, kInvalidMsg = rpc::kInvalidMsg, }; virtual ~Service() {} virtual uint32_t id() const = 0; virtual const char * name() const = 0; protected: friend class Channel; virtual CallMethodStatus callMethod(BasicCall::Ptr call, const char * request_data, uint32_t request_size); }; } }
[ "bique.alexandre@gmail.com" ]
bique.alexandre@gmail.com
b67aa3b1415c67dcc58f860bd1d6b4a9a762efac
8cc95381e7c810f0ee4921fb2e6140748dd3ea57
/200_299/288_valid_word_abbr.h
fcd20c969585af1a03c0c86a98dcfe12122999c5
[]
no_license
wangchenwc/leetcode_cpp
5691fd6091050cd09ececfa94c02497f78b88293
6c0c847f25710781f40a2817cb0e0152002f1755
refs/heads/master
2020-04-22T02:36:02.836904
2018-11-08T06:13:00
2018-11-08T06:13:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
678
h
// // 288_valid_word_abbr.h // cpp_code // // Created by zhongyingli on 2018/8/7. // Copyright © 2018 zhongyingli. All rights reserved. // #ifndef _88_valid_word_abbr_h #define _88_valid_word_abbr_h class ValidWordAbbr { public: ValidWordAbbr(vector<string> &dictionary) { for (auto a : dictionary) { string k = a[0] + to_string(a.size() - 2) + a.back(); m[k].insert(a); } } bool isUnique(string word) { string k = word[0] + to_string(word.size() - 2) + word.back(); return m[k].count(word) == m[k].size(); } private: unordered_map<string, set<string>> m; }; #endif /* _88_valid_word_abbr_h */
[ "lizhongying@ofo.com" ]
lizhongying@ofo.com
1a066ee12e853a19468f6ba429cec514f87d5457
a64128622c6e44549b2c0822a9989ec0db9f167f
/015_3Sum.cpp
ea0685d9e6e941333eb4ff06aa2157669620cc3f
[]
no_license
liuxiangbin/LeetCode
86c022552cde1d16bc63d71c8ae4f3d5c5280425
47d1289128917f09b0dac1dbec6b8e22b584d3a8
refs/heads/master
2020-05-31T13:36:44.530459
2015-05-24T13:58:51
2015-05-24T13:58:51
25,041,683
1
0
null
null
null
null
UTF-8
C++
false
false
3,203
cpp
/* Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. Note: Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c) The solution set must not contain duplicate triplets. For example, given array S = {-1 0 1 2 -1 -4}, A solution set is: (-1, 0, 1) (-1, -1, 2) */ //Solution 1:O(N^2*lgN) class Solution { public: vector<vector<int> > threeSum(vector<int> &num) { vector<vector<int> > result; if(num.size() < 3) return result; sort(num.begin(),num.end()); if(num[0]>0 || num[num.size()-1] < 0) return result; typedef vector<int>::iterator itv; itv gap = num.begin(); for(;*gap<0;++gap); vector<int> one(3,0); if(gap+2<num.end()&&*(gap+2)==0) result.push_back(one); itv i = num.begin(),j; while(i < gap){ j = i + 1; while(j<gap){ if(binary_search(gap,num.end(),-(*i+*j))){ one[0] = *i; one[1] = *j; one[2] = -(*i+*j); result.push_back(one); } while(j+1<gap&&*(j+1)==*j) ++j; ++j; } while(i+1<gap&&*(i+1)==*i) ++i; ++i; } i = gap; while(i < num.end()){ j = i + 1; while(j<num.end()){ if(binary_search(num.begin(),gap,-(*i+*j))){ one[0] = -(*i+*j); one[1] = *i; one[2] = *j; result.push_back(one); } while(j+1<num.end()&&*(j+1)==*j) ++j; ++j; } while(i+1<num.end()&&*(i+1)==*i) ++i; ++i; } return result; } }; //Solution 2:O(N^2) class Solution { public: vector<vector<int> > threeSum(vector<int> &num) { vector<vector<int> > result; int len = num.size(); if(len < 3) return result; sort(num.begin(),num.end()); if(num[0]>0 || num[len-1] < 0) return result; vector<int> one(3,0); for(int i=0;i<len-2;++i){ int a = num[i]; int start = i+1, end = len-1; while(start < end){ int sum = a+num[start]+num[end]; if(sum == 0){ one[0] = a; one[1] = num[start]; one[2] = num[end]; result.push_back(one); while(start<end&&num[start+1]==num[start]) ++start; ++start; while(start<end&&num[end-1]==num[end]) --end; --end; } else if(sum < 0){ ++start; } else{ --end; } } while(num[i+1] == a) ++i; } return result; } };
[ "mycodekingdom@gmail.com" ]
mycodekingdom@gmail.com
5d4d1546b25c8845bca12341157b336bbc3cfebf
339f4d197f735089f85784dc6e853c5ac046aff8
/src/utils.cpp
9122d5c842ee2622a6d429a42b22619c981e2e63
[ "Apache-2.0" ]
permissive
nmaupu/yokis-hack
722d741109bb5c89de33d23f5e8335502cbb00f2
c876cd3e2a56de171a49c5d66bc662cedfa92443
refs/heads/master
2022-03-09T13:49:19.995083
2022-02-22T17:52:58
2022-02-22T17:52:58
227,478,708
15
5
Apache-2.0
2022-02-22T17:42:39
2019-12-11T23:19:52
C++
UTF-8
C++
false
false
510
cpp
#include "utils.h" #include "globals.h" #include <Arduino.h> void printBinaryRepresentation(uint8_t n, bool leadingZero = false) { char buf[8 * sizeof(uint8_t) + 1]; // Assumes 8-bit chars plus zero byte. char* str = &buf[sizeof(buf) - 1]; uint8_t nb = 0; *str = '\0'; do { nb++; char c = n % 2; n /= 2; *--str = c < 10 ? c + '0' : c + 'A' - 10; } while (n); while (nb++ < 8 && leadingZero) { *--str = '0'; } LOG.print(str); }
[ "nmaupu@gmail.com" ]
nmaupu@gmail.com
3c4eeb55916213284e124b19ad89d91090d8864c
0617d09a276ee6f59d2feffd4db4739677198178
/src/viewer/render_instances.cpp
e9c70cbe50e440663cb10220259ef9d6e085bca3
[ "MIT" ]
permissive
fanghao6666/visionaray
2d72fa7b35f66ccfe3fd332eb52786f9b6ef9aee
18364c521cad82c3d5a2bbfd462bddb43a1f6a52
refs/heads/master
2022-07-16T08:50:46.153614
2020-05-12T23:04:00
2020-05-12T23:04:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,285
cpp
// This file is distributed under the MIT license. // See the LICENSE file for details. #include <cassert> #include "render.h" namespace visionaray { void render_instances_cpp( index_bvh<index_bvh<basic_triangle<3, float>>::bvh_inst>& bvh, aligned_vector<vec3> const& geometric_normals, aligned_vector<vec3> const& shading_normals, aligned_vector<vec2> const& tex_coords, aligned_vector<generic_material_t> const& materials, aligned_vector<vec3> const& colors, aligned_vector<texture_t> const& textures, aligned_vector<generic_light_t> const& lights, unsigned bounces, float epsilon, vec4 bgcolor, vec4 ambient, host_device_rt& rt, host_sched_t<ray_type_cpu>& sched, camera_t const& cam, unsigned& frame_num, algorithm algo, unsigned ssaa_samples, host_environment_light const& env_light ) { using bvh_ref = index_bvh<index_bvh<basic_triangle<3, float>>::bvh_inst>::bvh_ref; aligned_vector<bvh_ref> primitives; primitives.push_back(bvh.ref()); if (env_light.texture()) { auto kparams = make_kernel_params( normals_per_vertex_binding{}, colors_per_vertex_binding{}, primitives.data(), primitives.data() + primitives.size(), geometric_normals.data(), shading_normals.data(), tex_coords.data(), materials.data(), colors.data(), textures.data(), lights.data(), lights.data() + lights.size(), env_light, bounces, epsilon ); call_kernel( algo, sched, kparams, frame_num, ssaa_samples, cam, rt ); } else { auto kparams = make_kernel_params( normals_per_vertex_binding{}, colors_per_vertex_binding{}, primitives.data(), primitives.data() + primitives.size(), geometric_normals.data(), shading_normals.data(), tex_coords.data(), materials.data(), colors.data(), textures.data(), lights.data(), lights.data() + lights.size(), bounces, epsilon, bgcolor, ambient ); call_kernel( algo, sched, kparams, frame_num, ssaa_samples, cam, rt ); } } } // visionaray
[ "info@szellmann.de" ]
info@szellmann.de
0204c1b3106fa8cb81795f46b875119cd008c3d5
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/CMake/CMake-gumtree/Kitware_CMake_repos_basic_block_block_13135.cpp
a91cb4303fc3990e4e9cf8112a3bcb3f266b37c3
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
510
cpp
{ unsigned char x; if (p[0] >= 'a' && p[0] <= 'z') x = (p[0] - 'a' + 0x0a) << 4; else if (p[0] >= 'A' && p[0] <= 'Z') x = (p[0] - 'A' + 0x0a) << 4; else if (p[0] >= '0' && p[0] <= '9') x = (p[0] - '0') << 4; else return (-1); if (p[1] >= 'a' && p[1] <= 'z') x |= p[1] - 'a' + 0x0a; else if (p[1] >= 'A' && p[1] <= 'Z') x |= p[1] - 'A' + 0x0a; else if (p[1] >= '0' && p[1] <= '9') x |= p[1] - '0'; else return (-1); *b++ = x; bsize--; p += 2; psize -= 2; }
[ "993273596@qq.com" ]
993273596@qq.com
4fddc89eb407acb61b9b8eb19d1f4ea79cbaaaba
b4660cc8fa3ce045508105fa52228a98fa19a87d
/src/usage_stats/usage_stats.h
4e009a18e689890d8118df7402c9007e79d05adf
[ "BSD-3-Clause", "LicenseRef-scancode-unicode", "LicenseRef-scancode-public-domain" ]
permissive
hnakamur/mozc-deb
81e9b561863e57da73aa9ba90d24ff5d0bca480b
a0d6db21786ae7fc54806714cbeca6c7c74cbd36
refs/heads/master
2021-04-15T09:32:03.635220
2018-05-04T10:09:23
2018-05-04T10:09:23
126,575,465
0
1
null
null
null
null
UTF-8
C++
false
false
4,504
h
// Copyright 2010-2016, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef MOZC_USAGE_STATS_USAGE_STATS_H_ #define MOZC_USAGE_STATS_USAGE_STATS_H_ #include <map> #include <string> #include <vector> #include "base/port.h" #include "usage_stats/usage_stats.pb.h" namespace mozc { namespace usage_stats { typedef std::map<uint32, Stats::TouchEventStats> TouchEventStatsMap; class UsageStats { public: // Updates count value // Increments val to current value static void IncrementCountBy(const string &name, uint32 val); static void IncrementCount(const string &name) { IncrementCountBy(name, 1); } // Updates timing value // Updates current value using given val static void UpdateTiming(const string &name, uint32 val); // Sets integer value // Replaces old value with val static void SetInteger(const string &name, int val); // Sets boolean value // Replaces old value with val static void SetBoolean(const string &name, bool val); // Returns true if given stats name is in the stats list // (for debugging) static bool IsListed(const string &name); // Stores virtual keyboard touch event stats. // The map "touch_stats" structure is as following // (keyboard_name_01 : (source_id_1 : TouchEventStats, // source_id_2 : TouchEventStats, // source_id_3 : TouchEventStats), // keyboard_name_02 : (source_id_1 : TouchEventStats, // source_id_2 : TouchEventStats, // source_id_3 : TouchEventStats)) static void StoreTouchEventStats( const string &name, const std::map<string, TouchEventStatsMap> &touch_stats); // Synchronizes (writes) usage data into disk. Returns false on failure. static bool Sync(); // Clears existing data exept for Integer and Boolean stats. static void ClearStats(); // Clears all data. static void ClearAllStatsForTest(); // NOTE: These methods are for unit tests. // Reads a value from registry, and sets it in the value. // Returns true if all steps go successfully. // NULL pointers are accetable for the target arguments of GetTimingForTest(). static bool GetCountForTest(const string &name, uint32 *value); static bool GetIntegerForTest(const string &name, int32 *value); static bool GetBooleanForTest(const string &name, bool *value); static bool GetTimingForTest(const string &name, uint64 *total_time, uint32 *num_timings, uint32 *avg_time, uint32 *min_time, uint32 *max_time); static bool GetVirtualKeyboardForTest(const string &name, Stats *stats); // This method doesn't check type of the stats. static bool GetStatsForTest(const string &name, Stats *stats); private: DISALLOW_IMPLICIT_CONSTRUCTORS(UsageStats); }; } // namespace usage_stats } // namespace mozc #endif // MOZC_USAGE_STATS_USAGE_STATS_H_
[ "hnakamur@gmail.com" ]
hnakamur@gmail.com
27233accce4b93ae5a7a5a62f2714977d349c38c
6f2b6e9d77fc4dd5e1dae8ba6e5a66eb7c7ae849
/sstd_boost/sstd/libs/chrono/example/test_clock.cpp
c08473c9955c5c70dd319285902480cac71c6e94
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
KqSMea8/sstd_library
9e4e622e1b01bed5de7322c2682539400d13dd58
0fcb815f50d538517e70a788914da7fbbe786ce1
refs/heads/master
2020-05-03T21:07:01.650034
2019-04-01T00:10:47
2019-04-01T00:10:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,609
cpp
// test_system_clock.cpp ----------------------------------------------------------// // Copyright 2008 Howard Hinnant // Copyright 2008 Beman Dawes // Copyright 2009 Vicente J. Botet Escriba // Distributed under the Boost Software License, Version 1.0. // See http://www.boost.org/LICENSE_1_0.txt /* This code was extracted by Vicente J. Botet Escriba from Beman Dawes time2_demo.cpp which was derived by Beman Dawes from Howard Hinnant's time2_demo prototype. Many thanks to Howard for making his code available under the Boost license. The original code was modified to conform to Boost conventions and to section 20.9 Time utilities [time] of the C++ committee's working paper N2798. See http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2798.pdf. time2_demo contained this comment: Much thanks to Andrei Alexandrescu, Walter Brown, Peter Dimov, Jeff Garland, Terry Golubiewski, Daniel Krugler, Anthony Williams. */ #include <sstd/boost/chrono/chrono.hpp> #include <sstd/boost/type_traits.hpp> #include <iostream> #include "clock_name.hpp" #if defined(BOOST_NO_CXX11_CONSTEXPR) using namespace boost::chrono; template <typename Clock> void test_clock() { std::cout << "\n"<< name<Clock>::apply() << " test" << std::endl; { typename Clock::duration delay = milliseconds(5); typename Clock::time_point start = Clock::now(); while (Clock::now() - start <= delay) ; typename Clock::time_point stop = Clock::now(); //typename Clock::duration elapsed = stop - start; std::cout << "5 milliseconds paused " << nanoseconds(stop - start).count() << " nanoseconds\n"; } { typename Clock::time_point start = Clock::now(); typename Clock::time_point stop; std::size_t counter=1; while ((stop=Clock::now()) == start) { ++counter; } //typename Clock::duration elapsed = stop - start; std::cout << "After " << counter << " trials, elapsed time " << nanoseconds(stop - start).count() << " nanoseconds\n"; start = Clock::now(); for (std::size_t c=counter; c>0; --c) { stop=Clock::now();; } std::cout << "After " << counter << " trials, elapsed time " << nanoseconds(stop - start).count() << " nanoseconds\n"; } { typename Clock::time_point start = Clock::now(); typename Clock::time_point stop = Clock::now(); std::cout << "Resolution estimate: " << nanoseconds(stop-start).count() << " nanoseconds\n"; } } void test_system_clock() { std::cout << "system_clock test" << std::endl; system_clock::duration delay = milliseconds(5); system_clock::time_point start = system_clock::now(); while (system_clock::now() - start <= delay) ; system_clock::time_point stop = system_clock::now(); system_clock::duration elapsed = stop - start; std::cout << "paused " << nanoseconds(elapsed).count() << " nanoseconds\n"; start = system_clock::now(); stop = system_clock::now(); std::cout << "system_clock resolution estimate: " << nanoseconds(stop-start).count() << " nanoseconds\n"; } void test_steady_clock() { #ifdef BOOST_CHRONO_HAS_CLOCK_STEADY std::cout << "steady_clock test" << std::endl; steady_clock::duration delay = milliseconds(5); steady_clock::time_point start = steady_clock::now(); while (steady_clock::now() - start <= delay) ; steady_clock::time_point stop = steady_clock::now(); steady_clock::duration elapsed = stop - start; std::cout << "paused " << nanoseconds(elapsed).count() << " nanoseconds\n"; start = steady_clock::now(); stop = steady_clock::now(); std::cout << "steady_clock resolution estimate: " << nanoseconds(stop-start).count() << " nanoseconds\n"; #endif } void test_hi_resolution_clock() { std::cout << "high_resolution_clock test" << std::endl; high_resolution_clock::duration delay = milliseconds(5); high_resolution_clock::time_point start = high_resolution_clock::now(); while (high_resolution_clock::now() - start <= delay) ; high_resolution_clock::time_point stop = high_resolution_clock::now(); high_resolution_clock::duration elapsed = stop - start; std::cout << "paused " << nanoseconds(elapsed).count() << " nanoseconds\n"; start = high_resolution_clock::now(); stop = high_resolution_clock::now(); std::cout << "high_resolution_clock resolution estimate: " << nanoseconds(stop-start).count() << " nanoseconds\n"; } //void test_mixed_clock() //{ // std::cout << "mixed clock test" << std::endl; // high_resolution_clock::time_point hstart = high_resolution_clock::now(); // std::cout << "Add 5 milliseconds to a high_resolution_clock::time_point\n"; // steady_clock::time_point mend = hstart + milliseconds(5); // bool b = hstart == mend; // system_clock::time_point sstart = system_clock::now(); // std::cout << "Subtracting system_clock::time_point from steady_clock::time_point doesn't compile\n"; //// mend - sstart; // doesn't compile // std::cout << "subtract high_resolution_clock::time_point from steady_clock::time_point" // " and add that to a system_clock::time_point\n"; // system_clock::time_point send = sstart + duration_cast<system_clock::duration>(mend - hstart); // std::cout << "subtract two system_clock::time_point's and output that in microseconds:\n"; // microseconds ms = send - sstart; // std::cout << ms.count() << " microseconds\n"; //} // //void test_c_mapping() //{ // std::cout << "C map test\n"; // using namespace boost::chrono; // system_clock::time_point t1 = system_clock::now(); // std::time_t c_time = system_clock::to_time_t(t1); // std::tm* tmptr = std::localtime(&c_time); // std::cout << "It is now " << tmptr->tm_hour << ':' << tmptr->tm_min << ':' << tmptr->tm_sec << ' ' // << tmptr->tm_year + 1900 << '-' << tmptr->tm_mon + 1 << '-' << tmptr->tm_mday << '\n'; // c_time = std::mktime(tmptr); // system_clock::time_point t2 = system_clock::from_time_t(c_time); // microseconds ms = t1 - t2; // std::cout << "Round-tripping through the C interface truncated the precision by " << ms.count() << " microseconds\n"; //} int main() { test_system_clock(); test_steady_clock(); test_hi_resolution_clock(); //test_mixed_clock(); test_clock<system_clock>(); #ifdef BOOST_CHRONO_HAS_CLOCK_STEADY test_clock<steady_clock>(); #endif test_clock<high_resolution_clock>(); return 0; } #else int main() { return 0; } #endif
[ "zhaixueqiang@hotmail.com" ]
zhaixueqiang@hotmail.com
0b2d091f95bdb2a1b02ee144d71c421a199aad8a
c98365913c93d4e35eebf94d15286aac9266b500
/src/hpp/dds/pub/find.hpp
55bce9af14bc0e95e8206ee5672342f05232e021
[]
no_license
sutambe/dds-psm-cxx
5646349fc317f215418c30806f58f411c8abb337
bababd36ed41f0bab0ddca8d60b5ea38e1a7900b
refs/heads/master
2021-01-16T19:34:56.119255
2011-11-08T16:23:41
2011-11-08T16:23:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,754
hpp
#ifndef OMG_DDS_PUB_FIND_HPP_ #define OMG_DDS_PUB_FIND_HPP_ /* Copyright 2010, Object Management Group, Inc. * Copyright 2010, PrismTech, Corp. * Copyright 2010, Real-Time Innovations, Inc. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <string> #include <dds/core/corefwd.hpp> #include <dds/pub/pubfwd.hpp> #include <dds/pub/detail/find.hpp> namespace dds { namespace pub { template <typename WRITER, typename FwdIterator> uint32_t find(const dds::pub::Publisher& pub, const std::string& topic_name, FwdIterator begin, uint32_t max_size) { return ::dds::pub::detail::find<WRITER, FwdIterator>(pub, topic_name, begin, max_size); } template <typename WRITER, typename BinIterator> uint32_t find(const dds::pub::Publisher& pub, const std::string& topic_name, BinIterator begin) { return ::dds::pub::detail::find<WRITER, BinIterator>(pub, topic_name, begin); } } } #endif /* OMG_DDS_PUB_FIND_HPP_ */
[ "angelo@icorsaro.net" ]
angelo@icorsaro.net
99d572e71f00142d252a97191bf84f9ae25f6de8
d7fa3dabaeec38d4d0efb32e0f7eb78ac13a879b
/bbgram/src/model/User.h
5350972877c671e6bd35f95f4f5e0a2e6b0349b4
[]
no_license
niko-lay/bbgram
1c5de80f44ae496f08ddc6f3e0dc74650f225731
f93c4c0ddea27317241b6505663df1b380219d3e
refs/heads/master
2021-01-12T12:59:43.400736
2018-04-30T22:18:33
2018-04-30T22:18:33
68,862,315
0
0
null
2016-09-21T22:19:00
2016-09-21T22:19:00
null
UTF-8
C++
false
false
1,906
h
#pragma once #include <QMap> #include <bb/cascades/Image> #include "Peer.h" class User : public Peer { Q_OBJECT Q_PROPERTY(QString phone READ phone NOTIFY phoneChanged) Q_PROPERTY(QString firstName READ firstName NOTIFY nameChanged) Q_PROPERTY(QString lastName READ lastName NOTIFY nameChanged) Q_PROPERTY(QString name READ name NOTIFY nameChanged) Q_PROPERTY(bool online READ online NOTIFY statusChanged) Q_PROPERTY(QDateTime lastSeen READ lastSeen NOTIFY statusChanged) Q_PROPERTY(QString lastSeenFormatted READ lastSeenFormatted NOTIFY statusChanged) Q_PROPERTY(QString typingStatus READ typingStatus NOTIFY typingStatusChanged) Q_PROPERTY(QString sortingKey READ sortingKey CONSTANT) Q_PROPERTY(QString color READ color CONSTANT) public: User(int id = 0); ~User(); void load(const QVariantMap& map); void save(QVariantMap& map) const; const QString& phone() const; void setPhone(const QString& phone); const QString& firstName() const; const QString& lastName() const; QString name() const; void setName(const QString& firstName, const QString& lastName); bool online() const; const QDateTime& lastSeen() const; QString lastSeenFormatted() const; QString status() const; void setStatus(bool online, const QDateTime& lastSeen); QString title() const; QString typingStatus() const; void setTypingStatus(tgl_typing_status status); const QString& sortingKey() const; QString color() const; public slots: void resetTypingStatus(); signals: void phoneChanged(); void nameChanged(); void statusChanged(); void typingStatusChanged(); protected: QString m_phone; QString m_firstName; QString m_lastName; bool m_online; QDateTime m_lastSeen; tgl_typing_status m_typingStatus; }; Q_DECLARE_METATYPE(User*);
[ "moadib73rus@gmail.com" ]
moadib73rus@gmail.com
ab8bc2ca0ea37f8ad96e18ba2689b4b4b1b99a5d
d364a3bf6f43a16ef6bf0ead96828dc671d6f554
/narcissist/include/narcissist/narcissist.hpp
451cf32b80d3defd632dda916a1617f538313217
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
twistys01/narcissist
8e22db53042625c88c0b10eeda644997632a34ec
5dff539a607a089135e2b433da0c01fc02ed3181
refs/heads/master
2020-03-28T19:11:42.895103
2018-03-31T10:06:13
2018-03-31T10:07:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
138
hpp
#pragma once #include <secp256k1.h> namespace Narcissist { extern secp256k1_context *secp256k1ctx; void setup(); void destroy(); }
[ "matthew@incognito.host" ]
matthew@incognito.host
0f51d8f25f7ce89113e968c6515b1af60b131e5a
58bffd767c9c2fb289c48217eb1f1a4a3b610e31
/cpp/junk.hpp
5bd3a4f46756b080a183700c4fcbc1b51f785e77
[]
no_license
Grahack/wisp-1
e4b443f7f0b819890f60902a1583248de2459dc6
9d97db7bc3b92d01f9fd61c097b4836714f8c4d9
refs/heads/master
2021-01-21T08:46:11.921038
2013-05-27T19:27:31
2013-05-27T19:27:31
14,207,988
2
0
null
null
null
null
UTF-8
C++
false
false
3,763
hpp
#pragma once // some code that i wrote, that may or may not become useful in the future #include "alloc.hpp" #include "object.hpp" #include <boost/functional/hash.hpp> namespace harkon { // hmm is this even useful? template<class T> class gc_alloc { public: // type definitions typedef T value_type; typedef T* pointer; typedef const T* const_pointer; typedef T& reference; typedef const T& const_reference; typedef std::size_t size_type; typedef std::ptrdiff_t difference_type; // rebind allocator to type U template<class U> struct rebind { typedef gc_alloc<U> other; }; // return address of values pointer address(reference value) const { return &value; } const_pointer address(const_reference value) const { return &value; } /* constructors and destructor * - nothing to do because the allocator has no state */ gc_alloc() throw () { } gc_alloc(const gc_alloc&) throw () { } template<class U> gc_alloc(const gc_alloc<U>&) throw () { } ~gc_alloc() throw () { } // return maximum number of elements that can be allocated size_type max_size() const throw () { return std::numeric_limits<std::size_t>::max() / sizeof(T); } // allocate but don't initialize num elements of type T pointer allocate(size_type num, const void* = 0) { return (pointer) (GC_ALLOC(num * sizeof(T))); } // initialize elements of allocated storage p with value value void construct(pointer p, const T& value) { // initialize memory with placement new new ((void*) p) T(value); } // destroy elements of initialized storage p void destroy(pointer p) { p->~T(); } // deallocate storage p of deleted elements void deallocate(pointer p, size_type num) { } }; // return that all specializations of this allocator are interchangeable template<class T1, class T2> bool operator==(const gc_alloc<T1>&, const gc_alloc<T2>&) throw () { return true; } template<class T1, class T2> bool operator!=(const gc_alloc<T1>&, const gc_alloc<T2>&) throw () { return false; } // TODO: should this be seeded? struct hash_value_visitor: boost::static_visitor<std::size_t> { std::size_t operator()(bool b) const { return boost::hash_value(b); } std::size_t operator()(char c) const { return boost::hash_value(c); } std::size_t operator()(int i) const { return boost::hash_value(i); } std::size_t operator()(nil n) const { return hash_value(n); } std::size_t operator()(symbol const& s) const { return hash_value(s); } std::size_t operator()(string const& ps) { return hash_value(ps); } std::size_t operator()(object_list const& pl) const { return hash_value(pl); } }; inline std::size_t hash_value(object const& o) { hash_value_visitor visitor; return boost::apply_visitor(visitor, o); } inline std::size_t hash_value(symbol const& s) { std::size_t seed = 0x3BB65E2A; // random arbitrary number boost::hash_combine(seed, hash_value(static_cast<persistent::string>(s))); return seed; } inline std::size_t hash_value(string const& s) { std::size_t seed = 0xEF13F20E; // random arbitrary number boost::hash_combine(seed, hash_value(static_cast<persistent::string>(s))); return seed; } inline std::size_t hash_value(object_list const& ol) { std::size_t seed = 0x4AA3BC2E; for (object_list::const_iterator it(ol.begin()); it != ol.end(); ++it) { boost::hash_combine(seed, hash_value(*it)); } return seed; } inline std::size_t hash_value(nil) { return 0x0DD63634; } }
[ "ericwspringer@gmail.com" ]
ericwspringer@gmail.com
4c2e61be146acb29f353dae7614bc772ce8a311d
b1d0b228332702856ad2cbee60874e39db368834
/EllipseDetectorLib/EllipseDetectorLib.h
39d17a49d642ccea6fedcb4178b5950901706570
[]
no_license
Jasionkit/EllipseDetectorLib
9ef5538dc35e4df4c787b8ebed2691cfa9f0c88c
660e60c464760349dc580ba02272b1f295064ad6
refs/heads/master
2021-06-20T20:50:26.953688
2017-03-12T19:27:07
2017-03-12T19:27:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,504
h
// EllipseDetectorLib.h #pragma once using namespace System; #include "EllipseResult.h" #include "ExecutionTime.h" #include <opencv2\opencv.hpp> using namespace std; using namespace cv; using namespace System; using namespace System::Drawing; using namespace System::Runtime::InteropServices; namespace EllipseDetectorLib { /* * EllipseDetector is the main class * This class implements a .NET wrapper of very fast ellipse detector, codename: YAED (Yet Another Ellipse Detector) */ public ref class EllipseDetector { public: EllipseDetector(System::String ^fileName); ~EllipseDetector(void); !EllipseDetector(); property System::String ^FileName { System::String ^get() { return _sFileName; } void set(System::String ^value) { if(_sFileName != nullptr) { delete _sFileName; } _sFileName = value; } } //System::Collections::Generic::List<EllipseResult ^> ^Search(); System::Tuple<System::Drawing::Size, System::Collections::Generic::List<EllipseResult^>^> ^EllipseDetector::Search(); property int ThLength { int get() { return _iThLength; } void set(int value) { _iThLength = value; } } property float ThObb { float get() { return _fThObb; } void set(float value) { _fThObb = value; } } property float ThPos { float get() { return _fThPos; } void set(float value) { _fThPos = value; } } property float TaoCenters { float get() { return _fTaoCenters; } void set(float value) { _fTaoCenters = value; } } property int Ns { int get() { return _iNs; } void set(int value) { _iNs = value; } } property float ThScoreScore { float get() { return _fThScoreScore; } void set(float value) { _fThScoreScore = value; } } property System::Drawing::Size PreProcessingGaussKernelSize { System::Drawing::Size get(){ return _pPreProcessingGaussKernelSize; } void set(System::Drawing::Size value){ _pPreProcessingGaussKernelSize = value; } } property float DistanceToEllipseContour { float get() { return _fDistanceToEllipseContour; } void set(float value) { _fDistanceToEllipseContour = value; } } property double PreProcessingGaussSigma { double get() { return _dPreProcessingGaussSigma; } void set(double value) { _dPreProcessingGaussSigma = value; } } property float MinReliability { float get() { return _fMinReliability; } void set(float value) { _fMinReliability = value; } } property ExecutionTime^ Execution { ExecutionTime^ get() { return _etExecutionTime; } } // TODO: Add your methods for this class here. private: System::Collections::Generic::List<EllipseResult^> ^_searchResults; System::Tuple<System::Drawing::Size, System::Collections::Generic::List<EllipseResult^>^> ^_result; System::String ^_sFileName; ExecutionTime ^ _etExecutionTime; // Parameters Settings (Sect. 4.2) int _iThLength; float _fThObb; float _fThPos; float _fTaoCenters; int _iNs; float _fThScoreScore; System::Drawing::Size _pPreProcessingGaussKernelSize;// Gaussian filter parameters, in pre-processing double _dPreProcessingGaussSigma; float _fDistanceToEllipseContour; // (Sect. 3.3.1 - Validation) float _fMinReliability; // Const parameters to discard bad ellipses*/ }; }
[ "desakov@diasoft.ru" ]
desakov@diasoft.ru
05025747a2dacb0ce35b88b00d3be57815a9b6b3
93c4ca4bee3964373e01e5b83b890b756c8258c2
/futures.h
4b95c3669c48efffb5ff6424bed4484d2b4acf26
[]
no_license
maierlars/agency-node
4b157144637e07b3bc9633895a5a538cad8a3257
55c39797bc4ce6086af4fc6d0a2b0be91fde696b
refs/heads/master
2021-07-01T10:59:42.520005
2021-02-26T14:39:18
2021-02-26T14:39:18
224,397,500
2
2
null
2019-12-30T12:22:16
2019-11-27T09:48:59
C++
UTF-8
C++
false
false
5,283
h
#ifndef AGENCY_NODE_FUTURES_H #define AGENCY_NODE_FUTURES_H #include <utility> #include <optional> #include <functional> #include <atomic> #include <memory> #include <mutex> #include <condition_variable> #include <cassert> #include "deserialize/types.h" struct scheduler { static void queue(std::function<void(void)> const& handler) noexcept { handler(); } }; template<typename T> struct promise; template<typename T> struct future; template<typename T> struct shared_state { enum class state { EMPTY, CALLBACK, VALUE, DONE }; shared_state(shared_state&&) = delete; shared_state(shared_state const&) = delete; shared_state& operator=(shared_state&&) = delete; shared_state& operator=(shared_state const&) = delete; template<typename S = T> explicit shared_state(S&& s) : _state(state::VALUE), _callback(), _value(std::forward<S>(s)) {} shared_state() noexcept = default; std::atomic<state> _state; std::function<void(T&&)> _callback; std::optional<T> _value; template<typename S = T> void setValue(S && s) noexcept { _value = std::forward<S>(s); transit<state::VALUE, state::CALLBACK>(); } void setCallback(std::function<void(T&&)> cb) noexcept { _callback = cb; transit<state::CALLBACK, state::VALUE>(); }; private: template<state A, state B> void transit() { state expected = state::EMPTY; if (_state.compare_exchange_strong(expected, A)) { return ; } assert(expected == B); if (_state.compare_exchange_strong(expected, state::DONE)) { _callback(std::move(*_value)); return; } assert(false); } }; template<typename T> std::pair<future<T>, promise<T>> make_promise() noexcept; template<typename T> future<T> make_future(T&&) noexcept; template<typename T> struct promise { promise() = delete; promise(promise const&) = default; promise(promise&&) noexcept = default; promise& operator=(promise const&) = delete; promise& operator=(promise&&) noexcept = default; void set(T t) && noexcept { state->setValue(std::move(t)); state.reset(); }; std::shared_ptr<shared_state<T>> state; private: explicit promise(std::shared_ptr<shared_state<T>> state) : state(std::move(state)) {} friend std::pair<future<T>, promise<T>> make_promise<T>() noexcept; }; template<typename> struct is_future : std::false_type {}; template<typename T> struct is_future<future<T>> : std::true_type {}; template<typename T> constexpr auto is_future_v = is_future<T>::value; template<typename> struct is_unit : std::false_type {}; template<> struct is_unit<unit_type> : std::true_type {}; template<typename T> constexpr auto is_unit_v = is_unit<T>::value; template<typename T> struct future { using return_type = T; future() = delete; future(future const&) = delete; future(future&&) noexcept = default; future& operator=(future const&) = delete; future& operator=(future&&) noexcept = default; std::shared_ptr<shared_state<T>> state; template<typename F, typename S = std::invoke_result_t<F, T&&>, std::enable_if_t<!is_future_v<S> && !std::is_void_v<S>, int> = 0> auto then(F&& f) && noexcept -> future<S> { auto [fp, p] = make_promise<S>(); state->setCallback([p = std::move(p), f = std::forward<F>(f)](T && t) mutable { std::move(p).set(f(std::move(t))); }); state.reset(); return std::move(fp); } template<typename F, typename S = std::invoke_result_t<F, T&&>, std::enable_if_t<std::is_void_v<S>, int> = 0> auto then(F&& f) && noexcept -> future<unit_type> { auto [fp, p] = make_promise<unit_type>(); state->setCallback([p = std::move(p), f = std::forward<F>(f)](T && t) mutable { f(std::move(t)); std::move(p).set(unit_type{}); }); state.reset(); return std::move(fp); } template<typename F, typename S = std::invoke_result_t<F, T&&>, std::enable_if_t<is_future_v<S>, int> = 0, typename R = typename S::return_type> auto then(F&& f) && noexcept -> future<R> { auto [fp, p] = make_promise<R>(); state->setCallback([p = std::move(p), f = std::forward<F>(f)](T && t) mutable { f(std::move(t)) .then([p = std::move(p)](R && r) mutable { std::move(p).set(std::move(r)); }); }); state.reset(); return std::move(fp); } // passes execution to the scheduler at this point of the stack trace auto reschedule() && noexcept -> future<T> { auto [f, p] = make_promise<T>(); this->then([p = std::move(p)](T&& t) mutable { scheduler::queue([p = std::move(p), t = std::move(t)]() mutable { std::move(p).set(std::move(t)); }); }); return f; } private: future(std::shared_ptr<shared_state<T>> state) : state(std::move(state)) {} friend future<T> make_future<T>(T&&) noexcept; friend std::pair<future<T>, promise<T>> make_promise<T>() noexcept; }; template<typename T> std::pair<future<T>, promise<T>> make_promise() noexcept { auto state = std::make_shared<shared_state<T>>(); return std::make_pair(future{state}, promise{state}); } template<typename T> future<T> make_future(T&& t) noexcept { auto state = std::make_shared<shared_state<T>>(std::forward<T>(t)); return future<T>{state}; } #endif // AGENCY_NODE_FUTURES_H
[ "lars@arangodb.com" ]
lars@arangodb.com
890e99b88e96542cbfeba8c70047c4a5ea18f4db
7f7cfa3b40507e72f0b38d99b8eecaee96664d96
/trunk/07-Source/Project/util.cpp
9be97cca3a50985243ee993745e87e39c817bbce
[]
no_license
BGCX067/faiq-svn-to-git
4c61568005a49f9e59dd638767f7659d0f723ed1
043cc825890b5febb6b9373f1e082c6ab5ab24a7
refs/heads/master
2016-09-01T08:56:54.756786
2015-12-28T14:21:15
2015-12-28T14:21:15
48,699,066
0
0
null
null
null
null
UTF-8
C++
false
false
28,305
cpp
/**************************************************************************//** * NAME: util.cpp * * PURPOSE: Searchmonkey reusable and miscellaneous functions. * * DATE: September 6, 2009 *******************************************************************************/ #include "debug.h" #include <QAbstractButton> #include <QComboBox> #include <QDesktopServices> #include <QDir> #include <QFileDialog> #include <QFileInfo> #include <QIcon> #include <QLineEdit> #include <QList> #include <QListWidget> #include <QMessageBox> #include <QObject> #include <QSettings> #include <QString> #include <QStringList> #include <QUrl> #include "util.h" /**************************************************************************//** * BoxConfirm(): Popup confirmation with option to not show again. * * Returns : true if user presses 'OK ', false if user presses 'Cancel' ******************************************************************************/ bool boxConfirm (const QString &_s, const QString &_title, QAbstractButton *again, const QMessageBox::Icon _icon) { QMessageBox msgBox; if (again != nullptr) msgBox.addButton(again, QMessageBox::ApplyRole); msgBox.setWindowModality(Qt::NonModal); msgBox.setText(_s); msgBox.setIcon(_icon); msgBox.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel); msgBox.setDefaultButton(QMessageBox::Cancel); msgBox.setWindowIcon(QIcon(SM_ICON)); if (!_title.isEmpty()) msgBox.setWindowTitle(_title); // // This is kind of a hack. Probably best to add checkbox to a QDialog. // bool ret = true; forever { switch(msgBox.exec()) { case QMessageBox::Ok: break; case QMessageBox::Cancel: ret = false; break; default: // checkbox clicked continue; // Q_ASSERT(0); // unlikely } break; } if (again != nullptr) msgBox.removeButton(again); return ret; } /**************************************************************************//** * BoxError(): Pop up an error message box. (Default - warning icon.) ******************************************************************************/ void boxError (const QString &_s, const QMessageBox::Icon _icon) { ENTEX("::boxError"); QMessageBox msgBox; msgBox.setText(_s); msgBox.setIcon(_icon); msgBox.setWindowIcon(QIcon(SM_ICON)); qd(3) << "calling exec() on message box..."; msgBox.exec(); } QString tr (const char *s) { return QObject::tr(s); } /**************************************************************************//** * Browse(): Advanced browse for target directory. * * Parms : _this - parent * b - keep mru dir for different browse operations * * Returns : user-selected directory, otherwise empty string ******************************************************************************/ QString browse (QWidget *_this, Browse b) { ENTEX("::browse"); QString mruSetting = tr("MainWindow/mruDir") + (b == SEARCH ? "" : b == CONTEXT ? tr("1") : tr("2")); QString parentSetting = tr("MainWindow/mruParent") + (b == SEARCH ? "" : b == CONTEXT ? tr("1") : tr("2")); QList<QUrl> urls; urls << QUrl::fromLocalFile(QDesktopServices::storageLocation( QDesktopServices::DesktopLocation)) << QUrl::fromLocalFile(QDesktopServices::storageLocation( QDesktopServices::DocumentsLocation)) << QUrl::fromLocalFile(QDesktopServices::storageLocation( QDesktopServices::HomeLocation)) << QUrl::fromLocalFile(QDir::rootPath()) << QUrl::fromLocalFile(QDir::currentPath()); QSettings settings; QString mru = settings.value(mruSetting, "").toString(); QString parent = settings.value(parentSetting, "").toString(); QFileDialog dialog(_this, QObject::tr("Select Directory"), !parent.isEmpty() ? parent : QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation)); dialog.setSidebarUrls(urls); dialog.setFileMode(QFileDialog::Directory); dialog.setViewMode(QFileDialog::Detail); dialog.setOptions(QFileDialog::ShowDirsOnly); qd(3) << "selecting file-" << mru; dialog.selectFile(mru); QStringList fileNames; if (dialog.exec()) fileNames = dialog.selectedFiles(); QString directory; if (!fileNames.isEmpty()) directory = fileNames[0]; if (!directory.isEmpty()) { QDir dir(directory); // save parent dir so it lists dir we want QString dbg; settings.setValue(parentSetting, dbg = dir.cd("..") ? dir.absolutePath() : directory); qd(3) << "set parent-" << dbg; settings.setValue(mruSetting, directory); } return directory; } /**************************************************************************//** * bytes2units(): Convert bytes to B, KB, MB, GB, ... * * parms : _size - bytes * * returns : '0 B' if _size < 0; otherwise, nice string like '724 KB' ******************************************************************************/ QString bytes2units (qint64 _size) { quint64 size = _size < 0 ? Q_UINT64_C(0) : static_cast<ull>(_size); (void)_size; char s[16]; for (int i = 0; i < 16; s[i++]='\0') ; if (size < KB) sprintf (s, "%d B ", static_cast<int>(size)); else if (size < MB) { sprintf (s, "%1.1lf KB ", static_cast<double>(size) / KB); // // enforce N KB not N.0 KB // /*string _s(s); string::size_type loc = _s.find(".0"); if (loc != string::npos) { _s.erase(loc, 2); sprintf (s, "%s", _s.c_str()); }*/ } else if (size < GB) sprintf (s, "%1.1lf MB ", static_cast<double>(size) / MB); else if (size < TB) sprintf (s, "%1.1lf GB ", static_cast<double>(size) / GB); else if (size < PB) sprintf (s, "%1.1lf TB ", static_cast<double>(size) / TB); else sprintf (s, "%1.1lf PB ", static_cast<double>(size) / PB); return QString(s); } /**************************************************************************//** * charS() : make a string plural. * * Parms : cond - condition for plurality. * * Returns : 's' if cond true, '\0' otherwise ******************************************************************************/ QChar charS (bool cond) { return cond ? QChar('s') : QChar('\0'); } /**************************************************************************//** * Chop(): wrapper with return val for: void QString::chop(). * * Parms: s - string to be chopped * n - chars to chop off end of s * * Returns: chopped QString ******************************************************************************/ QString chop (QString s, int n) { s.chop(n); return s; } /**************************************************************************//** * CountHits(): Count occurrences of regex in chunk of text. * * Parms : _rx - regular expression * _text - text which may contain pattern * * Returns : number of occurrences ******************************************************************************/ int countHits (const QRegExp &_rx, const QString &_text) { ENTEX("::countHits"); register int hits = 0, index = _text.indexOf(_rx); while (index >= 0) { ++hits; int length = _rx.matchedLength(); index = _text.indexOf(_rx, index + length); } qd(11) << "returning " << hits << " hits"; return hits; } /**************************************************************************//** * FileRemove(): remove file. * * Parms : s - optional ptr to hold error msg * * Returns : true on success, false otherwise ******************************************************************************/ bool fileRemove (QString path, bool prompt, QString *s) { ENTEX("::fileRemove"); QFile file(path); if (!file.exists(path)) { ::boxError(QObject::tr("File %1 does not exist: cannot remove").arg(path)); return false; } if (prompt && !::boxConfirm(QObject::tr("Delete file %1 from disk?").arg(path))) return false; if (!file.remove(path)) { ::boxError(QObject::tr("Could not remove file %1").arg(path)); if (s != nullptr) *s = file.errorString(); qd(0) << "QFile::remove() failed:" << file.errorString(); return false; } return true; } /**************************************************************************//** * Filepath2abspath(): convert list of QFileInfo objects to absolute paths. * * Parms : fil - list of QFileInfo objects * * Returns : list of canonical filepaths ******************************************************************************/ QStringList filepath2abspath (const QFileInfoList &fil) { QStringList files; for (register int i = 0, sz = fil.size(); i < sz; ++i) files << fil[i].canonicalFilePath(); return files; } /**************************************************************************//** * Filepath2abspath(): convert list of filenames to absolute paths. * * Parms : _files - list of filenames * _dir - a directory * * Returns : list of filepaths i.e. filenames w/ prepended directory ******************************************************************************/ QStringList filepath2abspath (const QStringList &_files, const QDir &_dir) { QStringList files; register int size = _files.size(); for (register int i = 0; i < size; ++i) files << _dir.absoluteFilePath(_files[i]); return files; } /**************************************************************************//** * GetLine(): get line from searchmonkey config file. * * Parms : _file - config file * * Returns : line as QString ******************************************************************************/ QString getLine (QFile &_file) { char buf[512]; memset (buf, '\0', sizeof(buf)); QString line; while (!_file.atEnd()) { _file.readLine(buf, sizeof(buf)); line = QString(buf); line = line.trimmed(); if (line.isEmpty() || line[0] == '#') continue; else break; } return line; } /**************************************************************************//** * int2syntax(): convert uint to QRegExp::PatternSyntax without relying on the * actual values of the enumerated type. We are relying on the * order of elements in the combobox (see the *.ui file): * 0 - RegExp * 1 - RegExp2 * 2 - Wildcard * 3 - Fixed * * parms : index - position in syntaxComboBox * * returns : QRegExp::PatternSyntax ******************************************************************************/ QRegExp::PatternSyntax int2syntax (int index) { switch (index) { case +0 : return QRegExp::RegExp; case +1 : return QRegExp::RegExp2; case +2 : return QRegExp::Wildcard; case +3 : return QRegExp::FixedString; case -1 : return QRegExp::RegExp; // empty or no selection default : Q_ASSERT(0); } return QRegExp::RegExp; } /**************************************************************************//** * IntMax(): converter for quint64 to int using limits.h header. * * Parms : i - qint64 * * Returns : i as int if i < INT_MAX, otherwise INT_MAX * i as int if i > INT_MIN, otherwise INT_MIN ******************************************************************************/ int intMax (qint64 i) { if (i > 0LL) { if (i < static_cast<qint64>(INT_MAX)) return static_cast<int>(i); else return INT_MAX; } else if (i < 0LL) { if (i > static_cast<qint64>(INT_MIN)) return static_cast<int>(i); else return INT_MIN; } else return 0; } /**************************************************************************//** * List2ListWidget(): populate list widget from string list. ******************************************************************************/ void list2ListWidget (const QStringList &sl, QListWidget *lw) { if (sl.isEmpty() || !lw) return; lw->clear(); lw->addItems(sl); } /**************************************************************************//** * ListIntersect(): find the intersection of two QString lists. * * Parms : list1 * list2 * * Returns : intersection QString list ******************************************************************************/ QStringList listIntersect (const QStringList &list1, const QStringList &list2){ if (list1.empty() || list2.empty()) return QStringList(); if (list1 == list2) return list1; QStringList intersection; for (register int i = 0, sz = list1.size(); i < sz; ++i) { if (list2.contains(list1.at(i))) intersection << list1.at(i); } return intersection; } /**************************************************************************//** * ListSubtract(): subtract one QFileInfo list from another: (list1 - list2) * * Parms : list1 - minuend * list2 - subtrahend * * Returns : difference QFileInfo list ******************************************************************************/ QFileInfoList listSubtract (const QFileInfoList &list1, const QFileInfoList &list2) { if (list2.empty()) return QFileInfoList(list1); if (list1.empty() || list1 == list2) return QFileInfoList(); QFileInfoList difference; for (register int i = 0, sz = list1.size(); i < sz; ++i) { if (list2.indexOf(list1.at(i)) == -1) difference << list1.at(i); } return difference; } /**************************************************************************//** * ListSubtract(): subtract one QString list from another: (list1 - list2) * * Parms : list1 - minuend * list2 - subtrahend * * Returns : difference QString list ******************************************************************************/ QStringList listSubtract (const QStringList &list1,const QStringList &list2) { if (list2.empty()) return QStringList(list1); if (list1.empty() || list1 == list2) return QStringList(); QStringList difference; for (register int i = 0, sz = list1.size(); i < sz; ++i) { if (list2.indexOf(list1.at(i)) == -1) difference << list1.at(i); } return difference; } /**************************************************************************//** * ListWidget2List(): populate string list from list widget. ******************************************************************************/ void listWidget2List (QListWidget *lw, QStringList *sl) { if (!lw || !sl) return; sl->clear(); int count = lw->count(); for (int i = 0; i < count; ++i) { QListWidgetItem * item = lw->item(i); QString data = (item->data(Qt::DisplayRole)).toString(); *sl << data; } } /**************************************************************************//** * MakePrintable(): Reduce a raw QString to only printable QChars. * * Parms : _s - raw QString * * Returns : printable QString ******************************************************************************/ QString makePrintable (const QString &_s) { QString s; s.resize(_s.size()); register int j = 0; for (register int i = 0, sz = _s.size(); i < sz; ++i) { if (_s.at(i).isPrint()) s[j++] = _s.at(i); } s.resize(j); return s; } /**************************************************************************//** * ms2units(): Convert milliseconds to common macro units w/ integer rounding. * Form: 'n <units> [n <units>]' * * parms : _ms - milliseconds (non-negative) * * returns : handy string like '1 min 2 sec', '24 sec', or '123 ms' ******************************************************************************/ QString ms2units (quint64 _ms) { #define scul(x) static_cast<unsigned long>(x) const quint64 sec = Q_UINT64_C(1000); // ms in sec const quint64 min = Q_UINT64_C(60000); // ms in min const quint64 hour = Q_UINT64_C(3600000); // ms in hour const quint64 day = Q_UINT64_C(86400000); // ms in day const quint64 month = Q_UINT64_C(2592000000); // ms in month const quint64 year = Q_UINT64_C(31104000000); // ms in year char s[32]; for (int i = 0; i < 32; s[i++]='\0') ; if (_ms < sec) sprintf (s, "%lu ms", scul(_ms)); else if (_ms < min) sprintf (s, "%lu sec", scul(_ms / sec)); else if (_ms < hour) sprintf (s, "%lu min %lu sec", scul(_ms / min), scul((_ms % min) / sec)); else if (_ms < day) sprintf (s, "%lu hour %lu min", scul(_ms / hour), scul((_ms % hour) / min)); else if (_ms < month) sprintf (s, "%lu day %lu hour", scul(_ms / day), scul((_ms % day) / hour)); else if (_ms < year) sprintf (s, "%lu month %lu day", scul(_ms / month), scul((_ms % month) / day)); else sprintf (s, "%lu year %lu month", scul(_ms / year), scul((_ms % year) / month)); return QString(s); } /***************************************************************************//** * FUNCTION: ParseDelim() * * PURPOSE: Separates a string into fields by setting delimiters to null. * * INPUT: str - ptr to string to be parsed * delims - ptr to string of possible delims * * OUTPUT: flds - buffer to hold parsed fields * n_found - fields parsed (optional) * * COMMENTS: Allocates memory to hold both the pointers to the parsed fields, as * well as the input string itself. This buffer is returned, and it is * the calling application's responsibilty to free the memory. The * size of memory equals: * * n_found * sizeof (char *) + strlen (str) + 1 - xmem * * RETURNS: flds - buffer holding parsed fields *******************************************************************************/ void* parseDelim (const char* str, const char* delims, char*** flds, int* n_found) { int fields = 1, // fields parsed xmem = 0; // accumulate extra mem from stripped chars /*------------------------------------------------------------------------* Inititialize pfix, optional number found parm; validate pointers; copy subject string into marching pointer; and save the start address. *------------------------------------------------------------------------*/ n_found ? *n_found = 0 : 0; if (!(delims && *delims) || !flds || !(str && *str)) return (0); char * s, // marching ptr * start; // sentinel ptr if (!(start = s = strdup (str))) { qDebug() << "strdup(" << str << ") failed"; return (0); } /*------------------------------------------------------------------------* Remove trailing CR, LF and SP. *------------------------------------------------------------------------*/ int tmp; strip (s, string (SM_CR + SM_LF + SM_SP).c_str(), &tmp); xmem += tmp; /*------------------------------------------------------------------------* Parse. The position pointer, s, points to the next segment to process. *------------------------------------------------------------------------*/ bool done = false; while (!done) { if ((s = strpbrk (s, delims))) { /*----------------------------------------------------------------* Strip trailing blanks from each field. *----------------------------------------------------------------*/ char * p = s; if (p > start && *(p - 1) == ' ') { while (p - 1 >= start && *(p - 1) == ' ') p--; if (s - p) { xmem += s - p; s = (char *) memmove (p, s, strlen (s) + 1); } } *s++ = '\0'; // define field fields++; } else done = true; } // while /*------------------------------------------------------------------------* Allocate the exact amount of memory needed. The input string now has embedded nulls to delineate the fields. Copy this string into the lower part of the allocated buffer. Align the respective pointers upstream in the same buffer. Return the entire buffer. *------------------------------------------------------------------------*/ int space; tmp = strlen (str) + 1 - xmem; if ((*flds = (char **) malloc (space = fields * sizeof (char *) + tmp))) { memset (*flds, '\0', space); memcpy (s = (char *) *flds + fields * sizeof (char *), start, tmp); for (int i = 0; i < fields; i++) { (*flds)[i] = s; s = strchr (s, '\0') + 1; } n_found ? *n_found = fields : 0; } else { *flds = (char **) 0; } free (start); return ((void *) *flds); } // ParseDelim() /***************************************************************************//** * FUNCTION: positionAtLine() * * PURPOSE: Position file ptr to end of line equal to given string. * * INPUT: _file - file * _s - string * * RETURNS: file ptr position ******************************************************************************/ qint64 positionAfterLine(QFile &_file, const QString &_string) { ENTEX("::positionAfterLine"); char buf[512]; bool found = false; while (!_file.atEnd()) { memset(buf, '\0', sizeof(buf)); _file.readLine(buf, sizeof(buf)); QString s(buf); s = s.trimmed(); qd(11) << "s-" << s; if (s[0] == '#') continue; if ((found = s == _string)) break; } if (!found) _file.write(("\n" + _string + "\n").toStdString().c_str()); return _file.pos(); } /**************************************************************************//** * StarDotAdd: prepend "*." to QStringList of non-wildcard extensions. ******************************************************************************/ QStringList starDotAdd (const QStringList &_sl) { QStringList sl; for (int i = 0, sz = _sl.size(); i < sz; ++i) sl << ("*." + _sl.at(i)); return sl; } /**************************************************************************//** * StarDotRemove: remove "*." from QStringList of wildcard extensions. ******************************************************************************/ QStringList starDotRemove (const QStringList &_sl) { QStringList sl; for (int i = 0, sz = _sl.size(); i < sz; ++i) sl << QString(_sl.at(i)).remove("*."); return sl; } /***************************************************************************//** * FUNCTION: strip() * * PURPOSE: Strip trailing garbage from a string. * * INPUT: ps - string address * g - garbage * n - length change (optional) * * OUTPUT: ps - stripped * * RETURNS: stripped string address ******************************************************************************/ string* strip (string* ps, const string& g, int* n) { if (!ps || g.empty()) return (ps); // while the last element in the string is garbage, erase it int n_ = 0; size_t i; while ((i = (*ps).size() - 1) > 0 && g.find_first_of (string (1, (*ps)[i])) != string::npos) { (*ps).erase (i); ++n_; } n ? *n = n_ : n_; return (ps); } char * strip (char * pz, const char * g, int * n) { if (!(pz || *pz) || !(g || *g)) return (pz); /*--------------------------------------------------------------------* (1) pass constructed string ptr and garbage ref to string version (2) dereference returned string ptr (3) call resultant string's member c_str() conversion function (4) copy returned buffer into original buffer (always exceeds or equals size of stripped buffer) *--------------------------------------------------------------------*/ string s_(pz); return (strcpy (pz, (*strip (&s_, string (g), n)).c_str())); } // strip() /**************************************************************************//** * units2bytes(): Convert B, KB, MB, GB, TB, PB to bytes. * * parms : _units : string - 'N <units>' eg. 123 KB * * returns : -1 on error, otherwise bytes ******************************************************************************/ qint64 units2bytes (const QString &_units) { ENTEX("::units2bytes"); if (_units.isEmpty() || _units.isNull()) return (-1); float mag; char buf[_units.size()]; // more than big enough sscanf(_units.toStdString().c_str(), "%f %s", &mag, buf); QString z = QString(QObject::tr("units2bytes(): mag- %1 units-'%2'")).arg(mag).arg(buf); qd(11) << z; (void)_units; if (mag < 0) return (-1); QString units(buf); if (units == "B") return static_cast<qint64>(mag); if (units == "KB") return static_cast<qint64>(mag * KB); if (units == "MB") return static_cast<qint64>(mag * MB); if (units == "GB") return static_cast<qint64>(mag * GB); if (units == "TB") return static_cast<qint64>(mag * TB); if (units == "PB") return static_cast<qint64>(mag * PB); return -1; } /**************************************************************************//** * UpdateComboBox(): update a combobox's history. ******************************************************************************/ void updateComboBox (QComboBox *comboBox) { if (comboBox->findText(comboBox->currentText()) == -1) comboBox->addItem(comboBox->currentText()); } /**************************************************************************//** * ValidDir(): Validate a Qstring as an existing dir. ******************************************************************************/ bool validDir (const QString &dir) { QFileInfo fi(dir); return fi.isDir(); } /**************************************************************************//** * ValidRx(): Validate a QRegExp as a valid regular expression. ******************************************************************************/ bool validRx (const QRegExp &rx) { return rx.isValid(); } /**************************************************************************//** * ValidRx(): Validate a QRegExp as a valid regular expression. ******************************************************************************/ bool validRx (QRegExp *rx) { return rx->isValid(); } /**************************************************************************//** * ValidRx(): Validate a Qstring as a valid regular expression. ******************************************************************************/ bool validRx (const QString &s, QRegExp::PatternSyntax syntax) { QRegExp rx(s); rx.setPatternSyntax(syntax); return rx.isValid(); } /**************************************************************************//** * ValidRx(): Validate a QstringList as a valid regular expression. ******************************************************************************/ bool validRx (const QStringList &_sl, QRegExp::PatternSyntax _syntax) { QList<QString>::const_iterator i = _sl.begin(); while (i != _sl.end()) { if (!validRx(*(i++), _syntax)) return false; } return true; }
[ "you@example.com" ]
you@example.com
775e53378c6a20fca8f804f25ec80f49d85f6623
5838cf8f133a62df151ed12a5f928a43c11772ed
/NT/base/cluster/mgmt/clusocm/ctaskupgradewin2k.h
36dbe12ee13f00db4834d3221c8d0634176f95a3
[]
no_license
proaholic/Win2K3
e5e17b2262f8a2e9590d3fd7a201da19771eb132
572f0250d5825e7b80920b6610c22c5b9baaa3aa
refs/heads/master
2023-07-09T06:15:54.474432
2021-08-11T09:09:14
2021-08-11T09:09:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,649
h
////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2000-2002 Microsoft Corporation // // Module Name: // CTaskUpgradeWin2k.h // // Description: // This file contains the declaration of the class CTaskUpgradeWindows2000. // This class represents the task of upgrading the cluster service on // a node that had Windows 2000 installed on it. // // Implementation Files: // CTaskUpgradeWin2k.cpp // // Maintained By: // David Potter (DavidP) 07-SEP-2001 // Vij Vasu (Vvasu) 26-JUL-2000 // ////////////////////////////////////////////////////////////////////////////// #pragma once ////////////////////////////////////////////////////////////////////////////// // Include Files ////////////////////////////////////////////////////////////////////////////// // For the base class #include "CTaskUpgrade.h" ////////////////////////////////////////////////////////////////////////////// // Forward Declarations ////////////////////////////////////////////////////////////////////////////// class CTaskUpgradeWindows2000; ////////////////////////////////////////////////////////////////////////////// // External Declarations ////////////////////////////////////////////////////////////////////////////// class CClusOCMApp; ////////////////////////////////////////////////////////////////////////////// //++ // // class CTaskUpgradeWindows2000 // // Description: // This class represents the task of upgrading the cluster service on // a node that had Windows 2000 installed on it. // //-- ////////////////////////////////////////////////////////////////////////////// class CTaskUpgradeWindows2000 : public CTaskUpgrade { public: ////////////////////////////////////////////////////////////////////////// // Public constructors and destructors ////////////////////////////////////////////////////////////////////////// // Constructor. CTaskUpgradeWindows2000( const CClusOCMApp & rAppIn ); // Destructor virtual ~CTaskUpgradeWindows2000( void ); ////////////////////////////////////////////////////////////////////////// // Message handlers ////////////////////////////////////////////////////////////////////////// // Handler for the OC_QUEUE_FILE_OPS message. virtual DWORD DwOcQueueFileOps( HSPFILEQ hSetupFileQueueIn ); // Handler for the OC_COMPLETE_INSTALLATION message. virtual DWORD DwOcCompleteInstallation( void ); // Handler for the OC_CLEANUP message. virtual DWORD DwOcCleanup( void ); protected: ////////////////////////////////////////////////////////////////////////// // Protected methods ////////////////////////////////////////////////////////////////////////// // Map ids specified in the INF file to actual directories. DWORD DwSetDirectoryIds( void ); private: ////////////////////////////////////////////////////////////////////////// // Forbidden methods ////////////////////////////////////////////////////////////////////////// // // Copying an object of this class is not allowed. // // Private copy constructor. CTaskUpgradeWindows2000( const CTaskUpgradeWindows2000 & ); // Private assignment operator. const CTaskUpgradeWindows2000 & operator =( const CTaskUpgradeWindows2000 & ); ////////////////////////////////////////////////////////////////////////// // Private types ////////////////////////////////////////////////////////////////////////// typedef CTaskUpgrade BaseClass; }; //*** class CTaskUpgradeWindows2000
[ "blindtiger@foxmail.com" ]
blindtiger@foxmail.com
4e2998e39d261a9b018eb789011d6875c0e8b631
45074cc0edde439faa782146c9a11ea40148b3b5
/src/chef/CookInfo.h
cbc3fc12b670284d7cc9149bc8ba7339c8f51eda
[ "Zlib" ]
permissive
modificus/gaen
246b91cb4e1bc535a27bab91f119c5f144fc8a89
c8368942acb3c61f1e38e8f3acf93c9ae3af5786
refs/heads/master
2021-01-15T11:44:30.165220
2016-08-27T10:08:29
2016-08-27T10:08:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,227
h
//------------------------------------------------------------------------------ // CookInfo.h - Describes a cooking operation, and its buffer result // // Gaen Concurrency Engine - http://gaen.org // Copyright (c) 2014-2016 Lachlan Orr // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // // 3. This notice may not be removed or altered from any source // distribution. //------------------------------------------------------------------------------ #ifndef GAEN_CHEF_COOK_INFO_H #define GAEN_CHEF_COOK_INFO_H #include "core/mem.h" #include "core/Set.h" #include "core/List.h" #include "core/String.h" #include "assets/Config.h" #include "assets/file_utils.h" namespace gaen { enum CookFlags { kCF_None = 0x00, kCF_CookingDependency = 0x01 }; typedef List<kMEM_Chef, String<kMEM_Chef>> RecipeList; class Chef; class CookInfo { public: CookInfo(Chef * pChef, CookFlags flags, const char * rawPath, const char * cookedPath, const char * gamePath, const RecipeList & recipes); ~CookInfo(); // Record a dependency, but don't cook it to include in the parent // asset. void recordDependency(char * depRawPath, char * gamePath, const char * path) const; // Cook a dependency with the intention of including the cooked // buffer in the parent asset. UniquePtr<CookInfo> cookDependency(const char * path) const; CookFlags flags() const { return mFlags; } const char * rawPath() const { return mRawPath; } const char * cookedPath() const { return mCookedPath; } const char * gamePath() const { return mGamePath; } const void * cookedBuffer() const { return mpCookedBuffer; } u64 cookedBufferSize() const { return mCookedBufferSize; } bool isCooked() const { return mpCookedBuffer != nullptr && mCookedBufferSize > 0; } void setCookedBuffer(void * pBuffer, u64 size) const; const Config<kMEM_Chef> & recipe() const { return mRecipe; } const Set<kMEM_Chef, String<kMEM_Chef>> & dependencies() const { return mDependencies; } private: Chef * mpChef; CookFlags mFlags; char mRawPath[kMaxPath+1]; char mCookedPath[kMaxPath+1]; char mGamePath[kMaxPath+1]; mutable void * mpCookedBuffer; mutable u64 mCookedBufferSize; Config<kMEM_Chef> mRecipe; mutable Set<kMEM_Chef, String<kMEM_Chef>> mDependencies; }; } // namespace gaen #endif // #ifndef GAEN_CHEF_COOK_INFO_H
[ "lorr@gaen.org" ]
lorr@gaen.org
7f7a042dfb5381934c453a5dc3c041ae1e5f04c0
9ca50ac301ca48e38503aea0c1bf45bdadc310e4
/src/cbor_serializer.cpp
7e1cbe019e18d3e096fed30b37dd813d8fe9356e
[]
no_license
zdzhaoyong/svar_rosbridge
c0484546e1ce33cf866f412eadca9ecc80c0a921
10e7734776034bd2fd007f7867b696b4e4d4b9a8
refs/heads/master
2023-07-12T22:10:02.580484
2021-08-08T06:45:50
2021-08-08T06:45:50
383,981,892
7
0
null
null
null
null
UTF-8
C++
false
false
14,394
cpp
#include "Svar.h" using namespace sv; struct cbor_serializer final{ struct OSize{ template <typename T> OSize& operator <<(const T& c){ sz+=sizeof(T); return *this; } void write(const char* s,size_t length){ sz+=length; } size_t sz=0; }; struct OStream{ OStream(std::vector<char>& ost):o(ost),reverse(little_endianess()),ptr(ost.data()){} OStream& operator <<(char c){ *(ptr++)=c; return *this; } template <typename T> OStream& operator <<(const T& c){ std::array<char,sizeof(T)>& a=*(std::array<char,sizeof(T)>*)ptr; memcpy(a.data(),&c,sizeof(T)); if(reverse){ std::reverse(a.begin(), a.end()); } ptr+=sizeof(T); return *this; } void write(const char* s,size_t length){ memcpy(ptr,s,length); ptr+=length; } static constexpr bool little_endianess() noexcept { return 0x78 == (char)0x12345678; } std::vector<char>& o; bool reverse; char* ptr; }; struct IStream{ IStream(SvarBuffer& ist):i(ist),reverse(OStream::little_endianess()),ptr((const char*)i._ptr){} template<typename T> IStream& operator >>(T & c){ if(reverse){ std::array<char,sizeof(T)>& a=*(std::array<char,sizeof(T)>*)&c; memcpy(a.data(),ptr,a.size()); std::reverse(a.begin(),a.end()); } else memcpy(&c,ptr,sizeof(T)); ptr+=sizeof(T); return *this; } const void* read(size_t sz){ const void* ret=ptr; ptr+=sz; return ret; } SvarBuffer& i; const char* ptr; bool reverse; }; static Svar load(SvarBuffer input){ IStream i(input); return loadStream(i); } static Svar loadStream(IStream& i){ typedef unsigned char u_char; static std::vector<std::function<Svar(u_char,IStream&)> > funcs; if(funcs.empty()){ funcs.resize(256); for(int it=0;it<256;it++)funcs[it]=[](u_char c,IStream& i){return Svar::Undefined();}; for(u_char it=0;it<=0x17;it++) funcs[it]=[](u_char c,IStream& i){return Svar((int)c);}; funcs[0x18]=[](u_char c,IStream& i){uint8_t v;i>>v;return Svar((int)v);}; funcs[0x19]=[](u_char c,IStream& i){uint16_t v;i>>v;return Svar((int)v);}; funcs[0x1A]=[](u_char c,IStream& i){uint32_t v;i>>v;return Svar((int)v);}; funcs[0x1B]=[](u_char c,IStream& i){uint64_t v;i>>v;return Svar((int)v);};//positive int for(u_char it=0x20;it<=0x37;it++) funcs[it]=[](u_char c,IStream& i){return Svar((int)(-1-(c-0x20)));}; funcs[0x38]=[](u_char c,IStream& i){uint8_t v;i>>v;return Svar((int)(-1-v));}; funcs[0x39]=[](u_char c,IStream& i){uint16_t v;i>>v;return Svar((int)(-1-v));}; funcs[0x3A]=[](u_char c,IStream& i){uint32_t v;i>>v;return Svar((int)(-1-v));}; funcs[0x3B]=[](u_char c,IStream& i){uint64_t v;i>>v;return Svar((int)(-1-v));};//negative int for(u_char it=0x40;it<=0x5F;it++) funcs[it]=[](u_char c,IStream& i){ int len = funcs[c-0x40](c-0x40,i).as<int>(); std::string* buf=new std::string((char*)i.read(len),len); return Svar::create(SvarBuffer(buf->data(),buf->size(),std::unique_ptr<std::string>(buf))); };//binary string for(u_char it=0x60;it<=0x7B;it++) funcs[it]=[](u_char c,IStream& i){ int len = funcs[c-0x60](c-0x60,i).as<int>(); return Svar(std::string((char*)i.read(len),len)); };//string for(u_char it=0x80;it<=0x9B;it++) funcs[it]=[](u_char c,IStream& i){ int len = funcs[c-0x80](c-0x80,i).as<int>(); std::vector<Svar> vec(len); for(int j=0;j<len;j++){ uint8_t t;i>>t; vec[j]=funcs[t](t,i); } return Svar(vec); };//array for(u_char it=0xA0;it<=0xBB;it++) funcs[it]=[](u_char c,IStream& i){ int len = funcs[c-0xA0](c-0xA0,i).as<int>(); std::map<std::string,Svar> m; for(int j=0;j<len;j++){ uint8_t t1,t2; i>>t1; Svar f=funcs[t1](t1,i); i>>t2; m[f.castAs<std::string>()]=funcs[t2](t2,i); } return Svar(m); };//map funcs[0xF4]=[](u_char c,IStream& i){return Svar(false);};//false funcs[0xF5]=[](u_char c,IStream& i){return Svar(true);};//true funcs[0xF6]=[](u_char c,IStream& i){return Svar::Null();};//null funcs[0xFB]=[](u_char c,IStream& i){double d;i>>d;return Svar(d);};//double } u_char c; i>>c; return funcs[c](c,i); } static SvarBuffer dump(Svar var){ OSize sz; dumpStream(sz,var); std::vector<char>* ret=new std::vector<char>(); ret->resize(sz.sz); OStream ost(*ret); dumpStream(ost,var); return SvarBuffer(ret->data(),ret->size(),std::unique_ptr<std::vector<char>>(ret)); } static char c(std::uint8_t x){return *reinterpret_cast<char*>(&x);} template <typename T> static T& dumpStream(T& o,Svar var) { if(var.isUndefined()||var.isNull()) return o<<c(0xF6); if(var.is<bool>()) return o<<(var.as<bool>()? c(0xF5) : c(0xF4)); if(var.is<double>()) return o<<c(0xFB)<<var.as<double>(); if(var.is<int>()) { const int& v=var.as<int>(); if (v >= 0) { if (v <= 0x17) { return o<<c(static_cast<std::uint8_t>(v)); } else if (v <= (std::numeric_limits<std::uint8_t>::max)()) { return o<<c(0x18)<<c(static_cast<std::uint8_t>(v)); } else if (v <= (std::numeric_limits<std::uint16_t>::max)()) { return o<<c(0x19)<<(static_cast<std::uint16_t>(v)); } else if (v <= (std::numeric_limits<std::uint32_t>::max)()) { return o<<c(0x1A)<<static_cast<std::uint32_t>(v); } else// this never happens { return o<<c(0x1B)<<static_cast<std::uint64_t>(v); } } else { // The conversions below encode the sign in the first // byte, and the value is converted to a positive number. const auto n = -1 - v; if (v >= -24) { return o<<static_cast<std::uint8_t>(0x20 + n); } else if (n <= (std::numeric_limits<std::uint8_t>::max)()) { return o<<c(0x38)<<static_cast<std::uint8_t>(n); } else if (n <= (std::numeric_limits<std::uint16_t>::max)()) { return o<<c(0x39)<<static_cast<std::uint16_t>(n); } else if (n <= (std::numeric_limits<std::uint32_t>::max)()) { return o<<c(0x3A)<<static_cast<std::uint32_t>(n); } else { return o<<c(0x3B)<<static_cast<std::uint64_t>(n); } } } if(var.is<SvarBuffer>()){ SvarBuffer& s=var.as<SvarBuffer>(); const auto N = s.length(); if (N <= 0x17) { o<<c(static_cast<std::uint8_t>(0x40 + N)); } else if (N <= (std::numeric_limits<std::uint8_t>::max)()) { o<<c(0x58)<<(static_cast<std::uint8_t>(N)); } else if (N <= (std::numeric_limits<std::uint16_t>::max)()) { o<<c(0x59)<<static_cast<std::uint16_t>(N); } else if (N <= (std::numeric_limits<std::uint32_t>::max)()) { o<<c(0x5A)<<static_cast<std::uint32_t>(N); } // LCOV_EXCL_START else if (N <= (std::numeric_limits<std::uint64_t>::max)()) { o<<c(0x5B)<<(static_cast<std::uint64_t>(N)); } // LCOV_EXCL_STOP // step 2: write the string o.write(reinterpret_cast<const char*>(s._ptr),N); return o; } if(var.is<std::string>()) { // step 1: write control byte and the string length std::string& s=var.as<std::string>(); const auto N = s.size(); if (N <= 0x17) { o<<c(static_cast<std::uint8_t>(0x60 + N)); } else if (N <= (std::numeric_limits<std::uint8_t>::max)()) { o<<c(0x78)<<(static_cast<std::uint8_t>(N)); } else if (N <= (std::numeric_limits<std::uint16_t>::max)()) { o<<c(0x79)<<static_cast<std::uint16_t>(N); } else if (N <= (std::numeric_limits<std::uint32_t>::max)()) { o<<c(0x7A)<<static_cast<std::uint32_t>(N); } // LCOV_EXCL_START else if (N <= (std::numeric_limits<std::uint64_t>::max)()) { o<<c(0x7B)<<(static_cast<std::uint64_t>(N)); } // LCOV_EXCL_STOP // step 2: write the string o.write(reinterpret_cast<const char*>(s.data()),N); return o; } if(var.isArray()) { std::vector<Svar>& vec=var.as<SvarArray>()._var; const auto N = vec.size(); if (N <= 0x17) { o<<c(static_cast<std::uint8_t>(0x80 + N)); } else if (N <= (std::numeric_limits<std::uint8_t>::max)()) { o<<c(0x98)<<(static_cast<std::uint8_t>(N)); } else if (N <= (std::numeric_limits<std::uint16_t>::max)()) { o<<c(0x99)<<static_cast<std::uint16_t>(N); } else if (N <= (std::numeric_limits<std::uint32_t>::max)()) { o<<c(0x9A)<<static_cast<std::uint32_t>(N); } // LCOV_EXCL_START else if (N <= (std::numeric_limits<std::uint64_t>::max)()) { o<<c(0x9B)<<static_cast<std::uint64_t>(N); } // LCOV_EXCL_STOP // step 2: write each element for (const auto& el : vec) { dumpStream(o,el); } return o; } if(var.isObject()) { auto& obj=var.as<SvarObject>()._var; const auto N = obj.size(); if (N <= 0x17) { o<<(static_cast<std::uint8_t>(0xA0 + N)); } else if (N <= (std::numeric_limits<std::uint8_t>::max)()) { o<<c(0xB8)<<(static_cast<std::uint8_t>(N)); } else if (N <= (std::numeric_limits<std::uint16_t>::max)()) { o<<c(0xB9)<<(static_cast<std::uint16_t>(N)); } else if (N <= (std::numeric_limits<std::uint32_t>::max)()) { o<<c(0xBA)<<(static_cast<std::uint32_t>(N)); } // LCOV_EXCL_START else if (N <= (std::numeric_limits<std::uint64_t>::max)()) { o<<c(0xBB)<<(static_cast<std::uint64_t>(N)); } // LCOV_EXCL_STOP // step 2: write each element for (const auto& el : obj) { dumpStream(o,el.first); dumpStream(o,el.second); } return o; } Svar func_buffer=var.classPtr()->_attr["__buffer__"]; if(func_buffer.isFunction()){ dumpStream(o,func_buffer(var)); } throw SvarExeption("Unable dump cbor for type " + var.typeName()); } }; REGISTER_SVAR_MODULE(cbor){ sv::Class<cbor_serializer>("cbor_serializer") .def_static("load",&cbor_serializer::load) .def_static("dump",&cbor_serializer::dump); svar["serializers"]["cbor"]=cbor_serializer(); }
[ "zd5945@126.com" ]
zd5945@126.com
72f532c2fe42837e95ea871bf172b864298e4c5c
5e8d200078e64b97e3bbd1e61f83cb5bae99ab6e
/main/source/src/protocols/jd3/chunk_library_inputters/PDBChunkLibraryInputter.hh
570b086b554ed6448f8073cfdf6d99ae400880a5
[]
no_license
MedicaicloudLink/Rosetta
3ee2d79d48b31bd8ca898036ad32fe910c9a7a28
01affdf77abb773ed375b83cdbbf58439edd8719
refs/heads/master
2020-12-07T17:52:01.350906
2020-01-10T08:24:09
2020-01-10T08:24:09
232,757,729
2
6
null
null
null
null
UTF-8
C++
false
false
3,330
hh
// -*- mode:c++;tab-width:2;indent-tabs-mode:t;show-trailing-whitespace:t;rm-trailing-spaces:t -*- // vi: set ts=2 noet: // // (c) Copyright Rosetta Commons Member Institutions. // (c) This file is part of the Rosetta software suite and is made available under license. // (c) The Rosetta software is developed by the contributing members of the Rosetta Commons. // (c) For more information, see http://www.rosettacommons.org. Questions about this can be // (c) addressed to University of Washington CoMotion, email: license@uw.edu. /// @file protocols/jd3/chunk_library_inputters/PDBChunkLibraryInputter.hh /// @brief Declaration of the %PDBChunkLibraryInputter class for initializing Poses from .pdb or .pdb.gz files /// @author Andrew Leaver-Fay (aleaverfay@gmail.com) /// @author Steven Lewis (smlewi@gmail.com) #ifndef INCLUDED_protocols_jd3_chunk_library_inputters_PDBChunkLibraryInputter_HH #define INCLUDED_protocols_jd3_chunk_library_inputters_PDBChunkLibraryInputter_HH // Unit headers #include <protocols/jd3/chunk_library_inputters/PDBChunkLibraryInputter.fwd.hh> // Package headers #include <protocols/jd3/chunk_library_inputters/ChunkLibraryInputter.hh> // Project headers #include <core/pose/Pose.fwd.hh> //utility headers #include <utility/options/keys/OptionKey.fwd.hh> #include <utility/vector1.hh> #include <utility/tag/Tag.fwd.hh> #include <utility/tag/XMLSchemaGeneration.fwd.hh> namespace protocols { namespace jd3 { namespace chunk_library_inputters { /// @brief This is the simplest implementation of ChunkLibraryInputter, which reads from -s/-l and PDB files. class PDBChunkLibraryInputter : public ChunkLibraryInputter { public: PDBChunkLibraryInputter(); virtual ~PDBChunkLibraryInputter(); bool job_available_on_command_line() const override; /// @brief Constructs a list of ChunkLibraryInputSource objects reading from the /// -s or -l command line flags. This stores the names of the PDBs that /// are to be read in, and it initializes the input tags based on the pdb /// names, stripping the path and the extension from the file name. ChunkLibraryInputSources chunk_library_input_sources_from_command_line() override; ChunkLibraryInputSources chunk_library_input_sources_from_tag( utility::options::OptionCollection const & opts, utility::tag::TagCOP tag ) override; /// @brief Takes a ChunkLibraryInputSource object previously initialized in the /// call to initialize_chunk_library_input_sources() core::pose::PoseOP chunk_library_from_input_source( ChunkLibraryInputSource const &, utility::options::OptionCollection const &, utility::tag::TagCOP tag // possibly null-pointing tag pointer ) override; /// @brief returns the name for the element that will be used in a job-definition /// file for a structure originating from a .pdb file: "PDB" static std::string keyname(); /// @brief returns the schema for the PDB element used in a job-definition file /// including all options that govern how a PDB is loaded. static void provide_xml_schema( utility::tag::XMLSchemaDefinition & xsd ); static void list_options_read( utility::options::OptionKeyList & read_options ); }; // PDBChunkLibraryInputter } // namespace chunk_library_inputters } // namespace jd3 } // namespace protocols #endif //INCLUDED_protocols_jd3_PDBChunkLibraryInputter_HH
[ "36790013+MedicaicloudLink@users.noreply.github.com" ]
36790013+MedicaicloudLink@users.noreply.github.com
c8b1f41e9212d2ed1c055f76062146d7e825bbfb
415ecd6b3ea44dca3ad675b0f17ea145583c17d5
/base_station/receive_function.cpp
41a15f0dd989fa55ecf34d228ef9a011a4995098
[]
no_license
zappyfish/upes-nicky-boi
e7e6dc25da365ae47f1240a840901b90b6c93b3c
830a7f2083379a2832fb040d6c93ae2ef75957d7
refs/heads/master
2020-04-25T05:24:10.140349
2019-02-25T16:29:34
2019-02-25T16:29:34
172,541,715
0
0
null
null
null
null
UTF-8
C++
false
false
544
cpp
// // Created by Liam Kelly on 2/23/19. // #include "receive_function.h" ReceiveFunction::ReceiveFunction(char *name, void (*action)(Packet*)) : mName(name), mAction(action){} ReceiveFunction::ReceiveFunction(ReceiveFunction &toCopy) : mName(toCopy.mName), mAction(toCopy.mAction) {} ReceiveFunction::~ReceiveFunction() {} ReceiveFunction& ReceiveFunction::operator=(const ReceiveFunction &rhs) { mName = rhs.mName; mAction = rhs.mAction; return *this; } void ReceiveFunction::receive(Packet &packet) { mAction(&packet); }
[ "liamkelly2015@gmail.com" ]
liamkelly2015@gmail.com
9b00144b6ff5ba8a7046002ba65dd0d05800acbb
600df3590cce1fe49b9a96e9ca5b5242884a2a70
/mash/screenlock/screenlock.cc
17cf4f97df6acd57f6f918d892569c92d066f412
[ "BSD-3-Clause" ]
permissive
metux/chromium-suckless
efd087ba4f4070a6caac5bfbfb0f7a4e2f3c438a
72a05af97787001756bae2511b7985e61498c965
refs/heads/orig
2022-12-04T23:53:58.681218
2017-04-30T10:59:06
2017-04-30T23:35:58
89,884,931
5
3
BSD-3-Clause
2022-11-23T20:52:53
2017-05-01T00:09:08
null
UTF-8
C++
false
false
3,789
cc
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "mash/screenlock/screenlock.h" #include "ash/public/interfaces/container.mojom.h" #include "base/macros.h" #include "base/strings/utf_string_conversions.h" #include "mash/session/public/interfaces/session.mojom.h" #include "mojo/public/cpp/bindings/binding.h" #include "services/shell/public/cpp/connector.h" #include "services/ui/public/cpp/property_type_converters.h" #include "ui/views/background.h" #include "ui/views/controls/button/md_text_button.h" #include "ui/views/mus/aura_init.h" #include "ui/views/mus/native_widget_mus.h" #include "ui/views/mus/window_manager_connection.h" #include "ui/views/widget/widget_delegate.h" namespace mash { namespace screenlock { namespace { class ScreenlockView : public views::WidgetDelegateView, public views::ButtonListener { public: explicit ScreenlockView(shell::Connector* connector) : connector_(connector), unlock_button_( views::MdTextButton::Create(this, base::ASCIIToUTF16("Unlock"))) { set_background(views::Background::CreateSolidBackground(SK_ColorYELLOW)); AddChildView(unlock_button_); } ~ScreenlockView() override {} private: // Overridden from views::WidgetDelegate: base::string16 GetWindowTitle() const override { // TODO(beng): use resources. return base::ASCIIToUTF16("Screenlock"); } // Overridden from views::View: void Layout() override { gfx::Rect bounds = GetLocalBounds(); bounds.Inset(10, 10); gfx::Size ps = unlock_button_->GetPreferredSize(); bounds.set_height(bounds.height() - ps.height() - 10); unlock_button_->SetBounds(bounds.width() - ps.width(), bounds.bottom() + 10, ps.width(), ps.height()); } // Overridden from views::ButtonListener: void ButtonPressed(views::Button* sender, const ui::Event& event) override { DCHECK_EQ(sender, unlock_button_); mash::session::mojom::SessionPtr session; connector_->ConnectToInterface("service:mash_session", &session); session->UnlockScreen(); } shell::Connector* connector_; views::MdTextButton* unlock_button_; DISALLOW_COPY_AND_ASSIGN(ScreenlockView); }; } // namespace Screenlock::Screenlock() {} Screenlock::~Screenlock() {} void Screenlock::OnStart(const shell::Identity& identity) { tracing_.Initialize(connector(), identity.name()); mash::session::mojom::SessionPtr session; connector()->ConnectToInterface("service:mash_session", &session); session->AddScreenlockStateListener( bindings_.CreateInterfacePtrAndBind(this)); aura_init_.reset( new views::AuraInit(connector(), "views_mus_resources.pak")); window_manager_connection_ = views::WindowManagerConnection::Create(connector(), identity); views::Widget* widget = new views::Widget; views::Widget::InitParams params( views::Widget::InitParams::TYPE_WINDOW_FRAMELESS); params.delegate = new ScreenlockView(connector()); std::map<std::string, std::vector<uint8_t>> properties; properties[ash::mojom::kWindowContainer_Property] = mojo::ConvertTo<std::vector<uint8_t>>( static_cast<int32_t>(ash::mojom::Container::LOGIN_WINDOWS)); ui::Window* window = views::WindowManagerConnection::Get()->NewWindow(properties); params.native_widget = new views::NativeWidgetMus( widget, window, ui::mojom::SurfaceType::DEFAULT); widget->Init(params); widget->Show(); } void Screenlock::ScreenlockStateChanged(bool screen_locked) { if (!screen_locked) base::MessageLoop::current()->QuitWhenIdle(); } } // namespace screenlock } // namespace mash
[ "enrico.weigelt@gr13.net" ]
enrico.weigelt@gr13.net
b936314a44822a6a43b314d0f0ecc98e220bf826
59ad83925bd1ffb3f3b6248ddf317921ed2bb24b
/ATATool/PropertyPageBT.cpp
66d618c38fc1044d33e586b461f450a2b7f57d5b
[]
no_license
momoomom/ATA
f5cb01615b2b662d54ec834c95d7d5921ab96c7c
92489654d21c61b8a5cc6f62b790ddfa6448e704
refs/heads/master
2021-12-11T13:20:11.810785
2016-11-15T07:02:26
2016-11-15T07:02:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,323
cpp
// PropertyPageBT.cpp : implementation file // #include "stdafx.h" #include "ATATool.h" #include "PropertyPageBT.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CPropertyPageBT property page IMPLEMENT_DYNCREATE(CPropertyPageBT, CPropertyPage) CPropertyPageBT::CPropertyPageBT() : CPropertyPage(CPropertyPageBT::IDD) { //{{AFX_DATA_INIT(CPropertyPageBT) m_BTAddr = _T(""); /*zishuo20150727*/ m_BTHostAddr = _T(""); m_bCheckBTAddr = FALSE; /*end*/ //}}AFX_DATA_INIT } CPropertyPageBT::~CPropertyPageBT() { } void CPropertyPageBT::DoDataExchange(CDataExchange* pDX) { CPropertyPage::DoDataExchange(pDX); //{{AFX_DATA_MAP(CPropertyPageBT) DDX_Control(pDX, IDC_COMBO_SPEC_TYPE, m_comboSpecType); DDX_Text(pDX, IDC_EDIT_BT_ADDR, m_BTAddr); /*zishuo20150727*/ DDX_Check(pDX, IDC_CHECK_BT_ADDR, m_bCheckBTAddr); DDX_Text(pDX, IDC_EDIT_BT_HOSTADDR, m_BTHostAddr); /*end*/ //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CPropertyPageBT, CPropertyPage) //{{AFX_MSG_MAP(CPropertyPageBT) // NOTE: the ClassWizard will add message map macros here //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CPropertyPageBT message handlers void CPropertyPageBT::UpdateParameters() { UpdateData (true); sprintf (p_sTestSpec->bt_spec.addr, m_BTAddr.GetBuffer(0), m_BTAddr.GetLength()); p_sTestSpec->bt_spec.addr[m_BTAddr.GetLength()] = '\0'; p_sCommonCFG->bt_spec_type = p_sTestSpec->bt_spec.specType = m_comboSpecType.GetCurSel(); /*zishuo20150727*/ p_sCommonCFG->bt_cfg.bBtAddrCheck = m_bCheckBTAddr ? true : false; memcpy (p_sTestSpec->bt_spec.local_bssid, m_BTHostAddr.GetBuffer(0), m_BTHostAddr.GetLength()); p_sTestSpec->bt_spec.local_bssid[m_BTHostAddr.GetLength()] = '\0'; /*end*/ } void CPropertyPageBT::InitParameters () { m_BTAddr = p_sTestSpec->bt_spec.addr; m_comboSpecType.SetCurSel (p_sTestSpec->bt_spec.specType); /*zishuo20150727*/ m_bCheckBTAddr =p_sCommonCFG->bt_cfg.bBtAddrCheck; m_BTHostAddr=p_sTestSpec->bt_spec.local_bssid; /*end*/ UpdateData (false); }
[ "jian.song@wheatek.com" ]
jian.song@wheatek.com
6ab6adf5a7006c2bb78328c0120feb3ede910204
e99592f5f7a8c58c4619ca42d3ccb2292b49f332
/MFCApplication2/MFCApplication2/MFCApplication2View.h
ff7552f411fb314ccf44ac8e88523b008463c505
[]
no_license
tseebo/Vc
e19318b5c7daad2e0490edb08388a104f6663747
78e65b17d1443247dccde04e2e27839a0d16e175
refs/heads/master
2021-03-21T15:04:10.567853
2020-07-02T11:27:07
2020-07-02T11:27:07
247,305,884
1
0
null
null
null
null
GB18030
C++
false
false
954
h
// MFCApplication2View.h : CMFCApplication2View 类的接口 // #pragma once class CMFCApplication2View : public CView { protected: // 仅从序列化创建 CMFCApplication2View(); DECLARE_DYNCREATE(CMFCApplication2View) // 特性 public: CMFCApplication2Doc* GetDocument() const; // 操作 public: // 重写 public: virtual void OnDraw(CDC* pDC); // 重写以绘制该视图 virtual BOOL PreCreateWindow(CREATESTRUCT& cs); protected: // 实现 public: virtual ~CMFCApplication2View(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif protected: // 生成的消息映射函数 protected: DECLARE_MESSAGE_MAP() public: afx_msg void OnLButtonDown(UINT nFlags, CPoint point); }; #ifndef _DEBUG // MFCApplication2View.cpp 中的调试版本 inline CMFCApplication2Doc* CMFCApplication2View::GetDocument() const { return reinterpret_cast<CMFCApplication2Doc*>(m_pDocument); } #endif
[ "1305771558@qq.com" ]
1305771558@qq.com
7cc01444100343c9b18227f86ff3aee5594321b6
5547eb598cf36cd6bad73a2506f6d455af30829d
/Huiswerk Week 6/huiswerk week 6/huiswerk week 6/Main.cpp
cb8fb3d9db055f949ca3f5817486dfa7f1889ba9
[]
no_license
jellebooij/OOP-advanced
c13e9722a4fc457dfe2e7f5af305ae015474d8ac
7b4097f5d3ac25a3669e41cd0f39287870baa1dc
refs/heads/master
2020-03-29T22:07:32.736067
2018-11-02T15:01:31
2018-11-02T15:01:31
150,404,025
0
0
null
null
null
null
UTF-8
C++
false
false
476
cpp
#include <iostream> #include "Parent.h" #include <memory> using namespace std; int main() { std::unique_ptr<Parent> p1 = std::make_unique<Parent>("Parent1"); cout << "P1:" << *p1 << endl; Parent* p2 = new Parent(*p1); // roept de copy constructor aan cout << "P2:" << *p2 << endl; Parent* p3 = new Parent("Parent3"); cout << "P3:" << *p3 << endl; *p3 = *p1; // roept de assignment operator aan cout << "P3:" << *p3 << endl; delete p2; delete p3; return 0; }
[ "jellebooij@outlook.com" ]
jellebooij@outlook.com
2f3206a2476d7d968ae286484738fc47b3797eba
cfdae4915f49b5acd9fac9b2674a8084ba8dd1bf
/tests/functional/namespace/expected/Car.qml.cpp
6da8e024cc7b74a86b4a399a45de3bd8649a1953
[ "BSD-2-Clause" ]
permissive
cryoma01/doxyqml
729f38e447c30da42baa2a4c6172aaef862990b5
6481a723fec932cc724bcd8c8bcf9f343079deed
refs/heads/master
2020-09-21T15:19:17.966386
2019-04-28T18:05:02
2019-04-28T18:05:02
224,829,534
0
0
NOASSERTION
2019-11-29T10:14:30
2019-11-29T10:14:29
null
UTF-8
C++
false
false
123
cpp
namespace ns { /** * A car */ class Car : public Item { public: /** * Car speed */ Q_PROPERTY(real speed) }; }
[ "mail@agateau.com" ]
mail@agateau.com
3e2eff52fc20f9dec56129c88f09e236d45a0f2c
b0c55c3b2df6f09bd810a5355a31f1f14778c501
/test/arduino/PrettyColors/PrettyColors.ino
a1902bc136e921db023e80473026f3e59c172d1b
[]
no_license
patilpramod97/laboratory
cef1850a9ac68742285bc5ff339a128cd0a1f6ab
0c0e40283c242abc262bea90507f04981067cb07
refs/heads/master
2021-01-17T21:57:52.856821
2015-03-06T19:24:34
2015-03-06T19:24:34
32,625,549
2
0
null
2015-03-21T08:37:21
2015-03-21T08:37:21
null
UTF-8
C++
false
false
2,962
ino
/* Pretty colors. For use with the BL-L515 Round Type, FULL COLOR LED lamp (common anode)p Connect G, B, R pins of the LED to (PWM) digital out pins 9, 10, and 11, respectively, and connect the anode (long pin) to ground through a 100Ω resistor. */ #include <stdlib.h> const int redPin = 11; const int greenPin = 9; const int bluePin = 10; const double SPEED_LIMIT = 0.001; const double ACCELERATION = 0.000125; //#define INSTABILITY 0.01 // prevents red (which otherwise requires a higher resistance) from dominating const unsigned int RED_FACTOR = 60; //////////////////////////////////////// void writeColor(unsigned long color) { unsigned int red = (color & 0xff0000) >> 16; unsigned int green = (color & 0x00ff00) >> 8; unsigned int blue = (color & 0x0000ff); red = (red * RED_FACTOR) / 255; analogWrite(redPin, 255 - red); analogWrite(greenPin, 255 - green); analogWrite(bluePin, 255 - blue); } double x = 0.0, y = 0.0, z = 0.0; double xspeed = 0.0, yspeed = 0.0, zspeed = 0.0; //float theta = 0.0, phi = 0.0; unsigned long m_w = 42; /* must not be zero */ unsigned long m_z = 1331; /* must not be zero */ unsigned long get_random() { m_z = 36969 * (m_z & 65535) + (m_z >> 16); m_w = 18000 * (m_w & 65535) + (m_w >> 16); return (m_z << 16) + m_w; /* 32-bit result */ } double floatRand(double mn, double sup) { return mn + (get_random() % RAND_MAX) * (sup - mn) / ((double) RAND_MAX + 1); } void nextColor() { double xacc = floatRand(-ACCELERATION, ACCELERATION); double yacc = floatRand(-ACCELERATION, ACCELERATION); double zacc = floatRand(-ACCELERATION, ACCELERATION); xspeed += xacc; yspeed += yacc; zspeed += zacc; if (xspeed > SPEED_LIMIT) { xspeed = SPEED_LIMIT; } else if (xspeed < -SPEED_LIMIT) { xspeed = -SPEED_LIMIT; } if (yspeed > SPEED_LIMIT) { yspeed = SPEED_LIMIT; } else if (yspeed < -SPEED_LIMIT) { yspeed = -SPEED_LIMIT; } if (zspeed > SPEED_LIMIT) { zspeed = SPEED_LIMIT; } else if (zspeed < -SPEED_LIMIT) { zspeed = -SPEED_LIMIT; } x += xspeed; y += yspeed; z += zspeed; if (x > 1.0) { x = 2.0 - x; xspeed = -xspeed; } else if (x < 0.0) { x = -x; xspeed = -xspeed; } if (y > 1.0) { y = 2.0 - y; yspeed = -yspeed; } else if (y < 0.0) { y = -y; yspeed = -yspeed; } if (z > 1.0) { z = 2.0 - z; zspeed = -zspeed; } else if (z < 0.0) { z = -z; zspeed = -zspeed; } unsigned int red = x * 255; unsigned int green = y * 255; unsigned int blue = z * 255; unsigned long color = red * (unsigned long) 0x10000 + green * 0x100 + blue; writeColor(color); } //////////////////////////////////////// void setup() { pinMode(redPin, OUTPUT); pinMode(greenPin, OUTPUT); pinMode(bluePin, OUTPUT); } void loop() { nextColor(); delay(1); }
[ "josh@fortytwo.net" ]
josh@fortytwo.net
8d15a60c3dd3c0c459a30470830b49969b5318e6
bf7fe9c190e45d80200706bf39359716ba41587d
/Particles/Particle.cpp
e64c0e1e4c1617d6458ae8ee0190c005554474dc
[]
no_license
VladislavKoleda/CosmicDefender--master
de1a34f9ebe0bff764152b94d170710642809a98
042097567af4a3e6eba147971ce067a3a982907a
refs/heads/master
2020-11-23T21:04:17.911131
2019-12-13T10:53:43
2019-12-13T10:53:43
227,819,746
0
0
null
null
null
null
UTF-8
C++
false
false
293
cpp
#include "Particle.h" using namespace SFML::System; namespace ComicDefender { Particle::Particle(float angle, float speed, float dx, float dy, float x, float y, float Q, int Flag) { Angle = angle; Speed = speed; DX = dx; DY = dy; X = x; Y = y; q = Q; flag = Flag; } }
[ "koleda147@gmail.com" ]
koleda147@gmail.com
1bca70424b807cf1380b4830273f3f075b1d62a4
e179d313721d389730834cfe3677f9c4d7dacae5
/critpath/mcpat/processor.h
b8a1438fb7c770a84523f65471d97e773e488ed3
[]
no_license
PolyArch/prism
8796243a5618e8d12f965bf30b9f6e799112e1cd
583beba32710113e47f68ab573aae5376a19e010
refs/heads/master
2021-03-27T12:37:34.160907
2019-09-30T17:38:49
2019-09-30T17:38:49
111,027,680
0
0
null
null
null
null
UTF-8
C++
false
false
4,782
h
/***************************************************************************** * McPAT * SOFTWARE LICENSE AGREEMENT * Copyright 2012 Hewlett-Packard Development Company, L.P. * All Rights Reserved * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.” * ***************************************************************************/ #ifndef PROCESSOR_H_ #define PROCESSOR_H_ #include "XML_Parse.h" #include "area.h" #include "decoder.h" #include "parameter.h" #include "array.h" #include "arbiter.h" #include <vector> #include "basic_components.h" #include "core.h" #include "memoryctrl.h" #include "router.h" #include "sharedcache.h" #include "noc.h" #include "iocontrollers.h" class Processor : public Component { public: ParseXML *XML; vector<Core *> cores; vector<SharedCache *> l2array; vector<SharedCache *> l3array; vector<SharedCache *> l1dirarray; vector<SharedCache *> l2dirarray; vector<NoC *> nocs; MemoryController * mc; NIUController * niu; PCIeController * pcie; FlashController * flashcontroller; InputParameter interface_ip; ProcParam procdynp; //wire globalInterconnect; //clock_network globalClock; Component core, l2, l3, l1dir, l2dir, noc, mcs, cc, nius, pcies,flashcontrollers; int numCore, numL2, numL3, numNOC, numL1Dir, numL2Dir; Processor(ParseXML *XML_interface); //void compute(); virtual void set_proc_param(); virtual void displayEnergy(uint32_t indent = 0,int plevel = 100, bool is_tdp=true); virtual void displayDeviceType(int device_type_, uint32_t indent = 0); virtual void displayInterconnectType(int interconnect_type_, uint32_t indent = 0); ~Processor(); }; class PrismProcessor : public Processor { public: PrismProcessor(ParseXML* XML_interface); virtual void computeEnergy(); virtual void computeAccPower(); virtual void displayAccEnergy(); double executionTime_acc; //overall output energy Component overall_acc, core_acc, ifu_acc, icache_acc, lsu_acc, dcache_acc, mmu_acc, exu_acc, iiw_acc, fiw_acc, isel_acc, rnu_acc, corepipe_acc, undiffCore_acc, l2cache_acc, ialu_acc, fpu_acc, mul_acc, rfu_acc, l2_acc, l3_acc, l1dir_acc, l2dir_acc, noc_acc, cc_acc, nius_acc, pcies_acc, flashcontrollers_acc; //overall output power Component overall_acc_power, core_acc_power, ifu_acc_power, icache_acc_power, lsu_acc_power, dcache_acc_power, mmu_acc_power, exu_acc_power, iiw_acc_power, fiw_acc_power, isel_acc_power, rnu_acc_power, corepipe_acc_power, undiffCore_acc_power, l2cache_acc_power, ialu_acc_power, fpu_acc_power, mul_acc_power, rfu_acc_power, l2_acc_power, l3_acc_power, l1dir_acc_power, l2dir_acc_power, noc_acc_power, cc_acc_power, nius_acc_power, pcies_acc_power, flashcontrollers_acc_power; }; class NLAProcessor : public PrismProcessor { public: NLAProcessor(ParseXML* XML_interface); vector<NLAU *> nlas; virtual void computeEnergy(); virtual void computeAccPower(); virtual void displayAccEnergy(); //current energy Component nla, imu; //overall output energy Component nla_acc, imu_acc, nla_net_acc; //overall output power Component nla_acc_power, imu_acc_power, nla_net_acc_power; }; #endif /* PROCESSOR_H_ */
[ "tjn@cs.wisc.edu" ]
tjn@cs.wisc.edu
0b05a26b7af8621d8c8f4398b68c12144a422346
76f0efb245ff0013e0428ee7636e72dc288832ab
/out/Default/gen/blink/bindings/core/v8/V8SVGAnimatedLength.cpp
f047d3641e36c96ca3d249741f3d0bdafe150f78
[]
no_license
dckristiono/chromium
e8845d2a8754f39e0ca1d3d3d44d01231957367c
8ad7c1bd5778bfda3347cf6b30ef60d3e4d7c0b9
refs/heads/master
2020-04-22T02:34:41.775069
2016-08-24T14:05:09
2016-08-24T14:05:09
66,465,243
0
2
null
null
null
null
UTF-8
C++
false
false
5,966
cpp
// 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! #include "V8SVGAnimatedLength.h" #include "bindings/core/v8/ExceptionState.h" #include "bindings/core/v8/V8DOMConfiguration.h" #include "bindings/core/v8/V8ObjectConstructor.h" #include "bindings/core/v8/V8SVGElement.h" #include "bindings/core/v8/V8SVGLength.h" #include "core/dom/Document.h" #include "wtf/GetPtr.h" #include "wtf/RefPtr.h" namespace blink { // Suppress warning: global constructors, because struct WrapperTypeInfo is trivial // and does not depend on another global objects. #if defined(COMPONENT_BUILD) && defined(WIN32) && COMPILER(CLANG) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wglobal-constructors" #endif const WrapperTypeInfo V8SVGAnimatedLength::wrapperTypeInfo = { gin::kEmbedderBlink, V8SVGAnimatedLength::domTemplate, V8SVGAnimatedLength::trace, V8SVGAnimatedLength::traceWrappers, 0, V8SVGAnimatedLength::visitDOMWrapper, V8SVGAnimatedLength::preparePrototypeAndInterfaceObject, nullptr, "SVGAnimatedLength", 0, WrapperTypeInfo::WrapperTypeObjectPrototype, WrapperTypeInfo::ObjectClassId, WrapperTypeInfo::NotInheritFromEventTarget, WrapperTypeInfo::Dependent }; #if defined(COMPONENT_BUILD) && defined(WIN32) && COMPILER(CLANG) #pragma clang diagnostic pop #endif // This static member must be declared by DEFINE_WRAPPERTYPEINFO in SVGAnimatedLength.h. // For details, see the comment of DEFINE_WRAPPERTYPEINFO in // bindings/core/v8/ScriptWrappable.h. const WrapperTypeInfo& SVGAnimatedLength::s_wrapperTypeInfo = V8SVGAnimatedLength::wrapperTypeInfo; static_assert( !std::is_base_of<ActiveScriptWrappable, SVGAnimatedLength>::value, "SVGAnimatedLength inherits from ActiveScriptWrappable, but does not specify " "[ActiveScriptWrappable] extended attribute in the IDL file. " "Be consistent."); namespace SVGAnimatedLengthV8Internal { static void baseValAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info) { v8::Local<v8::Object> holder = info.Holder(); SVGAnimatedLength* impl = V8SVGAnimatedLength::toImpl(holder); v8SetReturnValueFast(info, WTF::getPtr(impl->baseVal()), impl); } static void baseValAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { SVGAnimatedLengthV8Internal::baseValAttributeGetter(info); } static void animValAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info) { v8::Local<v8::Object> holder = info.Holder(); SVGAnimatedLength* impl = V8SVGAnimatedLength::toImpl(holder); v8SetReturnValueFast(info, WTF::getPtr(impl->animVal()), impl); } static void animValAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { SVGAnimatedLengthV8Internal::animValAttributeGetter(info); } } // namespace SVGAnimatedLengthV8Internal void V8SVGAnimatedLength::visitDOMWrapper(v8::Isolate* isolate, ScriptWrappable* scriptWrappable, const v8::Persistent<v8::Object>& wrapper) { SVGAnimatedLength* impl = scriptWrappable->toImpl<SVGAnimatedLength>(); SVGElement* contextElement = impl->contextElement(); if (contextElement) { DOMWrapperWorld::setWrapperReferencesInAllWorlds(wrapper, contextElement, isolate); } } const V8DOMConfiguration::AccessorConfiguration V8SVGAnimatedLengthAccessors[] = { {"baseVal", SVGAnimatedLengthV8Internal::baseValAttributeGetterCallback, 0, 0, 0, 0, v8::DEFAULT, static_cast<v8::PropertyAttribute>(v8::ReadOnly), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder}, {"animVal", SVGAnimatedLengthV8Internal::animValAttributeGetterCallback, 0, 0, 0, 0, v8::DEFAULT, static_cast<v8::PropertyAttribute>(v8::ReadOnly), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder}, }; static void installV8SVGAnimatedLengthTemplate(v8::Isolate* isolate, const DOMWrapperWorld& world, v8::Local<v8::FunctionTemplate> interfaceTemplate) { // Initialize the interface object's template. V8DOMConfiguration::initializeDOMInterfaceTemplate(isolate, interfaceTemplate, V8SVGAnimatedLength::wrapperTypeInfo.interfaceName, v8::Local<v8::FunctionTemplate>(), V8SVGAnimatedLength::internalFieldCount); v8::Local<v8::Signature> signature = v8::Signature::New(isolate, interfaceTemplate); ALLOW_UNUSED_LOCAL(signature); v8::Local<v8::ObjectTemplate> instanceTemplate = interfaceTemplate->InstanceTemplate(); ALLOW_UNUSED_LOCAL(instanceTemplate); v8::Local<v8::ObjectTemplate> prototypeTemplate = interfaceTemplate->PrototypeTemplate(); ALLOW_UNUSED_LOCAL(prototypeTemplate); // Register DOM constants, attributes and operations. V8DOMConfiguration::installAccessors(isolate, world, instanceTemplate, prototypeTemplate, interfaceTemplate, signature, V8SVGAnimatedLengthAccessors, WTF_ARRAY_LENGTH(V8SVGAnimatedLengthAccessors)); } v8::Local<v8::FunctionTemplate> V8SVGAnimatedLength::domTemplate(v8::Isolate* isolate, const DOMWrapperWorld& world) { return V8DOMConfiguration::domClassTemplate(isolate, world, const_cast<WrapperTypeInfo*>(&wrapperTypeInfo), installV8SVGAnimatedLengthTemplate); } bool V8SVGAnimatedLength::hasInstance(v8::Local<v8::Value> v8Value, v8::Isolate* isolate) { return V8PerIsolateData::from(isolate)->hasInstance(&wrapperTypeInfo, v8Value); } v8::Local<v8::Object> V8SVGAnimatedLength::findInstanceInPrototypeChain(v8::Local<v8::Value> v8Value, v8::Isolate* isolate) { return V8PerIsolateData::from(isolate)->findInstanceInPrototypeChain(&wrapperTypeInfo, v8Value); } SVGAnimatedLength* V8SVGAnimatedLength::toImplWithTypeCheck(v8::Isolate* isolate, v8::Local<v8::Value> value) { return hasInstance(value, isolate) ? toImpl(v8::Local<v8::Object>::Cast(value)) : nullptr; } } // namespace blink
[ "dckristiono@gmail.com" ]
dckristiono@gmail.com
3a28223b812928a964dfe07d7d62d5cc976c1bc7
a8b937985a2a245195a039192be6b4334fe8a349
/tests/ordinary_differential_equations_test.cpp
3aa3ed0488c2db080c7852759cb15e2e2b3eb62a
[]
no_license
Quanteek/OpenNN-CMake
f7e460758f6dd62a39fedfc148726a5e9fb64f50
1cecec74764ef70f1caa10fc76272673c9eb3b40
refs/heads/master
2021-01-01T05:40:41.148486
2014-06-26T11:49:59
2014-06-26T11:49:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
17,338
cpp
/****************************************************************************************************************/ /* */ /* OpenNN: Open Neural Networks Library */ /* www.intelnics.com/opennn */ /* */ /* O R D I N A R Y D I F F E R E N T I A L E Q U A T I O N S T E S T C L A S S */ /* */ /* Roberto Lopez */ /* Intelnics - The artificial intelligence company */ /* robertolopez@intelnics.com */ /* */ /****************************************************************************************************************/ // Unit testing includes #include "ordinary_differential_equations_test.h" using namespace OpenNN; OrdinaryDifferentialEquationsTest::OrdinaryDifferentialEquationsTest(void) : UnitTesting() { } OrdinaryDifferentialEquationsTest::~OrdinaryDifferentialEquationsTest(void) { } void OrdinaryDifferentialEquationsTest::test_constructor(void) { message += "test_constructor\n"; } void OrdinaryDifferentialEquationsTest::test_destructor(void) { message += "test_destructor\n"; } void OrdinaryDifferentialEquationsTest::test_get_points_number(void) { message += "test_get_points_number\n"; } void OrdinaryDifferentialEquationsTest::test_get_tolerance(void) { message += "test_get_tolerance\n"; } void OrdinaryDifferentialEquationsTest::test_get_initial_size(void) { message += "test_get_initial_size\n"; } void OrdinaryDifferentialEquationsTest::test_get_warning_size(void) { message += "test_get_warning_size\n"; } void OrdinaryDifferentialEquationsTest::test_get_error_size(void) { message += "test_get_error_size\n"; } void OrdinaryDifferentialEquationsTest::test_get_display(void) { message += "test_get_display\n"; } void OrdinaryDifferentialEquationsTest::test_set_default(void) { message += "test_set_default\n"; } void OrdinaryDifferentialEquationsTest::test_set_points_number(void) { message += "test_set_points_number\n"; } void OrdinaryDifferentialEquationsTest::test_set_tolerance(void) { message += "test_set_tolerance\n"; } void OrdinaryDifferentialEquationsTest::test_set_initial_size(void) { message += "test_set_initial_size\n"; } void OrdinaryDifferentialEquationsTest::test_set_warning_size(void) { message += "test_set_warning_size\n"; } void OrdinaryDifferentialEquationsTest::test_set_error_size(void) { message += "test_set_error_size\n"; } void OrdinaryDifferentialEquationsTest::test_set_display(void) { message += "test_set_display\n"; } // @todo void OrdinaryDifferentialEquationsTest::test_calculate_Runge_Kutta_integral_1(void) { message += "test_calculate_Runge_Kutta_integral_1\n"; /* OrdinaryDifferentialEquations ode; NeuralNetwork nn; unsigned points_number = 11; ode.set_points_number(points_number); Vector<double> x(points_number); Vector<double> y(points_number); ode.calculate_Runge_Kutta_solution(*this, x, y, &OrdinaryDifferentialEquationsTest::calculate_zero_dot, nn, 0.0, 1.0, 0.0); assert_true(x[points_number-1] == 1.0, LOG); assert_true(y[points_number-1] == 0.0, LOG); ode.calculate_Runge_Kutta_solution(*this, x, y, &OrdinaryDifferentialEquationsTest::calculate_x_dot, nn, 0.0, 1.0, 0.0); assert_true(x[points_number-1] == 1.0, LOG); // assert_true(y[points_number-1] == 0.5, LOG); ode.calculate_Runge_Kutta_solution(*this, x, y, &OrdinaryDifferentialEquationsTest::calculate_x_squared_dot, nn, 0.0, 1.0, 0.0); assert_true(x[points_number-1] == 1.0, LOG); // assert_true(y[points_number-1] == 1.0/3.0, LOG); */ } // @todo void OrdinaryDifferentialEquationsTest::test_calculate_Runge_Kutta_integral_2(void) { message += "test_calculate_Runge_Kutta_integral_2\n"; /* OrdinaryDifferentialEquations ode; NeuralNetwork nn; unsigned points_number = 11; ode.set_points_number(points_number); Vector<double> x(points_number); Vector<double> y1(points_number); Vector<double> y2(points_number); ode.calculate_Runge_Kutta_solution(*this, x, y1, y2, &OrdinaryDifferentialEquationsTest::calculate_zero_dot, &OrdinaryDifferentialEquationsTest::calculate_zero_dot, nn, 0.0, 1.0, 0.0, 0.0); assert_true(x[points_number-1] == 1.0, LOG); assert_true(y1[points_number-1] == 0.0, LOG); assert_true(y2[points_number-1] == 0.0, LOG); */ } // @todo void OrdinaryDifferentialEquationsTest::test_calculate_Runge_Kutta_integral_3(void) { message += "test_calculate_Runge_Kutta_integral_3\n"; /* OrdinaryDifferentialEquations ode; NeuralNetwork nn; unsigned points_number = 11; ode.set_points_number(points_number); Vector<double> x(points_number); Vector<double> y1(points_number); Vector<double> y2(points_number); Vector<double> y3(points_number); ode.calculate_Runge_Kutta_solution(*this, x, y1, y2, y3, &OrdinaryDifferentialEquationsTest::calculate_zero_dot, &OrdinaryDifferentialEquationsTest::calculate_zero_dot, &OrdinaryDifferentialEquationsTest::calculate_zero_dot, nn, 0.0, 1.0, 0.0, 0.0, 0.0); assert_true(x[points_number-1] == 1.0, LOG); assert_true(y1[points_number-1] == 0.0, LOG); assert_true(y2[points_number-1] == 0.0, LOG); assert_true(y3[points_number-1] == 0.0, LOG); */ } // @todo void OrdinaryDifferentialEquationsTest::test_calculate_Runge_Kutta_integral_4(void) { message += "test_calculate_Runge_Kutta_integral_4\n"; /* OrdinaryDifferentialEquations ode; NeuralNetwork nn; unsigned points_number = 11; ode.set_points_number(points_number); Vector<double> x(points_number); Vector<double> y1(points_number); Vector<double> y2(points_number); Vector<double> y3(points_number); Vector<double> y4(points_number); ode.calculate_Runge_Kutta_solution(*this, x, y1, y2, y3, y4, &OrdinaryDifferentialEquationsTest::calculate_zero_dot, &OrdinaryDifferentialEquationsTest::calculate_zero_dot, &OrdinaryDifferentialEquationsTest::calculate_zero_dot, &OrdinaryDifferentialEquationsTest::calculate_zero_dot, nn, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0); assert_true(x[points_number-1] == 1.0, LOG); assert_true(y1[points_number-1] == 0.0, LOG); assert_true(y2[points_number-1] == 0.0, LOG); assert_true(y3[points_number-1] == 0.0, LOG); assert_true(y4[points_number-1] == 0.0, LOG); */ } // @todo void OrdinaryDifferentialEquationsTest::test_calculate_Runge_Kutta_integral_5(void) { message += "test_calculate_Runge_Kutta_integral_5\n"; /* OrdinaryDifferentialEquations ode; NeuralNetwork nn; unsigned points_number = 11; ode.set_points_number(points_number); Vector<double> x(points_number); Vector<double> y1(points_number); Vector<double> y2(points_number); Vector<double> y3(points_number); Vector<double> y4(points_number); Vector<double> y5(points_number); ode.calculate_Runge_Kutta_solution(*this, x, y1, y2, y3, y4, y5, &OrdinaryDifferentialEquationsTest::calculate_zero_dot, &OrdinaryDifferentialEquationsTest::calculate_zero_dot, &OrdinaryDifferentialEquationsTest::calculate_zero_dot, &OrdinaryDifferentialEquationsTest::calculate_zero_dot, &OrdinaryDifferentialEquationsTest::calculate_zero_dot, nn, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0); assert_true(x[points_number-1] == 1.0, LOG); assert_true(y1[points_number-1] == 0.0, LOG); assert_true(y2[points_number-1] == 0.0, LOG); assert_true(y3[points_number-1] == 0.0, LOG); assert_true(y4[points_number-1] == 0.0, LOG); assert_true(y5[points_number-1] == 0.0, LOG); */ } // @todo void OrdinaryDifferentialEquationsTest::test_calculate_Runge_Kutta_Fehlberg_integral_1(void) { message += "test_calculate_Runge_Kutta_Fehlberg_integral_1\n"; /* OrdinaryDifferentialEquations ode; NeuralNetwork nn; Vector<double> x; Vector<double> y; unsigned points_number = ode.calculate_Runge_Kutta_Fehlberg_solution(*this, x, y, &OrdinaryDifferentialEquationsTest::calculate_zero_dot, nn, 0.0, 1.0, 0.0); assert_true(x[points_number-1] == 1.0, LOG); assert_true(y[points_number-1] == 0.0, LOG); */ } // @todo void OrdinaryDifferentialEquationsTest::test_calculate_Runge_Kutta_Fehlberg_integral_2(void) { message += "test_calculate_Runge_Kutta_Fehlberg_integral_2\n"; /* OrdinaryDifferentialEquations ode; NeuralNetwork nn; Vector<double> x; Vector<double> y1; Vector<double> y2; unsigned points_number = ode.calculate_Runge_Kutta_Fehlberg_solution(*this, x, y1, y2, &OrdinaryDifferentialEquationsTest::calculate_zero_dot, &OrdinaryDifferentialEquationsTest::calculate_zero_dot, nn, 0.0, 1.0, 0.0, 0.0); assert_true(x[points_number-1] == 1.0, LOG); assert_true(y1[points_number-1] == 0.0, LOG); assert_true(y2[points_number-1] == 0.0, LOG); */ } // @todo void OrdinaryDifferentialEquationsTest::test_calculate_Runge_Kutta_Fehlberg_integral_3(void) { message += "test_calculate_Runge_Kutta_Fehlberg_integral_3\n"; // OrdinaryDifferentialEquations ode; // NeuralNetwork nn; // Vector<double> x; // Vector<double> y1; // Vector<double> y2; // Vector<double> y3; // unsigned points_number = ode.calculate_Runge_Kutta_Fehlberg_solution(*this, // x, y1, y2, y3, // &OrdinaryDifferentialEquationsTest::calculate_zero_dot, // &OrdinaryDifferentialEquationsTest::calculate_zero_dot, // &OrdinaryDifferentialEquationsTest::calculate_zero_dot, // nn, 0.0, 1.0, // 0.0, 0.0, 0.0); // assert_true(x[points_number-1] == 1.0, LOG); // assert_true(y1[points_number-1] == 0.0, LOG); // assert_true(y2[points_number-1] == 0.0, LOG); // assert_true(y3[points_number-1] == 0.0, LOG); } // @todo void OrdinaryDifferentialEquationsTest::test_calculate_Runge_Kutta_Fehlberg_integral_4(void) { message += "test_calculate_Runge_Kutta_Fehlberg_integral_4\n"; /* OrdinaryDifferentialEquations ode; NeuralNetwork nn; Vector<double> x; Vector<double> y1; Vector<double> y2; Vector<double> y3; Vector<double> y4; unsigned points_number = ode.calculate_Runge_Kutta_Fehlberg_solution(*this, x, y1, y2, y3, y4, &OrdinaryDifferentialEquationsTest::calculate_zero_dot, &OrdinaryDifferentialEquationsTest::calculate_zero_dot, &OrdinaryDifferentialEquationsTest::calculate_zero_dot, &OrdinaryDifferentialEquationsTest::calculate_zero_dot, nn, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0); assert_true(x[points_number-1] == 1.0, LOG); assert_true(y1[points_number-1] == 0.0, LOG); assert_true(y2[points_number-1] == 0.0, LOG); assert_true(y3[points_number-1] == 0.0, LOG); assert_true(y4[points_number-1] == 0.0, LOG); */ } // @todo void OrdinaryDifferentialEquationsTest::test_calculate_Runge_Kutta_Fehlberg_integral_5(void) { message += "test_calculate_Runge_Kutta_Fehlberg_integral_5\n"; /* OrdinaryDifferentialEquations ode; NeuralNetwork nn; Vector<double> x; Vector<double> y1; Vector<double> y2; Vector<double> y3; Vector<double> y4; Vector<double> y5; unsigned points_number = ode.calculate_Runge_Kutta_Fehlberg_solution(*this, x, y1, y2, y3, y4, y5, &OrdinaryDifferentialEquationsTest::calculate_zero_dot, &OrdinaryDifferentialEquationsTest::calculate_zero_dot, &OrdinaryDifferentialEquationsTest::calculate_zero_dot, &OrdinaryDifferentialEquationsTest::calculate_zero_dot, &OrdinaryDifferentialEquationsTest::calculate_zero_dot, nn, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0); assert_true(x[points_number-1] == 1.0, LOG); assert_true(y1[points_number-1] == 0.0, LOG); assert_true(y2[points_number-1] == 0.0, LOG); assert_true(y3[points_number-1] == 0.0, LOG); assert_true(y4[points_number-1] == 0.0, LOG); assert_true(y5[points_number-1] == 0.0, LOG); */ } double OrdinaryDifferentialEquationsTest::calculate_zero_dot(const NeuralNetwork&, const double&, const double&) const { return(0.0); } double OrdinaryDifferentialEquationsTest::calculate_zero_dot(const NeuralNetwork&, const double&, const double&, const double&) const { return(0.0); } double OrdinaryDifferentialEquationsTest::calculate_zero_dot(const NeuralNetwork&, const double&, const double&, const double&, const double&) const { return(0.0); } double OrdinaryDifferentialEquationsTest::calculate_zero_dot(const NeuralNetwork&, const double&, const double&, const double&, const double&, const double&) const { return(0.0); } double OrdinaryDifferentialEquationsTest::calculate_zero_dot(const NeuralNetwork&, const double&, const double&, const double&, const double&, const double&, const double&) const { return(0.0); } double OrdinaryDifferentialEquationsTest::calculate_x_dot(const NeuralNetwork&, const double& x, const double&) const { return(x); } double OrdinaryDifferentialEquationsTest::calculate_x_dot(const NeuralNetwork&, const double&, const double&, const double&) const { return(0.0); } double OrdinaryDifferentialEquationsTest::calculate_x_dot(const NeuralNetwork&, const double&, const double&, const double&, const double&) const { return(0.0); } double OrdinaryDifferentialEquationsTest::calculate_x_dot(const NeuralNetwork&, const double&, const double&, const double&, const double&, const double&) const { return(0.0); } double OrdinaryDifferentialEquationsTest::calculate_x_dot(const NeuralNetwork&, const double&, const double&, const double&, const double&, const double&, const double&) const { return(0.0); } double OrdinaryDifferentialEquationsTest::calculate_x_squared_dot(const NeuralNetwork&, const double& x, const double&) const { return(x*x); } void OrdinaryDifferentialEquationsTest::test_to_XML(void) { message += "test_to_XML\n"; } void OrdinaryDifferentialEquationsTest::test_from_XML(void) { message += "test_from_XML\n"; } void OrdinaryDifferentialEquationsTest::run_test_case(void) { message += "Running ordinary differential equations test case...\n"; // Constructor and destructor methods test_constructor(); test_destructor(); // Get methods test_get_points_number(); test_get_tolerance(); test_get_initial_size(); test_get_warning_size(); test_get_error_size(); test_get_display(); // Set methods test_set_default(); test_set_points_number(); test_set_tolerance(); test_set_initial_size(); test_set_warning_size(); test_set_error_size(); test_set_display(); // Runge-Kutta methods test_calculate_Runge_Kutta_integral_1(); test_calculate_Runge_Kutta_integral_2(); test_calculate_Runge_Kutta_integral_3(); test_calculate_Runge_Kutta_integral_4(); test_calculate_Runge_Kutta_integral_5(); // Runge-Kutta-Fehlberg methods test_calculate_Runge_Kutta_Fehlberg_integral_1(); test_calculate_Runge_Kutta_Fehlberg_integral_2(); test_calculate_Runge_Kutta_Fehlberg_integral_3(); test_calculate_Runge_Kutta_Fehlberg_integral_4(); test_calculate_Runge_Kutta_Fehlberg_integral_5(); message += "End of ordinary differential equations test case.\n"; } // OpenNN: Open Neural Networks Library. // Copyright (C) 2005-2014 Roberto Lopez // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
[ "benoitbayol@dhcp-23-78.wifi-auth.ecp.fr" ]
benoitbayol@dhcp-23-78.wifi-auth.ecp.fr
33991f2b695dde5e4e31de736c744c428b884efe
081c3f131070a238892670c96c18796d9dcffcf0
/VCExercisesOOP/ArrayParallelLookup/ArrayParallelLookup.cpp
5f55d394df563d502c41c30a972073cd37cbaca3
[]
no_license
EdgarCerna/csis223
77b66ffa8b8e8f04fa822ff4679f8abe2730a47c
f9f317f5f428799107edfad3a9ecca1f3db71cc1
refs/heads/master
2020-03-29T21:06:43.932374
2018-12-13T07:21:25
2018-12-13T07:21:25
150,350,218
0
0
null
null
null
null
UTF-8
C++
false
false
1,842
cpp
// ArrayParallelLookup.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> #include <fstream> #include <string> using namespace std; int main() { string stateCode[60]; // declare 2-letter state code array string stateName[60]; // declare state name array string codeInput; int cnt = 0; int pos; ifstream stateInput; stateInput.open("States.txt"); if (!stateInput) { cout << endl << "Error opening States input file." << endl << endl; system("pause"); return -1; } stateInput >> stateCode[cnt] >> stateName[cnt]; // read first record while (!stateInput.eof()) { cnt++; // count records stateInput >> stateCode[cnt] >> stateName[cnt]; // read next record } stateInput.close(); // close file after array has been loaded with data cout << endl << cnt << " state records loaded." << endl << endl; // display count of state lookup records cout << endl << endl << "Enter state code [Q to quit]: "; // prompt for first state code cin >> codeInput; // first state code input while (codeInput != "Q" && codeInput != "q") { pos = 0; // initialize array position to first element in stateCode array while (codeInput != stateCode[pos] && pos < cnt) // continue to next array element while pos < count { pos++; // increment value to next position in array } if (codeInput == stateCode[pos]) cout << endl << "Selected state is " << stateName[pos] << endl; else cout << endl << "State code " << codeInput << " not found in list." << endl; cout << endl << endl << "Enter state code [Q to quit]: "; // prompt for next state code cin >> codeInput; // next state code input (or Q to quit) } cout << endl << endl; system("pause"); return 0; }
[ "S1460902@student.mcckc.edu" ]
S1460902@student.mcckc.edu
03ba321494eb0d8a9d803ce9fa41ba43202dee1a
89a6e0eca52e0cb31915fa43d9b1ba3f0145b257
/演算法題型分類/Prefix-Sum/c462.cc
c8cd34d1dd66923ddd1b8abd864fd0f720deb7e4
[]
no_license
rollfatcat/ProblemSet
03a3a960ec324b831d3db422a52d623f2d04b6f0
f9c76320e8812304b73ac348e8e34e8a55e08a10
refs/heads/master
2023-04-03T15:48:44.551030
2023-03-21T19:09:32
2023-03-21T19:09:32
191,777,230
4
0
null
null
null
null
UTF-8
C++
false
false
1,161
cc
/* 給定K個單位長度和一個字串,輸出連續K個單位大小寫交錯的子字串長度? * 解題關鍵:貪婪法,將原字串轉變為連續大小寫的字元長度 * */ #include<bits/stdc++.h> using namespace std; const int MaxN=1e5; char ss[MaxN+2]; int num[MaxN]; int main(){ int K, N; while(scanf("%d",&K)!=EOF){ scanf("%s\n",ss); /* 轉換為"連續"大小寫字元的長度 */ N=0; num[0]=1; bool now, pre= 'A'<=ss[0] and ss[0]<='Z'; for(int i=1;ss[i]!='\0';i++, pre=now){ now='A'<=ss[i] and ss[i]<='Z'; (pre==now)? num[N]+=1: num[++N]=1; } /* 貪婪法:從枚舉起點,直到某一段的連續長度不等於K * 若新節點的長度 等於K時 nowL可以延伸一個單位 * 若新節點的長度不等於K時,nowL到這邊時就得停止 * 此時試著以這個節點作為新起點,往後延伸。 * 注意:最後一次時 nowL 可能剛好在延伸而沒有比對到 */ int maxL=0; int nowL=0; for(int i=0;i<=N;i++){ if(num[i]==K) nowL++; else{ maxL=max(maxL,nowL+(num[i]>K)); nowL= num[i]>K; } } printf("%d\n",max(maxL,nowL)*K); } }
[ "crhsieh1114@outlook.com" ]
crhsieh1114@outlook.com
4390c1bff6f099dd276e25e7a079ed18c3807248
ef5fe6b55f3d9a697392a252617e1dc79b184222
/AtCoder/ABC159/A.cpp
5526d6589ea1ad22a5b6d47d89fa5d4bc02c9914
[]
no_license
kunichan9292/Programing-contest
15110f1dbf00a9957d524c6163cd165b3828803f
9126d5c63b80f170de8108ca74c7ae7a2bf9c921
refs/heads/master
2022-06-18T04:40:45.662188
2020-05-12T19:49:16
2020-05-12T19:49:16
263,432,210
0
0
null
null
null
null
UTF-8
C++
false
false
234
cpp
#include<iostream> using namespace std; int main(){ int N,M; cin >> N >> M; int count_N=0; int count_M=0; if(N>=2){ count_N=N*(N-1)/2; } if(M>=2){ count_M=M*(M-1)/2; } cout << count_N + count_M << endl; }
[ "9230-kunichan@ezweb.ne.jp" ]
9230-kunichan@ezweb.ne.jp
529d27d51381dafc81e45d876cdddb9c74cb56d4
ef23e388061a637f82b815d32f7af8cb60c5bb1f
/src/emu/cpu/sh4/sh4comn.h
546468de860a577af428f1943de8fa266b407d59
[]
no_license
marcellodash/psmame
76fd877a210d50d34f23e50d338e65a17deff066
09f52313bd3b06311b910ed67a0e7c70c2dd2535
refs/heads/master
2021-05-29T23:57:23.333706
2011-06-23T20:11:22
2011-06-23T20:11:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,775
h
/***************************************************************************** * * sh4comn.h * * SH-4 non-specific components * *****************************************************************************/ #pragma once #ifndef __SH4COMN_H__ #define __SH4COMN_H__ //#define USE_SH4DRC /* speed up delay loops, bail out of tight loops */ #define BUSY_LOOP_HACKS 0 #define VERBOSE 0 #ifdef USE_SH4DRC #include "cpu/drcfe.h" #include "cpu/drcuml.h" #include "cpu/drcumlsh.h" class sh4_frontend; #endif #define CPU_TYPE_SH3 (2) #define CPU_TYPE_SH4 (3) #define LOG(x) do { if (VERBOSE) logerror x; } while (0) #define EXPPRI(pl,po,p,n) (((4-(pl)) << 24) | ((15-(po)) << 16) | ((p) << 8) | (255-(n))) #define NMIPRI() EXPPRI(3,0,16,SH4_INTC_NMI) #define INTPRI(p,n) EXPPRI(4,2,p,n) #define FP_RS(r) sh4->fr[(r)] // binary representation of single precision floating point register r #define FP_RFS(r) *( (float *)(sh4->fr+(r)) ) // single precision floating point register r #define FP_RFD(r) *( (double *)(sh4->fr+(r)) ) // double precision floating point register r #define FP_XS(r) sh4->xf[(r)] // binary representation of extended single precision floating point register r #define FP_XFS(r) *( (float *)(sh4->xf+(r)) ) // single precision extended floating point register r #define FP_XFD(r) *( (double *)(sh4->xf+(r)) ) // double precision extended floating point register r #ifdef LSB_FIRST #define FP_RS2(r) sh4->fr[(r) ^ sh4->fpu_pr] #define FP_RFS2(r) *( (float *)(sh4->fr+((r) ^ sh4->fpu_pr)) ) #define FP_XS2(r) sh4->xf[(r) ^ sh4->fpu_pr] #define FP_XFS2(r) *( (float *)(sh4->xf+((r) ^ sh4->fpu_pr)) ) #endif typedef struct { UINT32 ppc; UINT32 pc, spc; UINT32 pr; UINT32 sr, ssr; UINT32 gbr, vbr; UINT32 mach, macl; UINT32 r[16], rbnk[2][8], sgr; UINT32 fr[16], xf[16]; UINT32 ea; UINT32 delay; UINT32 cpu_off; UINT32 pending_irq; UINT32 test_irq; UINT32 fpscr; UINT32 fpul; UINT32 dbr; UINT32 exception_priority[128]; int exception_requesting[128]; INT8 irq_line_state[17]; device_irq_callback irq_callback; legacy_cpu_device *device; address_space *internal; address_space *program; direct_read_data *direct; address_space *io; UINT32 *m; INT8 nmi_line_state; UINT8 sleep_mode; int frt_input; int irln; int internal_irq_level; int internal_irq_vector; emu_timer *dma_timer[4]; emu_timer *refresh_timer; emu_timer *rtc_timer; emu_timer *timer[3]; UINT32 refresh_timer_base; int dma_timer_active[4]; int sh4_icount; int is_slave; int cpu_clock, bus_clock, pm_clock; int fpu_sz, fpu_pr; int ioport16_pullup, ioport16_direction; int ioport4_pullup, ioport4_direction; void (*ftcsr_read_callback)(UINT32 data); /* This MMU simulation is good for the simple remap used on Naomi GD-ROM SQ access *ONLY* */ UINT32 sh4_tlb_address[64]; UINT32 sh4_tlb_data[64]; UINT8 sh4_mmu_enabled; int cpu_type; #ifdef USE_SH4DRC int icount; int pcfsel; // last pcflush entry set int maxpcfsel; // highest valid pcflush entry UINT32 pcflushes[16]; // pcflush entries drc_cache * cache; /* pointer to the DRC code cache */ drcuml_state * drcuml; /* DRC UML generator state */ sh4_frontend * drcfe; /* pointer to the DRC front-end class */ UINT32 drcoptions; /* configurable DRC options */ /* internal stuff */ UINT8 cache_dirty; /* true if we need to flush the cache */ /* parameters for subroutines */ UINT64 numcycles; /* return value from gettotalcycles */ UINT32 arg0; /* print_debug argument 1 */ UINT32 arg1; /* print_debug argument 2 */ UINT32 irq; /* irq we're taking */ /* register mappings */ drcuml_parameter regmap[16]; /* parameter to register mappings for all 16 integer registers */ drcuml_codehandle * entry; /* entry point */ drcuml_codehandle * read8; /* read byte */ drcuml_codehandle * write8; /* write byte */ drcuml_codehandle * read16; /* read half */ drcuml_codehandle * write16; /* write half */ drcuml_codehandle * read32; /* read word */ drcuml_codehandle * write32; /* write word */ drcuml_codehandle * interrupt; /* interrupt */ drcuml_codehandle * nocode; /* nocode */ drcuml_codehandle * out_of_cycles; /* out of cycles exception handler */ UINT32 prefadr; UINT32 target; #endif } sh4_state; #ifdef USE_SH4DRC class sh4_frontend : public drc_frontend { public: sh4_frontend(sh4_state &state, UINT32 window_start, UINT32 window_end, UINT32 max_sequence); protected: virtual bool describe(opcode_desc &desc, const opcode_desc *prev); private: bool describe_group_0(opcode_desc &desc, const opcode_desc *prev, UINT16 opcode); bool describe_group_2(opcode_desc &desc, const opcode_desc *prev, UINT16 opcode); bool describe_group_3(opcode_desc &desc, const opcode_desc *prev, UINT16 opcode); bool describe_group_4(opcode_desc &desc, const opcode_desc *prev, UINT16 opcode); bool describe_group_6(opcode_desc &desc, const opcode_desc *prev, UINT16 opcode); bool describe_group_8(opcode_desc &desc, const opcode_desc *prev, UINT16 opcode); bool describe_group_12(opcode_desc &desc, const opcode_desc *prev, UINT16 opcode); bool describe_group_15(opcode_desc &desc, const opcode_desc *prev, UINT16 opcode); sh4_state &m_context; }; INLINE sh4_state *get_safe_token(device_t *device) { assert(device != NULL); assert(device->type() == SH3 || device->type() == SH4); return *(sh4_state **)downcast<legacy_cpu_device *>(device)->token(); } #else INLINE sh4_state *get_safe_token(device_t *device) { assert(device != NULL); assert(device->type() == SH3 || device->type() == SH4); return (sh4_state *)downcast<legacy_cpu_device *>(device)->token(); } #endif enum { ICF = 0x00800000, OCFA = 0x00080000, OCFB = 0x00040000, OVF = 0x00020000 }; /* Bits in SR */ #define T 0x00000001 #define S 0x00000002 #define I 0x000000f0 #define Q 0x00000100 #define M 0x00000200 #define FD 0x00008000 #define BL 0x10000000 #define sRB 0x20000000 #define MD 0x40000000 /* 29 bits */ #define AM 0x1fffffff #define FLAGS (MD|sRB|BL|FD|M|Q|I|S|T) /* Bits in FPSCR */ #define RM 0x00000003 #define DN 0x00040000 #define PR 0x00080000 #define SZ 0x00100000 #define FR 0x00200000 #define Rn ((opcode>>8)&15) #define Rm ((opcode>>4)&15) #define REGFLAG_R(n) (1 << (n)) #define REGFLAG_FR(n) (1 << (n)) #define REGFLAG_XR(n) (1 << (n)) /* register flags 1 */ #define REGFLAG_PR (1 << 0) #define REGFLAG_MACL (1 << 1) #define REGFLAG_MACH (1 << 2) #define REGFLAG_GBR (1 << 3) #define REGFLAG_VBR (1 << 4) #define REGFLAG_SR (1 << 5) #define REGFLAG_SGR (1 << 6) #define REGFLAG_FPUL (1 << 7) #define REGFLAG_FPSCR (1 << 8) #define REGFLAG_DBR (1 << 9) #define REGFLAG_SSR (1 << 10) #define REGFLAG_SPC (1 << 11) void sh4_exception_recompute(sh4_state *sh4); // checks if there is any interrupt with high enough priority void sh4_exception_request(sh4_state *sh4, int exception); // start requesting an exception void sh4_exception_unrequest(sh4_state *sh4, int exception); // stop requesting an exception void sh4_exception_checkunrequest(sh4_state *sh4, int exception); void sh4_exception(sh4_state *sh4, const char *message, int exception); // handle exception void sh4_change_register_bank(sh4_state *sh4, int to); void sh4_syncronize_register_bank(sh4_state *sh4, int to); void sh4_swap_fp_registers(sh4_state *sh4); void sh4_default_exception_priorities(sh4_state *sh4); // setup default priorities for exceptions void sh4_parse_configuration(sh4_state *sh4, const struct sh4_config *conf); void sh4_set_irq_line(sh4_state *sh4, int irqline, int state); // set state of external interrupt line #ifdef LSB_FIRST void sh4_swap_fp_couples(sh4_state *sh4); #endif void sh4_common_init(device_t *device); UINT32 sh4_getsqremap(sh4_state *sh4, UINT32 address); READ64_HANDLER( sh4_tlb_r ); WRITE64_HANDLER( sh4_tlb_w ); INLINE void sh4_check_pending_irq(sh4_state *sh4, const char *message) // look for highest priority active exception and handle it { int a,irq,z; irq = 0; z = -1; for (a=0;a <= SH4_INTC_ROVI;a++) { if (sh4->exception_requesting[a]) { if ((int)sh4->exception_priority[a] > z) { z = sh4->exception_priority[a]; irq = a; } } } if (z >= 0) { sh4_exception(sh4, message, irq); } } #endif /* __SH4COMN_H__ */
[ "Mike@localhost" ]
Mike@localhost
8da97996b3b05400945207630bfa70ab128623bb
aed00e5e89506629e4182f6074062d4f86644f07
/script/hardware_interface.cpp
53cf8d9916db2ec72cf2322cc48fcfb745833959
[]
no_license
AntoBrandi/Simple-Robot-Arm
a3504bb8c034dea07e4e235e793ff656e7daed13
65c86640353aeb4138929e04d8eb6d66bf1a2a95
refs/heads/master
2022-04-23T18:09:29.601832
2020-04-24T16:53:54
2020-04-24T16:53:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,726
cpp
#include <hardware_interface/joint_command_interface.h> #include <hardware_interface/joint_state_interface.h> #include <hardware_interface/robot_hw.h> #include <std_msgs/UInt16MultiArray.h> #include <ros/ros.h> class ArduinoBot : public hardware_interface::RobotHW { public: ArduinoBot() { // init the publisher and subscriber node ros::init(argc, argv, "node_interface"); pub = n.advertise<std_msgs::UInt16MultiArray>("servo_actuator",1000); sub = n.suscribe("servo_position",1000,read); msg.data.clear(); // connect and register the joint state interface hardware_interface::JointStateHandle state_handle_1("joint_1", &pos[0], &vel[0], &eff[0]); jnt_state_interface.registerHandle(state_handle_1); hardware_interface::JointStateHandle state_handle_2("joint_2", &pos[1], &vel[1], &eff[1]); jnt_state_interface.registerHandle(state_handle_2); hardware_interface::JointStateHandle state_handle_3("joint_3", &pos[2], &vel[2], &eff[2]); jnt_state_interface.registerHandle(state_handle_3); registerInterface(&jnt_state_interface); // connect and register the joint position interface hardware_interface::JointHandle pos_handle_1(jnt_state_interface.getHandle("joint_1"), &cmd[0]); jnt_pos_interface.registerHandle(pos_handle_1); hardware_interface::JointHandle pos_handle_2(jnt_state_interface.getHandle("joint_2"), &cmd[1]); jnt_pos_interface.registerHandle(pos_handle_2); hardware_interface::JointHandle pos_handle_3(jnt_state_interface.getHandle("joint_3"), &cmd[2]); jnt_pos_interface.registerHandle(pos_handle_3); registerInterface(&jnt_pos_interface); } read(const std_msgs::UInt16MultiArray& joints) { // Asks data about the servo motor position to the arduino controller for(int i = 0; i<3;i++){ pos[i]=joints.data[i]; } } write() { // Sends data about servo motor position to the arduino controller for (int i = 0; i<3;i++){ msg.data.push_back((int)((cmd[i]+1.57075)*180)/3.1415); } pub.publish(msg); } sleep() { rate.sleep(); } private: ros::NodeHandle n; ros::Publisher pub; ros::Subscriber sub; ros::Rate rate(10); std_msgs::UInt16MultiArray msg; hardware_interface::JointStateInterface jnt_state_interface; hardware_interface::PositionJointInterface jnt_pos_interface; // input from the controllers double cmd[3]; // output of the robot double pos[3]; double vel[3]; double eff[3]; }; int main(int argc, char **argv) { ArduinoBot robot; controller_manager::ControllerManager cm(&robot); while (true) { cm.update(robot.get_time(), robot.get_period()); robot.write(); robot.sleep(); } return 0; }
[ "antonio.brandi@outlook.it" ]
antonio.brandi@outlook.it
f31d492218d5a5164e8491352b55e6d3714200b9
2a4407f48856ced64bd1e70e2072cdd826aa8a14
/test/test_roscpp/test/src/param_update_test.cpp
7f9c12ff62325b804940504e51addce38a398e06
[]
no_license
ros/ros_comm
d6e75897bafb3f9a5bdc6074c1e9d5569c79d8a4
030e132884d613e49a576d4339f0b8ec6f75d2d8
refs/heads/noetic-devel
2023-08-31T23:10:32.862758
2023-04-20T14:08:38
2023-04-20T14:08:38
5,474,834
771
972
null
2023-09-12T21:44:32
2012-08-19T22:26:34
Python
UTF-8
C++
false
false
2,279
cpp
/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2008, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. ********************************************************************/ #include "ros/ros.h" int main(int argc, char** argv) { ros::init(argc, argv, "param_update_test"); ros::NodeHandle nh; while (ros::ok()) { ROS_INFO("getting parameters..."); int i = -1; if (nh.getParamCached("test", i)) { ROS_INFO("test=%d", i); } if (nh.getParamCached("test2", i)) { ROS_INFO("test2=%d", i); } if (nh.getParamCached("test3", i)) { ROS_INFO("test3=%d", i); } ros::WallDuration(0.1).sleep(); } return 0; }
[ "tfoote@willowgarage.com" ]
tfoote@willowgarage.com
8cb63b9b78cd536d71ab063985999366b19faebc
3d23b115ade7779122b269df86b3adcf01918cd3
/graphs/mst.cpp
00c01916447df63821c8d787fc354ec42d4ff3bf
[]
no_license
Pravesh-Jamgade/code
19938fb15f2df8b7d62840e4b0186d246e40f307
ea81ec55199eed885c6a03535aaecd06e5571474
refs/heads/master
2023-08-19T03:36:39.593886
2021-09-18T14:48:34
2021-09-18T14:48:34
407,887,780
0
0
null
null
null
null
UTF-8
C++
false
false
961
cpp
#include<bits/stdc++.h> using namespace std; const int MAX = 1e4 + 5; int id[MAX], nodes, edges; pair<long long, pair<int,int>> p[MAX]; void intialize(){ for(int i=0; i< MAX; i++){ id[i] = i; } } int root(int x){ while(id[x] != x){ id[x] = id[id[x]]; x = id[x]; } return x; } void union1(int x, int y){ int p = root(x); int q = root(y); id[p] = id[q]; } long long kruskal(pair<long long, pair<int,int>> p[]){ int x,y; long long cost, minCost=0; for(int i=0; i< edges; i++){ x = p[i].second.first; y = p[i].second.second; cost = p[i].first; if(root(x) != root(y)){ minCost += cost; union1(x,y); } } return minCost; } int main(){ freopen("input.txt", "r", stdin); int x,y; long long weight, cost, minCost; intialize(); cin>>nodes>>edges; for(int i=0; i< edges; i++){ cin>>x>>y>>weight; p[i] = make_pair(weight, make_pair(x,y)); } sort(p, p+edges); minCost = kruskal(p); cout<<minCost<<endl; return 0; }
[ "praveshjamgade@gmail.com" ]
praveshjamgade@gmail.com
d681ee609bd50301ed0666fdc92bb569a443651e
e763b855be527d69fb2e824dfb693d09e59cdacb
/aws-cpp-sdk-lightsail/include/aws/lightsail/model/ResourceType.h
92128354a424e17361c971abc9d26c4aef205384
[ "MIT", "Apache-2.0", "JSON" ]
permissive
34234344543255455465/aws-sdk-cpp
47de2d7bde504273a43c99188b544e497f743850
1d04ff6389a0ca24361523c58671ad0b2cde56f5
refs/heads/master
2023-06-10T16:15:54.618966
2018-05-07T23:32:08
2018-05-07T23:32:08
132,632,360
1
0
Apache-2.0
2023-06-01T23:20:47
2018-05-08T15:56:35
C++
UTF-8
C++
false
false
1,241
h
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #pragma once #include <aws/lightsail/Lightsail_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSString.h> namespace Aws { namespace Lightsail { namespace Model { enum class ResourceType { NOT_SET, Instance, StaticIp, KeyPair, InstanceSnapshot, Domain, PeeredVpc, LoadBalancer, LoadBalancerTlsCertificate, Disk, DiskSnapshot }; namespace ResourceTypeMapper { AWS_LIGHTSAIL_API ResourceType GetResourceTypeForName(const Aws::String& name); AWS_LIGHTSAIL_API Aws::String GetNameForResourceType(ResourceType value); } // namespace ResourceTypeMapper } // namespace Model } // namespace Lightsail } // namespace Aws
[ "henso@amazon.com" ]
henso@amazon.com
84498f78a8810b6e87c0c8c9daa8b1638b235d66
517b8f53ecc24928a787ab92cb729b7ebe6b3de4
/389 BASICALLY SPEAKING.cpp
4c119070127f877e54c10ec5f9b0f55640300d98
[]
no_license
sajalkhan/UVA-ONLINE-JUDGE
4c738fe946d536a5b058da56d8a025be54514856
801ebd2a6366d11226e275210171c66cc4baecfe
refs/heads/master
2021-05-12T08:15:41.628850
2018-01-12T19:32:30
2018-01-12T19:32:30
117,277,417
1
0
null
null
null
null
UTF-8
C++
false
false
1,561
cpp
/**-------------------------------------- MD.SOHARUB HOSSEN DAFFODIL INTERNATIONAL UNIVERSITY PROBLEM: UVA 389 BASICALLY SPEAKING ----------------------------------------*/ #include<bits/stdc++.h> using namespace std; int other_to_decimal(string s,int a) { int ln=s.size(); int p=ln-1; long long result=0; for(int i=0; i<ln; i++) { if(isdigit(s[i])) result+=(s[i]-'0')*pow(a,p--); if(isalpha(s[i])) result+=(s[i]-55)*pow(a,p--); } return result; } string decimal_to_other(long long num,int b) { if(!num)return "0"; string result; while(num) { int n=num%b; if(n<10)result+=n+'0'; else result+=n+55; num/=b; } reverse(result.begin(),result.end()); return result; } int main() { string s; int a,b; while(cin>>s>>a>>b) { if(a==10) { stringstream ss(s); long long n; ss>>n; string s1=decimal_to_other(n,b); int ln=s1.size(); if(ln<=7) { for(int i=0;i<7-ln;i++)printf(" "); cout<<s1<<endl; } else printf(" ERROR\n"); } else { long long n=other_to_decimal(s,a); string s1=decimal_to_other(n,b); int ln=s1.size(); if(ln<=7) { for(int i=0;i<7-ln;i++)printf(" "); cout<<s1<<endl; } else printf(" ERROR\n"); } } return 0; }
[ "sajalhossen@yahoo.com" ]
sajalhossen@yahoo.com
63601d52d33c9d54071905905b58be453a896972
992d3f90ab0f41ca157000c4b18d071087d14d85
/draw/CPPCODER.CPP
df1cbad125fdc62a8c9606dc67eae4e1c7b1039d
[]
no_license
axemclion/visionizzer
cabc53c9be41c07c04436a4733697e4ca35104e3
5b0158f8a3614e519183055e50c27349328677e7
refs/heads/master
2020-12-25T19:04:17.853016
2009-05-22T14:44:53
2009-05-22T14:44:53
29,331,323
0
0
null
null
null
null
UTF-8
C++
false
false
14,855
cpp
# include <process.h> # include <graphics.h> # include <dos.h> # include <stdio.h> # include <ctype.h> # include <stdlib.h> # include <string.h> # include <dir.h> # include <conio.h> # include <mouse.h> int fc(char *file1,char *file2,char *dest); void ccoder(char *); int main(int argc,char *argv[]) { if (argc < 1) return 1; ccoder(argv[1]); char path[100],path1[100]; strcpy(path,argv[1]); strcpy(path1,path); strcat(path1,"prog.java"); fc("code.cpp",NULL,path1); strcpy(path1,path); strcat(path1,"code.h"); remove(path1); remove("head"); fc("head","code.tmp",path1); remove("head"); FILE *fp = fopen("end.bat","wt"); fprintf(fp,"cls"); fclose(fp); strcpy(path1,path); return 0; } void ccoder(char *path) { char object[100]; remove("code.cpp"); strcat(path,"\\"); char *path1 =(char *)calloc(1,100); #ifdef AXE printf("%s",path); getch();getch(); click(); # endif char *name; if (!path1) return; strcpy(path1,path); FILE *fp,*prog,*draw; strcat(path1,"code.cpp"); prog=fopen("code.cpp","wt"); if (prog == NULL) return ; strcpy(path1,path); /**********writing to file ***********/ fprintf(prog,"import java.awt.*;\n"); fprintf(prog,"import javax.swing.*;\n"); fprintf(prog,"import java.applet.*;\n"); fp = fopen ("object.tmp","rt"); if (fp != NULL) { fprintf(prog,"\n\nvoid redraw();\n\n"); draw = fopen("draw.ini","rt"); int type=0,c=0; fgets(object,100,fp); if (object[strlen(object)-1] == '\n') object[strlen(object)-1] = NULL; fgets(path1,100,fp); do { rewind(draw); while (path1[c] != '=' && path1[c]!= NULL) c++; type = atoi(path1+c+1); c = 0; fscanf(draw,"%d %s",&c,path1); do{ char ss[100]; fscanf(draw,"%s\n",ss); if (type == c) break; fscanf(draw,"%d %s",&c,path1); }while(!feof(draw)); fprintf(prog,"%s %s(",path1,object); { FILE *head; head = fopen("head","at"); fprintf(head,"extern %s %s;\n",path1,object); fclose(head); } //fist arguement fgets(path1,100,fp); c=0; while (path1[c] != '=' && path1[c]!= NULL) c++; name = path1+c+1; if (name[strlen(name)-1] == '\n') name[strlen(name)-1] = NULL; if (isdigit(name[0])) fprintf(prog,"%d",atoi(name)); else fprintf(prog,"\"%s\"",name); fgets(path1,100,fp);c=0; do{ while (path1[c] != '=' && path1[c]!= NULL) c++; name = path1+c+1; if (name[strlen(name)-1] == '\n') name[strlen(name)-1] = NULL; if (isdigit(name[0])) fprintf(prog,",%d",atoi(name)); else fprintf(prog,",\"%s\"",name); fgets(path1,100,fp);c=0; }while (strcmp(path1,"**********\n") != 0 && !(feof(fp))); fprintf(prog,");\n"); fgets(object,100,fp);fgets(path1,100,fp); object[strlen(object)-1] = NULL; }while (!feof(fp)); fclose(draw); fclose(fp); } fprintf(prog,"\n\nint main()\n{\n"); fprintf(prog,"\tint gdriver = VGA, gmode=VGAMED, errorcode;\n");fprintf(prog,"\tinitgraph(&gdriver, &gmode,\"\");\n"); fprintf(prog,"\terrorcode = graphresult();");fprintf(prog,"\n\tif (errorcode != grOk) // an error occurred \n");fprintf(prog,"\t\t{\n"); fprintf(prog,"\t\tprintf(\"Graphics error:\");\n");fprintf(prog,"\t\tprintf(\"Press any key to halt:\");\n");fprintf(prog,"\t\tgetch();\n");fprintf(prog,"\t\texit(1);\n\t\t}\n"); fprintf(prog,"\nredraw();"); fprintf(prog,"\nmouse_present();\nshow_mouse();"); fprintf(prog,"\nwhile(1)\n{\nfocus = -1;key = 0;\n"); fprintf(prog,"\tmouse1 = mouse;\n\tmouse = status();"); fprintf(prog,"\tif (kbhit()) \n\t\tkey = getch();\n"); //start of events fp = fopen("object.tmp","rt"); draw = fopen("code.tmp","rt"); if (fp != NULL && draw != NULL) { fgets(object,100,fp); do{ object[strlen(object)-1] = NULL; fprintf(prog,"\tif (inarea(mouse.x,mouse.y,%s.x1,%s.y1,%s.x2,%s.y2))\n\t{\n\t\tfocus = %s.action();\n", object,object,object,object,object); //events are writen here rewind(draw); fgets(path1,100,draw); do{ int op = 0; while (path1[op++] != ' '); name=path1+op; if (path1[strlen(path1) -1] == '\n') path1[strlen(path1) -1] = NULL; if (strncmp(object,name,strlen(object)) == 0) fprintf(prog,"\t\t%s;\n",name); op = 1;fgetc(draw); while (op != 0) { if (path1[0] == '\"') while (fgetc(draw) == '\"'); else if (path1[0] == '\'') while (fgetc(draw) == '\''); else if (path1[0] =='{') op++; else if (path1[0] =='}') op--; path1[0] = fgetc(draw); }//read till end of function fgets(path1,100,draw); }while (!feof(draw)); //events are completed here fprintf(prog,"\t}//end of %s\n\n",object); while (strcmp(object,"**********\n") != 0) fgets(object,100,fp); fgets(object,100,fp); fgets(path1,100,fp); }while(!feof(fp)); fclose(fp); } fclose(draw); //end of events fprintf(prog,"\n}//end of main program execution loop"); fprintf(prog,"\n}//end of function main"); fprintf(prog,"\n\nvoid redraw()\n\t{\n"); fprintf(prog,"char pattern[8];\n"); fp = fopen("draw.tmp","rt"); while (!feof(fp) && fp != NULL) { fscanf(fp,"%s ",&object); int sx,sy,ex,ey,thk,ls,col,fs,fc; unsigned int fonts,fontn,fontdir; char cp[8]; sx=sy=ex=ey=thk=ls=col=fs=fc=fonts=fontn=fontdir=0; if (strcmp(object,"object") == 0) { fgets(object,100,fp); *(object + strlen(object) -1 ) = NULL; fprintf(prog,"%s.draw();\n",object); }//end of drawing objects else if (strcmp(object,"print") == 0) { fscanf(fp,"%03d,%03d,", &sx,&sy); fgets(object,100,fp); *(object + strlen(object) -1 ) = NULL; fprintf(prog,"gotoxy(%d,%d);\n",sx,sy); fprintf(prog,"printf(\"%s\");\n",object); }//end of text else if (strcmp(object,"line") == 0 || strcmp(object,"rectangle") == 0) { fscanf(fp,"%03d,%03d,%03d,%03d,%03d,%03d,%03d,%07d\n", &sx,&sy,&ex,&ey,&col,&thk,&ls,&fontn); fprintf(prog,"setcolor(%d);setlinestyle(%d,%d,%d);\n",col,ls,fontn,thk); if (strcmp(object,"rectangle") == 0) fprintf(prog,"rectangle(%d,%d,%d,%d);\n",sx,sy,ex,ey); else fprintf(prog,"line(%d,%d,%d,%d);\n",sx,sy,ex,ey); }//end of drawing a line else if (strcmp(object,"bar") == 0) { fscanf(fp,"%03d,%03d,%03d,%03d,%03d,%03d\n", &sx,&sy,&ex,&ey,&fc,&fs); fprintf(prog,"setfillstyle(%d,%d);\n",fs,fc); fprintf(prog,"bar(%d,%d,%d,%d);\n",sx,sy,ex,ey); }//end of drawing a rectangle else if (strcmp(object,"barp") == 0) { fscanf(fp,"%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d\n", &sx,&sy,&ex,&ey,&fc, &cp[0],&cp[1],&cp[2],&cp[3],&cp[4],&cp[5],&cp[6],&cp[7]); fprintf(prog,"\npattern[0] = %d;",cp[0]);fprintf(prog,"\npattern[1] = %d;",cp[1]);fprintf(prog,"\npattern[2] = %d;",cp[2]);fprintf(prog,"\npattern[3] = %d;",cp[3]); fprintf(prog,"\npattern[4] = %d;",cp[4]);fprintf(prog,"\npattern[5] = %d;",cp[5]);fprintf(prog,"\npattern[6] = %d;",cp[6]);fprintf(prog,"\npattern[7] = %d;",cp[7]); fprintf(prog,"\nsetfillpattern(pattern,%d);\n",fc); fprintf(prog,"bar(%d,%d,%d,%d);\n",sx,sy,ex,ey); } else if (strcmp(object,"text") == 0) { fscanf(fp,"%02d,%03d,%03d,%02d,%02d,%02d,", &col,&sx,&sy, &fontn,&fontdir,&fonts); fgets(object,100,fp); *(object + strlen(object) -1 ) = NULL; fprintf(prog,"setcolor(%d);\n",col); fprintf(prog,"settextstyle(%d,%d,%d);\n",fontn,fontdir,fonts); fprintf(prog,"outtextxy(%d,%d,\"%s\");\n",sx,sy,object); }//end of text else if (strcmp(object,"ellipse") == 0) { fscanf(fp,"%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d\n", &sx,&sy,&ex,&ey,&fonts,&fontn,&col,&thk); fprintf(prog,"setcolor(%d);\n",col); fprintf(prog,"setlinestyle(0,0,%d);\n",thk); fprintf(prog,"ellipse(%d,%d,%d,%d,%d,%d);\n",sx,sy,ex,ey,fonts,fontn); }//end of ellipse else if (strcmp(object,"pie") == 0) { fscanf(fp,"%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d\n", &sx,&sy,&ex,&ey,&fonts,&fontn, &col,&thk,&fc,&fs); fprintf(prog,"setcolor(%d);\n",col); fprintf(prog,"setlinestyle(0,0,%d);\n",thk); fprintf(prog,"setfillstyle(%d,%d);\n",fs,fc); fprintf(prog,"sector(%d,%d,%d,%d,%d,%d);\n",sx,sy,ex,ey,fonts,fontn); }//end of drawing simple piechart else if (strcmp(object,"piepattern") == 0) { int xradius,yradius; fscanf(fp,"%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d\n", &sx,&sy, &ex,&ey, &xradius,&yradius, &col,&thk,&fc, &cp[0],&cp[1],&cp[2],&cp[3],&cp[4],&cp[5],&cp[6],&cp[7]); fprintf(prog,"setcolor(%d);\n",col); fprintf(prog,"setlinestyle(0,0,%d);\n",thk); fprintf(prog,"\npattern[0] = %d;",cp[0]);fprintf(prog,"\npattern[1] = %d;",cp[1]);fprintf(prog,"\npattern[2] = %d;",cp[2]);fprintf(prog,"\npattern[3] = %d;",cp[3]); fprintf(prog,"\npattern[4] = %d;",cp[4]);fprintf(prog,"\npattern[5] = %d;",cp[5]);fprintf(prog,"\npattern[6] = %d;",cp[6]);fprintf(prog,"\npattern[7] = %d;",cp[7]); fprintf(prog,"setfillpattern(pattern,%d);\n",fc); fprintf(prog,"sector(%d,%d,%d,%d,%d,%d);\n",sx,sy,ex,ey,fonts,fontn); }//end of complex pie chart else if (strcmp(object,"fillellipse") == 0) { fscanf(fp,"%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d\n", &sx,&sy,&ex,&ey, &col,&thk,&fc,&fs); fprintf(prog,"setcolor(%d);\n",col); fprintf(prog,"setlinestyle(0,0,%d);\n",thk); fprintf(prog,"setfillstyle(%d,%d);\n",fs,fc); fprintf(prog,"fillellipse(%d,%d,%d,%d);\n",sx,sy,ex,ey); }//end of fillellipse simple else if (strcmp(object,"fillellipsep") == 0) { fscanf(fp,"%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d\n", &sx,&sy,&ex,&ey, &col,&thk,&fc, &cp[0],&cp[1],&cp[2],&cp[3],&cp[4],&cp[5],&cp[6],&cp[7]); fprintf(prog,"setcolor(%d);\n",col); fprintf(prog,"setlinestyle(0,0,%d);\n",thk); fprintf(prog,"\npattern[0] = %d;",cp[0]);fprintf(prog,"\npattern[1] = %d;",cp[1]);fprintf(prog,"\npattern[2] = %d;",cp[2]);fprintf(prog,"\npattern[3] = %d;",cp[3]); fprintf(prog,"\npattern[4] = %d;",cp[4]);fprintf(prog,"\npattern[5] = %d;",cp[5]);fprintf(prog,"\npattern[6] = %d;",cp[6]);fprintf(prog,"\npattern[7] = %d;",cp[7]); fprintf(prog,"setfillpattern(pattern,%d);\n",fc); fprintf(prog,"fillellipse(%d,%d,%d,%d);\n",sx,sy,ex,ey); }//end of complex ellipse filler else if (strcmp(object,"fillstyle") == 0) { fscanf(fp,"%03d,%03d,%02d,%02d,%02d\n", &sx,&sy,&col,&fc,&fs); fprintf(prog,"setfillstyle(%d,%d);\n",fs,fc); fprintf(prog,"floodfill(%d,%d,%d);\n",sx,sy,col); }//end of floodfilling else if (strcmp(object,"fillpattern") == 0) { fscanf(fp,"%03d,%03d,%02d,%02d,%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d\n", &sx,&sy,&col,&fc, &cp[0],&cp[1],&cp[2],&cp[3],&cp[4],&cp[5],&cp[6],&cp[7]); fprintf(prog,"\npattern[0] = %d;",cp[0]);fprintf(prog,"\npattern[1] = %d;",cp[1]);fprintf(prog,"\npattern[2] = %d;",cp[2]);fprintf(prog,"\npattern[3] = %d;",cp[3]); fprintf(prog,"\npattern[4] = %d;",cp[4]);fprintf(prog,"\npattern[5] = %d;",cp[5]);fprintf(prog,"\npattern[6] = %d;",cp[6]);fprintf(prog,"\npattern[7] = %d;",cp[7]); fprintf(prog,"setfillpattern(pattern,%d);\n",fc); fprintf(prog,"floodfill(%d,%d,%d);\n",sx,sy,col); }//end of fill pattern else if (strcmp(object,"polygon") == 0) { fscanf(fp,"%03d,%03d,%03d,%03d,%07d\n", &fontdir,&col,&ls,&thk,&fontn); int points[30]; fprintf(prog,"{\nint poly[] = {"); for (int i = 0; i < fontdir*2 && i < 30;i+=2) { fscanf(fp,"%03d,%03d",&points[i],&points[i+1]); fprintf(prog,"%3d,%3d,",points[i],points[i+1]); }//end of for next loop fprintf(prog,"0};\nsetcolor(%d);\n",col); fprintf(prog,"setlinestyle(%d,%d,%d);\n",ls,fontn,thk); fprintf(prog,"drawpoly(%d,poly);}\n",fontdir); }//end of simple polygon else if (strcmp(object,"fillpolygon") == 0) { fscanf(fp,"%03d,%03d,%03d,%03d,%03d,%03d,%07d\n", &fontdir,&col,&ls,&thk,&fc,&fs,&fontn); int points[30]; fprintf(prog,"{\nint poly[] = {"); for (int i = 0; i < fontdir*2 && i < 30;i+=2) { fscanf(fp,"%03d,%03d",&points[i],&points[i+1]); fprintf(prog,"%3d,%3d,",points[i],points[i+1]); }//end of for next loop fprintf(prog,"0};\nsetcolor(%d);\n",col); fprintf(prog,"setlinestyle(%d,0,%d);\n",ls,fontn,thk); fprintf(prog,"setfillstyle(%d,%d);\n",fs,fc); fprintf(prog,"fillpoly(%d,poly);}\n",fontdir); }//end of simple polygon filling simple else if (strcmp(object,"fillpolygonp") == 0) { fscanf(fp,"%03d,%03d,%03d,%03d,%03d,%07d,%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d\n", &fontdir,&col,&ls,&thk,&fc,&fontn, &cp[0],&cp[1],&cp[2],&cp[3],&cp[4],&cp[5],&cp[6],&cp[7]); int points[30]; fprintf(prog,"{\nint poly[] = {"); for (int i = 0; i < fonts*2 && i < 30;i+=2) { fscanf(fp,"%03d,%03d",&points[i],&points[i+1]); fprintf(prog,"%3d,%3d,",points[i],points[i+1]); }//end of for next loop fprintf(prog,"0};\nsetcolor(%d);\n",col); fprintf(prog,"setlinestyle(%d,%d,%d);\n",ls,fontn,thk); fprintf(prog,"\npattern[0] = %d;",cp[0]);fprintf(prog,"\npattern[1] = %d;",cp[1]);fprintf(prog,"\npattern[2] = %d;",cp[2]);fprintf(prog,"\npattern[3] = %d;",cp[3]); fprintf(prog,"\npattern[4] = %d;",cp[4]);fprintf(prog,"\npattern[5] = %d;",cp[5]);fprintf(prog,"\npattern[6] = %d;",cp[6]);fprintf(prog,"\npattern[7] = %d;",cp[7]); fprintf(prog,"setfillpattern(pattern,%d);\n",fc); fprintf(prog,"fillpoly(%d,poly);}\n",fontdir); }//end of simple polygon filling simple else if (strcmp(object,"bmp") == 0) { int sx,sy,ex,ey; fscanf(fp,"%03d,%03d,%03d,%03d,%s\n", &sx,&sy,&ex,&ey,&object); fprintf(prog,"loadbmp(\"%s\",%d,%d,%d,%d);\n",object,sx,sy,ex,ey); }//end of loading bitmaps }//end of parsing all values fclose(fp); fprintf(prog,"\n\t}//end of redrawing all objects\n\n"); fclose(prog); free(path); free(path1); }//end of function int fc(char *file1,char *file2,char *dest) { FILE *src,*dst; src = fopen(file1,"rt"); dst = fopen(dest,"at"); if (dst == NULL) return 1; char *buffer = (char *)calloc(1,100); if (src != NULL) { fgets(buffer,100,src); do{ fprintf(dst,"%s",buffer); fgets(buffer,100,src); }while (!feof(src)); fclose(src); } src = fopen(file2,"rt"); if (src != NULL) { fgets(buffer,100,src); do{ fprintf(dst,"%s",buffer); fgets(buffer,100,src); }while (!feof(src)); fclose(src); } free(buffer); fclose(dst); return 0; }
[ "github@nparashuram.com" ]
github@nparashuram.com
8593be8827ca07d71130a0b3aa9c0b4141b5b216
b77349e25b6154dae08820d92ac01601d4e761ee
/List/Ultimate Grid/Examples/BasicDlg/Ex3Dlg.cpp
89b362fda7fa827ec412e6d43d762dbb00ef1ade
[]
no_license
ShiverZm/MFC
e084c3460fe78f820ff1fec46fe1fc575c3e3538
3d05380d2e02b67269d2f0eb136a3ac3de0dbbab
refs/heads/master
2023-02-21T08:57:39.316634
2021-01-26T10:18:38
2021-01-26T10:18:38
332,725,087
0
0
null
2021-01-25T11:35:20
2021-01-25T11:29:59
null
UTF-8
C++
false
false
3,165
cpp
// Ex3Dlg.cpp : implementation file // #include "stdafx.h" //: include the header file for the Ultimate Grid derived class #include "MyCug.h" #include "Ex3.h" #include "Ex3Dlg.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CEx3Dlg dialog CEx3Dlg::CEx3Dlg(CWnd* pParent /*=NULL*/) : CDialog(CEx3Dlg::IDD, pParent) { //{{AFX_DATA_INIT(CEx3Dlg) //}}AFX_DATA_INIT // Note that LoadIcon does not require a subsequent DestroyIcon in Win32 m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); } void CEx3Dlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CEx3Dlg) //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CEx3Dlg, CDialog) //{{AFX_MSG_MAP(CEx3Dlg) ON_WM_SYSCOMMAND() ON_WM_PAINT() ON_WM_QUERYDRAGICON() ON_BN_CLICKED(IDC_CHECKXP, OnCheckxp) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CEx3Dlg message handlers BOOL CEx3Dlg::OnInitDialog() { CDialog::OnInitDialog(); // Add "About..." menu item to system menu. // IDM_ABOUTBOX must be in the system command range. ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX); ASSERT(IDM_ABOUTBOX < 0xF000); CMenu* pSysMenu = GetSystemMenu(FALSE); if (pSysMenu != NULL) { CString strAboutMenu; strAboutMenu.LoadString(IDS_ABOUTBOX); if (!strAboutMenu.IsEmpty()) { pSysMenu->AppendMenu(MF_SEPARATOR); pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu); } } // Set the icon for this dialog. The framework does this automatically // when the application's main window is not a dialog SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon // TODO: Add extra initialization here // attach the grid to the static control m_ctrl.AttachGrid(this, IDC_GRID); return TRUE; // return TRUE unless you set the focus to a control } void CEx3Dlg::OnSysCommand(UINT nID, LPARAM lParam) { if ((nID & 0xFFF0) == IDM_ABOUTBOX) { CAboutDlg dlgAbout; dlgAbout.DoModal(); } else { CDialog::OnSysCommand(nID, lParam); } } // If you add a minimize button to your dialog, you will need the code below // to draw the icon. For MFC applications using the document/view model, // this is automatically done for you by the framework. void CEx3Dlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this); // device context for painting SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0); // Center icon in client rectangle int cxIcon = GetSystemMetrics(SM_CXICON); int cyIcon = GetSystemMetrics(SM_CYICON); CRect rect; GetClientRect(&rect); int x = (rect.Width() - cxIcon + 1) / 2; int y = (rect.Height() - cyIcon + 1) / 2; // Draw the icon dc.DrawIcon(x, y, m_hIcon); } else { CDialog::OnPaint(); } } // The system calls this to obtain the cursor to display while the user drags // the minimized window. HCURSOR CEx3Dlg::OnQueryDragIcon() { return (HCURSOR) m_hIcon; } void CEx3Dlg::OnCheckxp() { UGXPThemes::UseThemes(!UGXPThemes::UseThemes()); Invalidate(); }
[ "w.z.y2006@163.com" ]
w.z.y2006@163.com
84639188ad69be1e93eba3fd87b3c6a5b4a74088
e8d783d45ac0f3ef7f38eadc5b44b7e2a595179f
/irrlicht/sound.cpp
0e5296ac0fcc57bb47abffddeb45bc036698fdaf
[ "Zlib" ]
permissive
osom8979/example
e3be7fd355e241be6b829586b93d3cbcb1fbf3a5
603bb7cbbc6427ebdc7de28f57263c47d583c2e4
refs/heads/master
2023-07-21T19:55:55.590941
2023-07-20T02:06:42
2023-07-20T02:06:42
52,238,897
2
1
NOASSERTION
2023-07-20T02:06:43
2016-02-22T01:42:09
C++
UTF-8
C++
false
false
2,007
cpp
/*! Sound Factory. provides a sound interface */ #include "sound.h" //#define USE_IRRKLANG #ifdef USE_IRRKLANG #include <irrKlang.h> #ifdef _IRR_WINDOWS_ #pragma comment (lib, "irrKlang.lib") #endif using namespace irrklang; struct soundfile: public IFileReader { soundfile ( io::IReadFile* f ): file (f ) {} virtual ~soundfile () {file->drop ();} virtual ik_s32 read(void* buffer, ik_u32 sizeToRead) {return file->read ( buffer, sizeToRead );} virtual bool seek(ik_s32 finalPos, bool relativeMovement = false) {return file->seek ( finalPos, relativeMovement );} virtual ik_s32 getSize() {return file->getSize ();} virtual ik_s32 getPos() {return file->getPos ();} virtual const ik_c8* getFileName() {return file->getFileName ();} io::IReadFile* file; }; struct klangFactory : public irrklang::IFileFactory { klangFactory ( IrrlichtDevice *device ) {Device = device;} virtual irrklang::IFileReader* createFileReader(const ik_c8* filename) { io::IReadFile* file = Device->getFileSystem()->createAndOpenFile(filename); if ( 0 == file ) return 0; return new soundfile ( file ); } IrrlichtDevice *Device; }; ISoundEngine *engine = 0; ISound *backMusic = 0; void sound_init ( IrrlichtDevice *device ) { engine = createIrrKlangDevice (); if ( 0 == engine ) return; klangFactory *f = new klangFactory ( device ); engine->addFileFactory ( f ); } void sound_shutdown () { if ( backMusic ) backMusic->drop (); if ( engine ) engine->drop (); } void background_music ( const c8 * file ) { if ( 0 == engine ) return; if ( backMusic ) { backMusic->stop (); backMusic->drop (); } backMusic = engine->play2D ( file, true, false, true ); if ( backMusic ) { backMusic->setVolume ( 0.5f ); } } #else void sound_init(IrrlichtDevice *device) { } void sound_shutdown() { } void background_music(const c8 * file) { } #endif
[ "osom8979@gmail.com" ]
osom8979@gmail.com
cc931e9cd7fc233654e794363cc42639e86c9b0c
8a3449c6dc68a9c631ee47b68b3c01a03ea66224
/src/base/FileHandle.cpp
bf3bb47878635fed642ff88d0211d66cbe9028b8
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-other-permissive" ]
permissive
woimalabs/libw
1985127215523a10857e30fae5fd1cc586cd0e94
8ffa06d3a9efc49d19cdfe682f89f3c4afe9a58a
refs/heads/master
2021-04-12T04:21:34.001019
2018-09-23T18:22:11
2018-09-23T18:22:11
12,668,614
1
1
null
2018-04-08T20:11:16
2013-09-07T17:27:37
C++
UTF-8
C++
false
false
4,927
cpp
/** * libw * * Copyright (C) 2012-2015 Woima Solutions * * This software is provided 'as-is', without any express or implied warranty. In * no event will the authors be held liable for any damages arising from the use * of this software. * * Permission is granted to anyone to use this software for any purpose, including * commercial applications, and to alter it and redistribute it freely, subject to * the following restrictions: * * 1) The origin of this software must not be misrepresented; you must not claim * that you wrote the original software. If you use this software in a product, * an acknowledgment in the product documentation is appreciated. * * 2) Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * * 3) This notice may not be removed or altered from any source distribution. * * @author antti.peuhkurinen@woimasolutions.com */ #include "w/base/FileHandle.hpp" #include "w/base/Exception.hpp" #include "w/base/Log.hpp" #include <stdio.h> #include <unistd.h> #include <string> #include <limits.h> namespace w { #ifdef ANDROID FileHandle::FileHandle(const std::string& filename, Type::Enum type, AAssetManager* androidAssetManager): #else // linux FileHandle::FileHandle(const std::string& filename, Type::Enum type): #endif type_(type), filename_(filename), currentReadIndex_(0), #ifdef ANDROID androidAssetManager_(androidAssetManager), #endif byteSize_(0) { open(); } FileHandle::~FileHandle() { close(); } // Opens the file and defines byte size void FileHandle::open() { // LOGD("opening file: %s", filename_.c_str()); #ifdef ANDROID file_ = AAssetManager_open(androidAssetManager_, filename_.c_str(), AASSET_MODE_STREAMING); if (file_ == NULL) { LOGE("Failed to load filename: '%s'", filename_.c_str()); throw Exception("FileHandle::open() failed"); } byteSize_ = AAsset_getLength(file_); #else // iOS and Linux const char* tmp = NULL; if(type_ == Type::ReadOnly_ExceptionIfNotExisting) { tmp = "rb"; } else if(type_ == Type::ReadOnly_CreateIfNotExisting) { tmp = "rb"; } else if(type_ == Type::WriteOnly_DestroyOldContent_CreateNewIfNotExisting) { tmp = "wb+"; } file_ = fopen(filename_.c_str(), tmp); if (file_ == NULL) { perror(filename_.c_str()); LOGE("Failed to load filename: '%s'", filename_.c_str()); throw Exception("FileHandle::open() failed"); } fseek(file_, 0, SEEK_END); long tmpSize = ftell(file_); if(tmpSize > UINT_MAX) { LOGE("Failed to load filename: '%s'", filename_.c_str()); throw Exception("FileHandle::open() file too large."); } byteSize_ = tmpSize & UINT_MAX;; fseek(file_, 0, SEEK_SET); #endif } unsigned int FileHandle::read(char* targetBuffer, unsigned int byteAmountToRead) { unsigned int bytesRead = 0; unsigned int bytesToBeRead = byteAmountToRead; while(true) { #ifdef ANDROID unsigned int readAmount = AAsset_read(file_, targetBuffer, bytesToBeRead); #else // linux size_t readAmount = fread(targetBuffer, sizeof(char), bytesToBeRead, file_); #endif bytesRead += readAmount; bytesToBeRead -= readAmount; if(readAmount == 0 || bytesToBeRead <= 0) { break; } } currentReadIndex_ += bytesRead; return bytesRead; } unsigned int FileHandle::write(const char* sourceBuffer, unsigned int byteAmountToWrite) { return fwrite(sourceBuffer, byteAmountToWrite, 1, file_); } std::string FileHandle::filename() { return filename_; } unsigned int FileHandle::byteSize() { return byteSize_; } #ifdef ANDROID AAsset* FileHandle::pointer() { return file_; } #else // linux FILE* FileHandle::pointer() { return file_; } #endif bool FileHandle::exists(const std::string& fullPath) { bool r = false; if(access(fullPath.c_str(), F_OK) != -1) { r = true; } return r; } void FileHandle::close() { #ifdef ANDROID AAsset_close(file_); #else // linux fclose(file_); #endif file_ = NULL; } }
[ "antti.peuhkurinen@woimasolutions.com" ]
antti.peuhkurinen@woimasolutions.com
dccb17880b282709f5a34a69d47c5f8f6d5e0a20
c23b42b301b365f6c074dd71fdb6cd63a7944a54
/contest/Jakarta/2014/j.cpp
c2fef12987b6aaa32a0609573354efaaecdb6b6d
[]
no_license
NTUwanderer/PECaveros
6c3b8a44b43f6b72a182f83ff0eb908c2e944841
8d068ea05ee96f54ee92dffa7426d3619b21c0bd
refs/heads/master
2020-03-27T22:15:49.847016
2019-01-04T14:20:25
2019-01-04T14:20:25
147,217,616
1
0
null
2018-09-03T14:40:49
2018-09-03T14:40:49
null
UTF-8
C++
false
false
2,553
cpp
// eddy1021 #include <bits/stdc++.h> using namespace std; typedef double D; typedef long long ll; typedef pair<int,int> PII; #define mod9 1000000009ll #define mod7 1000000007ll #define INF 1023456789ll #define INF16 10000000000000000ll #define FI first #define SE second #define PB push_back #define MP make_pair #define MT make_tuple #define eps 1e-9 #define SZ(x) (int)(x).size() #define ALL(x) (x).begin(), (x).end() ll getint(){ ll _x=0,_tmp=1; char _tc=getchar(); while( (_tc<'0'||_tc>'9')&&_tc!='-' ) _tc=getchar(); if( _tc == '-' ) _tc=getchar() , _tmp = -1; while(_tc>='0'&&_tc<='9') _x*=10,_x+=(_tc-'0'),_tc=getchar(); return _x*_tmp; } ll mypow( ll _a , ll _x , ll _mod ){ if( _x == 0 ) return 1ll; ll _tmp = mypow( _a , _x / 2 , _mod ); _tmp = ( _tmp * _tmp ) % _mod; if( _x & 1 ) _tmp = ( _tmp * _a ) % _mod; return _tmp; } bool equal( D _x , D _y ){ return _x > _y - eps && _x < _y + eps; } int __ = 1 , cs; /*********default*********/ #define N 1000010 int n , m; ll a[ N ] , pa[ N ] , b[ N ]; char c[ N ]; void build(){ } void init(){ n = getint(); m = getint(); scanf( "%s" , c + 1 ); a[ 0 ] = 1500000; for( int i = 1 ; i <= n ; i ++ ) if( c[ i ] == '/' ) a[ i ] = a[ i - 1 ] + 1 , b[ i ] = a[ i ] - 1; else if( c[ i ] == '\\' ) a[ i ] = a[ i - 1 ] - 1 , b[ i ] = a[ i ]; else a[ i ] = a[ i - 1 ] , b[ i ] = a[ i ]; pa[ 0 ] = 0; for( int i = 1 ; i <= n ; i ++ ) if( c[ i ] == '_' ) pa[ i ] = pa[ i - 1 ] + 2 * a[ i ]; else if( c[ i ] == '/' ) pa[ i ] = pa[ i - 1 ] + 2 * a[ i ] - 1; else pa[ i ] = pa[ i - 1 ] + 2 * a[ i ] + 1; // for( int i = 1 ; i <= n ; i ++ ) // printf( "%lld " , pa[ i ] ); puts( "" ); } int vl[ N ] , no[ N ] , pl , pr; void pop_front(){ pl ++; } void pop_back(){ pr --; } void push( int tno , int tvl ){ while( pl < pr ){ if( tvl < vl[ pr - 1 ] ) pop_back(); else break; } vl[ pr ] = tvl; no[ pr ++ ] = tno; } void solve(){ pl = pr = 0; for( int i = 1 ; i < m ; i ++ ) push( i , b[ i ] ); ll fans = pa[ n ]; for( int i = m ; i <= n ; i ++ ){ while( pl < pr && no[ pl ] <= i - m ) pop_front(); push( i , b[ i ] ); ll ans = pa[ i ] - pa[ i - m ]; ll res = vl[ pl ] * (ll)m * 2; ans -= res; // printf( "%lld %lld\n" , ans , res ); fans = min( fans , ans ); } printf( "Case #%d: %lld.%lld\n" , ++ cs , fans / 2 , ( fans % 2 ) * 5 ); } int main(){ build(); __ = getint(); while( __ -- ){ init(); solve(); } }
[ "c.c.hsu01@gmail.com" ]
c.c.hsu01@gmail.com
69cabe252752a39e693bece42045b6fa19fb4e3f
d5f6888f6d9a4b807384cc79025887f4d1e10e81
/src/midpoint_circle.cc
ece7028fb50f48ad93c9504ce0fcaeee516e18a3
[]
no_license
FudgeRacoon/2D-Graphics-Algorithms
298598fa707b7bd3b88f7678286c91c977749a73
0940bcdfc60bded87ffd3a1b2a883f033e6e4c95
refs/heads/main
2023-03-13T14:03:39.178851
2021-03-07T16:07:47
2021-03-07T16:07:47
344,158,814
0
0
null
null
null
null
UTF-8
C++
false
false
2,994
cc
#include "SDL/SDL.h" #include <iostream> using namespace std; SDL_Surface* pSurface; enum { SCREENWIDTH = 512, SCREENHEIGHT = 384, SCREENBPP = 0, SCREENFLAGS = SDL_ANYFORMAT } ; class Start { public: static void Draw() { int r,xc,yc; printf("Enter the values of xc and yc:\n"); scanf("%d %d",&xc,&yc); printf("Enter the Radius:\n"); scanf("%d", &r); SDL_Color color ; color.r = rand ( ) % 256 ; color.g = rand ( ) % 256 ; color.b = rand ( ) % 256 ; CircleMid(xc,yc,r,color); } static void CirclePlotPoints(int xc, int yc, int x, int y, SDL_Color color) { SetPixel(pSurface, xc+x,yc+y, color); SetPixel(pSurface, xc-x,yc+y, color); SetPixel(pSurface, xc+x,yc-y, color); SetPixel(pSurface, xc-x,yc-y, color); SetPixel(pSurface, xc+y,yc+x, color); SetPixel(pSurface, xc-y,yc+x, color); SetPixel(pSurface, xc+y,yc-x, color); SetPixel(pSurface, xc-y,yc-x, color); } static void CircleMid( int xc, int yc, int r, SDL_Color color) { int x = 0; int y = r; int p = 1 - r; CirclePlotPoints(xc,yc,x,y,color); while(x<y) { x++; if(p<0) p += 2*x + 1; else { y--; p += 2* (x-y) + 1; } CirclePlotPoints(xc,yc,x,y,color); } } static void SetPixel ( SDL_Surface* pSurface , int x , int y , SDL_Color color ) { //convert color Uint32 col = SDL_MapRGB ( pSurface->format , color.r , color.g , color.b ) ; //determine position char* pPosition = ( char* ) pSurface->pixels ; //offset by y pPosition += ( pSurface->pitch * y ) ; //offset by x pPosition += ( pSurface->format->BytesPerPixel * x ) ; //copy pixel data memcpy ( pPosition , &col , pSurface->format->BytesPerPixel ) ; } static SDL_Color GetPixel ( SDL_Surface* pSurface , int x , int y ) { SDL_Color color ; Uint32 col = 0 ; //determine position char* pPosition = ( char* ) pSurface->pixels ; //offset by y pPosition += ( pSurface->pitch * y ) ; //offset by x pPosition += ( pSurface->format->BytesPerPixel * x ) ; //copy pixel data memcpy ( &col , pPosition , pSurface->format->BytesPerPixel ) ; //convert color SDL_GetRGB ( col , pSurface->format , &color.r , &color.g , &color.b ) ; return ( color ) ; } }; class SDLInit { public: static void Init() { //initialize systems SDL_Init ( SDL_INIT_VIDEO ) ; //set our at exit function atexit ( SDL_Quit ) ; //create a window pSurface = SDL_SetVideoMode ( SCREENWIDTH , SCREENHEIGHT , SCREENBPP , SCREENFLAGS ) ; //declare event variable SDL_Event event ; // flag defined to stop looping foo() int flag = 1; //message pump for ( ; ; ) { //look for an event if ( SDL_PollEvent ( &event ) ) { //an event was found if ( event.type == SDL_QUIT ) break ; } if(flag) { Start::Draw(); // My coding! flag = 0; } }//end of message pump //done } };
[ "fudgeracoon@gmail.com" ]
fudgeracoon@gmail.com
97d207888cd38ea614b142a2814b06c9dbbd32ae
f79dec3c4033ca3cbb55d8a51a748cc7b8b6fbab
/audio/akode/patches/patch-aj
1a0fea264fbd525bdc2c3e7589189df7e809c77a
[]
no_license
jsonn/pkgsrc
fb34c4a6a2d350e8e415f3c4955d4989fcd86881
c1514b5f4a3726d90e30aa16b0c209adbc276d17
refs/heads/trunk
2021-01-24T09:10:01.038867
2017-07-07T15:49:43
2017-07-07T15:49:43
2,095,004
106
47
null
2016-09-19T09:26:01
2011-07-23T23:49:04
Makefile
UTF-8
C++
false
false
285
$NetBSD: patch-aj,v 1.1 2011/01/20 11:48:18 markd Exp $ --- akode/lib/auto_sink.cpp.orig 2005-10-26 13:50:29.000000000 +0000 +++ akode/lib/auto_sink.cpp @@ -21,6 +21,7 @@ #include "audioframe.h" #include "auto_sink.h" +#include <cstdlib> #include <iostream> namespace aKode {
[ "markd" ]
markd
d1a4845a06a9f8df43a55ae131dbcf2fcbcd3e1b
e5c6be6014b732eee00cafc7bef231d0b4a9dd1e
/include/m5gpack.hpp
2a54ebe3f9bf084a22153cdf9e35c4ebf97f1ab4
[]
no_license
kuvaldini/m5gpack
a346cd505012d4aced8e8769e86ad8d26aca1e1a
79e8e490f2db28f2a0fe81f82f301206bb07878b
refs/heads/main
2023-03-04T03:22:56.080669
2021-02-12T19:04:24
2021-02-12T19:04:24
324,422,385
0
0
null
null
null
null
UTF-8
C++
false
false
25,687
hpp
#pragma once //todo compare presision for floats/doubles //todo printer densed, printer pretty, printer json //todo // #include <endian> #include <cstdint> #include <optional> #include <variant> #include <vector> #include <string_view> #include <chrono> #include <iostream> #include <iomanip> #include <type_traits> // #include <format> //todo #include "byte_range_hex.hpp" /// helper constant to fail static_assert and report type template<class> inline constexpr bool always_false_v = false; /// From https://en.cppreference.com/w/cpp/utility/variant/visit /// helper type for the visitor #4 template<class... Ts> struct overloaded : Ts... { using Ts::operator()...; }; /// explicit deduction guide (not needed as of C++20) template<class... Ts> overloaded(Ts...) -> overloaded<Ts...>; // template<class T=void> struct m5g_value { using string = std::string; template<class...Ts> using vector = std::vector<Ts...>; template<class...Ts> using variant = std::variant<Ts...>; // template<class...Ts> using stdmap = std::map<Ts...>; using ostream = std::ostream; struct nil_t { constexpr bool operator< (nil_t const&)const{return true;} constexpr bool operator==(nil_t const&)const{return true;} }; static constexpr nil_t nil{}; // using bin_t = byte_vector; struct bin_t : std::vector<uint8_t>{ //declare struct instead of using type directly for better compile-time messages using std::vector<uint8_t>::vector; }; using blob_t = bin_t; struct array_t : std::vector<m5g_value>{ //declare struct instead of using type directly for better compile-time messages using std::vector<m5g_value>::vector; }; using pair_t = std::pair<m5g_value,m5g_value>; struct map_t : std::vector<pair_t>{ //declare struct instead of using type directly for better compile-time messages using std::vector<pair_t>::vector; }; struct ext_t{ uint8_t type; bin_t data; auto operator<=>(const ext_t&) const = default; }; struct time_t { using seconds = std::chrono::seconds; using nanoseconds = std::chrono::nanoseconds; std::chrono::seconds sec{0}; std::chrono::nanoseconds ns{0}; constexpr auto operator<=>(time_t const&)const = default; constexpr time_t() = default; constexpr time_t(time_t const&) = default; constexpr time_t(time_t&&) = default; constexpr time_t& operator=(time_t&&) = default; constexpr time_t& operator=(time_t const&) = default; // constexpr time_t(seconds const& s):sec(s){} constexpr time_t(seconds const& s, nanoseconds ns = nanoseconds{0}):sec(s),ns(ns){} constexpr time_t(nanoseconds ns):ns(ns){} friend auto operator<<(std::ostream&os, time_t const& t)->std::ostream&{ return os << t.sec.count() << "s_" << t.ns.count() << "ns"; } }; // enum kind_t { // nil=0, boolean, sigint, unsint, float32, float64, str, bin, arr, map, ext, time // } kind = nil; using var_t = std::variant<nil_t,bool,int64_t,uint64_t,float,double,string,bin_t,array_t,map_t,ext_t,time_t>; var_t var; // the only variable member template<class...Ts> constexpr m5g_value(Ts&&...vs) : var(std::forward<Ts>(vs)...) {} constexpr m5g_value(unsigned u):var(uint64_t(u)){} // template<class> constexpr m5g_value(m5g_value&&val) : var(std::forward<m5g_value>(val).var) {} constexpr m5g_value(m5g_value&&val) { *this = std::move(val); } constexpr m5g_value(m5g_value &val) { *this = val; } constexpr m5g_value(m5g_value const&val){ *this = val; } /* constexpr */ m5g_value& operator=(m5g_value&&val) { this->var=std::move(val.var); val.var={}; return *this; } /* constexpr */ m5g_value& operator=(m5g_value const&val) { this->var=val.var; return *this; } auto get_as_optional_long_double()const{ return std::visit( [](auto const& arg)->std::optional<long double>{ using T = std::decay_t<decltype(arg)>; if constexpr (std::is_arithmetic_v<T> and not std::is_same_v<T,bool>){ return arg; }else{ return {}; } }, this->var); }; constexpr bool is_number()const{ return std::visit([]<typename T>(T&&){ // using T = std::decay_t<decltype(arg)>; return std::is_arithmetic_v<T> and not std::is_same_v<T,bool>; },var); } /// Compare for sorting in map /// bin_t,array_t,map_t,ext_t should never be a key in map bool operator<(m5g_value const& other) const{ // if(this->var.index() == other.var.index()){ // return std::visit( // [&](auto const& arg)->bool{ // using T = std::decay_t<decltype(arg)>; // return arg < std::get<T>(other.var); // }, this->var); // }else{ // auto this_opt_ld = this->get_as_optional_long_double(); // auto other_opt_ld = other.get_as_optional_long_double(); // if(this_opt_ld and other_opt_ld){ // return *this_opt_ld < *other_opt_ld; // } // return this->var.index() < other.var.index(); // } auto this_opt_ld = this->get_as_optional_long_double(); auto other_opt_ld = other.get_as_optional_long_double(); if(this_opt_ld and other_opt_ld){ return *this_opt_ld < *other_opt_ld; } return this->var < other.var; } bool operator==(m5g_value const& other) const{ auto this_opt_ld = this->get_as_optional_long_double(); auto other_opt_ld = other.get_as_optional_long_double(); if(this_opt_ld and other_opt_ld){ return *this_opt_ld == *other_opt_ld; } return this->var == other.var; } // stringify to std::ostream like cerr or cout friend auto operator<<(ostream&os, m5g_value const& val) ->ostream& { std::visit([&](auto&& arg) { using T = std::decay_t<decltype(arg)>; using std::is_same_v; if constexpr (is_same_v<T, nil_t>) os << "nil"; else if constexpr (is_same_v<T, bool>) os << std::boolalpha << arg; else if constexpr (is_same_v<T, bin_t>) os << byte_range_hex(arg); else if constexpr (is_same_v<T, array_t>){ os << "["; auto comma = ""; for(auto&x:arg) os << comma << x, comma = ", "; os << "]"; }else if constexpr (is_same_v<T, map_t>){ os << "{"; auto comma = ""; for(auto&[k,w]:arg) os << comma << k << ": " << w, comma = ", "; os << "}"; }else if constexpr (is_same_v<T, time_t>){ os << arg.sec.count() << "s_" << arg.ns.count() << "ns"; }else if constexpr (is_same_v<T, string>){ os << std::quoted(arg); }else os << arg; //static_assert(always_false_v<T>, "non-exhaustive visitor!"); }, val.var); return os; } }; //m5g_value /* Formats Overview format name first byte (in binary) first byte (in hex) positive fixint 0xxxxxxx 0x00 - 0x7f fixmap 1000xxxx 0x80 - 0x8f fixarray 1001xxxx 0x90 - 0x9f fixstr 101xxxxx 0xa0 - 0xbf nil 11000000 0xc0 (never used) 11000001 0xc1 false 11000010 0xc2 true 11000011 0xc3 bin 8 11000100 0xc4 bin 16 11000101 0xc5 bin 32 11000110 0xc6 ext 8 11000111 0xc7 ext 16 11001000 0xc8 ext 32 11001001 0xc9 float 32 11001010 0xca float 64 11001011 0xcb uint 8 11001100 0xcc uint 16 11001101 0xcd uint 32 11001110 0xce uint 64 11001111 0xcf int 8 11010000 0xd0 int 16 11010001 0xd1 int 32 11010010 0xd2 int 64 11010011 0xd3 fixext 1 11010100 0xd4 fixext 2 11010101 0xd5 fixext 4 11010110 0xd6 fixext 8 11010111 0xd7 fixext 16 11011000 0xd8 str 8 11011001 0xd9 str 16 11011010 0xda str 32 11011011 0xdb array 16 11011100 0xdc array 32 11011101 0xdd map 16 11011110 0xde map 32 11011111 0xdf negative fixint 111xxxxx 0xe0 - 0xff */ struct m5g_byte_stream : std::vector<uint8_t> { using std::vector<uint8_t>::vector; enum format : uint8_t { /// Nil format stores nil in 1 byte. nil = 0xc0, falso = 0xc2, truo = 0xc3, /// positive fixnum stores 7-bit positive integer 0XXXXXXX pos_fixnum_id = 0b00000000, pos_fixnum_id_mask = 0b10000000, pos_fixnum_max = 127, pos_fixnum_data_mask = (uint8_t)~pos_fixnum_id_mask, //0b01111111, /// negative fixnum stores 5-bit negative integer 111YYYYY neg_fixnum_id = (uint8_t)0b11100000, neg_fixnum_id_mask = (uint8_t)0b11100000, // neg_fixnum_min = (uint8_t)~neg_fixnum_id_mask, // neg_fixnum_data_mask = (uint8_t)0b00011111, neg_fixnum_data_mask = (uint8_t)~neg_fixnum_id_mask, /// uint 8 stores a 8-bit unsigned integer uint8 = 0xcc, uint16 = 0xcd, uint32 = 0xce, uint64 = 0xcf, /// int 8 stores a 8-bit signed integer int8 = 0xd0, int16 = 0xd1, int32 = 0xd2, int64 = 0xd3, /// float 32 stores a floating point number in IEEE 754 single precision floating point number format: float32 = 0xca, float64 = 0xcb, /// fixstr stores a byte array whose length is upto 31 bytes: fixstr_id = 0b10100000, ///101XXXXX fixstr_id_mask = 0b11100000, fixstr_len_mask = (uint8_t)~fixstr_id_mask, fixstr_len_max = fixstr_len_mask, // fixstr_id_mask = (uint8_t)~fixstr_len_mask, /// str 8 stores a byte array whose length is upto (2^8)-1 bytes: str8 = 0xd9, /// str 16 stores a byte array whose length is upto (2^16)-1 bytes: str16 = 0xda, /// str 32 stores a byte array whose length is upto (2^32)-1 bytes: str32 = 0xdb, /// bin 8 stores a byte array whose length is upto (2^8)-1 bytes: bin8 = 0xc4, /// bin 16 stores a byte array whose length is upto (2^16)-1 bytes: bin16 = 0xc5, /// bin 32 stores a byte array whose length is upto (2^32)-1 bytes: bin32 = 0xc6, /// fixarray stores an array whose length is upto 15 elements: fixarr_id = 0b10010000, ///1001XXXX fixarr_id_mask = 0b11110000, //(uint8_t)~fixarr_len_mask, fixarr_len_mask = (uint8_t)~fixarr_id_mask, //0b00001111, fixarr_len_max = 0b00001111, /// array 16 stores an array whose length is upto (2^16)-1 elements: arr16 = 0xdc, /// array 32 stores an array whose length is upto (2^32)-1 elements: arr32 = 0xdd, /// fixmap stores a map whose length is upto 15 elements fixmap_id = 0b10000000, ///1001XXXX fixmap_id_mask = 0b11110000, fixmap_len_mask = (uint8_t)~fixmap_id_mask, fixmap_len_max = fixmap_len_mask, //0b00001111, /// map 16 stores a map whose length is upto (2^16)-1 elements map16 = 0xde, map32 = 0xdf, /// fixext 1 stores an integer and a byte array whose length is 1 byte fixext1 = 0xd4, fixext2 = 0xd5, fixext4 = 0xd6, fixext8 = 0xd7, fixext16 = 0xd8, /// ext 8 stores an integer and a byte array whose length is upto (2^8)-1 bytes: ext8 = 0xc7, ext16 = 0xc8, ext32 = 0xc9, /// timestamp 32 stores the number of seconds that have elapsed since 1970-01-01 00:00:00 UTC /// in an 32-bit unsigned integer: timestamp32 = 0xd6, /// timestamp 64 stores the number of seconds and nanoseconds that have elapsed since 1970-01-01 00:00:00 UTC /// in 32-bit unsigned integers: timestamp64 = 0xd7, /// timestamp 96 stores the number of seconds and nanoseconds that have elapsed since 1970-01-01 00:00:00 UTC /// in 64-bit signed integer and 32-bit unsigned integer: timestamp96 = 0xc7, }; m5g_byte_stream& operator<<(m5g_value const& val){ std::visit(overloaded{ [](auto&&a){ static_assert(always_false_v<decltype(a)>,"expected overload for type"); }, [&](m5g_value::nil_t){ detail() << nil; }, [&](bool b){ detail() << (b ? truo : falso); }, [&](int64_t const& i){ if(i < 0 and i >= -32){ // 5 bit allowed detail() << int8_t(i); }else if(int8_t(i) == i){ detail() << int8 << int8_t(i); }else if(int16_t(i) == i){ detail() << int16 << int16_t(i); }else if(int32_t(i) == i){ detail() << int32 << int32_t(i); }else{ detail() << int64 << i; } }, [&](uint64_t const& u){ if(u <= 127){ // 7 bit allowed detail() << uint8_t(u); }else if(uint8_t(u) == u){ detail() << uint8 << uint8_t(u); }else if(uint16_t(u) == u){ detail() << uint16 << uint16_t(u); }else if(uint32_t(u) == u){ detail() << uint32 << uint32_t(u); }else{ detail() << uint64 << u; } }, [&](float const& f){ detail()<< float32 << f; }, [&](double const& f){ detail() << float64 << f; }, [&](std::string const& str){ auto size = str.size(); if(size == (size & fixstr_len_mask)){ detail() << uint8_t(size | fixstr_id) << str; }else if(uint8_t(size) == size){ detail() << str8 << uint8_t(size) << str; }else if(uint16_t(size) == size){ detail() << str16 << uint16_t(size) << str; }else if(uint32_t(size) == size){ detail() << str32 << uint32_t(size) << str; }else std::terminate(); //throw m5g_exception("wrong size is more than uint32_t"); }, [&](m5g_value::bin_t const& bytes){ auto size = bytes.size(); if(uint8_t(size) == size){ detail() << bin8 << uint8_t(size); }else if(uint16_t(size) == size){ detail() << bin16 << uint16_t(size); }else if(uint32_t(size) == size){ detail() << bin32 << uint32_t(size); }else std::terminate(); //throw m5g_exception("wrong size is more than uint32_t"); detail() << bytes; }, [&](m5g_value::array_t const& arr){ auto size = arr.size(); if(size <= fixarr_len_max) detail() << uint8_t(size | fixarr_id); else if(uint16_t(size) == size) detail() << arr16 << uint16_t(size); else if(uint32_t(size) == size) detail() << arr32 << uint32_t(size); else std::terminate(); //throw m5g_exception("wrong size is more than uint32_t"); for(auto&each:arr) *this << each; }, [&](m5g_value::map_t const& m){ auto size = m.size(); if(size <= fixmap_len_max) detail() << uint8_t(size | fixmap_id); else if(uint16_t(size) == size) detail() << map16 << uint16_t(size); else if(uint32_t(size) == size) detail() << map32 << uint32_t(size); else std::terminate(); //throw m5g_exception("wrong size is more than uint32_t"); for(auto&[k,v]:m) *this << k << v; }, [&](m5g_value::ext_t const& e){ auto size = e.data.size(); if(size == 1) detail() << fixext1; else if(size == 2) detail() << fixext2; else if(size == 4) detail() << fixext4; else if(size == 8) detail() << fixext8; else if(size == 16) detail() << fixext16; else if(uint8_t(size) == size) detail() << ext8 << uint8_t(size); else if(uint16_t(size) == size) detail() << ext16 << uint16_t(size); else if(uint32_t(size) == size) detail() << ext32 << uint32_t(size); else std::terminate();//throw detail() << e.type << e.data; }, [&](m5g_value::time_t const& t){ using namespace std::chrono; int64_t sec = t.sec.count(); uint32_t nsec = t.ns.count(); if (sec <= UINT32_MAX and sec >= 0 and nsec == 0){ detail() << timestamp32 << char(-1) << uint32_t(sec); }else if (sec == (sec & 0x3'FFFF'FFFF)){ detail() << timestamp64 << char(-1) << ((uint64_t(nsec) << 34)|sec); }else{ detail() << timestamp96 << uint8_t(12) << char(-1) << uint32_t(nsec) << sec; } } },val.var); return *this; } auto operator<<(m5g_byte_stream const& bs) ->m5g_byte_stream& { insert(end(), bs.begin(), bs.end()); return *this; } m5g_byte_stream& operator>>(m5g_value&val){ auto&var=val.var; auto set_array = [&](size_t len){ var = m5g_value::array_t(len); for(auto&v:get<m5g_value::array_t>(var)) *this >> v; }; auto set_map = [&](size_t len){ var = m5g_value::map_t(len); for(auto&[k,v]:get<m5g_value::map_t>(var)) *this >> k >> v; }; auto set_str = [&](size_t len){ var = std::string(begin(),begin()+len); erase(begin(),begin()+len); }; auto set_bin = [&](size_t len){ var = m5g_value::bin_t(begin(),begin()+len); erase(begin(),begin()+len); }; auto set_ext = [&](size_t len){ uint8_t type; detail() >> type; if(type == (uint8_t)-1){ //time switch(len){ using namespace std::chrono; case 4:{ uint32_t sec; detail() >> sec; var = m5g_value::time_t(seconds(sec),nanoseconds(0)); }break; case 8:{ uint64_t data; detail()>>data; var = m5g_value::time_t{ .sec = seconds{data&((1ull<<34)-1)}, .ns = nanoseconds{data>>34}, }; }break; case 12:{ int64_t sec; uint32_t nsec; detail()>>nsec>>sec; var = m5g_value::time_t{seconds(sec),nanoseconds(nsec)}; }break; default: throw std::logic_error("wrong len {} for ext type -1 time"); } }else{ var = m5g_value::ext_t{ .type=type, .data= m5g_value::bin_t(begin(),begin()+len) }; erase(begin(),begin()+len); } }; enum format f{};// = front(); detail() >> f; switch(f){ case nil : var = m5g_value::nil; break; case falso: var = false; break; case truo : var = true; break; case uint8 :{ uint8_t v; detail() >> v; var = uint64_t(v);} break; case uint16:{ uint16_t v; detail() >> v; var = uint64_t(v);} break; case uint32:{ uint32_t v; detail() >> v; var = uint64_t(v);} break; case uint64:{ uint64_t v; detail() >> v; var = v; } break; case int8 :{ int8_t v; detail() >> v; var = int64_t(v);} break; case int16:{ int16_t v; detail() >> v; var = int64_t(v);} break; case int32:{ int32_t v; detail() >> v; var = int64_t(v);} break; case int64:{ int64_t v; detail() >> v; var = v; } break; // case str8 :{ uint8_t len; detail()>>len; set_str(len); } break; case str16:{ uint16_t len; detail()>>len; set_str(len); } break; case str32:{ uint32_t len; detail()>>len; set_str(len); } break; case bin8 :{ uint8_t len; detail()>>len; set_bin(len); } break; case bin16:{ uint16_t len; detail()>>len; set_bin(len); } break; case bin32:{ uint32_t len; detail()>>len; set_bin(len); } break; case arr16:{ uint16_t len; detail()>>len; set_array(len); } break; case arr32:{ uint32_t len; detail()>>len; set_array(len); } break; case map16:{ uint16_t len; detail()>>len; set_map(len); } break; case map32:{ uint32_t len; detail()>>len; set_map(len); } break; // case fixext1 : set_ext(1); break; case fixext2 : set_ext(2); break; case fixext4 : set_ext(4); break; case fixext8 : set_ext(8); break; case fixext16: set_ext(16); break; case ext8 : { uint8_t len; detail()>>len; set_ext(len); } break; case ext16: { uint16_t len; detail()>>len; set_ext(len); } break; case ext32: { uint32_t len; detail()>>len; set_ext(len); } break; default: // The longest masks go first if((f&fixmap_id_mask)==fixmap_id){ uint8_t len = f & fixmap_len_mask; set_map(len); }else if((f&fixarr_id_mask)==fixarr_id){ uint8_t len = f & fixarr_len_mask; set_array(len); }else if((f&fixstr_id_mask)==fixstr_id){ //is_fixstr(f) size_t len = f & fixstr_len_mask; var = std::string(begin(),begin()+len); }else if((f&neg_fixnum_id_mask)==neg_fixnum_id){ //is_neg_fixnum(f)){ var = int64_t(f&neg_fixnum_data_mask); }else if((f&pos_fixnum_id_mask)==pos_fixnum_id){ //is_pos_fixnum(f)){ var = uint64_t(f&pos_fixnum_data_mask); }else{ // ToDo use std::format but g++10 on Mac has no header <format> // throw std::logic_error(std::format("Unexpencted format {}.", f)); throw std::logic_error("Unexpencted msgpack format byte {}"); } }//switch return *this; } private: struct detail_ { m5g_byte_stream& mbs; template<typename T> auto operator<<(T const& v) noexcept ->std::enable_if_t<std::is_arithmetic_v<T> and not std::is_same_v<T,bool>, detail_& > { #if (BYTE_ORDER == LITTLE_ENDIAN) //C++20 if constexpr (std::endian::native == std::endian::little) std::reverse_iterator<uint8_t*> first{(uint8_t *) (&v + 1)}, last{(uint8_t *) (&v)}; #else uint8_t *first=(uint8_t*)&v, *last=(uint8_t*)(&v+1); #endif mbs.insert(mbs.end(), first, last); return *this; } template<typename T> auto operator>>(T const& val) ->std::enable_if_t<std::is_arithmetic_v<T> and not std::is_same_v<T,bool>, detail_& > { using namespace std; if(mbs.size() < sizeof(T)){ cerr<<"err in "<<__func__<<"(): input stream is too short (size:"<<mbs.size() <<", requested:"<< sizeof(T)<<")"<<endl; std::stringstream ss; ss<<"input stream is too short (size:"<<mbs.size()<<", requested:"<< sizeof(T)<<")"<<endl; throw std::logic_error(ss.str()); //mbs.error_flag() = true; return *this; } #if BYTE_ORDER == LITTLE_ENDIAN std::reverse_iterator<uint8_t*> out_it{(uint8_t*)(&val+1)}, out_end{(uint8_t*)(&val)}; #else uint8_t* out_it{(uint8_t*)(&val)}, *out_end{(uint8_t*)(&val+1)}; #endif auto iter = mbs.begin(); while (out_it != out_end && iter != mbs.end()) { *out_it++ = *iter++; } mbs.erase(mbs.begin(),iter); ///FIXME OPTIMIZE as stream circular buffer return *this; } detail_& operator<<(enum format ef){ return *this << (uint8_t)ef; } detail_& operator>>(enum format &ef){ return *this >> (uint8_t&)ef; } detail_& operator<<(std::string const& s) { mbs.insert(mbs.end(), s.begin(), s.end()); // Alternative way: vec.reserve(vec.size()+sv.size()); for(auto&c:sv) vec<<c; return *this; } detail_& operator<<(m5g_value::bin_t const& b) { mbs.insert(mbs.end(), b.begin(), b.end()); // Alternative way: vec.reserve(vec.size()+sv.size()); for(auto&c:sv) vec<<c; return *this; } }; detail_ detail() { return {*this}; } }; //struct m5g_byte_stream namespace m5g { using value = m5g_value; using nil_t = m5g_value::nil_t; constexpr auto nil = m5g_value::nil; using bin = m5g_value::bin_t; // using blob = m5g_value::blob_t; using array = m5g_value::array_t; using arr = m5g_value::array_t; using map = m5g_value::map_t; using ext = m5g_value::ext_t; using timestamp = m5g_value::time_t; //using map = m5g_map; //using string = m5g_string; using stream = m5g_byte_stream; using byte_stream = m5g_byte_stream; // constexpr m5g::value nilval{}, valnil{}; } namespace m5gpack { using m5gval = m5g::value; using m5gnil_t = m5g::nil_t; constexpr auto m5gnil = m5g::nil; // using m5gstr = m5g::string; using m5gbin = m5g::bin; // using m5gblob = m5g::blob; using m5garr = m5g::array; using m5gmap = m5g::map; }
[ "i.kyb@ya.ru" ]
i.kyb@ya.ru
be25d908a6d455b2b3e2e842c7a68adcdf78391d
f7a3844b5d8800c56e4a9cf93cea55c75124af8a
/NMEExtensions/sources/iphone/ActivityIndicator.h
b98b1bd174fd7a6e0f171fa6fad99a05aa035df8
[ "MIT" ]
permissive
cristibaluta/sdk.ralcr
4b88b1b8e1d5d4c84196acba407b16cce1071454
7248ae917fc2fd7f0a5f162fec33e2df8d4b2203
refs/heads/master
2021-05-28T20:58:35.154651
2013-07-02T15:58:18
2013-07-02T15:58:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
187
h
#ifndef ActivityIndicator #define ActivityIndicator namespace ralcr { void new_activity_indicator (int x, int y, bool white, bool large); void destroy_activity_indicator(); } #endif
[ "cristi.baluta@gmail.com" ]
cristi.baluta@gmail.com
a5fcd7c531557a7971d2160dca52c56fba4bdbe5
13170cde328d6ce63fc10bfd726eecd4fefff3e7
/vst/JuceLibraryCode/modules/juce_audio_basics/sources/juce_MixerAudioSource.cpp
b5b211bd329443fe7f06bc06f66e820879e90480
[]
no_license
owenvallis/KeyValueVST
32b7e69c8d56c54e96eda3a9b214de5425d686e8
faaccb8be35bbfa78aa9acb6001c61dc9307dd3c
refs/heads/master
2016-08-06T20:54:32.577745
2012-03-21T05:59:41
2012-03-21T05:59:41
3,444,001
2
0
null
null
null
null
UTF-8
C++
false
false
4,691
cpp
/* ============================================================================== This file is part of the JUCE library - "Jules' Utility Class Extensions" Copyright 2004-11 by Raw Material Software Ltd. ------------------------------------------------------------------------------ JUCE can be redistributed and/or modified under the terms of the GNU General Public License (Version 2), as published by the Free Software Foundation. A copy of the license is included in the JUCE distribution, or can be found online at www.gnu.org/licenses. JUCE 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. ------------------------------------------------------------------------------ To release a closed-source product which uses JUCE, commercial licenses are available: visit www.rawmaterialsoftware.com/juce for more information. ============================================================================== */ MixerAudioSource::MixerAudioSource() : tempBuffer (2, 0), currentSampleRate (0.0), bufferSizeExpected (0) { } MixerAudioSource::~MixerAudioSource() { removeAllInputs(); } //============================================================================== void MixerAudioSource::addInputSource (AudioSource* input, const bool deleteWhenRemoved) { if (input != nullptr && ! inputs.contains (input)) { double localRate; int localBufferSize; { const ScopedLock sl (lock); localRate = currentSampleRate; localBufferSize = bufferSizeExpected; } if (localRate > 0.0) input->prepareToPlay (localBufferSize, localRate); const ScopedLock sl (lock); inputsToDelete.setBit (inputs.size(), deleteWhenRemoved); inputs.add (input); } } void MixerAudioSource::removeInputSource (AudioSource* const input) { if (input != nullptr) { ScopedPointer<AudioSource> toDelete; { const ScopedLock sl (lock); const int index = inputs.indexOf (input); if (index < 0) return; if (inputsToDelete [index]) toDelete = input; inputsToDelete.shiftBits (index, 1); inputs.remove (index); } input->releaseResources(); } } void MixerAudioSource::removeAllInputs() { OwnedArray<AudioSource> toDelete; { const ScopedLock sl (lock); for (int i = inputs.size(); --i >= 0;) if (inputsToDelete[i]) toDelete.add (inputs.getUnchecked(i)); inputs.clear(); } for (int i = toDelete.size(); --i >= 0;) toDelete.getUnchecked(i)->releaseResources(); } void MixerAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate) { tempBuffer.setSize (2, samplesPerBlockExpected); const ScopedLock sl (lock); currentSampleRate = sampleRate; bufferSizeExpected = samplesPerBlockExpected; for (int i = inputs.size(); --i >= 0;) inputs.getUnchecked(i)->prepareToPlay (samplesPerBlockExpected, sampleRate); } void MixerAudioSource::releaseResources() { const ScopedLock sl (lock); for (int i = inputs.size(); --i >= 0;) inputs.getUnchecked(i)->releaseResources(); tempBuffer.setSize (2, 0); currentSampleRate = 0; bufferSizeExpected = 0; } void MixerAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info) { const ScopedLock sl (lock); if (inputs.size() > 0) { inputs.getUnchecked(0)->getNextAudioBlock (info); if (inputs.size() > 1) { tempBuffer.setSize (jmax (1, info.buffer->getNumChannels()), info.buffer->getNumSamples()); AudioSourceChannelInfo info2; info2.buffer = &tempBuffer; info2.numSamples = info.numSamples; info2.startSample = 0; for (int i = 1; i < inputs.size(); ++i) { inputs.getUnchecked(i)->getNextAudioBlock (info2); for (int chan = 0; chan < info.buffer->getNumChannels(); ++chan) info.buffer->addFrom (chan, info.startSample, tempBuffer, chan, 0, info.numSamples); } } } else { info.clearActiveBufferRegion(); } }
[ "ow3nskip" ]
ow3nskip
f588866f132160c77b68e3acf5b0c866d32a9cca
8992d58c52017d7c2060de0a9e01e78b9a729549
/src/masternode.cpp
1899b2339704876a18c42ff4048160feaf45824f
[ "MIT" ]
permissive
AnabolicRampage/Linda-1
f744efccfc93818fec1cd2fa0878a558b8fb01bd
612a80960d0661bd8c72f3885a723b7e1674fc48
refs/heads/master
2020-04-16T13:13:10.911616
2019-01-13T13:29:01
2019-01-13T13:29:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
30,284
cpp
#include "masternode.h" #include "activemasternode.h" #include "darksend.h" //#include "primitives/transaction.h" #include "main.h" #include "util.h" #include "addrman.h" #include <boost/lexical_cast.hpp> int CMasterNode::minProtoVersion = MIN_MN_PROTO_VERSION; /** The list of active masternodes */ std::vector<CMasterNode> vecMasternodes; /** Object for who's going to get paid on which blocks */ CMasternodePayments masternodePayments; // keep track of masternode votes I've seen map<uint256, CMasternodePaymentWinner> mapSeenMasternodeVotes; // keep track of the scanning errors I've seen map<uint256, int> mapSeenMasternodeScanningErrors; // who's asked for the masternode list and the last time std::map<CNetAddr, int64_t> askedForMasternodeList; // which masternodes we've asked for std::map<COutPoint, int64_t> askedForMasternodeListEntry; // cache block hashes as we calculate them std::map<int64_t, uint256> mapCacheBlockHashes; // manage the masternode connections void ProcessMasternodeConnections(){ LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) { //if it's our masternode, let it be if(darkSendPool.submittedToMasternode == pnode->addr) continue; if(pnode->fDarkSendMaster){ LogPrintf("Closing masternode connection %s \n", pnode->addr.ToString().c_str()); pnode->CloseSocketDisconnect(); } } } void ProcessMessageMasternode(CNode* pfrom, std::string& strCommand, CDataStream& vRecv) { if (strCommand == "dsee") { //DarkSend Election Entry if(fLiteMode) return; //disable all darksend/masternode related functionality bool fIsInitialDownload = IsInitialBlockDownload(); if(fIsInitialDownload) return; CTxIn vin; CService addr; CPubKey pubkey; CPubKey pubkey2; vector<unsigned char> vchSig; int64_t sigTime; int count; int current; int64_t lastUpdated; int protocolVersion; std::string strMessage; // 70047 and greater vRecv >> vin >> addr >> vchSig >> sigTime >> pubkey >> pubkey2 >> count >> current >> lastUpdated >> protocolVersion; // make sure signature isn't in the future (past is OK) if (sigTime > GetAdjustedTime() + 60 * 60) { LogPrintf("dsee - Signature rejected, too far into the future %s\n", vin.ToString().c_str()); return; } bool isLocal = addr.IsRFC1918() || addr.IsLocal(); //if(Params().MineBlocksOnDemand()) isLocal = false; std::string vchPubKey(pubkey.begin(), pubkey.end()); std::string vchPubKey2(pubkey2.begin(), pubkey2.end()); strMessage = addr.ToString() + boost::lexical_cast<std::string>(sigTime) + vchPubKey + vchPubKey2 + boost::lexical_cast<std::string>(protocolVersion); if(protocolVersion < MIN_MN_PROTO_VERSION) { LogPrintf("dsee - ignoring outdated masternode %s protocol version %d\n", vin.ToString().c_str(), protocolVersion); return; } CScript pubkeyScript; pubkeyScript =GetScriptForDestination(pubkey.GetID()); if(pubkeyScript.size() != 25) { LogPrintf("dsee - pubkey the wrong size\n"); Misbehaving(pfrom->GetId(), 100); return; } CScript pubkeyScript2; pubkeyScript2 =GetScriptForDestination(pubkey2.GetID()); if(pubkeyScript2.size() != 25) { LogPrintf("dsee - pubkey2 the wrong size\n"); Misbehaving(pfrom->GetId(), 100); return; } std::string errorMessage = ""; if(!darkSendSigner.VerifyMessage(pubkey, vchSig, strMessage, errorMessage)){ LogPrintf("dsee - Got bad masternode address signature\n"); Misbehaving(pfrom->GetId(), 100); return; } //search existing masternode list, this is where we update existing masternodes with new dsee broadcasts BOOST_FOREACH(CMasterNode& mn, vecMasternodes) { if(mn.vin.prevout == vin.prevout) { // count == -1 when it's a new entry // e.g. We don't want the entry relayed/time updated when we're syncing the list // mn.pubkey = pubkey, IsVinAssociatedWithPubkey is validated once below, // after that they just need to match if(count == -1 && mn.pubkey == pubkey && !mn.UpdatedWithin(MASTERNODE_MIN_DSEE_SECONDS)){ mn.UpdateLastSeen(); if(mn.now < sigTime){ //take the newest entry LogPrintf("dsee - Got updated entry for %s\n", addr.ToString().c_str()); mn.pubkey2 = pubkey2; mn.now = sigTime; mn.sig = vchSig; mn.protocolVersion = protocolVersion; mn.addr = addr; RelayDarkSendElectionEntry(vin, addr, vchSig, sigTime, pubkey, pubkey2, count, current, lastUpdated, protocolVersion); } } return; } else if ((CNetAddr)mn.addr == (CNetAddr)addr) { // don't add masternodes with the same service address as they // are attempting to earn payments without contributing // we won't mark the sending node as misbehaving unless // they are the culprit LogPrintf("dsee - Already have mn with same service address:%s\n", addr.ToString()); if ((CNetAddr)pfrom->addr == (CNetAddr)addr) Misbehaving(pfrom->GetId(), 20); return; } } // make sure the vout that was signed is related to the transaction that spawned the masternode // - this is expensive, so it's only done once per masternode if(!darkSendSigner.IsVinAssociatedWithPubkey(vin, pubkey)) { LogPrintf("dsee - Got mismatched pubkey and vin\n"); Misbehaving(pfrom->GetId(), 100); return; } if(fDebug) LogPrintf("dsee - Got NEW masternode entry %s\n", addr.ToString().c_str()); // make sure it's still unspent // - this is checked later by .check() in many places and by ThreadCheckDarkSendPool() CValidationState state; CTransaction tx = CTransaction(); int64_t nTempTxOut = (MASTERNODE_COLLATERAL / COIN) - 1; CTxOut vout = CTxOut(nTempTxOut*COIN, darkSendPool.collateralPubKey); tx.vin.push_back(vin); tx.vout.push_back(vout); bool pfMissingInputs = false; if(AcceptableInputs(mempool, state, tx, false, &pfMissingInputs)){ if(fDebug) LogPrintf("dsee - Accepted masternode entry %i %i\n", count, current); if(GetInputAge(vin) < MASTERNODE_MIN_CONFIRMATIONS){ LogPrintf("dsee - Input must have least %d confirmations\n", MASTERNODE_MIN_CONFIRMATIONS); Misbehaving(pfrom->GetId(), 20); return; } // use this as a peer addrman.Add(CAddress(addr), pfrom->addr, 2*60*60); // add our masternode CMasterNode mn(addr, vin, pubkey, vchSig, sigTime, pubkey2, protocolVersion); mn.UpdateLastSeen(lastUpdated); vecMasternodes.push_back(mn); // if it matches our masternodeprivkey, then we've been remotely activated if(pubkey2 == activeMasternode.pubKeyMasternode && protocolVersion == PROTOCOL_VERSION){ activeMasternode.EnableHotColdMasterNode(vin, addr); } if(count == -1 && !isLocal) RelayDarkSendElectionEntry(vin, addr, vchSig, sigTime, pubkey, pubkey2, count, current, lastUpdated, protocolVersion); } else { LogPrintf("dsee - Rejected masternode entry %s\n", addr.ToString().c_str()); int nDoS = 0; if (state.IsInvalid(nDoS)) { LogPrintf("dsee - %s from %s %s was not accepted into the memory pool\n", tx.GetHash().ToString().c_str(), pfrom->addr.ToString().c_str(), pfrom->cleanSubVer.c_str()); if (nDoS > 0) Misbehaving(pfrom->GetId(), nDoS); } } } else if (strCommand == "dseep") { //DarkSend Election Entry Ping if(fLiteMode) return; //disable all darksend/masternode related functionality bool fIsInitialDownload = IsInitialBlockDownload(); if(fIsInitialDownload) return; CTxIn vin; vector<unsigned char> vchSig; int64_t sigTime; bool stop; vRecv >> vin >> vchSig >> sigTime >> stop; if(fDebug) LogPrintf("dseep - Received: vin: %s sigTime: %lld stop: %s\n", vin.ToString().c_str(), sigTime, stop ? "true" : "false"); if (sigTime > GetAdjustedTime() + 60 * 60) { LogPrintf("dseep - Signature rejected, too far into the future %s\n", vin.ToString().c_str()); return; } if (sigTime <= GetAdjustedTime() - 60 * 60) { LogPrintf("dseep - Signature rejected, too far into the past %s - %d %d \n", vin.ToString().c_str(), sigTime, GetAdjustedTime()); return; } // see if we have this masternode BOOST_FOREACH(CMasterNode& mn, vecMasternodes) { if(mn.vin.prevout == vin.prevout) { if(fDebug) LogPrintf("dseep - Found corresponding mn for vin: %s\n", vin.ToString().c_str()); // take this only if it's newer if(mn.lastDseep < sigTime){ std::string strMessage = mn.addr.ToString() + boost::lexical_cast<std::string>(sigTime) + boost::lexical_cast<std::string>(stop); std::string errorMessage = ""; if(!darkSendSigner.VerifyMessage(mn.pubkey2, vchSig, strMessage, errorMessage)){ LogPrintf("dseep - Got bad masternode address signature %s \n", vin.ToString().c_str()); return; } mn.lastDseep = sigTime; if(!mn.UpdatedWithin(MASTERNODE_MIN_DSEEP_SECONDS)){ mn.UpdateLastSeen(); if(stop) { mn.Disable(); mn.Check(); } RelayDarkSendElectionEntryPing(vin, vchSig, sigTime, stop); } } return; } } if(fDebug) LogPrintf("dseep - Couldn't find masternode entry %s\n", vin.ToString().c_str()); std::map<COutPoint, int64_t>::iterator i = askedForMasternodeListEntry.find(vin.prevout); if (i != askedForMasternodeListEntry.end()){ int64_t t = (*i).second; if (GetTime() < t) { // we've asked recently return; } } // ask for the dsee info once from the node that sent dseep LogPrintf("dseep - Asking source node for missing entry %s\n", vin.ToString().c_str()); pfrom->PushMessage("dseg", vin); int64_t askAgain = GetTime() + MASTERNODE_MIN_DSEEP_SECONDS; askedForMasternodeListEntry[vin.prevout] = askAgain; } else if (strCommand == "dseg") { //Get masternode list or specific entry if(fLiteMode) return; //disable all darksend/masternode related functionality CTxIn vin; vRecv >> vin; if(vin == CTxIn()) { //only should ask for this once //local network //Note tor peers show up as local proxied addrs //if(!pfrom->addr.IsRFC1918())//&& !Params().MineBlocksOnDemand()) //{ std::map<CNetAddr, int64_t>::iterator i = askedForMasternodeList.find(pfrom->addr); if (i != askedForMasternodeList.end()) { int64_t t = (*i).second; if (GetTime() < t) { //Misbehaving(pfrom->GetId(), 34); //LogPrintf("dseg - peer already asked me for the list\n"); //return; } } int64_t askAgain = GetTime()+(60*60*3); askedForMasternodeList[pfrom->addr] = askAgain; //} } //else, asking for a specific node which is ok int count = vecMasternodes.size(); int i = 0; BOOST_FOREACH(CMasterNode mn, vecMasternodes) { if(mn.addr.IsRFC1918()) continue; //local network if(vin == CTxIn()){ mn.Check(); if(mn.IsEnabled()) { if(fDebug) LogPrintf("dseg - Sending masternode entry - %s \n", mn.addr.ToString().c_str()); pfrom->PushMessage("dsee", mn.vin, mn.addr, mn.sig, mn.now, mn.pubkey, mn.pubkey2, count, i, mn.lastTimeSeen, mn.protocolVersion); } } else if (vin == mn.vin) { if(fDebug) LogPrintf("dseg - Sending masternode entry - %s \n", mn.addr.ToString().c_str()); pfrom->PushMessage("dsee", mn.vin, mn.addr, mn.sig, mn.now, mn.pubkey, mn.pubkey2, count, i, mn.lastTimeSeen, mn.protocolVersion); LogPrintf("dseg - Sent 1 masternode entries to %s\n", pfrom->addr.ToString().c_str()); return; } i++; } LogPrintf("dseg - Sent %d masternode entries to %s\n", count, pfrom->addr.ToString().c_str()); } else if (strCommand == "mnget") { //Masternode Payments Request Sync if(fLiteMode) return; //disable all darksend/masternode related functionality /*if(pfrom->HasFulfilledRequest("mnget")) { LogPrintf("mnget - peer already asked me for the list\n"); Misbehaving(pfrom->GetId(), 20); return; }*/ pfrom->FulfilledRequest("mnget"); masternodePayments.Sync(pfrom); LogPrintf("mnget - Sent masternode winners to %s\n", pfrom->addr.ToString().c_str()); } else if (strCommand == "mnw") { //Masternode Payments Declare Winner //this is required in litemode CMasternodePaymentWinner winner; int a = 0; vRecv >> winner >> a; if(pindexBest == NULL) return; uint256 hash = winner.GetHash(); if(mapSeenMasternodeVotes.count(hash)) { if(fDebug) LogPrintf("mnw - seen vote %s Height %d bestHeight %d\n", hash.ToString().c_str(), winner.nBlockHeight, pindexBest->nHeight); return; } if(winner.nBlockHeight < pindexBest->nHeight - 10 || winner.nBlockHeight > pindexBest->nHeight+20){ LogPrintf("mnw - winner out of range %s Height %d bestHeight %d\n", winner.vin.ToString().c_str(), winner.nBlockHeight, pindexBest->nHeight); return; } if(winner.vin.nSequence != std::numeric_limits<unsigned int>::max()){ LogPrintf("mnw - invalid nSequence\n"); Misbehaving(pfrom->GetId(), 100); return; } LogPrintf("mnw - winning vote %s Height %d bestHeight %d\n", winner.vin.ToString().c_str(), winner.nBlockHeight, pindexBest->nHeight); if(!masternodePayments.CheckSignature(winner)){ LogPrintf("mnw - invalid signature\n"); Misbehaving(pfrom->GetId(), 100); return; } mapSeenMasternodeVotes.insert(make_pair(hash, winner)); if(masternodePayments.AddWinningMasternode(winner)){ masternodePayments.Relay(winner); } } } struct CompareValueOnly { bool operator()(const pair<int64_t, CTxIn>& t1, const pair<int64_t, CTxIn>& t2) const { return t1.first < t2.first; } }; struct CompareValueOnly2 { bool operator()(const pair<int64_t, int>& t1, const pair<int64_t, int>& t2) const { return t1.first < t2.first; } }; int CountMasternodesAboveProtocol(int protocolVersion) { int i = 0; BOOST_FOREACH(CMasterNode& mn, vecMasternodes) { if(mn.protocolVersion < protocolVersion) continue; i++; } return i; } int GetMasternodeByVin(CTxIn& vin) { int i = 0; BOOST_FOREACH(CMasterNode& mn, vecMasternodes) { if (mn.vin == vin) return i; i++; } return -1; } bool IsMasternodePaidInList(std::vector<CScript> vecPaidMasternodes, CScript sAddress) { return std::find(vecPaidMasternodes.begin(), vecPaidMasternodes.end(), sAddress) != vecPaidMasternodes.end(); } int GetCurrentMasterNode(int64_t nBlockHeight, int minProtocol) { int i = 0; unsigned int score = 0; int winner = -1; // masternodes show be payed at most once per day // and rewards should be shared evenly amongst all contributors // this can be accomplished by checking the last cycle of blocks // and removing all already paid masternodes from the // winner selection for the next block int count = vecMasternodes.size(); count = std::max(count, 960); count = std::min(count, 1500); // limit so we don't cause wallet lockups int iCount = count; std::vector<CScript> vecPaidMasternodes; CBlockIndex* pblockindex = mapBlockIndex[hashBestChain]; for (int n = 0; n < count; n++) { CBlock block; if (block.ReadFromDisk(pblockindex)) { if (block.HasMasternodePayment()) { if (block.vtx[1].vout.size() == 3) { CScript mnScript = block.vtx[1].vout[2].scriptPubKey; if (!IsMasternodePaidInList(vecPaidMasternodes, mnScript)) vecPaidMasternodes.push_back(mnScript); } else if (block.vtx[1].vout.size() == 4) { CScript mnScript = block.vtx[1].vout[3].scriptPubKey; if (!IsMasternodePaidInList(vecPaidMasternodes, mnScript)) vecPaidMasternodes.push_back(mnScript); } } } pblockindex = pblockindex->pprev; } // scan for winner BOOST_FOREACH(CMasterNode mn, vecMasternodes) { CScript mnScript = GetScriptForDestination(mn.pubkey.GetID()); if (IsMasternodePaidInList(vecPaidMasternodes, mnScript)) { i++; continue; } mn.Check(); if(mn.protocolVersion < minProtocol) continue; if(!mn.IsEnabled()) { i++; continue; } // calculate the score for each masternode uint256 n = mn.CalculateScore(nBlockHeight); unsigned int n2 = 0; memcpy(&n2, &n, sizeof(n2)); // determine the winner if(n2 > score) { score = n2; winner = i; } i++; } return winner; } int GetMasternodeByRank(int findRank, int64_t nBlockHeight, int minProtocol) { int i = 0; std::vector<pair<unsigned int, int> > vecMasternodeScores; i = 0; BOOST_FOREACH(CMasterNode mn, vecMasternodes) { mn.Check(); if(mn.protocolVersion < minProtocol) continue; if(!mn.IsEnabled()) { i++; continue; } uint256 n = mn.CalculateScore(nBlockHeight); unsigned int n2 = 0; memcpy(&n2, &n, sizeof(n2)); vecMasternodeScores.push_back(make_pair(n2, i)); i++; } sort(vecMasternodeScores.rbegin(), vecMasternodeScores.rend(), CompareValueOnly2()); int rank = 0; BOOST_FOREACH (PAIRTYPE(unsigned int, int)& s, vecMasternodeScores){ rank++; if(rank == findRank) return s.second; } return -1; } int GetMasternodeRank(CTxIn& vin, int64_t nBlockHeight, int minProtocol) { std::vector<pair<unsigned int, CTxIn> > vecMasternodeScores = GetMasternodeScores(nBlockHeight, minProtocol); return GetMasternodeRank(vin, vecMasternodeScores); } int GetMasternodeRank(CTxIn& vin, std::vector<pair<unsigned int, CTxIn> >& vecMasternodeScores) { unsigned int rank = 0; BOOST_FOREACH (PAIRTYPE(unsigned int, CTxIn)& s, vecMasternodeScores) { rank++; if(s.second == vin) { return rank; } } return -1; } std::vector<pair<unsigned int, CTxIn> > GetMasternodeScores(int64_t nBlockHeight, int minProtocol) { std::vector<pair<unsigned int, CTxIn> > vecMasternodeScores; BOOST_FOREACH(CMasterNode& mn, vecMasternodes) { mn.Check(); if(mn.protocolVersion < minProtocol) { continue; } if(!mn.IsEnabled()) { continue; } uint256 n = mn.CalculateScore(nBlockHeight); unsigned int n2 = 0; memcpy(&n2, &n, sizeof(n2)); vecMasternodeScores.push_back(make_pair(n2, mn.vin)); } sort(vecMasternodeScores.rbegin(), vecMasternodeScores.rend(), CompareValueOnly()); return vecMasternodeScores; } //Get the last hash that matches the modulus given. Processed in reverse order bool GetBlockHash(uint256& hash, int nBlockHeight) { if (pindexBest == NULL) return false; if(nBlockHeight == 0) nBlockHeight = pindexBest->nHeight; if(mapCacheBlockHashes.count(nBlockHeight)){ hash = mapCacheBlockHashes[nBlockHeight]; return true; } const CBlockIndex *BlockLastSolved = pindexBest; const CBlockIndex *BlockReading = pindexBest; if (BlockLastSolved == NULL || BlockLastSolved->nHeight == 0 || pindexBest->nHeight+1 < nBlockHeight) return false; int nBlocksAgo = 0; if(nBlockHeight > 0) nBlocksAgo = (pindexBest->nHeight+1)-nBlockHeight; assert(nBlocksAgo >= 0); int n = 0; for (unsigned int i = 1; BlockReading && BlockReading->nHeight > 0; i++) { if(n >= nBlocksAgo){ hash = BlockReading->GetBlockHash(); mapCacheBlockHashes[nBlockHeight] = hash; return true; } n++; if (BlockReading->pprev == NULL) { assert(BlockReading); break; } BlockReading = BlockReading->pprev; } return false; } // // Deterministically calculate a given "score" for a masternode depending on how close it's hash is to // the proof of work for that block. The further away they are the better, the furthest will win the election // and get paid this block // uint256 CMasterNode::CalculateScore(int64_t nBlockHeight) { if(pindexBest == NULL) return 0; uint256 hash = 0; uint256 aux = vin.prevout.hash + vin.prevout.n; if(!GetBlockHash(hash, nBlockHeight)) return 0; CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION); ss << hash; uint256 hash2 = ss.GetHash(); CHashWriter ss2(SER_GETHASH, PROTOCOL_VERSION); ss2 << hash; ss2 << aux; uint256 hash3 = ss2.GetHash(); uint256 r = (hash3 > hash2 ? hash3 - hash2 : hash2 - hash3); return r; } void CMasterNode::Check() { //once spent, stop doing the checks if(enabled==3) return; if(!UpdatedWithin(MASTERNODE_REMOVAL_SECONDS)){ enabled = 4; return; } if(!UpdatedWithin(MASTERNODE_EXPIRATION_SECONDS)){ enabled = 2; return; } if(!unitTest){ CValidationState state; CTransaction tx = CTransaction(); int64_t nTempTxOut = (MASTERNODE_COLLATERAL/COIN) - 1; CTxOut vout = CTxOut(nTempTxOut*COIN, darkSendPool.collateralPubKey); tx.vin.push_back(vin); tx.vout.push_back(vout); bool pfMissingInputs = false; if(!AcceptableInputs(mempool, state, tx, false, &pfMissingInputs)) { enabled = 3; return; } } enabled = 1; // OK } bool CMasternodePayments::CheckSignature(CMasternodePaymentWinner& winner) { //note: need to investigate why this is failing std::string strMessage = winner.vin.ToString().c_str() + boost::lexical_cast<std::string>(winner.nBlockHeight) + winner.payee.ToString(); std::string strPubKey = strMainPubKey ; CPubKey pubkey(ParseHex(strPubKey)); std::string errorMessage = ""; if(!darkSendSigner.VerifyMessage(pubkey, winner.vchSig, strMessage, errorMessage)){ return false; } return true; } bool CMasternodePayments::Sign(CMasternodePaymentWinner& winner) { std::string strMessage = winner.vin.ToString().c_str() + boost::lexical_cast<std::string>(winner.nBlockHeight) + winner.payee.ToString(); CKey key2; CPubKey pubkey2; std::string errorMessage = ""; if(!darkSendSigner.SetKey(strMasterPrivKey, errorMessage, key2, pubkey2)) { LogPrintf("CMasternodePayments::Sign - ERROR: Invalid masternodeprivkey: '%s'\n", errorMessage.c_str()); return false; } if(!darkSendSigner.SignMessage(strMessage, errorMessage, winner.vchSig, key2)) { LogPrintf("CMasternodePayments::Sign - Sign message failed"); return false; } if(!darkSendSigner.VerifyMessage(pubkey2, winner.vchSig, strMessage, errorMessage)) { LogPrintf("CMasternodePayments::Sign - Verify message failed"); return false; } return true; } uint64_t CMasternodePayments::CalculateScore(uint256 blockHash, CTxIn& vin) { uint256 n1 = blockHash; uint256 n2 = Hash(BEGIN(n1), END(n1)); uint256 n3 = Hash(BEGIN(vin.prevout.hash), END(vin.prevout.hash)); uint256 n4 = n3 > n2 ? (n3 - n2) : (n2 - n3); //LogPrintf(" -- CMasternodePayments CalculateScore() n2 = %d \n", n2.Get64()); //LogPrintf(" -- CMasternodePayments CalculateScore() n3 = %d \n", n3.Get64()); //LogPrintf(" -- CMasternodePayments CalculateScore() n4 = %d \n", n4.Get64()); return n4.Get64(); } bool CMasternodePayments::GetBlockPayee(int nBlockHeight, CScript& payee) { BOOST_FOREACH(CMasternodePaymentWinner& winner, vWinning){ if(winner.nBlockHeight == nBlockHeight) { payee = winner.payee; return true; } } return false; } bool CMasternodePayments::GetWinningMasternode(int nBlockHeight, CTxIn& vinOut) { BOOST_FOREACH(CMasternodePaymentWinner& winner, vWinning){ if(winner.nBlockHeight == nBlockHeight) { vinOut = winner.vin; return true; } } return false; } bool CMasternodePayments::AddWinningMasternode(CMasternodePaymentWinner& winnerIn) { uint256 blockHash = 0; if(!GetBlockHash(blockHash, winnerIn.nBlockHeight-576)) { return false; } winnerIn.score = CalculateScore(blockHash, winnerIn.vin); bool foundBlock = false; BOOST_FOREACH(CMasternodePaymentWinner& winner, vWinning){ if(winner.nBlockHeight == winnerIn.nBlockHeight) { foundBlock = true; if(winner.score < winnerIn.score){ winner.score = winnerIn.score; winner.vin = winnerIn.vin; winner.payee = winnerIn.payee; winner.vchSig = winnerIn.vchSig; return true; } } } // if it's not in the vector if(!foundBlock){ vWinning.push_back(winnerIn); mapSeenMasternodeVotes.insert(make_pair(winnerIn.GetHash(), winnerIn)); return true; } return false; } void CMasternodePayments::CleanPaymentList() { if(pindexBest == NULL) return; int nLimit = std::max(((int)vecMasternodes.size())*2, 1000); vector<CMasternodePaymentWinner>::iterator it; for(it=vWinning.begin();it<vWinning.end();it++){ if(pindexBest->nHeight - (*it).nBlockHeight > nLimit){ if(fDebug) LogPrintf("CMasternodePayments::CleanPaymentList - Removing old masternode payment - block %d\n", (*it).nBlockHeight); vWinning.erase(it); break; } } } bool CMasternodePayments::ProcessBlock(int nBlockHeight) { if(!enabled) return false; CMasternodePaymentWinner winner; std::vector<CTxIn> vecLastPayments; int c = 0; BOOST_REVERSE_FOREACH(CMasternodePaymentWinner& winner, vWinning){ vecLastPayments.push_back(winner.vin); //if we have one full payment cycle, break if(++c > (int)vecMasternodes.size()) break; } std::random_shuffle ( vecMasternodes.begin(), vecMasternodes.end() ); BOOST_FOREACH(CMasterNode& mn, vecMasternodes) { bool found = false; BOOST_FOREACH(CTxIn& vin, vecLastPayments) if(mn.vin == vin) found = true; if(found) continue; mn.Check(); if(!mn.IsEnabled()) { continue; } winner.score = 0; winner.nBlockHeight = nBlockHeight; winner.vin = mn.vin; winner.payee =GetScriptForDestination(mn.pubkey.GetID()); break; } //if we can't find someone to get paid, pick randomly if(winner.nBlockHeight == 0 && vecMasternodes.size() > 0) { winner.score = 0; winner.nBlockHeight = nBlockHeight; winner.vin = vecMasternodes[0].vin; winner.payee =GetScriptForDestination(vecMasternodes[0].pubkey.GetID()); } if(Sign(winner)){ if(AddWinningMasternode(winner)){ Relay(winner); return true; } } return false; } void CMasternodePayments::Relay(CMasternodePaymentWinner& winner) { CInv inv(MSG_MASTERNODE_WINNER, winner.GetHash()); vector<CInv> vInv; vInv.push_back(inv); LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes){ pnode->PushMessage("inv", vInv); } } void CMasternodePayments::Sync(CNode* node) { int a = 0; BOOST_FOREACH(CMasternodePaymentWinner& winner, vWinning) if(winner.nBlockHeight >= pindexBest->nHeight-10 && winner.nBlockHeight <= pindexBest->nHeight + 20) node->PushMessage("mnw", winner, a); } bool CMasternodePayments::SetPrivKey(std::string strPrivKey) { CMasternodePaymentWinner winner; // Test signing successful, proceed strMasterPrivKey = strPrivKey; Sign(winner); if(CheckSignature(winner)){ LogPrintf("CMasternodePayments::SetPrivKey - Successfully initialized as masternode payments master\n"); enabled = true; return true; } else { return false; } }
[ "dstoneham.93@gmail.com" ]
dstoneham.93@gmail.com
aba668714a63e3b52f0f6f5056f1c59a328a48d1
3011f9e4204f2988c983b8815187f56a6bf58ebd
/src/ys_library/ysfontrenderer/src/yssystemfontrenderer.cpp
d0a2edc1f1eba15c05c12335e75b2d34f007aba2
[]
no_license
hvantil/AR-BoardGames
9e80a0f2bb24f8bc06902785d104178a214d0d63
71b9620df66d80c583191b8c8e8b925a6df5ddc3
refs/heads/master
2020-03-17T01:36:47.674272
2018-05-13T18:11:16
2018-05-13T18:11:16
133,160,216
0
0
null
null
null
null
UTF-8
C++
false
false
3,094
cpp
/* //////////////////////////////////////////////////////////// File Name: yssystemfontrenderer.cpp Copyright (c) 2017 Soji Yamakawa. All rights reserved. http://www.ysflight.com Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. //////////////////////////////////////////////////////////// */ #include "yssystemfontrenderer.h" #include <yssystemfont.h> YsSystemFontRenderer::YsSystemFontRenderer() { fontCache=new YsSystemFontCache; Initialize(); } YsSystemFontRenderer::~YsSystemFontRenderer() { delete fontCache; } void YsSystemFontRenderer::Initialize(void) { RequestDefaultFontWithPixelHeight(10); fontHeightCache=0; } YSRESULT YsSystemFontRenderer::RequestDefaultFontWithPixelHeight(unsigned int fontHeightInPix) { fontHeightCache=0; return fontCache->RequestDefaultFontWithHeight(fontHeightInPix); } YSRESULT YsSystemFontRenderer::RenderString(YsBitmap &bmp,const wchar_t wStr[],const YsColor &fgCol,const YsColor &bgCol) const { unsigned char fg[3]={(unsigned char)fgCol.Ri(),(unsigned char)fgCol.Gi(),(unsigned char)fgCol.Bi()}; unsigned char bg[3]={(unsigned char)bgCol.Ri(),(unsigned char)bgCol.Gi(),(unsigned char)bgCol.Bi()}; YsSystemFontTextBitmap tmpBmp; if(YSOK==fontCache->MakeRGBABitmap(tmpBmp,wStr,fg,bg,YSTRUE)) { const unsigned int wid=tmpBmp.Width(); const unsigned int hei=tmpBmp.Height(); unsigned char *bmpBuf=tmpBmp.TransferBitmap(); bmp.SetDirect(wid,hei,bmpBuf); return YSOK; } bmp.CleanUp(); return YSERR; } YSRESULT YsSystemFontRenderer::GetTightRenderSize(int &wid,int &hei,const wchar_t wStr[]) const { return fontCache->GetTightBitmapSize(wid,hei,wStr); } int YsSystemFontRenderer::GetFontHeight(void) const { if(0==fontHeightCache) { int x; GetTightRenderSize(x,fontHeightCache,L"X"); } return fontHeightCache; }
[ "harrison.vantil@outlook.com" ]
harrison.vantil@outlook.com
ba04a69bef5bf63a44b099bcb31aa96ed6724ece
f315fa72bef535ab925573c63abd96fff3ba6983
/src/kitti/DrawTracklet.cpp
8112521990d978bbc528c0c13ccc805bc22bf1be
[]
no_license
VTD-YJ/VirtualTestDriveFramework
161fb95cfc680c60733d35ee531ecf7f8ae4e9df
a6fb65f73dc27b956c6f13786063ab7ffa56a86c
refs/heads/master
2022-04-24T21:01:55.131085
2017-06-27T14:26:11
2017-06-27T14:26:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,064
cpp
// // Created by geislerd on 16.03.17. // #include <kitti/DrawTracklet.h> namespace saliency_sandbox { namespace kitti { template<Camera _camera> void DrawTracklet<_camera>::convert(input_image_t &img) { this->m_data.mat(img); } template<> void DrawTracklet<LEFT_GRAY>::convert(input_image_t &img) { cv::cvtColor(img, this->m_data, CV_GRAY2RGB); } template<> void DrawTracklet<RIGHT_GRAY>::convert(input_image_t &img) { cv::cvtColor(img, this->m_data, CV_GRAY2RGB); } template<Camera _camera> bool DrawTracklet<_camera>::inImage(cv::Point *points, size_t num) { bool ret = true; for (int i = 0; i < num && ret; i++) ret &= (points[i].x > 0 && points[i].y > 0) && (points[i].x < 1242 && points[i].y < 375); return ret; } template<Camera _camera> void DrawTracklet<_camera>::drawTracklet(Tracklet &tracklet, Calibration &calibration) { cv::Vec3f faces3D[16]; cv::Vec2f faces2D[16]; cv::Point pf[4], center(0, 0); size_t num = 0; std::stringstream saliency_ss; tracklet.boundingbox(faces3D); calibration.veloToCam(faces3D, faces2D, 16, _camera); for (int i = 0; i < 16; i += 4) { pf[0] = cv::Point2f(faces2D[i + 0]); pf[1] = cv::Point2f(faces2D[i + 1]); pf[2] = cv::Point2f(faces2D[i + 2]); pf[3] = cv::Point2f(faces2D[i + 3]); if (this->inImage(pf, 4)) { cv::line(this->m_data, pf[0], pf[1], cv::Scalar(255, 0, 0)); cv::line(this->m_data, pf[1], pf[2], cv::Scalar(0, 255, 0)); cv::line(this->m_data, pf[2], pf[3], cv::Scalar(0, 0, 255)); cv::line(this->m_data, pf[3], pf[0], cv::Scalar(255, 0, 255)); center += pf[0] + pf[1] + pf[2] + pf[3]; num += 4; } } if (num > 0) { center.x /= num; center.y /= num; } else return; cv::putText(this->m_data, tracklet.label(), center, CV_FONT_HERSHEY_COMPLEX_SMALL, 0.8, cvScalar(255, 255, 255), 1, CV_AA); if (tracklet.properties()->template has<float>("saliency")) { saliency_ss << "s: " << std::setprecision(2) << tracklet.properties()->template get<float>("saliency"); cv::putText(this->m_data, saliency_ss.str(), cv::Point(center.x, center.y + 14), CV_FONT_HERSHEY_COMPLEX_SMALL, 0.8, cvScalar(255, 255, 255), 1, CV_AA); } } template<Camera _camera> void DrawTracklet<_camera>::drawTracklets(TrackletList &tracklets, Calibration &calibration) { for (int i = 0; i < tracklets.size(); i++) this->drawTracklet(*tracklets[i], calibration); } template<Camera _camera> DrawTracklet<_camera>::DrawTracklet() { this->template input<0>()->name("image"); this->template input<1>()->name("tracking"); this->template input<2>()->name("calibration"); this->template output<0>()->name("image"); this->template output<0>()->value(&(this->m_data)); } template<Camera _camera> void DrawTracklet<_camera>::calc() { this->convert(*this->template input<0>()->value()); this->drawTracklets(*this->template input<1>()->value(), *this->template input<2>()->value()); this->template output<0>()->value(&(this->m_data)); } template<Camera _camera> void DrawTracklet<_camera>::reset() {} template class DrawTracklet<LEFT_GRAY>; template class DrawTracklet<RIGHT_GRAY>; template class DrawTracklet<LEFT_RGB>; template class DrawTracklet<RIGHT_RGB>; } }
[ "david.geisler@uni-tuebingen.de" ]
david.geisler@uni-tuebingen.de
16c8bf98fd3db51be736fd44b51e561bd2823914
600df3590cce1fe49b9a96e9ca5b5242884a2a70
/third_party/WebKit/public/platform/modules/background_sync/WebSyncError.h
8eae550745628620251cf2f0c909c75a3666bf90
[ "BSD-3-Clause", "LGPL-2.0-or-later", "LicenseRef-scancode-warranty-disclaimer", "LGPL-2.1-only", "GPL-1.0-or-later", "GPL-2.0-only", "LGPL-2.0-only", "BSD-2-Clause", "LicenseRef-scancode-other-copyleft", "MIT", "Apache-2.0" ]
permissive
metux/chromium-suckless
efd087ba4f4070a6caac5bfbfb0f7a4e2f3c438a
72a05af97787001756bae2511b7985e61498c965
refs/heads/orig
2022-12-04T23:53:58.681218
2017-04-30T10:59:06
2017-04-30T23:35:58
89,884,931
5
3
BSD-3-Clause
2022-11-23T20:52:53
2017-05-01T00:09:08
null
UTF-8
C++
false
false
693
h
// Copyright 2015 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. #ifndef WebSyncError_h #define WebSyncError_h #include "public/platform/WebString.h" namespace blink { struct WebSyncError { enum ErrorType { ErrorTypeAbort = 0, ErrorTypeNoPermission, ErrorTypeNotFound, ErrorTypePermissionDenied, ErrorTypeUnknown, ErrorTypeLast = ErrorTypeUnknown }; WebSyncError(ErrorType errorType, const WebString& message) : errorType(errorType), message(message) {} ErrorType errorType; WebString message; }; } // namespace blink #endif // WebSyncError_h
[ "enrico.weigelt@gr13.net" ]
enrico.weigelt@gr13.net
a3250c05e497674fdac373dc27c3df7f50b46e73
a4fa50c7af93f09b2ddf463ddacd82ed404615f9
/include/ir/instructions/IRInstruction.h
4339f4444e48fc43233059c7a5a1e884c7694dd4
[]
no_license
hadley-siqueira/hdc
4cd0ab8b98afbc6ee207fc963443e5b89aa0a458
4df9e3f8d4070139de292fd98de93d8afbd659b2
refs/heads/master
2021-07-08T12:04:59.211561
2020-12-28T02:20:46
2020-12-28T02:20:46
136,125,618
3
0
null
null
null
null
UTF-8
C++
false
false
233
h
#ifndef HDC_IR_INSTRUCTION_H #define HDC_IR_INSTRUCTION_H #include "ir/IR.h" namespace hdc { class IRInstruction : public IR { public: virtual void accept(IRVisitor* visitor)=0; }; } #endif // IRINSTRUCTION_H
[ "hadley.siqueira@gmail.com" ]
hadley.siqueira@gmail.com
bbb859afa0b129c88714ec9aba359ec9a500ac4b
248baea990108d445b554908ec70f6df680f0dd8
/src/openSMOKEpp4kineticOptimizer/math/native-dae-solvers/interfaces/Band_Ida.h
7539596d926bbbfc9e323a643e83bf6436024d64
[]
no_license
olarrh/OpenSMOKEpp_KineticOptimizer
7dbf5776441f5c22f30439ac550d58cd5d0ab7b7
a90468b3583629c4ef3d50c3012f5b40f74c9bcc
refs/heads/master
2020-06-23T11:37:39.476575
2018-07-22T21:43:48
2018-07-22T21:43:48
null
0
0
null
null
null
null
MacCentralEurope
C++
false
false
17,262
h
/*----------------------------------------------------------------------*\ | ___ ____ __ __ ___ _ _______ | | / _ \ _ __ ___ _ __ / ___|| \/ |/ _ \| |/ / ____| _ _ | | | | | | '_ \ / _ \ '_ \\___ \| |\/| | | | | ' /| _| _| |_ _| |_ | | | |_| | |_) | __/ | | |___) | | | | |_| | . \| |__|_ _|_ _| | | \___/| .__/ \___|_| |_|____/|_| |_|\___/|_|\_\_____||_| |_| | | |_| | | | | Author: Alberto Cuoci <alberto.cuoci@polimi.it> | | CRECK Modeling Group <http://creckmodeling.chem.polimi.it> | | Department of Chemistry, Materials and Chemical Engineering | | Politecnico di Milano | | P.zza Leonardo da Vinci 32, 20133 Milano | | | |-------------------------------------------------------------------------| | | | This file is part of OpenSMOKE++ Suite. | | | | Copyright(C) 2015, 2014, 2013 Alberto Cuoci | | Source-code or binary products cannot be resold or distributed | | Non-commercial use only | | Cannot modify source-code for any purpose (cannot create | | derivative works) | | | \*-----------------------------------------------------------------------*/ #include <boost/timer/timer.hpp> #include <sunmatrix/sunmatrix_sparse.h> /* access to sparse SUNMatrix */ #include <sunlinsol/sunlinsol_dense.h> /* access to dense SUNLinearSolver */ #include <sunlinsol/sunlinsol_band.h> /* access to dense SUNLinearSolver */ #include <sunlinsol/sunlinsol_lapackdense.h> /* access to dense SUNLinearSolver */ #include <sunlinsol/sunlinsol_lapackband.h> /* access to dense SUNLinearSolver */ #include <ida/ida_spils.h> /* access to IDASpils interface */ #include <sunlinsol/sunlinsol_spgmr.h> /* access to spgmr SUNLinearSolver */ namespace DaeSMOKE { static void IDAStatistics(void *mem, realtype cpuTime, N_Vector y, N_Vector yp); void CheckSolver(const int flag_solver); template<typename Object> int Solve_Band_Ida(Object* object, const DaeSMOKE::DaeSolver_Parameters& parameters, const double t0, const double tEnd) { std::cout << "Band DAE solution (IDA)..." << std::endl; const int neq = object->NumberOfEquations(); void *mem; int flag; int ier; N_Vector y; N_Vector yp; N_Vector res; N_Vector id; N_Vector yInitial; IDAUserData data; SUNMatrix A; SUNLinearSolver LS; mem = NULL; data = NULL; y = NULL; yp = NULL; res = NULL; id = NULL; yInitial = NULL; A = NULL; LS = NULL; // Memory allocation { y = N_VNew_Serial(neq); if (check_flag((void *)y, "N_VNew_Serial", 0)) return(1); yp = N_VNew_Serial(neq); if (check_flag((void *)yp, "N_VNew_Serial", 0)) return(1); res = N_VNew_Serial(neq); if (check_flag((void *)res, "N_VNew_Serial", 0)) return(1); id = N_VNew_Serial(neq); if (check_flag((void *)id, "N_VNew_Serial", 0)) return(1); yInitial = N_VNew_Serial(neq); if (check_flag((void *)yInitial, "N_VNew_Serial", 0)) return(1); } // User data data = (IDAUserData)malloc(sizeof *data); //Initialize { object->UnknownsVector(NV_DATA_S(y)); object->UnknownsVector(NV_DATA_S(yInitial)); } // Initialize and allocate memory mem = IDACreate(); if (check_flag((void *)mem, "IDACreate", 0)) return(1); // Set user data flag = IDASetUserData(mem, data); if (check_flag(&flag, "IDASetUserData", 1)) return(1); if (parameters.sparse_linear_algebra() == true) { data->J = N_VNew_Serial(neq); if (check_flag((void *)data->J, "N_VNew_Serial", 0)) return(1); data->invJ = N_VNew_Serial(neq); if (check_flag((void *)data->invJ, "N_VNew_Serial", 0)) return(1); } // Differential/Algebraic equations { object->AlgebraicDifferentialVector(NV_DATA_S(id)); flag = IDASetId(mem, id); if (check_flag(&flag, "IDASetId", 1)) return(1); } // Assign the system { //Initialize yp vector to 0. ida_initial_derivatives(t0, y, yp, data); flag = IDAInit(mem, ida_equations, ida_print_solution, t0, y, yp); if (check_flag(&flag, "IDAInit", 1)) return(1); } // Set optional input { // Tolerances if (parameters.relative_tolerances().size() == neq) { // Allocate memory for absolute tolerances vector N_Vector abstol; abstol = N_VNew_Serial(neq); if (check_flag((void *)abstol, "N_VNew_Serial", 0)) return(1); // Fill the vector for (int i=0;i<neq;i++) NV_Ith_S(abstol,i) = parameters.absolute_tolerances()(i); // Assign the vector flag = IDASVtolerances(mem, parameters.relative_tolerance(), abstol); if (check_flag(&flag, "IDASVtolerances", 1)) return(1); // Free the memory N_VDestroy_Serial(abstol); } else { flag = IDASStolerances(mem, parameters.relative_tolerance(), parameters.absolute_tolerance()); if (check_flag(&flag, "IDASStolerances", 1)) return(1); } // Maximum number of steps flag = IDASetMaxNumSteps(mem, parameters.maximum_number_of_steps()); if (check_flag(&flag, "IDASetMaxNumSteps", 1)) return(1); /* // Maximum number of error test failures flag = IDASetMaxErrTestFails(mem, parameters.maximum_err_test_fails()); if (check_flag(&flag, "IDASetMaxErrTestFails", 1)) return(1); // Maximum number of non linear iterations flag = IDASetMaxNonlinIters(mem, parameters.maximum_nl_iter()); if (check_flag(&flag, "IDASetMaxNonlinIters", 1)) return(1); // Maximum number of convergence failures flag = IDASetMaxConvFails(mem, parameters.maximum_conv_fails()); if (check_flag(&flag, "IDASetMaxConvFails", 1)) return(1); // Maximum number of non linear convergence tests flag = IDASetNonlinConvCoef(mem, parameters.coefficient_nonlinear_convergence_test()); if (check_flag(&flag, "IDASetNonlinConvCoef", 1)) return(1); // Maximum order flag = IDASetMaxOrd(mem, parameters.maximum_order()); if (check_flag(&flag, "IDASetMaxOrd", 1)) return(1); // Initial step size if (parameters.initial_step() > 0.) { flag = IDASetInitStep(mem, parameters.initial_step()); if (check_flag(&flag, "IDASetInitStep", 1)) return(1); } // Maximum step size if (parameters.maximum_step() > 0.) { flag = IDASetMaxStep(mem, parameters.maximum_step()); if (check_flag(&flag, "IDASetInitStep", 1)) return(1); } */ } // Set minimum constraints if (parameters.non_negative_unknowns() == true) { N_Vector constraints; constraints = NULL; constraints = N_VNew_Serial(neq); if (check_flag((void *)constraints, "N_VNew_Serial", 0)) return(1); // All the unknowns will be constrained to be >= 0 N_VConst(1., constraints); flag = KINSetConstraints(mem, constraints); if (check_flag(&flag, "KINSetConstraints", 1)) return(1); N_VDestroy_Serial(constraints); } // Set maximum constraints if (parameters.maximum_constraints() == true) { // Sundials IDA does not support this function } // Attach band linear solver { // Band solver if (parameters.sparse_linear_algebra() == false) { int mu = object->UpperBand(); int ml = object->LowerBand(); #if OPENSMOKE_USE_MKL == 1 { std::cout << "IDA with Lapack solver..." << std::endl; /* Create banded SUNMatrix for use in linear solves -- since this will be factored, set the storage bandwidth to be the sum of upper and lower bandwidths */ A = SUNBandMatrix(neq, mu, ml, (mu + ml)); if (check_flag((void *)A, "SUNBandMatrix", 0)) return(1); /* Create banded SUNLinearSolver object for use by CVode */ LS = SUNLapackBand(y, A); if (check_flag((void *)LS, "SUNLapackBand", 0)) return(1); } #else { /* Create banded SUNMatrix for use in linear solves -- since this will be factored, set the storage bandwidth to be the sum of upper and lower bandwidths */ A = SUNBandMatrix(neq, mu, ml, (mu + ml)); if (check_flag((void *)A, "SUNBandMatrix", 0)) return(1); /* Create banded SUNLinearSolver object for use by CVode */ LS = SUNBandLinearSolver(y, A); if (check_flag((void *)LS, "SUNBandLinearSolver", 0)) return(1); } #endif /* Attach the matrix and linear solver */ flag = IDADlsSetLinearSolver(mem, LS, A); if (check_flag(&flag, "IDADlsSetLinearSolver", 1)) return(1); } // Iterative (sparse) solver else { /* Create the linear solver SUNSPGMR with left preconditioning and the default Krylov dimension */ LS = SUNSPGMR(y, PREC_LEFT, 0); if (check_flag((void *)LS, "SUNSPGMR", 0)) return(1); /* IDA recommends allowing up to 5 restarts (default is 0) */ ier = SUNSPGMRSetMaxRestarts(LS, 5); if (check_flag(&ier, "SUNSPGMRSetMaxRestarts", 1)) return(1); /* Attach the linear sovler */ ier = IDASpilsSetLinearSolver(mem, LS); if (check_flag(&ier, "IDASpilsSetLinearSolver", 1)) return(1); // TODO std::cout << "IDASpilsSetPreconditioner not available" << std::endl; getchar(); exit(-1); /* Set the preconditioner solve and setup functions */ //ier = IDASpilsSetPreconditioner(mem, ida_preconditioner_setup, ida_preconditioner_solution); //if (check_flag(&ier, "IDASpilsSetPreconditioner", 1)) return(1); } } double increasing_factor = 10.; unsigned int n_steps = 7; double t_initial = t0; double dt0 = 0.; if (t0 == 0.) t_initial = tEnd / std::pow(increasing_factor, double(n_steps-1)); else { double sum = 1.; for (unsigned int i = 1; i <= n_steps - 1; i++) sum += std::pow(increasing_factor, double(i)); dt0 = (tEnd - t0) / sum; t_initial = t0 + dt0; } // Call IDACalcIC to correct the initial values. std::cout << "Initial conditions..." << t0 << " " << tEnd << std::endl; flag = IDACalcIC(mem, IDA_YA_YDP_INIT, t_initial); if (check_flag(&flag, "IDACalcIC", 1)) return(1); // Loop over output times, call IDASolve, and print results. int flag_solver; boost::timer::cpu_timer timer; double tout = t_initial; for (unsigned int iout = 1; iout <= n_steps; iout++) { std::cout << "Integrating to: " << tout << std::endl; realtype tret; flag_solver = IDASolve(mem, tout, &tret, y, yp, IDA_NORMAL); if (check_flag(&flag_solver, "IDASolve", 1)) return(1); CheckSolver(flag_solver); if (flag_solver >= 0) { realtype sum_abs_yp = N_SumAbs(yp); realtype norm2_yp = N_Norm2(yp); // Get scaled norm of the system function std::cout << " IDA solution: " << "||y'||sum = " << sum_abs_yp << " ||y'||2 = " << norm2_yp << std::endl; // Check if the solution reached the steady state conditions if (sum_abs_yp < parameters.minimum_yp()*neq) break; } else { break; } if (t0 == 0.) tout *= increasing_factor; else tout += dt0*std::pow(increasing_factor, double(iout)); } boost::timer::cpu_times elapsed = timer.elapsed(); if (flag_solver >= 0) { // Give results back object->CorrectedUnknownsVector(NV_DATA_S(y)); // Print remaining counters and free memory. double cpuTime = elapsed.wall / 1.e9; IDAStatistics(mem, cpuTime, y, yp); } else { // Recover initial solution object->CorrectedUnknownsVector(NV_DATA_S(yInitial)); } // Free memory IDAFree(&mem); N_VDestroy_Serial(y); N_VDestroy_Serial(yInitial); N_VDestroy_Serial(yp); N_VDestroy_Serial(id); N_VDestroy_Serial(res); free(data); SUNLinSolFree(LS); SUNMatDestroy(A); return flag_solver; } static void IDAStatistics(void *mem, realtype cpuTime, N_Vector y, N_Vector yp) { int flag; realtype hused; long int nst, nni, nje, nre, nreLS; int kused; int neq = NV_LENGTH_S(y); check_flag(&flag, "IDAGetNumSteps", 1); flag = IDAGetNumNonlinSolvIters(mem, &nni); flag = IDAGetLastOrder(mem, &kused); check_flag(&flag, "IDAGetLastOrder", 1); flag = IDAGetLastStep(mem, &hused); check_flag(&flag, "IDAGetLastStep", 1); flag = IDADlsGetNumJacEvals(mem, &nje); check_flag(&flag, "IDADlsGetNumJacEvals", 1); flag = IDAGetNumResEvals(mem, &nre); check_flag(&flag, "IDAGetNumResEvals", 1); flag = IDADlsGetNumResEvals(mem, &nreLS); check_flag(&flag, "IDADlsGetNumResEvals", 1); flag = IDAGetNumSteps(mem, &nst); check_flag(&flag, "IDAGetNumNonlinSolvIters", 1); std::cout << std::endl; std::cout << " * CPU time (s): " << cpuTime << std::endl; std::cout << " * number of steps: " << nni << std::endl; std::cout << " * number of functions: " << nre << std::endl; std::cout << " * number of non linear iter.: " << nst << std::endl; std::cout << " * number of Jacobians: " << nje << std::endl; std::cout << " * dummy: " << 0 << std::endl; std::cout << " * number of functions (Jacobian): " << nreLS << std::endl; std::cout << " * last order: " << kused << std::endl; std::cout << " * last step size: " << std::scientific << hused << std::endl; std::cout << " * mean y': " << std::scientific << N_SumAbs(yp) / double(neq) << std::endl; std::cout << std::endl; } void CheckSolver(const int flag_solver) { if (flag_solver >= 0) { std::string message("IDA successfully solved: "); // IDASolve succeeded if (flag_solver == IDA_SUCCESS) message += "IDA_SUCCESS"; // IDASolve succeeded by reaching the stop point specified through the optional input function IDASetStopTime. else if (flag_solver == IDA_TSTOP_RETURN) message += "IDA_TSTOP_RETURN"; // IDASolve succeeded and found one or more roots.In this case, // tret is the location of the root.If nrtfn > 1, call IDAGetRootInfo // to see which gi were found to have a root.See ß4.5.9.3 for more information. else if (flag_solver == IDA_ROOT_RETURN) message += "IDA_ROOT_RETURN"; } else { std::string message("IDA solver error: "); // The ida mem argument was NULL if (flag_solver == IDA_MEM_NULL) message += "IDA_MEM_NULL"; // One of the inputs to IDASolve was illegal, or some other input to the solver was either illegal or missing.The latter category // includes the following situations : (a)The tolerances have not been set. (b) A component of the error weight vector became zero during // internal time - stepping. (c)The linear solver initialization function (called by the user after calling IDACreate) failed to set the linear // solver - specific lsolve field in ida mem. (d)A root of one of the root functions was found both at a point t and also very near t.In // any case, the user should see the printed error message for details. else if (flag_solver == IDA_ILL_INPUT) message += "IDA_ILL_INPUT"; // The solver took mxstep internal steps but could not reach tout. // The default value for mxstep is MXSTEP DEFAULT = 500. else if (flag_solver == IDA_TOO_MUCH_WORK) message += "IDA_TOO_MUCH_WORK"; // The solver could not satisfy the accuracy demanded by the user for some internal step. else if (flag_solver == IDA_TOO_MUCH_ACC) message += "IDA_TOO_MUCH_ACC"; // Error test failures occurred too many times(MXNEF = 10) during // one internal time step or occurred with | h | = hmin. else if (flag_solver == IDA_ERR_FAIL) message += "IDA_ERR_FAIL"; // Convergence test failures occurred too many times(MXNCF = 10) // during one internal time step or occurred with | h | = hmin. else if (flag_solver == IDA_CONV_FAIL) message += "IDA_CONV_FAIL"; // The linear solverís initialization function failed. else if (flag_solver == IDA_LINIT_FAIL) message += "IDA_LINIT_FAIL"; // The linear solverís setup function failed in an unrecoverable manner. else if (flag_solver == IDA_LSETUP_FAIL) message += "IDA_LSETUP_FAIL"; // The linear solverís solve function failed in an unrecoverable manner. else if (flag_solver == IDA_LSOLVE_FAIL) message += "IDA_LSOLVE_FAIL"; // The inequality constraints were violated and the solver was unable to recover. else if (flag_solver == IDA_CONSTR_FAIL) message += "IDA_CONSTR_FAIL"; // The userís residual function repeatedly returned a recoverable error flag, but the solver was unable to recover. else if (flag_solver == IDA_REP_RES_ERR) message += "IDA_REP_RES_ERR"; // The userís residual function returned a nonrecoverable error flag. else if (flag_solver == IDA_RES_FAIL) message += "IDA_RES_FAIL"; // The rootfinding function failed. else if (flag_solver == IDA_RTFUNC_FAIL) message += "IDA_RTFUNC_FAIL"; std::cout << message << std::endl; } } }
[ "alberto.cuoci@polimi.it" ]
alberto.cuoci@polimi.it
2b7d4497100d8dd733fd1c562ee56cbbf376c36f
b69757fb6048d2bca2aa62b19d6e50f68bc6381f
/Volume 015/UVa1583.cpp
5619ec85be76d007d9627130cc0aceed526182ab
[]
no_license
absa1am/UVa-Solutions
afbf5304b5b994ecc009aac2f283ad6ee99df412
c06d2c23b62d3f2a7409420b0c7afbf906ee5e5b
refs/heads/master
2020-07-23T13:09:54.158083
2020-03-04T09:42:30
2020-03-04T09:42:30
205,831,241
0
0
null
null
null
null
UTF-8
C++
false
false
506
cpp
/* * Problem: 1584 - Digit Generator */ #include <bits/stdc++.h> #define MAX 100007 using namespace std; int gen[MAX]; void digitSum(int n) { int x, sum; for(int i = 1; i <= n; i++) { x = i; sum = x; while(x > 0) { sum += (x % 10); x /= 10; } if(!gen[sum]) gen[sum] = i; } } int main() { int T, n; digitSum(MAX); cin >> T; while(T--) { cin >> n; cout << gen[n] << "\n"; } return 0; }
[ "salaam.mbstu@gmail.com" ]
salaam.mbstu@gmail.com
bd2827fe45981ab628d20c90e9fadcb5838e9ebe
89dedd7f3c7acc81d12e2bcb2e716f9af9e5fa04
/third_party/WebKit/Source/core/page/PrintContext.cpp
5b745438fc202ad1e093cc152bde688882dadd39
[ "BSD-3-Clause", "LGPL-2.0-or-later", "LicenseRef-scancode-warranty-disclaimer", "LGPL-2.1-only", "GPL-1.0-or-later", "GPL-2.0-only", "LGPL-2.0-only", "BSD-2-Clause", "LicenseRef-scancode-other-copyleft", "MIT", "Apache-2.0" ]
permissive
bino7/chromium
8d26f84a1b6e38a73d1b97fea6057c634eff68cb
4666a6bb6fdcb1114afecf77bdaa239d9787b752
refs/heads/master
2022-12-22T14:31:53.913081
2016-09-06T10:05:11
2016-09-06T10:05:11
67,410,510
1
3
BSD-3-Clause
2022-12-17T03:08:52
2016-09-05T10:11:59
null
UTF-8
C++
false
false
12,914
cpp
/* * Copyright (C) 2007 Alp Toker <alp@atoker.com> * Copyright (C) 2007 Apple Inc. * * 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/page/PrintContext.h" #include "core/frame/FrameView.h" #include "core/frame/LocalFrame.h" #include "core/layout/LayoutView.h" #include "core/layout/api/LayoutViewItem.h" #include "platform/graphics/GraphicsContext.h" namespace blink { // By shrinking to a width of 75% (1.333f) we will render the correct physical // dimensions in paged media (i.e. cm, pt,). The shrinkage used // to be 80% (1.25f) to match other browsers - they have since moved on. // Wide pages will be scaled down more than this. const float printingMinimumShrinkFactor = 1.333f; // This number determines how small we are willing to reduce the page content // in order to accommodate the widest line. If the page would have to be // reduced smaller to make the widest line fit, we just clip instead (this // behavior matches MacIE and Mozilla, at least). // TODO(rhogan): Decide if this quirk is still required. const float printingMaximumShrinkFactor = 2; PrintContext::PrintContext(LocalFrame* frame) : m_frame(frame) , m_isPrinting(false) , m_linkedDestinationsValid(false) { } PrintContext::~PrintContext() { if (m_isPrinting) end(); } void PrintContext::computePageRects(const FloatRect& printRect, float headerHeight, float footerHeight, float userScaleFactor, float& outPageHeight) { m_pageRects.clear(); outPageHeight = 0; if (!m_frame->document() || !m_frame->view() || m_frame->document()->layoutViewItem().isNull()) return; if (userScaleFactor <= 0) { DLOG(ERROR) << "userScaleFactor has bad value " << userScaleFactor; return; } LayoutViewItem view = m_frame->document()->layoutViewItem(); const IntRect& documentRect = view.documentRect(); FloatSize pageSize = m_frame->resizePageRectsKeepingRatio(FloatSize(printRect.width(), printRect.height()), FloatSize(documentRect.width(), documentRect.height())); float pageWidth = pageSize.width(); float pageHeight = pageSize.height(); outPageHeight = pageHeight; // this is the height of the page adjusted by margins pageHeight -= headerHeight + footerHeight; if (pageHeight <= 0) { DLOG(ERROR) << "pageHeight has bad value " << pageHeight; return; } computePageRectsWithPageSizeInternal(FloatSize(pageWidth / userScaleFactor, pageHeight / userScaleFactor)); } void PrintContext::computePageRectsWithPageSize(const FloatSize& pageSizeInPixels) { m_pageRects.clear(); computePageRectsWithPageSizeInternal(pageSizeInPixels); } void PrintContext::computePageRectsWithPageSizeInternal(const FloatSize& pageSizeInPixels) { if (!m_frame->document() || !m_frame->view() || m_frame->document()->layoutViewItem().isNull()) return; LayoutViewItem view = m_frame->document()->layoutViewItem(); IntRect docRect = view.documentRect(); int pageWidth = pageSizeInPixels.width(); // We scaled with floating point arithmetic and need to ensure results like 13329.99 // are treated as 13330 so that we don't mistakenly assign an extra page for the // stray pixel. int pageHeight = pageSizeInPixels.height() + LayoutUnit::epsilon(); bool isHorizontal = view.style()->isHorizontalWritingMode(); int docLogicalHeight = isHorizontal ? docRect.height() : docRect.width(); int pageLogicalHeight = isHorizontal ? pageHeight : pageWidth; int pageLogicalWidth = isHorizontal ? pageWidth : pageHeight; int inlineDirectionStart; int inlineDirectionEnd; int blockDirectionStart; int blockDirectionEnd; if (isHorizontal) { if (view.style()->isFlippedBlocksWritingMode()) { blockDirectionStart = docRect.maxY(); blockDirectionEnd = docRect.y(); } else { blockDirectionStart = docRect.y(); blockDirectionEnd = docRect.maxY(); } inlineDirectionStart = view.style()->isLeftToRightDirection() ? docRect.x() : docRect.maxX(); inlineDirectionEnd = view.style()->isLeftToRightDirection() ? docRect.maxX() : docRect.x(); } else { if (view.style()->isFlippedBlocksWritingMode()) { blockDirectionStart = docRect.maxX(); blockDirectionEnd = docRect.x(); } else { blockDirectionStart = docRect.x(); blockDirectionEnd = docRect.maxX(); } inlineDirectionStart = view.style()->isLeftToRightDirection() ? docRect.y() : docRect.maxY(); inlineDirectionEnd = view.style()->isLeftToRightDirection() ? docRect.maxY() : docRect.y(); } unsigned pageCount = ceilf((float)docLogicalHeight / pageLogicalHeight); for (unsigned i = 0; i < pageCount; ++i) { int pageLogicalTop = blockDirectionEnd > blockDirectionStart ? blockDirectionStart + i * pageLogicalHeight : blockDirectionStart - (i + 1) * pageLogicalHeight; int pageLogicalLeft = inlineDirectionEnd > inlineDirectionStart ? inlineDirectionStart : inlineDirectionStart - pageLogicalWidth; IntRect pageRect(pageLogicalLeft, pageLogicalTop, pageLogicalWidth, pageLogicalHeight); if (!isHorizontal) pageRect = pageRect.transposedRect(); m_pageRects.append(pageRect); } } void PrintContext::begin(float width, float height) { ASSERT(width > 0); ASSERT(height > 0); // This function can be called multiple times to adjust printing parameters without going back to screen mode. m_isPrinting = true; FloatSize originalPageSize = FloatSize(width, height); FloatSize minLayoutSize = m_frame->resizePageRectsKeepingRatio(originalPageSize, FloatSize(width * printingMinimumShrinkFactor, height * printingMinimumShrinkFactor)); // This changes layout, so callers need to make sure that they don't paint to screen while in printing mode. m_frame->setPrinting(true, minLayoutSize, originalPageSize, printingMaximumShrinkFactor / printingMinimumShrinkFactor); } void PrintContext::end() { ASSERT(m_isPrinting); m_isPrinting = false; m_frame->setPrinting(false, FloatSize(), FloatSize(), 0); m_linkedDestinations.clear(); m_linkedDestinationsValid = false; } static LayoutBoxModelObject* enclosingBoxModelObject(LayoutObject* object) { while (object && !object->isBoxModelObject()) object = object->parent(); if (!object) return nullptr; return toLayoutBoxModelObject(object); } int PrintContext::pageNumberForElement(Element* element, const FloatSize& pageSizeInPixels) { element->document().updateStyleAndLayout(); LocalFrame* frame = element->document().frame(); FloatRect pageRect(FloatPoint(0, 0), pageSizeInPixels); PrintContext printContext(frame); printContext.begin(pageRect.width(), pageRect.height()); LayoutBoxModelObject* box = enclosingBoxModelObject(element->layoutObject()); if (!box) return -1; FloatSize scaledPageSize = pageSizeInPixels; scaledPageSize.scale(frame->view()->contentsSize().width() / pageRect.width()); printContext.computePageRectsWithPageSize(scaledPageSize); int top = box->pixelSnappedOffsetTop(box->offsetParent()); int left = box->pixelSnappedOffsetLeft(box->offsetParent()); size_t pageNumber = 0; for (; pageNumber < printContext.pageCount(); pageNumber++) { const IntRect& page = printContext.pageRect(pageNumber); if (page.x() <= left && left < page.maxX() && page.y() <= top && top < page.maxY()) return pageNumber; } return -1; } void PrintContext::collectLinkedDestinations(Node* node) { for (Node* i = node->firstChild(); i; i = i->nextSibling()) collectLinkedDestinations(i); if (!node->isLink() || !node->isElementNode()) return; const AtomicString& href = toElement(node)->getAttribute(HTMLNames::hrefAttr); if (href.isNull()) return; KURL url = node->document().completeURL(href); if (!url.isValid()) return; if (url.hasFragmentIdentifier() && equalIgnoringFragmentIdentifier(url, node->document().baseURL())) { String name = url.fragmentIdentifier(); if (Element* element = node->document().findAnchor(name)) m_linkedDestinations.set(name, element); } } void PrintContext::outputLinkedDestinations(GraphicsContext& context, const IntRect& pageRect) { if (!m_linkedDestinationsValid) { // Collect anchors in the top-level frame only because our PrintContext // supports only one namespace for the anchors. collectLinkedDestinations(frame()->document()); m_linkedDestinationsValid = true; } for (const auto& entry : m_linkedDestinations) { LayoutObject* layoutObject = entry.value->layoutObject(); if (!layoutObject || !layoutObject->frameView()) continue; IntRect boundingBox = layoutObject->absoluteBoundingBoxRect(); // TODO(bokan): boundingBox looks to be in content coordinates but // convertToRootFrame doesn't apply scroll offsets when converting up to // the root frame. IntPoint point = layoutObject->frameView()->convertToRootFrame(boundingBox.location()); if (!pageRect.contains(point)) continue; point.clampNegativeToZero(); context.setURLDestinationLocation(entry.key, point); } } String PrintContext::pageProperty(LocalFrame* frame, const char* propertyName, int pageNumber) { Document* document = frame->document(); PrintContext printContext(frame); // Any non-zero size is OK here. We don't care about actual layout. We just want to collect // @page rules and figure out what declarations apply on a given page (that may or may not exist). printContext.begin(800, 1000); RefPtr<ComputedStyle> style = document->styleForPage(pageNumber); // Implement formatters for properties we care about. if (!strcmp(propertyName, "margin-left")) { if (style->marginLeft().isAuto()) return String("auto"); return String::number(style->marginLeft().value()); } if (!strcmp(propertyName, "line-height")) return String::number(style->lineHeight().value()); if (!strcmp(propertyName, "font-size")) return String::number(style->getFontDescription().computedPixelSize()); if (!strcmp(propertyName, "font-family")) return style->getFontDescription().family().family().getString(); if (!strcmp(propertyName, "size")) return String::number(style->pageSize().width()) + ' ' + String::number(style->pageSize().height()); return String("pageProperty() unimplemented for: ") + propertyName; } bool PrintContext::isPageBoxVisible(LocalFrame* frame, int pageNumber) { return frame->document()->isPageBoxVisible(pageNumber); } String PrintContext::pageSizeAndMarginsInPixels(LocalFrame* frame, int pageNumber, int width, int height, int marginTop, int marginRight, int marginBottom, int marginLeft) { DoubleSize pageSize(width, height); frame->document()->pageSizeAndMarginsInPixels(pageNumber, pageSize, marginTop, marginRight, marginBottom, marginLeft); return "(" + String::number(floor(pageSize.width())) + ", " + String::number(floor(pageSize.height())) + ") " + String::number(marginTop) + ' ' + String::number(marginRight) + ' ' + String::number(marginBottom) + ' ' + String::number(marginLeft); } int PrintContext::numberOfPages(LocalFrame* frame, const FloatSize& pageSizeInPixels) { frame->document()->updateStyleAndLayout(); FloatRect pageRect(FloatPoint(0, 0), pageSizeInPixels); PrintContext printContext(frame); printContext.begin(pageRect.width(), pageRect.height()); // Account for shrink-to-fit. FloatSize scaledPageSize = pageSizeInPixels; scaledPageSize.scale(frame->view()->contentsSize().width() / pageRect.width()); printContext.computePageRectsWithPageSize(scaledPageSize); return printContext.pageCount(); } DEFINE_TRACE(PrintContext) { visitor->trace(m_frame); visitor->trace(m_linkedDestinations); } } // namespace blink
[ "bino.zh@gmail.com" ]
bino.zh@gmail.com
28fec04d730c445ddfbb16ac5f55d90a7eabd61b
2fecc4cddee8782dfa8d7a8e4c7ab5a6e89dd01c
/t2 q3/c_1.cpp
447511e88ebe8aadb52f2bf5e3ccc2bf33c65da5
[]
no_license
baibolatovads/work
4640deecbae9d0444c0c499439e22bb33a79f7c5
833ec34d7dc39ddef4c7b26cc0c446fc9c1ded7f
refs/heads/master
2020-07-31T17:03:39.246947
2019-12-15T09:38:33
2019-12-15T09:38:33
210,684,631
0
0
null
null
null
null
UTF-8
C++
false
false
205
cpp
#include <iostream> using namespace std; int main(){ string s; getline(cin,s); for(int i = 0; i < s.size(); ++i){ if(s[i] != '\\'){ cout << s[i]; }else{ cout << endl; } } return 0; }
[ "baibolatovads@gmail.com" ]
baibolatovads@gmail.com
78af32310d01f3a3741fd16c6fa79f6fe492bc25
8491055b0dba74ff3e245f61d6596fe4353eab17
/build-helloworld-Desktop_Qt_5_10_0_GCC_64bit-Debug/moc_window2.cpp
fc7f6d9c618b72df419519539ebc935994f2a1d9
[]
no_license
Abiggg/helloword
9e552682cf7cc350671c7614ec87b72629244469
6c28e3a5cc2e509501a38cc6ff092f22ddc471e7
refs/heads/master
2020-03-17T03:51:48.516541
2018-11-15T16:03:51
2018-11-15T16:03:51
133,253,237
1
0
null
null
null
null
UTF-8
C++
false
false
2,610
cpp
/**************************************************************************** ** Meta object code from reading C++ file 'window2.h' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.10.0) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../helloworld/window2.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'window2.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.10.0. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE QT_WARNING_PUSH QT_WARNING_DISABLE_DEPRECATED struct qt_meta_stringdata_StackedDlg_t { QByteArrayData data[1]; char stringdata0[11]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_StackedDlg_t, stringdata0) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_StackedDlg_t qt_meta_stringdata_StackedDlg = { { QT_MOC_LITERAL(0, 0, 10) // "StackedDlg" }, "StackedDlg" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_StackedDlg[] = { // content: 7, // revision 0, // classname 0, 0, // classinfo 0, 0, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount 0 // eod }; void StackedDlg::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { Q_UNUSED(_o); Q_UNUSED(_id); Q_UNUSED(_c); Q_UNUSED(_a); } const QMetaObject StackedDlg::staticMetaObject = { { &QDialog::staticMetaObject, qt_meta_stringdata_StackedDlg.data, qt_meta_data_StackedDlg, qt_static_metacall, nullptr, nullptr} }; const QMetaObject *StackedDlg::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *StackedDlg::qt_metacast(const char *_clname) { if (!_clname) return nullptr; if (!strcmp(_clname, qt_meta_stringdata_StackedDlg.stringdata0)) return static_cast<void*>(this); return QDialog::qt_metacast(_clname); } int StackedDlg::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QDialog::qt_metacall(_c, _id, _a); return _id; } QT_WARNING_POP QT_END_MOC_NAMESPACE
[ "550153292@qq.com" ]
550153292@qq.com
7881f724449ff7a3c85e8a2ab95258bc607aa63b
626a2409bd8c30a59d353166f84654ca2e514305
/collections/StackADT.cpp
13683942df291ba6c443f9ac425d36cc53effdfd
[]
no_license
wyouyou/smartinote
8f93fb68dbe011d0eab3da2b32682b4b4a3d5eac
dae169c80f8d19528dc43de0ebdd9961d9ef3e30
refs/heads/master
2021-08-19T06:34:38.862511
2017-11-25T00:37:33
2017-11-25T00:37:33
111,965,179
0
0
null
2017-11-25T00:32:15
2017-11-25T00:32:14
null
UTF-8
C++
false
false
1,390
cpp
// // StackADT.cpp // smartinote // // Created by Jaye Wang on 10/18/17. // Copyright © 2017 JayeWang. All rights reserved. // #include "StackADT.hpp" /**~*~* Destructor *~**/ template <class T> Stack<T>::~Stack() { StackNode * Curr, next; // Curr start at the top of the stack Curr = top; // Traverse the list deleting each node while (Curr) { next = Curr->next; delete Curr; Curr = next; } } /**~*~* Member function push pushes the argument onto the stack. *~**/ template <class T> bool Stack<T>::push(T item) { StackNode* newN = new StackNode; newN->value = item; if (!newN) return false; // update 2 links, and update the counter newN->next = top; top = newN; count++; return true; } /**~*~* Member function pop pops the value at the top of the stack off, and copies it into the variable passed as an argument. *~**/ template <class T> bool Stack<T>::pop(T &item) { // empty stack case if (isEmpty()) return false; item = top->value; StackNode *deletePtr = top; top = top->next; delete deletePtr; count--; return true; } /**~*~* Member function isEmpty returns true if the stack is empty, or false otherwise. *~**/ template <class T> bool Stack<T>::isEmpty() { return count == 0; }
[ "wang.jaye@yahoo.com" ]
wang.jaye@yahoo.com
b84dc78a7aeb2f6b3ec286a40cb4dd9d862b8c73
9c32ed1719782b466c1c7e388bd99495d3046827
/FourDigitLCD.h
9405296028ce67632490c4006247ee2ae6bd069f
[ "MIT" ]
permissive
jakesjews/ArduinoBreathalyzer
b3fe1aa3f4dbbd79ff93ea582ce8439780f3999e
92cd9b883fcbc47b535c05815da39d16775a4a57
refs/heads/master
2021-01-10T10:29:39.180065
2016-02-28T20:25:36
2016-02-28T20:25:36
52,169,170
0
0
null
null
null
null
UTF-8
C++
false
false
114
h
#include <Arduino.h> class FourDigitLCD { public: FourDigitLCD(); void init(); void display(String str); };
[ "jacobjewell@eflexsystems.com" ]
jacobjewell@eflexsystems.com
6dfde1633cfd568d91a5e319662b0a106f8af4b3
f2ee22679f4015815f567c38089d396971e4c51a
/CAAApplicationFrame.edu/CAAAfrGeoDocument.m/LocalInterfaces/CAAEAfrEditorDocument.h
d38d6a21cda0bae2b1e4fa0c92e54c56f7c27f68
[]
no_license
poborskii/CAADoc_SelectAgent
72f0a162fa7a502d6763df15d65d76554e9268fe
51e0235ef461b5ac1fd710828c29be4bb538c43c
refs/heads/master
2022-12-06T01:19:28.965598
2020-08-31T02:48:11
2020-08-31T02:48:11
291,596,517
0
0
null
null
null
null
UTF-8
C++
false
false
2,864
h
#ifndef CAAEAfrEditorDocument_H #define CAAEAfrEditorDocument_H // COPYRIGHT DASSAULT SYSTEMES 2000 //=========================================================================== // Abstract of the sample: // ---------------------- // // Application using a new document type (CAAGeometry) with its own workshop // and commands. // //=========================================================================== // Abstract of the class: // ---------------------- // // Data Extension of the Late type CAAGeom. // //=========================================================================== // Usage: // ------ // Launch CATIA V5, File/New In the Dialog Box the new document type // appears. // //=========================================================================== // Inheritance: // ------------ // CATBaseUnknown (System Framework) // //=========================================================================== // Main Method: // ------------ // // GetEditor // //=========================================================================== // System framework #include "CATBaseUnknown.h" // Needed to derive from CATBaseUnknown #include "CATEventSubscriber.h" // Needed for the callback // ApplicationFrame framework class CATFrmEditor ; // CATIEditor class CAAEAfrEditorDocument: public CATBaseUnknown { // Used in conjunction with CATImplementClass in the .cpp file CATDeclareClass; public: CAAEAfrEditorDocument(); virtual ~CAAEAfrEditorDocument(); // GetEditor // --------- // Retrieves the editor of the document made active. // // This method is called by the File->New and the File->Open dialog boxes // and when swapping from a document to another. // // // The editor is created the first time that GetEditor is called, and is // kept as // CATFrmEditor * GetEditor(); // SetEditorToNullWhenClosed // -------------------------- // To set to NULL, _Editor when the editor is closed // void SetEditorToNullWhenClosed (CATCallbackEvent iEvent, void *iFrom, CATNotification *iNotification, CATSubscriberData iData, CATCallback iCallBack ); private: // Copy constructor, not implemented // Set as private to prevent from compiler automatic creation as public. CAAEAfrEditorDocument(const CAAEAfrEditorDocument &iObjectToCopy); // Assignment operator, not implemented // Set as private to prevent from compiler automatic creation as public. CAAEAfrEditorDocument & operator = (const CAAEAfrEditorDocument &iObjectToCopy); private: // The value created by GetEditor CATFrmEditor * _pEditor ; }; #endif
[ "poborsk_liu@613.com" ]
poborsk_liu@613.com
6b671b524cf6152b531cfd1692c71900a51b93b8
a8bffa6f4002d1590dab9f7f014ed94e5222e6c1
/BufferedOp/main.cpp
572f31687f8891cb553a992548fd6cf1841d8afa
[]
no_license
kreuzerkrieg/CPPJunk
6305c29bbaaa67633b9ab2fe7c1d4cc45a2228d1
e4d357ce7750bd4ded61b841d8d823ae6432916d
refs/heads/master
2022-02-05T03:29:19.600177
2022-01-26T15:58:45
2022-01-26T15:58:45
1,847,032
0
0
null
2020-03-16T08:10:34
2011-06-04T15:09:36
C++
UTF-8
C++
false
false
164
cpp
#include <iostream> struct foo { std::string bar(int i) { return std::to_string(i); } }; int main() { foo f; std::cout << f.bar(42) << std::endl; return 0; }
[ "kreuzerkrieg@gmail.com" ]
kreuzerkrieg@gmail.com
bbccdf2dc039be25460956ffbea70e0da5a57cb9
6aeccfb60568a360d2d143e0271f0def40747d73
/sandbox/task/libs/task/test/test_spin_condition_notify_one.cpp
9986e1b111d430f14e9bba30eef99775d0d348d4
[ "BSL-1.0" ]
permissive
ttyang/sandbox
1066b324a13813cb1113beca75cdaf518e952276
e1d6fde18ced644bb63e231829b2fe0664e51fac
refs/heads/trunk
2021-01-19T17:17:47.452557
2013-06-07T14:19:55
2013-06-07T14:19:55
13,488,698
1
3
null
2023-03-20T11:52:19
2013-10-11T03:08:51
C++
UTF-8
C++
false
false
4,476
cpp
// Copyright (C) 2007 Anthony Williams // // 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) #include <boost/bind.hpp> #include <boost/thread.hpp> #include <boost/test/unit_test.hpp> #include <boost/task.hpp> #include <libs/task/test/util.ipp> #include "condition_test_common.hpp" namespace tsk = boost::tasks; void do_test_condition_notify_one_wakes_from_wait() { wait_for_flag data; boost::thread thread(boost::bind(&wait_for_flag::wait_without_predicate, boost::ref(data))); { tsk::spin::mutex::scoped_lock lock(data.mutex); data.flag=true; data.cond_var.notify_one(); } thread.join(); BOOST_CHECK(data.woken); } void do_test_condition_notify_one_wakes_from_wait_with_predicate() { wait_for_flag data; boost::thread thread(boost::bind(&wait_for_flag::wait_with_predicate, boost::ref(data))); { tsk::spin::mutex::scoped_lock lock(data.mutex); data.flag=true; data.cond_var.notify_one(); } thread.join(); BOOST_CHECK(data.woken); } void do_test_condition_notify_one_wakes_from_timed_wait() { wait_for_flag data; boost::thread thread(boost::bind(&wait_for_flag::timed_wait_without_predicate, boost::ref(data))); { tsk::spin::mutex::scoped_lock lock(data.mutex); data.flag=true; data.cond_var.notify_one(); } thread.join(); BOOST_CHECK(data.woken); } void do_test_condition_notify_one_wakes_from_timed_wait_with_predicate() { wait_for_flag data; boost::thread thread(boost::bind(&wait_for_flag::timed_wait_with_predicate, boost::ref(data))); { tsk::spin::mutex::scoped_lock lock(data.mutex); data.flag=true; data.cond_var.notify_one(); } thread.join(); BOOST_CHECK(data.woken); } void do_test_condition_notify_one_wakes_from_relative_timed_wait_with_predicate() { wait_for_flag data; boost::thread thread(boost::bind(&wait_for_flag::relative_timed_wait_with_predicate, boost::ref( data))); { tsk::spin::mutex::scoped_lock lock(data.mutex); data.flag=true; data.cond_var.notify_one(); } thread.join(); BOOST_CHECK(data.woken); } namespace { tsk::spin::mutex multiple_wake_mutex; tsk::spin::condition multiple_wake_cond; unsigned multiple_wake_count=0; void wait_for_condvar_and_increase_count() { tsk::spin::mutex::scoped_lock lk(multiple_wake_mutex); multiple_wake_cond.wait(lk); ++multiple_wake_count; } } void do_test_multiple_notify_one_calls_wakes_multiple_threads() { boost::thread thread1(wait_for_condvar_and_increase_count); boost::thread thread2(wait_for_condvar_and_increase_count); boost::this_thread::sleep(boost::posix_time::milliseconds(200)); multiple_wake_cond.notify_one(); boost::thread thread3(wait_for_condvar_and_increase_count); boost::this_thread::sleep(boost::posix_time::milliseconds(200)); multiple_wake_cond.notify_one(); multiple_wake_cond.notify_one(); boost::this_thread::sleep(boost::posix_time::milliseconds(200)); { tsk::spin::mutex::scoped_lock lk(multiple_wake_mutex); BOOST_CHECK(multiple_wake_count==3); } thread1.join(); thread2.join(); thread3.join(); } void test_condition_notify_one() { timed_test(&do_test_condition_notify_one_wakes_from_wait, timeout_seconds, execution_monitor::use_mutex); timed_test(&do_test_condition_notify_one_wakes_from_wait_with_predicate, timeout_seconds, execution_monitor::use_mutex); timed_test(&do_test_condition_notify_one_wakes_from_timed_wait, timeout_seconds, execution_monitor::use_mutex); timed_test(&do_test_condition_notify_one_wakes_from_timed_wait_with_predicate, timeout_seconds, execution_monitor::use_mutex); timed_test(&do_test_condition_notify_one_wakes_from_relative_timed_wait_with_predicate, timeout_seconds, execution_monitor::use_mutex); timed_test(&do_test_multiple_notify_one_calls_wakes_multiple_threads, timeout_seconds, execution_monitor::use_mutex); } boost::unit_test_framework::test_suite* init_unit_test_suite(int, char*[]) { boost::unit_test_framework::test_suite* test = BOOST_TEST_SUITE("Boost.Task: condition test suite"); test->add(BOOST_TEST_CASE(&test_condition_notify_one)); return test; }
[ "oliver.kowalke@gmail.com" ]
oliver.kowalke@gmail.com
6d1ab072327bc485eb398f1cdb20b23c28b2e31e
60e878fc3920b2a22bbcf8f20f2cdfdcc92b1906
/fighter.h
ac8a0808f55191ad6798e2c16ca8748fe59bcbeb
[]
no_license
adaniele87/CIO_funMains
69cc5d53214195a4c1722cc7aac571af83762a75
c77bc3ccc20a569c6515973cde82f1e15ad2923a
refs/heads/master
2021-01-17T15:27:30.989576
2013-11-12T04:23:57
2013-11-12T04:23:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
165
h
#include "object.h" class Fighter : public Object { bool punching; public: Fighter(); Fighter(int,int,int = 1); void getInput(); void draw(); };
[ "andrew_daniele@hotmail.com" ]
andrew_daniele@hotmail.com
540caa209ed345d3c719b4f70abd5a0387fdfd71
9760944086e8dcbc68c3b693b5663ca9dbaed010
/mem_checker/src/track.hh
99059131459836b5516d761592757156426ce985
[]
no_license
Nomyo/memory_checker
32ceebeaece7677d0229e75d83dc8881ae197e90
7873465fb9fc7e1fa85b989ed7cb3a1867ef3c1c
refs/heads/master
2021-01-01T17:59:21.484281
2015-12-20T08:55:46
2015-12-20T08:55:46
98,214,650
6
0
null
null
null
null
UTF-8
C++
false
false
2,882
hh
#ifndef BREAK_HH # define BREAK_HH #include <map> #include <unistd.h> #include <sys/ptrace.h> #include <iostream> #include <elf.h> #include <link.h> #include "tools.hh" #include <string.h> #include <sys/mman.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <capstone/capstone.h> #include <sys/wait.h> #include "alloc_obj.hh" #include <list> #include <asm/unistd.h> #include <sys/reg.h> #include <sys/user.h> class Tracker { public: using pair_name_map = std::pair<std::string, std::map<uintptr_t, unsigned long>>; Tracker(); Tracker(pid_t pid, int state, char *name); ~Tracker(); void print_breaks(); int get_state(); void set_state(int state); void set_pid(pid_t pid); pid_t get_pid(); void print_lib_name(struct link_map *l_map); /* functions that handle load objects and breakpoints */ void update_break(ElfW(Addr) l_addr, ElfW(Off) off, ElfW(Xword) size, char *l_name); void get_shdr(ElfW(Ehdr) *elf_addr, ElfW(Addr) l_addr, char *name); void load_lo(struct link_map *l_map); void update(struct link_map *l_map); int treat_break(struct link_map *l_map, uintptr_t addr, struct user_regs_struct regs); void add_break(uintptr_t addr, std::string l_name); int rem_break(uintptr_t addr, char *l_name, struct user_regs_struct regs); void rem_loadobj(struct link_map *l_map); void init_break(); void wrap_alloc_syscall(unsigned long sysnum, struct user_regs_struct regs); int check_reg(struct user_regs_struct regs); /* wrapper that analyse pid_ registers, print and fill ls_mem_ struct */ void wrap_mmap(struct user_regs_struct regs); void wrap_mprotect(struct user_regs_struct regs); void wrap_munmap(struct user_regs_struct regs); void wrap_mremap(struct user_regs_struct regs); void wrap_brk(struct user_regs_struct regs); void wrap_free(struct user_regs_struct regs); void wrap_malloc_b(struct user_regs_struct regs); void wrap_realloc_b(struct user_regs_struct regs); void wrap_calloc_b(struct user_regs_struct regs); /* funciton in order to check memory */ void un_protect(struct S_mem map, struct user_regs_struct regs); void un_protect_all(struct user_regs_struct regs); void heap_valid(uintptr_t addr, struct user_regs_struct regs); void re_protect(struct S_mem map, struct user_regs_struct regs); void re_all_protect(struct user_regs_struct regs); void is_invalid(uintptr_t addr, struct user_regs_struct regs); void print_ls_mem(); void get_current_inst(uintptr_t addr); void show_leaks(); private: std::map<std::string, std::map<uintptr_t, unsigned long>> mbreak_; pid_t pid_; int p_state_; char *binary_; std::list<S_mem> ls_mem_; uintptr_t brk_ = 0; unsigned long brk_len_ = 0; unsigned long mem_alloc_ = 0; unsigned long nb_free_ = 0; unsigned long nb_alloc_ = 0; }; #endif /* !BREAK_HH */
[ "kiaies_a@epita.fr" ]
kiaies_a@epita.fr
0920bb13659f09d5f6d76a3683a975e5e01366e5
0b74b4859c1242fd0793611e36d5778c1c9ece38
/extern/llvm/tools/clang/include/clang/AST/AST.h
b66b4831542acfe12ac0ee67fb714570526acec0
[ "NCSA", "MIT" ]
permissive
abduld/clreflect
682b98694ec50dfcd65168fdf40e7d04ec44e0e5
76b47c518d9b046382618a5e5863f8fe6163e595
refs/heads/master
2022-07-15T21:02:58.217422
2015-04-07T16:06:07
2015-04-07T16:06:07
35,754,939
0
0
MIT
2020-02-22T09:59:11
2015-05-17T06:36:28
C++
UTF-8
C++
false
false
907
h
//===--- AST.h - "Umbrella" header for AST library --------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the interface to the AST classes. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_AST_AST_H #define LLVM_CLANG_AST_AST_H // This header exports all AST interfaces. #include "clang/AST/ASTContext.h" #include "clang/AST/Decl.h" #include "clang/AST/DeclCXX.h" #include "clang/AST/DeclObjC.h" #include "clang/AST/DeclTemplate.h" #include "clang/AST/Expr.h" #include "clang/AST/ExprObjC.h" #include "clang/AST/Type.h" #include "clang/AST/StmtVisitor.h" #endif
[ "xxuejie@gmail.com" ]
xxuejie@gmail.com
d1556af60e21acc93e2a2e61c7c7a641d8ba152b
629330e0607d78026a99850a8184f3924af60f05
/source/crisscross/md5.h
f1494c6d1a3122278dbb181474715f12cd4a8fd4
[]
no_license
prophile/crisscross
682092c8e87e4b948f934cd62f29b10cca000de6
1882aff64193627b58258861fb5b240e643254c1
refs/heads/master
2016-09-10T00:13:50.150868
2009-06-19T21:42:22
2009-06-19T22:30:21
108,875
1
1
null
null
null
null
UTF-8
C++
false
false
3,386
h
/* * CrissCross * A multi-purpose cross-platform library. * * A product of Uplink Laboratories. * * (c) 2006-2009 Steven Noonan. * Licensed under the New BSD License. * */ #ifndef __included_cc_md5_h #define __included_cc_md5_h #ifdef ENABLE_HASHES #ifdef ENABLE_MD5 #define MD5_DIGEST_LENGTH 16 /* MD5 context. */ /* @cond */ typedef struct { cc_uint32_t state[4]; /* state (ABCD) */ cc_uint32_t count[2]; /* number of bits, modulo 2^64 (lsb first) */ union { cc_uint8_t buf8[64]; /* undigested input */ cc_uint32_t buf32[16]; /* realigned input */ } buf_un; } cc_md5_ctx; /* @endcond */ namespace CrissCross { namespace Crypto { /*! \brief An MD5 hash generator. */ /*! * In recent years, MD5 hashes have waned in popularity because researchers * have found that collisions for MD5 are easy to generate. However, this * sort of attack can be rendered useless when a salt is added to the * input dataset. * * \warning Because MD5 is known to have weaknesses, use at your own risk! * \sa Hash MD2Hash MD4Hash */ class MD5Hash { private: mutable char *m_hashString; unsigned char *m_hash; cc_md5_ctx m_state; public: /*! \brief The default constructor. */ MD5Hash(); /*! \brief The destructor. */ ~MD5Hash(); /*! \brief Runs an MD5 hash on the data provided. */ /*! * \param _data The data to hash. The buffer does not need to be null * terminated. * \param _length The data length in bytes. * \return Zero on success, nonzero on failure. */ int Process(const void *_data, size_t _length); /*! \brief Runs a hash on the file provided. */ /*! * \param _reader The pre-opened CoreIOReader to run the hash on. * \return Zero on success, nonzero on failure. */ int Process(CrissCross::IO::CoreIOReader *_reader); /*! \brief Processes a piece of the dataset. */ /*! * This function will process only a segment of a larger dataset. It is designed * to be called multiple times before an eventual Finalize() call. * \param _data The data segment to hash. * \param _length The length of the data segment in bytes. */ int ProcessBlock(const void *_data, size_t _length); /*! \brief Finalizes the ProcessBlock() calls and generates the final hash value. */ void Finalize(); /*! \brief Resets the internal MD5 context and hash buffer. */ void Reset(); /*! \brief Converts the internal hash data into an hex string, a human readable format. */ /*! * The memory location returned by this function is freed when the class * is destructed. */ const char *ToString() const; /*! \brief Equality operator. */ /*! * Compares two instances of MD5Hash to see if the hashes are equal. * \param _other The other instance of MD5Hash to compare to. */ bool operator==(const MD5Hash &_other) const; /*! \brief Inequality operator. */ /*! * Compares two instances of MD5Hash to see if the hashes are not equal. * \param _other The other instance of MD5Hash to compare to. */ inline bool operator!=(const MD5Hash &_other) const { return !(*this == _other); }; }; } } #endif #endif #endif
[ "steven@uplinklabs.net" ]
steven@uplinklabs.net
5284307c5389c4a1c803e9e8d9d15140e72babe0
931a8f1634feb32916cf20ac6cd28a3ee2830ba0
/Native/System/Preferences/Keyboard/mainwindow.h
a2116532c5da704ef1a536fefa1fe4c246b7624a
[]
no_license
PyroOS/Pyro
2c4583bff246f80307fc722515c5e90668c00542
ea709dc1f706c4dfc182d959df14696d604572f8
refs/heads/master
2021-01-10T19:47:17.787899
2012-04-15T12:20:14
2012-04-15T12:20:14
4,031,632
6
1
null
null
null
null
UTF-8
C++
false
false
1,822
h
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <gui/window.h> #include <gui/layoutview.h> #include <gui/tabview.h> #include <gui/frameview.h> #include <gui/checkbox.h> #include <gui/listview.h> #include <gui/textview.h> #include <gui/stringview.h> #include <gui/slider.h> #include <gui/button.h> #include <gui/imagebutton.h> #include <gui/requesters.h> #include <util/application.h> #include <util/message.h> #include <util/resources.h> #include <storage/directory.h> #include <storage/nodemonitor.h> #include <appserver/keymap.h> using namespace os; #include <util/locale.h> #include <util/settings.h> #include <storage/file.h> #include <iostream> #include <sys/stat.h> class LanguageInfo { public: LanguageInfo( char *s ) { char bfr[256], *b; uint i, j; for( j = 0; j < 3 && *s; j++ ) { for( b = bfr, i = 0; i < sizeof( bfr ) && *s && *s != '\t'; i++ ) *b++ = *s++; *b = 0; for( ; *s == '\t' ; s++ ); m_cInfo[j] = bfr; } m_bValid = false; if( m_cInfo[0][0] != '#' && GetName() != "" && GetAlias() != "" && GetCode() != "" ) { m_bValid = true; } } bool IsValid() { return m_bValid; } os::String& GetName() { return m_cInfo[0]; } os::String& GetAlias() { return m_cInfo[1]; } os::String& GetCode() { return m_cInfo[2]; } private: os::String m_cInfo[3]; bool m_bValid; }; class MainWindow : public os::Window { public: MainWindow(); void ShowData(); void SetCurrent(); void LoadLanguages(); void Apply(); void Undo(); void Default(); void HandleMessage( os::Message* ); private: void LoadDatabase(); bool OkToQuit(); #include "mainwindowLayout.h" NodeMonitor* m_pcMonitor; os::String cPrimaryLanguage; os::String cKeymap; int iDelay, iRepeat, iDelay2, iRepeat2; int iOrigRow, iOrigRow2; std::vector<LanguageInfo> m_cDatabase; }; #endif
[ "mail@pyro-os.org" ]
mail@pyro-os.org
0fb381967718cdcc89340b6743cd6b379c29e053
3495e626ced5ed878e6d2b28307a2214ad30feb3
/ProjectManagement/projectlistwidget.h
817e35c3a76485641d4992289007a17ef8dfd1bd
[]
no_license
zcharli/carleton-student-project-partner-finder
240c51641ad5e6e66bc00c9e89f7952a1a511538
9567dafaec3ef7b2bd4e9208ae223cbc268b06dc
refs/heads/master
2021-01-10T01:42:33.265387
2016-02-15T07:25:47
2016-02-15T07:25:47
48,532,910
1
0
null
null
null
null
UTF-8
C++
false
false
1,488
h
#ifndef PROJECTLISTWIDGET_H #define PROJECTLISTWIDGET_H #include "sidebarwidget.h" #include "projectcellwidget.h" // Subsystem dependencies #include "DataAccessLayer/project.h" #include "abstractprojectview.h" #include <QScrollArea> #include <QLabel> #include <QPushButton> #include <QFormLayout> #include <QHBoxLayout> #include <QString> #include <QVector> #include "abstractprojectview.h" enum ListType { discoverProjectsList = 0, myProjectsList, noList }; class ProjectListWidget : public AbstractProjectView { Q_OBJECT QScrollArea scrollArea; public: explicit ProjectListWidget(QWidget *parent = 0); ~ProjectListWidget(); int listSize; ListType listType; /*! * @param: none * @desc: gets the list of projects from the database * @return: void */ void refreshList(); /*! * @param: none * @desc: adds all of the content of the projects * to the widget * @return: void */ void displayList(); void viewWillAppear(); void viewWillDisappear(); void cleanUpList(); void setUpList(); signals: void userToViewProject(); private: /* * List of projects */ QVector<Project*> projectList; ProjectCellWidget **projectCells; QWidget *items; signals: public slots: void handleUserContextSwitch(DetailViewType); void viewProjectSelected(int index); }; #endif // PROJECTLISTWIDGET_H
[ "dabeluchindubisi@yahoo.com" ]
dabeluchindubisi@yahoo.com
e4895e78e5f2611975897f2a169a08ebf85b9335
91a882547e393d4c4946a6c2c99186b5f72122dd
/Source/XPSP1/NT/windows/advcore/gdiplus/engine/imaging/api/decodedimg.cpp
5ebcc1547bcde7a9ff3dcf9f9ae34afd6968184e
[]
no_license
IAmAnubhavSaini/cryptoAlgorithm-nt5src
94f9b46f101b983954ac6e453d0cf8d02aa76fc7
d9e1cdeec650b9d6d3ce63f9f0abe50dabfaf9e2
refs/heads/master
2023-09-02T10:14:14.795579
2021-11-20T13:47:06
2021-11-20T13:47:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
28,727
cpp
/**************************************************************************\ * * Copyright (c) 1999 Microsoft Corporation * * Module Name: * * decodedimg.cpp * * Abstract: * * Implementation of GpDecodedImage class * * Revision History: * * 05/26/1999 davidx * Created it. * \**************************************************************************/ #include "precomp.hpp" /**************************************************************************\ * * Function Description: * * Create a GpDecodedImage object from a stream or a file * * Arguments: * * stream/filename - Specifies the input data stream or filename * image - Returns a pointer to newly created image object * * Return Value: * * Status code * \**************************************************************************/ HRESULT GpDecodedImage::CreateFromStream( IStream* stream, GpDecodedImage** image ) { if ( image == NULL ) { return E_INVALIDARG; } GpDecodedImage* pImage = new GpDecodedImage(stream); if ( pImage == NULL ) { return E_OUTOFMEMORY; } else if ( pImage->IsValid() ) { *image = pImage; return S_OK; } else { delete pImage; return E_FAIL; } }// CreateFromStream() HRESULT GpDecodedImage::CreateFromFile( const WCHAR* filename, GpDecodedImage** image ) { HRESULT hr; IStream* stream; hr = CreateStreamOnFileForRead(filename, &stream); if (SUCCEEDED(hr)) { hr = CreateFromStream(stream, image); stream->Release(); } return hr; } /**************************************************************************\ * * Function Description: * * Construct a GpDecodedImage object from an input stream * * Arguments: * * stream - Pointer to the input stream * * Return Value: * * NONE * \**************************************************************************/ GpDecodedImage::GpDecodedImage( IStream* stream ) { // Hold a reference to the input stream inputStream = stream; inputStream->AddRef(); // Initialize other fields to their default values decoder = NULL; decodeCache = NULL; cacheFlags = IMGFLAG_READONLY; gotProps = FALSE; propset = NULL; // Set override resolution to zero (i.e., no override) xdpiOverride = 0.0; ydpiOverride = 0.0; SetValid ( GetImageDecoder() == S_OK ); } /**************************************************************************\ * * Function Description: * * GpDecodedImage destructor * * Arguments: * * NONE * * Return Value: * * NONE * \**************************************************************************/ GpDecodedImage::~GpDecodedImage() { if (decodeCache) decodeCache->Release(); if (decoder) { decoder->TerminateDecoder(); decoder->Release(); } if (inputStream) inputStream->Release(); if (propset) propset->Release(); SetValid(FALSE); // so we don't use a deleted object } /**************************************************************************\ * * Function Description: * * Get the device-independent physical dimension of the image * in unit of 0.01mm * * Arguments: * * size - Buffer for returning physical dimension information * * Return Value: * * Status code * \**************************************************************************/ HRESULT GpDecodedImage::GetPhysicalDimension( OUT SIZE* size ) { // Query basic image info ImageInfo imageinfo; HRESULT hr; hr = InternalGetImageInfo(&imageinfo); if (SUCCEEDED(hr)) { size->cx = Pixel2HiMetric(imageinfo.Width, imageinfo.Xdpi); size->cy = Pixel2HiMetric(imageinfo.Height, imageinfo.Ydpi); } return hr; } /**************************************************************************\ * * Function Description: * * Get basic information about the decoded image object * * Arguments: * * imageInfo - Buffer for returning basic image info * * Return Value: * * Status code * \**************************************************************************/ HRESULT GpDecodedImage::GetImageInfo( OUT ImageInfo* imageInfo ) { // Query basic image info HRESULT hr; hr = InternalGetImageInfo(imageInfo); if (SUCCEEDED(hr)) { // Merge in our own image cache hints GpLock lock(&objectLock); if (lock.LockFailed()) hr = IMGERR_OBJECTBUSY; else imageInfo->Flags = (imageInfo->Flags & 0xffff) | cacheFlags; } return hr; } /**************************************************************************\ * * Function Description: * * Set image flags * * Arguments: * * flags - New image flags * * Return Value: * * Status code * \**************************************************************************/ HRESULT GpDecodedImage::SetImageFlags( IN UINT flags ) { // Only the top half of the image flag is settable. if (flags & 0xffff) return E_INVALIDARG; // Lock the image object GpLock lock(&objectLock); if (lock.LockFailed()) return IMGERR_OBJECTBUSY; // If image caching is being turn off // then blow away any cache we may current have cacheFlags = flags; if (!(flags & IMGFLAG_CACHING) && decodeCache) { decodeCache->Release(); decodeCache = NULL; } return S_OK; } /**************************************************************************\ * * Function Description: * * Display the image in a GDI device context * * Arguments: * * hdc - Specifies the destination device context * dstRect - Specifies the destination rectangle * srcRect - Specifies the source rectangle * NULL means the entire image * * Return Value: * * Status code * \**************************************************************************/ HRESULT GpDecodedImage::Draw( IN HDC hdc, IN const RECT* dstRect, IN OPTIONAL const RECT* srcRect ) { // Lock the current image object GpLock lock(&objectLock); if (lock.LockFailed()) return IMGERR_OBJECTBUSY; // !!! TODO // Eventually we'll create an IImageSink object // on top of the destination hdc and then ask // decoder to push image data into that sink. // For now, always decode into a memory bitmap. HRESULT hr; if (decodeCache == NULL) { // Allocate a new GpMemoryBitmap object GpMemoryBitmap* bmp = new GpMemoryBitmap(); if (bmp == NULL) return E_OUTOFMEMORY; // Ask the decoder to push data into the memory bitmap hr = InternalPushIntoSink(bmp); if (SUCCEEDED(hr)) hr = bmp->QueryInterface(IID_IImage, (VOID**) &decodeCache); bmp->Release(); if (FAILED(hr)) return hr; } // Ask the memory bitmap to draw itself hr = decodeCache->Draw(hdc, dstRect, srcRect); // Blow away the memory bitmap cache if needed if ((cacheFlags & IMGFLAG_CACHING) == 0) { decodeCache->Release(); decodeCache = NULL; } return hr; } /**************************************************************************\ * * Function Description: * * Push image data into an IImageSink * * Arguments: * * sink - The sink for receiving image data * * Return Value: * * Status code * \**************************************************************************/ HRESULT GpDecodedImage::PushIntoSink( IN IImageSink* sink ) { // Lock the current image object GpLock lock(&objectLock); if (lock.LockFailed()) return IMGERR_OBJECTBUSY; return InternalPushIntoSink(sink); } HRESULT GpDecodedImage::InternalPushIntoSink( IImageSink* sink ) { // Make sure we have a decoder object HRESULT hr = GetImageDecoder(); if (FAILED(hr)) return hr; // Start decoding hr = decoder->BeginDecode(sink, propset); if (FAILED(hr)) return hr; // Decode the source image while ((hr = decoder->Decode()) == E_PENDING) Sleep(0); // Stop decoding return decoder->EndDecode(hr); } /**************************************************************************\ * * Function Description: * * Ask the decoder if it can do the requested operation (color key output, * channel seperation for now) * * Arguments: * * Guid - Guid for request the operation (DECODER_TRANSCOLOR, * DECODER_OUTPUTCHANNEL) * * Return Value: * * Status code * * Revision History: * * 11/22/1999 minliu * Created it. * \**************************************************************************/ HRESULT GpDecodedImage::QueryDecoderParam( IN GUID Guid ) { // Make sure we have a decoder object HRESULT hResult = GetImageDecoder(); if ( FAILED(hResult) ) { return hResult; } // Query decoder capability for the real codec decoder hResult = decoder->QueryDecoderParam(Guid); return hResult; }// QueryDecoderParam() /**************************************************************************\ * * Function Description: * * Tell the decoder how to output decoded image data (color key output, * channel seperation for now) * * Arguments: * * Guid - Guid for request the operation (DECODER_TRANSCOLOR, * DECODER_OUTPUTCHANNEL) * Length - Length of the input parameters * Value - Value to set the decode parameter * * Return Value: * * Status code * * Revision History: * * 11/22/1999 minliu * Created it. * \**************************************************************************/ HRESULT GpDecodedImage::SetDecoderParam( IN GUID Guid, IN UINT Length, IN PVOID Value ) { // Make sure we have a decoder object HRESULT hResult = GetImageDecoder(); if ( FAILED(hResult) ) { return hResult; } // Set decoder parameters for the real codec decoder hResult = decoder->SetDecoderParam(Guid, Length, Value); return hResult; }// SetDecoderParam() HRESULT GpDecodedImage::GetPropertyCount( OUT UINT* numOfProperty ) { // Make sure we have a decoder object HRESULT hResult = GetImageDecoder(); if ( FAILED(hResult) ) { return hResult; } // Get property item count from the real codec decoder hResult = decoder->GetPropertyCount(numOfProperty); return hResult; }// GetPropertyItemCount() HRESULT GpDecodedImage::GetPropertyIdList( IN UINT numOfProperty, IN OUT PROPID* list ) { // Make sure we have a decoder object HRESULT hResult = GetImageDecoder(); if ( FAILED(hResult) ) { return hResult; } // Get property item list from the real codec decoder hResult = decoder->GetPropertyIdList(numOfProperty, list); return hResult; }// GetPropertyIdList() HRESULT GpDecodedImage::GetPropertyItemSize( IN PROPID propId, OUT UINT* size ) { // Make sure we have a decoder object HRESULT hResult = GetImageDecoder(); if ( FAILED(hResult) ) { return hResult; } // Get property item size from the real codec decoder hResult = decoder->GetPropertyItemSize(propId, size); return hResult; }// GetPropertyItemSize() HRESULT GpDecodedImage::GetPropertyItem( IN PROPID propId, IN UINT propSize, IN OUT PropertyItem* buffer ) { // Make sure we have a decoder object HRESULT hResult = GetImageDecoder(); if ( FAILED(hResult) ) { return hResult; } // Get property item from the real codec decoder hResult = decoder->GetPropertyItem(propId, propSize, buffer); return hResult; }// GetPropertyItem() HRESULT GpDecodedImage::GetPropertySize( OUT UINT* totalBufferSize, OUT UINT* numProperties ) { // Make sure we have a decoder object HRESULT hResult = GetImageDecoder(); if ( FAILED(hResult) ) { return hResult; } // Get property size from the real codec decoder hResult = decoder->GetPropertySize(totalBufferSize, numProperties); return hResult; }// GetPropertySize() HRESULT GpDecodedImage::GetAllPropertyItems( IN UINT totalBufferSize, IN UINT numProperties, IN OUT PropertyItem* allItems ) { // Make sure we have a decoder object HRESULT hResult = GetImageDecoder(); if ( FAILED(hResult) ) { return hResult; } // Get all property items from the real codec decoder hResult = decoder->GetAllPropertyItems(totalBufferSize, numProperties, allItems); return hResult; }// GetAllPropertyItems() HRESULT GpDecodedImage::RemovePropertyItem( IN PROPID propId ) { // Make sure we have a decoder object HRESULT hResult = GetImageDecoder(); if ( FAILED(hResult) ) { return hResult; } // Remove this property item from the list hResult = decoder->RemovePropertyItem(propId); return hResult; }// RemovePropertyItem() HRESULT GpDecodedImage::SetPropertyItem( IN PropertyItem item ) { // Make sure we have a decoder object HRESULT hResult = GetImageDecoder(); if ( FAILED(hResult) ) { return hResult; } // Set this property item in the list hResult = decoder->SetPropertyItem(item); return hResult; }// SetPropertyItem() /**************************************************************************\ * * Function Description: * * Ask the decoder for basic image info * * Arguments: * * imageinfo - Pointer to buffer for receiving image info * * Return Value: * * Status code * \**************************************************************************/ HRESULT GpDecodedImage::InternalGetImageInfo( ImageInfo* imageInfo ) { // Lock the current image object HRESULT hr; GpLock lock(&objectLock); if (lock.LockFailed()) hr = IMGERR_OBJECTBUSY; else { // Make sure we have a decoder object hr = GetImageDecoder(); if (SUCCEEDED(hr)) hr = decoder->GetImageInfo(imageInfo); if ((xdpiOverride > 0.0) && (ydpiOverride > 0.0)) { imageInfo->Xdpi = static_cast<double>(xdpiOverride); imageInfo->Ydpi = static_cast<double>(ydpiOverride); } } return hr; } /**************************************************************************\ * * Function Description: * * Ask the decoder for total number of frames in the image * * Arguments: * * dimensionID - Dimension ID (PAGE, RESOLUTION, TIME) the caller wants to * get the total number of frame for * count - Total number of frame * * Return Value: * * Status code * * Revision History: * * 11/19/1999 minliu * Created it. * \**************************************************************************/ HRESULT GpDecodedImage::GetFrameCount( IN const GUID* dimensionID, OUT UINT* count ) { // Lock the current image object HRESULT hResult; GpLock lock(&objectLock); if ( lock.LockFailed() ) { hResult = IMGERR_OBJECTBUSY; } else { // Make sure we have a decoder object hResult = GetImageDecoder(); if ( SUCCEEDED(hResult) ) { // Get the frame count from the decoder hResult = decoder->GetFrameCount(dimensionID, count); } } return hResult; }// GetFrameCount() /**************************************************************************\ * * Function Description: * * Get the total number of dimensions the image supports * * Arguments: * * count -- number of dimensions this image format supports * * Return Value: * * Status code * \**************************************************************************/ STDMETHODIMP GpDecodedImage::GetFrameDimensionsCount( UINT* count ) { // Lock the current image object HRESULT hResult; GpLock lock(&objectLock); if ( lock.LockFailed() ) { hResult = IMGERR_OBJECTBUSY; } else { // Make sure we have a decoder object hResult = GetImageDecoder(); if ( SUCCEEDED(hResult) ) { // Get the frame dimension info from the deocder hResult = decoder->GetFrameDimensionsCount(count); } } return hResult; }// GetFrameDimensionsCount() /**************************************************************************\ * * Function Description: * * Get an ID list of dimensions the image supports * * Arguments: * * dimensionIDs---Memory buffer to hold the result ID list * count -- number of dimensions this image format supports * * Return Value: * * Status code * \**************************************************************************/ STDMETHODIMP GpDecodedImage::GetFrameDimensionsList( GUID* dimensionIDs, UINT count ) { // Lock the current image object HRESULT hResult; GpLock lock(&objectLock); if ( lock.LockFailed() ) { hResult = IMGERR_OBJECTBUSY; } else { // Make sure we have a decoder object hResult = GetImageDecoder(); if ( SUCCEEDED(hResult) ) { // Get the frame dimension info from the deocder hResult = decoder->GetFrameDimensionsList(dimensionIDs, count); } } return hResult; }// GetFrameDimensionsList() /**************************************************************************\ * * Function Description: * * Select the active frame in the bitmap image * * Arguments: * * dimensionID - Dimension ID (PAGE, RESOLUTION, TIME) of where the caller * wants to set the active frame * frameIndex - Index number of the frame to be selected * * Return Value: * * Status code * * Revision History: * * 11/19/1999 minliu * Created it. * \**************************************************************************/ HRESULT GpDecodedImage::SelectActiveFrame( IN const GUID* dimensionID, IN UINT frameIndex ) { // Lock the current image object HRESULT hResult; GpLock lock(&objectLock); if ( lock.LockFailed() ) { hResult = IMGERR_OBJECTBUSY; } else { // Make sure we have a decoder object hResult = GetImageDecoder(); if ( SUCCEEDED(hResult) ) { // Set the active frame in the decoder hResult = decoder->SelectActiveFrame(dimensionID, frameIndex); } } return hResult; }// SelectActiveFrame() /**************************************************************************\ * * Function Description: * * Make sure we have a decoder object associated with the image * * Arguments: * * NONE * * Return Value: * * Status code * * Note: * * We assume the caller has already locked the current image object. * \**************************************************************************/ HRESULT GpDecodedImage::GetImageDecoder() { ASSERT(inputStream != NULL); if (decoder != NULL) return S_OK; // Create and initialize the decoder object return CreateDecoderForStream(inputStream, &decoder, DECODERINIT_NONE); } /**************************************************************************\ * * Function Description: * * Get a thumbnail representation for the image object * * Arguments: * * thumbWidth, thumbHeight - Specifies the desired thumbnail size in pixels * thumbImage - Return a pointer to the thumbnail image * The caller should Release it after using it. * * Return Value: * * Status code * \**************************************************************************/ HRESULT GpDecodedImage::GetThumbnail( IN OPTIONAL UINT thumbWidth, IN OPTIONAL UINT thumbHeight, OUT IImage** thumbImage ) { if (thumbWidth && !thumbHeight || !thumbWidth && thumbHeight) { return E_INVALIDARG; } // Ask the decoder for thumbnail image. // If one is returned, check if the size matches the requested size. // match: just return the thumbnail returned by the decoder // mismatch: scale the thumbnail returned by the decoder to the desired size HRESULT hr; IImage* img = NULL; { GpLock lock(&objectLock); if (lock.LockFailed()) return IMGERR_OBJECTBUSY; hr = GetImageDecoder(); if (FAILED(hr)) return hr; hr = decoder->GetThumbnail(thumbWidth, thumbHeight, &img); if (SUCCEEDED(hr)) { ImageInfo imginfo; hr = img->GetImageInfo(&imginfo); if (SUCCEEDED(hr) && imginfo.Width == thumbWidth || thumbWidth == 0 && imginfo.Height == thumbHeight || thumbHeight == 0) { *thumbImage = img; return S_OK; } } else img = NULL; } if (thumbWidth == 0 && thumbHeight == 0) thumbWidth = thumbHeight = DEFAULT_THUMBNAIL_SIZE; // Otherwise, generate the thumbnail ourselves using the built-in scaler // or scale the thumbnail returned by the decoder to the right size GpMemoryBitmap* bmp; hr = GpMemoryBitmap::CreateFromImage( img ? img : this, thumbWidth, thumbHeight, PIXFMT_DONTCARE, INTERP_AVERAGING, &bmp); if (SUCCEEDED(hr)) { hr = bmp->QueryInterface(IID_IImage, (VOID**) thumbImage); bmp->Release(); } if (img) img->Release(); return hr; } /**************************************************************************\ * * Function Description: * * Set the image resolution. Overrides the native resolution of the image. * * Arguments: * * Xdpi, Ydpi - new resolution * * Return Value: * * Status code * \**************************************************************************/ HRESULT GpDecodedImage::SetResolution( IN REAL Xdpi, IN REAL Ydpi ) { HRESULT hr = S_OK; if ((Xdpi > 0.0) && (Ydpi > 0.0)) { xdpiOverride = Xdpi; ydpiOverride = Ydpi; } else { hr = E_INVALIDARG; } return hr; } /**************************************************************************\ * * Function Description: * * Get the encoder parameter list size from an encoder object specified by * input clsid * * Arguments: * * clsid - Specifies the encoder class ID * size--- The size of the encoder parameter list * * Return Value: * * Status code * * Revision History: * * 03/22/2000 minliu * Created it. * \**************************************************************************/ HRESULT GpDecodedImage::GetEncoderParameterListSize( IN CLSID* clsidEncoder, OUT UINT* size ) { return CodecGetEncoderParameterListSize(clsidEncoder, size); }// GetEncoderParameterListSize() /**************************************************************************\ * * Function Description: * * Get the encoder parameter list from an encoder object specified by * input clsid * * Arguments: * * clsid --- Specifies the encoder class ID * size----- The size of the encoder parameter list * pBuffer-- Buffer for storing the list * * Return Value: * * Status code * * Revision History: * * 03/22/2000 minliu * Created it. * \**************************************************************************/ HRESULT GpDecodedImage::GetEncoderParameterList( IN CLSID* clsidEncoder, IN UINT size, OUT EncoderParameters* pBuffer ) { return CodecGetEncoderParameterList(clsidEncoder, size, pBuffer); }// GetEncoderParameterList() /**************************************************************************\ * * Function Description: * * Save the bitmap image to the specified stream. * * Arguments: * * stream ------------ Target stream * clsidEncoder ------ Specifies the CLSID of the encoder to use * encoderParameters - Optional parameters to pass to the encoder before * starting encoding * * Return Value: * * Status code * * Revision History: * * 03/22/2000 minliu * Created it. * \**************************************************************************/ HRESULT GpDecodedImage::SaveToStream( IN IStream* stream, IN CLSID* clsidEncoder, IN EncoderParameters* encoderParams, OUT IImageEncoder** ppEncoderPtr ) { if ( ppEncoderPtr == NULL ) { WARNING(("GpDecodedImage::SaveToStream---Invalid input arg")); return E_INVALIDARG; } // Get an image encoder. IImageEncoder* pEncoder = NULL; HRESULT hResult = CreateEncoderToStream(clsidEncoder, stream, &pEncoder); if ( SUCCEEDED(hResult) ) { *ppEncoderPtr = pEncoder; // Pass encode parameters to the encoder. // MUST do this before getting the sink interface. if ( encoderParams != NULL ) { hResult = pEncoder->SetEncoderParameters(encoderParams); } if ( (hResult == S_OK) || (hResult == E_NOTIMPL) ) { // Note: if the codec doesn't support SetEncoderparameters(), it is // still fine to save the image // Get an image sink from the encoder. IImageSink* encodeSink = NULL; hResult = pEncoder->GetEncodeSink(&encodeSink); if ( SUCCEEDED(hResult) ) { // Push bitmap into the encoder sink. hResult = this->PushIntoSink(encodeSink); encodeSink->Release(); } } } return hResult; }// SaveToStream() /**************************************************************************\ * * Function Description: * * Save the bitmap image to the specified file. * * Arguments: * * filename ----- Target filename * clsidEncoder ----- Specifies the CLSID of the encoder to use * encoderParameters - Optional parameters to pass to the encoder before * starting encoding * * Return Value: * * Status code * * Revision History: * * 03/06/2000 minliu * Created it. * \**************************************************************************/ HRESULT GpDecodedImage::SaveToFile( IN const WCHAR* filename, IN CLSID* clsidEncoder, IN EncoderParameters* encoderParams, OUT IImageEncoder** ppEncoderPtr ) { IStream* stream; HRESULT hResult = CreateStreamOnFileForWrite(filename, &stream); if ( SUCCEEDED(hResult) ) { hResult = SaveToStream(stream, clsidEncoder, encoderParams, ppEncoderPtr); stream->Release(); } return hResult; }// SaveToFile() /**************************************************************************\ * * Function Description: * * Append the bitmap object to current encoder object * * Arguments: * * encoderParameters - Optional parameters to pass to the encoder before * starting encoding * * Return Value: * * Status code * * Revision History: * * 04/21/2000 minliu * Created it. * \**************************************************************************/ HRESULT GpDecodedImage::SaveAppend( IN const EncoderParameters* encoderParams, IN IImageEncoder* destEncoderPtr ) { // The dest encoder pointer can't be NULL. Otherwise, it is a failure if ( destEncoderPtr == NULL ) { WARNING(("GpDecodedImage::SaveAppend---Called without an encoder")); return E_FAIL; } HRESULT hResult = S_OK; // Pass encode parameters to the encoder. // MUST do this before getting the sink interface. if ( encoderParams != NULL ) { hResult = destEncoderPtr->SetEncoderParameters(encoderParams); } if ( (hResult == S_OK) || (hResult == E_NOTIMPL) ) { // Note: if the codec doesn't support SetEncoderparameters(), it is // still fine to save the image // Get an image sink from the encoder. IImageSink* encodeSink = NULL; hResult = destEncoderPtr->GetEncodeSink(&encodeSink); if ( SUCCEEDED(hResult) ) { // Push bitmap into the encoder sink. hResult = this->PushIntoSink(encodeSink); encodeSink->Release(); } } return hResult; }// SaveAppend()
[ "support@cryptoalgo.cf" ]
support@cryptoalgo.cf
13eda1e0cd13abc037734ef314b32a7d8418a3c3
b28305dab0be0e03765c62b97bcd7f49a4f8073d
/chrome/browser/rlz/chrome_rlz_tracker_delegate.h
f1774e773219496eb02e5d286d709d2520ba8409
[ "BSD-3-Clause" ]
permissive
svarvel/browser-android-tabs
9e5e27e0a6e302a12fe784ca06123e5ce090ced5
bd198b4c7a1aca2f3e91f33005d881f42a8d0c3f
refs/heads/base-72.0.3626.105
2020-04-24T12:16:31.442851
2019-08-02T19:15:36
2019-08-02T19:15:36
171,950,555
1
2
NOASSERTION
2019-08-02T19:15:37
2019-02-21T21:47:44
null
UTF-8
C++
false
false
2,673
h
// Copyright 2015 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. #ifndef CHROME_BROWSER_RLZ_CHROME_RLZ_TRACKER_DELEGATE_H_ #define CHROME_BROWSER_RLZ_CHROME_RLZ_TRACKER_DELEGATE_H_ #include "base/callback.h" #include "base/macros.h" #include "components/omnibox/browser/omnibox_event_global_tracker.h" #include "components/rlz/rlz_tracker_delegate.h" #include "content/public/browser/notification_observer.h" #include "content/public/browser/notification_registrar.h" class Profile; namespace user_prefs { class PrefRegistrySyncable; } // ChromeRLZTrackerDelegate implements RLZTrackerDelegate abstract interface // and provides access to Chrome features. class ChromeRLZTrackerDelegate : public rlz::RLZTrackerDelegate, public content::NotificationObserver { public: ChromeRLZTrackerDelegate(); ~ChromeRLZTrackerDelegate() override; static void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry); static bool IsGoogleDefaultSearch(Profile* profile); static bool IsGoogleHomepage(Profile* profile); static bool IsGoogleInStartpages(Profile* profile); private: // RLZTrackerDelegate implementation. void Cleanup() override; bool IsOnUIThread() override; scoped_refptr<network::SharedURLLoaderFactory> GetURLLoaderFactory() override; bool GetBrand(std::string* brand) override; bool IsBrandOrganic(const std::string& brand) override; bool GetReactivationBrand(std::string* brand) override; bool ShouldEnableZeroDelayForTesting() override; bool GetLanguage(base::string16* language) override; bool GetReferral(base::string16* referral) override; bool ClearReferral() override; void SetOmniboxSearchCallback(const base::Closure& callback) override; void SetHomepageSearchCallback(const base::Closure& callback) override; // content::NotificationObserver implementation: void Observe(int type, const content::NotificationSource& source, const content::NotificationDetails& details) override; // Called when a URL is opened from the Omnibox. void OnURLOpenedFromOmnibox(OmniboxLog* log); content::NotificationRegistrar registrar_; base::Closure on_omnibox_search_callback_; base::Closure on_homepage_search_callback_; // Subscription for receiving callbacks that a URL was opened from the // omnibox. std::unique_ptr<base::CallbackList<void(OmniboxLog*)>::Subscription> omnibox_url_opened_subscription_; DISALLOW_COPY_AND_ASSIGN(ChromeRLZTrackerDelegate); }; #endif // CHROME_BROWSER_RLZ_CHROME_RLZ_TRACKER_DELEGATE_H_
[ "artem@brave.com" ]
artem@brave.com
be67146d136c318257d404ff54450a4a9b61add2
f4af4a530909bcec17478131ca69f28d03a776b0
/BaseLib/network/CStrMsgProcessor.cpp
5d3af178446fc7398d3c978b1a51da67e6e91c29
[]
no_license
eyes4/light-server-frame
5b478fd1bd1b89dae21fdfc10c872f117eba5cc3
8b2cd17b02bc766162d2eb5cae4603065077d476
refs/heads/master
2016-08-11T06:41:20.392870
2012-06-06T13:45:42
2012-06-06T13:45:42
52,317,838
1
1
null
null
null
null
GB18030
C++
false
false
3,095
cpp
#include "../include/CStrMsgProcessor.h" CStrMsgProcessor::CStrMsgProcessor(int nTimeOut, char *szTail) { m_nTimeOut = nTimeOut; strcpy(m_szTail, szTail); m_nTailSize = strlen(szTail); InitMutex(&m_Mutex); } CStrMsgProcessor::~CStrMsgProcessor() { DestroyMutex(&m_Mutex); } void CStrMsgProcessor::OnAccept(SOCKET socket, const char *szClientIP) { EnterMutex(&m_Mutex); //DEBUGMSG("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!Accept socket:%d\n", socket); m_RecvStrMap[socket] = ""; m_TimeOutTick[socket] = 10000; LeaveMutex(&m_Mutex); TStrMsg *pMsg = new TStrMsg(); pMsg->socket = socket; pMsg->msg = string("#1$");//特殊消息,表示Accept sprintf(pMsg->clientip, "%s", szClientIP); m_MsgQueue.push(pMsg); } void CStrMsgProcessor::OnRead(SOCKET socket, const char *szClientIP, char *buf, int len) { if (m_RecvStrMap.find(socket) == m_RecvStrMap.end()) return; int nHead = 0; m_TimeOutTick[socket] = m_nTimeOut / 10; char *p = strstr(buf, m_szTail);//"$"); while (p != NULL) { m_RecvStrMap[socket].append(buf, nHead, p - &buf[nHead]); nHead = (int)(p - buf + m_nTailSize);//1); TStrMsg *pMsg = new TStrMsg(); pMsg->socket = socket; pMsg->msg = m_RecvStrMap[socket]; sprintf(pMsg->clientip, "%s", szClientIP); m_MsgQueue.push(pMsg); p = strstr(&buf[nHead], m_szTail);//"$"); m_RecvStrMap[socket] = ""; //nHead = 0; } if (nHead < len) { //cout<<nHead<<" "<<len<<" "<<m_RecvStrMap[socket]<<endl; m_RecvStrMap[socket].append(buf, nHead, len - nHead); } } void CStrMsgProcessor::OnClose(SOCKET socket, const char *szClientIP) { //cout<<"----------------------------------onclose"<<endl; EnterMutex(&m_Mutex); TStrMsg *pMsg = new TStrMsg(); pMsg->socket = socket; pMsg->msg = "#0$";//特殊消息,表示网络断线 sprintf(pMsg->clientip, "%s", szClientIP); m_MsgQueue.push(pMsg); m_RecvStrMap.erase(socket); if (m_TimeOutTick.find(socket) != m_TimeOutTick.end()) m_TimeOutTick.erase(socket); LeaveMutex(&m_Mutex); } int CStrMsgProcessor::MsgCount(void) { return (int)m_MsgQueue.size(); } void *CStrMsgProcessor::GetMsg(void) { return (void *)m_MsgQueue.front(); } void CStrMsgProcessor::PopMsg(void) { TStrMsg *pMsg = m_MsgQueue.front(); delete pMsg; m_MsgQueue.pop(); } void CStrMsgProcessor::CheckTimeout(void) { EnterMutex(&m_Mutex); map<SOCKET, int>::iterator ClientIter; for (ClientIter = m_TimeOutTick.begin(); ClientIter != m_TimeOutTick.end(); ) { ClientIter->second--; if (ClientIter->second <= 0) { map<SOCKET, int>::iterator itErase= ClientIter; ++ClientIter; SOCKET s = itErase->first; TStrMsg *pMsg = new TStrMsg(); pMsg->socket = s; pMsg->msg = "#0$";//特殊消息,表示网络断线 sprintf(pMsg->clientip, "%s", ""); m_MsgQueue.push(pMsg); m_TimeOutTick.erase(s); m_RecvStrMap.erase(s); DEBUGMSG("*******************************close socket:%d\n", s); SocketClose(s); } else { ++ClientIter; } } LeaveMutex(&m_Mutex); }
[ "eyesfour@2c3afd96-2e2b-54bb-296e-4c59daaf94c1" ]
eyesfour@2c3afd96-2e2b-54bb-296e-4c59daaf94c1
4ca033ba46635a2b8a7ea726b2a7c2b7ad380581
5637549e7b1f7d01321d0d6e850454ebdf037392
/src/items_chave.h
5d691d403b46efe5d9394c8d9b1b1b0817e57b82
[]
no_license
zipleen/space-wolf
01ffd88ec41338a97194fe2d406f309d7c218736
83bb1d0aaca4671b7c66b22cd9d4a3e1027eb3cd
refs/heads/master
2022-02-13T09:30:10.674525
2022-01-19T22:39:36
2022-01-19T22:39:36
8,300,751
0
0
null
null
null
null
UTF-8
C++
false
false
425
h
/* * items_chave.h * proj * * Created by zipleen on 1/12/08. * Copyright 2008 __MyCompanyName__. All rights reserved. * */ #ifndef ITEMS_CHAVE_H #define ITEMS_CHAVE_H #include "items.h" class Items_Chave : public Items { int tipo; public: Items_Chave(){}; Items_Chave(GLfloat x,GLfloat y, int valor, int mapa_x, int mapa_y); virtual ~Items_Chave(){}; virtual bool consume(Player *p); }; #endif
[ "zipleen@gmail.com" ]
zipleen@gmail.com
9133832623fa70d2a7286cc3d3f3afae036c9d46
40d91f99f97512a0909c7a84a8b7f87c40768dc1
/beijing45/beijing54/CalculateModel/ng_db_lib/DBMySqlReader.cpp
58171b18b9ff152af1aa57ca8e147b63b4f54ea4
[]
no_license
radtek/NG_Beijing54
85c8662a80ec8407a2bb27eec170113c15bcdf62
211871dc7f047c0f1348526c91fbe3cd34d89c16
refs/heads/master
2020-09-01T15:33:28.332873
2019-08-06T09:51:27
2019-08-06T09:51:27
218,994,155
1
0
null
2019-11-01T13:49:49
2019-11-01T13:49:48
null
UTF-8
C++
false
false
8,219
cpp
#ifdef USE_MYSQL #include "DBMySqlReader.h" #include <stdio.h> #include <new> DBMySqlReader::DBMySqlReader(MYSQL * pcon) { p_con = pcon; p_stmt = NULL; lastRow = 0; bResultEnd = true; } DBMySqlReader::~DBMySqlReader(void) { Close(); } bool DBMySqlReader::Query( const char* sql ) { if(sql) { Close(); int res = mysql_query(p_con,sql); if(res) { DBText err = mysql_error(p_con); throw err; } p_stmt = mysql_store_result(p_con); lastRow = 0; bResultEnd = false; if(p_stmt == NULL) { const char * ex = mysql_error(p_con); if(ex!=NULL&&*ex!='\0') { DBText err = ex; throw err; } } } return (p_stmt != NULL); } void DBMySqlReader::Close() { if(p_stmt != NULL) { mysql_free_result(p_stmt); fields.clear(); lastRow = 0; p_stmt = NULL; } } bool DBMySqlReader::Read( void ) { if(p_stmt!=NULL) { //if(mysql_eof(p_stmt)) // return false; data_row = mysql_fetch_row(p_stmt); return data_row!=NULL; } return false; } bool DBMySqlReader::GetFields() { if(fields.empty()) { if(p_stmt != NULL) { int cout = mysql_num_fields(p_stmt); MYSQL_FIELD *pFilds = mysql_fetch_fields(p_stmt); for(int i=0;i<cout;i++) { std::string field = pFilds[i].name; fields.push_back(field); } } } return !fields.empty(); } int DBMySqlReader::GetColumnIndex( const char *name ) { if(GetFields()) { int count = fields.size(); for(int index=0;index<count;index++) { std::string colnumName = fields[index]; if(strcmpnocase(colnumName.c_str(),name)==0) return index; } } return -1; } index_int DBMySqlReader::GetFieldsCount( void ) { if(!fields.empty()) return fields.size(); else if(p_stmt!=NULL) { return mysql_num_fields(p_stmt); } return 0; } index_int DBMySqlReader::GetResultCount( void ) { if(p_stmt!=NULL) return (index_int)mysql_num_rows(p_stmt); return 0; } DBText DBMySqlReader::GetName( index_int index ) { if(GetFields()) { if(index>0&&(unsigned int)index<fields.size()) return DBText(fields[index].c_str()); } return DBText(); } NGDBCom::DBBool DBMySqlReader::GetBoolean( const char* name ) { if(p_stmt!=NULL) { int index = -1; if(-1!=(index =GetColumnIndex(name))) { return GetBoolean(index); } } return DBBool(); } NGDBCom::DBBool DBMySqlReader::GetBoolean( index_int index ) { DBBool val; if(index<0||index>=GetFieldsCount()) return val; if(data_row!=NULL) { const char * pData = data_row[index]; if(pData!=NULL) { int dbvalue = 0; sscanf(pData,"%d",&dbvalue); val = (dbvalue!=0); } } return val; } NGDBCom::DBByte DBMySqlReader::GetByte( const char* name ) { if(p_stmt!=NULL) { int index = -1; if(-1!=(index =GetColumnIndex(name))) { return GetByte(index); } } return DBByte(); } NGDBCom::DBByte DBMySqlReader::GetByte( index_int index ) { DBByte val; if(index<0||index>=GetFieldsCount()) return val; if(data_row!=NULL) { const char * pData = data_row[index]; if(pData!=NULL) { val = pData[0]; } } return val; } NGDBCom::DBBlob DBMySqlReader::GetBlob( const char*name ) { if(p_stmt!=NULL) { int index = -1; if(-1!=(index =GetColumnIndex(name))) { return GetBlob(index); } } return DBBlob(); } NGDBCom::DBBlob DBMySqlReader::GetBlob( index_int index ) { DBBlob value; if(p_stmt!=NULL) { if(!IsDBNull(index)) { const void * v = data_row[index]; unsigned long *FieldLength = mysql_fetch_lengths(p_stmt); unsigned int blobsize = FieldLength[index]; byte * bytes = new(std::nothrow) byte[blobsize]; if(bytes) { memcpy(bytes,v,blobsize); value.SetValue(bytes,blobsize,true); } } } return value; } NGDBCom::DBChar DBMySqlReader::GetChar( const char*name ) { if(p_stmt!=NULL) { int index = -1; if(-1!=(index =GetColumnIndex(name))) { return GetChar(index); } } return DBChar(); } NGDBCom::DBChar DBMySqlReader::GetChar( index_int index ) { DBChar val; if(index<0||index>=GetFieldsCount()) return val; if(data_row!=NULL) { const char * pData = data_row[index]; if(pData!=NULL) { val = pData[0]; } } return val; } NGDBCom::DBText DBMySqlReader::GetText( const char*name ) { if(p_stmt!=NULL) { int index = -1; if(-1!=(index =GetColumnIndex(name))) { return GetText(index); } } return DBText(); } NGDBCom::DBText DBMySqlReader::GetText( index_int index ) { DBText val; if(index<0||index>=GetFieldsCount()) return val; if(data_row!=NULL) { const char * pData = data_row[index]; if(pData!=NULL) { val = pData; } } return val; } NGDBCom::DBDatetime DBMySqlReader::GetDatetime( const char* name ) { if(p_stmt!=NULL) { int index = -1; if(-1!=(index =GetColumnIndex(name))) { return GetDatetime(index); } } return DBDatetime(); } NGDBCom::DBDatetime DBMySqlReader::GetDatetime( index_int index ) { DBDatetime val; if(index<0||index>=GetFieldsCount()) return val; if(data_row!=NULL) { const char * pData = data_row[index]; if(pData!=NULL) { tm temp; memset(&temp,0,sizeof(tm)); StringToTM((const char*)pData,temp); val = temp; } } return val; } NGDBCom::DBDouble DBMySqlReader::GetDouble( const char* name ) { if(p_stmt!=NULL) { int index = -1; if(-1!=(index =GetColumnIndex(name))) { return GetDouble(index); } } return DBDouble(); } NGDBCom::DBDouble DBMySqlReader::GetDouble( index_int index ) { DBDouble val; if(index<0||index>=GetFieldsCount()) return val; if(data_row!=NULL) { const char * pData = data_row[index]; char *stop; if(pData!=NULL) { double dbvalue = 0; sscanf(pData,"%lf",&dbvalue); val = dbvalue; } } return val; } NGDBCom::DBFloat DBMySqlReader::GetFloat( const char*name ) { if(p_stmt!=NULL) { int index = -1; if(-1!=(index =GetColumnIndex(name))) { return GetFloat(index); } } return DBFloat(); } NGDBCom::DBFloat DBMySqlReader::GetFloat( index_int index ) { DBFloat val; if(index<0||index>=GetFieldsCount()) return val; if(data_row!=NULL) { const char * pData = data_row[index]; char *stop; if(pData!=NULL) { float dbvalue =0; sscanf(pData,"%f",&dbvalue); val = (float)dbvalue; } } return val; } NGDBCom::DBInt16 DBMySqlReader::GetInt16( const char*name ) { if(p_stmt!=NULL) { int index = -1; if(-1!=(index =GetColumnIndex(name))) { return GetInt16(index); } } return DBInt16(); } NGDBCom::DBInt16 DBMySqlReader::GetInt16( index_int index ) { DBInt16 val; if(index<0||index>=GetFieldsCount()) return val; if(data_row!=NULL) { const char * pData = data_row[index]; if(pData!=NULL) { long dbvalue = 0; sscanf(pData,"%i",&dbvalue); val = (short)dbvalue; } } return val; } NGDBCom::DBInt32 DBMySqlReader::GetInt32( const char*name ) { if(p_stmt!=NULL) { int index = -1; if(-1!=(index =GetColumnIndex(name))) { return GetInt32(index); } } return DBInt32(); } NGDBCom::DBInt32 DBMySqlReader::GetInt32( index_int index ) { DBInt32 val; if(index<0||index>=GetFieldsCount()) return val; if(data_row!=NULL) { const char * pData = data_row[index]; char *stop; if(pData!=NULL) { int dbvalue = 0; sscanf(pData,"%d",&dbvalue); val = (int)dbvalue; } } return val; } NGDBCom::DBInt64 DBMySqlReader::GetInt64( const char*name ) { if(p_stmt!=NULL) { int index = -1; if(-1!=(index =GetColumnIndex(name))) { return GetInt64(index); } } return DBInt64(); } NGDBCom::DBInt64 DBMySqlReader::GetInt64( index_int index ) { DBInt64 val; if(index<0||index>=GetFieldsCount()) return val; if(data_row!=NULL) { const char * pData = data_row[index]; char *stop; if(pData!=NULL) { long long dbvalue = 0; sscanf(pData,"%lld",&dbvalue); val = dbvalue; } } return val; } bool DBMySqlReader::IsDBNull( const char*name ) { if(p_stmt!=NULL) { int index = -1; if(-1!=(index =GetColumnIndex(name))) { return IsDBNull(index); } } return true; } bool DBMySqlReader::IsDBNull( index_int index ) { if(index<0||index>=GetFieldsCount()) return true; if(data_row!=NULL) { const char * pData = data_row[index]; if(pData && pData[0]!='\0') return false; } return true; } #endif
[ "1037939838@qq.com" ]
1037939838@qq.com
03e6c2ce9edd7fcf7e6b0369224ef81b6336f91f
609b5ed11126da70fe95771eed71fd9d7e40c724
/src/ai/agents/agent.h
1c98c296428414c6d3e0063f8916108cb4946b9f
[]
no_license
trid/exp
4930b65913f2cc30d665c6ee19b28e8d937096f3
bcee0e50939ca941b84f77cd5299bef1775ae012
refs/heads/master
2023-02-21T23:25:42.292598
2023-02-05T16:19:34
2023-02-05T16:19:34
24,107,024
0
0
null
null
null
null
UTF-8
C++
false
false
955
h
#ifndef ACTOR_H #define ACTOR_H #include <string> #include <unordered_map> #include <unordered_set> #include "actor.h" #include "agent_needs.h" #include "agent_movement_data.h" #include "inventory.h" namespace Core { class GlobalMessageBus; class World; } // namespace Core namespace Core::AI::Agents { class Agent: public AgentNeeds, public AgentPositioningData, public Actor, public Inventory { public: explicit Agent(int id, Core::GlobalMessageBus& globalMessageBus); int getID() const; const std::string& getName() const; void setName(const std::string& name); void say(const std::string& message); void setType(const std::string& type); const std::string& getType() const; private: int _id; std::string _name; // TODO decide some better way to differentiate agent's color std::string _type; Core::GlobalMessageBus& _globalMessageBus; }; } // namespace Core::AI::Agents #endif // ACTOR_H
[ "hovyakov@gmail.com" ]
hovyakov@gmail.com
4b75d1a13aa936796934ac81ab466019a88dce0b
14988acd59ee96027a6668238b40555cc03cf3ca
/src/group-keys-distributor/group.hpp
0f1022ed41f42fb9f4b54dbdd552496e1d24fa5f
[]
no_license
djuanes87/PFG-NDNMacaroons
b8b1a6321e0e82bc7ca5530882a737e895703783
93804f7d7585aff7ac461d958aec7eca222b3712
refs/heads/master
2021-01-12T14:55:05.382746
2017-04-18T22:02:56
2017-04-18T22:02:56
68,912,624
0
0
null
null
null
null
UTF-8
C++
false
false
852
hpp
#include <ndn-cxx/security/key-chain.hpp> #include <NDNMacaroon/macaroon.hpp> #include <NDNMacaroon/macaroon-utils.hpp> class Group { public: std::string name; Group(); void setName(std::string); std::string getDischargueMacaroon(std::string gkd_location, uint8_t *caveat_key, uint8_t *identifier, size_t identifier_size); void addMember(std::string member); bool isMember(std::string name); private: ndn::SecTpmFileEnc m_secTpmFile; std::string discharge; std::set<std::string> members; // Example caveats std::string first_party_caveat = "time < 2018-02-27 08:22:00"; void createDischargeMacaroon(std::string gkd_location, uint8_t *caveat_key, uint8_t *identifier, size_t identifier_size); };
[ "daniel.juanes@gmail.com" ]
daniel.juanes@gmail.com
7815e256a09994bf02d4443a8447c765eda76de8
f580fd53d3d035fc4b6b1c0abb41470a91544236
/Estuardo/Estuardo.ino
1490effe1ad0c3b11b2fc14993157e22c2182ce3
[]
no_license
gatoherz11/Arduino_projects
b9536770e0f400380daeb41a925f3dae352b3672
874e6f2bcf521e8592f9f9a07c88f2e47eed19ee
refs/heads/master
2022-11-11T16:14:57.350004
2020-07-05T00:14:02
2020-07-05T00:14:02
277,204,241
1
0
null
null
null
null
UTF-8
C++
false
false
603
ino
#define echo 6 #define trig 7 long duracion; long distancia; void setup() { pinMode(trig, OUTPUT); pinMode(echo, INPUT); pinMode(8, OUTPUT); Serial.begin (115200); delay (500); } void loop() { digitalWrite(trig, LOW); delayMicroseconds(30); digitalWrite(trig, HIGH); delayMicroseconds(30); digitalWrite(trig, LOW); duracion = pulseIn(echo, HIGH); distancia = (duracion/2) / 29; if (distancia<40){ tone(8, 1000); delay (500); noTone(8); } delay (10); }
[ "64179143+gatoherz11@users.noreply.github.com" ]
64179143+gatoherz11@users.noreply.github.com
0abd6f31d3f6189c54d29f194c0f4ca4767230f7
985548d3d330e121a5cffa3e3f9f17443ee9e196
/2020/RoundG/D.cpp
667b47a89782414cf8d413511f54e71521e15209
[]
no_license
TYakumo/GoogleKickStart
3d7c210d51c4876821fa874a6c9a7ed981758a70
c25c00f62802794e918eeaabed038cd171411e10
refs/heads/master
2021-07-25T11:21:39.368943
2021-07-20T14:12:35
2021-07-20T14:12:35
248,889,725
0
0
null
2021-07-20T14:12:35
2020-03-21T02:06:35
C++
UTF-8
C++
false
false
1,653
cpp
#include <cstdio> #include <cstring> #include <algorithm> #include <iostream> #include <vector> #include <map> #include <queue> #include <set> #include <cmath> using namespace std; using VLL = vector <long long>; using VD = vector <double>; using VVD = vector <VD>; int main() { int TC; cin >> TC; cout.precision(9); for (int tc = 1; tc <= TC; tc++) { int N; cin >> N; VLL val(N); VLL sum(N); VVD dp(N+1, VD(N+1)); VD frontdp(N+1); VD reardp(N+1); for (int i = 0; i < N; ++i) { cin >> val[i]; sum[i] = val[i]; if (i) { sum[i] += sum[i-1]; } } for (int l = 2; l <= N; ++l) { for (int i = 0; i+l <= N; ++i) { int j = i+l-1; double prob = 1.0 / (j-i); double rangeSum = i ? sum[j] - sum[i-1] : sum[j]; double total = rangeSum * (j-i) + frontdp[i] + reardp[j]; // for (int k = i; k < j; ++k) { // // double total = dp[i][k] + dp[k+1][j] + rangeSum; // dp[i][j] += total * prob; // } dp[i][j] += total * prob; } for (int i = 0; i < N; ++i) { int tj = i+l-1; // j = i+l-1, i = j-l+1 int ti = i-l+1; frontdp[i] += dp[i][tj]; if (ti >= 0) { reardp[i] += dp[ti][i]; } } } cout << fixed << "Case #" << tc << ": " << dp[0][N-1] << endl; } return 0; }
[ "foxs91092@gmail.com" ]
foxs91092@gmail.com
211ece9dcfbeff9fce97c05f1685fb048a40c114
271d1e144baf8b1174e89b4c8950221cddaccfec
/src/prevector.h
d539be4a0f4eb95825c87e4032add5cc65b87c1b
[ "MIT" ]
permissive
TON-beta/TelegramOpenNetwork
61591a57cb0211ddf12fa94150db3bce09cc72fc
cb773a5a792e4b97d77d643189edd35da52e1a79
refs/heads/master
2020-06-26T15:01:29.600748
2019-08-07T23:50:08
2019-08-07T23:50:08
199,666,103
15
1
null
null
null
null
UTF-8
C++
false
false
18,171
h
// Copyright (c) 2015-2018 The ton Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef ton_PREVECTOR_H #define ton_PREVECTOR_H #include <assert.h> #include <stdlib.h> #include <stdint.h> #include <string.h> #include <algorithm> #include <cstddef> #include <iterator> #include <type_traits> #pragma pack(push, 1) /** Implements a drop-in replacement for std::vector<T> which stores up to N * elements directly (without heap allocation). The types Size and Diff are * used to store element counts, and can be any unsigned + signed type. * * Storage layout is either: * - Direct allocation: * - Size _size: the number of used elements (between 0 and N) * - T direct[N]: an array of N elements of type T * (only the first _size are initialized). * - Indirect allocation: * - Size _size: the number of used elements plus N + 1 * - Size capacity: the number of allocated elements * - T* indirect: a pointer to an array of capacity elements of type T * (only the first _size are initialized). * * The data type T must be movable by memmove/realloc(). Once we switch to C++, * move constructors can be used instead. */ template<unsigned int N, typename T, typename Size = uint32_t, typename Diff = int32_t> class prevector { public: typedef Size size_type; typedef Diff difference_type; typedef T value_type; typedef value_type& reference; typedef const value_type& const_reference; typedef value_type* pointer; typedef const value_type* const_pointer; class iterator { T* ptr; public: typedef Diff difference_type; typedef T value_type; typedef T* pointer; typedef T& reference; typedef std::random_access_iterator_tag iterator_category; iterator(T* ptr_) : ptr(ptr_) {} T& operator*() const { return *ptr; } T* operator->() const { return ptr; } T& operator[](size_type pos) { return ptr[pos]; } const T& operator[](size_type pos) const { return ptr[pos]; } iterator& operator++() { ptr++; return *this; } iterator& operator--() { ptr--; return *this; } iterator operator++(int) { iterator copy(*this); ++(*this); return copy; } iterator operator--(int) { iterator copy(*this); --(*this); return copy; } difference_type friend operator-(iterator a, iterator b) { return (&(*a) - &(*b)); } iterator operator+(size_type n) { return iterator(ptr + n); } iterator& operator+=(size_type n) { ptr += n; return *this; } iterator operator-(size_type n) { return iterator(ptr - n); } iterator& operator-=(size_type n) { ptr -= n; return *this; } bool operator==(iterator x) const { return ptr == x.ptr; } bool operator!=(iterator x) const { return ptr != x.ptr; } bool operator>=(iterator x) const { return ptr >= x.ptr; } bool operator<=(iterator x) const { return ptr <= x.ptr; } bool operator>(iterator x) const { return ptr > x.ptr; } bool operator<(iterator x) const { return ptr < x.ptr; } }; class reverse_iterator { T* ptr; public: typedef Diff difference_type; typedef T value_type; typedef T* pointer; typedef T& reference; typedef std::bidirectional_iterator_tag iterator_category; reverse_iterator(T* ptr_) : ptr(ptr_) {} T& operator*() { return *ptr; } const T& operator*() const { return *ptr; } T* operator->() { return ptr; } const T* operator->() const { return ptr; } reverse_iterator& operator--() { ptr++; return *this; } reverse_iterator& operator++() { ptr--; return *this; } reverse_iterator operator++(int) { reverse_iterator copy(*this); ++(*this); return copy; } reverse_iterator operator--(int) { reverse_iterator copy(*this); --(*this); return copy; } bool operator==(reverse_iterator x) const { return ptr == x.ptr; } bool operator!=(reverse_iterator x) const { return ptr != x.ptr; } }; class const_iterator { const T* ptr; public: typedef Diff difference_type; typedef const T value_type; typedef const T* pointer; typedef const T& reference; typedef std::random_access_iterator_tag iterator_category; const_iterator(const T* ptr_) : ptr(ptr_) {} const_iterator(iterator x) : ptr(&(*x)) {} const T& operator*() const { return *ptr; } const T* operator->() const { return ptr; } const T& operator[](size_type pos) const { return ptr[pos]; } const_iterator& operator++() { ptr++; return *this; } const_iterator& operator--() { ptr--; return *this; } const_iterator operator++(int) { const_iterator copy(*this); ++(*this); return copy; } const_iterator operator--(int) { const_iterator copy(*this); --(*this); return copy; } difference_type friend operator-(const_iterator a, const_iterator b) { return (&(*a) - &(*b)); } const_iterator operator+(size_type n) { return const_iterator(ptr + n); } const_iterator& operator+=(size_type n) { ptr += n; return *this; } const_iterator operator-(size_type n) { return const_iterator(ptr - n); } const_iterator& operator-=(size_type n) { ptr -= n; return *this; } bool operator==(const_iterator x) const { return ptr == x.ptr; } bool operator!=(const_iterator x) const { return ptr != x.ptr; } bool operator>=(const_iterator x) const { return ptr >= x.ptr; } bool operator<=(const_iterator x) const { return ptr <= x.ptr; } bool operator>(const_iterator x) const { return ptr > x.ptr; } bool operator<(const_iterator x) const { return ptr < x.ptr; } }; class const_reverse_iterator { const T* ptr; public: typedef Diff difference_type; typedef const T value_type; typedef const T* pointer; typedef const T& reference; typedef std::bidirectional_iterator_tag iterator_category; const_reverse_iterator(const T* ptr_) : ptr(ptr_) {} const_reverse_iterator(reverse_iterator x) : ptr(&(*x)) {} const T& operator*() const { return *ptr; } const T* operator->() const { return ptr; } const_reverse_iterator& operator--() { ptr++; return *this; } const_reverse_iterator& operator++() { ptr--; return *this; } const_reverse_iterator operator++(int) { const_reverse_iterator copy(*this); ++(*this); return copy; } const_reverse_iterator operator--(int) { const_reverse_iterator copy(*this); --(*this); return copy; } bool operator==(const_reverse_iterator x) const { return ptr == x.ptr; } bool operator!=(const_reverse_iterator x) const { return ptr != x.ptr; } }; private: size_type _size = 0; union direct_or_indirect { char direct[sizeof(T) * N]; struct { size_type capacity; char* indirect; }; } _union = {}; T* direct_ptr(difference_type pos) { return reinterpret_cast<T*>(_union.direct) + pos; } const T* direct_ptr(difference_type pos) const { return reinterpret_cast<const T*>(_union.direct) + pos; } T* indirect_ptr(difference_type pos) { return reinterpret_cast<T*>(_union.indirect) + pos; } const T* indirect_ptr(difference_type pos) const { return reinterpret_cast<const T*>(_union.indirect) + pos; } bool is_direct() const { return _size <= N; } void change_capacity(size_type new_capacity) { if (new_capacity <= N) { if (!is_direct()) { T* indirect = indirect_ptr(0); T* src = indirect; T* dst = direct_ptr(0); memcpy(dst, src, size() * sizeof(T)); free(indirect); _size -= N + 1; } } else { if (!is_direct()) { /* FIXME: Because malloc/realloc here won't call new_handler if allocation fails, assert success. These should instead use an allocator or new/delete so that handlers are called as necessary, but performance would be slightly degraded by doing so. */ _union.indirect = static_cast<char*>(realloc(_union.indirect, ((size_t)sizeof(T)) * new_capacity)); assert(_union.indirect); _union.capacity = new_capacity; } else { char* new_indirect = static_cast<char*>(malloc(((size_t)sizeof(T)) * new_capacity)); assert(new_indirect); T* src = direct_ptr(0); T* dst = reinterpret_cast<T*>(new_indirect); memcpy(dst, src, size() * sizeof(T)); _union.indirect = new_indirect; _union.capacity = new_capacity; _size += N + 1; } } } T* item_ptr(difference_type pos) { return is_direct() ? direct_ptr(pos) : indirect_ptr(pos); } const T* item_ptr(difference_type pos) const { return is_direct() ? direct_ptr(pos) : indirect_ptr(pos); } void fill(T* dst, ptrdiff_t count, const T& value = T{}) { std::fill_n(dst, count, value); } template<typename InputIterator> void fill(T* dst, InputIterator first, InputIterator last) { while (first != last) { new(static_cast<void*>(dst)) T(*first); ++dst; ++first; } } public: void assign(size_type n, const T& val) { clear(); if (capacity() < n) { change_capacity(n); } _size += n; fill(item_ptr(0), n, val); } template<typename InputIterator> void assign(InputIterator first, InputIterator last) { size_type n = last - first; clear(); if (capacity() < n) { change_capacity(n); } _size += n; fill(item_ptr(0), first, last); } prevector() {} explicit prevector(size_type n) { resize(n); } explicit prevector(size_type n, const T& val) { change_capacity(n); _size += n; fill(item_ptr(0), n, val); } template<typename InputIterator> prevector(InputIterator first, InputIterator last) { size_type n = last - first; change_capacity(n); _size += n; fill(item_ptr(0), first, last); } prevector(const prevector<N, T, Size, Diff>& other) { size_type n = other.size(); change_capacity(n); _size += n; fill(item_ptr(0), other.begin(), other.end()); } prevector(prevector<N, T, Size, Diff>&& other) { swap(other); } prevector& operator=(const prevector<N, T, Size, Diff>& other) { if (&other == this) { return *this; } assign(other.begin(), other.end()); return *this; } prevector& operator=(prevector<N, T, Size, Diff>&& other) { swap(other); return *this; } size_type size() const { return is_direct() ? _size : _size - N - 1; } bool empty() const { return size() == 0; } iterator begin() { return iterator(item_ptr(0)); } const_iterator begin() const { return const_iterator(item_ptr(0)); } iterator end() { return iterator(item_ptr(size())); } const_iterator end() const { return const_iterator(item_ptr(size())); } reverse_iterator rbegin() { return reverse_iterator(item_ptr(size() - 1)); } const_reverse_iterator rbegin() const { return const_reverse_iterator(item_ptr(size() - 1)); } reverse_iterator rend() { return reverse_iterator(item_ptr(-1)); } const_reverse_iterator rend() const { return const_reverse_iterator(item_ptr(-1)); } size_t capacity() const { if (is_direct()) { return N; } else { return _union.capacity; } } T& operator[](size_type pos) { return *item_ptr(pos); } const T& operator[](size_type pos) const { return *item_ptr(pos); } void resize(size_type new_size) { size_type cur_size = size(); if (cur_size == new_size) { return; } if (cur_size > new_size) { erase(item_ptr(new_size), end()); return; } if (new_size > capacity()) { change_capacity(new_size); } ptrdiff_t increase = new_size - cur_size; fill(item_ptr(cur_size), increase); _size += increase; } void reserve(size_type new_capacity) { if (new_capacity > capacity()) { change_capacity(new_capacity); } } void shrink_to_fit() { change_capacity(size()); } void clear() { resize(0); } iterator insert(iterator pos, const T& value) { size_type p = pos - begin(); size_type new_size = size() + 1; if (capacity() < new_size) { change_capacity(new_size + (new_size >> 1)); } T* ptr = item_ptr(p); memmove(ptr + 1, ptr, (size() - p) * sizeof(T)); _size++; new(static_cast<void*>(ptr)) T(value); return iterator(ptr); } void insert(iterator pos, size_type count, const T& value) { size_type p = pos - begin(); size_type new_size = size() + count; if (capacity() < new_size) { change_capacity(new_size + (new_size >> 1)); } T* ptr = item_ptr(p); memmove(ptr + count, ptr, (size() - p) * sizeof(T)); _size += count; fill(item_ptr(p), count, value); } template<typename InputIterator> void insert(iterator pos, InputIterator first, InputIterator last) { size_type p = pos - begin(); difference_type count = last - first; size_type new_size = size() + count; if (capacity() < new_size) { change_capacity(new_size + (new_size >> 1)); } T* ptr = item_ptr(p); memmove(ptr + count, ptr, (size() - p) * sizeof(T)); _size += count; fill(ptr, first, last); } inline void resize_uninitialized(size_type new_size) { // resize_uninitialized changes the size of the prevector but does not initialize it. // If size < new_size, the added elements must be initialized explicitly. if (capacity() < new_size) { change_capacity(new_size); _size += new_size - size(); return; } if (new_size < size()) { erase(item_ptr(new_size), end()); } else { _size += new_size - size(); } } iterator erase(iterator pos) { return erase(pos, pos + 1); } iterator erase(iterator first, iterator last) { // Erase is not allowed to the change the object's capacity. That means // that when starting with an indirectly allocated prevector with // size and capacity > N, the result may be a still indirectly allocated // prevector with size <= N and capacity > N. A shrink_to_fit() call is // necessary to switch to the (more efficient) directly allocated // representation (with capacity N and size <= N). iterator p = first; char* endp = (char*)&(*end()); if (!std::is_trivially_destructible<T>::value) { while (p != last) { (*p).~T(); _size--; ++p; } } else { _size -= last - p; } memmove(&(*first), &(*last), endp - ((char*)(&(*last)))); return first; } void push_back(const T& value) { size_type new_size = size() + 1; if (capacity() < new_size) { change_capacity(new_size + (new_size >> 1)); } new(item_ptr(size())) T(value); _size++; } void pop_back() { erase(end() - 1, end()); } T& front() { return *item_ptr(0); } const T& front() const { return *item_ptr(0); } T& back() { return *item_ptr(size() - 1); } const T& back() const { return *item_ptr(size() - 1); } void swap(prevector<N, T, Size, Diff>& other) { std::swap(_union, other._union); std::swap(_size, other._size); } ~prevector() { if (!std::is_trivially_destructible<T>::value) { clear(); } if (!is_direct()) { free(_union.indirect); _union.indirect = nullptr; } } bool operator==(const prevector<N, T, Size, Diff>& other) const { if (other.size() != size()) { return false; } const_iterator b1 = begin(); const_iterator b2 = other.begin(); const_iterator e1 = end(); while (b1 != e1) { if ((*b1) != (*b2)) { return false; } ++b1; ++b2; } return true; } bool operator!=(const prevector<N, T, Size, Diff>& other) const { return !(*this == other); } bool operator<(const prevector<N, T, Size, Diff>& other) const { if (size() < other.size()) { return true; } if (size() > other.size()) { return false; } const_iterator b1 = begin(); const_iterator b2 = other.begin(); const_iterator e1 = end(); while (b1 != e1) { if ((*b1) < (*b2)) { return true; } if ((*b2) < (*b1)) { return false; } ++b1; ++b2; } return false; } size_t allocated_memory() const { if (is_direct()) { return 0; } else { return ((size_t)(sizeof(T))) * _union.capacity; } } value_type* data() { return item_ptr(0); } const value_type* data() const { return item_ptr(0); } }; #pragma pack(pop) #endif // ton_PREVECTOR_H
[ "53483064+TON-beta@users.noreply.github.com" ]
53483064+TON-beta@users.noreply.github.com
73d7ff34d0dda8b53aa01d3a9530fef167ec1b24
b22cde09ef90971a3691f344e1d71daefe30a25e
/Project3/fibo_heap.cpp
67e85abc114aa50afdf421b157b663e545312949
[]
no_license
jlpang1997/algorithm_completion_c_cpp_edition
3147e67ace1392279fa754e0311912b414a5ede2
36f1fd888c99b6145981b289f55ddf44b26a169d
refs/heads/master
2020-09-01T03:01:35.474356
2019-11-30T04:28:58
2019-11-30T04:28:58
218,864,379
1
0
null
null
null
null
UTF-8
C++
false
false
5,550
cpp
#include"fibo_heap.h" #include<stdio.h> #include<malloc.h> #include<math.h> void add_fibo_node(Fibo_node *node, Fibo_node *root) { node->left = root->left; root->left->right = node; node->right = root; root->left = node; } int fibo_heap_insert(Fibo_heap &fibo_heap, int *, int, Fibo_node*, int x) { Fibo_node*node = (Fibo_node*)malloc(sizeof(Fibo_node)); node->child = NULL; node->parent = NULL; node->degreee = 0; node->key = x; node->marked = false; fibo_heap.keynum++; fibo_heap.rootnum++; if (fibo_heap.min == NULL) { node->left = node->right = node; fibo_heap.min = node; } else { add_fibo_node(node, fibo_heap.min); if (x < fibo_heap.min->key) fibo_heap.min = node; } return -1; } int fibo_heap_build(Fibo_heap &fibo_heap, int*data, int n, Fibo_node*, int)//�����˳�ʼ�� { fibo_heap.rootnum = 0; fibo_heap.keynum = 0; fibo_heap.maxdegree = 0; fibo_heap.min = NULL; for (int i = 0; i < n; i++) { fibo_heap_insert(fibo_heap,NULL, -1,NULL,data[i]); } return 1; } void print_fibo(Fibo_heap fibo_heap) { if (fibo_heap.keynum == 0) return; Fibo_node*p= fibo_heap.min->left,*next_p=fibo_heap.min; Fibo_node*end = p; do { p = next_p; next_p = p->right; printf("%d\n", p->key); } while (p != end); printf("\n\n"); } int fibo_heap_extract_min(Fibo_heap &fibo_heap, int *, int, Fibo_node*, int) { Fibo_node *z = fibo_heap.min; //print_fibo(fibo_heap); if (!z) { printf("heap is empty\n"); return -1; } else { int i = 0; for (Fibo_node *x = z->child; i < z->degreee; i++) { //��z��ÿ�����Ӳ��뵽���� Fibo_node*tmp = x->right; add_fibo_node(x, fibo_heap.min); x->parent = NULL; x = tmp; } if (z->right == z) { fibo_heap.min = NULL; fibo_heap.keynum--; } else { //�Ӹ���ɾ����z��Ȼ�����CONSOLIDATE���е��� z->right->left = z->left; z->left->right = z->right; fibo_heap.min = z->right; CONSOLIDATE(fibo_heap); fibo_heap.keynum--; } return z->key;//��û�ͷ� } } void CONSOLIDATE(Fibo_heap &fibo_heap) { //dnΪ��������Ĵ�С int dn = (int)(log(fibo_heap.keynum)/log(2))+1; //print_fibo(fibo_heap); Fibo_node **A = (Fibo_node**)malloc(sizeof(Fibo_node*)*(dn + 1)); for (int i = 0; i < (dn + 1); i++) A[i] = NULL; Fibo_node*end = fibo_heap.min->left; Fibo_node* w = fibo_heap.min->left,*next_w=fibo_heap.min; do { //�����и�����б�����Ȼ���degree��ͬ�ĺϲ� w = next_w; next_w = w->right; Fibo_node *x; x = w; int d = x->degreee; while (A[d]) { //ֻҪ�Ƕ�Ϊd�ĸ��Ѿ����ڶ�����кϲ� Fibo_node *y = A[d]; if (x->key > y->key) { //��֤y��key��x��С Fibo_node*tmp = x; x = y; y = tmp; } fib_heap_link(fibo_heap, y, x);//�ϲ���������ͬ�ĸ� A[d] = NULL; d++;//��ǰx�Ķ�++ } A[d] = x; } while (w != end); int root_num = 0; int min = -1; for (int i = 0; i < (dn + 1); i++)//�ҵ���С�ĸ� { //�Ӹ����еõ���С�ĸ���min if (A[i]) { root_num++; if (min == -1) { min = i; } else if (A[i]->key < A[min]->key) { min = i; } } } fibo_heap.min = A[min]; fibo_heap.rootnum = root_num; free(A); //print_fibo(fibo_heap); return; } void fib_heap_link(Fibo_heap &fibo_heap, Fibo_node*y, Fibo_node*x) { y->left->right = y->right; y->right->left = y->left; if (x->child) { y->left = x->child->left; x->child->left->right = y; y->right = x->child; x->child->left = y; } else { x->child = y; y->left = y->right = y; } y->parent = x; x->degreee++; if (x->degreee > fibo_heap.maxdegree) fibo_heap.maxdegree = x->degreee; y->marked = false; } int fibo_heap_decrease(Fibo_heap &fibo_heap, int *, int, Fibo_node* x, int k) //ֱ���ýڵ� { if (k > x->key) { printf("Ӧ������һ����С��ֵ\n"); return -1; } x->key = k; Fibo_node*y = x->parent; if (y&&x->key < y->key)//Ϊ�˱�����С�ѵ����ԣ�����cut { CUT(fibo_heap, x, y); CASCADING_CUT(fibo_heap, y); } if (x->key < fibo_heap.min->key)//����min fibo_heap.min = x; return 1; } void CUT(Fibo_heap &fibo_heap, Fibo_node *&x, Fibo_node*&y) { if (y->degreee == 1) { y->child = NULL; } else { if (x == y->child) { y->child = x->right; } x->left->right = x->right; x->right->left = x->left; } add_fibo_node(x, fibo_heap.min); x->parent = NULL; x->marked = false; y->degreee--; fibo_heap.rootnum++; } void CASCADING_CUT(Fibo_heap &fibo_heap, Fibo_node *&y) { Fibo_node *z = y->parent; if (z) { if (y->marked == false) { y->marked = true; } else { CUT(fibo_heap, y,z); CASCADING_CUT(fibo_heap, z); } } } Fibo_node *fibo_heap_search(Fibo_node *root, int cousins, int x) { Fibo_node*result; if (!root) { return NULL; } else if (root->key == x) { return root; } if (cousins > 0) { result = fibo_heap_search(root->right, cousins - 1, x); if (result) return result; } if (root->child) { result = fibo_heap_search(root->child, root->degreee - 1, x); if (result) return result; } else return NULL; } int fibo_heap_delete(Fibo_heap &fibo_heap, int *, int, Fibo_node*value, int) { fibo_heap_decrease(fibo_heap,NULL,-1, value, -MYINFINITY); long a=fibo_heap_extract_min(fibo_heap,NULL,-1,NULL,-1); return -1; }
[ "JLPANG1997@outlook.com" ]
JLPANG1997@outlook.com
de03342bfe7cb4d975103fc294c1daa9fae9f237
b1af8bb863a6730e6e4e93129efbad89d33cf509
/SDK/SCUM_Mulberry_parameters.hpp
d1874e487106294ced52e20fb1251d67aa433fae
[]
no_license
frankie-11/SCUM_SDK7.13.2020
b3bbd8fb9b6c03120b865a6254eca6a2389ea654
7b48bcf9e8088aa8917c07dd6756eac90e3f693a
refs/heads/master
2022-11-16T05:48:55.729087
2020-07-13T23:48:50
2020-07-13T23:48:50
279,433,512
0
1
null
null
null
null
UTF-8
C++
false
false
2,325
hpp
#pragma once // SCUM (4.24) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "../SDK.hpp" namespace SDK { //--------------------------------------------------------------------------- //Parameters //--------------------------------------------------------------------------- // Function ConZ.FoodItem.OnRep_Temperature struct AMulberry_C_OnRep_Temperature_Params { }; // Function ConZ.FoodItem.OnRep_ItemOpened struct AMulberry_C_OnRep_ItemOpened_Params { }; // Function ConZ.FoodItem.OnRep_IsCooking struct AMulberry_C_OnRep_IsCooking_Params { }; // Function ConZ.FoodItem.OnAudioComponentExpired struct AMulberry_C_OnAudioComponentExpired_Params { }; // Function ConZ.FoodItem.IsCooking struct AMulberry_C_IsCooking_Params { bool ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) }; // Function ConZ.FoodItem.GetVolume struct AMulberry_C_GetVolume_Params { float ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) }; // Function ConZ.FoodItem.GetThermalConductivityFactor struct AMulberry_C_GetThermalConductivityFactor_Params { float ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) }; // Function ConZ.FoodItem.GetTemperature struct AMulberry_C_GetTemperature_Params { float ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) }; // Function ConZ.FoodItem.GetEnvironmentTemperature struct AMulberry_C_GetEnvironmentTemperature_Params { float ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) }; // Function ConZ.FoodItem.GetCookingAmount struct AMulberry_C_GetCookingAmount_Params { float ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "60810131+frankie-11@users.noreply.github.com" ]
60810131+frankie-11@users.noreply.github.com
5369a6a873ef384967f78f6757db25f9590a353e
26e2c4ab25a742a2fbe4245d8bcac7a19f79b4ef
/TebasakiChronicle/src/Object/Enemy/EnemyType/EnemyTypeManager.h
c3a94755ee14f7c0008f271282c6395491015c97
[]
no_license
feveleK5563/TebasakiChronicle
39e4ee0f18c8612366a22d9aed12d1d4012488ad
f4111b9d0b7b045e4e887992faab8e38626a8ba4
refs/heads/master
2020-03-11T01:34:19.538064
2018-07-18T08:45:59
2018-07-18T08:45:59
129,695,292
0
2
null
null
null
null
SHIFT_JIS
C++
false
false
851
h
#pragma once #include "EnemyType.h" #include "../../../Helper.h" class EnemyTypeManager { public: struct EnemyData //敵情報のまとめ { EnemyType::ParameterData* paramater; EnemyType::CollisionData* collision; std::vector<EnemyMovePattern::MoveSetUpData*> movesetupdata; EnemyData(){} ~EnemyData() { Memory::SafeDelete(paramater); Memory::SafeDelete(collision); for (auto it : movesetupdata) Memory::SafeDelete(it); } }; public: std::vector<EnemyType*> eType; //コンストラクタ EnemyTypeManager(); //デストラクタ ~EnemyTypeManager(); //ファイルを読み込んで敵のデータを作る //引数:読み込むファイルへのパス(string) void CreateEnemyData(EnemyData* ed); //指定番号の敵データのアドレス値を返す EnemyType* GetEnemyTypeData(int enemyNum); };
[ "buncha102828@gmail.com" ]
buncha102828@gmail.com
2f13451c0ccd7ec357b679c3676c54203785618a
5a908aa642ecddf009849e33172ad3da9469c78f
/src/ast2ram/provenance/ConstraintTranslator.cpp
b234d6492336abdbe7526b6357e8110588106a00
[ "UPL-1.0" ]
permissive
LittleLightLittleFire/souffle
63a93a613d69d195a9c19ea190daecfed8b186b5
468213129729fe2ac17d6e666105e5adb6dae5eb
refs/heads/master
2021-08-18T02:46:03.372142
2021-01-27T00:39:19
2021-01-27T00:39:19
93,007,429
0
0
null
2017-06-01T02:19:23
2017-06-01T02:19:22
null
UTF-8
C++
false
false
1,761
cpp
/* * Souffle - A Datalog Compiler * Copyright (c) 2020 The Souffle Developers. All rights reserved * Licensed under the Universal Permissive License v 1.0 as shown at: * - https://opensource.org/licenses/UPL * - <souffle root>/licenses/SOUFFLE-UPL.txt */ /************************************************************************ * * @file ConstraintTranslator.cpp * ***********************************************************************/ #include "ast2ram/provenance/ConstraintTranslator.h" #include "ast/Atom.h" #include "ast/TranslationUnit.h" #include "ast2ram/ValueTranslator.h" #include "ast2ram/utility/TranslatorContext.h" #include "ast2ram/utility/Utils.h" #include "ast2ram/utility/ValueIndex.h" #include "ram/ExistenceCheck.h" #include "ram/Negation.h" #include "ram/UndefValue.h" namespace souffle::ast2ram::provenance { Own<ram::Condition> ConstraintTranslator::translateConstraint(const ast::Literal* lit) { assert(lit != nullptr && "literal should be defined"); return ConstraintTranslator(context, symbolTable, index)(*lit); } Own<ram::Condition> ConstraintTranslator::visit_(type_identity<ast::Negation>, const ast::Negation& neg) { // construct the atom and create a negation const auto* atom = neg.getAtom(); VecOwn<ram::Expression> values; // actual arguments for (const auto* arg : atom->getArguments()) { values.push_back(context.translateValue(symbolTable, index, arg)); } // add rule + level number values.push_back(mk<ram::UndefValue>()); values.push_back(mk<ram::UndefValue>()); return mk<ram::Negation>( mk<ram::ExistenceCheck>(getConcreteRelationName(atom->getQualifiedName()), std::move(values))); } } // namespace souffle::ast2ram::provenance
[ "azre6702@uni.sydney.edu.au" ]
azre6702@uni.sydney.edu.au
c1569d495db517fad99d178efc35e8eaa42ceba7
99249e222a2f35ac11a7fd93bff10a3a13f6f948
/ros2_mod_ws/install/include/robobo_msgs_aux/srv/play_sound__traits.hpp
eafe5c2d216c7b1826e092c441fdeabe7b1bda8e
[ "Apache-2.0" ]
permissive
mintforpeople/robobo-ros2-ios-port
87aec17a0c89c3fc5a42411822a18f08af8a5b0f
1a5650304bd41060925ebba41d6c861d5062bfae
refs/heads/master
2020-08-31T19:41:01.124753
2019-10-31T16:01:11
2019-10-31T16:01:11
218,764,551
1
0
null
null
null
null
UTF-8
C++
false
false
1,185
hpp
// generated from rosidl_generator_cpp/resource/srv__traits.hpp.em // generated code does not contain a copyright notice #include "robobo_msgs_aux/srv/play_sound__struct.hpp" #ifndef ROBOBO_MSGS_AUX__SRV__PLAY_SOUND__TRAITS_HPP_ #define ROBOBO_MSGS_AUX__SRV__PLAY_SOUND__TRAITS_HPP_ namespace rosidl_generator_traits { #ifndef __ROSIDL_GENERATOR_CPP_TRAITS #define __ROSIDL_GENERATOR_CPP_TRAITS template<typename T> struct has_fixed_size : std::false_type {}; template<typename T> struct has_bounded_size : std::false_type {}; #endif // __ROSIDL_GENERATOR_CPP_TRAITS template<> struct has_fixed_size<robobo_msgs_aux::srv::PlaySound> : std::integral_constant< bool, has_fixed_size<robobo_msgs_aux::srv::PlaySound_Request>::value && has_fixed_size<robobo_msgs_aux::srv::PlaySound_Response>::value > { }; template<> struct has_bounded_size<robobo_msgs_aux::srv::PlaySound> : std::integral_constant< bool, has_bounded_size<robobo_msgs_aux::srv::PlaySound_Request>::value && has_bounded_size<robobo_msgs_aux::srv::PlaySound_Response>::value > { }; } // namespace rosidl_generator_traits #endif // ROBOBO_MSGS_AUX__SRV__PLAY_SOUND__TRAITS_HPP_
[ "lfllamas93@gmail.com" ]
lfllamas93@gmail.com
6f9ac6c7fece6679b56488c6f29f392d2f09d111
2013049b2718bc6f77f471f7b3a0d3da7b212f03
/216-1m.cpp
203ac9de7c10726631cd5b839b4b3dffdc5d01af
[]
no_license
sky58/TopcoderSRM_AcceptedCodes
084a9de1bb7285681f0e5128c72f2fb064d626f1
de20a696261e56824754ba0031ab992cb6b757ea
refs/heads/master
2020-05-20T04:45:32.935744
2015-04-08T03:42:24
2015-04-08T03:42:24
33,550,779
0
0
null
null
null
null
UTF-8
C++
false
false
878
cpp
//SRM216DIV1-500 Refactoring #include<vector> #include<cmath> #include<map> #include<cstdlib> #include<iostream> #include<sstream> #include<string> #include<algorithm> #include<cstring> #include<cstdio> #include<set> #include<stack> #include<bitset> #include<functional> #include<cstdlib> #include<ctime> #include<queue> #include<deque> using namespace std; #define pb push_back #define pf push_front typedef long long lint; #define mp make_pair #define fi first #define se second typedef pair<int,int> pint; #define All(s) s.begin(),s.end() #define rAll(s) s.rbegin(),s.rend() #define REP(i,a,b) for(i=a;i<b;i++) #define rep(i,n) REP(i,0,n) int rec(int a,int b){ int ret=1,i; for(i=a;i*i<=b;i++){ int c=b; while(c%i==0){ c/=i; if(i<=c) ret+=rec(i+1,c); } } return ret; } class Refactoring{ public: int Refactoring::refactor(int a){ return rec(2,a)-1; } };
[ "skyaozora@gmail.com" ]
skyaozora@gmail.com
5e803d16945fb5c17022063989f6933c748590b5
a9931d6ad4d99ed9458b11ee4ce95f6a5de5d4aa
/Baekjoon-Judge-Project/10952.cpp
ff0d5d32de51aa74dc7c2d6755884954343e648d
[]
no_license
StevenKim1994/Baekjoon-Judge
919498c9e1fd0b617078a7cfcada2ec4a54f0b93
7ed646455a85987199776533fa411c3ea2f2f69a
refs/heads/master
2022-07-18T21:41:37.739027
2022-06-24T13:11:23
2022-06-24T13:11:23
112,476,967
1
0
null
null
null
null
UTF-8
C++
false
false
229
cpp
#include <iostream> int main() { std::cin.tie(NULL); std::ios_base::sync_with_stdio(false); short A, B; while (true) { std::cin >> A >> B; if (A == 0 && B == 0) break; std::cout << A + B << '\n'; } return 0; }
[ "dev@donga.ac.kr" ]
dev@donga.ac.kr
cdfe18cbad6d9ebaa765c8c362ec239ba190ef0d
50c884b8b7e06074056549c238eebfa4935cf034
/media/gpu/v4l2/v4l2_slice_video_decode_accelerator.cc
74219c29189355b447ec4a274452509fcab70a04
[ "BSD-3-Clause" ]
permissive
stanhuff/chromium
321ce7ad62755d714b7814ad46fcdc72f9647370
306663d182d154e3a7f6cf089ef1acb0c1cb4164
refs/heads/master
2023-03-02T21:07:16.058891
2019-11-29T18:35:13
2019-11-29T18:35:13
224,907,296
0
0
BSD-3-Clause
2019-11-29T18:52:14
2019-11-29T18:52:13
null
UTF-8
C++
false
false
88,164
cc
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "media/gpu/v4l2/v4l2_slice_video_decode_accelerator.h" #include <errno.h> #include <fcntl.h> #include <linux/media.h> #include <linux/videodev2.h> #include <poll.h> #include <string.h> #include <sys/eventfd.h> #include <sys/ioctl.h> #include <sys/mman.h> #include <memory> #include "base/bind.h" #include "base/bind_helpers.h" #include "base/callback.h" #include "base/callback_helpers.h" #include "base/command_line.h" #include "base/memory/ptr_util.h" #include "base/numerics/safe_conversions.h" #include "base/posix/eintr_wrapper.h" #include "base/single_thread_task_runner.h" #include "base/stl_util.h" #include "base/strings/stringprintf.h" #include "base/threading/thread_task_runner_handle.h" #include "base/time/time.h" #include "base/trace_event/memory_dump_manager.h" #include "base/trace_event/trace_event.h" #include "media/base/bind_to_current_loop.h" #include "media/base/media_switches.h" #include "media/base/scopedfd_helper.h" #include "media/base/unaligned_shared_memory.h" #include "media/base/video_types.h" #include "media/gpu/chromeos/fourcc.h" #include "media/gpu/macros.h" #include "media/gpu/v4l2/v4l2_decode_surface.h" #include "media/gpu/v4l2/v4l2_h264_accelerator.h" #include "media/gpu/v4l2/v4l2_h264_accelerator_legacy.h" #include "media/gpu/v4l2/v4l2_image_processor.h" #include "media/gpu/v4l2/v4l2_vda_helpers.h" #include "media/gpu/v4l2/v4l2_vp8_accelerator.h" #include "media/gpu/v4l2/v4l2_vp8_accelerator_legacy.h" #include "media/gpu/v4l2/v4l2_vp9_accelerator.h" #include "ui/gl/gl_context.h" #include "ui/gl/gl_image.h" #include "ui/gl/scoped_binders.h" #define NOTIFY_ERROR(x) \ do { \ VLOGF(1) << "Setting error state: " << x; \ SetErrorState(x); \ } while (0) #define IOCTL_OR_ERROR_RETURN_VALUE(type, arg, value, type_str) \ do { \ if (device_->Ioctl(type, arg) != 0) { \ VPLOGF(1) << "ioctl() failed: " << type_str; \ return value; \ } \ } while (0) #define IOCTL_OR_ERROR_RETURN(type, arg) \ IOCTL_OR_ERROR_RETURN_VALUE(type, arg, ((void)0), #type) #define IOCTL_OR_ERROR_RETURN_FALSE(type, arg) \ IOCTL_OR_ERROR_RETURN_VALUE(type, arg, false, #type) #define IOCTL_OR_LOG_ERROR(type, arg) \ do { \ if (device_->Ioctl(type, arg) != 0) \ VPLOGF(1) << "ioctl() failed: " << #type; \ } while (0) namespace media { // static const uint32_t V4L2SliceVideoDecodeAccelerator::supported_input_fourccs_[] = { V4L2_PIX_FMT_H264_SLICE, V4L2_PIX_FMT_VP8_FRAME, V4L2_PIX_FMT_VP9_FRAME, }; V4L2SliceVideoDecodeAccelerator::OutputRecord::OutputRecord() : picture_id(-1), texture_id(0), cleared(false), num_times_sent_to_client(0) {} V4L2SliceVideoDecodeAccelerator::OutputRecord::OutputRecord(OutputRecord&&) = default; V4L2SliceVideoDecodeAccelerator::OutputRecord::~OutputRecord() = default; struct V4L2SliceVideoDecodeAccelerator::BitstreamBufferRef { BitstreamBufferRef( base::WeakPtr<VideoDecodeAccelerator::Client>& client, const scoped_refptr<base::SingleThreadTaskRunner>& client_task_runner, scoped_refptr<DecoderBuffer> buffer, int32_t input_id); ~BitstreamBufferRef(); const base::WeakPtr<VideoDecodeAccelerator::Client> client; const scoped_refptr<base::SingleThreadTaskRunner> client_task_runner; scoped_refptr<DecoderBuffer> buffer; off_t bytes_used; const int32_t input_id; }; V4L2SliceVideoDecodeAccelerator::BitstreamBufferRef::BitstreamBufferRef( base::WeakPtr<VideoDecodeAccelerator::Client>& client, const scoped_refptr<base::SingleThreadTaskRunner>& client_task_runner, scoped_refptr<DecoderBuffer> buffer, int32_t input_id) : client(client), client_task_runner(client_task_runner), buffer(std::move(buffer)), bytes_used(0), input_id(input_id) {} V4L2SliceVideoDecodeAccelerator::BitstreamBufferRef::~BitstreamBufferRef() { if (input_id >= 0) { DVLOGF(5) << "returning input_id: " << input_id; client_task_runner->PostTask( FROM_HERE, base::BindOnce( &VideoDecodeAccelerator::Client::NotifyEndOfBitstreamBuffer, client, input_id)); } } V4L2SliceVideoDecodeAccelerator::PictureRecord::PictureRecord( bool cleared, const Picture& picture) : cleared(cleared), picture(picture) {} V4L2SliceVideoDecodeAccelerator::PictureRecord::~PictureRecord() {} V4L2SliceVideoDecodeAccelerator::V4L2SliceVideoDecodeAccelerator( const scoped_refptr<V4L2Device>& device, EGLDisplay egl_display, const BindGLImageCallback& bind_image_cb, const MakeGLContextCurrentCallback& make_context_current_cb) : input_planes_count_(0), output_planes_count_(0), child_task_runner_(base::ThreadTaskRunnerHandle::Get()), device_(device), decoder_thread_("V4L2SliceVideoDecodeAcceleratorThread"), video_profile_(VIDEO_CODEC_PROFILE_UNKNOWN), input_format_fourcc_(0), output_format_fourcc_(0), state_(kUninitialized), output_mode_(Config::OutputMode::ALLOCATE), decoder_flushing_(false), decoder_resetting_(false), surface_set_change_pending_(false), picture_clearing_count_(0), egl_display_(egl_display), bind_image_cb_(bind_image_cb), make_context_current_cb_(make_context_current_cb), gl_image_format_fourcc_(0), gl_image_planes_count_(0), weak_this_factory_(this) { weak_this_ = weak_this_factory_.GetWeakPtr(); } V4L2SliceVideoDecodeAccelerator::~V4L2SliceVideoDecodeAccelerator() { DVLOGF(2); DCHECK(child_task_runner_->BelongsToCurrentThread()); DCHECK(!decoder_thread_.IsRunning()); DCHECK(requests_.empty()); DCHECK(output_buffer_map_.empty()); } void V4L2SliceVideoDecodeAccelerator::NotifyError(Error error) { // Notifying the client should only happen from the client's thread. if (!child_task_runner_->BelongsToCurrentThread()) { child_task_runner_->PostTask( FROM_HERE, base::BindOnce(&V4L2SliceVideoDecodeAccelerator::NotifyError, weak_this_, error)); return; } // Notify the decoder's client an error has occurred. if (client_) { client_->NotifyError(error); client_ptr_factory_.reset(); } } bool V4L2SliceVideoDecodeAccelerator::Initialize(const Config& config, Client* client) { VLOGF(2) << "profile: " << config.profile; DCHECK(child_task_runner_->BelongsToCurrentThread()); DCHECK_EQ(state_, kUninitialized); if (config.is_encrypted()) { NOTREACHED() << "Encrypted streams are not supported for this VDA"; return false; } if (config.output_mode != Config::OutputMode::ALLOCATE && config.output_mode != Config::OutputMode::IMPORT) { NOTREACHED() << "Only ALLOCATE and IMPORT OutputModes are supported"; return false; } client_ptr_factory_.reset( new base::WeakPtrFactory<VideoDecodeAccelerator::Client>(client)); client_ = client_ptr_factory_->GetWeakPtr(); // If we haven't been set up to decode on separate thread via // TryToSetupDecodeOnSeparateThread(), use the main thread/client for // decode tasks. if (!decode_task_runner_) { decode_task_runner_ = child_task_runner_; DCHECK(!decode_client_); decode_client_ = client_; } // We need the context to be initialized to query extensions. if (make_context_current_cb_) { if (egl_display_ == EGL_NO_DISPLAY) { VLOGF(1) << "could not get EGLDisplay"; return false; } if (!make_context_current_cb_.Run()) { VLOGF(1) << "could not make context current"; return false; } if (!gl::g_driver_egl.ext.b_EGL_KHR_fence_sync) { VLOGF(1) << "context does not have EGL_KHR_fence_sync"; return false; } } else { DVLOGF(2) << "No GL callbacks provided, initializing without GL support"; } video_profile_ = config.profile; input_planes_count_ = 1; input_format_fourcc_ = V4L2Device::VideoCodecProfileToV4L2PixFmt(video_profile_, true); if (!input_format_fourcc_ || !device_->Open(V4L2Device::Type::kDecoder, input_format_fourcc_)) { VLOGF(1) << "Failed to open device for profile: " << config.profile << " fourcc: " << FourccToString(input_format_fourcc_); return false; } struct v4l2_requestbuffers reqbufs; memset(&reqbufs, 0, sizeof(reqbufs)); reqbufs.count = 0; reqbufs.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE; reqbufs.memory = V4L2_MEMORY_MMAP; IOCTL_OR_ERROR_RETURN_FALSE(VIDIOC_REQBUFS, &reqbufs); if (reqbufs.capabilities & V4L2_BUF_CAP_SUPPORTS_REQUESTS) { supports_requests_ = true; VLOGF(1) << "Using request API"; DCHECK(!media_fd_.is_valid()); // Let's try to open the media device // TODO(crbug.com/985230): remove this hardcoding, replace with V4L2Device // integration. int media_fd = open("/dev/media-dec0", O_RDWR, 0); if (media_fd < 0) { VPLOGF(1) << "Failed to open media device: "; NOTIFY_ERROR(PLATFORM_FAILURE); } media_fd_ = base::ScopedFD(media_fd); } else { VLOGF(1) << "Using config store"; } // Check if |video_profile_| is supported by a decoder driver. if (!IsSupportedProfile(video_profile_)) { VLOGF(1) << "Unsupported profile " << GetProfileName(video_profile_); return false; } if (video_profile_ >= H264PROFILE_MIN && video_profile_ <= H264PROFILE_MAX) { if (supports_requests_) { decoder_.reset(new H264Decoder( std::make_unique<V4L2H264Accelerator>(this, device_.get()), video_profile_)); } else { decoder_.reset(new H264Decoder( std::make_unique<V4L2LegacyH264Accelerator>(this, device_.get()), video_profile_)); } } else if (video_profile_ >= VP8PROFILE_MIN && video_profile_ <= VP8PROFILE_MAX) { if (supports_requests_) { decoder_.reset(new VP8Decoder( std::make_unique<V4L2VP8Accelerator>(this, device_.get()))); } else { decoder_.reset(new VP8Decoder( std::make_unique<V4L2LegacyVP8Accelerator>(this, device_.get()))); } } else if (video_profile_ >= VP9PROFILE_MIN && video_profile_ <= VP9PROFILE_MAX) { decoder_.reset(new VP9Decoder( std::make_unique<V4L2VP9Accelerator>(this, device_.get()), video_profile_)); } else { NOTREACHED() << "Unsupported profile " << GetProfileName(video_profile_); return false; } // Capabilities check. struct v4l2_capability caps; const __u32 kCapsRequired = V4L2_CAP_VIDEO_M2M_MPLANE | V4L2_CAP_STREAMING; IOCTL_OR_ERROR_RETURN_FALSE(VIDIOC_QUERYCAP, &caps); if ((caps.capabilities & kCapsRequired) != kCapsRequired) { VLOGF(1) << "ioctl() failed: VIDIOC_QUERYCAP" << ", caps check failed: 0x" << std::hex << caps.capabilities; return false; } if (!SetupFormats()) return false; if (!decoder_thread_.Start()) { VLOGF(1) << "device thread failed to start"; return false; } decoder_thread_task_runner_ = decoder_thread_.task_runner(); base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider( this, "media::V4l2SliceVideoDecodeAccelerator", decoder_thread_task_runner_); state_ = kInitialized; output_mode_ = config.output_mode; // InitializeTask will NOTIFY_ERROR on failure. decoder_thread_task_runner_->PostTask( FROM_HERE, base::BindOnce(&V4L2SliceVideoDecodeAccelerator::InitializeTask, base::Unretained(this))); VLOGF(2) << "V4L2SliceVideoDecodeAccelerator initialized"; return true; } void V4L2SliceVideoDecodeAccelerator::InitializeTask() { VLOGF(2); DCHECK(decoder_thread_task_runner_->BelongsToCurrentThread()); DCHECK_EQ(state_, kInitialized); TRACE_EVENT0("media,gpu", "V4L2SVDA::InitializeTask"); if (IsDestroyPending()) return; input_queue_ = device_->GetQueue(V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE); output_queue_ = device_->GetQueue(V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE); if (!input_queue_ || !output_queue_) { NOTIFY_ERROR(PLATFORM_FAILURE); return; } if (!CreateInputBuffers()) NOTIFY_ERROR(PLATFORM_FAILURE); // Output buffers will be created once decoder gives us information // about their size and required count. state_ = kDecoding; } void V4L2SliceVideoDecodeAccelerator::Destroy() { VLOGF(2); DCHECK(child_task_runner_->BelongsToCurrentThread()); // Signal any waiting/sleeping tasks to early exit as soon as possible to // avoid waiting too long for the decoder_thread_ to Stop(). destroy_pending_.Signal(); weak_this_factory_.InvalidateWeakPtrs(); if (decoder_thread_.IsRunning()) { decoder_thread_task_runner_->PostTask( FROM_HERE, // The image processor's destructor may post new tasks to // |decoder_thread_task_runner_|. In order to make sure that // DestroyTask() runs last, we perform shutdown in two stages: // 1) Destroy image processor so that no new task it posted by it // 2) Post DestroyTask to |decoder_thread_task_runner_| so that it // executes after all the tasks potentially posted by the IP. base::BindOnce( [](V4L2SliceVideoDecodeAccelerator* vda) { vda->gl_image_device_ = nullptr; // The image processor's thread was the user of the image // processor device, so let it keep the last reference and destroy // it in its own thread. vda->image_processor_device_ = nullptr; vda->image_processor_ = nullptr; vda->surfaces_at_ip_ = {}; vda->decoder_thread_task_runner_->PostTask( FROM_HERE, base::BindOnce(&V4L2SliceVideoDecodeAccelerator::DestroyTask, base::Unretained(vda))); }, base::Unretained(this))); // Wait for tasks to finish/early-exit. decoder_thread_.Stop(); } delete this; VLOGF(2) << "Destroyed"; } void V4L2SliceVideoDecodeAccelerator::DestroyTask() { DVLOGF(2); DCHECK(decoder_thread_task_runner_->BelongsToCurrentThread()); TRACE_EVENT0("media,gpu", "V4L2SVDA::DestroyTask"); state_ = kDestroying; decoder_->Reset(); decoder_current_bitstream_buffer_.reset(); while (!decoder_input_queue_.empty()) decoder_input_queue_.pop_front(); // Stop streaming and the device_poll_thread_. StopDevicePoll(); DestroyInputBuffers(); DestroyOutputs(false); media_fd_.reset(); input_queue_ = nullptr; output_queue_ = nullptr; base::trace_event::MemoryDumpManager::GetInstance()->UnregisterDumpProvider( this); // Clear the V4L2 devices in the decoder thread so the V4L2Device's // destructor is called from the thread that used it. device_ = nullptr; DCHECK(surfaces_at_device_.empty()); DCHECK(surfaces_at_display_.empty()); DCHECK(decoder_display_queue_.empty()); } bool V4L2SliceVideoDecodeAccelerator::SetupFormats() { DCHECK_EQ(state_, kUninitialized); size_t input_size; gfx::Size max_resolution, min_resolution; device_->GetSupportedResolution(input_format_fourcc_, &min_resolution, &max_resolution); if (max_resolution.width() > 1920 && max_resolution.height() > 1088) input_size = kInputBufferMaxSizeFor4k; else input_size = kInputBufferMaxSizeFor1080p; struct v4l2_fmtdesc fmtdesc; memset(&fmtdesc, 0, sizeof(fmtdesc)); fmtdesc.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE; bool is_format_supported = false; while (device_->Ioctl(VIDIOC_ENUM_FMT, &fmtdesc) == 0) { if (fmtdesc.pixelformat == input_format_fourcc_) { is_format_supported = true; break; } ++fmtdesc.index; } if (!is_format_supported) { DVLOGF(1) << "Input fourcc " << input_format_fourcc_ << " not supported by device."; return false; } struct v4l2_format format; memset(&format, 0, sizeof(format)); format.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE; format.fmt.pix_mp.pixelformat = input_format_fourcc_; format.fmt.pix_mp.plane_fmt[0].sizeimage = input_size; format.fmt.pix_mp.num_planes = input_planes_count_; IOCTL_OR_ERROR_RETURN_FALSE(VIDIOC_S_FMT, &format); DCHECK_EQ(format.fmt.pix_mp.pixelformat, input_format_fourcc_); // We have to set up the format for output, because the driver may not allow // changing it once we start streaming; whether it can support our chosen // output format or not may depend on the input format. memset(&fmtdesc, 0, sizeof(fmtdesc)); fmtdesc.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE; output_format_fourcc_ = 0; while (device_->Ioctl(VIDIOC_ENUM_FMT, &fmtdesc) == 0) { if (device_->CanCreateEGLImageFrom(fmtdesc.pixelformat)) { output_format_fourcc_ = fmtdesc.pixelformat; break; } ++fmtdesc.index; } DCHECK(!image_processor_device_); if (output_format_fourcc_ == 0) { VLOGF(2) << "Could not find a usable output format. Trying image processor"; if (!V4L2ImageProcessor::IsSupported()) { VLOGF(1) << "Image processor not available"; return false; } image_processor_device_ = V4L2Device::Create(); if (!image_processor_device_) { VLOGF(1) << "Could not create a V4L2Device for image processor"; return false; } output_format_fourcc_ = v4l2_vda_helpers::FindImageProcessorInputFormat(device_.get()); if (output_format_fourcc_ == 0) { VLOGF(1) << "Can't find a usable input format from image processor"; return false; } gl_image_format_fourcc_ = v4l2_vda_helpers::FindImageProcessorOutputFormat( image_processor_device_.get()); if (gl_image_format_fourcc_ == 0) { VLOGF(1) << "Can't find a usable output format from image processor"; return false; } gl_image_planes_count_ = V4L2Device::GetNumPlanesOfV4L2PixFmt(gl_image_format_fourcc_); output_planes_count_ = V4L2Device::GetNumPlanesOfV4L2PixFmt(output_format_fourcc_); gl_image_device_ = image_processor_device_; } else { gl_image_format_fourcc_ = output_format_fourcc_; output_planes_count_ = gl_image_planes_count_ = V4L2Device::GetNumPlanesOfV4L2PixFmt(output_format_fourcc_); gl_image_device_ = device_; } // Only set fourcc for output; resolution, etc., will come from the // driver once it extracts it from the stream. memset(&format, 0, sizeof(format)); format.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE; format.fmt.pix_mp.pixelformat = output_format_fourcc_; format.fmt.pix_mp.num_planes = V4L2Device::GetNumPlanesOfV4L2PixFmt(output_format_fourcc_); IOCTL_OR_ERROR_RETURN_FALSE(VIDIOC_S_FMT, &format); DCHECK_EQ(format.fmt.pix_mp.pixelformat, output_format_fourcc_); DCHECK_EQ(static_cast<size_t>(format.fmt.pix_mp.num_planes), output_planes_count_); return true; } bool V4L2SliceVideoDecodeAccelerator::ResetImageProcessor() { VLOGF(2); DCHECK(decoder_thread_.task_runner()->BelongsToCurrentThread()); DCHECK(image_processor_); if (!image_processor_->Reset()) return false; surfaces_at_ip_ = {}; return true; } bool V4L2SliceVideoDecodeAccelerator::CreateImageProcessor() { VLOGF(2); DCHECK(decoder_thread_.task_runner()->BelongsToCurrentThread()); DCHECK(!image_processor_); const ImageProcessor::OutputMode image_processor_output_mode = (output_mode_ == Config::OutputMode::ALLOCATE ? ImageProcessor::OutputMode::ALLOCATE : ImageProcessor::OutputMode::IMPORT); image_processor_ = v4l2_vda_helpers::CreateImageProcessor( output_format_fourcc_, gl_image_format_fourcc_, coded_size_, gl_image_size_, decoder_->GetVisibleRect().size(), output_buffer_map_.size(), image_processor_device_, image_processor_output_mode, // Unretained(this) is safe for ErrorCB because |decoder_thread_| is owned // by this V4L2VideoDecodeAccelerator and |this| must be valid when // ErrorCB is executed. decoder_thread_.task_runner(), base::BindRepeating(&V4L2SliceVideoDecodeAccelerator::ImageProcessorError, base::Unretained(this))); if (!image_processor_) { VLOGF(1) << "Error creating image processor"; NOTIFY_ERROR(PLATFORM_FAILURE); return false; } DCHECK_EQ(gl_image_size_, image_processor_->output_config().size); return true; } bool V4L2SliceVideoDecodeAccelerator::CreateInputBuffers() { VLOGF(2); DCHECK(decoder_thread_task_runner_->BelongsToCurrentThread()); DCHECK(!input_queue_->IsStreaming()); if (input_queue_->AllocateBuffers(kNumInputBuffers, V4L2_MEMORY_MMAP) < kNumInputBuffers) { NOTIFY_ERROR(PLATFORM_FAILURE); return false; } // The remainder of this method only applies if requests are used. if (!supports_requests_) return true; DCHECK(requests_.empty()); DCHECK(media_fd_.is_valid()); for (size_t i = 0; i < input_queue_->AllocatedBuffersCount(); i++) { int request_fd; int ret = HANDLE_EINTR( ioctl(media_fd_.get(), MEDIA_IOC_REQUEST_ALLOC, &request_fd)); if (ret < 0) { VPLOGF(1) << "Failed to create request: "; return false; } requests_.push(base::ScopedFD(request_fd)); } DCHECK_EQ(requests_.size(), input_queue_->AllocatedBuffersCount()); return true; } bool V4L2SliceVideoDecodeAccelerator::CreateOutputBuffers() { VLOGF(2); DCHECK(decoder_thread_task_runner_->BelongsToCurrentThread()); DCHECK(!output_queue_->IsStreaming()); DCHECK(output_buffer_map_.empty()); DCHECK(surfaces_at_display_.empty()); DCHECK(surfaces_at_ip_.empty()); DCHECK(surfaces_at_device_.empty()); gfx::Size pic_size = decoder_->GetPicSize(); size_t num_pictures = decoder_->GetRequiredNumOfPictures(); DCHECK_GT(num_pictures, 0u); DCHECK(!pic_size.IsEmpty()); // Since VdaVideoDecoder doesn't allocate PictureBuffer with size adjusted by // itself, we have to adjust here. struct v4l2_format format; memset(&format, 0, sizeof(format)); format.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE; if (device_->Ioctl(VIDIOC_G_FMT, &format) != 0) { VPLOGF(1) << "Failed getting OUTPUT format"; NOTIFY_ERROR(PLATFORM_FAILURE); return false; } format.fmt.pix_mp.width = pic_size.width(); format.fmt.pix_mp.height = pic_size.height(); if (device_->Ioctl(VIDIOC_S_FMT, &format) != 0) { VPLOGF(1) << "Failed setting OUTPUT format to: " << input_format_fourcc_; NOTIFY_ERROR(PLATFORM_FAILURE); return false; } // Get the coded size from the CAPTURE queue memset(&format, 0, sizeof(format)); format.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE; if (device_->Ioctl(VIDIOC_G_FMT, &format) != 0) { VPLOGF(1) << "Failed getting CAPTURE format"; NOTIFY_ERROR(PLATFORM_FAILURE); return false; } coded_size_.SetSize(base::checked_cast<int>(format.fmt.pix_mp.width), base::checked_cast<int>(format.fmt.pix_mp.height)); DCHECK_EQ(coded_size_.width() % 16, 0); DCHECK_EQ(coded_size_.height() % 16, 0); // Now that we know the desired buffers resolution, ask the image processor // what it supports so we can request the correct picture buffers. if (image_processor_device_) { // Try to get an image size as close as possible to the final one (i.e. // coded_size_ may include padding required by the decoder). gl_image_size_ = pic_size; size_t planes_count; if (!V4L2ImageProcessor::TryOutputFormat( output_format_fourcc_, gl_image_format_fourcc_, coded_size_, &gl_image_size_, &planes_count)) { VLOGF(1) << "Failed to get output size and plane count of IP"; return false; } if (gl_image_planes_count_ != planes_count) { VLOGF(1) << "IP buffers planes count returned by V4L2 (" << planes_count << ") doesn't match the computed number (" << gl_image_planes_count_ << ")"; return false; } } else { gl_image_size_ = coded_size_; } if (!gfx::Rect(coded_size_).Contains(gfx::Rect(pic_size))) { VLOGF(1) << "Got invalid adjusted coded size: " << coded_size_.ToString(); return false; } DVLOGF(3) << "buffer_count=" << num_pictures << ", pic size=" << pic_size.ToString() << ", coded size=" << coded_size_.ToString(); VideoPixelFormat pixel_format = Fourcc::FromV4L2PixFmt(gl_image_format_fourcc_).ToVideoPixelFormat(); child_task_runner_->PostTask( FROM_HERE, base::BindOnce( &VideoDecodeAccelerator::Client::ProvidePictureBuffersWithVisibleRect, client_, num_pictures, pixel_format, 1, gl_image_size_, decoder_->GetVisibleRect(), device_->GetTextureTarget())); // Go into kAwaitingPictureBuffers to prevent us from doing any more decoding // or event handling while we are waiting for AssignPictureBuffers(). Not // having Pictures available would not have prevented us from making decoding // progress entirely e.g. in the case of H.264 where we could further decode // non-slice NALUs and could even get another resolution change before we were // done with this one. After we get the buffers, we'll go back into kIdle and // kick off further event processing, and eventually go back into kDecoding // once no more events are pending (if any). state_ = kAwaitingPictureBuffers; return true; } void V4L2SliceVideoDecodeAccelerator::DestroyInputBuffers() { VLOGF(2); DCHECK(decoder_thread_task_runner_->BelongsToCurrentThread() || !decoder_thread_.IsRunning()); if (!input_queue_) return; DCHECK(!input_queue_->IsStreaming()); input_queue_->DeallocateBuffers(); if (supports_requests_) requests_ = {}; } void V4L2SliceVideoDecodeAccelerator::DismissPictures( const std::vector<int32_t>& picture_buffer_ids, base::WaitableEvent* done) { DVLOGF(3); DCHECK(child_task_runner_->BelongsToCurrentThread()); for (auto picture_buffer_id : picture_buffer_ids) { DVLOGF(4) << "dismissing PictureBuffer id=" << picture_buffer_id; client_->DismissPictureBuffer(picture_buffer_id); } done->Signal(); } void V4L2SliceVideoDecodeAccelerator::ServiceDeviceTask(bool event) { DVLOGF(4); DCHECK(decoder_thread_task_runner_->BelongsToCurrentThread()); DVLOGF(3) << "buffer counts: " << "INPUT[" << decoder_input_queue_.size() << "]" << " => DEVICE[" << input_queue_->FreeBuffersCount() << "+" << input_queue_->QueuedBuffersCount() << "/" << input_queue_->AllocatedBuffersCount() << "]->[" << output_queue_->FreeBuffersCount() << "+" << output_queue_->QueuedBuffersCount() << "/" << output_buffer_map_.size() << "]" << " => DISPLAYQ[" << decoder_display_queue_.size() << "]" << " => CLIENT[" << surfaces_at_display_.size() << "]"; if (IsDestroyPending()) return; Dequeue(); } void V4L2SliceVideoDecodeAccelerator::Enqueue( const scoped_refptr<V4L2DecodeSurface>& dec_surface) { DCHECK(decoder_thread_task_runner_->BelongsToCurrentThread()); if (!EnqueueInputRecord(dec_surface.get())) { VLOGF(1) << "Failed queueing an input buffer"; NOTIFY_ERROR(PLATFORM_FAILURE); return; } if (!EnqueueOutputRecord(dec_surface.get())) { VLOGF(1) << "Failed queueing an output buffer"; NOTIFY_ERROR(PLATFORM_FAILURE); return; } surfaces_at_device_.push(dec_surface); } void V4L2SliceVideoDecodeAccelerator::Dequeue() { DVLOGF(4); DCHECK(decoder_thread_task_runner_->BelongsToCurrentThread()); while (input_queue_->QueuedBuffersCount() > 0) { DCHECK(input_queue_->IsStreaming()); auto ret = input_queue_->DequeueBuffer(); if (ret.first == false) { NOTIFY_ERROR(PLATFORM_FAILURE); return; } else if (!ret.second) { // we're just out of buffers to dequeue. break; } DVLOGF(4) << "Dequeued input=" << ret.second->BufferId() << " count: " << input_queue_->QueuedBuffersCount(); } while (output_queue_->QueuedBuffersCount() > 0) { DCHECK(output_queue_->IsStreaming()); auto ret = output_queue_->DequeueBuffer(); if (ret.first == false) { NOTIFY_ERROR(PLATFORM_FAILURE); return; } else if (!ret.second) { // we're just out of buffers to dequeue. break; } const size_t buffer_id = ret.second->BufferId(); DVLOGF(4) << "Dequeued output=" << buffer_id << " count " << output_queue_->QueuedBuffersCount(); DCHECK(!surfaces_at_device_.empty()); auto surface = std::move(surfaces_at_device_.front()); surfaces_at_device_.pop(); DCHECK_EQ(static_cast<size_t>(surface->output_record()), buffer_id); // If using an image processor, process the image before considering it // decoded. if (image_processor_) { if (!ProcessFrame(std::move(ret.second), std::move(surface))) { VLOGF(1) << "Processing frame failed"; NOTIFY_ERROR(PLATFORM_FAILURE); } } else { DCHECK_EQ(decoded_buffer_map_.count(buffer_id), 0u); decoded_buffer_map_.emplace(buffer_id, buffer_id); surface->SetDecoded(); surface->SetReleaseCallback( base::BindOnce(&V4L2SliceVideoDecodeAccelerator::ReuseOutputBuffer, base::Unretained(this), std::move(ret.second))); } } // A frame was decoded, see if we can output it. TryOutputSurfaces(); ProcessPendingEventsIfNeeded(); ScheduleDecodeBufferTaskIfNeeded(); } void V4L2SliceVideoDecodeAccelerator::NewEventPending() { // Switch to event processing mode if we are decoding. Otherwise we are either // already in it, or we will potentially switch to it later, after finishing // other tasks. if (state_ == kDecoding) state_ = kIdle; ProcessPendingEventsIfNeeded(); } bool V4L2SliceVideoDecodeAccelerator::FinishEventProcessing() { DCHECK_EQ(state_, kIdle); state_ = kDecoding; ScheduleDecodeBufferTaskIfNeeded(); return true; } void V4L2SliceVideoDecodeAccelerator::ProcessPendingEventsIfNeeded() { DCHECK(decoder_thread_task_runner_->BelongsToCurrentThread()); // Process pending events, if any, in the correct order. // We always first process the surface set change, as it is an internal // event from the decoder and interleaving it with external requests would // put the decoder in an undefined state. using ProcessFunc = bool (V4L2SliceVideoDecodeAccelerator::*)(); const ProcessFunc process_functions[] = { &V4L2SliceVideoDecodeAccelerator::FinishSurfaceSetChange, &V4L2SliceVideoDecodeAccelerator::FinishFlush, &V4L2SliceVideoDecodeAccelerator::FinishReset, &V4L2SliceVideoDecodeAccelerator::FinishEventProcessing, }; for (const auto& fn : process_functions) { if (state_ != kIdle) return; if (!(this->*fn)()) return; } } void V4L2SliceVideoDecodeAccelerator::ReuseOutputBuffer( V4L2ReadableBufferRef buffer) { DVLOGF(4) << "Reusing output buffer, index=" << buffer->BufferId(); DCHECK(decoder_thread_task_runner_->BelongsToCurrentThread()); DCHECK_EQ(decoded_buffer_map_.count(buffer->BufferId()), 1u); decoded_buffer_map_.erase(buffer->BufferId()); ScheduleDecodeBufferTaskIfNeeded(); } bool V4L2SliceVideoDecodeAccelerator::EnqueueInputRecord( V4L2DecodeSurface* dec_surface) { DVLOGF(4); DCHECK_NE(dec_surface, nullptr); // Enqueue an input (VIDEO_OUTPUT) buffer for an input video frame. V4L2WritableBufferRef input_buffer = std::move(dec_surface->input_buffer()); DCHECK(input_buffer.IsValid()); const int index = input_buffer.BufferId(); input_buffer.PrepareQueueBuffer(*dec_surface); if (!std::move(input_buffer).QueueMMap()) { NOTIFY_ERROR(PLATFORM_FAILURE); return false; } DVLOGF(4) << "Enqueued input=" << index << " count: " << input_queue_->QueuedBuffersCount(); return true; } bool V4L2SliceVideoDecodeAccelerator::EnqueueOutputRecord( V4L2DecodeSurface* dec_surface) { DVLOGF(4); // Enqueue an output (VIDEO_CAPTURE) buffer. V4L2WritableBufferRef output_buffer = std::move(dec_surface->output_buffer()); DCHECK(output_buffer.IsValid()); size_t index = output_buffer.BufferId(); OutputRecord& output_record = output_buffer_map_[index]; DCHECK_NE(output_record.picture_id, -1); bool ret = false; switch (output_buffer.Memory()) { case V4L2_MEMORY_MMAP: ret = std::move(output_buffer).QueueMMap(); break; case V4L2_MEMORY_DMABUF: { const auto& fds = output_record.output_frame->DmabufFds(); DCHECK_EQ(output_planes_count_, fds.size()); ret = std::move(output_buffer).QueueDMABuf(fds); break; } default: NOTREACHED(); } if (!ret) { NOTIFY_ERROR(PLATFORM_FAILURE); return false; } DVLOGF(4) << "Enqueued output=" << index << " count: " << output_queue_->QueuedBuffersCount(); return true; } bool V4L2SliceVideoDecodeAccelerator::StartDevicePoll() { DVLOGF(3) << "Starting device poll"; DCHECK(decoder_thread_task_runner_->BelongsToCurrentThread()); if (!input_queue_->Streamon()) return false; if (!output_queue_->Streamon()) return false; // We can use base::Unretained here because the client thread will flush // all tasks posted to the decoder thread before deleting the SVDA. return device_->StartPolling( base::BindRepeating(&V4L2SliceVideoDecodeAccelerator::ServiceDeviceTask, base::Unretained(this)), base::BindRepeating(&V4L2SliceVideoDecodeAccelerator::OnPollError, base::Unretained(this))); } void V4L2SliceVideoDecodeAccelerator::OnPollError() { NOTIFY_ERROR(PLATFORM_FAILURE); } bool V4L2SliceVideoDecodeAccelerator::StopDevicePoll() { DVLOGF(3) << "Stopping device poll"; if (decoder_thread_.IsRunning()) DCHECK(decoder_thread_task_runner_->BelongsToCurrentThread()); if (!device_->StopPolling()) return false; // We may be called before the queue is acquired. if (input_queue_) { if (!input_queue_->Streamoff()) return false; DCHECK_EQ(input_queue_->QueuedBuffersCount(), 0u); } // We may be called before the queue is acquired. if (output_queue_) { if (!output_queue_->Streamoff()) return false; DCHECK_EQ(output_queue_->QueuedBuffersCount(), 0u); } // Mark as decoded to allow reuse. while (!surfaces_at_device_.empty()) surfaces_at_device_.pop(); // Drop all surfaces that were awaiting decode before being displayed, // since we've just cancelled all outstanding decodes. while (!decoder_display_queue_.empty()) decoder_display_queue_.pop(); DVLOGF(3) << "Device poll stopped"; return true; } void V4L2SliceVideoDecodeAccelerator::Decode(BitstreamBuffer bitstream_buffer) { Decode(bitstream_buffer.ToDecoderBuffer(), bitstream_buffer.id()); } void V4L2SliceVideoDecodeAccelerator::Decode( scoped_refptr<DecoderBuffer> buffer, int32_t bitstream_id) { DVLOGF(4) << "input_id=" << bitstream_id << ", size=" << (buffer ? buffer->data_size() : 0); DCHECK(decode_task_runner_->BelongsToCurrentThread()); if (bitstream_id < 0) { VLOGF(1) << "Invalid bitstream buffer, id: " << bitstream_id; NOTIFY_ERROR(INVALID_ARGUMENT); return; } decoder_thread_task_runner_->PostTask( FROM_HERE, base::BindOnce(&V4L2SliceVideoDecodeAccelerator::DecodeTask, base::Unretained(this), std::move(buffer), bitstream_id)); } void V4L2SliceVideoDecodeAccelerator::DecodeTask( scoped_refptr<DecoderBuffer> buffer, int32_t bitstream_id) { DVLOGF(4) << "input_id=" << bitstream_id << " size=" << (buffer ? buffer->data_size() : 0); DCHECK(decoder_thread_task_runner_->BelongsToCurrentThread()); if (IsDestroyPending()) return; std::unique_ptr<BitstreamBufferRef> bitstream_record(new BitstreamBufferRef( decode_client_, decode_task_runner_, std::move(buffer), bitstream_id)); // Skip empty buffer. if (!bitstream_record->buffer) return; decoder_input_queue_.push_back(std::move(bitstream_record)); TRACE_COUNTER_ID1("media,gpu", "V4L2SVDA decoder input BitstreamBuffers", this, decoder_input_queue_.size()); ScheduleDecodeBufferTaskIfNeeded(); } bool V4L2SliceVideoDecodeAccelerator::TrySetNewBistreamBuffer() { DCHECK(decoder_thread_task_runner_->BelongsToCurrentThread()); DCHECK(!decoder_current_bitstream_buffer_); if (decoder_input_queue_.empty()) return false; decoder_current_bitstream_buffer_ = std::move(decoder_input_queue_.front()); decoder_input_queue_.pop_front(); if (decoder_current_bitstream_buffer_->input_id == kFlushBufferId) { // This is a buffer we queued for ourselves to trigger flush at this time. InitiateFlush(); return false; } decoder_->SetStream(decoder_current_bitstream_buffer_->input_id, *decoder_current_bitstream_buffer_->buffer); return true; } void V4L2SliceVideoDecodeAccelerator::ScheduleDecodeBufferTaskIfNeeded() { DCHECK(decoder_thread_task_runner_->BelongsToCurrentThread()); if (state_ == kDecoding) { decoder_thread_task_runner_->PostTask( FROM_HERE, base::BindOnce(&V4L2SliceVideoDecodeAccelerator::DecodeBufferTask, base::Unretained(this))); } } void V4L2SliceVideoDecodeAccelerator::DecodeBufferTask() { DVLOGF(4); DCHECK(decoder_thread_task_runner_->BelongsToCurrentThread()); TRACE_EVENT0("media,gpu", "V4L2SVDA::DecodeBufferTask"); if (IsDestroyPending()) return; if (state_ != kDecoding) { DVLOGF(3) << "Early exit, not in kDecoding"; return; } while (true) { TRACE_EVENT_BEGIN0("media,gpu", "V4L2SVDA::DecodeBufferTask AVD::Decode"); const AcceleratedVideoDecoder::DecodeResult res = decoder_->Decode(); TRACE_EVENT_END0("media,gpu", "V4L2SVDA::DecodeBufferTask AVD::Decode"); switch (res) { case AcceleratedVideoDecoder::kConfigChange: if (!IsSupportedProfile(decoder_->GetProfile())) { VLOGF(2) << "Unsupported profile: " << decoder_->GetProfile(); NOTIFY_ERROR(PLATFORM_FAILURE); return; } VLOGF(2) << "Decoder requesting a new set of surfaces"; InitiateSurfaceSetChange(); return; case AcceleratedVideoDecoder::kRanOutOfStreamData: decoder_current_bitstream_buffer_.reset(); if (!TrySetNewBistreamBuffer()) return; break; case AcceleratedVideoDecoder::kRanOutOfSurfaces: // No more surfaces for the decoder, we'll come back once we have more. DVLOGF(4) << "Ran out of surfaces"; return; case AcceleratedVideoDecoder::kNeedContextUpdate: DVLOGF(4) << "Awaiting context update"; return; case AcceleratedVideoDecoder::kDecodeError: VLOGF(1) << "Error decoding stream"; NOTIFY_ERROR(PLATFORM_FAILURE); return; case AcceleratedVideoDecoder::kTryAgain: NOTREACHED() << "Should not reach here unless this class accepts " "encrypted streams."; DVLOGF(4) << "No key for decoding stream."; NOTIFY_ERROR(PLATFORM_FAILURE); return; } } } void V4L2SliceVideoDecodeAccelerator::InitiateSurfaceSetChange() { VLOGF(2); DCHECK(decoder_thread_task_runner_->BelongsToCurrentThread()); DCHECK_EQ(state_, kDecoding); TRACE_EVENT_ASYNC_BEGIN0("media,gpu", "V4L2SVDA Resolution Change", this); DCHECK(!surface_set_change_pending_); surface_set_change_pending_ = true; NewEventPending(); } bool V4L2SliceVideoDecodeAccelerator::FinishSurfaceSetChange() { VLOGF(2); DCHECK(decoder_thread_task_runner_->BelongsToCurrentThread()); if (!surface_set_change_pending_) return true; if (!surfaces_at_device_.empty()) return false; // Wait until all pending frames in image processor are processed. if (image_processor_ && !surfaces_at_ip_.empty()) return false; DCHECK_EQ(state_, kIdle); DCHECK(decoder_display_queue_.empty()); // All output buffers should've been returned from decoder and device by now. // The only remaining owner of surfaces may be display (client), and we will // dismiss them when destroying output buffers below. DCHECK_EQ(output_queue_->FreeBuffersCount() + surfaces_at_display_.size(), output_buffer_map_.size()); if (!StopDevicePoll()) { NOTIFY_ERROR(PLATFORM_FAILURE); return false; } image_processor_ = nullptr; // Dequeued decoded surfaces may be pended in pending_picture_ready_ if they // are waiting for some pictures to be cleared. We should post them right away // because they are about to be dismissed and destroyed for surface set // change. SendPictureReady(); // This will return only once all buffers are dismissed and destroyed. // This does not wait until they are displayed however, as display retains // references to the buffers bound to textures and will release them // after displaying. if (!DestroyOutputs(true)) { NOTIFY_ERROR(PLATFORM_FAILURE); return false; } if (!CreateOutputBuffers()) { NOTIFY_ERROR(PLATFORM_FAILURE); return false; } surface_set_change_pending_ = false; VLOGF(2) << "Surface set change finished"; TRACE_EVENT_ASYNC_END0("media,gpu", "V4L2SVDA Resolution Change", this); return true; } bool V4L2SliceVideoDecodeAccelerator::DestroyOutputs(bool dismiss) { VLOGF(2); DCHECK(decoder_thread_task_runner_->BelongsToCurrentThread()); std::vector<int32_t> picture_buffers_to_dismiss; if (output_buffer_map_.empty()) return true; for (auto& output_record : output_buffer_map_) { picture_buffers_to_dismiss.push_back(output_record.picture_id); } if (dismiss) { VLOGF(2) << "Scheduling picture dismissal"; base::WaitableEvent done(base::WaitableEvent::ResetPolicy::AUTOMATIC, base::WaitableEvent::InitialState::NOT_SIGNALED); child_task_runner_->PostTask( FROM_HERE, base::BindOnce(&V4L2SliceVideoDecodeAccelerator::DismissPictures, weak_this_, picture_buffers_to_dismiss, &done)); done.Wait(); } // At this point client can't call ReusePictureBuffer on any of the pictures // anymore, so it's safe to destroy. return DestroyOutputBuffers(); } bool V4L2SliceVideoDecodeAccelerator::DestroyOutputBuffers() { VLOGF(2); DCHECK(decoder_thread_task_runner_->BelongsToCurrentThread() || !decoder_thread_.IsRunning()); DCHECK(surfaces_at_device_.empty()); DCHECK(decoder_display_queue_.empty()); if (!output_queue_ || output_buffer_map_.empty()) return true; DCHECK(!output_queue_->IsStreaming()); DCHECK_EQ(output_queue_->QueuedBuffersCount(), 0u); // Release all buffers waiting for an import buffer event. output_wait_map_.clear(); // Release all buffers awaiting a fence since we are about to destroy them. surfaces_awaiting_fence_ = {}; // It's ok to do this, client will retain references to textures, but we are // not interested in reusing the surfaces anymore. // This will prevent us from reusing old surfaces in case we have some // ReusePictureBuffer() pending on ChildThread already. It's ok to ignore // them, because we have already dismissed them (in DestroyOutputs()). surfaces_at_display_.clear(); DCHECK_EQ(output_queue_->FreeBuffersCount(), output_buffer_map_.size()); output_buffer_map_.clear(); output_queue_->DeallocateBuffers(); return true; } void V4L2SliceVideoDecodeAccelerator::AssignPictureBuffers( const std::vector<PictureBuffer>& buffers) { VLOGF(2); DCHECK(child_task_runner_->BelongsToCurrentThread()); decoder_thread_task_runner_->PostTask( FROM_HERE, base::BindOnce(&V4L2SliceVideoDecodeAccelerator::AssignPictureBuffersTask, base::Unretained(this), buffers)); } void V4L2SliceVideoDecodeAccelerator::AssignPictureBuffersTask( const std::vector<PictureBuffer>& buffers) { VLOGF(2); DCHECK(!output_queue_->IsStreaming()); DCHECK(decoder_thread_task_runner_->BelongsToCurrentThread()); DCHECK_EQ(state_, kAwaitingPictureBuffers); TRACE_EVENT1("media,gpu", "V4L2SVDA::AssignPictureBuffersTask", "buffers_size", buffers.size()); if (IsDestroyPending()) return; const uint32_t req_buffer_count = decoder_->GetRequiredNumOfPictures(); if (buffers.size() < req_buffer_count) { VLOGF(1) << "Failed to provide requested picture buffers. " << "(Got " << buffers.size() << ", requested " << req_buffer_count << ")"; NOTIFY_ERROR(INVALID_ARGUMENT); return; } // If a client allocate a different frame size, S_FMT should be called with // the size. if (!image_processor_device_ && coded_size_ != buffers[0].size()) { const auto& new_frame_size = buffers[0].size(); v4l2_format format = {}; format.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE; format.fmt.pix_mp.width = new_frame_size.width(); format.fmt.pix_mp.height = new_frame_size.height(); format.fmt.pix_mp.pixelformat = output_format_fourcc_; format.fmt.pix_mp.num_planes = output_planes_count_; if (device_->Ioctl(VIDIOC_S_FMT, &format) != 0) { VPLOGF(1) << "Failed with frame size adjusted by client: " << new_frame_size.ToString(); NOTIFY_ERROR(PLATFORM_FAILURE); return; } coded_size_.SetSize(format.fmt.pix_mp.width, format.fmt.pix_mp.height); // If size specified by ProvidePictureBuffers() is adjusted by the client, // the size must not be adjusted by a v4l2 driver again. if (coded_size_ != new_frame_size) { VLOGF(1) << "The size of PictureBuffer is invalid." << " size adjusted by the client = " << new_frame_size.ToString() << " size adjusted by a driver = " << coded_size_.ToString(); NOTIFY_ERROR(INVALID_ARGUMENT); return; } if (!gfx::Rect(coded_size_).Contains(gfx::Rect(decoder_->GetPicSize()))) { VLOGF(1) << "Got invalid adjusted coded size: " << coded_size_.ToString(); NOTIFY_ERROR(INVALID_ARGUMENT); return; } gl_image_size_ = coded_size_; } const v4l2_memory memory = (image_processor_device_ || output_mode_ == Config::OutputMode::ALLOCATE ? V4L2_MEMORY_MMAP : V4L2_MEMORY_DMABUF); if (output_queue_->AllocateBuffers(buffers.size(), memory) != buffers.size()) { VLOGF(1) << "Could not allocate enough output buffers"; NOTIFY_ERROR(PLATFORM_FAILURE); return; } DCHECK(output_buffer_map_.empty()); DCHECK(output_wait_map_.empty()); output_buffer_map_.resize(buffers.size()); // In import mode we will create the IP when importing the first buffer. if (image_processor_device_ && output_mode_ == Config::OutputMode::ALLOCATE) { if (!CreateImageProcessor()) { NOTIFY_ERROR(PLATFORM_FAILURE); return; } } // Reserve all buffers until ImportBufferForPictureTask() is called while (output_queue_->FreeBuffersCount() > 0) { V4L2WritableBufferRef buffer = output_queue_->GetFreeBuffer(); DCHECK(buffer.IsValid()); int i = buffer.BufferId(); DCHECK_EQ(output_wait_map_.count(buffers[i].id()), 0u); // The buffer will remain here until ImportBufferForPicture is called, // either by the client, or by ourselves, if we are allocating. output_wait_map_.emplace(buffers[i].id(), std::move(buffer)); } // All available buffers should be in the wait map now. DCHECK_EQ(output_buffer_map_.size(), output_wait_map_.size()); for (size_t i = 0; i < buffers.size(); i++) { OutputRecord& output_record = output_buffer_map_[i]; DCHECK_EQ(output_record.picture_id, -1); DCHECK_EQ(output_record.cleared, false); output_record.picture_id = buffers[i].id(); output_record.texture_id = buffers[i].service_texture_ids().empty() ? 0 : buffers[i].service_texture_ids()[0]; output_record.client_texture_id = buffers[i].client_texture_ids().empty() ? 0 : buffers[i].client_texture_ids()[0]; // If we are in allocate mode, then we can already call // ImportBufferForPictureTask(). if (output_mode_ == Config::OutputMode::ALLOCATE) { std::vector<base::ScopedFD> passed_dmabuf_fds; // If we are using an image processor, the DMABufs that we need to import // are those of the image processor's buffers, not the decoders. So // pass an empty FDs array in that case. if (!image_processor_) { passed_dmabuf_fds = gl_image_device_->GetDmabufsForV4L2Buffer( i, gl_image_planes_count_, V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE); if (passed_dmabuf_fds.empty()) { NOTIFY_ERROR(PLATFORM_FAILURE); return; } } int plane_horiz_bits_per_pixel = VideoFrame::PlaneHorizontalBitsPerPixel( Fourcc::FromV4L2PixFmt(gl_image_format_fourcc_).ToVideoPixelFormat(), 0); ImportBufferForPictureTask( output_record.picture_id, std::move(passed_dmabuf_fds), gl_image_size_.width() * plane_horiz_bits_per_pixel / 8); } // else we'll get triggered via ImportBufferForPicture() from client. DVLOGF(3) << "buffer[" << i << "]: picture_id=" << output_record.picture_id; } if (!StartDevicePoll()) { NOTIFY_ERROR(PLATFORM_FAILURE); return; } } void V4L2SliceVideoDecodeAccelerator::CreateGLImageFor( size_t buffer_index, int32_t picture_buffer_id, std::vector<base::ScopedFD> passed_dmabuf_fds, GLuint client_texture_id, GLuint texture_id, const gfx::Size& size, uint32_t fourcc) { DVLOGF(3) << "index=" << buffer_index; DCHECK(child_task_runner_->BelongsToCurrentThread()); DCHECK_NE(texture_id, 0u); TRACE_EVENT1("media,gpu", "V4L2SVDA::CreateGLImageFor", "picture_buffer_id", picture_buffer_id); if (!make_context_current_cb_) { VLOGF(1) << "GL callbacks required for binding to GLImages"; NOTIFY_ERROR(INVALID_ARGUMENT); return; } if (!make_context_current_cb_.Run()) { VLOGF(1) << "No GL context"; NOTIFY_ERROR(INVALID_ARGUMENT); return; } scoped_refptr<gl::GLImage> gl_image = gl_image_device_->CreateGLImage(size, fourcc, passed_dmabuf_fds); if (!gl_image) { VLOGF(1) << "Could not create GLImage," << " index=" << buffer_index << " texture_id=" << texture_id; NOTIFY_ERROR(PLATFORM_FAILURE); return; } gl::ScopedTextureBinder bind_restore(gl_image_device_->GetTextureTarget(), texture_id); bool ret = gl_image->BindTexImage(gl_image_device_->GetTextureTarget()); DCHECK(ret); bind_image_cb_.Run(client_texture_id, gl_image_device_->GetTextureTarget(), gl_image, true); } void V4L2SliceVideoDecodeAccelerator::ImportBufferForPicture( int32_t picture_buffer_id, VideoPixelFormat pixel_format, gfx::GpuMemoryBufferHandle gpu_memory_buffer_handle) { DVLOGF(3) << "picture_buffer_id=" << picture_buffer_id; DCHECK(child_task_runner_->BelongsToCurrentThread()); if (output_mode_ != Config::OutputMode::IMPORT) { VLOGF(1) << "Cannot import in non-import mode"; NOTIFY_ERROR(INVALID_ARGUMENT); return; } decoder_thread_.task_runner()->PostTask( FROM_HERE, base::BindOnce( &V4L2SliceVideoDecodeAccelerator::ImportBufferForPictureForImportTask, base::Unretained(this), picture_buffer_id, pixel_format, std::move(gpu_memory_buffer_handle.native_pixmap_handle))); } void V4L2SliceVideoDecodeAccelerator::ImportBufferForPictureForImportTask( int32_t picture_buffer_id, VideoPixelFormat pixel_format, gfx::NativePixmapHandle handle) { DCHECK(decoder_thread_.task_runner()->BelongsToCurrentThread()); if (pixel_format != Fourcc::FromV4L2PixFmt(gl_image_format_fourcc_).ToVideoPixelFormat()) { VLOGF(1) << "Unsupported import format: " << VideoPixelFormatToString(pixel_format); NOTIFY_ERROR(INVALID_ARGUMENT); return; } std::vector<base::ScopedFD> dmabuf_fds; for (auto& plane : handle.planes) { dmabuf_fds.push_back(std::move(plane.fd)); } // If the driver does not accept as many fds as we received from the client, // we have to check if the additional fds are actually duplicated fds pointing // to previous planes; if so, we can close the duplicates and keep only the // original fd(s). // Assume that an fd is a duplicate of a previous plane's fd if offset != 0. // Otherwise, if offset == 0, return error as it may be pointing to a new // plane. while (dmabuf_fds.size() > gl_image_planes_count_) { const size_t idx = dmabuf_fds.size() - 1; if (handle.planes[idx].offset == 0) { VLOGF(1) << "The dmabuf fd points to a new buffer, "; NOTIFY_ERROR(INVALID_ARGUMENT); return; } // Drop safely, because this fd is duplicate dmabuf fd pointing to previous // buffer and the appropriate address can be accessed by associated offset. dmabuf_fds.pop_back(); } ImportBufferForPictureTask(picture_buffer_id, std::move(dmabuf_fds), handle.planes[0].stride); } void V4L2SliceVideoDecodeAccelerator::ImportBufferForPictureTask( int32_t picture_buffer_id, std::vector<base::ScopedFD> passed_dmabuf_fds, int32_t stride) { DVLOGF(3) << "picture_buffer_id=" << picture_buffer_id; DCHECK(decoder_thread_task_runner_->BelongsToCurrentThread()); if (IsDestroyPending()) return; const auto iter = std::find_if(output_buffer_map_.begin(), output_buffer_map_.end(), [picture_buffer_id](const OutputRecord& output_record) { return output_record.picture_id == picture_buffer_id; }); if (iter == output_buffer_map_.end()) { // It's possible that we've already posted a DismissPictureBuffer for this // picture, but it has not yet executed when this ImportBufferForPicture was // posted to us by the client. In that case just ignore this (we've already // dismissed it and accounted for that). DVLOGF(3) << "got picture id=" << picture_buffer_id << " not in use (anymore?)."; return; } if (!output_wait_map_.count(iter->picture_id)) { VLOGF(1) << "Passed buffer is not waiting to be imported"; NOTIFY_ERROR(INVALID_ARGUMENT); return; } // TODO(crbug.com/982172): This must be done in AssignPictureBuffers(). // However the size of PictureBuffer might not be adjusted by ARC++. So we // keep this until ARC++ side is fixed. int plane_horiz_bits_per_pixel = VideoFrame::PlaneHorizontalBitsPerPixel( Fourcc::FromV4L2PixFmt(gl_image_format_fourcc_).ToVideoPixelFormat(), 0); if (plane_horiz_bits_per_pixel == 0 || (stride * 8) % plane_horiz_bits_per_pixel != 0) { VLOGF(1) << "Invalid format " << gl_image_format_fourcc_ << " or stride " << stride; NOTIFY_ERROR(INVALID_ARGUMENT); return; } int adjusted_coded_width = stride * 8 / plane_horiz_bits_per_pixel; if (image_processor_device_ && !image_processor_) { DCHECK_EQ(kAwaitingPictureBuffers, state_); // This is the first buffer import. Create the image processor and change // the decoder state. The client may adjust the coded width. We don't have // the final coded size in AssignPictureBuffers yet. Use the adjusted coded // width to create the image processor. DVLOGF(3) << "Original gl_image_size=" << gl_image_size_.ToString() << ", adjusted coded width=" << adjusted_coded_width; DCHECK_GE(adjusted_coded_width, gl_image_size_.width()); gl_image_size_.set_width(adjusted_coded_width); if (!CreateImageProcessor()) return; } DCHECK_EQ(gl_image_size_.width(), adjusted_coded_width); // Put us in kIdle to allow further event processing. // ProcessPendingEventsIfNeeded() will put us back into kDecoding after all // other pending events are processed successfully. if (state_ == kAwaitingPictureBuffers) { state_ = kIdle; decoder_thread_.task_runner()->PostTask( FROM_HERE, base::BindOnce( &V4L2SliceVideoDecodeAccelerator::ProcessPendingEventsIfNeeded, base::Unretained(this))); } // If in import mode, build output_frame from the passed DMABUF FDs. if (output_mode_ == Config::OutputMode::IMPORT) { DCHECK_EQ(gl_image_planes_count_, passed_dmabuf_fds.size()); DCHECK(!iter->output_frame); // TODO(acourbot): Create a more accurate layout from the GMBhandle instead // of assuming the image size will be enough (we may have extra information // between planes). auto layout = VideoFrameLayout::Create( Fourcc::FromV4L2PixFmt(gl_image_format_fourcc_).ToVideoPixelFormat(), gl_image_size_); if (!layout) { VLOGF(1) << "Cannot create layout!"; NOTIFY_ERROR(INVALID_ARGUMENT); return; } const gfx::Rect visible_rect = decoder_->GetVisibleRect(); iter->output_frame = VideoFrame::WrapExternalDmabufs( *layout, visible_rect, visible_rect.size(), DuplicateFDs(passed_dmabuf_fds), base::TimeDelta()); } // We should only create the GL image if rendering is enabled // (texture_id !=0). Moreover, if an image processor is in use, we will // create the GL image when its buffer becomes visible in FrameProcessed(). if (iter->texture_id != 0 && !image_processor_) { DCHECK_EQ(gl_image_planes_count_, passed_dmabuf_fds.size()); size_t index = iter - output_buffer_map_.begin(); child_task_runner_->PostTask( FROM_HERE, base::BindOnce(&V4L2SliceVideoDecodeAccelerator::CreateGLImageFor, weak_this_, index, picture_buffer_id, std::move(passed_dmabuf_fds), iter->client_texture_id, iter->texture_id, gl_image_size_, gl_image_format_fourcc_)); } // Buffer is now ready to be used. DCHECK_EQ(output_wait_map_.count(picture_buffer_id), 1u); output_wait_map_.erase(picture_buffer_id); ScheduleDecodeBufferTaskIfNeeded(); } void V4L2SliceVideoDecodeAccelerator::ReusePictureBuffer( int32_t picture_buffer_id) { DCHECK(child_task_runner_->BelongsToCurrentThread()); DVLOGF(4) << "picture_buffer_id=" << picture_buffer_id; std::unique_ptr<gl::GLFenceEGL> egl_fence; if (make_context_current_cb_) { if (!make_context_current_cb_.Run()) { VLOGF(1) << "could not make context current"; NOTIFY_ERROR(PLATFORM_FAILURE); return; } egl_fence = gl::GLFenceEGL::Create(); if (!egl_fence) { VLOGF(1) << "gl::GLFenceEGL::Create() failed"; NOTIFY_ERROR(PLATFORM_FAILURE); return; } } decoder_thread_task_runner_->PostTask( FROM_HERE, base::BindOnce(&V4L2SliceVideoDecodeAccelerator::ReusePictureBufferTask, base::Unretained(this), picture_buffer_id, std::move(egl_fence))); } void V4L2SliceVideoDecodeAccelerator::ReusePictureBufferTask( int32_t picture_buffer_id, std::unique_ptr<gl::GLFenceEGL> egl_fence) { DVLOGF(4) << "picture_buffer_id=" << picture_buffer_id; DCHECK(decoder_thread_task_runner_->BelongsToCurrentThread()); if (IsDestroyPending()) return; V4L2DecodeSurfaceByPictureBufferId::iterator it = surfaces_at_display_.find(picture_buffer_id); if (it == surfaces_at_display_.end()) { // It's possible that we've already posted a DismissPictureBuffer for this // picture, but it has not yet executed when this ReusePictureBuffer was // posted to us by the client. In that case just ignore this (we've already // dismissed it and accounted for that) and let the fence object get // destroyed. DVLOGF(3) << "got picture id=" << picture_buffer_id << " not in use (anymore?)."; return; } DCHECK_EQ(decoded_buffer_map_.count(it->second->output_record()), 1u); const size_t output_map_index = decoded_buffer_map_[it->second->output_record()]; DCHECK_LT(output_map_index, output_buffer_map_.size()); OutputRecord& output_record = output_buffer_map_[output_map_index]; if (!output_record.at_client()) { VLOGF(1) << "picture_buffer_id not reusable"; NOTIFY_ERROR(INVALID_ARGUMENT); return; } --output_record.num_times_sent_to_client; // A output buffer might be sent multiple times. We only use the last fence. // When the last fence is signaled, all the previous fences must be executed. if (!output_record.at_client()) { // Take ownership of the EGL fence. if (egl_fence) surfaces_awaiting_fence_.push( std::make_pair(std::move(egl_fence), std::move(it->second))); surfaces_at_display_.erase(it); } } void V4L2SliceVideoDecodeAccelerator::Flush() { VLOGF(2); DCHECK(child_task_runner_->BelongsToCurrentThread()); decoder_thread_task_runner_->PostTask( FROM_HERE, base::BindOnce(&V4L2SliceVideoDecodeAccelerator::FlushTask, base::Unretained(this))); } void V4L2SliceVideoDecodeAccelerator::FlushTask() { VLOGF(2); DCHECK(decoder_thread_task_runner_->BelongsToCurrentThread()); if (IsDestroyPending()) return; // Queue an empty buffer which - when reached - will trigger flush sequence. decoder_input_queue_.push_back(std::make_unique<BitstreamBufferRef>( decode_client_, decode_task_runner_, nullptr, kFlushBufferId)); ScheduleDecodeBufferTaskIfNeeded(); } void V4L2SliceVideoDecodeAccelerator::InitiateFlush() { VLOGF(2); DCHECK(decoder_thread_task_runner_->BelongsToCurrentThread()); TRACE_EVENT_ASYNC_BEGIN0("media,gpu", "V4L2SVDA Flush", this); // This will trigger output for all remaining surfaces in the decoder. // However, not all of them may be decoded yet (they would be queued // in hardware then). if (!decoder_->Flush()) { DVLOGF(1) << "Failed flushing the decoder."; NOTIFY_ERROR(PLATFORM_FAILURE); return; } // Put the decoder in an idle state, ready to resume. decoder_->Reset(); DCHECK(!decoder_flushing_); decoder_flushing_ = true; NewEventPending(); } bool V4L2SliceVideoDecodeAccelerator::FinishFlush() { VLOGF(4); DCHECK(decoder_thread_task_runner_->BelongsToCurrentThread()); if (!decoder_flushing_) return true; if (!surfaces_at_device_.empty()) return false; // Even if all output buffers have been returned, the decoder may still // be holding on an input device. Wait until the queue is actually drained. if (input_queue_->QueuedBuffersCount() != 0) return false; // Wait until all pending image processor tasks are completed. if (image_processor_ && !surfaces_at_ip_.empty()) return false; DCHECK_EQ(state_, kIdle); // At this point, all remaining surfaces are decoded and dequeued, and since // we have already scheduled output for them in InitiateFlush(), their // respective PictureReady calls have been posted (or they have been queued on // pending_picture_ready_). So at this time, once we SendPictureReady(), // we will have all remaining PictureReady() posted to the client and we // can post NotifyFlushDone(). DCHECK(decoder_display_queue_.empty()); // Decoder should have already returned all surfaces and all surfaces are // out of hardware. There can be no other owners of input buffers. DCHECK_EQ(input_queue_->FreeBuffersCount(), input_queue_->AllocatedBuffersCount()); SendPictureReady(); decoder_flushing_ = false; VLOGF(2) << "Flush finished"; child_task_runner_->PostTask( FROM_HERE, base::BindOnce(&Client::NotifyFlushDone, client_)); TRACE_EVENT_ASYNC_END0("media,gpu", "V4L2SVDA Flush", this); return true; } void V4L2SliceVideoDecodeAccelerator::Reset() { VLOGF(2); DCHECK(child_task_runner_->BelongsToCurrentThread()); decoder_thread_task_runner_->PostTask( FROM_HERE, base::BindOnce(&V4L2SliceVideoDecodeAccelerator::ResetTask, base::Unretained(this))); } void V4L2SliceVideoDecodeAccelerator::ResetTask() { VLOGF(2); DCHECK(decoder_thread_task_runner_->BelongsToCurrentThread()); TRACE_EVENT_ASYNC_BEGIN0("media,gpu", "V4L2SVDA Reset", this); if (IsDestroyPending()) return; if (decoder_resetting_) { // This is a bug in the client, multiple Reset()s before NotifyResetDone() // are not allowed. NOTREACHED() << "Client should not be requesting multiple Reset()s"; return; } // Put the decoder in an idle state, ready to resume. decoder_->Reset(); // Drop all remaining inputs. decoder_current_bitstream_buffer_.reset(); while (!decoder_input_queue_.empty()) decoder_input_queue_.pop_front(); decoder_resetting_ = true; NewEventPending(); } bool V4L2SliceVideoDecodeAccelerator::FinishReset() { VLOGF(4); DCHECK(decoder_thread_task_runner_->BelongsToCurrentThread()); if (!decoder_resetting_) return true; if (!surfaces_at_device_.empty()) return false; // Drop all buffers in image processor. if (image_processor_ && !ResetImageProcessor()) { VLOGF(1) << "Fail to reset image processor"; NOTIFY_ERROR(PLATFORM_FAILURE); return false; } DCHECK_EQ(state_, kIdle); DCHECK(!decoder_flushing_); SendPictureReady(); // Drop any pending outputs. while (!decoder_display_queue_.empty()) decoder_display_queue_.pop(); // At this point we can have no input buffers in the decoder, because we // Reset()ed it in ResetTask(), and have not scheduled any new Decode()s // having been in kIdle since. We don't have any surfaces in the HW either - // we just checked that surfaces_at_device_.empty(), and inputs are tied // to surfaces. Since there can be no other owners of input buffers, we can // simply mark them all as available. DCHECK_EQ(input_queue_->QueuedBuffersCount(), 0u); decoder_resetting_ = false; VLOGF(2) << "Reset finished"; child_task_runner_->PostTask( FROM_HERE, base::BindOnce(&Client::NotifyResetDone, client_)); TRACE_EVENT_ASYNC_END0("media,gpu", "V4L2SVDA Reset", this); return true; } bool V4L2SliceVideoDecodeAccelerator::IsDestroyPending() { return destroy_pending_.IsSignaled(); } void V4L2SliceVideoDecodeAccelerator::SetErrorState(Error error) { // We can touch decoder_state_ only if this is the decoder thread or the // decoder thread isn't running. if (decoder_thread_.IsRunning() && !decoder_thread_task_runner_->BelongsToCurrentThread()) { decoder_thread_task_runner_->PostTask( FROM_HERE, base::BindOnce(&V4L2SliceVideoDecodeAccelerator::SetErrorState, base::Unretained(this), error)); return; } // Notifying the client of an error will only happen if we are already // initialized, as the API does not allow doing so before that. Subsequent // errors and errors while destroying will be suppressed. if (state_ != kError && state_ != kUninitialized && state_ != kDestroying) NotifyError(error); state_ = kError; } bool V4L2SliceVideoDecodeAccelerator::SubmitSlice( const scoped_refptr<V4L2DecodeSurface>& dec_surface, const uint8_t* data, size_t size) { DCHECK(decoder_thread_task_runner_->BelongsToCurrentThread()); V4L2WritableBufferRef& input_buffer = dec_surface->input_buffer(); DCHECK(input_buffer.IsValid()); const size_t plane_size = input_buffer.GetPlaneSize(0); const size_t bytes_used = input_buffer.GetPlaneBytesUsed(0); if (bytes_used + size > plane_size) { VLOGF(1) << "Input buffer too small"; return false; } uint8_t* mapping = static_cast<uint8_t*>(input_buffer.GetPlaneMapping(0)); DCHECK_NE(mapping, nullptr); memcpy(mapping + bytes_used, data, size); input_buffer.SetPlaneBytesUsed(0, bytes_used + size); return true; } void V4L2SliceVideoDecodeAccelerator::DecodeSurface( const scoped_refptr<V4L2DecodeSurface>& dec_surface) { DCHECK(decoder_thread_task_runner_->BelongsToCurrentThread()); DVLOGF(3) << "Submitting decode for surface: " << dec_surface->ToString(); Enqueue(dec_surface); if (!dec_surface->Submit()) { VLOGF(1) << "Error while submitting frame for decoding!"; NOTIFY_ERROR(PLATFORM_FAILURE); } } void V4L2SliceVideoDecodeAccelerator::SurfaceReady( const scoped_refptr<V4L2DecodeSurface>& dec_surface, int32_t bitstream_id, const gfx::Rect& visible_rect, const VideoColorSpace& /* color_space */) { DVLOGF(4); DCHECK(decoder_thread_task_runner_->BelongsToCurrentThread()); dec_surface->SetVisibleRect(visible_rect); decoder_display_queue_.push(std::make_pair(bitstream_id, dec_surface)); TryOutputSurfaces(); } void V4L2SliceVideoDecodeAccelerator::TryOutputSurfaces() { while (!decoder_display_queue_.empty()) { scoped_refptr<V4L2DecodeSurface> dec_surface = decoder_display_queue_.front().second; if (!dec_surface->decoded()) break; int32_t bitstream_id = decoder_display_queue_.front().first; decoder_display_queue_.pop(); OutputSurface(bitstream_id, dec_surface); } } void V4L2SliceVideoDecodeAccelerator::OutputSurface( int32_t bitstream_id, const scoped_refptr<V4L2DecodeSurface>& dec_surface) { DCHECK(decoder_thread_task_runner_->BelongsToCurrentThread()); DCHECK_EQ(decoded_buffer_map_.count(dec_surface->output_record()), 1u); const size_t output_map_index = decoded_buffer_map_[dec_surface->output_record()]; DCHECK_LT(output_map_index, output_buffer_map_.size()); OutputRecord& output_record = output_buffer_map_[output_map_index]; if (!output_record.at_client()) { bool inserted = surfaces_at_display_ .insert(std::make_pair(output_record.picture_id, dec_surface)) .second; DCHECK(inserted); } else { // The surface is already sent to client, and not returned back yet. DCHECK(surfaces_at_display_.find(output_record.picture_id) != surfaces_at_display_.end()); CHECK(surfaces_at_display_[output_record.picture_id].get() == dec_surface.get()); } DCHECK_NE(output_record.picture_id, -1); ++output_record.num_times_sent_to_client; // TODO(hubbe): Insert correct color space. http://crbug.com/647725 Picture picture(output_record.picture_id, bitstream_id, dec_surface->visible_rect(), gfx::ColorSpace(), true /* allow_overlay */); DVLOGF(4) << dec_surface->ToString() << ", bitstream_id: " << picture.bitstream_buffer_id() << ", picture_id: " << picture.picture_buffer_id() << ", visible_rect: " << picture.visible_rect().ToString(); pending_picture_ready_.push(PictureRecord(output_record.cleared, picture)); SendPictureReady(); output_record.cleared = true; } void V4L2SliceVideoDecodeAccelerator::CheckGLFences() { DVLOGF(4); DCHECK(decoder_thread_task_runner_->BelongsToCurrentThread()); while (!surfaces_awaiting_fence_.empty() && surfaces_awaiting_fence_.front().first->HasCompleted()) { // Buffer at the front of the queue goes back to V4L2Queue's free list // and can be reused. surfaces_awaiting_fence_.pop(); } // If we have no free buffers available, then preemptively schedule a // call to DecodeBufferTask() in a short time, otherwise we may starve out // of buffers because fences will not call back into us once they are // signaled. The delay chosen roughly corresponds to the time a frame is // displayed, which should be optimal in most cases. if (output_queue_->FreeBuffersCount() == 0) { constexpr int64_t kRescheduleDelayMs = 17; decoder_thread_.task_runner()->PostDelayedTask( FROM_HERE, base::BindOnce(&V4L2SliceVideoDecodeAccelerator::DecodeBufferTask, base::Unretained(this)), base::TimeDelta::FromMilliseconds(kRescheduleDelayMs)); } } scoped_refptr<V4L2DecodeSurface> V4L2SliceVideoDecodeAccelerator::CreateSurface() { DCHECK(decoder_thread_task_runner_->BelongsToCurrentThread()); DCHECK_EQ(state_, kDecoding); TRACE_COUNTER_ID2( "media,gpu", "V4L2 input buffers", this, "free", input_queue_->FreeBuffersCount(), "in use", input_queue_->AllocatedBuffersCount() - input_queue_->FreeBuffersCount()); TRACE_COUNTER_ID2("media,gpu", "V4L2 output buffers", this, "free", output_queue_->FreeBuffersCount(), "in use", output_queue_->AllocatedBuffersCount() - output_queue_->AllocatedBuffersCount()); TRACE_COUNTER_ID2("media,gpu", "V4L2 output buffers", this, "at client", GetNumOfOutputRecordsAtClient(), "at device", GetNumOfOutputRecordsAtDevice()); // Release some output buffers if their fence has been signaled. CheckGLFences(); if (input_queue_->FreeBuffersCount() == 0 || output_queue_->FreeBuffersCount() == 0) return nullptr; V4L2WritableBufferRef input_buffer = input_queue_->GetFreeBuffer(); DCHECK(input_buffer.IsValid()); // All buffers that are returned to the output free queue have their GL // fence signaled, so we can use them directly. V4L2WritableBufferRef output_buffer = output_queue_->GetFreeBuffer(); DCHECK(output_buffer.IsValid()); int input = input_buffer.BufferId(); int output = output_buffer.BufferId(); scoped_refptr<V4L2DecodeSurface> dec_surface; if (supports_requests_) { // Here we just borrow the older request to use it, before // immediately putting it back at the back of the queue. base::ScopedFD request = std::move(requests_.front()); requests_.pop(); auto ret = V4L2RequestDecodeSurface::Create(std::move(input_buffer), std::move(output_buffer), nullptr, request.get()); requests_.push(std::move(request)); // Not being able to create the decode surface at this stage is a // fatal error. if (!ret) { NOTIFY_ERROR(PLATFORM_FAILURE); return nullptr; } dec_surface = std::move(ret).value(); } else { dec_surface = new V4L2ConfigStoreDecodeSurface( std::move(input_buffer), std::move(output_buffer), nullptr); } DVLOGF(4) << "Created surface " << input << " -> " << output; return dec_surface; } void V4L2SliceVideoDecodeAccelerator::SendPictureReady() { DVLOGF(4); DCHECK(decoder_thread_task_runner_->BelongsToCurrentThread()); bool send_now = (decoder_resetting_ || decoder_flushing_ || surface_set_change_pending_); while (!pending_picture_ready_.empty()) { bool cleared = pending_picture_ready_.front().cleared; const Picture& picture = pending_picture_ready_.front().picture; if (cleared && picture_clearing_count_ == 0) { DVLOGF(4) << "Posting picture ready to decode task runner for: " << picture.picture_buffer_id(); // This picture is cleared. It can be posted to a thread different than // the main GPU thread to reduce latency. This should be the case after // all pictures are cleared at the beginning. decode_task_runner_->PostTask( FROM_HERE, base::BindOnce(&Client::PictureReady, decode_client_, picture)); pending_picture_ready_.pop(); } else if (!cleared || send_now) { DVLOGF(4) << "cleared=" << pending_picture_ready_.front().cleared << ", decoder_resetting_=" << decoder_resetting_ << ", decoder_flushing_=" << decoder_flushing_ << ", surface_set_change_pending_=" << surface_set_change_pending_ << ", picture_clearing_count_=" << picture_clearing_count_; DVLOGF(4) << "Posting picture ready to GPU for: " << picture.picture_buffer_id(); // If the picture is not cleared, post it to the child thread because it // has to be cleared in the child thread. A picture only needs to be // cleared once. If the decoder is resetting or flushing or changing // resolution, send all pictures to ensure PictureReady arrive before // reset done, flush done, or picture dismissed. child_task_runner_->PostTaskAndReply( FROM_HERE, base::BindOnce(&Client::PictureReady, client_, picture), // Unretained is safe. If Client::PictureReady gets to run, |this| is // alive. Destroy() will wait the decode thread to finish. base::BindOnce(&V4L2SliceVideoDecodeAccelerator::PictureCleared, base::Unretained(this))); picture_clearing_count_++; pending_picture_ready_.pop(); } else { // This picture is cleared. But some pictures are about to be cleared on // the child thread. To preserve the order, do not send this until those // pictures are cleared. break; } } } void V4L2SliceVideoDecodeAccelerator::PictureCleared() { DVLOGF(4) << "clearing count=" << picture_clearing_count_; DCHECK(decoder_thread_task_runner_->BelongsToCurrentThread()); DCHECK_GT(picture_clearing_count_, 0); picture_clearing_count_--; SendPictureReady(); } bool V4L2SliceVideoDecodeAccelerator::TryToSetupDecodeOnSeparateThread( const base::WeakPtr<Client>& decode_client, const scoped_refptr<base::SingleThreadTaskRunner>& decode_task_runner) { decode_client_ = decode_client; decode_task_runner_ = decode_task_runner; return true; } // static VideoDecodeAccelerator::SupportedProfiles V4L2SliceVideoDecodeAccelerator::GetSupportedProfiles() { scoped_refptr<V4L2Device> device = V4L2Device::Create(); if (!device) return SupportedProfiles(); return device->GetSupportedDecodeProfiles( base::size(supported_input_fourccs_), supported_input_fourccs_); } bool V4L2SliceVideoDecodeAccelerator::IsSupportedProfile( VideoCodecProfile profile) { DCHECK(device_); if (supported_profiles_.empty()) { SupportedProfiles profiles = GetSupportedProfiles(); for (const SupportedProfile& profile : profiles) supported_profiles_.push_back(profile.profile); } return std::find(supported_profiles_.begin(), supported_profiles_.end(), profile) != supported_profiles_.end(); } size_t V4L2SliceVideoDecodeAccelerator::GetNumOfOutputRecordsAtDevice() const { DCHECK(decoder_thread_.task_runner()->BelongsToCurrentThread()); return output_queue_->QueuedBuffersCount(); } size_t V4L2SliceVideoDecodeAccelerator::GetNumOfOutputRecordsAtClient() const { DCHECK(decoder_thread_.task_runner()->BelongsToCurrentThread()); return std::count_if(output_buffer_map_.begin(), output_buffer_map_.end(), [](const auto& r) { return r.at_client(); }); } void V4L2SliceVideoDecodeAccelerator::ImageProcessorError() { DCHECK(decoder_thread_.task_runner()->BelongsToCurrentThread()); VLOGF(1) << "Image processor error"; NOTIFY_ERROR(PLATFORM_FAILURE); } bool V4L2SliceVideoDecodeAccelerator::ProcessFrame( V4L2ReadableBufferRef buffer, scoped_refptr<V4L2DecodeSurface> surface) { DVLOGF(4); DCHECK(decoder_thread_.task_runner()->BelongsToCurrentThread()); scoped_refptr<VideoFrame> input_frame = buffer->GetVideoFrame(); DCHECK(input_frame); if (image_processor_->output_mode() == ImageProcessor::OutputMode::IMPORT) { // In IMPORT mode we can decide ourselves which IP buffer to use, so choose // the one with the same index number as our decoded buffer. const OutputRecord& output_record = output_buffer_map_[buffer->BufferId()]; const scoped_refptr<VideoFrame>& output_frame = output_record.output_frame; // We will set a destruction observer to the output frame, so wrap the // imported frame into another one that we can destruct. scoped_refptr<VideoFrame> wrapped_frame = VideoFrame::WrapVideoFrame( output_frame, output_frame->format(), output_frame->visible_rect(), output_frame->coded_size()); DCHECK(output_frame != nullptr); image_processor_->Process( std::move(input_frame), std::move(wrapped_frame), base::BindOnce(&V4L2SliceVideoDecodeAccelerator::FrameProcessed, base::Unretained(this), surface, buffer->BufferId())); } else { // In ALLOCATE mode we cannot choose which IP buffer to use. We will get // the surprise when FrameProcessed() is invoked... if (!image_processor_->Process( std::move(input_frame), base::BindOnce(&V4L2SliceVideoDecodeAccelerator::FrameProcessed, base::Unretained(this), surface))) return false; } surfaces_at_ip_.push(std::make_pair(std::move(surface), std::move(buffer))); return true; } void V4L2SliceVideoDecodeAccelerator::FrameProcessed( scoped_refptr<V4L2DecodeSurface> surface, size_t ip_buffer_index, scoped_refptr<VideoFrame> frame) { DVLOGF(4); DCHECK(decoder_thread_.task_runner()->BelongsToCurrentThread()); if (IsDestroyPending()) return; // TODO(crbug.com/921825): Remove this workaround once reset callback is // implemented. if (surfaces_at_ip_.empty() || surfaces_at_ip_.front().first != surface || output_buffer_map_.empty()) { // This can happen if image processor is reset. // V4L2SliceVideoDecodeAccelerator::Reset() makes // |buffers_at_ip_| empty. // During ImageProcessor::Reset(), some FrameProcessed() can have been // posted to |decoder_thread|. |bitsream_buffer_id| is pushed to // |buffers_at_ip_| in ProcessFrame(). Although we // are not sure a new bitstream buffer id is pushed after Reset() and before // FrameProcessed(), We should skip the case of mismatch of bitstream buffer // id for safety. // For |output_buffer_map_|, it is cleared in Destroy(). Destroy() destroys // ImageProcessor which may call FrameProcessed() in parallel similar to // Reset() case. DVLOGF(4) << "Ignore processed frame after reset"; return; } DCHECK_LT(ip_buffer_index, output_buffer_map_.size()); OutputRecord& ip_output_record = output_buffer_map_[ip_buffer_index]; // If the picture has not been cleared yet, this means it is the first time // we are seeing this buffer from the image processor. Schedule a call to // CreateGLImageFor before the picture is sent to the client. It is // guaranteed that CreateGLImageFor will complete before the picture is sent // to the client as both events happen on the child thread due to the picture // uncleared status. if (ip_output_record.texture_id != 0 && !ip_output_record.cleared) { DCHECK(frame->HasDmaBufs()); child_task_runner_->PostTask( FROM_HERE, base::BindOnce(&V4L2SliceVideoDecodeAccelerator::CreateGLImageFor, weak_this_, ip_buffer_index, ip_output_record.picture_id, media::DuplicateFDs(frame->DmabufFds()), ip_output_record.client_texture_id, ip_output_record.texture_id, gl_image_size_, gl_image_format_fourcc_)); } DCHECK(!surfaces_at_ip_.empty()); DCHECK_EQ(surfaces_at_ip_.front().first, surface); V4L2ReadableBufferRef decoded_buffer = std::move(surfaces_at_ip_.front().second); surfaces_at_ip_.pop(); DCHECK_EQ(decoded_buffer->BufferId(), static_cast<size_t>(surface->output_record())); // Keep the decoder buffer until the IP frame is itself released. // We need to keep this V4L2 frame because the decode surface still references // its index and we will use its OutputRecord to reference the IP buffer. frame->AddDestructionObserver( base::BindOnce(&V4L2SliceVideoDecodeAccelerator::ReuseOutputBuffer, base::Unretained(this), decoded_buffer)); // This holds the IP video frame until everyone is done with it surface->SetReleaseCallback( base::BindOnce([](scoped_refptr<VideoFrame> frame) {}, frame)); DCHECK_EQ(decoded_buffer_map_.count(decoded_buffer->BufferId()), 0u); decoded_buffer_map_.emplace(decoded_buffer->BufferId(), ip_buffer_index); surface->SetDecoded(); TryOutputSurfaces(); ProcessPendingEventsIfNeeded(); ScheduleDecodeBufferTaskIfNeeded(); } // base::trace_event::MemoryDumpProvider implementation. bool V4L2SliceVideoDecodeAccelerator::OnMemoryDump( const base::trace_event::MemoryDumpArgs& args, base::trace_event::ProcessMemoryDump* pmd) { // OnMemoryDump() must be performed on |decoder_thread_|. DCHECK(decoder_thread_.task_runner()->BelongsToCurrentThread()); // VIDEO_OUTPUT queue's memory usage. const size_t input_queue_buffers_count = input_queue_->AllocatedBuffersCount(); size_t input_queue_memory_usage = 0; std::string input_queue_buffers_memory_type = V4L2Device::V4L2MemoryToString(input_queue_->GetMemoryType()); input_queue_memory_usage += input_queue_->GetMemoryUsage(); // VIDEO_CAPTURE queue's memory usage. const size_t output_queue_buffers_count = output_buffer_map_.size(); size_t output_queue_memory_usage = 0; std::string output_queue_buffers_memory_type = V4L2Device::V4L2MemoryToString(output_queue_->GetMemoryType()); if (output_mode_ == Config::OutputMode::ALLOCATE) { // Call QUERY_BUF here because the length of buffers on VIDIOC_CATURE queue // are not recorded nowhere in V4L2VideoDecodeAccelerator. for (uint32_t index = 0; index < output_buffer_map_.size(); ++index) { struct v4l2_buffer v4l2_buffer = {}; struct v4l2_plane v4l2_planes[VIDEO_MAX_PLANES]; DCHECK_LT(output_planes_count_, base::size(v4l2_planes)); v4l2_buffer.m.planes = v4l2_planes; v4l2_buffer.length = std::min(output_planes_count_, base::size(v4l2_planes)); v4l2_buffer.index = index; v4l2_buffer.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE; v4l2_buffer.memory = V4L2_MEMORY_MMAP; IOCTL_OR_ERROR_RETURN_FALSE(VIDIOC_QUERYBUF, &v4l2_buffer); for (size_t i = 0; i < output_planes_count_; ++i) output_queue_memory_usage += v4l2_buffer.m.planes[i].length; } } const size_t total_usage = input_queue_memory_usage + output_queue_memory_usage; using ::base::trace_event::MemoryAllocatorDump; auto dump_name = base::StringPrintf("gpu/v4l2/slice_decoder/0x%" PRIxPTR, reinterpret_cast<uintptr_t>(this)); MemoryAllocatorDump* dump = pmd->CreateAllocatorDump(dump_name); dump->AddScalar(MemoryAllocatorDump::kNameSize, MemoryAllocatorDump::kUnitsBytes, static_cast<uint64_t>(total_usage)); dump->AddScalar("input_queue_memory_usage", MemoryAllocatorDump::kUnitsBytes, static_cast<uint64_t>(input_queue_memory_usage)); dump->AddScalar("input_queue_buffers_count", MemoryAllocatorDump::kUnitsObjects, static_cast<uint64_t>(input_queue_buffers_count)); dump->AddString("input_queue_buffers_memory_type", "", input_queue_buffers_memory_type); dump->AddScalar("output_queue_memory_usage", MemoryAllocatorDump::kUnitsBytes, static_cast<uint64_t>(output_queue_memory_usage)); dump->AddScalar("output_queue_buffers_count", MemoryAllocatorDump::kUnitsObjects, static_cast<uint64_t>(output_queue_buffers_count)); dump->AddString("output_queue_buffers_memory_type", "", output_queue_buffers_memory_type); return true; } } // namespace media
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
57c95729598d3a40028f050f77920a198025ab9b
12154201c2c4dc8968b690fa8237ebfe1932f60a
/BOJ/1408.cpp
f9ad36c8837d2e7fb34019cc1b21e3dd52c98de0
[]
no_license
heon24500/PS
9cc028de3d9b1a26543b5bd498cfd5134d3d6de4
df901f6fc71f8c9d659b4c5397d44de9a2031a9d
refs/heads/master
2023-02-20T17:06:30.065944
2021-01-25T12:43:48
2021-01-25T12:43:48
268,433,390
2
0
null
null
null
null
UTF-8
C++
false
false
715
cpp
#include <iostream> using namespace std; int main() { ios::sync_with_stdio(0); cin.tie(0); char temp; int n[3], s[3], r[3]; cin >> n[0] >> temp >> n[1] >> temp >> n[2]; cin >> s[0] >> temp >> s[1] >> temp >> s[2]; if (n[0] > s[0] || (n[0] == s[0] && n[1] > s[1]) || (n[0] == s[0] && n[1] == s[1] && n[2] > s[2])) s[0] += 24; r[2] = s[2] - n[2]; if (r[2] < 0) { r[2] += 60; s[1]--; } r[1] = s[1] - n[1]; if (r[1] < 0) { r[1] += 60; s[0]--; } r[0] = s[0] - n[0]; if (r[0] < 10) cout << 0; cout << r[0] << ":"; if (r[1] < 10) cout << 0; cout << r[1] << ":"; if (r[2] < 10) cout << 0; cout << r[2]; }
[ "heon24500@naver.com" ]
heon24500@naver.com
04fd6fad9c00c15d184f0587ac2a4f9778328134
60db84d8cb6a58bdb3fb8df8db954d9d66024137
/android-cpp-sdk/platforms/android-7/org/w3c/dom/Node.hpp
f3c4c62d305e7267f6f69be783b618c432bac02a
[ "BSL-1.0" ]
permissive
tpurtell/android-cpp-sdk
ba853335b3a5bd7e2b5c56dcb5a5be848da6550c
8313bb88332c5476645d5850fe5fdee8998c2415
refs/heads/master
2021-01-10T20:46:37.322718
2012-07-17T22:06:16
2012-07-17T22:06:16
37,555,992
5
4
null
null
null
null
UTF-8
C++
false
false
18,786
hpp
/*================================================================================ code generated by: java2cpp author: Zoran Angelov, mailto://baldzar@gmail.com class: org.w3c.dom.Node ================================================================================*/ #ifndef J2CPP_INCLUDE_IMPLEMENTATION #ifndef J2CPP_ORG_W3C_DOM_NODE_HPP_DECL #define J2CPP_ORG_W3C_DOM_NODE_HPP_DECL namespace j2cpp { namespace java { namespace lang { class Object; } } } namespace j2cpp { namespace java { namespace lang { class String; } } } namespace j2cpp { namespace org { namespace w3c { namespace dom { class Document; } } } } namespace j2cpp { namespace org { namespace w3c { namespace dom { class NamedNodeMap; } } } } namespace j2cpp { namespace org { namespace w3c { namespace dom { class NodeList; } } } } #include <java/lang/Object.hpp> #include <java/lang/String.hpp> #include <org/w3c/dom/Document.hpp> #include <org/w3c/dom/NamedNodeMap.hpp> #include <org/w3c/dom/NodeList.hpp> namespace j2cpp { namespace org { namespace w3c { namespace dom { class Node; class Node : public object<Node> { public: J2CPP_DECLARE_CLASS J2CPP_DECLARE_METHOD(0) J2CPP_DECLARE_METHOD(1) J2CPP_DECLARE_METHOD(2) J2CPP_DECLARE_METHOD(3) J2CPP_DECLARE_METHOD(4) J2CPP_DECLARE_METHOD(5) J2CPP_DECLARE_METHOD(6) J2CPP_DECLARE_METHOD(7) J2CPP_DECLARE_METHOD(8) J2CPP_DECLARE_METHOD(9) J2CPP_DECLARE_METHOD(10) J2CPP_DECLARE_METHOD(11) J2CPP_DECLARE_METHOD(12) J2CPP_DECLARE_METHOD(13) J2CPP_DECLARE_METHOD(14) J2CPP_DECLARE_METHOD(15) J2CPP_DECLARE_METHOD(16) J2CPP_DECLARE_METHOD(17) J2CPP_DECLARE_METHOD(18) J2CPP_DECLARE_METHOD(19) J2CPP_DECLARE_METHOD(20) J2CPP_DECLARE_METHOD(21) J2CPP_DECLARE_METHOD(22) J2CPP_DECLARE_METHOD(23) J2CPP_DECLARE_METHOD(24) J2CPP_DECLARE_FIELD(0) J2CPP_DECLARE_FIELD(1) J2CPP_DECLARE_FIELD(2) J2CPP_DECLARE_FIELD(3) J2CPP_DECLARE_FIELD(4) J2CPP_DECLARE_FIELD(5) J2CPP_DECLARE_FIELD(6) J2CPP_DECLARE_FIELD(7) J2CPP_DECLARE_FIELD(8) J2CPP_DECLARE_FIELD(9) J2CPP_DECLARE_FIELD(10) J2CPP_DECLARE_FIELD(11) explicit Node(jobject jobj) : object<Node>(jobj) { } operator local_ref<java::lang::Object>() const; local_ref< java::lang::String > getNodeName(); local_ref< java::lang::String > getNodeValue(); void setNodeValue(local_ref< java::lang::String > const&); jshort getNodeType(); local_ref< org::w3c::dom::Node > getParentNode(); local_ref< org::w3c::dom::NodeList > getChildNodes(); local_ref< org::w3c::dom::Node > getFirstChild(); local_ref< org::w3c::dom::Node > getLastChild(); local_ref< org::w3c::dom::Node > getPreviousSibling(); local_ref< org::w3c::dom::Node > getNextSibling(); local_ref< org::w3c::dom::NamedNodeMap > getAttributes(); local_ref< org::w3c::dom::Document > getOwnerDocument(); local_ref< org::w3c::dom::Node > insertBefore(local_ref< org::w3c::dom::Node > const&, local_ref< org::w3c::dom::Node > const&); local_ref< org::w3c::dom::Node > replaceChild(local_ref< org::w3c::dom::Node > const&, local_ref< org::w3c::dom::Node > const&); local_ref< org::w3c::dom::Node > removeChild(local_ref< org::w3c::dom::Node > const&); local_ref< org::w3c::dom::Node > appendChild(local_ref< org::w3c::dom::Node > const&); jboolean hasChildNodes(); local_ref< org::w3c::dom::Node > cloneNode(jboolean); void normalize(); jboolean isSupported(local_ref< java::lang::String > const&, local_ref< java::lang::String > const&); local_ref< java::lang::String > getNamespaceURI(); local_ref< java::lang::String > getPrefix(); void setPrefix(local_ref< java::lang::String > const&); local_ref< java::lang::String > getLocalName(); jboolean hasAttributes(); static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(0), J2CPP_FIELD_SIGNATURE(0), jshort > ELEMENT_NODE; static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(1), J2CPP_FIELD_SIGNATURE(1), jshort > ATTRIBUTE_NODE; static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(2), J2CPP_FIELD_SIGNATURE(2), jshort > TEXT_NODE; static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(3), J2CPP_FIELD_SIGNATURE(3), jshort > CDATA_SECTION_NODE; static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(4), J2CPP_FIELD_SIGNATURE(4), jshort > ENTITY_REFERENCE_NODE; static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(5), J2CPP_FIELD_SIGNATURE(5), jshort > ENTITY_NODE; static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(6), J2CPP_FIELD_SIGNATURE(6), jshort > PROCESSING_INSTRUCTION_NODE; static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(7), J2CPP_FIELD_SIGNATURE(7), jshort > COMMENT_NODE; static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(8), J2CPP_FIELD_SIGNATURE(8), jshort > DOCUMENT_NODE; static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(9), J2CPP_FIELD_SIGNATURE(9), jshort > DOCUMENT_TYPE_NODE; static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(10), J2CPP_FIELD_SIGNATURE(10), jshort > DOCUMENT_FRAGMENT_NODE; static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(11), J2CPP_FIELD_SIGNATURE(11), jshort > NOTATION_NODE; }; //class Node } //namespace dom } //namespace w3c } //namespace org } //namespace j2cpp #endif //J2CPP_ORG_W3C_DOM_NODE_HPP_DECL #else //J2CPP_INCLUDE_IMPLEMENTATION #ifndef J2CPP_ORG_W3C_DOM_NODE_HPP_IMPL #define J2CPP_ORG_W3C_DOM_NODE_HPP_IMPL namespace j2cpp { org::w3c::dom::Node::operator local_ref<java::lang::Object>() const { return local_ref<java::lang::Object>(get_jobject()); } local_ref< java::lang::String > org::w3c::dom::Node::getNodeName() { return call_method< org::w3c::dom::Node::J2CPP_CLASS_NAME, org::w3c::dom::Node::J2CPP_METHOD_NAME(0), org::w3c::dom::Node::J2CPP_METHOD_SIGNATURE(0), local_ref< java::lang::String > >(get_jobject()); } local_ref< java::lang::String > org::w3c::dom::Node::getNodeValue() { return call_method< org::w3c::dom::Node::J2CPP_CLASS_NAME, org::w3c::dom::Node::J2CPP_METHOD_NAME(1), org::w3c::dom::Node::J2CPP_METHOD_SIGNATURE(1), local_ref< java::lang::String > >(get_jobject()); } void org::w3c::dom::Node::setNodeValue(local_ref< java::lang::String > const &a0) { return call_method< org::w3c::dom::Node::J2CPP_CLASS_NAME, org::w3c::dom::Node::J2CPP_METHOD_NAME(2), org::w3c::dom::Node::J2CPP_METHOD_SIGNATURE(2), void >(get_jobject(), a0); } jshort org::w3c::dom::Node::getNodeType() { return call_method< org::w3c::dom::Node::J2CPP_CLASS_NAME, org::w3c::dom::Node::J2CPP_METHOD_NAME(3), org::w3c::dom::Node::J2CPP_METHOD_SIGNATURE(3), jshort >(get_jobject()); } local_ref< org::w3c::dom::Node > org::w3c::dom::Node::getParentNode() { return call_method< org::w3c::dom::Node::J2CPP_CLASS_NAME, org::w3c::dom::Node::J2CPP_METHOD_NAME(4), org::w3c::dom::Node::J2CPP_METHOD_SIGNATURE(4), local_ref< org::w3c::dom::Node > >(get_jobject()); } local_ref< org::w3c::dom::NodeList > org::w3c::dom::Node::getChildNodes() { return call_method< org::w3c::dom::Node::J2CPP_CLASS_NAME, org::w3c::dom::Node::J2CPP_METHOD_NAME(5), org::w3c::dom::Node::J2CPP_METHOD_SIGNATURE(5), local_ref< org::w3c::dom::NodeList > >(get_jobject()); } local_ref< org::w3c::dom::Node > org::w3c::dom::Node::getFirstChild() { return call_method< org::w3c::dom::Node::J2CPP_CLASS_NAME, org::w3c::dom::Node::J2CPP_METHOD_NAME(6), org::w3c::dom::Node::J2CPP_METHOD_SIGNATURE(6), local_ref< org::w3c::dom::Node > >(get_jobject()); } local_ref< org::w3c::dom::Node > org::w3c::dom::Node::getLastChild() { return call_method< org::w3c::dom::Node::J2CPP_CLASS_NAME, org::w3c::dom::Node::J2CPP_METHOD_NAME(7), org::w3c::dom::Node::J2CPP_METHOD_SIGNATURE(7), local_ref< org::w3c::dom::Node > >(get_jobject()); } local_ref< org::w3c::dom::Node > org::w3c::dom::Node::getPreviousSibling() { return call_method< org::w3c::dom::Node::J2CPP_CLASS_NAME, org::w3c::dom::Node::J2CPP_METHOD_NAME(8), org::w3c::dom::Node::J2CPP_METHOD_SIGNATURE(8), local_ref< org::w3c::dom::Node > >(get_jobject()); } local_ref< org::w3c::dom::Node > org::w3c::dom::Node::getNextSibling() { return call_method< org::w3c::dom::Node::J2CPP_CLASS_NAME, org::w3c::dom::Node::J2CPP_METHOD_NAME(9), org::w3c::dom::Node::J2CPP_METHOD_SIGNATURE(9), local_ref< org::w3c::dom::Node > >(get_jobject()); } local_ref< org::w3c::dom::NamedNodeMap > org::w3c::dom::Node::getAttributes() { return call_method< org::w3c::dom::Node::J2CPP_CLASS_NAME, org::w3c::dom::Node::J2CPP_METHOD_NAME(10), org::w3c::dom::Node::J2CPP_METHOD_SIGNATURE(10), local_ref< org::w3c::dom::NamedNodeMap > >(get_jobject()); } local_ref< org::w3c::dom::Document > org::w3c::dom::Node::getOwnerDocument() { return call_method< org::w3c::dom::Node::J2CPP_CLASS_NAME, org::w3c::dom::Node::J2CPP_METHOD_NAME(11), org::w3c::dom::Node::J2CPP_METHOD_SIGNATURE(11), local_ref< org::w3c::dom::Document > >(get_jobject()); } local_ref< org::w3c::dom::Node > org::w3c::dom::Node::insertBefore(local_ref< org::w3c::dom::Node > const &a0, local_ref< org::w3c::dom::Node > const &a1) { return call_method< org::w3c::dom::Node::J2CPP_CLASS_NAME, org::w3c::dom::Node::J2CPP_METHOD_NAME(12), org::w3c::dom::Node::J2CPP_METHOD_SIGNATURE(12), local_ref< org::w3c::dom::Node > >(get_jobject(), a0, a1); } local_ref< org::w3c::dom::Node > org::w3c::dom::Node::replaceChild(local_ref< org::w3c::dom::Node > const &a0, local_ref< org::w3c::dom::Node > const &a1) { return call_method< org::w3c::dom::Node::J2CPP_CLASS_NAME, org::w3c::dom::Node::J2CPP_METHOD_NAME(13), org::w3c::dom::Node::J2CPP_METHOD_SIGNATURE(13), local_ref< org::w3c::dom::Node > >(get_jobject(), a0, a1); } local_ref< org::w3c::dom::Node > org::w3c::dom::Node::removeChild(local_ref< org::w3c::dom::Node > const &a0) { return call_method< org::w3c::dom::Node::J2CPP_CLASS_NAME, org::w3c::dom::Node::J2CPP_METHOD_NAME(14), org::w3c::dom::Node::J2CPP_METHOD_SIGNATURE(14), local_ref< org::w3c::dom::Node > >(get_jobject(), a0); } local_ref< org::w3c::dom::Node > org::w3c::dom::Node::appendChild(local_ref< org::w3c::dom::Node > const &a0) { return call_method< org::w3c::dom::Node::J2CPP_CLASS_NAME, org::w3c::dom::Node::J2CPP_METHOD_NAME(15), org::w3c::dom::Node::J2CPP_METHOD_SIGNATURE(15), local_ref< org::w3c::dom::Node > >(get_jobject(), a0); } jboolean org::w3c::dom::Node::hasChildNodes() { return call_method< org::w3c::dom::Node::J2CPP_CLASS_NAME, org::w3c::dom::Node::J2CPP_METHOD_NAME(16), org::w3c::dom::Node::J2CPP_METHOD_SIGNATURE(16), jboolean >(get_jobject()); } local_ref< org::w3c::dom::Node > org::w3c::dom::Node::cloneNode(jboolean a0) { return call_method< org::w3c::dom::Node::J2CPP_CLASS_NAME, org::w3c::dom::Node::J2CPP_METHOD_NAME(17), org::w3c::dom::Node::J2CPP_METHOD_SIGNATURE(17), local_ref< org::w3c::dom::Node > >(get_jobject(), a0); } void org::w3c::dom::Node::normalize() { return call_method< org::w3c::dom::Node::J2CPP_CLASS_NAME, org::w3c::dom::Node::J2CPP_METHOD_NAME(18), org::w3c::dom::Node::J2CPP_METHOD_SIGNATURE(18), void >(get_jobject()); } jboolean org::w3c::dom::Node::isSupported(local_ref< java::lang::String > const &a0, local_ref< java::lang::String > const &a1) { return call_method< org::w3c::dom::Node::J2CPP_CLASS_NAME, org::w3c::dom::Node::J2CPP_METHOD_NAME(19), org::w3c::dom::Node::J2CPP_METHOD_SIGNATURE(19), jboolean >(get_jobject(), a0, a1); } local_ref< java::lang::String > org::w3c::dom::Node::getNamespaceURI() { return call_method< org::w3c::dom::Node::J2CPP_CLASS_NAME, org::w3c::dom::Node::J2CPP_METHOD_NAME(20), org::w3c::dom::Node::J2CPP_METHOD_SIGNATURE(20), local_ref< java::lang::String > >(get_jobject()); } local_ref< java::lang::String > org::w3c::dom::Node::getPrefix() { return call_method< org::w3c::dom::Node::J2CPP_CLASS_NAME, org::w3c::dom::Node::J2CPP_METHOD_NAME(21), org::w3c::dom::Node::J2CPP_METHOD_SIGNATURE(21), local_ref< java::lang::String > >(get_jobject()); } void org::w3c::dom::Node::setPrefix(local_ref< java::lang::String > const &a0) { return call_method< org::w3c::dom::Node::J2CPP_CLASS_NAME, org::w3c::dom::Node::J2CPP_METHOD_NAME(22), org::w3c::dom::Node::J2CPP_METHOD_SIGNATURE(22), void >(get_jobject(), a0); } local_ref< java::lang::String > org::w3c::dom::Node::getLocalName() { return call_method< org::w3c::dom::Node::J2CPP_CLASS_NAME, org::w3c::dom::Node::J2CPP_METHOD_NAME(23), org::w3c::dom::Node::J2CPP_METHOD_SIGNATURE(23), local_ref< java::lang::String > >(get_jobject()); } jboolean org::w3c::dom::Node::hasAttributes() { return call_method< org::w3c::dom::Node::J2CPP_CLASS_NAME, org::w3c::dom::Node::J2CPP_METHOD_NAME(24), org::w3c::dom::Node::J2CPP_METHOD_SIGNATURE(24), jboolean >(get_jobject()); } static_field< org::w3c::dom::Node::J2CPP_CLASS_NAME, org::w3c::dom::Node::J2CPP_FIELD_NAME(0), org::w3c::dom::Node::J2CPP_FIELD_SIGNATURE(0), jshort > org::w3c::dom::Node::ELEMENT_NODE; static_field< org::w3c::dom::Node::J2CPP_CLASS_NAME, org::w3c::dom::Node::J2CPP_FIELD_NAME(1), org::w3c::dom::Node::J2CPP_FIELD_SIGNATURE(1), jshort > org::w3c::dom::Node::ATTRIBUTE_NODE; static_field< org::w3c::dom::Node::J2CPP_CLASS_NAME, org::w3c::dom::Node::J2CPP_FIELD_NAME(2), org::w3c::dom::Node::J2CPP_FIELD_SIGNATURE(2), jshort > org::w3c::dom::Node::TEXT_NODE; static_field< org::w3c::dom::Node::J2CPP_CLASS_NAME, org::w3c::dom::Node::J2CPP_FIELD_NAME(3), org::w3c::dom::Node::J2CPP_FIELD_SIGNATURE(3), jshort > org::w3c::dom::Node::CDATA_SECTION_NODE; static_field< org::w3c::dom::Node::J2CPP_CLASS_NAME, org::w3c::dom::Node::J2CPP_FIELD_NAME(4), org::w3c::dom::Node::J2CPP_FIELD_SIGNATURE(4), jshort > org::w3c::dom::Node::ENTITY_REFERENCE_NODE; static_field< org::w3c::dom::Node::J2CPP_CLASS_NAME, org::w3c::dom::Node::J2CPP_FIELD_NAME(5), org::w3c::dom::Node::J2CPP_FIELD_SIGNATURE(5), jshort > org::w3c::dom::Node::ENTITY_NODE; static_field< org::w3c::dom::Node::J2CPP_CLASS_NAME, org::w3c::dom::Node::J2CPP_FIELD_NAME(6), org::w3c::dom::Node::J2CPP_FIELD_SIGNATURE(6), jshort > org::w3c::dom::Node::PROCESSING_INSTRUCTION_NODE; static_field< org::w3c::dom::Node::J2CPP_CLASS_NAME, org::w3c::dom::Node::J2CPP_FIELD_NAME(7), org::w3c::dom::Node::J2CPP_FIELD_SIGNATURE(7), jshort > org::w3c::dom::Node::COMMENT_NODE; static_field< org::w3c::dom::Node::J2CPP_CLASS_NAME, org::w3c::dom::Node::J2CPP_FIELD_NAME(8), org::w3c::dom::Node::J2CPP_FIELD_SIGNATURE(8), jshort > org::w3c::dom::Node::DOCUMENT_NODE; static_field< org::w3c::dom::Node::J2CPP_CLASS_NAME, org::w3c::dom::Node::J2CPP_FIELD_NAME(9), org::w3c::dom::Node::J2CPP_FIELD_SIGNATURE(9), jshort > org::w3c::dom::Node::DOCUMENT_TYPE_NODE; static_field< org::w3c::dom::Node::J2CPP_CLASS_NAME, org::w3c::dom::Node::J2CPP_FIELD_NAME(10), org::w3c::dom::Node::J2CPP_FIELD_SIGNATURE(10), jshort > org::w3c::dom::Node::DOCUMENT_FRAGMENT_NODE; static_field< org::w3c::dom::Node::J2CPP_CLASS_NAME, org::w3c::dom::Node::J2CPP_FIELD_NAME(11), org::w3c::dom::Node::J2CPP_FIELD_SIGNATURE(11), jshort > org::w3c::dom::Node::NOTATION_NODE; J2CPP_DEFINE_CLASS(org::w3c::dom::Node,"org/w3c/dom/Node") J2CPP_DEFINE_METHOD(org::w3c::dom::Node,0,"getNodeName","()Ljava/lang/String;") J2CPP_DEFINE_METHOD(org::w3c::dom::Node,1,"getNodeValue","()Ljava/lang/String;") J2CPP_DEFINE_METHOD(org::w3c::dom::Node,2,"setNodeValue","(Ljava/lang/String;)V") J2CPP_DEFINE_METHOD(org::w3c::dom::Node,3,"getNodeType","()S") J2CPP_DEFINE_METHOD(org::w3c::dom::Node,4,"getParentNode","()Lorg/w3c/dom/Node;") J2CPP_DEFINE_METHOD(org::w3c::dom::Node,5,"getChildNodes","()Lorg/w3c/dom/NodeList;") J2CPP_DEFINE_METHOD(org::w3c::dom::Node,6,"getFirstChild","()Lorg/w3c/dom/Node;") J2CPP_DEFINE_METHOD(org::w3c::dom::Node,7,"getLastChild","()Lorg/w3c/dom/Node;") J2CPP_DEFINE_METHOD(org::w3c::dom::Node,8,"getPreviousSibling","()Lorg/w3c/dom/Node;") J2CPP_DEFINE_METHOD(org::w3c::dom::Node,9,"getNextSibling","()Lorg/w3c/dom/Node;") J2CPP_DEFINE_METHOD(org::w3c::dom::Node,10,"getAttributes","()Lorg/w3c/dom/NamedNodeMap;") J2CPP_DEFINE_METHOD(org::w3c::dom::Node,11,"getOwnerDocument","()Lorg/w3c/dom/Document;") J2CPP_DEFINE_METHOD(org::w3c::dom::Node,12,"insertBefore","(Lorg/w3c/dom/Node;Lorg/w3c/dom/Node;)Lorg/w3c/dom/Node;") J2CPP_DEFINE_METHOD(org::w3c::dom::Node,13,"replaceChild","(Lorg/w3c/dom/Node;Lorg/w3c/dom/Node;)Lorg/w3c/dom/Node;") J2CPP_DEFINE_METHOD(org::w3c::dom::Node,14,"removeChild","(Lorg/w3c/dom/Node;)Lorg/w3c/dom/Node;") J2CPP_DEFINE_METHOD(org::w3c::dom::Node,15,"appendChild","(Lorg/w3c/dom/Node;)Lorg/w3c/dom/Node;") J2CPP_DEFINE_METHOD(org::w3c::dom::Node,16,"hasChildNodes","()Z") J2CPP_DEFINE_METHOD(org::w3c::dom::Node,17,"cloneNode","(Z)Lorg/w3c/dom/Node;") J2CPP_DEFINE_METHOD(org::w3c::dom::Node,18,"normalize","()V") J2CPP_DEFINE_METHOD(org::w3c::dom::Node,19,"isSupported","(Ljava/lang/String;Ljava/lang/String;)Z") J2CPP_DEFINE_METHOD(org::w3c::dom::Node,20,"getNamespaceURI","()Ljava/lang/String;") J2CPP_DEFINE_METHOD(org::w3c::dom::Node,21,"getPrefix","()Ljava/lang/String;") J2CPP_DEFINE_METHOD(org::w3c::dom::Node,22,"setPrefix","(Ljava/lang/String;)V") J2CPP_DEFINE_METHOD(org::w3c::dom::Node,23,"getLocalName","()Ljava/lang/String;") J2CPP_DEFINE_METHOD(org::w3c::dom::Node,24,"hasAttributes","()Z") J2CPP_DEFINE_FIELD(org::w3c::dom::Node,0,"ELEMENT_NODE","S") J2CPP_DEFINE_FIELD(org::w3c::dom::Node,1,"ATTRIBUTE_NODE","S") J2CPP_DEFINE_FIELD(org::w3c::dom::Node,2,"TEXT_NODE","S") J2CPP_DEFINE_FIELD(org::w3c::dom::Node,3,"CDATA_SECTION_NODE","S") J2CPP_DEFINE_FIELD(org::w3c::dom::Node,4,"ENTITY_REFERENCE_NODE","S") J2CPP_DEFINE_FIELD(org::w3c::dom::Node,5,"ENTITY_NODE","S") J2CPP_DEFINE_FIELD(org::w3c::dom::Node,6,"PROCESSING_INSTRUCTION_NODE","S") J2CPP_DEFINE_FIELD(org::w3c::dom::Node,7,"COMMENT_NODE","S") J2CPP_DEFINE_FIELD(org::w3c::dom::Node,8,"DOCUMENT_NODE","S") J2CPP_DEFINE_FIELD(org::w3c::dom::Node,9,"DOCUMENT_TYPE_NODE","S") J2CPP_DEFINE_FIELD(org::w3c::dom::Node,10,"DOCUMENT_FRAGMENT_NODE","S") J2CPP_DEFINE_FIELD(org::w3c::dom::Node,11,"NOTATION_NODE","S") } //namespace j2cpp #endif //J2CPP_ORG_W3C_DOM_NODE_HPP_IMPL #endif //J2CPP_INCLUDE_IMPLEMENTATION
[ "baldzar@gmail.com" ]
baldzar@gmail.com
872ac6169ed38c7baba41cb29ffbca027ca5927b
d4954c36aaee9e59391082b3f66daf2fac999e5c
/CourseWork-3sem/MainMenu.cpp
906282380bec41c5ae30d7bd45f3486a2bab376c
[]
no_license
Sintexer/CourseWork-3sem
621a4730f41e6ba69d1779a382cb3b55c3b608c7
44a73620e41d260fabb3787379912b393d3f3dd3
refs/heads/master
2020-09-22T00:04:45.616950
2019-12-18T16:55:46
2019-12-18T16:55:46
224,980,299
1
0
null
null
null
null
WINDOWS-1251
C++
false
false
5,297
cpp
#include "MainMenu.h" #include "Interface.h" #include "PhysTest.h" #include "MathTest.h" #include "PersonalityTest.h" #include "ProfTest.h" #include "TeachingTest.h" void MainMenu::init() //Метод вывода меню на экран пользователя и работы с ним { size_t answer{}; //Переменная для ввода пользователя do { system("cls"); cout << "Главное меню\n\n" << "Выберите вид тестов:\n" << "1: Психологические тесты\n" << "2: Тесты по предметам обучения\n" << "3: Тесты обучающие\n\n" << "0: Выход" << endl; inputSafe(cin, answer, 0, 3); //Метод безопасного ввода числа в диапазоне switch (answer){ case 1: if (!psychoTestMenu()) //Меню психологических тестов, вернет false, если пользователь решил выйти return; //Выход из меню break; case 2: if (!ratingTestMenu()) //Меню тестов оценивания знаний, вернет false, если пользователь решил выйти return; //Выход из меню break; case 3: if (!teachingTestMenu()) //Меню обучающих тестов, вернет false, если пользователь решил выйти return; //Выход из меню break; case 0: return;//Выход из программы default: cout << "Некорректный ввод, выберите цифру из меню\n" << endl; system("pause"); break; } } while (answer); system("cls"); } bool MainMenu::psychoTestMenu() { size_t answer{};//Переменная для ввода пользователя do { system("cls"); cout << "Психологические тесты\n\n" << "Выберите вид тестов:\n" << "1: Личностные\n" << "2: Тесты на проф пригодность\n\n" << "3: Главное меню\n" << "0: Выход" << endl; inputSafe(cin, answer, 0, 3);//Метод безопасного ввода числа в диапазоне switch (answer){ case 1: { Interface<PersTest> inter;//Инициализация интерфейса Личностных тестов inter.init(); //Вводит тесты из файла в дерево if (!inter.chooseTest()) //Вернет false, если пользователь решил выйти из программы return false; break; } case 2: { Interface<ProfTest> inter;//Инициализация интерфейса тестов на проф пригодность inter.init(); //Вводит тесты из файла в дерево if (!inter.chooseTest()) //Вернет false, если пользователь решил выйти из программы return false; } case 3: return true; //Возврат в главное меню break; case 0: return false; //Выход из программы break; default: cout << "Некорректный ввод, выберите цифру из меню" << endl; system("pause"); break; } } while (answer); system("cls"); return false;//Выход из программы } bool MainMenu::ratingTestMenu() { size_t answer{};//Переменная для ввода пользователя do { system("cls"); cout << "Тесты по предметам обучения\n\n" << "Выберите предмет:\n" << "1: Математика\n" << "2: Физика\n\n" << "3: Главное меню\n" << "0: Выход" << endl; inputSafe(cin, answer, 0, 3);//Метод безопасного ввода числа в диапазоне switch (answer){ case 1: { Interface<MathTest> inter; //Инициализация интерфейса тестов по математике inter.init(); //Вводит тесты из файла в дерево if (!inter.chooseTest()) //Вернет false, если пользователь решил выйти из программы return false; break; } case 2: { Interface<PhysTest> inter; inter.init(); //Инициализация интерфейса тестов по физике if (!inter.chooseTest()) //Вернет false, если пользователь решил выйти из программы return false;//Выход из программы break; } case 3: return true;//Возврат в главное меню case 0: return false;//Выход из программы default: cout << "Некорректный ввод, выберите цифру из меню" << endl; system("pause"); break; } } while (answer); system("cls"); return false;//Выход из программы } bool MainMenu::teachingTestMenu() { Interface<TeachingTest> inter; inter.init(); //Вводит тесты из файла в дерево if (!inter.chooseTest()) //Вернет false, если пользователь решил выйти из программы return false; return true;//Возврат в главное меню }
[ "neonlightnight@gmail.com" ]
neonlightnight@gmail.com
0e754574eb552a66b5d018aac1129dc282f8bde6
be6b8917be00a203c418765a65b2665cbd41c36c
/source/common/vec.h
df85aef205d61fca75c86b09dad0321808ccef33
[]
no_license
noahhendlish/Raytracing
ec072c5841552ff23f1f0aeea74df3f9c9c748cc
43b50e66ff0129c8679bc89fe9b1ff4e67c4d113
refs/heads/master
2022-11-09T09:33:21.694918
2020-06-17T03:12:35
2020-06-17T03:12:35
272,866,461
1
0
null
null
null
null
UTF-8
C++
false
false
10,640
h
////////////////////////////////////////////////////////////////////////////// // // --- vec.h --- // ////////////////////////////////////////////////////////////////////////////// #ifndef __ANGEL_VEC_H__ #define __ANGEL_VEC_H__ #include "common.h" namespace Angel { ////////////////////////////////////////////////////////////////////////////// // // vec2.h - 2D vector // struct vec2 { GLfloat x; GLfloat y; // // --- Constructors and Destructors --- // vec2( GLfloat s = GLfloat(0.0) ) : x(s), y(s) {} vec2( GLfloat x, GLfloat y ) : x(x), y(y) {} vec2( const vec2& v ) { x = v.x; y = v.y; } // // --- Indexing Operator --- // GLfloat& operator [] ( int i ) { return *(&x + i); } const GLfloat operator [] ( int i ) const { return *(&x + i); } // // --- (non-modifying) Arithematic Operators --- // vec2 operator - () const // unary minus operator { return vec2( -x, -y ); } vec2 operator + ( const vec2& v ) const { return vec2( x + v.x, y + v.y ); } vec2 operator - ( const vec2& v ) const { return vec2( x - v.x, y - v.y ); } vec2 operator * ( const GLfloat s ) const { return vec2( s*x, s*y ); } vec2 operator * ( const vec2& v ) const { return vec2( x*v.x, y*v.y ); } friend vec2 operator * ( const GLfloat s, const vec2& v ) { return v * s; } vec2 operator / ( const GLfloat s ) const { #ifdef DEBUG if ( std::fabs(s) < DivideByZeroTolerance ) { std::cerr << "[" << __FILE__ << ":" << __LINE__ << "] " << "Division by zero" << std::endl; return vec2(); } #endif // DEBUG GLfloat r = GLfloat(1.0) / s; return *this * r; } // // --- (modifying) Arithematic Operators --- // vec2& operator += ( const vec2& v ) { x += v.x; y += v.y; return *this; } vec2& operator -= ( const vec2& v ) { x -= v.x; y -= v.y; return *this; } vec2& operator *= ( const GLfloat s ) { x *= s; y *= s; return *this; } vec2& operator *= ( const vec2& v ) { x *= v.x; y *= v.y; return *this; } vec2& operator /= ( const GLfloat s ) { #ifdef DEBUG if ( std::fabs(s) < DivideByZeroTolerance ) { std::cerr << "[" << __FILE__ << ":" << __LINE__ << "] " << "Division by zero" << std::endl; } #endif // DEBUG GLfloat r = GLfloat(1.0) / s; *this *= r; return *this; } // // --- Insertion and Extraction Operators --- // friend std::ostream& operator << ( std::ostream& os, const vec2& v ) { return os << "( " << v.x << ", " << v.y << " )"; } friend std::istream& operator >> ( std::istream& is, vec2& v ) { return is >> v.x >> v.y ; } // // --- Conversion Operators --- // operator const GLfloat* () const { return static_cast<const GLfloat*>( &x ); } operator GLfloat* () { return static_cast<GLfloat*>( &x ); } }; //---------------------------------------------------------------------------- // // Non-class vec2 Methods // inline GLfloat dot( const vec2& u, const vec2& v ) { return u.x * v.x + u.y * v.y; } inline GLfloat length( const vec2& v ) { return std::sqrt( dot(v,v) ); } inline vec2 normalize( const vec2& v ) { return v / length(v); } ////////////////////////////////////////////////////////////////////////////// // // vec3.h - 3D vector // ////////////////////////////////////////////////////////////////////////////// struct vec3 { GLfloat x; GLfloat y; GLfloat z; // // --- Constructors and Destructors --- // vec3( GLfloat s = GLfloat(0.0) ) : x(s), y(s), z(s) {} vec3( GLfloat x, GLfloat y, GLfloat z ) : x(x), y(y), z(z) {} vec3( const vec3& v ) { x = v.x; y = v.y; z = v.z; } vec3( const vec2& v, const float f ) { x = v.x; y = v.y; z = f; } // // --- Indexing Operator --- // GLfloat& operator [] ( int i ) { return *(&x + i); } const GLfloat operator [] ( int i ) const { return *(&x + i); } // // --- (non-modifying) Arithematic Operators --- // vec3 operator - () const // unary minus operator { return vec3( -x, -y, -z ); } vec3 operator + ( const vec3& v ) const { return vec3( x + v.x, y + v.y, z + v.z ); } vec3 operator - ( const vec3& v ) const { return vec3( x - v.x, y - v.y, z - v.z ); } vec3 operator * ( const GLfloat s ) const { return vec3( s*x, s*y, s*z ); } vec3 operator * ( const vec3& v ) const { return vec3( x*v.x, y*v.y, z*v.z ); } friend vec3 operator * ( const GLfloat s, const vec3& v ) { return v * s; } vec3 operator / ( const GLfloat s ) const { #ifdef DEBUG if ( std::fabs(s) < DivideByZeroTolerance ) { std::cerr << "[" << __FILE__ << ":" << __LINE__ << "] " << "Division by zero" << std::endl; return vec3(); } #endif // DEBUG GLfloat r = GLfloat(1.0) / s; return *this * r; } // // --- (modifying) Arithematic Operators --- // vec3& operator += ( const vec3& v ) { x += v.x; y += v.y; z += v.z; return *this; } vec3& operator -= ( const vec3& v ) { x -= v.x; y -= v.y; z -= v.z; return *this; } vec3& operator *= ( const GLfloat s ) { x *= s; y *= s; z *= s; return *this; } vec3& operator *= ( const vec3& v ) { x *= v.x; y *= v.y; z *= v.z; return *this; } vec3& operator /= ( const GLfloat s ) { #ifdef DEBUG if ( std::fabs(s) < DivideByZeroTolerance ) { std::cerr << "[" << __FILE__ << ":" << __LINE__ << "] " << "Division by zero" << std::endl; } #endif // DEBUG GLfloat r = GLfloat(1.0) / s; *this *= r; return *this; } // // --- Insertion and Extraction Operators --- // friend std::ostream& operator << ( std::ostream& os, const vec3& v ) { return os << "( " << v.x << ", " << v.y << ", " << v.z << " )"; } friend std::istream& operator >> ( std::istream& is, vec3& v ) { return is >> v.x >> v.y >> v.z ; } // // --- Conversion Operators --- // operator const GLfloat* () const { return static_cast<const GLfloat*>( &x ); } operator GLfloat* () { return static_cast<GLfloat*>( &x ); } }; //---------------------------------------------------------------------------- // // Non-class vec3 Methods // inline GLfloat dot( const vec3& u, const vec3& v ) { return u.x*v.x + u.y*v.y + u.z*v.z ; } inline GLfloat length( const vec3& v ) { return std::sqrt( dot(v,v) ); } inline vec3 normalize( const vec3& v ) { return v / length(v); } inline vec3 cross(const vec3& a, const vec3& b ) { return vec3( a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x ); } inline vec3 reflect( const vec3& I, const vec3& N ) { return I - 2.0 * dot(N, I) * N; } ////////////////////////////////////////////////////////////////////////////// // // vec4 - 4D vector // ////////////////////////////////////////////////////////////////////////////// struct vec4 { GLfloat x; GLfloat y; GLfloat z; GLfloat w; // // --- Constructors and Destructors --- // vec4( GLfloat s = GLfloat(0.0) ) : x(s), y(s), z(s), w(s) {} vec4( GLfloat x, GLfloat y, GLfloat z, GLfloat w ) : x(x), y(y), z(z), w(w) {} vec4( const vec4& v ) { x = v.x; y = v.y; z = v.z; w = v.w; } vec4( const vec3& v, const float w = 1.0 ) : w(w) { x = v.x; y = v.y; z = v.z; } vec4( const vec2& v, const float z, const float w ) : z(z), w(w) { x = v.x; y = v.y; } // // --- Indexing Operator --- // GLfloat& operator [] ( int i ) { return *(&x + i); } const GLfloat operator [] ( int i ) const { return *(&x + i); } // // --- (non-modifying) Arithematic Operators --- // vec4 operator - () const // unary minus operator { return vec4( -x, -y, -z, -w ); } vec4 operator + ( const vec4& v ) const { return vec4( x + v.x, y + v.y, z + v.z, w + v.w ); } vec4 operator - ( const vec4& v ) const { return vec4( x - v.x, y - v.y, z - v.z, w - v.w ); } vec4 operator * ( const GLfloat s ) const { return vec4( s*x, s*y, s*z, s*w ); } vec4 operator * ( const vec4& v ) const { return vec4( x*v.x, y*v.y, z*v.z, w*v.z ); } friend vec4 operator * ( const GLfloat s, const vec4& v ) { return v * s; } vec4 operator / ( const GLfloat s ) const { #ifdef DEBUG if ( std::fabs(s) < DivideByZeroTolerance ) { std::cerr << "[" << __FILE__ << ":" << __LINE__ << "] " << "Division by zero" << std::endl; return vec4(); } #endif // DEBUG GLfloat r = GLfloat(1.0) / s; return *this * r; } // // --- (modifying) Arithematic Operators --- // vec4& operator += ( const vec4& v ) { x += v.x; y += v.y; z += v.z; w += v.w; return *this; } vec4& operator -= ( const vec4& v ) { x -= v.x; y -= v.y; z -= v.z; w -= v.w; return *this; } vec4& operator *= ( const GLfloat s ) { x *= s; y *= s; z *= s; w *= s; return *this; } vec4& operator *= ( const vec4& v ) { x *= v.x, y *= v.y, z *= v.z, w *= v.w; return *this; } vec4& operator /= ( const GLfloat s ) { #ifdef DEBUG if ( std::fabs(s) < DivideByZeroTolerance ) { std::cerr << "[" << __FILE__ << ":" << __LINE__ << "] " << "Division by zero" << std::endl; } #endif // DEBUG GLfloat r = GLfloat(1.0) / s; *this *= r; return *this; } // // --- Insertion and Extraction Operators --- // friend std::ostream& operator << ( std::ostream& os, const vec4& v ) { return os << "( " << v.x << ", " << v.y << ", " << v.z << ", " << v.w << " )"; } friend std::istream& operator >> ( std::istream& is, vec4& v ) { return is >> v.x >> v.y >> v.z >> v.w; } // // --- Conversion Operators --- // operator const GLfloat* () const { return static_cast<const GLfloat*>( &x ); } operator GLfloat* () { return static_cast<GLfloat*>( &x ); } }; //---------------------------------------------------------------------------- // // Non-class vec4 Methods // inline GLfloat dot( const vec4& u, const vec4& v ) { return u.x*v.x + u.y*v.y + u.z*v.z + u.w+v.w; } inline GLfloat length( const vec4& v ) { return std::sqrt( dot(v,v) ); } inline vec4 normalize( const vec4& v ) { return v / length(v); } inline vec3 cross(const vec4& a, const vec4& b ) { return vec3( a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x ); } inline vec4 reflect( const vec4& I, const vec4& N ) { return I - 2.0 * dot(N, I) * N; } //---------------------------------------------------------------------------- } // namespace Angel #endif // __ANGEL_VEC_H__
[ "nhendlis@tulane.edu" ]
nhendlis@tulane.edu
5e7f2601b27fa758210a0ecf6e41d47b2bbafcb8
865bfdce73e6c142ede4a7c9163c2ac9aac5ceb6
/Source/Game/UI/Scenes/UIScene_MiscOptions.h
eb863ce5efa9023aac2271f79df35cbe096a4e6c
[]
no_license
TLeonardUK/ZombieGrinder
d1b77aa0fcdf4a5b765e394711147d5621c8d4e8
8fc3c3b7f24f9980b75a143cbf37fab32cf66bbf
refs/heads/master
2021-03-19T14:20:54.990622
2019-08-26T16:35:58
2019-08-26T16:35:58
78,782,741
6
3
null
null
null
null
UTF-8
C++
false
false
889
h
// =================================================================== // Copyright (C) 2013 Tim Leonard // =================================================================== #ifndef _GAME_UI_SCENES_UISCENE_MISC_OPTIONS_ #define _GAME_UI_SCENES_UISCENE_Misc_OPTIONS_ #include "Engine/UI/UIScene.h" class UIScene_MiscOptions : public UIScene { MEMORY_ALLOCATOR(UIScene_MiscOptions, "UI"); private: protected: public: UIScene_MiscOptions(); const char* Get_Name(); bool Should_Render_Lower_Scenes(); bool Is_Focusable(); bool Should_Display_Cursor(); UIScene* Get_Background(UIManager* manager); void Enter(UIManager* manager); void Exit(UIManager* manager); void Tick(const FrameTime& time, UIManager* manager, int scene_index); void Draw(const FrameTime& time, UIManager* manager, int scene_index); void Recieve_Event(UIManager* manager, UIEvent e); }; #endif
[ "tim@programmingbytim.com" ]
tim@programmingbytim.com
67115d0c8e8fee1cb898f133cb57562671ac2190
83b64d364dfbadafc64e27271a1a0afc32625a19
/Week4/lecture6.cpp
76897469581fe56e259ed4441d65bc683d86a74a
[]
no_license
JanMouwes/uni-gp-cpp-homework
f6af4b04994b1fdf04da04bd39d5a71845c7f7c3
fecc2c45aaaa089cfe71a34d025f3e9be66ca58c
refs/heads/master
2022-06-04T07:36:12.814474
2020-05-04T21:36:05
2020-05-04T21:36:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
698
cpp
// // Created by Jan Mouwes on 02/05/2020. // #include "lecture6.h" #include <stack> #include <iostream> #include <vector> #include <algorithm> void print(double d) { std::cout << d << std::endl; } void run_lecture6_ex1() { std::stack<double> s; s.push(5.1); s.push(5.2); s.push(5.3); s.push(5.4); s.push(5.5); while (!s.empty()) { print(s.top()); s.pop(); } } void run_lecture6_ex2() { std::vector<int> favouriteNumberVector; favouriteNumberVector.reserve(10); for (int i = 0; i < 10; ++i) { favouriteNumberVector.push_back(7); } for_each (favouriteNumberVector.begin(), favouriteNumberVector.end(), print); }
[ "jan.mouwes@gmail.com" ]
jan.mouwes@gmail.com
07368bea44a3fcf36e9ffe7550a0fa5626a82d50
577d695a629ec832cf024ebb7eb75bc7fb3b587f
/src/examples/px4_mavlink_debug/px4_mavlink_debug.cpp
123935ac5802eee1a53b2c5a414cb5d5941cd5ca
[ "BSD-3-Clause" ]
permissive
mgkim3070/Drone_Firmware
d42ebd9568db289fd3fb32c01fc24241992fef92
6843061ce5eb573424424598cf3bac33e037d4d0
refs/heads/master
2021-01-22T22:27:57.177190
2019-05-08T14:18:06
2019-05-08T14:18:06
85,544,132
0
0
null
null
null
null
UTF-8
C++
false
false
4,310
cpp
/**************************************************************************** * * Copyright (c) 2012-2015 PX4 Development Team. 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 PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /** * @file px4_mavlink_debug.cpp * Debug application example for PX4 autopilot * * @author Example User <mail@example.com> */ #include <px4_config.h> #include <unistd.h> #include <stdio.h> #include <string.h> #include <poll.h> #include <systemlib/err.h> #include <drivers/drv_hrt.h> #include <uORB/uORB.h> #include <uORB/topics/debug_key_value.h> #include <uORB/topics/debug_value.h> #include <uORB/topics/debug_vect.h> #include <uORB/topics/debug_array.h> extern "C" __EXPORT int px4_mavlink_debug_main(int argc, char *argv[]); int px4_mavlink_debug_main(int argc, char *argv[]) { printf("Hello Debug!\n"); /* advertise named debug value */ struct debug_key_value_s dbg_key; strncpy(dbg_key.key, "velx", 10); dbg_key.value = 0.0f; orb_advert_t pub_dbg_key = orb_advertise(ORB_ID(debug_key_value), &dbg_key); /* advertise indexed debug value */ struct debug_value_s dbg_ind; dbg_ind.ind = 42; dbg_ind.value = 0.5f; orb_advert_t pub_dbg_ind = orb_advertise(ORB_ID(debug_value), &dbg_ind); /* advertise debug vect */ struct debug_vect_s dbg_vect; strncpy(dbg_vect.name, "vel3D", 10); dbg_vect.x = 1.0f; dbg_vect.y = 2.0f; dbg_vect.z = 3.0f; orb_advert_t pub_dbg_vect = orb_advertise(ORB_ID(debug_vect), &dbg_vect); /* advertise debug array */ struct debug_array_s dbg_array; dbg_array.id = 1; strncpy(dbg_array.name, "dbg_array", 10); orb_advert_t pub_dbg_array = orb_advertise(ORB_ID(debug_array), &dbg_array); int value_counter = 0; while (value_counter < 100) { uint64_t timestamp_us = hrt_absolute_time(); /* send one named value */ dbg_key.value = value_counter; dbg_key.timestamp = timestamp_us; orb_publish(ORB_ID(debug_key_value), pub_dbg_key, &dbg_key); /* send one indexed value */ dbg_ind.value = 0.5f * value_counter; dbg_ind.timestamp = timestamp_us; orb_publish(ORB_ID(debug_value), pub_dbg_ind, &dbg_ind); /* send one vector */ dbg_vect.x = 1.0f * value_counter; dbg_vect.y = 2.0f * value_counter; dbg_vect.z = 3.0f * value_counter; dbg_vect.timestamp = timestamp_us; orb_publish(ORB_ID(debug_vect), pub_dbg_vect, &dbg_vect); /* send one array */ for (size_t i = 0; i < debug_array_s::ARRAY_SIZE; i++) { dbg_array.data[i] = value_counter + i * 0.01f; } dbg_array.timestamp = timestamp_us; orb_publish(ORB_ID(debug_array), pub_dbg_array, &dbg_array); warnx("sent one more value.."); value_counter++; px4_usleep(500000); } return 0; }
[ "mgkim3070@unist.ac.kr" ]
mgkim3070@unist.ac.kr