text
string
size
int64
token_count
int64
/*__________________________________________________________________________________________ (c) Hash(BEGIN(Satoshi[2010]), END(Sunny[2012])) == Videlicet[2014] ++ (c) Copyright The Nexus Developers 2014 - 2019 Distributed under the MIT software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. "ad vocem populi" - To the Voice of the People ____________________________________________________________________________________________*/ #include "util.h" #include <LLC/include/random.h> #include <unit/catch2/catch.hpp> #include <LLD/include/global.h> #include <TAO/Ledger/types/transaction.h> #include <TAO/Ledger/include/chainstate.h> #include <TAO/Operation/include/enum.h> #include <TAO/Operation/include/execute.h> #include <TAO/Register/include/create.h> #include <TAO/API/types/names.h> TEST_CASE( "Test Tokens API - create token", "[tokens/create/token]") { /* Declare variables shared across test cases */ json::json params; json::json ret; json::json result; json::json error; /* Generate random token name */ std::string strToken = "TOKEN" + std::to_string(LLC::GetRand()); /* Ensure user is created and logged in for testing */ InitializeUser(USERNAME1, PASSWORD, PIN, GENESIS1, SESSION1); /* tokens/create/token fail with missing pin (only relevant for multiuser)*/ if(config::fMultiuser.load()) { /* Build the parameters to pass to the API */ params.clear(); params["session"] = SESSION1; /* Invoke the API */ ret = APICall("tokens/create/token", params); /* Check response is an error and validate error code */ REQUIRE(ret.find("error") != ret.end()); REQUIRE(ret["error"]["code"].get<int32_t>() == -129); } /* tokens/create/token fail with missing session (only relevant for multiuser)*/ if(config::fMultiuser.load()) { /* Build the parameters to pass to the API */ params.clear(); params["pin"] = PIN; /* Invoke the API */ ret = APICall("tokens/create/token", params); /* Check response is an error and validate error code */ REQUIRE(ret.find("error") != ret.end()); REQUIRE(ret["error"]["code"].get<int32_t>() == -12); } /* tokens/create/token fail with missing supply */ { /* Build the parameters to pass to the API */ params.clear(); params["pin"] = PIN; params["session"] = SESSION1; params["name"] = strToken; /* Invoke the API */ ret = APICall("tokens/create/token", params); /* Check response is an error and validate error code */ REQUIRE(ret.find("error") != ret.end()); REQUIRE(ret["error"]["code"].get<int32_t>() == -119); } /* tokens/create/token success */ { /* Build the parameters to pass to the API */ params.clear(); params["pin"] = PIN; params["session"] = SESSION1; params["name"] = strToken; params["supply"] = "10000"; params["decimals"] = "2"; /* Invoke the API */ ret = APICall("tokens/create/token", params); /* Check that the result is as we expect it to be */ REQUIRE(ret.find("result") != ret.end()); result = ret["result"]; REQUIRE(result.find("txid") != result.end()); REQUIRE(result.find("address") != result.end()); } } TEST_CASE( "Test Tokens API - debit token", "[tokens/debit/token]") { /* Declare variables shared across test cases */ json::json params; json::json ret; json::json result; json::json error; /* Generate random token name */ std::string strToken = "TOKEN" +std::to_string(LLC::GetRand()); /* Ensure user is created and logged in for testing */ InitializeUser(USERNAME1, PASSWORD, PIN, GENESIS1, SESSION1); /* Create Token */ { /* Build the parameters to pass to the API */ params.clear(); params["pin"] = PIN; params["session"] = SESSION1; params["name"] = strToken; params["supply"] = "10000"; params["decimals"] = "2"; /* Invoke the API */ ret = APICall("tokens/create/token", params); /* Check that the result is as we expect it to be */ REQUIRE(ret.find("result") != ret.end()); result = ret["result"]; REQUIRE(result.find("txid") != result.end()); REQUIRE(result.find("address") != result.end()); } /* Test fail with missing amount */ { /* Build the parameters to pass to the API */ params.clear(); params["pin"] = PIN; params["session"] = SESSION1; /* Invoke the API */ ret = APICall("tokens/debit/token", params); /* Check response is an error and validate error code */ REQUIRE(ret.find("error") != ret.end()); REQUIRE(ret["error"]["code"].get<int32_t>() == -46); } /* Test fail with missing name / address*/ { /* Build the parameters to pass to the API */ params.clear(); params["pin"] = PIN; params["session"] = SESSION1; params["amount"] = "100"; params["address_to"] = TAO::Register::Address(TAO::Register::Address::ACCOUNT).ToString(); /* Invoke the API */ ret = APICall("tokens/debit/token", params); /* Check response is an error and validate error code */ REQUIRE(ret.find("error") != ret.end()); REQUIRE(ret["error"]["code"].get<int32_t>() == -33); } /* Test fail with invalid name */ { /* Build the parameters to pass to the API */ params.clear(); params["pin"] = PIN; params["session"] = SESSION1; params["amount"] = "100"; params["name_to"] = "random"; params["name"] = "random"; /* Invoke the API */ ret = APICall("tokens/debit/token", params); /* Check response is an error and validate error code */ REQUIRE(ret.find("error") != ret.end()); REQUIRE(ret["error"]["code"].get<int32_t>() == -101); } /* Test fail with invalid address */ { /* Build the parameters to pass to the API */ params.clear(); params["pin"] = PIN; params["session"] = SESSION1; params["amount"] = "100"; params["address_to"] = TAO::Register::Address(TAO::Register::Address::ACCOUNT).ToString(); params["address"] = TAO::Register::Address(TAO::Register::Address::TOKEN).ToString(); /* Invoke the API */ ret = APICall("tokens/debit/token", params); /* Check response is an error and validate error code */ REQUIRE(ret.find("error") != ret.end()); REQUIRE(ret["error"]["code"].get<int32_t>() == -122); } /* Test fail with missing name_to / address_to */ { /* Build the parameters to pass to the API */ params.clear(); params["pin"] = PIN; params["session"] = SESSION1; params["name"] = strToken; params["amount"] = "100"; /* Invoke the API */ ret = APICall("tokens/debit/token", params); /* Check response is an error and validate error code */ REQUIRE(ret.find("error") != ret.end()); REQUIRE(ret["error"]["code"].get<int32_t>() == -64); } /* Test fail with invalid name_to */ { /* Build the parameters to pass to the API */ params.clear(); params["pin"] = PIN; params["session"] = SESSION1; params["name"] = strToken; params["amount"] = "100"; params["name_to"] = "random"; /* Invoke the API */ ret = APICall("tokens/debit/token", params); /* Check response is an error and validate error code */ REQUIRE(ret.find("error") != ret.end()); REQUIRE(ret["error"]["code"].get<int32_t>() == -101); } /* Create an account to send to */ std::string strAccountAddress; { /* Build the parameters to pass to the API */ params.clear(); params["pin"] = PIN; params["session"] = SESSION1; params["name"] = "main"; params["token_name"] = strToken; /* Invoke the API */ ret = APICall("tokens/create/account", params); /* Check that the result is as we expect it to be */ REQUIRE(ret.find("result") != ret.end()); result = ret["result"]; REQUIRE(result.find("txid") != result.end()); REQUIRE(result.find("address") != result.end()); strAccountAddress = result["address"].get<std::string>(); } /* Test success case by name_to */ { /* Build the parameters to pass to the API */ params.clear(); params["pin"] = PIN; params["session"] = SESSION1; params["name"] = strToken; params["amount"] = "100"; params["name_to"] = "main"; /* Invoke the API */ ret = APICall("tokens/debit/token", params); REQUIRE(result.find("txid") != result.end()); } /* Test success case by address_to */ { /* Build the parameters to pass to the API */ params.clear(); params["pin"] = PIN; params["session"] = SESSION1; params["name"] = strToken; params["amount"] = "100"; params["address_to"] = strAccountAddress; /* Invoke the API */ ret = APICall("tokens/debit/token", params); REQUIRE(result.find("txid") != result.end()); } } TEST_CASE( "Test Tokens API - credit token", "[tokens/credit/token]") { /* Declare variables shared across test cases */ json::json params; json::json ret; json::json result; json::json error; /* Generate random token name */ std::string strToken = "TOKEN" +std::to_string(LLC::GetRand()); std::string strTXID; /* Ensure user is created and logged in for testing */ InitializeUser(USERNAME1, PASSWORD, PIN, GENESIS1, SESSION1); /* Create Token to debit and then credit*/ { /* Build the parameters to pass to the API */ params.clear(); params["pin"] = PIN; params["session"] = SESSION1; params["name"] = strToken; params["supply"] = "10000"; params["decimals"] = "2"; /* Invoke the API */ ret = APICall("tokens/create/token", params); /* Check that the result is as we expect it to be */ REQUIRE(ret.find("result") != ret.end()); result = ret["result"]; REQUIRE(result.find("txid") != result.end()); REQUIRE(result.find("address") != result.end()); } /* Create debit transaction to random address (we will be crediting it back to ourselves so it doesn't matter where it goes) */ { /* Build the parameters to pass to the API */ params.clear(); params["pin"] = PIN; params["session"] = SESSION1; params["name"] = strToken; params["amount"] = "100"; params["address_to"] = TAO::Register::Address(TAO::Register::Address::ACCOUNT).ToString(); /* Invoke the API */ ret = APICall("tokens/debit/token", params); REQUIRE(result.find("txid") != result.end()); strTXID = result["txid"].get<std::string>(); } /* Test fail with missing txid */ { /* Build the parameters to pass to the API */ params.clear(); params["pin"] = PIN; params["session"] = SESSION1; /* Invoke the API */ ret = APICall("tokens/credit/token", params); /* Check response is an error and validate error code */ REQUIRE(ret.find("error") != ret.end()); REQUIRE(ret["error"]["code"].get<int32_t>() == -50); } /* Test fail with invalid txid */ { /* Build the parameters to pass to the API */ params.clear(); params["pin"] = PIN; params["session"] = SESSION1; params["txid"] = LLC::GetRand256().GetHex(); /* Invoke the API */ ret = APICall("tokens/credit/token", params); /* Check response is an error and validate error code */ REQUIRE(ret.find("error") != ret.end()); REQUIRE(ret["error"]["code"].get<int32_t>() == -40); } /* Test success case */ { /* Build the parameters to pass to the API */ params.clear(); params["pin"] = PIN; params["session"] = SESSION1; params["txid"] = strTXID; /* Invoke the API */ ret = APICall("tokens/credit/token", params); REQUIRE(result.find("txid") != result.end()); } } TEST_CASE( "Test Tokens API - get token", "[tokens/get/token]") { /* Declare variables shared across test cases */ json::json params; json::json ret; json::json result; json::json error; /* Generate random token name */ std::string strToken = "TOKEN" +std::to_string(LLC::GetRand()); std::string strTokenAddress; std::string strTXID; /* Ensure user is created and logged in for testing */ InitializeUser(USERNAME1, PASSWORD, PIN, GENESIS1, SESSION1); /* Create Token to retrieve */ { /* Build the parameters to pass to the API */ params.clear(); params["pin"] = PIN; params["session"] = SESSION1; params["name"] = strToken; params["supply"] = "10000"; params["decimals"] = "2"; /* Invoke the API */ ret = APICall("tokens/create/token", params); /* Check that the result is as we expect it to be */ REQUIRE(ret.find("result") != ret.end()); result = ret["result"]; REQUIRE(result.find("txid") != result.end()); REQUIRE(result.find("address") != result.end()); strTokenAddress = result["address"].get<std::string>(); } /* Test fail with missing name / address */ { /* Build the parameters to pass to the API */ params.clear(); params["pin"] = PIN; params["session"] = SESSION1; /* Invoke the API */ ret = APICall("tokens/get/token", params); /* Check response is an error and validate error code */ REQUIRE(ret.find("error") != ret.end()); REQUIRE(ret["error"]["code"].get<int32_t>() == -33); } /* Test fail with invalid name */ { /* Build the parameters to pass to the API */ params.clear(); params["pin"] = PIN; params["session"] = SESSION1; params["name"] = "asdfsdfsdf"; /* Invoke the API */ ret = APICall("tokens/get/token", params); /* Check response is an error and validate error code */ REQUIRE(ret.find("error") != ret.end()); REQUIRE(ret["error"]["code"].get<int32_t>() == -101); } /* Test fail with invalid address */ { /* Build the parameters to pass to the API */ params.clear(); params["pin"] = PIN; params["session"] = SESSION1; params["address"] = TAO::Register::Address(TAO::Register::Address::TOKEN).ToString(); /* Invoke the API */ ret = APICall("tokens/get/token", params); /* Check response is an error and validate error code */ REQUIRE(ret.find("error") != ret.end()); REQUIRE(ret["error"]["code"].get<int32_t>() == -122); } /* Test successful get by name */ { /* Build the parameters to pass to the API */ params.clear(); params["pin"] = PIN; params["session"] = SESSION1; params["name"] = strToken; /* Invoke the API */ ret = APICall("tokens/get/token", params); /* Check that the result is as we expect it to be */ REQUIRE(ret.find("result") != ret.end()); result = ret["result"]; REQUIRE(result.find("owner") != result.end()); REQUIRE(result.find("created") != result.end()); REQUIRE(result.find("modified") != result.end()); REQUIRE(result.find("name") != result.end()); REQUIRE(result.find("address") != result.end()); REQUIRE(result.find("balance") != result.end()); REQUIRE(result.find("maxsupply") != result.end()); REQUIRE(result.find("currentsupply") != result.end()); REQUIRE(result.find("decimals") != result.end()); } /* Test successful get by address */ { /* Build the parameters to pass to the API */ params.clear(); params["pin"] = PIN; params["session"] = SESSION1; params["address"] = strTokenAddress; /* Invoke the API */ ret = APICall("tokens/get/token", params); /* Check that the result is as we expect it to be */ REQUIRE(ret.find("result") != ret.end()); result = ret["result"]; REQUIRE(result.find("owner") != result.end()); REQUIRE(result.find("created") != result.end()); REQUIRE(result.find("modified") != result.end()); REQUIRE(result.find("name") != result.end()); REQUIRE(result.find("address") != result.end()); REQUIRE(result.find("balance") != result.end()); REQUIRE(result.find("maxsupply") != result.end()); REQUIRE(result.find("currentsupply") != result.end()); REQUIRE(result.find("decimals") != result.end()); } } TEST_CASE( "Test Tokens API - create account", "[tokens/create/account]") { /* Declare variables shared across test cases */ json::json params; json::json ret; json::json result; json::json error; /* Generate random token name */ std::string strToken = "TOKEN" +std::to_string(LLC::GetRand()); std::string strTokenAddress; /* Ensure user is created and logged in for testing */ InitializeUser(USERNAME1, PASSWORD, PIN, GENESIS1, SESSION1); /* create token to create account for */ { /* Build the parameters to pass to the API */ params.clear(); params["pin"] = PIN; params["session"] = SESSION1; params["name"] = strToken; params["supply"] = "10000"; params["decimals"] = "2"; /* Invoke the API */ ret = APICall("tokens/create/token", params); /* Check that the result is as we expect it to be */ REQUIRE(ret.find("result") != ret.end()); result = ret["result"]; REQUIRE(result.find("txid") != result.end()); REQUIRE(result.find("address") != result.end()); strTokenAddress = result["address"].get<std::string>(); } /* tokens/create/account fail with missing pin (only relevant for multiuser)*/ if(config::fMultiuser.load()) { /* Build the parameters to pass to the API */ params.clear(); params["session"] = SESSION1; /* Invoke the API */ ret = APICall("tokens/create/account", params); /* Check response is an error and validate error code */ REQUIRE(ret.find("error") != ret.end()); REQUIRE(ret["error"]["code"].get<int32_t>() == -129); } /* tokens/create/account fail with missing session (only relevant for multiuser)*/ if(config::fMultiuser.load()) { /* Build the parameters to pass to the API */ params.clear(); params["pin"] = PIN; /* Invoke the API */ ret = APICall("tokens/create/account", params); /* Check response is an error and validate error code */ REQUIRE(ret.find("error") != ret.end()); REQUIRE(ret["error"]["code"].get<int32_t>() == -12); } /* tokens/create/account fail with missing token name / address*/ { /* Build the parameters to pass to the API */ params.clear(); params["pin"] = PIN; params["session"] = SESSION1; /* Invoke the API */ ret = APICall("tokens/create/account", params); /* Check response is an error and validate error code */ REQUIRE(ret.find("error") != ret.end()); REQUIRE(ret["error"]["code"].get<int32_t>() == -37); } /* tokens/create/account by token name success */ { /* Build the parameters to pass to the API */ params.clear(); params["pin"] = PIN; params["session"] = SESSION1; params["token_name"] = strToken; /* Invoke the API */ ret = APICall("tokens/create/account", params); /* Check that the result is as we expect it to be */ REQUIRE(ret.find("result") != ret.end()); result = ret["result"]; REQUIRE(result.find("txid") != result.end()); REQUIRE(result.find("address") != result.end()); } /* tokens/create/account by token address success */ { /* Build the parameters to pass to the API */ params.clear(); params["pin"] = PIN; params["session"] = SESSION1; params["token"] = strTokenAddress; /* Invoke the API */ ret = APICall("tokens/create/account", params); /* Check that the result is as we expect it to be */ REQUIRE(ret.find("result") != ret.end()); result = ret["result"]; REQUIRE(result.find("txid") != result.end()); REQUIRE(result.find("address") != result.end()); } } TEST_CASE( "Test Tokens API - debit account", "[tokens/debit/account]") { /* Declare variables shared across test cases */ json::json params; json::json ret; json::json result; json::json error; /* Generate random token name */ std::string strToken = "TOKEN" +std::to_string(LLC::GetRand()); TAO::Register::Address hashToken = TAO::Register::Address(TAO::Register::Address::TOKEN); std::string strAccount = "ACCOUNT" +std::to_string(LLC::GetRand()); TAO::Register::Address hashAccount = TAO::Register::Address(TAO::Register::Address::ACCOUNT); uint512_t hashDebitTx; /* Ensure user is created and logged in for testing */ InitializeUser(USERNAME1, PASSWORD, PIN, GENESIS1, SESSION1); /* create token to create account for */ { //create the transaction object TAO::Ledger::Transaction tx; tx.hashGenesis = GENESIS1; tx.nSequence = 0; tx.nTimestamp = runtime::timestamp(); //create object TAO::Register::Object token = TAO::Register::CreateToken(hashToken, 1000000, 2); //payload tx[0] << uint8_t(TAO::Operation::OP::CREATE) << hashToken << uint8_t(TAO::Register::REGISTER::OBJECT) << token.GetState(); //create name tx[1] = TAO::API::Names::CreateName(GENESIS1, strToken, "", hashToken); //generate the prestates and poststates REQUIRE(tx.Build()); //verify the prestates and poststates REQUIRE(tx.Verify()); //commit to disk REQUIRE(Execute(tx[0], TAO::Ledger::FLAGS::BLOCK)); //commit to disk REQUIRE(Execute(tx[1], TAO::Ledger::FLAGS::BLOCK)); } /* create account to debit */ { //create the transaction object TAO::Ledger::Transaction tx; tx.hashGenesis = GENESIS1; tx.nSequence = 1; tx.nTimestamp = runtime::timestamp(); //create object TAO::Register::Object account = TAO::Register::CreateAccount(hashToken); //payload tx[0] << uint8_t(TAO::Operation::OP::CREATE) << hashAccount << uint8_t(TAO::Register::REGISTER::OBJECT) << account.GetState(); //create name tx[1] = TAO::API::Names::CreateName(GENESIS1, strAccount, "", hashAccount); //generate the prestates and poststates REQUIRE(tx.Build()); //verify the prestates and poststates REQUIRE(tx.Verify()); //commit to disk REQUIRE(Execute(tx[0], TAO::Ledger::FLAGS::BLOCK)); //commit to disk REQUIRE(Execute(tx[1], TAO::Ledger::FLAGS::BLOCK)); } /* Test fail with missing amount */ { /* Build the parameters to pass to the API */ params.clear(); params["pin"] = PIN; params["session"] = SESSION1; /* Invoke the API */ ret = APICall("tokens/debit/account", params); /* Check response is an error and validate error code */ REQUIRE(ret.find("error") != ret.end()); REQUIRE(ret["error"]["code"].get<int32_t>() == -46); } /* Test fail with missing name / address*/ { /* Build the parameters to pass to the API */ params.clear(); params["pin"] = PIN; params["session"] = SESSION1; params["amount"] = "100"; params["address_to"] = TAO::Register::Address(TAO::Register::Address::ACCOUNT).ToString(); /* Invoke the API */ ret = APICall("tokens/debit/account", params); /* Check response is an error and validate error code */ REQUIRE(ret.find("error") != ret.end()); REQUIRE(ret["error"]["code"].get<int32_t>() == -33); } /* Test fail with invalid name */ { /* Build the parameters to pass to the API */ params.clear(); params["pin"] = PIN; params["session"] = SESSION1; params["amount"] = "100"; params["name_to"] = "random"; params["name"] = "random"; /* Invoke the API */ ret = APICall("tokens/debit/account", params); /* Check response is an error and validate error code */ REQUIRE(ret.find("error") != ret.end()); REQUIRE(ret["error"]["code"].get<int32_t>() == -101); } /* Test fail with invalid address */ { /* Build the parameters to pass to the API */ params.clear(); params["pin"] = PIN; params["session"] = SESSION1; params["amount"] = "100"; params["address_to"] = TAO::Register::Address(TAO::Register::Address::ACCOUNT).ToString(); params["address"] = TAO::Register::Address(TAO::Register::Address::ACCOUNT).ToString(); /* Invoke the API */ ret = APICall("tokens/debit/account", params); /* Check response is an error and validate error code */ REQUIRE(ret.find("error") != ret.end()); REQUIRE(ret["error"]["code"].get<int32_t>() == -122); } /* Test fail with missing name_to / address_to */ { /* Build the parameters to pass to the API */ params.clear(); params["pin"] = PIN; params["session"] = SESSION1; params["address"] = hashAccount.ToString(); params["amount"] = "100"; /* Invoke the API */ ret = APICall("tokens/debit/account", params); /* Check response is an error and validate error code */ REQUIRE(ret.find("error") != ret.end()); REQUIRE(ret["error"]["code"].get<int32_t>() == -64); } /* Test fail with invalid name_to */ { /* Build the parameters to pass to the API */ params.clear(); params["pin"] = PIN; params["session"] = SESSION1; params["address"] = hashAccount.ToString(); params["amount"] = "100"; params["name_to"] = "random"; /* Invoke the API */ ret = APICall("tokens/debit/account", params); /* Check response is an error and validate error code */ REQUIRE(ret.find("error") != ret.end()); REQUIRE(ret["error"]["code"].get<int32_t>() == -101); } /* Test fail with insufficient funds */ { /* Build the parameters to pass to the API */ params.clear(); params["pin"] = PIN; params["session"] = SESSION1; params["address"] = hashAccount.ToString(); params["amount"] = "100"; params["address_to"] = hashToken.ToString(); /* Invoke the API */ ret = APICall("tokens/debit/account", params); /* Check response is an error and validate error code */ REQUIRE(ret.find("error") != ret.end()); REQUIRE(ret["error"]["code"].get<int32_t>() == -69); } /* Debit the token and credit the account so that we have some funds to debit */ { TAO::Ledger::Transaction tx; tx.hashGenesis = GENESIS1; tx.nSequence = 0; tx.nTimestamp = runtime::timestamp(); //payload tx[0] << uint8_t(TAO::Operation::OP::DEBIT) << hashToken << hashAccount << uint64_t(100000) << uint64_t(0); //generate the prestates and poststates REQUIRE(tx.Build()); //verify the prestates and poststates REQUIRE(tx.Verify()); //write transaction REQUIRE(LLD::Ledger->WriteTx(tx.GetHash(), tx)); REQUIRE(LLD::Ledger->IndexBlock(tx.GetHash(), TAO::Ledger::ChainState::Genesis())); //commit to disk REQUIRE(Execute(tx[0], TAO::Ledger::FLAGS::BLOCK)); hashDebitTx = tx.GetHash(); } { TAO::Ledger::Transaction tx; tx.hashGenesis = GENESIS1; tx.nSequence = 1; tx.nTimestamp = runtime::timestamp(); //payload tx[0] << uint8_t(TAO::Operation::OP::CREDIT) << hashDebitTx << uint32_t(0) << hashAccount << hashToken << uint64_t(100000); //generate the prestates and poststates REQUIRE(tx.Build()); //verify the prestates and poststates REQUIRE(tx.Verify()); //write transaction REQUIRE(LLD::Ledger->WriteTx(tx.GetHash(), tx)); REQUIRE(LLD::Ledger->IndexBlock(tx.GetHash(), TAO::Ledger::ChainState::Genesis())); //commit to disk REQUIRE(Execute(tx[0], TAO::Ledger::FLAGS::BLOCK)); } /* Test success case by name_to */ { /* Build the parameters to pass to the API */ params.clear(); params["pin"] = PIN; params["session"] = SESSION1; params["name"] = strAccount; params["amount"] = "100"; params["name_to"] = strToken; /* Invoke the API */ ret = APICall("tokens/debit/account", params); REQUIRE(ret.find("result") != ret.end()); result = ret["result"]; REQUIRE(result.find("txid") != result.end()); } /* Test success case by address_to */ { /* Build the parameters to pass to the API */ params.clear(); params["pin"] = PIN; params["session"] = SESSION1; params["address"] = hashAccount.ToString(); params["amount"] = "100"; params["address_to"] = hashToken.ToString(); /* Invoke the API */ ret = APICall("tokens/debit/account", params); REQUIRE(ret.find("result") != ret.end()); result = ret["result"]; REQUIRE(result.find("txid") != result.end()); } } TEST_CASE( "Test Tokens API - credit account", "[tokens/credit/account]") { /* Declare variables shared across test cases */ json::json params; json::json ret; json::json result; json::json error; /* Generate random token name */ std::string strToken = "TOKEN" + std::to_string(LLC::GetRand()); TAO::Register::Address hashToken = TAO::Register::Address(TAO::Register::Address::TOKEN); std::string strAccount = "ACCOUNT" + std::to_string(LLC::GetRand()); TAO::Register::Address hashAccount = TAO::Register::Address(TAO::Register::Address::ACCOUNT); std::string strTXID; /* Ensure user is created and logged in for testing */ InitializeUser(USERNAME1, PASSWORD, PIN, GENESIS1, SESSION1); /* create token to create account for */ { //create the transaction object TAO::Ledger::Transaction tx; tx.hashGenesis = GENESIS1; tx.nSequence = 0; tx.nTimestamp = runtime::timestamp(); //create object TAO::Register::Object token = TAO::Register::CreateToken(hashToken, 10000, 2); //payload tx[0] << uint8_t(TAO::Operation::OP::CREATE) << hashToken << uint8_t(TAO::Register::REGISTER::OBJECT) << token.GetState(); //create name tx[1] = TAO::API::Names::CreateName(GENESIS1, strToken, "", hashToken); //generate the prestates and poststates REQUIRE(tx.Build()); //verify the prestates and poststates REQUIRE(tx.Verify()); //commit to disk REQUIRE(Execute(tx[0], TAO::Ledger::FLAGS::BLOCK)); //commit to disk REQUIRE(Execute(tx[1], TAO::Ledger::FLAGS::BLOCK)); } /* create account to debit */ { //create the transaction object TAO::Ledger::Transaction tx; tx.hashGenesis = GENESIS1; tx.nSequence = 1; tx.nTimestamp = runtime::timestamp(); //create object TAO::Register::Object account = TAO::Register::CreateAccount(hashToken); //create name TAO::Register::Object name = TAO::Register::CreateName("", strToken, hashAccount); //payload tx[0] << uint8_t(TAO::Operation::OP::CREATE) << hashAccount << uint8_t(TAO::Register::REGISTER::OBJECT) << account.GetState(); //create name tx[1] = TAO::API::Names::CreateName(GENESIS1, strAccount, "", hashAccount); //generate the prestates and poststates REQUIRE(tx.Build()); //verify the prestates and poststates REQUIRE(tx.Verify()); //commit to disk REQUIRE(Execute(tx[0], TAO::Ledger::FLAGS::BLOCK)); //commit to disk REQUIRE(Execute(tx[1], TAO::Ledger::FLAGS::BLOCK)); } /* Debit the token and credit the account so that we have some funds to debit */ { TAO::Ledger::Transaction tx; tx.hashGenesis = GENESIS1; tx.nSequence = 2; tx.nTimestamp = runtime::timestamp(); //payload tx[0] << uint8_t(TAO::Operation::OP::DEBIT) << hashToken << hashAccount << uint64_t(1000) << uint64_t(0); //generate the prestates and poststates REQUIRE(tx.Build()); //verify the prestates and poststates REQUIRE(tx.Verify()); //write transaction REQUIRE(LLD::Ledger->WriteTx(tx.GetHash(), tx)); REQUIRE(LLD::Ledger->IndexBlock(tx.GetHash(), TAO::Ledger::ChainState::Genesis())); //commit to disk REQUIRE(Execute(tx[0], TAO::Ledger::FLAGS::BLOCK)); strTXID = tx.GetHash().GetHex(); } /* Test fail with missing txid */ { /* Build the parameters to pass to the API */ params.clear(); params["pin"] = PIN; params["session"] = SESSION1; /* Invoke the API */ ret = APICall("tokens/credit/account", params); /* Check response is an error and validate error code */ REQUIRE(ret.find("error") != ret.end()); REQUIRE(ret["error"]["code"].get<int32_t>() == -50); } /* Test fail with invalid txid */ { /* Build the parameters to pass to the API */ params.clear(); params["pin"] = PIN; params["session"] = SESSION1; params["txid"] = LLC::GetRand256().GetHex(); /* Invoke the API */ ret = APICall("tokens/credit/account", params); /* Check response is an error and validate error code */ REQUIRE(ret.find("error") != ret.end()); REQUIRE(ret["error"]["code"].get<int32_t>() == -40); } /* Test success case */ { /* Build the parameters to pass to the API */ params.clear(); params["pin"] = PIN; params["session"] = SESSION1; params["txid"] = strTXID; /* Invoke the API */ ret = APICall("tokens/credit/account", params); /* Check the result */ REQUIRE(ret.find("result") != ret.end()); result = ret["result"]; REQUIRE(result.find("txid") != result.end()); } } TEST_CASE( "Test Tokens API - get account", "[tokens/get/account]") { /* Declare variables shared across test cases */ json::json params; json::json ret; json::json result; json::json error; /* Generate random token name */ std::string strToken = "TOKEN" +std::to_string(LLC::GetRand()); TAO::Register::Address hashToken = TAO::Register::Address(TAO::Register::Address::TOKEN); std::string strAccount = "ACCOUNT" +std::to_string(LLC::GetRand()); TAO::Register::Address hashAccount = TAO::Register::Address(TAO::Register::Address::ACCOUNT); std::string strTXID; /* Ensure user is created and logged in for testing */ InitializeUser(USERNAME1, PASSWORD, PIN, GENESIS1, SESSION1); /* create token to create account for */ { /* Build the parameters to pass to the API */ params.clear(); params["pin"] = PIN; params["session"] = SESSION1; params["name"] = strToken; params["supply"] = "10000"; params["decimals"] = "2"; /* Invoke the API */ ret = APICall("tokens/create/token", params); /* Check that the result is as we expect it to be */ REQUIRE(ret.find("result") != ret.end()); result = ret["result"]; REQUIRE(result.find("txid") != result.end()); REQUIRE(result.find("address") != result.end()); hashToken.SetBase58( result["address"].get<std::string>()); } /* tokens/create/account by token address success */ { /* Build the parameters to pass to the API */ params.clear(); params["pin"] = PIN; params["session"] = SESSION1; params["name"] = strAccount; params["token"] = hashToken.ToString(); /* Invoke the API */ ret = APICall("tokens/create/account", params); /* Check that the result is as we expect it to be */ REQUIRE(ret.find("result") != ret.end()); result = ret["result"]; REQUIRE(result.find("txid") != result.end()); REQUIRE(result.find("address") != result.end()); hashAccount.SetBase58( result["address"].get<std::string>()); } /* Test fail with missing name / address */ { /* Build the parameters to pass to the API */ params.clear(); params["pin"] = PIN; params["session"] = SESSION1; /* Invoke the API */ ret = APICall("tokens/get/account", params); /* Check response is an error and validate error code */ REQUIRE(ret.find("error") != ret.end()); REQUIRE(ret["error"]["code"].get<int32_t>() == -33); } /* Test fail with invalid name */ { /* Build the parameters to pass to the API */ params.clear(); params["pin"] = PIN; params["session"] = SESSION1; params["name"] = "asdfsdfsdf"; /* Invoke the API */ ret = APICall("tokens/get/account", params); /* Check response is an error and validate error code */ REQUIRE(ret.find("error") != ret.end()); REQUIRE(ret["error"]["code"].get<int32_t>() == -101); } /* Test fail with invalid address */ { /* Build the parameters to pass to the API */ params.clear(); params["pin"] = PIN; params["session"] = SESSION1; params["address"] = TAO::Register::Address(TAO::Register::Address::ACCOUNT).ToString(); /* Invoke the API */ ret = APICall("tokens/get/account", params); /* Check response is an error and validate error code */ REQUIRE(ret.find("error") != ret.end()); REQUIRE(ret["error"]["code"].get<int32_t>() == -122); } /* Test successful get by name */ { /* Build the parameters to pass to the API */ params.clear(); params["pin"] = PIN; params["session"] = SESSION1; params["name"] = strAccount; /* Invoke the API */ ret = APICall("tokens/get/account", params); /* Check that the result is as we expect it to be */ REQUIRE(ret.find("result") != ret.end()); result = ret["result"]; REQUIRE(result.find("owner") != result.end()); REQUIRE(result.find("created") != result.end()); REQUIRE(result.find("modified") != result.end()); REQUIRE(result.find("name") != result.end()); REQUIRE(result.find("address") != result.end()); REQUIRE(result.find("token_name") != result.end()); REQUIRE(result.find("token") != result.end()); REQUIRE(result.find("balance") != result.end()); } /* Test successful get by address */ { /* Build the parameters to pass to the API */ params.clear(); params["pin"] = PIN; params["session"] = SESSION1; params["address"] = hashAccount.ToString(); /* Invoke the API */ ret = APICall("tokens/get/account", params); /* Check that the result is as we expect it to be */ REQUIRE(ret.find("result") != ret.end()); result = ret["result"]; REQUIRE(result.find("owner") != result.end()); REQUIRE(result.find("created") != result.end()); REQUIRE(result.find("modified") != result.end()); REQUIRE(result.find("name") != result.end()); REQUIRE(result.find("address") != result.end()); REQUIRE(result.find("token_name") != result.end()); REQUIRE(result.find("token") != result.end()); REQUIRE(result.find("balance") != result.end()); } }
41,185
12,921
/** * Include Header */ #include "Pipeline.h" /** * Include Camera */ #include <ING/Camera/Camera.h> /** * Include Renderer */ #include <ING/Rendering/Renderer/Renderer.h> /** * Include Rendering API */ #include <ING/Rendering/API/API.h> /** * Include Rendering Device Context */ #include <ING/Rendering/API/Device/Context/Context.h> /** * Include Rendering Device */ #include <ING/Rendering/API/Device/Device.h> /** * Include Rendering Pass */ #include <ING/Rendering/Pass/Pass.h> namespace ING { namespace Rendering { /**IIDeviceContext * Constructors And Destructor */ IPipeline::IPipeline (const String& name) : renderer(0) { this->name = name; isRendering = false; } IPipeline::~IPipeline () { } /** * Release Methods */ void IPipeline::Release() { for (unsigned int i = 0; i < passVector.size(); ++i) { passVector[i]->Release(); } passVector.clear(); for (Camera* camera : CameraManager::GetInstance()->GetCameraList()) { if (camera->GetRenderingPipeline() == this) { ClearCameraData(camera); camera->SetRenderingPipeline(0); } } delete this; } /** * Methods */ void IPipeline::AddPass(IPass* pass) { AddPass(pass, passVector.size()); } void IPipeline::AddPass(IPass* pass, unsigned int index) { if (passVector.size() == index) { passVector.push_back(pass); } else { passVector.insert(passVector.begin() + index, pass); unsigned int passCount = passVector.size(); for (unsigned int i = index + 1; i < passCount; ++i) { name2PassIndex[passVector[i]->GetName()]++; } } name2PassIndex[pass->GetName()] = index; pass->parent = 0; pass->SetPipeline(this); } void IPipeline::RemovePass(unsigned int index) { String passName = GetPass(index)->GetName(); GetPass(index)->SetPipeline(0); passVector.erase(passVector.begin() + index); unsigned int passCount = passVector.size(); for (unsigned int i = index + 1; i < passCount; ++i) { name2PassIndex[passVector[i]->GetName()]--; } name2PassIndex.erase(passName); } void IPipeline::RemovePass(const String& name) { RemovePass(name2PassIndex[name]); } void IPipeline::RemovePass(IPass* pass) { RemovePass(pass->GetName()); } void IPipeline::SetupCamera (IDeviceContext* context, Camera* camera) { } void IPipeline::ClearCameraData(Camera* camera) { camera->SetRenderingData(0); } bool IPipeline::Render (IDeviceContext* context) { BeginRender(context); EndRender(context); return true; } void IPipeline::BeginRender(IDeviceContext* context) { isRendering = true; for (Camera* camera : CameraManager::GetInstance()->GetCameraList()) { if (camera->GetRenderingPipeline() == this && camera->GetRenderingData() == 0) { SetupCamera(context, camera); } } } void IPipeline::EndRender(IDeviceContext* context) { isRendering = false; } } }
3,040
1,263
/** * Copyright (c) 2021 OceanBase * OceanBase CE is licensed under Mulan PubL v2. * You can use this software according to the terms and conditions of the Mulan PubL v2. * You may obtain a copy of Mulan PubL v2 at: * http://license.coscl.org.cn/MulanPubL-2.0 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PubL v2 for more details. */ #define USING_LOG_PREFIX SQL_ENG #include "sql/engine/expr/ob_expr_rownum.h" #include "sql/engine/basic/ob_count.h" #include "sql/engine/basic/ob_count_op.h" #include "sql/engine/ob_exec_context.h" #include "sql/code_generator/ob_static_engine_expr_cg.h" #include "sql/engine/expr/ob_expr_util.h" namespace oceanbase { using namespace common; namespace sql { OB_SERIALIZE_MEMBER((ObExprRowNum, ObFuncExprOperator), operator_id_); ObExprRowNum::ObExprRowNum(ObIAllocator& alloc) : ObFuncExprOperator(alloc, T_FUN_SYS_ROWNUM, "rownum", 0, NOT_ROW_DIMENSION), operator_id_(OB_INVALID_ID) {} ObExprRowNum::~ObExprRowNum() {} int ObExprRowNum::calc_result_type0(ObExprResType& type, ObExprTypeCtx& type_ctx) const { UNUSED(type_ctx); type.set_number(); type.set_scale(ObAccuracy::DDL_DEFAULT_ACCURACY[ObNumberType].scale_); type.set_precision(ObAccuracy::DDL_DEFAULT_ACCURACY[ObNumberType].precision_); return OB_SUCCESS; } int ObExprRowNum::calc_result0(ObObj& result, ObExprCtx& expr_ctx) const { int ret = OB_SUCCESS; if (OB_ISNULL(expr_ctx.exec_ctx_) || OB_ISNULL(expr_ctx.calc_buf_)) { ret = OB_ERR_UNEXPECTED; LOG_WARN("exec ctx is null", K(ret), K(expr_ctx.exec_ctx_), K(expr_ctx.calc_buf_)); } else { ObExecContext& exec_ctx = *expr_ctx.exec_ctx_; ObCount::ObCountCtx* count_ctx = NULL; number::ObNumber num; uint64_t count_op_id = OB_INVALID_ID == operator_id_ ? expr_ctx.phy_operator_ctx_id_ : operator_id_; if (OB_ISNULL(count_ctx = GET_PHY_OPERATOR_CTX(ObCount::ObCountCtx, exec_ctx, count_op_id))) { ret = OB_ERR_UNEXPECTED; LOG_WARN("get physical operator ctx failed", K(ret)); } else if (OB_FAIL(num.from(count_ctx->cur_rownum_, *expr_ctx.calc_buf_))) { LOG_WARN("failed to convert int as number", K(ret)); } else { result.set_number(num); } } return ret; } int ObExprRowNum::cg_expr(ObExprCGCtx& op_cg_ctx, const ObRawExpr& raw_expr, ObExpr& rt_expr) const { int ret = OB_SUCCESS; UNUSED(raw_expr); UNUSED(op_cg_ctx); rt_expr.extra_ = operator_id_; rt_expr.eval_func_ = &rownum_eval; return ret; } int ObExprRowNum::rownum_eval(const ObExpr& expr, ObEvalCtx& ctx, ObDatum& expr_datum) { int ret = OB_SUCCESS; uint64_t operator_id = expr.extra_; ObOperatorKit* kit = ctx.exec_ctx_.get_operator_kit(operator_id); if (OB_ISNULL(kit) || OB_ISNULL(kit->op_)) { ret = OB_ERR_UNEXPECTED; LOG_WARN("operator is NULL", K(ret), K(operator_id), KP(kit)); } else if (OB_UNLIKELY(PHY_COUNT != kit->op_->get_spec().type_)) { ret = OB_ERR_UNEXPECTED; LOG_WARN("is not count operator", K(ret), K(operator_id), "spec", kit->op_->get_spec()); } else { char local_buff[number::ObNumber::MAX_BYTE_LEN]; ObDataBuffer local_alloc(local_buff, number::ObNumber::MAX_BYTE_LEN); number::ObNumber num; ObCountOp* count_op = static_cast<ObCountOp*>(kit->op_); if (OB_FAIL(num.from(count_op->get_cur_rownum(), local_alloc))) { LOG_WARN("failed to convert int to number", K(ret)); } else { expr_datum.set_number(num); } } return ret; } } /* namespace sql */ } /* namespace oceanbase */
3,681
1,491
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ #include <netinet/in.h> #include <sys/socket.h> #include <sys/types.h> #include "ipv4-raw-socket-impl.h" #include "ipv4-l3-protocol.h" #include "icmpv4.h" #include "ns3/ipv4-packet-info-tag.h" #include "ns3/inet-socket-address.h" #include "ns3/node.h" #include "ns3/packet.h" #include "ns3/uinteger.h" #include "ns3/boolean.h" #include "ns3/log.h" namespace ns3 { NS_LOG_COMPONENT_DEFINE ("Ipv4RawSocketImpl"); NS_OBJECT_ENSURE_REGISTERED (Ipv4RawSocketImpl); TypeId Ipv4RawSocketImpl::GetTypeId (void) { static TypeId tid = TypeId ("ns3::Ipv4RawSocketImpl") .SetParent<Socket> () .SetGroupName ("Internet") .AddAttribute ("Protocol", "Protocol number to match.", UintegerValue (0), MakeUintegerAccessor (&Ipv4RawSocketImpl::m_protocol), MakeUintegerChecker<uint16_t> ()) .AddAttribute ("IcmpFilter", "Any icmp header whose type field matches a bit in this filter is dropped. Type must be less than 32.", UintegerValue (0), MakeUintegerAccessor (&Ipv4RawSocketImpl::m_icmpFilter), MakeUintegerChecker<uint32_t> ()) // // from raw (7), linux, returned length of Send/Recv should be // // | IP_HDRINC on | off | // ----------+---------------+-------------+- // Send(Ipv4)| hdr + payload | payload | // Recv(Ipv4)| hdr + payload | hdr+payload | // ----------+---------------+-------------+- .AddAttribute ("IpHeaderInclude", "Include IP Header information (a.k.a setsockopt (IP_HDRINCL)).", BooleanValue (false), MakeBooleanAccessor (&Ipv4RawSocketImpl::m_iphdrincl), MakeBooleanChecker ()) ; return tid; } Ipv4RawSocketImpl::Ipv4RawSocketImpl () { NS_LOG_FUNCTION (this); m_err = Socket::ERROR_NOTERROR; m_node = 0; m_src = Ipv4Address::GetAny (); m_dst = Ipv4Address::GetAny (); m_protocol = 0; m_shutdownSend = false; m_shutdownRecv = false; } void Ipv4RawSocketImpl::SetNode (Ptr<Node> node) { NS_LOG_FUNCTION (this << node); m_node = node; } void Ipv4RawSocketImpl::DoDispose (void) { NS_LOG_FUNCTION (this); m_node = 0; Socket::DoDispose (); } enum Socket::SocketErrno Ipv4RawSocketImpl::GetErrno (void) const { NS_LOG_FUNCTION (this); return m_err; } enum Socket::SocketType Ipv4RawSocketImpl::GetSocketType (void) const { NS_LOG_FUNCTION (this); return NS3_SOCK_RAW; } Ptr<Node> Ipv4RawSocketImpl::GetNode (void) const { NS_LOG_FUNCTION (this); return m_node; } int Ipv4RawSocketImpl::Bind (const Address &address) { NS_LOG_FUNCTION (this << address); if (!InetSocketAddress::IsMatchingType (address)) { m_err = Socket::ERROR_INVAL; return -1; } InetSocketAddress ad = InetSocketAddress::ConvertFrom (address); m_src = ad.GetIpv4 (); return 0; } int Ipv4RawSocketImpl::Bind (void) { NS_LOG_FUNCTION (this); m_src = Ipv4Address::GetAny (); return 0; } int Ipv4RawSocketImpl::Bind6 (void) { NS_LOG_FUNCTION (this); return (-1); } int Ipv4RawSocketImpl::GetSockName (Address &address) const { NS_LOG_FUNCTION (this << address); address = InetSocketAddress (m_src, 0); return 0; } int Ipv4RawSocketImpl::GetPeerName (Address &address) const { NS_LOG_FUNCTION (this << address); if (m_dst == Ipv4Address::GetAny ()) { m_err = ERROR_NOTCONN; return -1; } address = InetSocketAddress (m_dst, 0); return 0; } int Ipv4RawSocketImpl::Close (void) { NS_LOG_FUNCTION (this); Ptr<Ipv4> ipv4 = m_node->GetObject<Ipv4> (); if (ipv4 != 0) { ipv4->DeleteRawSocket (this); } return 0; } int Ipv4RawSocketImpl::ShutdownSend (void) { NS_LOG_FUNCTION (this); m_shutdownSend = true; return 0; } int Ipv4RawSocketImpl::ShutdownRecv (void) { NS_LOG_FUNCTION (this); m_shutdownRecv = true; return 0; } int Ipv4RawSocketImpl::Connect (const Address &address) { NS_LOG_FUNCTION (this << address); if (!InetSocketAddress::IsMatchingType (address)) { m_err = Socket::ERROR_INVAL; return -1; } InetSocketAddress ad = InetSocketAddress::ConvertFrom (address); m_dst = ad.GetIpv4 (); SetIpTos (ad.GetTos ()); return 0; } int Ipv4RawSocketImpl::Listen (void) { NS_LOG_FUNCTION (this); m_err = Socket::ERROR_OPNOTSUPP; return -1; } uint32_t Ipv4RawSocketImpl::GetTxAvailable (void) const { NS_LOG_FUNCTION (this); return 0xffffffff; } int Ipv4RawSocketImpl::Send (Ptr<Packet> p, uint32_t flags) { NS_LOG_FUNCTION (this << p << flags); InetSocketAddress to = InetSocketAddress (m_dst, m_protocol); to.SetTos (GetIpTos ()); return SendTo (p, flags, to); } int Ipv4RawSocketImpl::SendTo (Ptr<Packet> p, uint32_t flags, const Address &toAddress) { NS_LOG_FUNCTION (this << p << flags << toAddress); if (!InetSocketAddress::IsMatchingType (toAddress)) { m_err = Socket::ERROR_INVAL; return -1; } if (m_shutdownSend) { return 0; } InetSocketAddress ad = InetSocketAddress::ConvertFrom (toAddress); Ptr<Ipv4> ipv4 = m_node->GetObject<Ipv4> (); Ipv4Address dst = ad.GetIpv4 (); Ipv4Address src = m_src; uint8_t tos = ad.GetTos (); uint8_t priority = GetPriority (); if (tos) { SocketIpTosTag ipTosTag; ipTosTag.SetTos (tos); // This packet may already have a SocketIpTosTag (see BUG 2440) p->ReplacePacketTag (ipTosTag); priority = IpTos2Priority (tos); } if (priority) { SocketPriorityTag priorityTag; priorityTag.SetPriority (priority); p->ReplacePacketTag (priorityTag); } if (IsManualIpTtl () && GetIpTtl () != 0 && !dst.IsMulticast () && !dst.IsBroadcast ()) { SocketIpTtlTag tag; tag.SetTtl (GetIpTtl ()); p->AddPacketTag (tag); } if (ipv4->GetRoutingProtocol ()) { Ipv4Header header; if (!m_iphdrincl) { header.SetDestination (dst); header.SetProtocol (m_protocol); } else { p->RemoveHeader (header); dst = header.GetDestination (); src = header.GetSource (); } SocketErrno errno_ = ERROR_NOTERROR; //do not use errno as it is the standard C last error number Ptr<Ipv4Route> route; Ptr<NetDevice> oif = m_boundnetdevice; //specify non-zero if bound to a source address if (!oif && src != Ipv4Address::GetAny ()) { int32_t index = ipv4->GetInterfaceForAddress (src); NS_ASSERT (index >= 0); oif = ipv4->GetNetDevice (index); NS_LOG_LOGIC ("Set index " << oif << "from source " << src); } // TBD-- we could cache the route and just check its validity route = ipv4->GetRoutingProtocol ()->RouteOutput (p, header, oif, errno_); if (route != 0) { NS_LOG_LOGIC ("Route exists"); uint32_t pktSize = p->GetSize (); if (!m_iphdrincl) { ipv4->Send (p, route->GetSource (), dst, m_protocol, route); } else { pktSize += header.GetSerializedSize (); ipv4->SendWithHeader (p, header, route); } NotifyDataSent (pktSize); NotifySend (GetTxAvailable ()); return pktSize; } else { NS_LOG_DEBUG ("dropped because no outgoing route."); return -1; } } return 0; } uint32_t Ipv4RawSocketImpl::GetRxAvailable (void) const { NS_LOG_FUNCTION (this); uint32_t rx = 0; for (std::list<Data>::const_iterator i = m_recv.begin (); i != m_recv.end (); ++i) { rx += (i->packet)->GetSize (); } return rx; } Ptr<Packet> Ipv4RawSocketImpl::Recv (uint32_t maxSize, uint32_t flags) { NS_LOG_FUNCTION (this << maxSize << flags); Address tmp; return RecvFrom (maxSize, flags, tmp); } Ptr<Packet> Ipv4RawSocketImpl::RecvFrom (uint32_t maxSize, uint32_t flags, Address &fromAddress) { NS_LOG_FUNCTION (this << maxSize << flags << fromAddress); if (m_recv.empty ()) { return 0; } struct Data data = m_recv.front (); m_recv.pop_front (); InetSocketAddress inet = InetSocketAddress (data.fromIp, data.fromProtocol); fromAddress = inet; if (data.packet->GetSize () > maxSize) { Ptr<Packet> first = data.packet->CreateFragment (0, maxSize); if (!(flags & MSG_PEEK)) { data.packet->RemoveAtStart (maxSize); } m_recv.push_front (data); return first; } return data.packet; } void Ipv4RawSocketImpl::SetProtocol (uint16_t protocol) { NS_LOG_FUNCTION (this << protocol); m_protocol = protocol; } bool Ipv4RawSocketImpl::ForwardUp (Ptr<const Packet> p, Ipv4Header ipHeader, Ptr<Ipv4Interface> incomingInterface) { NS_LOG_FUNCTION (this << *p << ipHeader << incomingInterface); if (m_shutdownRecv) { return false; } Ptr<NetDevice> boundNetDevice = Socket::GetBoundNetDevice(); if (boundNetDevice) { if (boundNetDevice != incomingInterface->GetDevice()) { return false; } } NS_LOG_LOGIC ("src = " << m_src << " dst = " << m_dst); if ((m_src == Ipv4Address::GetAny () || ipHeader.GetDestination () == m_src) && (m_dst == Ipv4Address::GetAny () || ipHeader.GetSource () == m_dst) && ipHeader.GetProtocol () == m_protocol) { Ptr<Packet> copy = p->Copy (); // Should check via getsockopt ().. if (IsRecvPktInfo ()) { Ipv4PacketInfoTag tag; copy->RemovePacketTag (tag); tag.SetRecvIf (incomingInterface->GetDevice ()->GetIfIndex ()); copy->AddPacketTag (tag); } //Check only version 4 options if (IsIpRecvTos ()) { SocketIpTosTag ipTosTag; ipTosTag.SetTos (ipHeader.GetTos ()); copy->AddPacketTag (ipTosTag); } if (IsIpRecvTtl ()) { SocketIpTtlTag ipTtlTag; ipTtlTag.SetTtl (ipHeader.GetTtl ()); copy->AddPacketTag (ipTtlTag); } if (m_protocol == 1) { Icmpv4Header icmpHeader; copy->PeekHeader (icmpHeader); uint8_t type = icmpHeader.GetType (); if (type < 32 && ((uint32_t(1) << type) & m_icmpFilter)) { // filter out icmp packet. return false; } } copy->AddHeader (ipHeader); struct Data data; data.packet = copy; data.fromIp = ipHeader.GetSource (); data.fromProtocol = ipHeader.GetProtocol (); m_recv.push_back (data); NotifyDataRecv (); return true; } return false; } bool Ipv4RawSocketImpl::SetAllowBroadcast (bool allowBroadcast) { NS_LOG_FUNCTION (this << allowBroadcast); if (!allowBroadcast) { return false; } return true; } bool Ipv4RawSocketImpl::GetAllowBroadcast () const { NS_LOG_FUNCTION (this); return true; } } // namespace ns3
11,192
4,158
/**************************************************************************** ** ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the QtGui module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** GNU Lesser General Public License Usage ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this ** file. Please review the following information to ensure the GNU Lesser ** General Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU General ** Public License version 3.0 as published by the Free Software Foundation ** and appearing in the file LICENSE.GPL included in the packaging of this ** file. Please review the following information to ensure the GNU General ** Public License version 3.0 requirements will be met: ** http://www.gnu.org/copyleft/gpl.html. ** ** Other Usage ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qradiobutton.h" #include "qapplication.h" #include "qbitmap.h" #include "qbuttongroup.h" #include "qstylepainter.h" #include "qstyle.h" #include "qstyleoption.h" #include "qevent.h" #include "private/qabstractbutton_p.h" QT_BEGIN_NAMESPACE class QRadioButtonPrivate : public QAbstractButtonPrivate { Q_DECLARE_PUBLIC(QRadioButton) public: QRadioButtonPrivate() : QAbstractButtonPrivate(QSizePolicy::RadioButton), hovering(true) {} void init(); uint hovering : 1; }; /* Initializes the radio button. */ void QRadioButtonPrivate::init() { Q_Q(QRadioButton); q->setCheckable(true); q->setAutoExclusive(true); q->setMouseTracking(true); q->setForegroundRole(QPalette::WindowText); setLayoutItemMargins(QStyle::SE_RadioButtonLayoutItem); } /*! \class QRadioButton \brief The QRadioButton widget provides a radio button with a text label. \ingroup basicwidgets A QRadioButton is an option button that can be switched on (checked) or off (unchecked). Radio buttons typically present the user with a "one of many" choice. In a group of radio buttons only one radio button at a time can be checked; if the user selects another button, the previously selected button is switched off. Radio buttons are autoExclusive by default. If auto-exclusive is enabled, radio buttons that belong to the same parent widget behave as if they were part of the same exclusive button group. If you need multiple exclusive button groups for radio buttons that belong to the same parent widget, put them into a QButtonGroup. Whenever a button is switched on or off it emits the toggled() signal. Connect to this signal if you want to trigger an action each time the button changes state. Use isChecked() to see if a particular button is selected. Just like QPushButton, a radio button displays text, and optionally a small icon. The icon is set with setIcon(). The text can be set in the constructor or with setText(). A shortcut key can be specified by preceding the preferred character with an ampersand in the text. For example: \snippet doc/src/snippets/code/src_gui_widgets_qradiobutton.cpp 0 In this example the shortcut is \e{Alt+c}. See the \l {QShortcut#mnemonic}{QShortcut} documentation for details (to display an actual ampersand, use '&&'). Important inherited members: text(), setText(), text(), setDown(), isDown(), autoRepeat(), group(), setAutoRepeat(), toggle(), pressed(), released(), clicked(), and toggled(). \table 100% \row \o \inlineimage plastique-radiobutton.png Screenshot of a Plastique radio button \o A radio button shown in the \l{Plastique Style Widget Gallery}{Plastique widget style}. \row \o \inlineimage windows-radiobutton.png Screenshot of a Windows XP radio button \o A radio button shown in the \l{Windows XP Style Widget Gallery}{Windows XP widget style}. \row \o \inlineimage macintosh-radiobutton.png Screenshot of a Macintosh radio button \o A radio button shown in the \l{Macintosh Style Widget Gallery}{Macintosh widget style}. \endtable \sa QPushButton, QToolButton, QCheckBox, {fowler}{GUI Design Handbook: Radio Button}, {Group Box Example} */ /*! Constructs a radio button with the given \a parent, but with no text or pixmap. The \a parent argument is passed on to the QAbstractButton constructor. */ QRadioButton::QRadioButton(QWidget *parent) : QAbstractButton(*new QRadioButtonPrivate, parent) { Q_D(QRadioButton); d->init(); } /*! Constructs a radio button with the given \a parent and a \a text string. The \a parent argument is passed on to the QAbstractButton constructor. */ QRadioButton::QRadioButton(const QString &text, QWidget *parent) : QAbstractButton(*new QRadioButtonPrivate, parent) { Q_D(QRadioButton); d->init(); setText(text); } /*! Initialize \a option with the values from this QRadioButton. This method is useful for subclasses when they need a QStyleOptionButton, but don't want to fill in all the information themselves. \sa QStyleOption::initFrom() */ void QRadioButton::initStyleOption(QStyleOptionButton *option) const { if (!option) return; Q_D(const QRadioButton); option->initFrom(this); option->text = d->text; option->icon = d->icon; option->iconSize = iconSize(); if (d->down) option->state |= QStyle::State_Sunken; option->state |= (d->checked) ? QStyle::State_On : QStyle::State_Off; if (testAttribute(Qt::WA_Hover) && underMouse()) { if (d->hovering) option->state |= QStyle::State_MouseOver; else option->state &= ~QStyle::State_MouseOver; } } /*! \reimp */ QSize QRadioButton::sizeHint() const { Q_D(const QRadioButton); if (d->sizeHint.isValid()) return d->sizeHint; ensurePolished(); QStyleOptionButton opt; initStyleOption(&opt); QSize sz = style()->itemTextRect(fontMetrics(), QRect(), Qt::TextShowMnemonic, false, text()).size(); if (!opt.icon.isNull()) sz = QSize(sz.width() + opt.iconSize.width() + 4, qMax(sz.height(), opt.iconSize.height())); d->sizeHint = (style()->sizeFromContents(QStyle::CT_RadioButton, &opt, sz, this). expandedTo(QApplication::globalStrut())); return d->sizeHint; } /*! \reimp \since 4.8 */ QSize QRadioButton::minimumSizeHint() const { return sizeHint(); } /*! \reimp */ bool QRadioButton::hitButton(const QPoint &pos) const { QStyleOptionButton opt; initStyleOption(&opt); return style()->subElementRect(QStyle::SE_RadioButtonClickRect, &opt, this).contains(pos); } /*! \reimp */ void QRadioButton::mouseMoveEvent(QMouseEvent *e) { Q_D(QRadioButton); if (testAttribute(Qt::WA_Hover)) { bool hit = false; if (underMouse()) hit = hitButton(e->pos()); if (hit != d->hovering) { update(); d->hovering = hit; } } QAbstractButton::mouseMoveEvent(e); } /*!\reimp */ void QRadioButton::paintEvent(QPaintEvent *) { QStylePainter p(this); QStyleOptionButton opt; initStyleOption(&opt); p.drawControl(QStyle::CE_RadioButton, opt); } /*! \reimp */ bool QRadioButton::event(QEvent *e) { Q_D(QRadioButton); if (e->type() == QEvent::StyleChange #ifdef Q_WS_MAC || e->type() == QEvent::MacSizeChange #endif ) d->setLayoutItemMargins(QStyle::SE_RadioButtonLayoutItem); return QAbstractButton::event(e); } #ifdef QT3_SUPPORT /*! Use one of the constructors that doesn't take the \a name argument and then use setObjectName() instead. */ QRadioButton::QRadioButton(QWidget *parent, const char* name) : QAbstractButton(*new QRadioButtonPrivate, parent) { Q_D(QRadioButton); d->init(); setObjectName(QString::fromAscii(name)); } /*! Use one of the constructors that doesn't take the \a name argument and then use setObjectName() instead. */ QRadioButton::QRadioButton(const QString &text, QWidget *parent, const char* name) : QAbstractButton(*new QRadioButtonPrivate, parent) { Q_D(QRadioButton); d->init(); setObjectName(QString::fromAscii(name)); setText(text); } #endif QT_END_NAMESPACE
9,147
2,780
#include "graphics/sprite/particles.h" #include "halley/maths/random.h" #include "halley/support/logger.h" using namespace Halley; Particles::Particles() : rng(&Random::getGlobal()) { } Particles::Particles(const ConfigNode& node, Resources& resources) : rng(&Random::getGlobal()) { spawnRate = node["spawnRate"].asFloat(100); spawnArea = node["spawnArea"].asVector2f(Vector2f(0, 0)); ttl = node["ttl"].asFloat(1.0f); ttlScatter = node["ttlScatter"].asFloat(0.0f); speed = node["speed"].asFloat(100.0f); speedScatter = node["speedScatter"].asFloat(0.0f); speedDamp = node["speedDamp"].asFloat(0.0f); acceleration = node["acceleration"].asVector2f(Vector2f()); angle = node["angle"].asFloat(0.0f); angleScatter = node["angleScatter"].asFloat(0.0f); startScale = node["startScale"].asFloat(1.0f); endScale = node["endScale"].asFloat(1.0f); fadeInTime = node["fadeInTime"].asFloat(0.0f); fadeOutTime = node["fadeOutTime"].asFloat(0.0f); stopTime = node["stopTime"].asFloat(0.0f); directionScatter = node["directionScatter"].asFloat(0.0f); rotateTowardsMovement = node["rotateTowardsMovement"].asBool(false); destroyWhenDone = node["destroyWhenDone"].asBool(false); if (node.hasKey("maxParticles")) { maxParticles = node["maxParticles"].asInt(); } if (node.hasKey("burst")) { burst = node["burst"].asInt(); } } ConfigNode Particles::toConfigNode() const { ConfigNode::MapType result; result["spawnRate"] = spawnRate; result["spawnArea"] = spawnArea; result["ttl"] = ttl; result["ttlScatter"] = ttlScatter; result["speed"] = speed; result["speedScatter"] = speedScatter; result["speedDamp"] = speedDamp; result["acceleration"] = acceleration; result["angle"] = angle; result["angleScatter"] = angleScatter; result["startScale"] = startScale; result["endScale"] = endScale; result["fadeInTime"] = fadeInTime; result["fadeOutTime"] = fadeOutTime; result["stopTime"] = stopTime; result["directionScatter"] = directionScatter; result["rotateTowardsMovement"] = rotateTowardsMovement; result["destroyWhenDone"] = destroyWhenDone; if (maxParticles) { result["maxParticles"] = static_cast<int>(maxParticles.value()); } if (burst) { result["burst"] = static_cast<int>(burst.value()); } return result; } void Particles::setEnabled(bool e) { enabled = e; } bool Particles::isEnabled() const { return enabled; } void Particles::setSpawnRateMultiplier(float value) { spawnRateMultiplier = value; } float Particles::getSpawnRateMultiplier() const { return spawnRateMultiplier; } void Particles::setPosition(Vector2f pos) { position = pos; } void Particles::setSpawnArea(Vector2f area) { spawnArea = area; } void Particles::setAngle(float newAngle) { angle = newAngle; } void Particles::start() { if (burst) { spawn(burst.value()); } } void Particles::update(Time t) { if (firstUpdate) { firstUpdate = false; start(); } pendingSpawn += static_cast<float>(t * spawnRate * (enabled && !burst ? spawnRateMultiplier : 0)); const int toSpawn = static_cast<int>(floor(pendingSpawn)); pendingSpawn = pendingSpawn - static_cast<float>(toSpawn); // Spawn new particles spawn(static_cast<size_t>(toSpawn)); // Update particles updateParticles(static_cast<float>(t)); // Remove dead particles for (size_t i = 0; i < nParticlesAlive; ) { if (!particles[i].alive) { if (i != nParticlesAlive - 1) { // Swap with last particle that's alive std::swap(particles[i], particles[nParticlesAlive - 1]); std::swap(sprites[i], sprites[nParticlesAlive - 1]); if (isAnimated()) { std::swap(animationPlayers[i], animationPlayers[nParticlesAlive - 1]); } } --nParticlesAlive; // Don't increment i here, since i is now a new particle that's still alive } else { ++i; } } // Update visibility nParticlesVisible = nParticlesAlive; if (nParticlesVisible > 0 && !sprites[0].hasMaterial()) { nParticlesVisible = 0; } } void Particles::setSprites(std::vector<Sprite> sprites) { baseSprites = std::move(sprites); } void Particles::setAnimation(std::shared_ptr<const Animation> animation) { baseAnimation = std::move(animation); } bool Particles::isAnimated() const { return !!baseAnimation; } bool Particles::isAlive() const { return nParticlesAlive > 0 || !destroyWhenDone; } gsl::span<Sprite> Particles::getSprites() { return gsl::span<Sprite>(sprites).subspan(0, nParticlesVisible); } gsl::span<const Sprite> Particles::getSprites() const { return gsl::span<const Sprite>(sprites).subspan(0, nParticlesVisible); } void Particles::spawn(size_t n) { if (maxParticles) { n = std::min(n, maxParticles.value() - nParticlesAlive); } const size_t start = nParticlesAlive; nParticlesAlive += n; const size_t size = std::max(size_t(8), nextPowerOf2(nParticlesAlive)); if (particles.size() < size) { particles.resize(size); sprites.resize(size); if (isAnimated()) { animationPlayers.resize(size, AnimationPlayerLite(baseAnimation)); } } for (size_t i = start; i < nParticlesAlive; ++i) { initializeParticle(i); } } void Particles::initializeParticle(size_t index) { const auto startDirection = Angle1f::fromDegrees(rng->getFloat(angle - angleScatter, angle + angleScatter)); auto& particle = particles[index]; particle.alive = true; particle.time = 0; particle.ttl = rng->getFloat(ttl - ttlScatter, ttl + ttlScatter); particle.pos = getSpawnPosition(); particle.angle = rotateTowardsMovement ? startDirection : Angle1f(); particle.scale = startScale; particle.vel = Vector2f(rng->getFloat(speed - speedScatter, speed + speedScatter), startDirection); auto& sprite = sprites[index]; if (isAnimated()) { auto& anim = animationPlayers[index]; anim.update(0, sprite); } else if (!baseSprites.empty()) { sprite = rng->getRandomElement(baseSprites); } } void Particles::updateParticles(float time) { const bool hasAnim = isAnimated(); for (size_t i = 0; i < nParticlesAlive; ++i) { if (hasAnim) { animationPlayers[i].update(time, sprites[i]); } auto& particle = particles[i]; particle.time += time; if (particle.time >= particle.ttl) { particle.alive = false; } else { particle.vel += acceleration * time; if (stopTime > 0.00001f && particle.time + stopTime >= particle.ttl) { particle.vel = damp(particle.vel, Vector2f(), 10.0f, time); } if (speedDamp > 0.0001f) { particle.vel = damp(particle.vel, Vector2f(), speedDamp, time); } if (directionScatter > 0.00001f) { particle.vel = particle.vel.rotate(Angle1f::fromDegrees(rng->getFloat(-directionScatter * time, directionScatter * time))); } particle.pos += particle.vel * time; if (rotateTowardsMovement && particle.vel.squaredLength() > 0.001f) { particle.angle = particle.vel.angle(); } particle.scale = lerp(startScale, endScale, particle.time / particle.ttl); if (fadeInTime > 0.000001f || fadeOutTime > 0.00001f) { const float alpha = clamp(std::min(particle.time / fadeInTime, (particle.ttl - particle.time) / fadeOutTime), 0.0f, 1.0f); sprites[i].getColour().a = alpha; } sprites[i] .setPosition(particle.pos) .setRotation(particle.angle) .setScale(particle.scale); } } } Vector2f Particles::getSpawnPosition() const { return position + Vector2f(rng->getFloat(-spawnArea.x * 0.5f, spawnArea.x * 0.5f), rng->getFloat(-spawnArea.y * 0.5f, spawnArea.y * 0.5f)); } ConfigNode ConfigNodeSerializer<Particles>::serialize(const Particles& particles, const ConfigNodeSerializationContext& context) { return particles.toConfigNode(); } Particles ConfigNodeSerializer<Particles>::deserialize(const ConfigNodeSerializationContext& context, const ConfigNode& node) { return Particles(node, *context.resources); }
7,747
3,048
#include "SmokeIcon-gen.h" #pragma warning(push, 0) #include <max.h> #pragma warning(pop) /* Auto-generated file */ void SmokeIcon::fillMesh(Mesh & outMesh, const float scale) { outMesh.setNumVerts(48); outMesh.setNumFaces(42); outMesh.verts[0].x = scale * 0.500000f; outMesh.verts[0].y = scale * 0.000000f; outMesh.verts[0].z = scale * 0.000000f; outMesh.verts[1].x = scale * 0.460672f; outMesh.verts[1].y = scale * 0.194517f; outMesh.verts[1].z = scale * 0.000000f; outMesh.verts[2].x = scale * 0.353460f; outMesh.verts[2].y = scale * 0.353460f; outMesh.verts[2].z = scale * 0.000000f; outMesh.verts[3].x = scale * 0.194517f; outMesh.verts[3].y = scale * 0.460672f; outMesh.verts[3].z = scale * 0.000000f; outMesh.verts[4].x = scale * -0.000000f; outMesh.verts[4].y = scale * 0.500000f; outMesh.verts[4].z = scale * 0.000000f; outMesh.verts[5].x = scale * -0.194517f; outMesh.verts[5].y = scale * 0.460672f; outMesh.verts[5].z = scale * 0.000000f; outMesh.verts[6].x = scale * -0.353460f; outMesh.verts[6].y = scale * 0.353460f; outMesh.verts[6].z = scale * 0.000000f; outMesh.verts[7].x = scale * -0.460672f; outMesh.verts[7].y = scale * 0.194517f; outMesh.verts[7].z = scale * 0.000000f; outMesh.verts[8].x = scale * -0.500000f; outMesh.verts[8].y = scale * -0.000000f; outMesh.verts[8].z = scale * 0.000000f; outMesh.verts[9].x = scale * -0.460672f; outMesh.verts[9].y = scale * -0.194517f; outMesh.verts[9].z = scale * 0.000000f; outMesh.verts[10].x = scale * -0.353460f; outMesh.verts[10].y = scale * -0.353460f; outMesh.verts[10].z = scale * 0.000000f; outMesh.verts[11].x = scale * -0.194517f; outMesh.verts[11].y = scale * -0.460672f; outMesh.verts[11].z = scale * 0.000000f; outMesh.verts[12].x = scale * 0.000000f; outMesh.verts[12].y = scale * -0.500000f; outMesh.verts[12].z = scale * 0.000000f; outMesh.verts[13].x = scale * 0.194517f; outMesh.verts[13].y = scale * -0.460672f; outMesh.verts[13].z = scale * 0.000000f; outMesh.verts[14].x = scale * 0.353460f; outMesh.verts[14].y = scale * -0.353460f; outMesh.verts[14].z = scale * 0.000000f; outMesh.verts[15].x = scale * 0.460672f; outMesh.verts[15].y = scale * -0.194517f; outMesh.verts[15].z = scale * 0.000000f; outMesh.verts[16].x = scale * 0.500000f; outMesh.verts[16].y = scale * 0.000000f; outMesh.verts[16].z = scale * 0.000000f; outMesh.verts[17].x = scale * 0.460672f; outMesh.verts[17].y = scale * -0.000000f; outMesh.verts[17].z = scale * 0.194517f; outMesh.verts[18].x = scale * 0.353460f; outMesh.verts[18].y = scale * -0.000000f; outMesh.verts[18].z = scale * 0.353460f; outMesh.verts[19].x = scale * 0.194517f; outMesh.verts[19].y = scale * -0.000000f; outMesh.verts[19].z = scale * 0.460672f; outMesh.verts[20].x = scale * -0.000000f; outMesh.verts[20].y = scale * -0.000000f; outMesh.verts[20].z = scale * 0.500000f; outMesh.verts[21].x = scale * -0.194517f; outMesh.verts[21].y = scale * -0.000000f; outMesh.verts[21].z = scale * 0.460672f; outMesh.verts[22].x = scale * -0.353460f; outMesh.verts[22].y = scale * -0.000000f; outMesh.verts[22].z = scale * 0.353460f; outMesh.verts[23].x = scale * -0.460672f; outMesh.verts[23].y = scale * -0.000000f; outMesh.verts[23].z = scale * 0.194517f; outMesh.verts[24].x = scale * -0.500000f; outMesh.verts[24].y = scale * 0.000000f; outMesh.verts[24].z = scale * -0.000000f; outMesh.verts[25].x = scale * -0.460672f; outMesh.verts[25].y = scale * 0.000000f; outMesh.verts[25].z = scale * -0.194517f; outMesh.verts[26].x = scale * -0.353460f; outMesh.verts[26].y = scale * 0.000000f; outMesh.verts[26].z = scale * -0.353460f; outMesh.verts[27].x = scale * -0.194517f; outMesh.verts[27].y = scale * 0.000000f; outMesh.verts[27].z = scale * -0.460672f; outMesh.verts[28].x = scale * 0.000000f; outMesh.verts[28].y = scale * 0.000000f; outMesh.verts[28].z = scale * -0.500000f; outMesh.verts[29].x = scale * 0.194517f; outMesh.verts[29].y = scale * 0.000000f; outMesh.verts[29].z = scale * -0.460672f; outMesh.verts[30].x = scale * 0.353460f; outMesh.verts[30].y = scale * 0.000000f; outMesh.verts[30].z = scale * -0.353460f; outMesh.verts[31].x = scale * 0.460672f; outMesh.verts[31].y = scale * 0.000000f; outMesh.verts[31].z = scale * -0.194517f; outMesh.verts[32].x = scale * -0.000000f; outMesh.verts[32].y = scale * -0.500000f; outMesh.verts[32].z = scale * 0.000000f; outMesh.verts[33].x = scale * -0.000000f; outMesh.verts[33].y = scale * -0.460672f; outMesh.verts[33].z = scale * 0.194517f; outMesh.verts[34].x = scale * -0.000000f; outMesh.verts[34].y = scale * -0.353460f; outMesh.verts[34].z = scale * 0.353460f; outMesh.verts[35].x = scale * -0.000000f; outMesh.verts[35].y = scale * -0.194517f; outMesh.verts[35].z = scale * 0.460672f; outMesh.verts[36].x = scale * -0.000000f; outMesh.verts[36].y = scale * 0.000000f; outMesh.verts[36].z = scale * 0.500000f; outMesh.verts[37].x = scale * -0.000000f; outMesh.verts[37].y = scale * 0.194517f; outMesh.verts[37].z = scale * 0.460672f; outMesh.verts[38].x = scale * 0.000000f; outMesh.verts[38].y = scale * 0.353460f; outMesh.verts[38].z = scale * 0.353460f; outMesh.verts[39].x = scale * 0.000000f; outMesh.verts[39].y = scale * 0.460672f; outMesh.verts[39].z = scale * 0.194517f; outMesh.verts[40].x = scale * 0.000000f; outMesh.verts[40].y = scale * 0.500000f; outMesh.verts[40].z = scale * -0.000000f; outMesh.verts[41].x = scale * 0.000000f; outMesh.verts[41].y = scale * 0.460672f; outMesh.verts[41].z = scale * -0.194517f; outMesh.verts[42].x = scale * 0.000000f; outMesh.verts[42].y = scale * 0.353460f; outMesh.verts[42].z = scale * -0.353460f; outMesh.verts[43].x = scale * 0.000000f; outMesh.verts[43].y = scale * 0.194517f; outMesh.verts[43].z = scale * -0.460672f; outMesh.verts[44].x = scale * 0.000000f; outMesh.verts[44].y = scale * -0.000000f; outMesh.verts[44].z = scale * -0.500000f; outMesh.verts[45].x = scale * 0.000000f; outMesh.verts[45].y = scale * -0.194517f; outMesh.verts[45].z = scale * -0.460672f; outMesh.verts[46].x = scale * 0.000000f; outMesh.verts[46].y = scale * -0.353460f; outMesh.verts[46].z = scale * -0.353460f; outMesh.verts[47].x = scale * -0.000000f; outMesh.verts[47].y = scale * -0.460672f; outMesh.verts[47].z = scale * -0.194517f; outMesh.faces[0].setVerts(11, 12, 13); outMesh.faces[0].setEdgeVisFlags(1, 2, 0); outMesh.faces[1].setVerts(11, 13, 14); outMesh.faces[1].setEdgeVisFlags(0, 2, 0); outMesh.faces[2].setVerts(10, 11, 14); outMesh.faces[2].setEdgeVisFlags(1, 0, 0); outMesh.faces[3].setVerts(10, 14, 15); outMesh.faces[3].setEdgeVisFlags(0, 2, 0); outMesh.faces[4].setVerts(10, 15, 0); outMesh.faces[4].setEdgeVisFlags(0, 2, 0); outMesh.faces[5].setVerts(10, 0, 1); outMesh.faces[5].setEdgeVisFlags(0, 2, 0); outMesh.faces[6].setVerts(10, 1, 2); outMesh.faces[6].setEdgeVisFlags(0, 2, 0); outMesh.faces[7].setVerts(10, 2, 3); outMesh.faces[7].setEdgeVisFlags(0, 2, 0); outMesh.faces[8].setVerts(10, 3, 4); outMesh.faces[8].setEdgeVisFlags(0, 2, 0); outMesh.faces[9].setVerts(10, 4, 5); outMesh.faces[9].setEdgeVisFlags(0, 2, 0); outMesh.faces[10].setVerts(10, 5, 6); outMesh.faces[10].setEdgeVisFlags(0, 2, 0); outMesh.faces[11].setVerts(10, 6, 7); outMesh.faces[11].setEdgeVisFlags(0, 2, 0); outMesh.faces[12].setVerts(10, 7, 8); outMesh.faces[12].setEdgeVisFlags(0, 2, 0); outMesh.faces[13].setVerts(10, 8, 9); outMesh.faces[13].setEdgeVisFlags(0, 2, 4); outMesh.faces[14].setVerts(27, 28, 29); outMesh.faces[14].setEdgeVisFlags(1, 2, 0); outMesh.faces[15].setVerts(27, 29, 30); outMesh.faces[15].setEdgeVisFlags(0, 2, 0); outMesh.faces[16].setVerts(26, 27, 30); outMesh.faces[16].setEdgeVisFlags(1, 0, 0); outMesh.faces[17].setVerts(26, 30, 31); outMesh.faces[17].setEdgeVisFlags(0, 2, 0); outMesh.faces[18].setVerts(26, 31, 16); outMesh.faces[18].setEdgeVisFlags(0, 2, 0); outMesh.faces[19].setVerts(26, 16, 17); outMesh.faces[19].setEdgeVisFlags(0, 2, 0); outMesh.faces[20].setVerts(26, 17, 18); outMesh.faces[20].setEdgeVisFlags(0, 2, 0); outMesh.faces[21].setVerts(26, 18, 19); outMesh.faces[21].setEdgeVisFlags(0, 2, 0); outMesh.faces[22].setVerts(26, 19, 20); outMesh.faces[22].setEdgeVisFlags(0, 2, 0); outMesh.faces[23].setVerts(26, 20, 21); outMesh.faces[23].setEdgeVisFlags(0, 2, 0); outMesh.faces[24].setVerts(26, 21, 22); outMesh.faces[24].setEdgeVisFlags(0, 2, 0); outMesh.faces[25].setVerts(26, 22, 23); outMesh.faces[25].setEdgeVisFlags(0, 2, 0); outMesh.faces[26].setVerts(26, 23, 24); outMesh.faces[26].setEdgeVisFlags(0, 2, 0); outMesh.faces[27].setVerts(26, 24, 25); outMesh.faces[27].setEdgeVisFlags(0, 2, 4); outMesh.faces[28].setVerts(43, 44, 45); outMesh.faces[28].setEdgeVisFlags(1, 2, 0); outMesh.faces[29].setVerts(43, 45, 46); outMesh.faces[29].setEdgeVisFlags(0, 2, 0); outMesh.faces[30].setVerts(42, 43, 46); outMesh.faces[30].setEdgeVisFlags(1, 0, 0); outMesh.faces[31].setVerts(42, 46, 47); outMesh.faces[31].setEdgeVisFlags(0, 2, 0); outMesh.faces[32].setVerts(42, 47, 32); outMesh.faces[32].setEdgeVisFlags(0, 2, 0); outMesh.faces[33].setVerts(42, 32, 33); outMesh.faces[33].setEdgeVisFlags(0, 2, 0); outMesh.faces[34].setVerts(42, 33, 34); outMesh.faces[34].setEdgeVisFlags(0, 2, 0); outMesh.faces[35].setVerts(42, 34, 35); outMesh.faces[35].setEdgeVisFlags(0, 2, 0); outMesh.faces[36].setVerts(42, 35, 36); outMesh.faces[36].setEdgeVisFlags(0, 2, 0); outMesh.faces[37].setVerts(42, 36, 37); outMesh.faces[37].setEdgeVisFlags(0, 2, 0); outMesh.faces[38].setVerts(42, 37, 38); outMesh.faces[38].setEdgeVisFlags(0, 2, 0); outMesh.faces[39].setVerts(42, 38, 39); outMesh.faces[39].setEdgeVisFlags(0, 2, 0); outMesh.faces[40].setVerts(42, 39, 40); outMesh.faces[40].setEdgeVisFlags(0, 2, 0); outMesh.faces[41].setVerts(42, 40, 41); outMesh.faces[41].setEdgeVisFlags(0, 2, 4); outMesh.InvalidateGeomCache(); }
10,616
6,035
/* * Copyright (c) 2020, Ben Wiederhake <BenWiederhake.GitHub@gmx.de> * * SPDX-License-Identifier: BSD-2-Clause */ #include <LibTest/TestCase.h> #include <AK/ByteBuffer.h> #include <AK/Random.h> #include <AK/StringBuilder.h> #include <ctype.h> #include <stdio.h> #include <string.h> struct Testcase { const char* dest; size_t dest_n; const char* src; size_t src_n; const char* dest_expected; size_t dest_expected_n; // == dest_n }; static String show(const ByteBuffer& buf) { StringBuilder builder; for (size_t i = 0; i < buf.size(); ++i) { builder.appendff("{:02x}", buf[i]); } builder.append(' '); builder.append('('); for (size_t i = 0; i < buf.size(); ++i) { if (isprint(buf[i])) builder.append(buf[i]); else builder.append('_'); } builder.append(')'); return builder.build(); } static bool test_single(const Testcase& testcase) { constexpr size_t SANDBOX_CANARY_SIZE = 8; // Preconditions: if (testcase.dest_n != testcase.dest_expected_n) { warnln("dest length {} != expected dest length {}? Check testcase! (Probably miscounted.)", testcase.dest_n, testcase.dest_expected_n); return false; } if (testcase.src_n != strlen(testcase.src)) { warnln("src length {} != actual src length {}? src can't contain NUL bytes!", testcase.src_n, strlen(testcase.src)); return false; } // Setup ByteBuffer actual = ByteBuffer::create_uninitialized(SANDBOX_CANARY_SIZE + testcase.dest_n + SANDBOX_CANARY_SIZE); fill_with_random(actual.data(), actual.size()); ByteBuffer expected = actual; VERIFY(actual.offset_pointer(0) != expected.offset_pointer(0)); actual.overwrite(SANDBOX_CANARY_SIZE, testcase.dest, testcase.dest_n); expected.overwrite(SANDBOX_CANARY_SIZE, testcase.dest_expected, testcase.dest_expected_n); // "unsigned char" != "char", so we have to convince the compiler to allow this. char* dst = reinterpret_cast<char*>(actual.offset_pointer(SANDBOX_CANARY_SIZE)); // The actual call: size_t actual_return = strlcpy(dst, testcase.src, testcase.dest_n); // Checking the results: bool return_ok = actual_return == testcase.src_n; bool canary_1_ok = actual.slice(0, SANDBOX_CANARY_SIZE) == expected.slice(0, SANDBOX_CANARY_SIZE); bool main_ok = actual.slice(SANDBOX_CANARY_SIZE, testcase.dest_n) == expected.slice(SANDBOX_CANARY_SIZE, testcase.dest_n); bool canary_2_ok = actual.slice(SANDBOX_CANARY_SIZE + testcase.dest_n, SANDBOX_CANARY_SIZE) == expected.slice(SANDBOX_CANARY_SIZE + testcase.dest_n, SANDBOX_CANARY_SIZE); bool buf_ok = actual == expected; // Evaluate gravity: if (buf_ok && (!canary_1_ok || !main_ok || !canary_2_ok)) { warnln("Internal error! ({} != {} | {} | {})", buf_ok, canary_1_ok, main_ok, canary_2_ok); buf_ok = false; } if (!canary_1_ok) { warnln("Canary 1 overwritten: Expected canary {}\n" " instead got {}", show(expected.slice(0, SANDBOX_CANARY_SIZE)), show(actual.slice(0, SANDBOX_CANARY_SIZE))); } if (!main_ok) { warnln("Wrong output: Expected {}\n" " instead got {}", show(expected.slice(SANDBOX_CANARY_SIZE, testcase.dest_n)), show(actual.slice(SANDBOX_CANARY_SIZE, testcase.dest_n))); } if (!canary_2_ok) { warnln("Canary 2 overwritten: Expected {}\n" " instead got {}", show(expected.slice(SANDBOX_CANARY_SIZE + testcase.dest_n, SANDBOX_CANARY_SIZE)), show(actual.slice(SANDBOX_CANARY_SIZE + testcase.dest_n, SANDBOX_CANARY_SIZE))); } if (!return_ok) { warnln("Wrong return value: Expected {}, got {} instead!", testcase.src_n, actual_return); } return buf_ok && return_ok; } // Drop the NUL terminator added by the C++ compiler. #define LITERAL(x) x, (sizeof(x) - 1) //static Testcase TESTCASES[] = { // // Golden path: // // Hitting the border: // // Too long: // { LITERAL("Hello World!\0"), LITERAL("Hello Friend!"), LITERAL("Hello Friend\0") }, // { LITERAL("Hello World!\0"), LITERAL("This source is just *way* too long!"), LITERAL("This source \0") }, // { LITERAL("x"), LITERAL("This source is just *way* too long!"), LITERAL("\0") }, // // Other special cases: // { LITERAL(""), LITERAL(""), LITERAL("") }, // { LITERAL(""), LITERAL("Empty test"), LITERAL("") }, // { LITERAL("x"), LITERAL(""), LITERAL("\0") }, // { LITERAL("xx"), LITERAL(""), LITERAL("\0x") }, // { LITERAL("xxx"), LITERAL(""), LITERAL("\0xx") }, //}; TEST_CASE(golden_path) { EXPECT(test_single({ LITERAL("Hello World!\0\0\0"), LITERAL("Hello Friend!"), LITERAL("Hello Friend!\0\0") })); EXPECT(test_single({ LITERAL("Hello World!\0\0\0"), LITERAL("Hello Friend!"), LITERAL("Hello Friend!\0\0") })); EXPECT(test_single({ LITERAL("aaaaaaaaaa"), LITERAL("whf"), LITERAL("whf\0aaaaaa") })); } TEST_CASE(exact_fit) { EXPECT(test_single({ LITERAL("Hello World!\0\0"), LITERAL("Hello Friend!"), LITERAL("Hello Friend!\0") })); EXPECT(test_single({ LITERAL("AAAA"), LITERAL("aaa"), LITERAL("aaa\0") })); } TEST_CASE(off_by_one) { EXPECT(test_single({ LITERAL("AAAAAAAAAA"), LITERAL("BBBBB"), LITERAL("BBBBB\0AAAA") })); EXPECT(test_single({ LITERAL("AAAAAAAAAA"), LITERAL("BBBBBBBCC"), LITERAL("BBBBBBBCC\0") })); EXPECT(test_single({ LITERAL("AAAAAAAAAA"), LITERAL("BBBBBBBCCX"), LITERAL("BBBBBBBCC\0") })); EXPECT(test_single({ LITERAL("AAAAAAAAAA"), LITERAL("BBBBBBBCCXY"), LITERAL("BBBBBBBCC\0") })); } TEST_CASE(nearly_empty) { EXPECT(test_single({ LITERAL(""), LITERAL(""), LITERAL("") })); EXPECT(test_single({ LITERAL(""), LITERAL("Empty test"), LITERAL("") })); EXPECT(test_single({ LITERAL("x"), LITERAL(""), LITERAL("\0") })); EXPECT(test_single({ LITERAL("xx"), LITERAL(""), LITERAL("\0x") })); EXPECT(test_single({ LITERAL("x"), LITERAL("y"), LITERAL("\0") })); } static char* const POISON = (char*)1; TEST_CASE(to_nullptr) { EXPECT_EQ(0u, strlcpy(POISON, "", 0)); EXPECT_EQ(1u, strlcpy(POISON, "x", 0)); EXPECT(test_single({ LITERAL("Hello World!\0\0\0"), LITERAL("Hello Friend!"), LITERAL("Hello Friend!\0\0") })); EXPECT(test_single({ LITERAL("aaaaaaaaaa"), LITERAL("whf"), LITERAL("whf\0aaaaaa") })); }
6,460
2,551
#include "RealMode.hpp" #include <FunnyOS/Hardware/Interrupts.hpp> // Defined in real_mode.asm extern FunnyOS::Bootloader32::Registers32 g_savedRegisters; extern uint8_t g_realBuffer; extern uint8_t g_realBufferTop; F_CDECL extern void do_real_mode_interrupt(); namespace FunnyOS::Bootloader32 { using namespace Stdlib; constexpr static uint32_t MAX_REAL_MODE_ADDR = 0xFFFF * 16 + 0xFFFF; Memory::SizedBuffer<uint8_t>& GetRealModeBuffer() { static Memory::SizedBuffer<uint8_t> c_realModeBuffer{ &g_realBuffer, reinterpret_cast<size_t>(&g_realBufferTop) - reinterpret_cast<size_t>(&g_realBuffer)}; return c_realModeBuffer; } void GetRealModeAddress(void* address, uint16_t& segment, uint16_t& offset) { GetRealModeAddress(reinterpret_cast<uint32_t>(address), segment, offset); } void GetRealModeAddress(uint32_t address, uint16_t& segment, uint16_t& offset) { F_ASSERT(address < MAX_REAL_MODE_ADDR, "address >= MAX_REAL_MODE_ADDR"); segment = static_cast<uint16_t>((address & 0xF0000) >> 4); offset = static_cast<uint16_t>(address & 0xFFFF); } void GetRealModeBufferAddress(uint16_t& segment, uint16_t& offset) { auto address = reinterpret_cast<uintptr_t>(GetRealModeBuffer().Data); GetRealModeAddress(address, segment, offset); } void RealModeInt(uint8_t interrupt, Registers32& registers) { HW::NoInterruptsBlock noInterrupts; Memory::Copy(static_cast<void*>(&g_savedRegisters), static_cast<void*>(&registers), sizeof(Registers32)); #ifdef __GNUC__ asm( // Save state "pushfl \n" "pushal \n" "pushw %%es \n" "pushw %%fs \n" "pushw %%gs \n" // Push interrupt number and call do_real_mode_interrupt "pushl %[int_number] \n" "call do_real_mode_interrupt \n" "add $4, %%esp \n" // Restore state "popw %%gs \n" "popw %%fs \n" "popw %%es \n" "popal \n" "popfl \n" : : [ int_number ] "a"(static_cast<uintmax_t>(interrupt)) : "memory"); #endif Memory::Copy(static_cast<void*>(&registers), static_cast<void*>(&g_savedRegisters), sizeof(Registers32)); } } // namespace FunnyOS::Bootloader32
2,623
868
// Copyright Carl Philipp Reh 2009 - 2018. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef FCPPT_STRING_LITERAL_HPP_INCLUDED #define FCPPT_STRING_LITERAL_HPP_INCLUDED #include <fcppt/detail/string_literal.hpp> /** \brief A char or wchar_t string literal depending on a type. \ingroup fcpptvarious If \a _type is char, then the literal will be of type <code>char const *</code>. If \a _type is wchar_t, then the literal will be of type <code>wchar_t const *</code>. \param _type Must be char or wchar_t. \param _literal Must be a string literal. */ #define FCPPT_STRING_LITERAL(\ _type,\ _literal\ )\ fcppt::detail::string_literal<\ _type\ >(\ _literal, \ L ## _literal \ ) #endif
831
335
#ifndef COMPONENT_H #define COMPONENT_H #include "Object.hpp" class SceneObject; class Component : public Object { public: enum Type { TYPE_UNKNOWN = -1, TYPE_MESHFILTER, TYPE_MESHRENDERER, }; public: Component( int type ) : m_enabled( true ), m_type( type ), m_owner( 0 ) {} virtual ~Component() {} int getType() const { return m_type; } SceneObject* getOwner() { return m_owner; } void setOwner( SceneObject* owner ) { m_owner = owner; } virtual bool onAddToOwner( SceneObject* owner ) { return true; } protected: bool m_enabled; int m_type; SceneObject* m_owner; }; #endif // COMPONENT_H
630
265
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <tencentcloud/waf/v20180125/model/CreateAttackDownloadTaskRequest.h> #include <tencentcloud/core/utils/rapidjson/document.h> #include <tencentcloud/core/utils/rapidjson/writer.h> #include <tencentcloud/core/utils/rapidjson/stringbuffer.h> using namespace TencentCloud::Waf::V20180125::Model; using namespace std; CreateAttackDownloadTaskRequest::CreateAttackDownloadTaskRequest() : m_domainHasBeenSet(false), m_fromTimeHasBeenSet(false), m_toTimeHasBeenSet(false), m_nameHasBeenSet(false), m_riskLevelHasBeenSet(false), m_statusHasBeenSet(false), m_ruleIdHasBeenSet(false), m_attackIpHasBeenSet(false), m_attackTypeHasBeenSet(false) { } string CreateAttackDownloadTaskRequest::ToJsonString() const { rapidjson::Document d; d.SetObject(); rapidjson::Document::AllocatorType& allocator = d.GetAllocator(); if (m_domainHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Domain"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(m_domain.c_str(), allocator).Move(), allocator); } if (m_fromTimeHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "FromTime"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(m_fromTime.c_str(), allocator).Move(), allocator); } if (m_toTimeHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "ToTime"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(m_toTime.c_str(), allocator).Move(), allocator); } if (m_nameHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Name"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(m_name.c_str(), allocator).Move(), allocator); } if (m_riskLevelHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "RiskLevel"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, m_riskLevel, allocator); } if (m_statusHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Status"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, m_status, allocator); } if (m_ruleIdHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "RuleId"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, m_ruleId, allocator); } if (m_attackIpHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "AttackIp"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(m_attackIp.c_str(), allocator).Move(), allocator); } if (m_attackTypeHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "AttackType"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(m_attackType.c_str(), allocator).Move(), allocator); } rapidjson::StringBuffer buffer; rapidjson::Writer<rapidjson::StringBuffer> writer(buffer); d.Accept(writer); return buffer.GetString(); } string CreateAttackDownloadTaskRequest::GetDomain() const { return m_domain; } void CreateAttackDownloadTaskRequest::SetDomain(const string& _domain) { m_domain = _domain; m_domainHasBeenSet = true; } bool CreateAttackDownloadTaskRequest::DomainHasBeenSet() const { return m_domainHasBeenSet; } string CreateAttackDownloadTaskRequest::GetFromTime() const { return m_fromTime; } void CreateAttackDownloadTaskRequest::SetFromTime(const string& _fromTime) { m_fromTime = _fromTime; m_fromTimeHasBeenSet = true; } bool CreateAttackDownloadTaskRequest::FromTimeHasBeenSet() const { return m_fromTimeHasBeenSet; } string CreateAttackDownloadTaskRequest::GetToTime() const { return m_toTime; } void CreateAttackDownloadTaskRequest::SetToTime(const string& _toTime) { m_toTime = _toTime; m_toTimeHasBeenSet = true; } bool CreateAttackDownloadTaskRequest::ToTimeHasBeenSet() const { return m_toTimeHasBeenSet; } string CreateAttackDownloadTaskRequest::GetName() const { return m_name; } void CreateAttackDownloadTaskRequest::SetName(const string& _name) { m_name = _name; m_nameHasBeenSet = true; } bool CreateAttackDownloadTaskRequest::NameHasBeenSet() const { return m_nameHasBeenSet; } uint64_t CreateAttackDownloadTaskRequest::GetRiskLevel() const { return m_riskLevel; } void CreateAttackDownloadTaskRequest::SetRiskLevel(const uint64_t& _riskLevel) { m_riskLevel = _riskLevel; m_riskLevelHasBeenSet = true; } bool CreateAttackDownloadTaskRequest::RiskLevelHasBeenSet() const { return m_riskLevelHasBeenSet; } uint64_t CreateAttackDownloadTaskRequest::GetStatus() const { return m_status; } void CreateAttackDownloadTaskRequest::SetStatus(const uint64_t& _status) { m_status = _status; m_statusHasBeenSet = true; } bool CreateAttackDownloadTaskRequest::StatusHasBeenSet() const { return m_statusHasBeenSet; } uint64_t CreateAttackDownloadTaskRequest::GetRuleId() const { return m_ruleId; } void CreateAttackDownloadTaskRequest::SetRuleId(const uint64_t& _ruleId) { m_ruleId = _ruleId; m_ruleIdHasBeenSet = true; } bool CreateAttackDownloadTaskRequest::RuleIdHasBeenSet() const { return m_ruleIdHasBeenSet; } string CreateAttackDownloadTaskRequest::GetAttackIp() const { return m_attackIp; } void CreateAttackDownloadTaskRequest::SetAttackIp(const string& _attackIp) { m_attackIp = _attackIp; m_attackIpHasBeenSet = true; } bool CreateAttackDownloadTaskRequest::AttackIpHasBeenSet() const { return m_attackIpHasBeenSet; } string CreateAttackDownloadTaskRequest::GetAttackType() const { return m_attackType; } void CreateAttackDownloadTaskRequest::SetAttackType(const string& _attackType) { m_attackType = _attackType; m_attackTypeHasBeenSet = true; } bool CreateAttackDownloadTaskRequest::AttackTypeHasBeenSet() const { return m_attackTypeHasBeenSet; }
6,890
2,399
#include <iostream> #include <cmath> #include <cassert> using namespace std; double pai = 3.1415927; typedef struct { double x; double y; } Point; double eq(double d0, double d1, bool sqr = false) { // return sqr ? (abs(d0 - d1) < (d0 / 10000)) : abs(d0 - d1) < 0.01; return sqr ? eq(sqrt(d0), sqrt(d1)) : abs(d0 - d1) < (abs(d0 - d1) / 100); } double get_angle(double x, double y) { double res = 0; if (x > 0) res = atan(y / x); if (x < 0 && y >= 0) res = atan(y / x) + pai; if (x < 0 && y < 0) res = atan(y / x) - pai; if (x == 0 && y > 0) res = pai / 2; if (x == 0 && y < 0) res = -pai / 2; if (x == 0 && y == 0) res = 0; // cout << "angle: " << x << " " << y << " " << res << endl; assert(res < 3.14160 && res > -3.14160); return res; } bool fit(Point& p0, Point& p1, double scale_sqr, double angle) { double l0 = p0.x * p0.x + p0.y * p0.y; double l1 = p1.x * p1.x + p1.y * p1.y; // cout << "l0 = " << l0 << "; l1 = " << l1 << endl; if (!eq(l0, l1 * scale_sqr, true)) { return false; } if (l0 == 0) return true; assert(l1 != 0); double angle0 = get_angle(p0.x, p0.y); double angle1 = get_angle(p1.x, p1.y); double angle_delta = angle0 - angle1; if (angle_delta > pai ) angle_delta = angle_delta - 2 * pai; if (angle_delta < -pai) angle_delta = angle_delta + 2 * pai; // cout << "s angle0 = " << angle0 << endl; // cout << "s angle1 = " << angle1 << endl; // cout << "angle_delta = " << angle_delta << endl; // cout << "s delta_angle = " << (angle_delta / 3.1415926) * 180 << endl; return eq(angle, angle_delta); } bool has_result(Point* p0, Point* p1, int n, int i, double& res) { int s0 = 0; int s1 = i; double l0 = 0; double l1 = 0; while (l0 == 0 && l1 == 0 && s0 < n) { l0 = p0[s0].x * p0[s0].x + p0[s0].y * p0[s0].y; l1 = p1[s1].x * p1[s1].x + p1[s1].y * p1[s1].y; assert(l0 == 0 && l1 == 0 || l0 != 0 && l1 != 0); if (l0 == 0 && l1 == 0) { s0++; s1++; if (s1 == n) s1 = 0; } else { break; } } if (s0 == n) { res = 0; return true; } // cout << "i = " << i << endl; double scale_sqr = l0 / l1; double angle0 = get_angle(p0[s0].x, p0[s0].y); double angle1 = get_angle(p1[s1].x, p1[s1].y); double angle = angle0 - angle1; // cout << "scale: " << scale_sqr << endl; // cout << "angle0 = " << angle0 << endl; // cout << "angle1 = " << angle1 << endl; // cout << "delta_angle = " << (angle / 3.1415926) * 180 << endl; int j1 = s1+1; for (int j0 = s0+1; j0 < n; ++j0, ++j1) { if (j1 == n) j1 = 0; // cout << "j0 = " << j0 << "; j1 = " << j1 << endl; if (!fit(p0[j0], p1[j1], scale_sqr, angle)) { // cout << "not fit" << endl; return false; } } res = angle; // cout << "fit" << endl; return true; } double result(Point* p0, Point* p1, int n) { double res = 0; for (int i = 0; i < n; ++i) { bool has_res = has_result(p0, p1, n, i, res); if (has_res) return res; } assert(0); return 0; } int main() { int n; cout.precision(2); cout.setf(ios::fixed); while (cin >> n) { Point* p0 = new Point[n]; Point* p1 = new Point[n]; for (int i = 0; i < n; ++i) { cin >> p0[i].x; cin >> p0[i].y; } for (int i = 0; i < n; ++i) { cin >> p1[i].x; cin >> p1[i].y; } double res = result(p0, p1, n); res = (res / pai) * 180; if (res < 0) res += 360; res = 360 - res; if (eq(res, 90)) { cout << "90.0" << endl; } else cout << res << endl; delete [] p0; delete [] p1; } return 0; }
3,569
1,768
#pragma once namespace evnt { struct DeleteEntity { DeleteEntity(std::uint32_t entityId) : entityId(entityId) {} std::uint32_t entityId; }; }
150
60
//===- VectorWarpUtils.cpp - Utilities vector warp ops --------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "Dialects/VectorExt/VectorExtOps.h" #include "Dialects/VectorExt/VectorExtWarpUtils.h" #include "mlir/Dialect/Affine/IR/AffineOps.h" #include "mlir/Dialect/Vector/VectorOps.h" #include "mlir/IR/AffineMap.h" #include "mlir/IR/BlockAndValueMapping.h" #include "mlir/Support/LogicalResult.h" using namespace mlir; using namespace mlir::vector; using namespace mlir::vector_ext; // Clones `op` into a new operations that takes `operands` and returns // `resultTypes`. static Operation *cloneOpWithOperandsAndTypes(OpBuilder &builder, Location loc, Operation *op, ArrayRef<Value> operands, ArrayRef<Type> resultTypes) { OperationState res(loc, op->getName().getStringRef(), operands, resultTypes, op->getAttrs()); return builder.createOperation(res); } /// Helper to create a new WarpSingleLaneOp regions with different signature. static WarpSingleLaneOp moveRegionToNewWarpOpAndReplaceReturns(OpBuilder &b, WarpSingleLaneOp warpOp, ValueRange newYieldedValues, TypeRange newReturnTypes) { // Create a new op before the existing one, with the extra operands. OpBuilder::InsertionGuard g(b); b.setInsertionPoint(warpOp); auto newWarpOp = b.create<WarpSingleLaneOp>(warpOp.getLoc(), newReturnTypes, warpOp.laneid()); Region &opBody = warpOp.getBodyRegion(); Region &newOpBody = newWarpOp.getBodyRegion(); newOpBody.takeBody(opBody); auto yield = cast<vector_ext::YieldOp>(newOpBody.getBlocks().begin()->getTerminator()); yield.operandsMutable().assign(newYieldedValues); return newWarpOp; } /// Helper to create a new WarpSingleLaneOp region with extra outputs. static WarpSingleLaneOp moveRegionToNewWarpOpAndAppendReturns(OpBuilder &b, WarpSingleLaneOp warpOp, ValueRange newYieldedValues, TypeRange newReturnTypes) { SmallVector<Type> types(warpOp.getResultTypes().begin(), warpOp.getResultTypes().end()); types.append(newReturnTypes.begin(), newReturnTypes.end()); auto yield = cast<vector_ext::YieldOp>( warpOp.getBodyRegion().getBlocks().begin()->getTerminator()); SmallVector<Value> yieldValues(yield.getOperands().begin(), yield.getOperands().end()); yieldValues.append(newYieldedValues.begin(), newYieldedValues.end()); WarpSingleLaneOp newWarpOp = moveRegionToNewWarpOpAndReplaceReturns(b, warpOp, yieldValues, types); for (auto it : llvm::zip(warpOp.getResults(), newWarpOp.getResults().take_front(warpOp.getNumResults()))) std::get<0>(it).replaceAllUsesWith(std::get<1>(it)); return newWarpOp; } OpOperand *getWarpResult(WarpSingleLaneOp warpOp, std::function<bool(Operation *)> fn) { auto yield = cast<vector_ext::YieldOp>( warpOp.getBodyRegion().getBlocks().begin()->getTerminator()); for (OpOperand &yieldOperand : yield->getOpOperands()) { Value yieldValues = yieldOperand.get(); Operation *definedOp = yieldValues.getDefiningOp(); if (definedOp && fn(definedOp)) { if (!warpOp.getResult(yieldOperand.getOperandNumber()).use_empty()) return &yieldOperand; } } return {}; } /// Currently the distribution map is implicit based on the vector shape. In the /// future it will be part of the op. /// Example: /// ``` /// %0 = vector_ext.warp_execute_on_lane_0(%arg0) -> (vector<1x16x2xf32>) { /// ... /// vector_ext.yield %3 : vector<32x16x64xf32> /// } /// ``` /// Would have an implicit map of: /// `(d0, d1, d2) -> (d0, d2)` static AffineMap calculateImplicitMap(Value yield, Value ret) { auto srcType = yield.getType().cast<VectorType>(); auto dstType = ret.getType().cast<VectorType>(); SmallVector<AffineExpr, 4> perm; // Check which dimension have a multiplicity greater than 1 and associated // them to the IDs in order. for (unsigned i = 0, e = srcType.getRank(); i < e; i++) { if (srcType.getDimSize(i) != dstType.getDimSize(i)) perm.push_back(getAffineDimExpr(i, yield.getContext())); } auto map = AffineMap::get(srcType.getRank(), 0, perm, yield.getContext()); return map; } /// Sink out elementwise op feeding into a warp op yield. /// ``` /// %0 = vector_ext.warp_execute_on_lane_0(%arg0) -> (vector<1xf32>) { /// ... /// %3 = arith.addf %1, %2 : vector<32xf32> /// vector_ext.yield %3 : vector<32xf32> /// } /// ``` /// To /// ``` /// %r:3 = vector_ext.warp_execute_on_lane_0(%arg0) -> (vector<1xf32>, /// vector<1xf32>, vector<1xf32>) { /// ... /// %4 = arith.addf %2, %3 : vector<32xf32> /// vector_ext.yield %4, %2, %3 : vector<32xf32>, vector<32xf32>, /// vector<32xf32> /// } /// %0 = arith.addf %r#1, %r#2 : vector<1xf32> struct WarpOpElementwise : public OpRewritePattern<WarpSingleLaneOp> { using OpRewritePattern<WarpSingleLaneOp>::OpRewritePattern; LogicalResult matchAndRewrite(WarpSingleLaneOp warpOp, PatternRewriter &rewriter) const override { OpOperand *yieldOperand = getWarpResult(warpOp, [](Operation *op) { return OpTrait::hasElementwiseMappableTraits(op); }); if (!yieldOperand) return failure(); Operation *elementWise = yieldOperand->get().getDefiningOp(); unsigned operandIndex = yieldOperand->getOperandNumber(); Value distributedVal = warpOp.getResult(operandIndex); SmallVector<Value> yieldValues; SmallVector<Type> retTypes; for (OpOperand &operand : elementWise->getOpOperands()) { auto targetType = VectorType::get( distributedVal.getType().cast<VectorType>().getShape(), operand.get().getType().cast<VectorType>().getElementType()); retTypes.push_back(targetType); yieldValues.push_back(operand.get()); } WarpSingleLaneOp newWarpOp = moveRegionToNewWarpOpAndAppendReturns( rewriter, warpOp, yieldValues, retTypes); SmallVector<Value> newOperands(elementWise->getOperands().begin(), elementWise->getOperands().end()); for (unsigned i : llvm::seq(unsigned(0), elementWise->getNumOperands())) { newOperands[i] = newWarpOp.getResult(i + warpOp.getNumResults()); } OpBuilder::InsertionGuard g(rewriter); rewriter.setInsertionPointAfter(newWarpOp); Operation *newOp = cloneOpWithOperandsAndTypes( rewriter, warpOp.getLoc(), elementWise, newOperands, {warpOp.getResult(operandIndex).getType()}); newWarpOp.getResult(operandIndex).replaceAllUsesWith(newOp->getResult(0)); rewriter.eraseOp(warpOp); return success(); } }; /// Sink out transfer_read op feeding into a warp op yield. /// ``` /// %0 = vector_ext.warp_execute_on_lane_0(%arg0) -> (vector<1xf32>) { /// ... // %2 = vector.transfer_read %src[%c0], %cst : memref<1024xf32>, // vector<32xf32> /// vector_ext.yield %2 : vector<32xf32> /// } /// ``` /// To /// ``` /// %dead = vector_ext.warp_execute_on_lane_0(%arg0) -> (vector<1xf32>, /// vector<1xf32>, vector<1xf32>) { /// ... /// %2 = vector.transfer_read %src[%c0], %cst : memref<1024xf32>, /// vector<32xf32> vector_ext.yield %2 : vector<32xf32> /// } /// %0 = vector.transfer_read %src[%c0], %cst : memref<1024xf32>, vector<1xf32> struct WarpOpTransferRead : public OpRewritePattern<WarpSingleLaneOp> { using OpRewritePattern<WarpSingleLaneOp>::OpRewritePattern; LogicalResult matchAndRewrite(WarpSingleLaneOp warpOp, PatternRewriter &rewriter) const override { OpOperand *operand = getWarpResult( warpOp, [](Operation *op) { return isa<vector::TransferReadOp>(op); }); if (!operand) return failure(); auto read = operand->get().getDefiningOp<vector::TransferReadOp>(); unsigned operandIndex = operand->getOperandNumber(); Value distributedVal = warpOp.getResult(operandIndex); SmallVector<Value, 4> indices(read.indices().begin(), read.indices().end()); AffineMap map = calculateImplicitMap(read.getResult(), distributedVal); AffineMap indexMap = map.compose(read.permutation_map()); OpBuilder::InsertionGuard g(rewriter); rewriter.setInsertionPoint(warpOp); for (auto it : llvm::zip(indexMap.getResults(), map.getResults())) { AffineExpr d0, d1; bindDims(read.getContext(), d0, d1); auto indexExpr = std::get<0>(it).dyn_cast<AffineDimExpr>(); if (!indexExpr) continue; unsigned indexPos = indexExpr.getPosition(); unsigned vectorPos = std::get<1>(it).cast<AffineDimExpr>().getPosition(); int64_t scale = distributedVal.getType().cast<VectorType>().getDimSize(vectorPos); indices[indexPos] = makeComposedAffineApply(rewriter, read.getLoc(), d0 + scale * d1, {indices[indexPos], warpOp.laneid()}); } Value newRead = rewriter.create<vector::TransferReadOp>( read.getLoc(), distributedVal.getType(), read.source(), indices, read.permutation_mapAttr(), read.padding(), read.mask(), read.in_boundsAttr()); distributedVal.replaceAllUsesWith(newRead); return success(); } }; /// Remove any result that has no use along with the matching yieldOp operand. // TODO: Move this in WarpSingleLaneOp canonicalization. struct WarpOpDeadResult : public OpRewritePattern<WarpSingleLaneOp> { using OpRewritePattern<WarpSingleLaneOp>::OpRewritePattern; LogicalResult matchAndRewrite(WarpSingleLaneOp warpOp, PatternRewriter &rewriter) const override { SmallVector<Type> resultTypes; SmallVector<Value> yieldValues; auto yield = cast<vector_ext::YieldOp>( warpOp.getBodyRegion().getBlocks().begin()->getTerminator()); for (OpResult result : warpOp.getResults()) { if (result.use_empty()) continue; resultTypes.push_back(result.getType()); yieldValues.push_back(yield.getOperand(result.getResultNumber())); } if (yield.getNumOperands() == yieldValues.size()) return failure(); WarpSingleLaneOp newWarpOp = moveRegionToNewWarpOpAndReplaceReturns( rewriter, warpOp, yieldValues, resultTypes); unsigned resultIndex = 0; for (OpResult result : warpOp.getResults()) { if (result.use_empty()) continue; result.replaceAllUsesWith(newWarpOp.getResult(resultIndex++)); } rewriter.eraseOp(warpOp); return success(); } }; void mlir::vector_ext::populatePropagateVectorDistributionPatterns( RewritePatternSet &pattern) { pattern.add<WarpOpElementwise, WarpOpTransferRead, WarpOpDeadResult>( pattern.getContext()); }
11,206
3,662
#include <CppUtil/Basic/StrAPI.h> #include <cassert> #include <algorithm> using namespace CppUtil::Basic; using namespace std; const string StrAPI::Head(const string & str, int n) { assert(n >= 0); return str.substr(0, std::min(static_cast<size_t>(n), str.size())); } const string StrAPI::Tail(const string & str, int n) { assert(n >= 0); return str.substr(str.size() - n, n); } const string StrAPI::TailAfter(const string & str, char c) { auto idx = str.find_last_of(c); if (idx == string::npos) return ""; return str.substr(idx + 1); } bool StrAPI::IsBeginWith(const string & str, const string & suffix) { return Head(str, static_cast<int>(suffix.size())) == suffix; } bool StrAPI::IsEndWith(const string & str, const string & postfix) { return Tail(str, static_cast<int>(postfix.size())) == postfix; } const vector<string> StrAPI::Spilt(const string & str, const string & separator) { vector<string> rst; if (separator.empty()) return rst; size_t beginIdx = 0; while(true){ size_t targetIdx = str.find(separator, beginIdx); if (targetIdx == string::npos) { rst.push_back(str.substr(beginIdx, str.size() - beginIdx)); break; } rst.push_back(str.substr(beginIdx, targetIdx - beginIdx)); beginIdx = targetIdx + separator.size(); } return rst; } const string StrAPI::Join(const vector<string> & strs, const string & separator) { string rst; for (size_t i = 0; i < strs.size()-1; i++) { rst += strs[i]; rst += separator; } rst += strs.back(); return rst; } const string StrAPI::Replace(const string & str, const string & orig, const string & target) { return Join(Spilt(str, orig), target); } const std::string StrAPI::DelTailAfter(const std::string & str, char c) { for (size_t i = str.size() - 1; i >= 0; i--) { if (str[i] == c) return str.substr(0, i); } return str; } const string StrAPI::Between(const string & str, char left, char right) { auto start = str.find_first_of(left, 0); if (start == string::npos) return ""; auto end = str.find_last_of(right); if (end == string::npos || end == start) return ""; return str.substr(start + 1, end - (start + 1)); }
2,149
847
/* +---------------------------------------------------------------------------+ | Mobile Robot Programming Toolkit (MRPT) | | http://www.mrpt.org/ | | | | Copyright (c) 2005-2017, Individual contributors, see AUTHORS file | | See: http://www.mrpt.org/Authors - All rights reserved. | | Released under BSD License. See details in http://www.mrpt.org/License | +---------------------------------------------------------------------------+ */ #include "obs-precomp.h" // Precompiled headers #include <mrpt/maps/CSimpleMap.h> #include <mrpt/utils/CFileGZInputStream.h> #include <mrpt/utils/CFileGZOutputStream.h> #include <mrpt/utils/CStream.h> using namespace mrpt::obs; using namespace mrpt::maps; using namespace mrpt::utils; using namespace mrpt::poses; using namespace mrpt::poses; using namespace std; #include <mrpt/utils/metaprogramming.h> using namespace mrpt::utils::metaprogramming; IMPLEMENTS_SERIALIZABLE(CSimpleMap, CSerializable,mrpt::maps) /*--------------------------------------------------------------- Constructor ---------------------------------------------------------------*/ CSimpleMap::CSimpleMap() : m_posesObsPairs() { } /*--------------------------------------------------------------- Copy ---------------------------------------------------------------*/ CSimpleMap::CSimpleMap( const CSimpleMap &o ) : m_posesObsPairs( o.m_posesObsPairs ) { for_each( m_posesObsPairs.begin(), m_posesObsPairs.end(), ObjectPairMakeUnique() ); } /*--------------------------------------------------------------- Copy ---------------------------------------------------------------*/ CSimpleMap & CSimpleMap::operator = ( const CSimpleMap& o) { MRPT_START //TPosePDFSensFramePair pair; if (this == &o) return *this; // It may be used sometimes m_posesObsPairs = o.m_posesObsPairs; for_each( m_posesObsPairs.begin(), m_posesObsPairs.end(), ObjectPairMakeUnique() ); return *this; MRPT_END } /*--------------------------------------------------------------- size ---------------------------------------------------------------*/ size_t CSimpleMap::size() const { return m_posesObsPairs.size(); } bool CSimpleMap::empty() const { return m_posesObsPairs.empty(); } /*--------------------------------------------------------------- clear ---------------------------------------------------------------*/ void CSimpleMap::clear() { m_posesObsPairs.clear(); } /*--------------------------------------------------------------- Destructor ---------------------------------------------------------------*/ CSimpleMap::~CSimpleMap() { clear(); } /*--------------------------------------------------------------- get const ---------------------------------------------------------------*/ void CSimpleMap::get( size_t index, CPose3DPDFPtr &out_posePDF, CSensoryFramePtr &out_SF ) const { if (index>=m_posesObsPairs.size()) THROW_EXCEPTION("Index out of bounds"); out_posePDF = m_posesObsPairs[index].first; out_SF = m_posesObsPairs[index].second; } /*--------------------------------------------------------------- remove ---------------------------------------------------------------*/ void CSimpleMap::remove(size_t index) { MRPT_START if (index>=m_posesObsPairs.size()) THROW_EXCEPTION("Index out of bounds"); m_posesObsPairs.erase( m_posesObsPairs.begin() + index ); MRPT_END } /*--------------------------------------------------------------- set ---------------------------------------------------------------*/ void CSimpleMap::set( size_t index, const CPose3DPDFPtr &in_posePDF, const CSensoryFramePtr & in_SF ) { MRPT_START if (index>=m_posesObsPairs.size()) THROW_EXCEPTION("Index out of bounds"); if (in_posePDF) m_posesObsPairs[index].first = in_posePDF; if (in_SF) m_posesObsPairs[index].second = in_SF; MRPT_END } /*--------------------------------------------------------------- set 2D ---------------------------------------------------------------*/ void CSimpleMap::set( size_t index, const CPosePDFPtr &in_posePDF, const CSensoryFramePtr &in_SF ) { MRPT_START if (index>=m_posesObsPairs.size()) THROW_EXCEPTION("Index out of bounds"); if (in_posePDF) m_posesObsPairs[index].first = CPose3DPDFPtr( CPose3DPDF::createFrom2D( *in_posePDF ) ); if (in_SF) m_posesObsPairs[index].second = in_SF; MRPT_END } /*--------------------------------------------------------------- insert ---------------------------------------------------------------*/ void CSimpleMap::insert( const CPose3DPDF *in_posePDF, const CSensoryFramePtr &in_SF ) { MRPT_START TPosePDFSensFramePair pair; pair.second = in_SF; pair.first = CPose3DPDFPtr( static_cast<CPose3DPDF*>(in_posePDF->duplicate()) ); m_posesObsPairs.push_back( pair ); MRPT_END } /*--------------------------------------------------------------- insert ---------------------------------------------------------------*/ void CSimpleMap::insert( const CPose3DPDFPtr &in_posePDF, const CSensoryFramePtr &in_SF ) { MRPT_START TPosePDFSensFramePair pair; pair.second = in_SF; pair.first = in_posePDF; m_posesObsPairs.push_back( pair ); MRPT_END } /*--------------------------------------------------------------- insert ---------------------------------------------------------------*/ void CSimpleMap::insert( const CPose3DPDF *in_posePDF, const CSensoryFrame &in_SF ) { MRPT_START TPosePDFSensFramePair pair; pair.second = CSensoryFramePtr( new CSensoryFrame(in_SF) ); pair.first = CPose3DPDFPtr( static_cast<CPose3DPDF*>(in_posePDF->duplicate()) ); m_posesObsPairs.push_back( pair ); MRPT_END } /*--------------------------------------------------------------- insert ---------------------------------------------------------------*/ void CSimpleMap::insert( const CPosePDF *in_posePDF, const CSensoryFrame &in_SF ) { MRPT_START TPosePDFSensFramePair pair; pair.second = CSensoryFramePtr( new CSensoryFrame(in_SF) ); pair.first = CPose3DPDFPtr( static_cast<CPose3DPDF*>(in_posePDF->duplicate()) ); m_posesObsPairs.push_back( pair ); MRPT_END } /*--------------------------------------------------------------- insert ---------------------------------------------------------------*/ void CSimpleMap::insert( const CPosePDF *in_posePDF, const CSensoryFramePtr &in_SF ) { MRPT_START TPosePDFSensFramePair pair; pair.second = in_SF; pair.first = CPose3DPDFPtr( static_cast<CPose3DPDF*>(in_posePDF->duplicate()) ); m_posesObsPairs.push_back( pair ); MRPT_END } /*--------------------------------------------------------------- insert 2D ---------------------------------------------------------------*/ void CSimpleMap::insert( const CPosePDFPtr &in_posePDF, const CSensoryFramePtr &in_SF ) { insert( CPose3DPDFPtr( CPose3DPDF::createFrom2D( *in_posePDF ) ) ,in_SF); } /*--------------------------------------------------------------- writeToStream Implements the writing to a CStream capability of CSerializable objects ---------------------------------------------------------------*/ void CSimpleMap::writeToStream(mrpt::utils::CStream &out,int *version) const { if (version) *version = 1; else { uint32_t i,n; n = m_posesObsPairs.size(); out << n; for (i=0;i<n;i++) out << *m_posesObsPairs[i].first << *m_posesObsPairs[i].second; } } /*--------------------------------------------------------------- readFromStream ---------------------------------------------------------------*/ void CSimpleMap::readFromStream(mrpt::utils::CStream &in, int version) { switch(version) { case 1: { uint32_t i,n; clear(); in >> n; m_posesObsPairs.resize(n); for (i=0;i<n;i++) in >> m_posesObsPairs[i].first >> m_posesObsPairs[i].second; } break; case 0: { // There are 2D poses PDF instead of 3D: transform them: uint32_t i,n; clear(); in >> n; m_posesObsPairs.resize(n); for (i=0;i<n;i++) { CPosePDFPtr aux2Dpose; in >> aux2Dpose >> m_posesObsPairs[i].second; m_posesObsPairs[i].first = CPose3DPDFPtr( CPose3DPDF::createFrom2D( *aux2Dpose ) ); } } break; default: MRPT_THROW_UNKNOWN_SERIALIZATION_VERSION(version) }; } /*--------------------------------------------------------------- changeCoordinatesOrigin ---------------------------------------------------------------*/ void CSimpleMap::changeCoordinatesOrigin( const CPose3D &newOrigin ) { for (TPosePDFSensFramePairList::iterator it=m_posesObsPairs.begin(); it!=m_posesObsPairs.end(); ++it) it->first->changeCoordinatesReference(newOrigin); } /** Save this object to a .simplemap binary file (compressed with gzip) * \sa loadFromFile * \return false on any error. */ bool CSimpleMap::saveToFile(const std::string &filName) const { try { mrpt::utils::CFileGZOutputStream f(filName); f << *this; return true; } catch (...) { return false; } } /** Load the contents of this object from a .simplemap binary file (possibly compressed with gzip) * \sa saveToFile * \return false on any error. */ bool CSimpleMap::loadFromFile(const std::string &filName) { try { mrpt::utils::CFileGZInputStream f(filName); f >> *this; return true; } catch (...) { return false; } }
9,530
3,249
// ******************************************************** // This C++ code was automatically generated by ml2cpp (development version). // Copyright 2020 // https://github.com/antoinecarme/ml2cpp // Model : XGBClassifier // Dataset : BreastCancer // This CPP code can be compiled using any C++-17 compiler. // g++ -Wall -Wno-unused-function -std=c++17 -g -o ml2cpp-demo_XGBClassifier_BreastCancer.exe ml2cpp-demo_XGBClassifier_BreastCancer.cpp // Model deployment code // ******************************************************** #include "../../Generic.i" namespace { std::vector<std::any> get_classes(){ std::vector<std::any> lClasses = { 0, 1 }; return lClasses; } namespace XGB_Tree_0_0 { std::vector<std::any> get_classes(){ std::vector<std::any> lClasses = { 0, 1 }; return lClasses; } typedef std::vector<double> tNodeData; std::map<int, tNodeData> Decision_Tree_Node_data = { { 3 , {0.577859819 }} , { 4 , {0.104347833 }} , { 5 , {-0.381818205 }} , { 6 , {-0.578181803 }} }; int get_decision_tree_node_index(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29) { int lNodeIndex = ( Feature_27 < 0.145449996 ) ? ( ( Feature_22 < 105.850006 ) ? ( 3 ) : ( 4 ) ) : ( ( Feature_0 < 15.2600002 ) ? ( 5 ) : ( 6 ) ); return lNodeIndex; } std::vector<std::string> get_input_names(){ std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3", "Feature_4", "Feature_5", "Feature_6", "Feature_7", "Feature_8", "Feature_9", "Feature_10", "Feature_11", "Feature_12", "Feature_13", "Feature_14", "Feature_15", "Feature_16", "Feature_17", "Feature_18", "Feature_19", "Feature_20", "Feature_21", "Feature_22", "Feature_23", "Feature_24", "Feature_25", "Feature_26", "Feature_27", "Feature_28", "Feature_29" }; return lFeatures; } std::vector<std::string> get_output_names(){ std::vector<std::string> lOutputs = { "Score_0", "Score_1", "Proba_0", "Proba_1", "LogProba_0", "LogProba_1" }; return lOutputs; } tTable compute_classification_scores(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29) { auto lClasses = get_classes(); int lNodeIndex = get_decision_tree_node_index(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29); std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ]; tTable lTable; lTable["Score"] = { lNodeValue [0], 1.0 - lNodeValue [0] } ; lTable["Proba"] = { std::any(), std::any() } ; recompute_log_probas( lTable ); return lTable; } tTable compute_model_outputs_from_table( tTable const & iTable) { tTable lTable = compute_classification_scores(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0], iTable.at("Feature_4")[0], iTable.at("Feature_5")[0], iTable.at("Feature_6")[0], iTable.at("Feature_7")[0], iTable.at("Feature_8")[0], iTable.at("Feature_9")[0], iTable.at("Feature_10")[0], iTable.at("Feature_11")[0], iTable.at("Feature_12")[0], iTable.at("Feature_13")[0], iTable.at("Feature_14")[0], iTable.at("Feature_15")[0], iTable.at("Feature_16")[0], iTable.at("Feature_17")[0], iTable.at("Feature_18")[0], iTable.at("Feature_19")[0], iTable.at("Feature_20")[0], iTable.at("Feature_21")[0], iTable.at("Feature_22")[0], iTable.at("Feature_23")[0], iTable.at("Feature_24")[0], iTable.at("Feature_25")[0], iTable.at("Feature_26")[0], iTable.at("Feature_27")[0], iTable.at("Feature_28")[0], iTable.at("Feature_29")[0]); return lTable; } } // eof namespace XGB_Tree_0_0 namespace XGB_Tree_0_1 { std::vector<std::any> get_classes(){ std::vector<std::any> lClasses = { 0, 1 }; return lClasses; } typedef std::vector<double> tNodeData; std::map<int, tNodeData> Decision_Tree_Node_data = { { 2 , {-0.443791091 }} , { 3 , {0.452014327 }} , { 4 , {0.0273430217 }} }; int get_decision_tree_node_index(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29) { int lNodeIndex = ( Feature_22 < 114.399994 ) ? ( ( Feature_7 < 0.0489199981 ) ? ( 3 ) : ( 4 ) ) : ( 2 ); return lNodeIndex; } std::vector<std::string> get_input_names(){ std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3", "Feature_4", "Feature_5", "Feature_6", "Feature_7", "Feature_8", "Feature_9", "Feature_10", "Feature_11", "Feature_12", "Feature_13", "Feature_14", "Feature_15", "Feature_16", "Feature_17", "Feature_18", "Feature_19", "Feature_20", "Feature_21", "Feature_22", "Feature_23", "Feature_24", "Feature_25", "Feature_26", "Feature_27", "Feature_28", "Feature_29" }; return lFeatures; } std::vector<std::string> get_output_names(){ std::vector<std::string> lOutputs = { "Score_0", "Score_1", "Proba_0", "Proba_1", "LogProba_0", "LogProba_1" }; return lOutputs; } tTable compute_classification_scores(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29) { auto lClasses = get_classes(); int lNodeIndex = get_decision_tree_node_index(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29); std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ]; tTable lTable; lTable["Score"] = { lNodeValue [0], 1.0 - lNodeValue [0] } ; lTable["Proba"] = { std::any(), std::any() } ; recompute_log_probas( lTable ); return lTable; } tTable compute_model_outputs_from_table( tTable const & iTable) { tTable lTable = compute_classification_scores(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0], iTable.at("Feature_4")[0], iTable.at("Feature_5")[0], iTable.at("Feature_6")[0], iTable.at("Feature_7")[0], iTable.at("Feature_8")[0], iTable.at("Feature_9")[0], iTable.at("Feature_10")[0], iTable.at("Feature_11")[0], iTable.at("Feature_12")[0], iTable.at("Feature_13")[0], iTable.at("Feature_14")[0], iTable.at("Feature_15")[0], iTable.at("Feature_16")[0], iTable.at("Feature_17")[0], iTable.at("Feature_18")[0], iTable.at("Feature_19")[0], iTable.at("Feature_20")[0], iTable.at("Feature_21")[0], iTable.at("Feature_22")[0], iTable.at("Feature_23")[0], iTable.at("Feature_24")[0], iTable.at("Feature_25")[0], iTable.at("Feature_26")[0], iTable.at("Feature_27")[0], iTable.at("Feature_28")[0], iTable.at("Feature_29")[0]); return lTable; } } // eof namespace XGB_Tree_0_1 namespace XGB_Tree_0_2 { std::vector<std::any> get_classes(){ std::vector<std::any> lClasses = { 0, 1 }; return lClasses; } typedef std::vector<double> tNodeData; std::map<int, tNodeData> Decision_Tree_Node_data = { { 3 , {0.396163613 }} , { 4 , {0.0294305328 }} , { 5 , {-0.232830554 }} , { 6 , {-0.411204338 }} }; int get_decision_tree_node_index(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29) { int lNodeIndex = ( Feature_27 < 0.145449996 ) ? ( ( Feature_13 < 32.8499985 ) ? ( 3 ) : ( 4 ) ) : ( ( Feature_21 < 26.2200012 ) ? ( 5 ) : ( 6 ) ); return lNodeIndex; } std::vector<std::string> get_input_names(){ std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3", "Feature_4", "Feature_5", "Feature_6", "Feature_7", "Feature_8", "Feature_9", "Feature_10", "Feature_11", "Feature_12", "Feature_13", "Feature_14", "Feature_15", "Feature_16", "Feature_17", "Feature_18", "Feature_19", "Feature_20", "Feature_21", "Feature_22", "Feature_23", "Feature_24", "Feature_25", "Feature_26", "Feature_27", "Feature_28", "Feature_29" }; return lFeatures; } std::vector<std::string> get_output_names(){ std::vector<std::string> lOutputs = { "Score_0", "Score_1", "Proba_0", "Proba_1", "LogProba_0", "LogProba_1" }; return lOutputs; } tTable compute_classification_scores(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29) { auto lClasses = get_classes(); int lNodeIndex = get_decision_tree_node_index(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29); std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ]; tTable lTable; lTable["Score"] = { lNodeValue [0], 1.0 - lNodeValue [0] } ; lTable["Proba"] = { std::any(), std::any() } ; recompute_log_probas( lTable ); return lTable; } tTable compute_model_outputs_from_table( tTable const & iTable) { tTable lTable = compute_classification_scores(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0], iTable.at("Feature_4")[0], iTable.at("Feature_5")[0], iTable.at("Feature_6")[0], iTable.at("Feature_7")[0], iTable.at("Feature_8")[0], iTable.at("Feature_9")[0], iTable.at("Feature_10")[0], iTable.at("Feature_11")[0], iTable.at("Feature_12")[0], iTable.at("Feature_13")[0], iTable.at("Feature_14")[0], iTable.at("Feature_15")[0], iTable.at("Feature_16")[0], iTable.at("Feature_17")[0], iTable.at("Feature_18")[0], iTable.at("Feature_19")[0], iTable.at("Feature_20")[0], iTable.at("Feature_21")[0], iTable.at("Feature_22")[0], iTable.at("Feature_23")[0], iTable.at("Feature_24")[0], iTable.at("Feature_25")[0], iTable.at("Feature_26")[0], iTable.at("Feature_27")[0], iTable.at("Feature_28")[0], iTable.at("Feature_29")[0]); return lTable; } } // eof namespace XGB_Tree_0_2 namespace XGB_Tree_0_3 { std::vector<std::any> get_classes(){ std::vector<std::any> lClasses = { 0, 1 }; return lClasses; } typedef std::vector<double> tNodeData; std::map<int, tNodeData> Decision_Tree_Node_data = { { 2 , {-0.369929641 }} , { 3 , {0.352983713 }} , { 4 , {0.0058717085 }} }; int get_decision_tree_node_index(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29) { int lNodeIndex = ( Feature_22 < 117.449997 ) ? ( ( Feature_27 < 0.122299999 ) ? ( 3 ) : ( 4 ) ) : ( 2 ); return lNodeIndex; } std::vector<std::string> get_input_names(){ std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3", "Feature_4", "Feature_5", "Feature_6", "Feature_7", "Feature_8", "Feature_9", "Feature_10", "Feature_11", "Feature_12", "Feature_13", "Feature_14", "Feature_15", "Feature_16", "Feature_17", "Feature_18", "Feature_19", "Feature_20", "Feature_21", "Feature_22", "Feature_23", "Feature_24", "Feature_25", "Feature_26", "Feature_27", "Feature_28", "Feature_29" }; return lFeatures; } std::vector<std::string> get_output_names(){ std::vector<std::string> lOutputs = { "Score_0", "Score_1", "Proba_0", "Proba_1", "LogProba_0", "LogProba_1" }; return lOutputs; } tTable compute_classification_scores(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29) { auto lClasses = get_classes(); int lNodeIndex = get_decision_tree_node_index(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29); std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ]; tTable lTable; lTable["Score"] = { lNodeValue [0], 1.0 - lNodeValue [0] } ; lTable["Proba"] = { std::any(), std::any() } ; recompute_log_probas( lTable ); return lTable; } tTable compute_model_outputs_from_table( tTable const & iTable) { tTable lTable = compute_classification_scores(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0], iTable.at("Feature_4")[0], iTable.at("Feature_5")[0], iTable.at("Feature_6")[0], iTable.at("Feature_7")[0], iTable.at("Feature_8")[0], iTable.at("Feature_9")[0], iTable.at("Feature_10")[0], iTable.at("Feature_11")[0], iTable.at("Feature_12")[0], iTable.at("Feature_13")[0], iTable.at("Feature_14")[0], iTable.at("Feature_15")[0], iTable.at("Feature_16")[0], iTable.at("Feature_17")[0], iTable.at("Feature_18")[0], iTable.at("Feature_19")[0], iTable.at("Feature_20")[0], iTable.at("Feature_21")[0], iTable.at("Feature_22")[0], iTable.at("Feature_23")[0], iTable.at("Feature_24")[0], iTable.at("Feature_25")[0], iTable.at("Feature_26")[0], iTable.at("Feature_27")[0], iTable.at("Feature_28")[0], iTable.at("Feature_29")[0]); return lTable; } } // eof namespace XGB_Tree_0_3 namespace XGB_Tree_0_4 { std::vector<std::any> get_classes(){ std::vector<std::any> lClasses = { 0, 1 }; return lClasses; } typedef std::vector<double> tNodeData; std::map<int, tNodeData> Decision_Tree_Node_data = { { 3 , {0.331853092 }} , { 4 , {0.0621976517 }} , { 5 , {-0.196852133 }} , { 6 , {-0.360705614 }} }; int get_decision_tree_node_index(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29) { int lNodeIndex = ( Feature_20 < 16.7950001 ) ? ( ( Feature_7 < 0.0447399989 ) ? ( 3 ) : ( 4 ) ) : ( ( Feature_1 < 20.2350006 ) ? ( 5 ) : ( 6 ) ); return lNodeIndex; } std::vector<std::string> get_input_names(){ std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3", "Feature_4", "Feature_5", "Feature_6", "Feature_7", "Feature_8", "Feature_9", "Feature_10", "Feature_11", "Feature_12", "Feature_13", "Feature_14", "Feature_15", "Feature_16", "Feature_17", "Feature_18", "Feature_19", "Feature_20", "Feature_21", "Feature_22", "Feature_23", "Feature_24", "Feature_25", "Feature_26", "Feature_27", "Feature_28", "Feature_29" }; return lFeatures; } std::vector<std::string> get_output_names(){ std::vector<std::string> lOutputs = { "Score_0", "Score_1", "Proba_0", "Proba_1", "LogProba_0", "LogProba_1" }; return lOutputs; } tTable compute_classification_scores(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29) { auto lClasses = get_classes(); int lNodeIndex = get_decision_tree_node_index(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29); std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ]; tTable lTable; lTable["Score"] = { lNodeValue [0], 1.0 - lNodeValue [0] } ; lTable["Proba"] = { std::any(), std::any() } ; recompute_log_probas( lTable ); return lTable; } tTable compute_model_outputs_from_table( tTable const & iTable) { tTable lTable = compute_classification_scores(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0], iTable.at("Feature_4")[0], iTable.at("Feature_5")[0], iTable.at("Feature_6")[0], iTable.at("Feature_7")[0], iTable.at("Feature_8")[0], iTable.at("Feature_9")[0], iTable.at("Feature_10")[0], iTable.at("Feature_11")[0], iTable.at("Feature_12")[0], iTable.at("Feature_13")[0], iTable.at("Feature_14")[0], iTable.at("Feature_15")[0], iTable.at("Feature_16")[0], iTable.at("Feature_17")[0], iTable.at("Feature_18")[0], iTable.at("Feature_19")[0], iTable.at("Feature_20")[0], iTable.at("Feature_21")[0], iTable.at("Feature_22")[0], iTable.at("Feature_23")[0], iTable.at("Feature_24")[0], iTable.at("Feature_25")[0], iTable.at("Feature_26")[0], iTable.at("Feature_27")[0], iTable.at("Feature_28")[0], iTable.at("Feature_29")[0]); return lTable; } } // eof namespace XGB_Tree_0_4 namespace XGB_Tree_0_5 { std::vector<std::any> get_classes(){ std::vector<std::any> lClasses = { 0, 1 }; return lClasses; } typedef std::vector<double> tNodeData; std::map<int, tNodeData> Decision_Tree_Node_data = { { 2 , {-0.299602687 }} , { 3 , {0.323272616 }} , { 4 , {-0.00179177092 }} }; int get_decision_tree_node_index(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29) { int lNodeIndex = ( Feature_27 < 0.150749996 ) ? ( ( Feature_13 < 29.3899994 ) ? ( 3 ) : ( 4 ) ) : ( 2 ); return lNodeIndex; } std::vector<std::string> get_input_names(){ std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3", "Feature_4", "Feature_5", "Feature_6", "Feature_7", "Feature_8", "Feature_9", "Feature_10", "Feature_11", "Feature_12", "Feature_13", "Feature_14", "Feature_15", "Feature_16", "Feature_17", "Feature_18", "Feature_19", "Feature_20", "Feature_21", "Feature_22", "Feature_23", "Feature_24", "Feature_25", "Feature_26", "Feature_27", "Feature_28", "Feature_29" }; return lFeatures; } std::vector<std::string> get_output_names(){ std::vector<std::string> lOutputs = { "Score_0", "Score_1", "Proba_0", "Proba_1", "LogProba_0", "LogProba_1" }; return lOutputs; } tTable compute_classification_scores(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29) { auto lClasses = get_classes(); int lNodeIndex = get_decision_tree_node_index(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29); std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ]; tTable lTable; lTable["Score"] = { lNodeValue [0], 1.0 - lNodeValue [0] } ; lTable["Proba"] = { std::any(), std::any() } ; recompute_log_probas( lTable ); return lTable; } tTable compute_model_outputs_from_table( tTable const & iTable) { tTable lTable = compute_classification_scores(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0], iTable.at("Feature_4")[0], iTable.at("Feature_5")[0], iTable.at("Feature_6")[0], iTable.at("Feature_7")[0], iTable.at("Feature_8")[0], iTable.at("Feature_9")[0], iTable.at("Feature_10")[0], iTable.at("Feature_11")[0], iTable.at("Feature_12")[0], iTable.at("Feature_13")[0], iTable.at("Feature_14")[0], iTable.at("Feature_15")[0], iTable.at("Feature_16")[0], iTable.at("Feature_17")[0], iTable.at("Feature_18")[0], iTable.at("Feature_19")[0], iTable.at("Feature_20")[0], iTable.at("Feature_21")[0], iTable.at("Feature_22")[0], iTable.at("Feature_23")[0], iTable.at("Feature_24")[0], iTable.at("Feature_25")[0], iTable.at("Feature_26")[0], iTable.at("Feature_27")[0], iTable.at("Feature_28")[0], iTable.at("Feature_29")[0]); return lTable; } } // eof namespace XGB_Tree_0_5 namespace XGB_Tree_0_6 { std::vector<std::any> get_classes(){ std::vector<std::any> lClasses = { 0, 1 }; return lClasses; } typedef std::vector<double> tNodeData; std::map<int, tNodeData> Decision_Tree_Node_data = { { 2 , {-0.257835239 }} , { 3 , {0.318035483 }} , { 4 , {0.0797671974 }} }; int get_decision_tree_node_index(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29) { int lNodeIndex = ( Feature_22 < 113.149994 ) ? ( ( Feature_21 < 25.1800003 ) ? ( 3 ) : ( 4 ) ) : ( 2 ); return lNodeIndex; } std::vector<std::string> get_input_names(){ std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3", "Feature_4", "Feature_5", "Feature_6", "Feature_7", "Feature_8", "Feature_9", "Feature_10", "Feature_11", "Feature_12", "Feature_13", "Feature_14", "Feature_15", "Feature_16", "Feature_17", "Feature_18", "Feature_19", "Feature_20", "Feature_21", "Feature_22", "Feature_23", "Feature_24", "Feature_25", "Feature_26", "Feature_27", "Feature_28", "Feature_29" }; return lFeatures; } std::vector<std::string> get_output_names(){ std::vector<std::string> lOutputs = { "Score_0", "Score_1", "Proba_0", "Proba_1", "LogProba_0", "LogProba_1" }; return lOutputs; } tTable compute_classification_scores(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29) { auto lClasses = get_classes(); int lNodeIndex = get_decision_tree_node_index(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29); std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ]; tTable lTable; lTable["Score"] = { lNodeValue [0], 1.0 - lNodeValue [0] } ; lTable["Proba"] = { std::any(), std::any() } ; recompute_log_probas( lTable ); return lTable; } tTable compute_model_outputs_from_table( tTable const & iTable) { tTable lTable = compute_classification_scores(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0], iTable.at("Feature_4")[0], iTable.at("Feature_5")[0], iTable.at("Feature_6")[0], iTable.at("Feature_7")[0], iTable.at("Feature_8")[0], iTable.at("Feature_9")[0], iTable.at("Feature_10")[0], iTable.at("Feature_11")[0], iTable.at("Feature_12")[0], iTable.at("Feature_13")[0], iTable.at("Feature_14")[0], iTable.at("Feature_15")[0], iTable.at("Feature_16")[0], iTable.at("Feature_17")[0], iTable.at("Feature_18")[0], iTable.at("Feature_19")[0], iTable.at("Feature_20")[0], iTable.at("Feature_21")[0], iTable.at("Feature_22")[0], iTable.at("Feature_23")[0], iTable.at("Feature_24")[0], iTable.at("Feature_25")[0], iTable.at("Feature_26")[0], iTable.at("Feature_27")[0], iTable.at("Feature_28")[0], iTable.at("Feature_29")[0]); return lTable; } } // eof namespace XGB_Tree_0_6 namespace XGB_Tree_0_7 { std::vector<std::any> get_classes(){ std::vector<std::any> lClasses = { 0, 1 }; return lClasses; } typedef std::vector<double> tNodeData; std::map<int, tNodeData> Decision_Tree_Node_data = { { 2 , {-0.183022752 }} , { 3 , {0.148378 }} , { 4 , {0.320678353 }} }; int get_decision_tree_node_index(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29) { int lNodeIndex = ( Feature_7 < 0.0489199981 ) ? ( ( Feature_15 < 0.0144750001 ) ? ( 3 ) : ( 4 ) ) : ( 2 ); return lNodeIndex; } std::vector<std::string> get_input_names(){ std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3", "Feature_4", "Feature_5", "Feature_6", "Feature_7", "Feature_8", "Feature_9", "Feature_10", "Feature_11", "Feature_12", "Feature_13", "Feature_14", "Feature_15", "Feature_16", "Feature_17", "Feature_18", "Feature_19", "Feature_20", "Feature_21", "Feature_22", "Feature_23", "Feature_24", "Feature_25", "Feature_26", "Feature_27", "Feature_28", "Feature_29" }; return lFeatures; } std::vector<std::string> get_output_names(){ std::vector<std::string> lOutputs = { "Score_0", "Score_1", "Proba_0", "Proba_1", "LogProba_0", "LogProba_1" }; return lOutputs; } tTable compute_classification_scores(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29) { auto lClasses = get_classes(); int lNodeIndex = get_decision_tree_node_index(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29); std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ]; tTable lTable; lTable["Score"] = { lNodeValue [0], 1.0 - lNodeValue [0] } ; lTable["Proba"] = { std::any(), std::any() } ; recompute_log_probas( lTable ); return lTable; } tTable compute_model_outputs_from_table( tTable const & iTable) { tTable lTable = compute_classification_scores(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0], iTable.at("Feature_4")[0], iTable.at("Feature_5")[0], iTable.at("Feature_6")[0], iTable.at("Feature_7")[0], iTable.at("Feature_8")[0], iTable.at("Feature_9")[0], iTable.at("Feature_10")[0], iTable.at("Feature_11")[0], iTable.at("Feature_12")[0], iTable.at("Feature_13")[0], iTable.at("Feature_14")[0], iTable.at("Feature_15")[0], iTable.at("Feature_16")[0], iTable.at("Feature_17")[0], iTable.at("Feature_18")[0], iTable.at("Feature_19")[0], iTable.at("Feature_20")[0], iTable.at("Feature_21")[0], iTable.at("Feature_22")[0], iTable.at("Feature_23")[0], iTable.at("Feature_24")[0], iTable.at("Feature_25")[0], iTable.at("Feature_26")[0], iTable.at("Feature_27")[0], iTable.at("Feature_28")[0], iTable.at("Feature_29")[0]); return lTable; } } // eof namespace XGB_Tree_0_7 namespace XGB_Tree_0_8 { std::vector<std::any> get_classes(){ std::vector<std::any> lClasses = { 0, 1 }; return lClasses; } typedef std::vector<double> tNodeData; std::map<int, tNodeData> Decision_Tree_Node_data = { { 1 , {0.26075694 }} , { 2 , {-0.140906826 }} }; int get_decision_tree_node_index(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29) { int lNodeIndex = ( Feature_23 < 739.199951 ) ? ( 1 ) : ( 2 ); return lNodeIndex; } std::vector<std::string> get_input_names(){ std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3", "Feature_4", "Feature_5", "Feature_6", "Feature_7", "Feature_8", "Feature_9", "Feature_10", "Feature_11", "Feature_12", "Feature_13", "Feature_14", "Feature_15", "Feature_16", "Feature_17", "Feature_18", "Feature_19", "Feature_20", "Feature_21", "Feature_22", "Feature_23", "Feature_24", "Feature_25", "Feature_26", "Feature_27", "Feature_28", "Feature_29" }; return lFeatures; } std::vector<std::string> get_output_names(){ std::vector<std::string> lOutputs = { "Score_0", "Score_1", "Proba_0", "Proba_1", "LogProba_0", "LogProba_1" }; return lOutputs; } tTable compute_classification_scores(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29) { auto lClasses = get_classes(); int lNodeIndex = get_decision_tree_node_index(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29); std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ]; tTable lTable; lTable["Score"] = { lNodeValue [0], 1.0 - lNodeValue [0] } ; lTable["Proba"] = { std::any(), std::any() } ; recompute_log_probas( lTable ); return lTable; } tTable compute_model_outputs_from_table( tTable const & iTable) { tTable lTable = compute_classification_scores(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0], iTable.at("Feature_4")[0], iTable.at("Feature_5")[0], iTable.at("Feature_6")[0], iTable.at("Feature_7")[0], iTable.at("Feature_8")[0], iTable.at("Feature_9")[0], iTable.at("Feature_10")[0], iTable.at("Feature_11")[0], iTable.at("Feature_12")[0], iTable.at("Feature_13")[0], iTable.at("Feature_14")[0], iTable.at("Feature_15")[0], iTable.at("Feature_16")[0], iTable.at("Feature_17")[0], iTable.at("Feature_18")[0], iTable.at("Feature_19")[0], iTable.at("Feature_20")[0], iTable.at("Feature_21")[0], iTable.at("Feature_22")[0], iTable.at("Feature_23")[0], iTable.at("Feature_24")[0], iTable.at("Feature_25")[0], iTable.at("Feature_26")[0], iTable.at("Feature_27")[0], iTable.at("Feature_28")[0], iTable.at("Feature_29")[0]); return lTable; } } // eof namespace XGB_Tree_0_8 namespace XGB_Tree_0_9 { std::vector<std::any> get_classes(){ std::vector<std::any> lClasses = { 0, 1 }; return lClasses; } typedef std::vector<double> tNodeData; std::map<int, tNodeData> Decision_Tree_Node_data = { { 1 , {0.257348537 }} , { 2 , {-0.121567562 }} }; int get_decision_tree_node_index(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29) { int lNodeIndex = ( Feature_26 < 0.224800006 ) ? ( 1 ) : ( 2 ); return lNodeIndex; } std::vector<std::string> get_input_names(){ std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3", "Feature_4", "Feature_5", "Feature_6", "Feature_7", "Feature_8", "Feature_9", "Feature_10", "Feature_11", "Feature_12", "Feature_13", "Feature_14", "Feature_15", "Feature_16", "Feature_17", "Feature_18", "Feature_19", "Feature_20", "Feature_21", "Feature_22", "Feature_23", "Feature_24", "Feature_25", "Feature_26", "Feature_27", "Feature_28", "Feature_29" }; return lFeatures; } std::vector<std::string> get_output_names(){ std::vector<std::string> lOutputs = { "Score_0", "Score_1", "Proba_0", "Proba_1", "LogProba_0", "LogProba_1" }; return lOutputs; } tTable compute_classification_scores(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29) { auto lClasses = get_classes(); int lNodeIndex = get_decision_tree_node_index(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29); std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ]; tTable lTable; lTable["Score"] = { lNodeValue [0], 1.0 - lNodeValue [0] } ; lTable["Proba"] = { std::any(), std::any() } ; recompute_log_probas( lTable ); return lTable; } tTable compute_model_outputs_from_table( tTable const & iTable) { tTable lTable = compute_classification_scores(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0], iTable.at("Feature_4")[0], iTable.at("Feature_5")[0], iTable.at("Feature_6")[0], iTable.at("Feature_7")[0], iTable.at("Feature_8")[0], iTable.at("Feature_9")[0], iTable.at("Feature_10")[0], iTable.at("Feature_11")[0], iTable.at("Feature_12")[0], iTable.at("Feature_13")[0], iTable.at("Feature_14")[0], iTable.at("Feature_15")[0], iTable.at("Feature_16")[0], iTable.at("Feature_17")[0], iTable.at("Feature_18")[0], iTable.at("Feature_19")[0], iTable.at("Feature_20")[0], iTable.at("Feature_21")[0], iTable.at("Feature_22")[0], iTable.at("Feature_23")[0], iTable.at("Feature_24")[0], iTable.at("Feature_25")[0], iTable.at("Feature_26")[0], iTable.at("Feature_27")[0], iTable.at("Feature_28")[0], iTable.at("Feature_29")[0]); return lTable; } } // eof namespace XGB_Tree_0_9 namespace XGB_Tree_0_10 { std::vector<std::any> get_classes(){ std::vector<std::any> lClasses = { 0, 1 }; return lClasses; } typedef std::vector<double> tNodeData; std::map<int, tNodeData> Decision_Tree_Node_data = { { 1 , {0.271092504 }} , { 2 , {-0.100576989 }} }; int get_decision_tree_node_index(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29) { int lNodeIndex = ( Feature_21 < 23.0250015 ) ? ( 1 ) : ( 2 ); return lNodeIndex; } std::vector<std::string> get_input_names(){ std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3", "Feature_4", "Feature_5", "Feature_6", "Feature_7", "Feature_8", "Feature_9", "Feature_10", "Feature_11", "Feature_12", "Feature_13", "Feature_14", "Feature_15", "Feature_16", "Feature_17", "Feature_18", "Feature_19", "Feature_20", "Feature_21", "Feature_22", "Feature_23", "Feature_24", "Feature_25", "Feature_26", "Feature_27", "Feature_28", "Feature_29" }; return lFeatures; } std::vector<std::string> get_output_names(){ std::vector<std::string> lOutputs = { "Score_0", "Score_1", "Proba_0", "Proba_1", "LogProba_0", "LogProba_1" }; return lOutputs; } tTable compute_classification_scores(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29) { auto lClasses = get_classes(); int lNodeIndex = get_decision_tree_node_index(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29); std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ]; tTable lTable; lTable["Score"] = { lNodeValue [0], 1.0 - lNodeValue [0] } ; lTable["Proba"] = { std::any(), std::any() } ; recompute_log_probas( lTable ); return lTable; } tTable compute_model_outputs_from_table( tTable const & iTable) { tTable lTable = compute_classification_scores(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0], iTable.at("Feature_4")[0], iTable.at("Feature_5")[0], iTable.at("Feature_6")[0], iTable.at("Feature_7")[0], iTable.at("Feature_8")[0], iTable.at("Feature_9")[0], iTable.at("Feature_10")[0], iTable.at("Feature_11")[0], iTable.at("Feature_12")[0], iTable.at("Feature_13")[0], iTable.at("Feature_14")[0], iTable.at("Feature_15")[0], iTable.at("Feature_16")[0], iTable.at("Feature_17")[0], iTable.at("Feature_18")[0], iTable.at("Feature_19")[0], iTable.at("Feature_20")[0], iTable.at("Feature_21")[0], iTable.at("Feature_22")[0], iTable.at("Feature_23")[0], iTable.at("Feature_24")[0], iTable.at("Feature_25")[0], iTable.at("Feature_26")[0], iTable.at("Feature_27")[0], iTable.at("Feature_28")[0], iTable.at("Feature_29")[0]); return lTable; } } // eof namespace XGB_Tree_0_10 namespace XGB_Tree_0_11 { std::vector<std::any> get_classes(){ std::vector<std::any> lClasses = { 0, 1 }; return lClasses; } typedef std::vector<double> tNodeData; std::map<int, tNodeData> Decision_Tree_Node_data = { { 1 , {0.172649145 }} , { 2 , {-0.193059087 }} }; int get_decision_tree_node_index(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29) { int lNodeIndex = ( Feature_13 < 34.4049988 ) ? ( 1 ) : ( 2 ); return lNodeIndex; } std::vector<std::string> get_input_names(){ std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3", "Feature_4", "Feature_5", "Feature_6", "Feature_7", "Feature_8", "Feature_9", "Feature_10", "Feature_11", "Feature_12", "Feature_13", "Feature_14", "Feature_15", "Feature_16", "Feature_17", "Feature_18", "Feature_19", "Feature_20", "Feature_21", "Feature_22", "Feature_23", "Feature_24", "Feature_25", "Feature_26", "Feature_27", "Feature_28", "Feature_29" }; return lFeatures; } std::vector<std::string> get_output_names(){ std::vector<std::string> lOutputs = { "Score_0", "Score_1", "Proba_0", "Proba_1", "LogProba_0", "LogProba_1" }; return lOutputs; } tTable compute_classification_scores(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29) { auto lClasses = get_classes(); int lNodeIndex = get_decision_tree_node_index(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29); std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ]; tTable lTable; lTable["Score"] = { lNodeValue [0], 1.0 - lNodeValue [0] } ; lTable["Proba"] = { std::any(), std::any() } ; recompute_log_probas( lTable ); return lTable; } tTable compute_model_outputs_from_table( tTable const & iTable) { tTable lTable = compute_classification_scores(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0], iTable.at("Feature_4")[0], iTable.at("Feature_5")[0], iTable.at("Feature_6")[0], iTable.at("Feature_7")[0], iTable.at("Feature_8")[0], iTable.at("Feature_9")[0], iTable.at("Feature_10")[0], iTable.at("Feature_11")[0], iTable.at("Feature_12")[0], iTable.at("Feature_13")[0], iTable.at("Feature_14")[0], iTable.at("Feature_15")[0], iTable.at("Feature_16")[0], iTable.at("Feature_17")[0], iTable.at("Feature_18")[0], iTable.at("Feature_19")[0], iTable.at("Feature_20")[0], iTable.at("Feature_21")[0], iTable.at("Feature_22")[0], iTable.at("Feature_23")[0], iTable.at("Feature_24")[0], iTable.at("Feature_25")[0], iTable.at("Feature_26")[0], iTable.at("Feature_27")[0], iTable.at("Feature_28")[0], iTable.at("Feature_29")[0]); return lTable; } } // eof namespace XGB_Tree_0_11 namespace XGB_Tree_0_12 { std::vector<std::any> get_classes(){ std::vector<std::any> lClasses = { 0, 1 }; return lClasses; } typedef std::vector<double> tNodeData; std::map<int, tNodeData> Decision_Tree_Node_data = { { 1 , {0.181349665 }} , { 2 , {-0.152797535 }} }; int get_decision_tree_node_index(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29) { int lNodeIndex = ( Feature_27 < 0.130999997 ) ? ( 1 ) : ( 2 ); return lNodeIndex; } std::vector<std::string> get_input_names(){ std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3", "Feature_4", "Feature_5", "Feature_6", "Feature_7", "Feature_8", "Feature_9", "Feature_10", "Feature_11", "Feature_12", "Feature_13", "Feature_14", "Feature_15", "Feature_16", "Feature_17", "Feature_18", "Feature_19", "Feature_20", "Feature_21", "Feature_22", "Feature_23", "Feature_24", "Feature_25", "Feature_26", "Feature_27", "Feature_28", "Feature_29" }; return lFeatures; } std::vector<std::string> get_output_names(){ std::vector<std::string> lOutputs = { "Score_0", "Score_1", "Proba_0", "Proba_1", "LogProba_0", "LogProba_1" }; return lOutputs; } tTable compute_classification_scores(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29) { auto lClasses = get_classes(); int lNodeIndex = get_decision_tree_node_index(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29); std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ]; tTable lTable; lTable["Score"] = { lNodeValue [0], 1.0 - lNodeValue [0] } ; lTable["Proba"] = { std::any(), std::any() } ; recompute_log_probas( lTable ); return lTable; } tTable compute_model_outputs_from_table( tTable const & iTable) { tTable lTable = compute_classification_scores(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0], iTable.at("Feature_4")[0], iTable.at("Feature_5")[0], iTable.at("Feature_6")[0], iTable.at("Feature_7")[0], iTable.at("Feature_8")[0], iTable.at("Feature_9")[0], iTable.at("Feature_10")[0], iTable.at("Feature_11")[0], iTable.at("Feature_12")[0], iTable.at("Feature_13")[0], iTable.at("Feature_14")[0], iTable.at("Feature_15")[0], iTable.at("Feature_16")[0], iTable.at("Feature_17")[0], iTable.at("Feature_18")[0], iTable.at("Feature_19")[0], iTable.at("Feature_20")[0], iTable.at("Feature_21")[0], iTable.at("Feature_22")[0], iTable.at("Feature_23")[0], iTable.at("Feature_24")[0], iTable.at("Feature_25")[0], iTable.at("Feature_26")[0], iTable.at("Feature_27")[0], iTable.at("Feature_28")[0], iTable.at("Feature_29")[0]); return lTable; } } // eof namespace XGB_Tree_0_12 namespace XGB_Tree_0_13 { std::vector<std::any> get_classes(){ std::vector<std::any> lClasses = { 0, 1 }; return lClasses; } typedef std::vector<double> tNodeData; std::map<int, tNodeData> Decision_Tree_Node_data = { { 1 , {0.153317034 }} , { 2 , {-0.155450851 }} }; int get_decision_tree_node_index(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29) { int lNodeIndex = ( Feature_23 < 822.849976 ) ? ( 1 ) : ( 2 ); return lNodeIndex; } std::vector<std::string> get_input_names(){ std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3", "Feature_4", "Feature_5", "Feature_6", "Feature_7", "Feature_8", "Feature_9", "Feature_10", "Feature_11", "Feature_12", "Feature_13", "Feature_14", "Feature_15", "Feature_16", "Feature_17", "Feature_18", "Feature_19", "Feature_20", "Feature_21", "Feature_22", "Feature_23", "Feature_24", "Feature_25", "Feature_26", "Feature_27", "Feature_28", "Feature_29" }; return lFeatures; } std::vector<std::string> get_output_names(){ std::vector<std::string> lOutputs = { "Score_0", "Score_1", "Proba_0", "Proba_1", "LogProba_0", "LogProba_1" }; return lOutputs; } tTable compute_classification_scores(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29) { auto lClasses = get_classes(); int lNodeIndex = get_decision_tree_node_index(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29); std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ]; tTable lTable; lTable["Score"] = { lNodeValue [0], 1.0 - lNodeValue [0] } ; lTable["Proba"] = { std::any(), std::any() } ; recompute_log_probas( lTable ); return lTable; } tTable compute_model_outputs_from_table( tTable const & iTable) { tTable lTable = compute_classification_scores(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0], iTable.at("Feature_4")[0], iTable.at("Feature_5")[0], iTable.at("Feature_6")[0], iTable.at("Feature_7")[0], iTable.at("Feature_8")[0], iTable.at("Feature_9")[0], iTable.at("Feature_10")[0], iTable.at("Feature_11")[0], iTable.at("Feature_12")[0], iTable.at("Feature_13")[0], iTable.at("Feature_14")[0], iTable.at("Feature_15")[0], iTable.at("Feature_16")[0], iTable.at("Feature_17")[0], iTable.at("Feature_18")[0], iTable.at("Feature_19")[0], iTable.at("Feature_20")[0], iTable.at("Feature_21")[0], iTable.at("Feature_22")[0], iTable.at("Feature_23")[0], iTable.at("Feature_24")[0], iTable.at("Feature_25")[0], iTable.at("Feature_26")[0], iTable.at("Feature_27")[0], iTable.at("Feature_28")[0], iTable.at("Feature_29")[0]); return lTable; } } // eof namespace XGB_Tree_0_13 namespace XGB_Tree_0_14 { std::vector<std::any> get_classes(){ std::vector<std::any> lClasses = { 0, 1 }; return lClasses; } typedef std::vector<double> tNodeData; std::map<int, tNodeData> Decision_Tree_Node_data = { { 1 , {0.153998569 }} , { 2 , {-0.142487958 }} }; int get_decision_tree_node_index(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29) { int lNodeIndex = ( Feature_1 < 19.4699993 ) ? ( 1 ) : ( 2 ); return lNodeIndex; } std::vector<std::string> get_input_names(){ std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3", "Feature_4", "Feature_5", "Feature_6", "Feature_7", "Feature_8", "Feature_9", "Feature_10", "Feature_11", "Feature_12", "Feature_13", "Feature_14", "Feature_15", "Feature_16", "Feature_17", "Feature_18", "Feature_19", "Feature_20", "Feature_21", "Feature_22", "Feature_23", "Feature_24", "Feature_25", "Feature_26", "Feature_27", "Feature_28", "Feature_29" }; return lFeatures; } std::vector<std::string> get_output_names(){ std::vector<std::string> lOutputs = { "Score_0", "Score_1", "Proba_0", "Proba_1", "LogProba_0", "LogProba_1" }; return lOutputs; } tTable compute_classification_scores(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29) { auto lClasses = get_classes(); int lNodeIndex = get_decision_tree_node_index(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29); std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ]; tTable lTable; lTable["Score"] = { lNodeValue [0], 1.0 - lNodeValue [0] } ; lTable["Proba"] = { std::any(), std::any() } ; recompute_log_probas( lTable ); return lTable; } tTable compute_model_outputs_from_table( tTable const & iTable) { tTable lTable = compute_classification_scores(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0], iTable.at("Feature_4")[0], iTable.at("Feature_5")[0], iTable.at("Feature_6")[0], iTable.at("Feature_7")[0], iTable.at("Feature_8")[0], iTable.at("Feature_9")[0], iTable.at("Feature_10")[0], iTable.at("Feature_11")[0], iTable.at("Feature_12")[0], iTable.at("Feature_13")[0], iTable.at("Feature_14")[0], iTable.at("Feature_15")[0], iTable.at("Feature_16")[0], iTable.at("Feature_17")[0], iTable.at("Feature_18")[0], iTable.at("Feature_19")[0], iTable.at("Feature_20")[0], iTable.at("Feature_21")[0], iTable.at("Feature_22")[0], iTable.at("Feature_23")[0], iTable.at("Feature_24")[0], iTable.at("Feature_25")[0], iTable.at("Feature_26")[0], iTable.at("Feature_27")[0], iTable.at("Feature_28")[0], iTable.at("Feature_29")[0]); return lTable; } } // eof namespace XGB_Tree_0_14 namespace XGB_Tree_0_15 { std::vector<std::any> get_classes(){ std::vector<std::any> lClasses = { 0, 1 }; return lClasses; } typedef std::vector<double> tNodeData; std::map<int, tNodeData> Decision_Tree_Node_data = { { 1 , {0.141609788 }} , { 2 , {-0.121677577 }} }; int get_decision_tree_node_index(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29) { int lNodeIndex = ( Feature_27 < 0.130999997 ) ? ( 1 ) : ( 2 ); return lNodeIndex; } std::vector<std::string> get_input_names(){ std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3", "Feature_4", "Feature_5", "Feature_6", "Feature_7", "Feature_8", "Feature_9", "Feature_10", "Feature_11", "Feature_12", "Feature_13", "Feature_14", "Feature_15", "Feature_16", "Feature_17", "Feature_18", "Feature_19", "Feature_20", "Feature_21", "Feature_22", "Feature_23", "Feature_24", "Feature_25", "Feature_26", "Feature_27", "Feature_28", "Feature_29" }; return lFeatures; } std::vector<std::string> get_output_names(){ std::vector<std::string> lOutputs = { "Score_0", "Score_1", "Proba_0", "Proba_1", "LogProba_0", "LogProba_1" }; return lOutputs; } tTable compute_classification_scores(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29) { auto lClasses = get_classes(); int lNodeIndex = get_decision_tree_node_index(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29); std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ]; tTable lTable; lTable["Score"] = { lNodeValue [0], 1.0 - lNodeValue [0] } ; lTable["Proba"] = { std::any(), std::any() } ; recompute_log_probas( lTable ); return lTable; } tTable compute_model_outputs_from_table( tTable const & iTable) { tTable lTable = compute_classification_scores(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0], iTable.at("Feature_4")[0], iTable.at("Feature_5")[0], iTable.at("Feature_6")[0], iTable.at("Feature_7")[0], iTable.at("Feature_8")[0], iTable.at("Feature_9")[0], iTable.at("Feature_10")[0], iTable.at("Feature_11")[0], iTable.at("Feature_12")[0], iTable.at("Feature_13")[0], iTable.at("Feature_14")[0], iTable.at("Feature_15")[0], iTable.at("Feature_16")[0], iTable.at("Feature_17")[0], iTable.at("Feature_18")[0], iTable.at("Feature_19")[0], iTable.at("Feature_20")[0], iTable.at("Feature_21")[0], iTable.at("Feature_22")[0], iTable.at("Feature_23")[0], iTable.at("Feature_24")[0], iTable.at("Feature_25")[0], iTable.at("Feature_26")[0], iTable.at("Feature_27")[0], iTable.at("Feature_28")[0], iTable.at("Feature_29")[0]); return lTable; } } // eof namespace XGB_Tree_0_15 std::vector<std::string> get_input_names(){ std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3", "Feature_4", "Feature_5", "Feature_6", "Feature_7", "Feature_8", "Feature_9", "Feature_10", "Feature_11", "Feature_12", "Feature_13", "Feature_14", "Feature_15", "Feature_16", "Feature_17", "Feature_18", "Feature_19", "Feature_20", "Feature_21", "Feature_22", "Feature_23", "Feature_24", "Feature_25", "Feature_26", "Feature_27", "Feature_28", "Feature_29" }; return lFeatures; } std::vector<std::string> get_output_names(){ std::vector<std::string> lOutputs = { "Score_0", "Score_1", "Proba_0", "Proba_1", "LogProba_0", "LogProba_1", "Decision", "DecisionProba" }; return lOutputs; } tTable compute_classification_scores(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29) { auto lClasses = get_classes(); std::vector<tTable> lTreeScores = { XGB_Tree_0_0::compute_classification_scores(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29), XGB_Tree_0_1::compute_classification_scores(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29), XGB_Tree_0_2::compute_classification_scores(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29), XGB_Tree_0_3::compute_classification_scores(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29), XGB_Tree_0_4::compute_classification_scores(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29), XGB_Tree_0_5::compute_classification_scores(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29), XGB_Tree_0_6::compute_classification_scores(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29), XGB_Tree_0_7::compute_classification_scores(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29), XGB_Tree_0_8::compute_classification_scores(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29), XGB_Tree_0_9::compute_classification_scores(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29), XGB_Tree_0_10::compute_classification_scores(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29), XGB_Tree_0_11::compute_classification_scores(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29), XGB_Tree_0_12::compute_classification_scores(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29), XGB_Tree_0_13::compute_classification_scores(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29), XGB_Tree_0_14::compute_classification_scores(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29), XGB_Tree_0_15::compute_classification_scores(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29) }; tTable lAggregatedTable = aggregate_xgb_scores(lTreeScores, {"Score"}); tTable lTable; lTable["Score"] = { std::any(), std::any() } ; lTable["Proba"] = { 1.0 - logistic(lAggregatedTable["Score"][0]), logistic(lAggregatedTable["Score"][0]) } ; int lBestClass = get_arg_max( lTable["Proba"] ); auto lDecision = lClasses[lBestClass]; lTable["Decision"] = { lDecision } ; lTable["DecisionProba"] = { lTable["Proba"][lBestClass] }; recompute_log_probas( lTable ); return lTable; } tTable compute_model_outputs_from_table( tTable const & iTable) { tTable lTable = compute_classification_scores(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0], iTable.at("Feature_4")[0], iTable.at("Feature_5")[0], iTable.at("Feature_6")[0], iTable.at("Feature_7")[0], iTable.at("Feature_8")[0], iTable.at("Feature_9")[0], iTable.at("Feature_10")[0], iTable.at("Feature_11")[0], iTable.at("Feature_12")[0], iTable.at("Feature_13")[0], iTable.at("Feature_14")[0], iTable.at("Feature_15")[0], iTable.at("Feature_16")[0], iTable.at("Feature_17")[0], iTable.at("Feature_18")[0], iTable.at("Feature_19")[0], iTable.at("Feature_20")[0], iTable.at("Feature_21")[0], iTable.at("Feature_22")[0], iTable.at("Feature_23")[0], iTable.at("Feature_24")[0], iTable.at("Feature_25")[0], iTable.at("Feature_26")[0], iTable.at("Feature_27")[0], iTable.at("Feature_28")[0], iTable.at("Feature_29")[0]); return lTable; } } // eof namespace int main() { score_csv_file("outputs/ml2cpp-demo/datasets/BreastCancer.csv"); return 0; }
78,227
35,865
#include<bits/stdc++.h> using namespace std; int main() { int num , atMost ; cin >> num >> atMost ; vector<double>ans(num , 0.0); for(int i = 0; i < num ; i++) { cin >> ans[i]; } sort(ans.begin(),ans.end()); double max_dist = 0.0; for(int i = 0 ; i < num-1 ; i++) { if(ans[i+1]-ans[i] > max_dist) max_dist = ans[i+1]-ans[i]; } max_dist = max(max_dist/2 , max(ans[0]-0 , atMost-ans[num-1])); cout << fixed << setprecision(10) << max_dist << endl; return 0; }
543
236
// ========================================================================== // // File : hwlib-pin.hpp // Part of : hwlib library for V1OOPC and V1IPAS // Copyright : wouter@voti.nl 2016 // // 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) // // ========================================================================== /// @file #ifndef HWLIB_PIN_H #define HWLIB_PIN_H #include "hwlib-wait.hpp" namespace hwlib { /// input pin interface // /// This class abstracts the interface for an input-only pin. class pin_in { public: /// read the pin // /// This function returns the level of the pin. /// When the pin level is high the value true is returned, /// when the pin level is low the value false is returned. virtual bool get() = 0; }; /// output pin interface // /// This class abstracts the interface for an output-only pin. class pin_out { public: /// write the pin // /// This function sets the level of the pin to /// the value v. A value of true makes the pin high, a value of /// false makes it low. virtual void set( bool v ) = 0; }; /// input/output pin interface // /// This class abstracts the interface for an input/output pin. class pin_in_out { public: /// set the direction of a pin to input. // /// Calling this function sets the pin identified by p to input. virtual void direction_set_input() = 0; /// read the pin // /// This function returns the level of the pin. /// When the pin level is high the value true is returned, /// when the pin level is low the value false is returned. /// /// Before calling this function the pin direction must have been /// set to input by calling direction_set_input(). virtual bool get() = 0; /// set the direction of a pin to output // /// Calling this function sets the pin identified by p to output. virtual void direction_set_output() = 0; /// write the pin // /// This function sets the level of the pin to /// the value v. A value of true makes the pin high, a value of /// false makes it low. /// /// Before calling this function the pin direction must have been /// set to output by calling direction_set_output(). virtual void set( bool x ) = 0; }; /// open-collector input/output pin interface // /// This class abstracts the interface for /// an open-collector input/output pin. class pin_oc { public: /// read the pin // /// This function returns the level of the pin. /// When the pin level is high the value true is returned, /// when the pin level is low the value false is returned. /// /// This function can be called after set( false ) has been called /// on the pin, but then the level will read low (false). /// Call set( true ) to let the line float /// (presumably pulled high by a pull-up resistor) /// to read the level put on the line by /// an external device. virtual bool get() = 0; /// write the pin // /// This function sets the level of the pin to /// the value v. A value of true makes the pin hihg-impedance /// (presumably pulled high by a pull-up resistor), /// a value of false makes it low. virtual void set( bool x ) = 0; }; /* class pin_oc_from_out { private: pin_out & pin; public: pin_oc_from_out( pin_out & pin ): pin{ pin } { } }; */ }; // namespace hwlib #endif // HWLIB_PIN_H
3,541
1,062
// Copyright Daan Zimmerman van Woesik 2019 - 2021. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) #include "hwlib.hpp" #include "mcbelib.hpp" int main( void ) { hwlib::wait_ms(1); namespace target = hwlib::target; //gyroscoop auto scl = target::pin_oc( target::pins::d21 ); auto sda = target::pin_oc( target::pins::d20 ); auto gyro_bus = hwlib::i2c_bus_bit_banged_scl_sda( scl, sda ); auto chip = mcbelib::gy521( gyro_bus, GYRO_ADDRESS, 1000 ); //communication auto masterPin_in = target::pin_in( target::pins::d28); auto masterPin_out = target::pin_out( target::pins::d30); auto masterState = target::pin_in( target::pins::d32); auto master = mcbelib::hc05( masterPin_in, masterPin_out, masterState ); //game auto scl_game = target::pin_oc( target::pins::d19 ); auto sda_game = target::pin_oc( target::pins::d18 ); auto start = target::pin_in( target::pins::d22 ); auto reset = target::pin_in( target::pins::d24 ); auto game_bus = hwlib::i2c_bus_bit_banged_scl_sda( scl_game, sda_game ); auto setup = hwlib::glcd_oled( game_bus, DISPLAY_ADDRESS ); auto game = mcbelib::snake( setup, start, reset, chip, master, true ); for (;;) { hwlib::cout << master.readData(); } }
1,408
578
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // //=============================================================================// #include "cbase.h" #include "hegrenade_projectile.h" #include "soundent.h" #include "cs_player.h" #include "KeyValues.h" #include "weapon_csbase.h" #define GRENADE_MODEL "models/weapons/w_eq_fraggrenade_thrown.mdl" LINK_ENTITY_TO_CLASS( hegrenade_projectile, CHEGrenadeProjectile ); PRECACHE_WEAPON_REGISTER( hegrenade_projectile ); CHEGrenadeProjectile* CHEGrenadeProjectile::Create( const Vector &position, const QAngle &angles, const Vector &velocity, const AngularImpulse &angVelocity, CBaseCombatCharacter *pOwner, float timer ) { CHEGrenadeProjectile *pGrenade = (CHEGrenadeProjectile*)CBaseEntity::Create( "hegrenade_projectile", position, angles, pOwner ); // Set the timer for 1 second less than requested. We're going to issue a SOUND_DANGER // one second before detonation. pGrenade->SetDetonateTimerLength( 1.5 ); pGrenade->SetAbsVelocity( velocity ); pGrenade->SetupInitialTransmittedGrenadeVelocity( velocity ); pGrenade->SetThrower( pOwner ); pGrenade->SetGravity( BaseClass::GetGrenadeGravity() ); pGrenade->SetFriction( BaseClass::GetGrenadeFriction() ); pGrenade->SetElasticity( BaseClass::GetGrenadeElasticity() ); pGrenade->m_flDamage = 100; pGrenade->m_DmgRadius = pGrenade->m_flDamage * 3.5f; pGrenade->ChangeTeam( pOwner->GetTeamNumber() ); pGrenade->ApplyLocalAngularVelocityImpulse( angVelocity ); // make NPCs afaid of it while in the air pGrenade->SetThink( &CHEGrenadeProjectile::DangerSoundThink ); pGrenade->SetNextThink( gpGlobals->curtime ); pGrenade->m_pWeaponInfo = GetWeaponInfo( WEAPON_HEGRENADE ); return pGrenade; } void CHEGrenadeProjectile::Spawn() { SetModel( GRENADE_MODEL ); BaseClass::Spawn(); } void CHEGrenadeProjectile::Precache() { PrecacheModel( GRENADE_MODEL ); PrecacheScriptSound( "HEGrenade.Bounce" ); BaseClass::Precache(); } void CHEGrenadeProjectile::BounceSound( void ) { EmitSound( "HEGrenade.Bounce" ); } void CHEGrenadeProjectile::Detonate() { BaseClass::Detonate(); // tell the bots an HE grenade has exploded CCSPlayer *player = ToCSPlayer(GetThrower()); if ( player ) { IGameEvent * event = gameeventmanager->CreateEvent( "hegrenade_detonate" ); if ( event ) { event->SetInt( "userid", player->GetUserID() ); event->SetFloat( "x", GetAbsOrigin().x ); event->SetFloat( "y", GetAbsOrigin().y ); event->SetFloat( "z", GetAbsOrigin().z ); gameeventmanager->FireEvent( event ); } } }
2,608
1,032
#include "UdQueuePair.h" void rdma::UdQueuePair::connect(const rdma::Address &) { connect(defaultPort); } void rdma::UdQueuePair::connect(uint8_t port, uint32_t packetSequenceNumber) { using Mod = ibv::queuepair::AttrMask; { ibv::queuepair::Attributes attr{}; attr.setQpState(ibv::queuepair::State::INIT); attr.setPkeyIndex(0); attr.setPortNum(port); attr.setQkey(0x22222222); // todo: bad magic constant qp->modify(attr, {Mod::STATE, Mod::PKEY_INDEX, Mod::PORT, Mod::QKEY}); } { // RTR ibv::queuepair::Attributes attr{}; attr.setQpState(ibv::queuepair::State::RTR); qp->modify(attr, {Mod::STATE}); } { // RTS ibv::queuepair::Attributes attr{}; attr.setQpState(ibv::queuepair::State::RTS); attr.setSqPsn(packetSequenceNumber); qp->modify(attr, {Mod::STATE, Mod::SQ_PSN}); } }
924
351
#include <fmt/format.h> #define CONDUIT_NO_LUA #define CONDUIT_NO_PYTHON #include <conduit/conduit.h> #include <conduit/function.h> #include <string> #include <iostream> #include <algorithm> #include <queue> #include <random> struct QueueEntry { int priority; conduit::Function<void()> event; friend bool operator <(const QueueEntry &lhs, const QueueEntry &rhs) { return lhs.priority < rhs.priority; } }; int main(int argc, char const *argv[]) { conduit::Registrar reg("reg", nullptr); // This example uses 2 channels to demonstrate how our queue can hold // channels of any signature. auto int_print = reg.lookup<void(int, int)>("int print channel"); auto float_print = reg.lookup<void(int, int, float)>("float print channel"); reg.lookup<void(int, int)>("int print channel").hook([] (int i, int priority) { fmt::print("{} was inserted with priority {}\n", i, priority); }); reg.lookup<void(int, int, float)>("float print channel").hook([] (int i, int priority, float value) { fmt::print("{} was inserted with priority {} and with float value {}\n", i, priority, value); }); // A priority queue of events. Each QueueEntry has a priority and a function // wrapper holding the actual work to perform. The function wrapper can hold // anything that can be called without arguments (QueueEntry::event is a // nullary type erased function adapter). std::priority_queue<QueueEntry> queue; // Get our random number generator ready std::random_device rd; std::mt19937 eng(rd()); std::uniform_int_distribution<> dist(0, 100); // Queue messages on either the int_print or float_print channels. // conduit::make_delayed pairs a callable (in this case our channel) with its // arguments and saves it for later. See below where we apply the arguments // to the channel to send a message on the channel. for (int i = 0; i < 10; ++i) { auto r = dist(eng); if (r & 1) { queue.push(QueueEntry{r, conduit::make_delayed(int_print, i, r)}); } else { queue.push(QueueEntry{r, conduit::make_delayed(float_print, i, r, static_cast<float>(i) / r)}); } } // Now that we have events in our priority_queue, execute them in priority // order. while (!queue.empty()) { queue.top().event(); queue.pop(); } }
2,417
752
#include <iostream> #include <SFML/Audio.hpp> #include "Spectrogram.hpp" #define OUTPUTPATH std::string("") int main(int argc, const char * argv[]) { sf::Clock Timer; SpectrographGen Generator(250,4096,2); Generator.loadFromFile("come alive.ogg"); sf::Image Gram=Generator.generateImage(); SpectrographDecode Decoder(250,44100,2,2); Decoder.loadFromImage(Gram); Decoder.saveToFile(OUTPUTPATH+"test.ogg"); std::cout<<Timer.getElapsedTime().asSeconds(); return 0; }
500
188
#include "AsyncTaskMsg.hpp" AsyncTaskMsg::AsyncTaskMsg(taskNames_t myTaskName) { _myTaskName = myTaskName; _taskId = static_cast<int>(myTaskName); } void AsyncTaskMsg::update(){ _ptrAsyncTask = &(tasksManager[_taskId]); taskNames_t taskFrom = _ptrAsyncTask->getMsgTaskFrom(); asyncMsg_t msg = _ptrAsyncTask->getMsgName(); int index = _ptrAsyncTask->getMsgIndex(); int value = _ptrAsyncTask->getMsgValue(); if (msg == AsyncMsg::WRITE_VAR) { _asyncValues.at(index) = value; } else if (msg == AsyncMsg::READ_VAR) { //Answer with specific message, and with the same index, and with the READ value tasksManager[(int)taskFrom].sendMessage( AsyncMsg::ANSWER_READ_VAR, (taskNames_t)_taskId, index, _asyncValues.at(index)); } else if (msg == AsyncMsg::ANSWER_READ_VAR) { _asyncValuesRead.at(index) = value; } } int AsyncTaskMsg::getLocalValue(int index) { return(_asyncValues.at(index)); } void AsyncTaskMsg::setLocalValue(int index, int value) { _asyncValues.at(index) = value; } int AsyncTaskMsg::getLastRemoteValue(int index) { return(_asyncValuesRead.at(index)); } void AsyncTaskMsg::readRemoteValue(taskNames_t taskName, int index) { tasksManager[(int)taskName].sendMessage(AsyncMsg::READ_VAR, _myTaskName, index, 0); } void AsyncTaskMsg::writeRemoteValue(taskNames_t taskName, int index, int value) { tasksManager[(int)taskName].sendMessage(AsyncMsg::WRITE_VAR, _myTaskName, index, value); } AsyncTaskMsg::~AsyncTaskMsg() { }
1,595
534
#include <iostream> using namespace std; int main() { int A, B; while (cin >> A >> B && A != 0) { int c = B - A; const int c1000 = c / 1000; c %= 1000; const int c500 = c / 500; c %= 500; cout << c/100 << ' ' << c500 << ' ' << c1000 << endl; } return 0; }
289
146
// Copyright (c) 2021 The worldwideweb Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <consensus/validation.h> #include <policy/packages.h> #include <primitives/transaction.h> #include <uint256.h> #include <util/hasher.h> #include <numeric> #include <unordered_set> bool CheckPackage(const Package& txns, PackageValidationState& state) { const unsigned int package_count = txns.size(); if (package_count > MAX_PACKAGE_COUNT) { return state.Invalid(PackageValidationResult::PCKG_POLICY, "package-too-many-transactions"); } const int64_t total_size = std::accumulate(txns.cbegin(), txns.cend(), 0, [](int64_t sum, const auto& tx) { return sum + GetVirtualTransactionSize(*tx); }); // If the package only contains 1 tx, it's better to report the policy violation on individual tx size. if (package_count > 1 && total_size > MAX_PACKAGE_SIZE * 1000) { return state.Invalid(PackageValidationResult::PCKG_POLICY, "package-too-large"); } // Require the package to be sorted in order of dependency, i.e. parents appear before children. // An unsorted package will fail anyway on missing-inputs, but it's better to quit earlier and // fail on something less ambiguous (missing-inputs could also be an orphan or trying to // spend nonexistent coins). std::unordered_set<uint256, SaltedTxidHasher> later_txids; std::transform(txns.cbegin(), txns.cend(), std::inserter(later_txids, later_txids.end()), [](const auto& tx) { return tx->GetHash(); }); for (const auto& tx : txns) { for (const auto& input : tx->vin) { if (later_txids.find(input.prevout.hash) != later_txids.end()) { // The parent is a subsequent transaction in the package. return state.Invalid(PackageValidationResult::PCKG_POLICY, "package-not-sorted"); } } later_txids.erase(tx->GetHash()); } // Don't allow any conflicting transactions, i.e. spending the same inputs, in a package. std::unordered_set<COutPoint, SaltedOutpointHasher> inputs_seen; for (const auto& tx : txns) { for (const auto& input : tx->vin) { if (inputs_seen.find(input.prevout) != inputs_seen.end()) { // This input is also present in another tx in the package. return state.Invalid(PackageValidationResult::PCKG_POLICY, "conflict-in-package"); } } // Batch-add all the inputs for a tx at a time. If we added them 1 at a time, we could // catch duplicate inputs within a single tx. This is a more severe, consensus error, // and we want to report that from CheckTransaction instead. std::transform(tx->vin.cbegin(), tx->vin.cend(), std::inserter(inputs_seen, inputs_seen.end()), [](const auto& input) { return input.prevout; }); } return true; }
3,051
936
// // Created by Alex Beccaro on 03/08/2021. // #include "problem151.hpp" #include "generics.hpp" #include <numeric> #include <vector> #include <unordered_map> #include <unordered_set> using std::vector; using std::unordered_map; using std::unordered_set; using generics::digits; using std::accumulate; namespace problems { double problem151::solve() { // states are represented as a number where each digit, in order, represents the quantity of A2, A3, A4 and A5 // sheets in the envelope unordered_map<uint32_t, double> p = {{1111, 1}}; vector<uint32_t> current = {1111}; unordered_set<uint32_t> next; for (uint32_t batch = 2; batch <= 16; batch++) { for (const auto& state : current) { vector<uint32_t> d = digits(state); uint32_t total = accumulate(d.begin(), d.end(), 0u); // total number of sheets in the envelope // each mask represents a possible format (A2, A3, A4 or A5) for (uint32_t mask = 1000; mask > 0; mask /= 10) { uint32_t n = state % (mask * 10) / mask; // number of sheets of the mask format if (n == 0) continue; // apply cuts to generate the new state and add it to the set for next batch uint32_t to_add = 0; for (uint32_t i = 1; i < mask; i *= 10) to_add += i; uint32_t new_state = state - mask + to_add; next.insert(new_state); // update probability of new state double p_next = p[state] * n / total; if (p.find(new_state) != p.end()) p[new_state] += p_next; else p.insert({new_state, p_next}); } } current.assign(next.begin(), next.end()); next.clear(); } return p[1000] + p[100] + p[10]; } }
2,045
659
#include<iostream> #include<string> #include<map> using namespace std; int main(){ int n; string s; map<string,int> ber; cin >> n; while(n--){ cin >> s; if(ber.find(s) == ber.end()) cout << "OK" << endl , ber[s]++; else{ s = s + to_string(ber[s]++); cout << s << endl; } } return 0; }
317
156
//===================================================================== // Copyright 2016 (c), Advanced Micro Devices, Inc. All rights reserved. // /// \author AMD Developer Tools Team /// \file osWrappersInitFunc.cpp /// //===================================================================== //------------------------------ osWrappersInitFunc.cpp ------------------------------ // Local: #include <AMDTOSWrappers/Include/osTransferableObjectCreator.h> #include <AMDTOSWrappers/Include/osTransferableObjectCreatorsManager.h> #include <AMDTOSWrappers/Include/osFilePath.h> #include <AMDTOSWrappers/Include/osDirectory.h> #include <AMDTOSWrappers/Include/osWrappersInitFunc.h> // --------------------------------------------------------------------------- // Name: apiClassesInitFunc // Description: Initialization function for the GROSWrappers library. // Return Val: bool - Success / failure. // Author: AMD Developer Tools Team // Date: 2/6/2004 // Implementation Notes: // Registeres all the GROSWrappers transferable objects in the transferable // objects creator manager. // --------------------------------------------------------------------------- bool osWrappersInitFunc() { // Verify that this function code is executed only once: static bool wasThisFunctionCalled = false; if (!wasThisFunctionCalled) { wasThisFunctionCalled = true; // Get the osTransferableObjectCreatorsManager single instance: osTransferableObjectCreatorsManager& theTransfetableObsCreatorsManager = osTransferableObjectCreatorsManager::instance(); // ----------- Register transferable objects creators ----------- osTransferableObjectCreator<osFilePath> osFilePathCreator; theTransfetableObsCreatorsManager.registerCreator(osFilePathCreator); osTransferableObjectCreator<osDirectory> osDirectoryCreator; theTransfetableObsCreatorsManager.registerCreator(osDirectoryCreator); } return true; }
2,000
531
// // Created by Lilith on 2020-05-28. // #pragma once #include <deque> #include <filesystem> #include <fstream> #include <iostream> #include <iterator> #include <set> #include <type_traits> #include "Array.hpp" #include "macros.hpp" #ifdef _WIN32 # ifndef WIN32_LEAN_AND_MEAN # define WIN32_LEAN_AND_MEAN # endif // WIN32_LEAN_AND_MEAN # include <Windows.h> #endif namespace dragon { template<typename T> inline typename std::enable_if<std::is_integral<T>::value, T>::type Align(T value, T align) { T v = value % align; if (v != 0) return value + align - v; return value; } inline Array<uint8_t> read_file(const std::filesystem::path &path) { #ifdef DRAGON_TOOLS DRAGON_LOG("Reading file " << path); #endif std::ifstream file(path, std::ios::binary | std::ios::in); auto size = (size_t) std::filesystem::file_size(path); Array<uint8_t> bytes(size, nullptr); file.seekg(0, std::ios::beg); file.read(reinterpret_cast<char *>(bytes.data()), (std::streamsize) size); file.close(); return bytes; } inline void write_file(const std::filesystem::path &path, const Array<uint8_t> &buffer) { if (buffer.empty()) return; #ifdef DRAGON_TOOLS if (std::filesystem::exists(path)) { DRAGON_ELOG("Overwriting file " << path); } else { DRAGON_LOG("Writing file " << path); } #endif std::ofstream file(path, std::ios::binary | std::ios::out | std::ios::trunc); file.write(reinterpret_cast<const char *>(buffer.data()), (std::streamsize) buffer.size()); file.flush(); file.close(); } inline void str_to_lower(std::string &str) { std::transform(str.begin(), str.end(), str.begin(), [](char c) { return std::tolower(c); }); } inline void str_to_upper(std::string &str) { std::transform(str.begin(), str.end(), str.begin(), [](char c) { return std::toupper(c); }); } inline void find_paths(const std::filesystem::path &path, std::deque<std::filesystem::path> &container, const std::set<std::string> &filters = {}, std::filesystem::directory_options options = {}) { if (!std::filesystem::exists(path)) { return; } if (std::filesystem::is_directory(path)) { for (const auto &entry : std::filesystem::recursive_directory_iterator(path, options)) { if (entry.is_directory()) { continue; } const auto &sub_path = entry.path(); auto ext = sub_path.extension(); if (!filters.empty()) { bool found = false; for (const auto &filter : filters) { if (ext == filter) { found = true; break; } } if (!found) { continue; } } container.emplace_back(sub_path); } } else { container.emplace_back(path); } } inline std::deque<std::filesystem::path> find_paths(std::deque<std::string> &paths, const std::set<std::string> &filters = {}, std::filesystem::directory_options options = {}) { std::deque<std::filesystem::path> container; for (const auto &path : paths) { find_paths(path, container, filters, options); } return container; } inline std::deque<std::filesystem::path> find_paths(std::deque<std::filesystem::path> &paths, const std::set<std::string> &filters = {}, std::filesystem::directory_options options = {}) { std::deque<std::filesystem::path> container; for (const auto &path : paths) { find_paths(path, container, filters, options); } return container; } } // namespace dragon
4,017
1,246
// Copyright (C) 2011 - 2014 David Reid. See included LICENCE. #ifndef GT_SceneStateStackStagingArea #define GT_SceneStateStackStagingArea #include "SceneStateStackRestoreCommands.hpp" #include "Serialization.hpp" namespace GT { class Scene; class SceneStateStackBranch; /// Class representing the staging area. class SceneStateStackStagingArea { public: /// Constructor. SceneStateStackStagingArea(SceneStateStackBranch &branch); /// Destructor. ~SceneStateStackStagingArea(); /// Retrieves a reference to the branch that owns this staging area. SceneStateStackBranch & GetBranch() { return this->branch; } const SceneStateStackBranch & GetBranch() const { return this->branch; } /// Retrieves a reference to the relevant scene. Scene & GetScene(); const Scene & GetScene() const; /// Stages an insert command of the given scene node. /// /// @param sceneNodeID [in] The ID of the scene node that was inserted. void StageInsert(uint64_t sceneNodeID); /// Stages a delete command of the given scene node. /// /// @param sceneNodeID [in] The ID of the scene node that was deleted. void StageDelete(uint64_t sceneNodeID); /// Stages an update command of the given scene node. /// /// @param sceneNodeID [in] The ID of the scene node that was updated. void StageUpdate(uint64_t sceneNodeID); /// Clears the staging area. void Clear(); /// Retrieves a reference to the insert commands. Vector<uint64_t> & GetInserts() { return this->inserts; } const Vector<uint64_t> & GetInserts() const { return this->inserts; } /// Retrieves a reference to the delete commands. Map<uint64_t, BasicSerializer*> & GetDeletes() { return this->deletes; } const Map<uint64_t, BasicSerializer*> & GetDeletes() const { return this->deletes; } /// Retrieves a reference to the update commands. Vector<uint64_t> & GetUpdates() { return this->updates; } const Vector<uint64_t> & GetUpdates() const { return this->updates; } /// Retrieves a reference to the hierarchy. Map<uint64_t, uint64_t> & GetHierarchy() { return this->hierarchy; } const Map<uint64_t, uint64_t> & GetHierarchy() const { return this->hierarchy; } /// Retrieves the set of commands to use to revert the scene from the changes in the staging area. /// /// @param commands [out] A reference to the object that will receive the restore commands. void GetRevertCommands(SceneStateStackRestoreCommands &commands); /// Retrieves a set of commands that can be used to put the scene into a state as currently defined by the staging area. /// /// @param commands [out] A reference to the object that will receive the restore commands. void GetRestoreCommands(SceneStateStackRestoreCommands &commands); ///////////////////////////////////////////////// // Serialization/Deserialization /// Serializes the state stack staging area. void Serialize(Serializer &serializer) const; /// Deserializes the state stack staging area. void Deserialize(Deserializer &deserializer); private: /// Adds the given scene node to the hierarchy. /// /// @param sceneNodeID [in] The ID of the scene node that is being added to the hierarchy. /// /// @remarks /// This does nothing if the scene node does not have a parent. void AddToHierarchy(uint64_t sceneNodeID); /// Removes the given scene node from the hierarchy. /// /// @param sceneNodeID [in] The ID of the scene node that is being removed from the hierarchy. void RemoveFromHierarchy(uint64_t sceneNodeID); /// Retrieves the ID of the parent node from the hierarchy, or 0 if it does not have a parent. /// /// @param childSceneNodeID [in] The ID of the scene node whose parent ID is being retrieved. uint64_t GetParentSceneNodeIDFromHierarchy(uint64_t childSceneNodeID) const; private: /// The branch that owns this staging area. SceneStateStackBranch &branch; /// The list of scene node ID's of newly inserted scene nodes in the staging area. Vector<uint64_t> inserts; /// The list of scene node ID's of newly deleted scene nodes in the staging area. We need to keep track of the serialized data /// because the scene will want to delete the node, after which point we won't be able to retrieve the data. Map<uint64_t, BasicSerializer*> deletes; /// The list of scene node ID's of newly updated scene nodes in the staging area. Vector<uint64_t> updates; /// The hierarchy of the nodes containined in the staging area. The key is the child node ID and the value is the parent node ID. Map<uint64_t, uint64_t> hierarchy; }; } #endif
5,163
1,429
/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #include <cmath> #include <QMessageBox> #include <gnuradio/qtgui/histogramdisplayform.h> #include <iostream> HistogramDisplayForm::HistogramDisplayForm(int nplots, QWidget* parent) : DisplayForm(nplots, parent) { d_semilogx = false; d_semilogy = false; d_int_validator = new QIntValidator(this); d_int_validator->setBottom(0); d_layout = new QGridLayout(this); d_display_plot = new HistogramDisplayPlot(nplots, this); d_layout->addWidget(d_display_plot, 0, 0); setLayout(d_layout); d_nptsmenu = new NPointsMenu(this); d_menu->addAction(d_nptsmenu); connect(d_nptsmenu, SIGNAL(whichTrigger(int)), this, SLOT(setNPoints(const int))); d_nbinsmenu = new NPointsMenu(this); d_nbinsmenu->setText("Number of Bins"); d_menu->addAction(d_nbinsmenu); connect(d_nbinsmenu, SIGNAL(whichTrigger(int)), this, SLOT(setNumBins(const int))); d_accum_act = new QAction("Accumulate", this); d_accum_act->setCheckable(true); d_menu->addAction(d_accum_act); connect(d_accum_act, SIGNAL(triggered(bool)), this, SLOT(setAccumulate(bool))); d_menu->removeAction(d_autoscale_act); d_autoscale_act->setText(tr("Auto Scale Y")); d_autoscale_act->setStatusTip(tr("Autoscale Y-axis")); d_autoscale_act->setCheckable(true); d_autoscale_act->setChecked(true); d_autoscale_state = true; d_menu->addAction(d_autoscale_act); d_autoscalex_act = new QAction("Auto Scale X", this); d_autoscalex_act->setStatusTip(tr("Update X-axis scale")); d_autoscalex_act->setCheckable(false); connect(d_autoscalex_act, SIGNAL(changed()), this, SLOT(autoScaleX())); d_autoscalex_state = false; d_menu->addAction(d_autoscalex_act); // d_semilogxmenu = new QAction("Semilog X", this); // d_semilogxmenu->setCheckable(true); // d_menu->addAction(d_semilogxmenu); // connect(d_semilogxmenu, SIGNAL(triggered(bool)), // this, SLOT(setSemilogx(bool))); // // d_semilogymenu = new QAction("Semilog Y", this); // d_semilogymenu->setCheckable(true); // d_menu->addAction(d_semilogymenu); // connect(d_semilogymenu, SIGNAL(triggered(bool)), // this, SLOT(setSemilogy(bool))); Reset(); connect(d_display_plot, SIGNAL(plotPointSelected(const QPointF)), this, SLOT(onPlotPointSelected(const QPointF))); } HistogramDisplayForm::~HistogramDisplayForm() { // Qt deletes children when parent is deleted // Don't worry about deleting Display Plots - they are deleted when parents are deleted delete d_int_validator; } HistogramDisplayPlot* HistogramDisplayForm::getPlot() { return ((HistogramDisplayPlot*)d_display_plot); } void HistogramDisplayForm::newData(const QEvent* updateEvent) { HistogramUpdateEvent *hevent = (HistogramUpdateEvent*)updateEvent; const std::vector<double*> dataPoints = hevent->getDataPoints(); const uint64_t numDataPoints = hevent->getNumDataPoints(); getPlot()->plotNewData(dataPoints, numDataPoints, d_update_time); } void HistogramDisplayForm::customEvent(QEvent * e) { if(e->type() == HistogramUpdateEvent::Type()) { newData(e); } else if(e->type() == HistogramSetAccumulator::Type()) { bool en = ((HistogramSetAccumulator*)e)->getAccumulator(); setAccumulate(en); } else if(e->type() == HistogramClearEvent::Type()) { getPlot()->clear(); } } void HistogramDisplayForm::setYaxis(double min, double max) { getPlot()->setYaxis(min, max); } void HistogramDisplayForm::setXaxis(double min, double max) { getPlot()->setXaxis(min, max); } int HistogramDisplayForm::getNPoints() const { return d_npoints; } void HistogramDisplayForm::setNPoints(const int npoints) { d_npoints = npoints; d_nptsmenu->setDiagText(npoints); } void HistogramDisplayForm::autoScale(bool en) { d_autoscale_state = en; d_autoscale_act->setChecked(en); getPlot()->setAutoScale(d_autoscale_state); getPlot()->replot(); } void HistogramDisplayForm::autoScaleX() { getPlot()->setAutoScaleX(); getPlot()->replot(); } void HistogramDisplayForm::setSemilogx(bool en) { d_semilogx = en; d_semilogxmenu->setChecked(en); getPlot()->setSemilogx(d_semilogx); getPlot()->replot(); } void HistogramDisplayForm::setSemilogy(bool en) { d_semilogy = en; d_semilogymenu->setChecked(en); getPlot()->setSemilogy(d_semilogy); getPlot()->replot(); } void HistogramDisplayForm::setNumBins(const int bins) { getPlot()->setNumBins(bins); getPlot()->replot(); d_nbinsmenu->setDiagText(bins); } void HistogramDisplayForm::setAccumulate(bool en) { // Turn on y-axis autoscaling when turning accumulate on. if(en) { autoScale(true); } d_accum_act->setChecked(en); getPlot()->setAccumulate(en); getPlot()->replot(); } bool HistogramDisplayForm::getAccumulate() { return getPlot()->getAccumulate(); }
5,563
2,081
/** ****************************************************************************** * This file is part of the TouchGFX 4.13.0 distribution. * * <h2><center>&copy; Copyright (c) 2019 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** */ #ifndef OUTLINE_HPP #define OUTLINE_HPP #include <touchgfx/canvas_widget_renderer/Cell.hpp> namespace touchgfx { /** * @class Outline Outline.hpp touchgfx/canvas_widget_renderer/Outline.hpp * * @brief An internal class that implements the main rasterization algorithm. * * An internal class that implements the main rasterization algorithm. Used in the * Rasterizer. Should not be used direcly. */ class Outline { public: /** * @typedef unsigned int OutlineFlags_t * * @brief Defines an alias representing the outline flags. * * Defines an alias representing the outline flags. */ typedef unsigned int OutlineFlags_t; static const OutlineFlags_t OUTLINE_NOT_CLOSED = 1U; ///< If this bit is set in flags, the current Outline has not yet been closed. Used for automatic closing an Outline before rendering the Outline. static const OutlineFlags_t OUTLINE_SORT_REQUIRED = 2U; ///< If this bit is set in flags, Cell objects have been added to the Outline requiring the Cell list needs to be sorted. /** * @fn Outline::Outline(); * * @brief Default constructor. * * Default constructor. */ Outline(); /** * @fn Outline::~Outline(); * * @brief Destructor. * * Destructor. */ virtual ~Outline(); /** * @fn void Outline::reset(); * * @brief Resets this object. * * Resets this object. This implies removing the current Cell objects and preparing * for a new Outline. */ void reset(); /** * @fn void Outline::moveTo(int x, int y); * * @brief Move a virtual pen to the specified coordinate. * * Move a virtual pen to the specified coordinate. * * @param x The x coordinate. * @param y The y coordinate. */ void moveTo(int x, int y); /** * @fn void Outline::lineTo(int x, int y); * * @brief Create a line from the current virtual pen coordinate to the given coordinate * creating an Outline. * * Create a line from the current virtual pen coordinate to the given coordinate * creating an Outline. * * @param x The x coordinate. * @param y The y coordinate. */ void lineTo(int x, int y); /** * @fn unsigned Outline::getNumCells() const * * @brief Gets number cells registered in the current drawn path for the Outline. * * Gets number cells registered in the current drawn path for the Outline. * * @return The number of cells. */ unsigned getNumCells() const { return numCells; } /** * @fn const Cell* Outline::getCells(); * * @brief Gets a pointer to the the Cell objects in the Outline. * * Gets a pointer to the the Cell objects in the Outline. If the Outline is not * closed, it is closed. If the Outline is unsorted, it will be quick sorted first. * * @return A pointer to the sorted list of Cell objects in the Outline. */ const Cell* getCells(); /** * @fn void Outline::setMaxRenderY(int y) * * @brief Sets maximum render y coordinate. * * Sets maximum render y coordinate. This is used to avoid registering any Cell that * has a y coordinate less than zero of higher than the given y. * * @param y The max y coordinate to render for the Outline. */ void setMaxRenderY(int y) { maxRenderY = y; } /** * @fn bool Outline::wasOutlineTooComplex() * * @brief Determines if there was enough memory to register the entire outline. * * Determines if there was enough memory to register the entire outline, of if the * outline was too complex. * * @return false if the buffer for Outline Cell objects was too small. */ bool wasOutlineTooComplex() { return outlineTooComplex; } private: /** * @fn void Outline::setCurCell(int x, int y); * * @brief Sets coordinate of the current Cell. * * Sets coordinate of the current Cell. * * @param x The x coordinate. * @param y The y coordinate. */ void setCurCell(int x, int y); /** * @fn void Outline::addCurCell(); * * @brief Adds current cell to the Outline. * * Adds current cell to the Outline. */ void addCurCell(); /** * @fn void Outline::sortCells(); * * @brief Sort cells in the Outline. * * Sort cells in the Outline. */ void sortCells(); /** * @fn void Outline::renderScanline(int ey, int x1, int y1, int x2, int y2); * * @brief Render the scanline in the special case where the line is on the same scanline. * * Render the scanline in the special case where the line is on the same scanline, * though it might not be 100% horizontal as the fraction of the y endpoints might * differ making the line tilt ever so slightly. * * @param ey The entire part of the from/to y coordinate (same for both from y and to y as it * is a horizontal scanline). * @param x1 The from x coordinate in poly format. * @param y1 The from y coordinate fraction part in poly format. * @param x2 The to x coordinate in poly format. * @param y2 The to y coordinate fraction part in poly format. */ void renderScanline(int ey, int x1, int y1, int x2, int y2); /** * @fn void Outline::renderLine(int x1, int y1, int x2, int y2); * * @brief Render the line. * * Render the line. This is the general case which handles all cases regardless of * the position of the from coordinate and the to coordinate. * * @param x1 The from x coordinate in poly format. * @param y1 The from y coordinate in poly format. * @param x2 The to x coordinate in poly format. * @param y2 The to y coordinate in poly format. */ void renderLine(int x1, int y1, int x2, int y2); /** * @fn static void Outline::qsortCells(Cell* const start, unsigned num); * * @brief Quick sort Outline cells. * * Quick sort Outline cells. * * @param [in] start The first Cell object in the Cell array to sort. * @param num Number of Cell objects to sort. */ static void qsortCells(Cell* const start, unsigned num); private: unsigned maxCells; unsigned numCells; Cell* cells; Cell* curCellPtr; Cell curCell; int curX; int curY; int closeX; int closeY; int minX; int minY; int maxX; int maxY; unsigned int flags; int maxRenderY; bool outlineTooComplex; #ifdef SIMULATOR unsigned numCellsMissing; unsigned numCellsUsed; #endif }; } // namespace touchgfx #endif // OUTLINE_HPP
7,756
2,272
// Copyright (c) 2020-2022 Daniel Frey and Dr. Colin Hirsch // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt) #ifndef TAO_PQ_PARAMETER_TRAITS_AGGREGATE_HPP #define TAO_PQ_PARAMETER_TRAITS_AGGREGATE_HPP #include <tao/pq/internal/aggregate.hpp> #include <tao/pq/is_aggregate.hpp> #include <tao/pq/parameter_traits.hpp> namespace tao::pq { namespace internal { template< typename T > struct parameter_tie_aggregate { using result_t = decltype( internal::tie_aggregate( std::declval< const T& >() ) ); const result_t result; explicit parameter_tie_aggregate( const T& t ) noexcept : result( internal::tie_aggregate( t ) ) {} }; } // namespace internal template< typename T > struct parameter_traits< T, std::enable_if_t< is_aggregate_parameter< T > > > : private internal::parameter_tie_aggregate< T >, public parameter_traits< typename internal::parameter_tie_aggregate< T >::result_t > { using typename internal::parameter_tie_aggregate< T >::result_t; explicit parameter_traits( const T& t ) noexcept( noexcept( internal::parameter_tie_aggregate< T >( t ), parameter_traits< result_t >( std::declval< result_t >() ) ) ) : internal::parameter_tie_aggregate< T >( t ), parameter_traits< result_t >( this->result ) {} }; } // namespace tao::pq #endif
1,573
542
#include "BMA250.h" #include <inttypes.h> #include "Arduino.h" #include <Wire.h> BMA250::BMA250() { } int BMA250::begin(uint8_t range, uint8_t bw) { //Detect address I2Caddress = BMA250_I2CADDR; Wire.beginTransmission(I2Caddress); if (Wire.endTransmission()) { I2Caddress++; Wire.beginTransmission(I2Caddress); if (Wire.endTransmission()) { I2Caddress = 0; return -1; } } //Setup the range measurement setting Wire.beginTransmission(I2Caddress); Wire.write(0x0F); Wire.write(range); Wire.endTransmission(); //Setup the bandwidth Wire.beginTransmission(I2Caddress); Wire.write(0x10); Wire.write(bw); Wire.endTransmission(); return 0; } void BMA250::read() { //Set register index Wire.beginTransmission(I2Caddress); Wire.write(0x02); Wire.endTransmission(); //Request seven data bytes Wire.requestFrom(I2Caddress, 7); //Receive acceleration measurements as 16 bit integers X = (int16_t)Wire.read(); X |= (int16_t)Wire.read() << 8; Y = (int16_t)Wire.read(); Y |= (int16_t)Wire.read() << 8; Z = (int16_t)Wire.read(); Z |= (int16_t)Wire.read() << 8; //Only use the 10 significant bits X >>= 6; Y >>= 6; Z >>= 6; //Receive temperature measurement rawTemp = Wire.read(); tempC = rawTemp/2 + 23; }
1,290
566
/***************************************************************************** * * * OpenNI 2.x Alpha * * Copyright (C) 2012 PrimeSense Ltd. * * * * This file is part of OpenNI. * * * * 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. * * * *****************************************************************************/ //--------------------------------------------------------------------------- // Includes //--------------------------------------------------------------------------- #include "XnAudioStream.h" #include <XnOS.h> //--------------------------------------------------------------------------- // Defines //--------------------------------------------------------------------------- #define XN_AUDIO_STREAM_BUFFER_SIZE_IN_SECONDS 1.5 //--------------------------------------------------------------------------- // Code //--------------------------------------------------------------------------- XnAudioStream::XnAudioStream(const XnChar* csName, XnUInt32 nMaxNumberOfChannels) : XnStreamingStream(XN_STREAM_TYPE_AUDIO, csName), m_SampleRate(XN_STREAM_PROPERTY_SAMPLE_RATE, "SampleRate", XN_SAMPLE_RATE_48K), m_NumberOfChannels(XN_STREAM_PROPERTY_NUMBER_OF_CHANNELS, "NumChannels", 2), m_nMaxNumberOfChannels(nMaxNumberOfChannels) { } XnStatus XnAudioStream::Init() { XnStatus nRetVal = XN_STATUS_OK; // init base nRetVal = XnStreamingStream::Init(); XN_IS_STATUS_OK(nRetVal); m_SampleRate.UpdateSetCallback(SetSampleRateCallback, this); m_NumberOfChannels.UpdateSetCallback(SetNumberOfChannelsCallback, this); XN_VALIDATE_ADD_PROPERTIES(this, &m_SampleRate, &m_NumberOfChannels); // required size nRetVal = RegisterRequiredSizeProperty(&m_SampleRate); XN_IS_STATUS_OK(nRetVal); return (XN_STATUS_OK); } XnStatus XnAudioStream::SetSampleRate(XnSampleRate nSampleRate) { XnStatus nRetVal = XN_STATUS_OK; nRetVal = m_SampleRate.UnsafeUpdateValue(nSampleRate); XN_IS_STATUS_OK(nRetVal); return (XN_STATUS_OK); } XnStatus XnAudioStream::SetNumberOfChannels(XnUInt32 nNumberOfChannels) { XnStatus nRetVal = XN_STATUS_OK; nRetVal = m_NumberOfChannels.UnsafeUpdateValue(nNumberOfChannels); XN_IS_STATUS_OK(nRetVal); return (XN_STATUS_OK); } XnStatus XnAudioStream::CalcRequiredSize(XnUInt32* pnRequiredSize) const { XnUInt32 nSampleSize = 2 * m_nMaxNumberOfChannels; // 16-bit per channel (2 bytes) XnUInt32 nSamples = (XnUInt32)(GetSampleRate() * XN_AUDIO_STREAM_BUFFER_SIZE_IN_SECONDS); *pnRequiredSize = nSamples * nSampleSize; return (XN_STATUS_OK); } XnStatus XnAudioStream::SetSampleRateCallback(XnActualIntProperty* /*pSender*/, XnUInt64 nValue, void* pCookie) { XnAudioStream* pStream = (XnAudioStream*)pCookie; return pStream->SetSampleRate((XnSampleRate)nValue); } XnStatus XnAudioStream::SetNumberOfChannelsCallback(XnActualIntProperty* /*pSender*/, XnUInt64 nValue, void* pCookie) { XnAudioStream* pStream = (XnAudioStream*)pCookie; return pStream->SetNumberOfChannels((XnUInt32)nValue); }
4,230
1,269
/** * MaNGOS is a full featured server for World of Warcraft, supporting * the following clients: 1.12.x, 2.4.3, 3.3.5a, 4.3.4a and 5.4.8 * * Copyright (C) 2005-2016 MaNGOS project <https://getmangos.eu> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * World of Warcraft, and all World of Warcraft or Warcraft art, images, * and lore are copyrighted by Blizzard Entertainment, Inc. */ #include "Corpse.h" #include "Player.h" #include "UpdateMask.h" #include "ObjectAccessor.h" #include "ObjectGuid.h" #include "Database/DatabaseEnv.h" #include "Opcodes.h" #include "GossipDef.h" #include "World.h" #include "ObjectMgr.h" Corpse::Corpse(CorpseType type) : WorldObject(), loot(this), lootRecipient(NULL), lootForBody(false) { m_objectType |= TYPEMASK_CORPSE; m_objectTypeId = TYPEID_CORPSE; // 2.3.2 - 0x58 m_updateFlag = (UPDATEFLAG_LOWGUID | UPDATEFLAG_HIGHGUID | UPDATEFLAG_HAS_POSITION); m_valuesCount = CORPSE_END; m_type = type; m_time = time(NULL); } Corpse::~Corpse() { } void Corpse::AddToWorld() { ///- Register the corpse for guid lookup if (!IsInWorld()) { sObjectAccessor.AddObject(this); } Object::AddToWorld(); } void Corpse::RemoveFromWorld() { ///- Remove the corpse from the accessor if (IsInWorld()) { sObjectAccessor.RemoveObject(this); } Object::RemoveFromWorld(); } bool Corpse::Create(uint32 guidlow) { Object::_Create(guidlow, 0, HIGHGUID_CORPSE); return true; } bool Corpse::Create(uint32 guidlow, Player* owner) { MANGOS_ASSERT(owner); WorldObject::_Create(guidlow, HIGHGUID_CORPSE); Relocate(owner->GetPositionX(), owner->GetPositionY(), owner->GetPositionZ(), owner->GetOrientation()); // we need to assign owner's map for corpse // in other way we will get a crash in Corpse::SaveToDB() SetMap(owner->GetMap()); if (!IsPositionValid()) { sLog.outError("Corpse (guidlow %d, owner %s) not created. Suggested coordinates isn't valid (X: %f Y: %f)", guidlow, owner->GetName(), owner->GetPositionX(), owner->GetPositionY()); return false; } SetObjectScale(DEFAULT_OBJECT_SCALE); SetFloatValue(CORPSE_FIELD_POS_X, GetPositionX()); SetFloatValue(CORPSE_FIELD_POS_Y, GetPositionY()); SetFloatValue(CORPSE_FIELD_POS_Z, GetPositionZ()); SetFloatValue(CORPSE_FIELD_FACING, GetOrientation()); SetGuidValue(CORPSE_FIELD_OWNER, owner->GetObjectGuid()); m_grid = MaNGOS::ComputeGridPair(GetPositionX(), GetPositionY()); return true; } void Corpse::SaveToDB() { // bones should not be saved to DB (would be deleted on startup anyway) MANGOS_ASSERT(GetType() != CORPSE_BONES); // prevent DB data inconsistence problems and duplicates CharacterDatabase.BeginTransaction(); DeleteFromDB(); std::ostringstream ss; ss << "INSERT INTO corpse (guid,player,position_x,position_y,position_z,orientation,map,time,corpse_type,instance) VALUES (" << GetGUIDLow() << ", " << GetOwnerGuid().GetCounter() << ", " << GetPositionX() << ", " << GetPositionY() << ", " << GetPositionZ() << ", " << GetOrientation() << ", " << GetMapId() << ", " << uint64(m_time) << ", " << uint32(GetType()) << ", " << int(GetInstanceId()) << ")"; CharacterDatabase.Execute(ss.str().c_str()); CharacterDatabase.CommitTransaction(); } void Corpse::DeleteBonesFromWorld() { MANGOS_ASSERT(GetType() == CORPSE_BONES); Corpse* corpse = GetMap()->GetCorpse(GetObjectGuid()); if (!corpse) { sLog.outError("Bones %u not found in world.", GetGUIDLow()); return; } AddObjectToRemoveList(); } void Corpse::DeleteFromDB() { // bones should not be saved to DB (would be deleted on startup anyway) MANGOS_ASSERT(GetType() != CORPSE_BONES); // all corpses (not bones) static SqlStatementID id; SqlStatement stmt = CharacterDatabase.CreateStatement(id, "DELETE FROM corpse WHERE player = ? AND corpse_type <> '0'"); stmt.PExecute(GetOwnerGuid().GetCounter()); } bool Corpse::LoadFromDB(uint32 lowguid, Field* fields) { //// 0 1 2 3 4 5 6 // QueryResult *result = CharacterDatabase.Query("SELECT corpse.guid, player, corpse.position_x, corpse.position_y, corpse.position_z, corpse.orientation, corpse.map," //// 7 8 9 10 11 12 13 14 15 16 17 // "time, corpse_type, instance, gender, race, class, playerBytes, playerBytes2, equipmentCache, guildId, playerFlags FROM corpse" uint32 playerLowGuid = fields[1].GetUInt32(); float positionX = fields[2].GetFloat(); float positionY = fields[3].GetFloat(); float positionZ = fields[4].GetFloat(); float orientation = fields[5].GetFloat(); uint32 mapid = fields[6].GetUInt32(); Object::_Create(lowguid, 0, HIGHGUID_CORPSE); m_time = time_t(fields[7].GetUInt64()); m_type = CorpseType(fields[8].GetUInt32()); if (m_type >= MAX_CORPSE_TYPE) { sLog.outError("%s Owner %s have wrong corpse type (%i), not load.", GetGuidStr().c_str(), GetOwnerGuid().GetString().c_str(), m_type); return false; } uint32 instanceid = fields[9].GetUInt32(); uint8 gender = fields[10].GetUInt8(); uint8 race = fields[11].GetUInt8(); uint8 _class = fields[12].GetUInt8(); uint32 playerBytes = fields[13].GetUInt32(); uint32 playerBytes2 = fields[14].GetUInt32(); uint32 guildId = fields[16].GetUInt32(); uint32 playerFlags = fields[17].GetUInt32(); ObjectGuid guid = ObjectGuid(HIGHGUID_CORPSE, lowguid); ObjectGuid playerGuid = ObjectGuid(HIGHGUID_PLAYER, playerLowGuid); // overwrite possible wrong/corrupted guid SetGuidValue(OBJECT_FIELD_GUID, guid); SetGuidValue(CORPSE_FIELD_OWNER, playerGuid); SetObjectScale(DEFAULT_OBJECT_SCALE); PlayerInfo const* info = sObjectMgr.GetPlayerInfo(race, _class); if (!info) { sLog.outError("Player %u has incorrect race/class pair.", GetGUIDLow()); return false; } SetUInt32Value(CORPSE_FIELD_DISPLAY_ID, gender == GENDER_FEMALE ? info->displayId_f : info->displayId_m); // Load equipment Tokens data = StrSplit(fields[15].GetCppString(), " "); for (uint8 slot = 0; slot < EQUIPMENT_SLOT_END; ++slot) { uint32 visualbase = slot * 2; uint32 item_id = GetUInt32ValueFromArray(data, visualbase); const ItemPrototype* proto = ObjectMgr::GetItemPrototype(item_id); if (!proto) { SetUInt32Value(CORPSE_FIELD_ITEM + slot, 0); continue; } SetUInt32Value(CORPSE_FIELD_ITEM + slot, proto->DisplayInfoID | (proto->InventoryType << 24)); } uint8 skin = (uint8)(playerBytes); uint8 face = (uint8)(playerBytes >> 8); uint8 hairstyle = (uint8)(playerBytes >> 16); uint8 haircolor = (uint8)(playerBytes >> 24); uint8 facialhair = (uint8)(playerBytes2); SetUInt32Value(CORPSE_FIELD_BYTES_1, ((0x00) | (race << 8) | (gender << 16) | (skin << 24))); SetUInt32Value(CORPSE_FIELD_BYTES_2, ((face) | (hairstyle << 8) | (haircolor << 16) | (facialhair << 24))); SetUInt32Value(CORPSE_FIELD_GUILD, guildId); uint32 flags = CORPSE_FLAG_UNK2; if (playerFlags & PLAYER_FLAGS_HIDE_HELM) { flags |= CORPSE_FLAG_HIDE_HELM; } if (playerFlags & PLAYER_FLAGS_HIDE_CLOAK) { flags |= CORPSE_FLAG_HIDE_CLOAK; } SetUInt32Value(CORPSE_FIELD_FLAGS, flags); // no need to mark corpse as lootable, because corpses are not saved in battle grounds // place SetLocationInstanceId(instanceid); SetLocationMapId(mapid); Relocate(positionX, positionY, positionZ, orientation); if (!IsPositionValid()) { sLog.outError("%s Owner %s not created. Suggested coordinates isn't valid (X: %f Y: %f)", GetGuidStr().c_str(), GetOwnerGuid().GetString().c_str(), GetPositionX(), GetPositionY()); return false; } m_grid = MaNGOS::ComputeGridPair(GetPositionX(), GetPositionY()); return true; } bool Corpse::IsVisibleForInState(Player const* u, WorldObject const* viewPoint, bool inVisibleList) const { return IsInWorld() && u->IsInWorld() && IsWithinDistInMap(viewPoint, GetMap()->GetVisibilityDistance() + (inVisibleList ? World::GetVisibleObjectGreyDistance() : 0.0f), false); } bool Corpse::IsHostileTo(Unit const* unit) const { if (Player* owner = sObjectMgr.GetPlayer(GetOwnerGuid())) { return owner->IsHostileTo(unit); } else { return false; } } bool Corpse::IsFriendlyTo(Unit const* unit) const { if (Player* owner = sObjectMgr.GetPlayer(GetOwnerGuid())) { return owner->IsFriendlyTo(unit); } else { return true; } } bool Corpse::IsExpired(time_t t) const { if (m_type == CORPSE_BONES) { return m_time < t - 60 * MINUTE; } else { return m_time < t - 3 * DAY; } }
9,905
3,495
//<snippet1> // Sample for String::Equals(Object) // String::Equals(String) // String::Equals(String, String) using namespace System; using namespace System::Text; int main() { StringBuilder^ sb = gcnew StringBuilder( "abcd" ); String^ str1 = "abcd"; String^ str2 = nullptr; Object^ o2 = nullptr; Console::WriteLine(); Console::WriteLine( " * The value of String str1 is '{0}'.", str1 ); Console::WriteLine( " * The value of StringBuilder sb is '{0}'.", sb ); Console::WriteLine(); Console::WriteLine( "1a) String::Equals(Object). Object is a StringBuilder, not a String." ); Console::WriteLine( " Is str1 equal to sb?: {0}", str1->Equals( sb ) ); Console::WriteLine(); Console::WriteLine( "1b) String::Equals(Object). Object is a String." ); str2 = sb->ToString(); o2 = str2; Console::WriteLine( " * The value of Object o2 is '{0}'.", o2 ); Console::WriteLine( " Is str1 equal to o2?: {0}", str1->Equals( o2 ) ); Console::WriteLine(); Console::WriteLine( " 2) String::Equals(String)" ); Console::WriteLine( " * The value of String str2 is '{0}'.", str2 ); Console::WriteLine( " Is str1 equal to str2?: {0}", str1->Equals( str2 ) ); Console::WriteLine(); Console::WriteLine( " 3) String::Equals(String, String)" ); Console::WriteLine( " Is str1 equal to str2?: {0}", String::Equals( str1, str2 ) ); } /* This example produces the following results: * The value of String str1 is 'abcd'. * The value of StringBuilder sb is 'abcd'. 1a) String::Equals(Object). Object is a StringBuilder, not a String. Is str1 equal to sb?: False 1b) String::Equals(Object). Object is a String. * The value of Object o2 is 'abcd'. Is str1 equal to o2?: True 2) String::Equals(String) * The value of String str2 is 'abcd'. Is str1 equal to str2?: True 3) String::Equals(String, String) Is str1 equal to str2?: True */ //</snippet1>
2,006
655
/* +------------------------------------------------------------------------+ | Mobile Robot Programming Toolkit (MRPT) | | https://www.mrpt.org/ | | | | Copyright (c) 2005-2019, Individual contributors, see AUTHORS file | | See: https://www.mrpt.org/Authors - All rights reserved. | | Released under BSD License. See: https://www.mrpt.org/License | +------------------------------------------------------------------------+ */ #include <iostream> #include "vision-precomp.h" // Precompiled headers //#include <mrpt/math/types_math.h> // Eigen must be included first via MRPT to // enable the plugin system #include <Eigen/Dense> #include <Eigen/SVD> #include <Eigen/StdVector> #include "lhm.h" using namespace mrpt::vision::pnp; lhm::lhm( Eigen::MatrixXd obj_pts_, Eigen::MatrixXd img_pts_, Eigen::MatrixXd cam_, int n0) : F(n0) { obj_pts = obj_pts_; img_pts = img_pts_; cam_intrinsic = cam_; n = n0; // Store obj_pts as 3XN and img_projections as 2XN matrices P = obj_pts.transpose(); Q = Eigen::MatrixXd::Ones(3, n); Q = img_pts.transpose(); t.setZero(); } void lhm::estimate_t() { Eigen::Vector3d sum_; sum_.setZero(); for (int i = 0; i < n; i++) sum_ += F[i] * R * P.col(i); t = G * sum_; } void lhm::xform() { for (int i = 0; i < n; i++) Q.col(i) = R * P.col(i) + t; } Eigen::Matrix4d lhm::qMatQ(Eigen::VectorXd q) { Eigen::Matrix4d Q_(4, 4); Q_ << q(0), -q(1), -q(2), -q(3), q(1), q(0), -q(3), q(2), q(2), q(3), q(0), -q(1), q(3), -q(2), q(1), q(0); return Q_; } Eigen::Matrix4d lhm::qMatW(Eigen::VectorXd q) { Eigen::Matrix4d Q_(4, 4); Q_ << q(0), -q(1), -q(2), -q(3), q(1), q(0), q(3), -q(2), q(2), -q(3), q(0), q(1), q(3), q(2), -q(1), q(0); return Q_; } void lhm::absKernel() { for (int i = 0; i < n; i++) Q.col(i) = F[i] * Q.col(i); Eigen::Vector3d P_bar, Q_bar; P_bar = P.rowwise().mean(); Q_bar = Q.rowwise().mean(); for (int i = 0; i < n; i++) { P.col(i) = P.col(i) - P_bar; Q.col(i) = Q.col(i) - Q_bar; } //<------------------- Use SVD Solution ------------------->// /* Eigen::Matrix3d M; M.setZero(); for (i = 0; i < n; i++) M += P.col(i)*Q.col(i).transpose(); Eigen::JacobiSVD<Eigen::MatrixXd> svd(M, Eigen::ComputeThinU | Eigen::ComputeThinV); R = svd.matrixV()*svd.matrixU().transpose(); Eigen::Matrix3d dummy; dummy.col(0) = -svd.matrixV().col(0); dummy.col(1) = -svd.matrixV().col(1); dummy.col(2) = svd.matrixV().col(2); if (R.determinant() == 1) { estimate_t(); if (t(2) < 0) { R = dummy*svd.matrixU().transpose(); estimate_t(); } } else { R = -dummy*svd.matrixU().transpose(); estimate_t(); if (t(2) < 0) { R = -svd.matrixV()*svd.matrixU().transpose(); estimate_t(); } } err2 = 0; xform(); Eigen::Vector3d vec; Eigen::Matrix3d I3 = Eigen::MatrixXd::Identity(3, 3); for (i = 0; i < n; i++) { vec = (I3 - F[i])*Q.col(i); err2 += vec.squaredNorm(); } */ //<------------------- Use QTN Solution ------------------->// Eigen::Matrix4d A; A.setZero(); for (int i = 0; i < n; i++) { Eigen::Vector4d q1, q2; q1 << 1, Q.col(i); q2 << 1, P.col(i); A += qMatQ(q1).transpose() * qMatW(q2); } Eigen::EigenSolver<Eigen::Matrix4d> es(A); const Eigen::Matrix4d Ae = es.pseudoEigenvalueMatrix(); Eigen::Vector4d D; // Ae.diagonal(); for some reason this leads to an // internal compiler error in MSVC11... (sigh) for (int i = 0; i < 4; i++) D[i] = Ae(i, i); Eigen::Matrix4d V_mat = es.pseudoEigenvectors(); Eigen::Vector4d::Index max_index; D.maxCoeff(&max_index); Eigen::Vector4d V; V = V_mat.col(max_index); Eigen::Quaterniond q(V(0), V(1), V(2), V(3)); R = q.toRotationMatrix(); estimate_t(); err2 = 0; xform(); Eigen::Vector3d vec; Eigen::Matrix3d I3 = Eigen::MatrixXd::Identity(3, 3); for (int i = 0; i < n; i++) { vec = (I3 - F[i]) * Q.col(i); err2 += vec.squaredNorm(); } } bool lhm::compute_pose( Eigen::Ref<Eigen::Matrix3d> R_, Eigen::Ref<Eigen::Vector3d> t_) { int i, j = 0; Eigen::VectorXd p_bar; Eigen::Matrix3d sum_F, I3; I3 = Eigen::MatrixXd::Identity(3, 3); sum_F.setZero(); p_bar = P.rowwise().mean(); for (i = 0; i < n; i++) { P.col(i) -= p_bar; F[i] = Q.col(i) * Q.col(i).transpose() / Q.col(i).squaredNorm(); sum_F = sum_F + F[i]; } G = (I3 - sum_F / n).inverse() / n; err = 0; err2 = 1000; absKernel(); while (std::abs(err2 - err) > TOL_LHM && err2 > EPSILON_LHM) { err = err2; absKernel(); j += 1; if (j > 100) break; } R_ = R; t_ = t - R * p_bar; return true; }
4,720
2,270
/******************************************************************************* * * Program: Friend Functions Examples * * Description: Examples of how to use friend functions in C++. * * YouTube Lesson: https://www.youtube.com/watch?v=lOfI1At3tKM * * Author: Kevin Browne @ https://portfoliocourses.com * *******************************************************************************/ #include <iostream> using namespace std; // A simple class with some private members class MyClass { // We declare a 'friend function' double_x that will be allowed access to any // protected and private members of MyClass objects. The friend function is // NOT a member function of MyClass. We could put this declaration beneath // the public or private access specifiers and it would work the same as it // does here, because it is NOT a member of MyClass. friend void double_x(MyClass &object); private: // a private member variable x int x; // a private member function add that adds an int argument provided to x void add(int n) { x += n; } public: // a constructor that sets the member variable x to the int argument provided MyClass(int x) : x(x) {}; // A public member function that prints out the value of member variable x... // MyClass CAN access private members of MyClass, but the "outside world" // such as the main function cannot... friend functions will *also* be able // to access private and protected members! void print() { cout << "x: " << x << endl; } }; // We define the friend function double_x and because it is declared a friend // function inside MyClass (notice the friend keyword is absent here) we can // access the private and protected members of the MyClass object instance. void double_x(MyClass &object) { // access the private member variable x, store it into current_x_value int current_x_value = object.x; // use the private member function add to add the current_x_value to itself, // having the effect of doubling x object.add(current_x_value); // Alternatively we could have accessed the private member variable x directly // in order to double it like this... // // object.x *= 2; } // A friend function can also be a friend to multiple classes, here we have an // example of a friend function that is a friend to both a Revenue1 class and a // Costs1 class. // forward declaration of Costs1 so we can use it in the Revenue1 class class Costs1; // A very simple class for representing revenue class Revenue1 { // declare friend function profit1 friend bool profit1(Revenue1 rev, Costs1 cos); private: // private member variable revenue for representing revenue int revenue; public: // construct sets the revenue member variable to the int argument provided Revenue1(int revenue) : revenue(revenue) {} }; // A very simple class for representing costs class Costs1 { // we ALSO declare the profit1 function as a friend of Costs1 friend bool profit1(Revenue1 rev, Costs1 cos); private: // private member variable for representing costs int costs; public: // Constructor for setting the costs member variable Costs1(int costs) : costs(costs) {} }; // The profit1() function will have access to the protected and private members // of BOTH Revenue1 AND Costs1 because both classes declare it as a friend // function! We return true if revenue is greater than costs (as this would // represent a profit), otherwise we return false. bool profit1(Revenue1 rev, Costs1 cos) { if (rev.revenue > cos.costs) return true; else return false; } // A friend function can also be a member function of another class! Here we // re-work the above example to make the profit2 function a member of class // Revenue2 and a friend function of Costs2. // Again we provide a forward declaration of Costs2 class Costs2; // A simple class for representing revenues class Revenue2 { private: // a private member variable for representing the revenue int revenue; public: // Construct sets revenue member variable to the int argument provided Revenue2(int revenue) : revenue(revenue) {} // profit2 is a member variable of Revenue2 (we will define it later) and it // will be a friend function of the Costs2 class bool profit2(Costs2 cos); }; // A simple class for representing costs class Costs2 { // profit2 is a member function of Revenue2 (notice Revenue2::) BUT is also // declared as a friend function of Class2 below friend bool Revenue2::profit2(Costs2 cos); private: // private member variable for representing costs int costs; public: // Constructor sets costs member variable to the int argument provided Costs2(int costs) : costs(costs) {} }; // Define the Revenue2 member function profit2... because it is a friend of // Costs2 it will have access to the private and protected members of the // Costs2 object. We return return if revenue is greater than costs, and // false otherwise. bool Revenue2::profit2(Costs2 cos) { if (revenue > cos.costs) return true; else return false; } // Test out the above classes int main() { // Create an instance of MyClass with x set to 7 MyClass myobject(7); // Call print to print out the current value of x myobject.print(); // Use friend function double_x() to double the value of x... notice how we // do NOT call it like a member function (e.g. my.object.doublex(...)) because // it is NOT a member function of MyClass objects. double_x(myobject); // Print out the current value of x again to verify that it has doubled to 14 myobject.print(); // Create Revenue1 and Costs1 objects, here revenue is greater than costs Revenue1 revenue1(1000); Costs1 costs1(500); // Use the profit1() function which is a friend of both Revenue1 and Costs1 // classes, and we should report that a profit has occurred if (profit1(revenue1, costs1)) cout << "Profit!" << endl; else cout << "No profit!" << endl; // Create Revenue2 and Costs2 objects, here revenue is not greater than costs Revenue2 revenue2(500); Costs2 costs2(1000); // Use the profit2() member function of the Revenue2 object revenue2 which is // ALSO a friend of the Costs2 class, and we should report no profit this time if (revenue2.profit2(costs2)) cout << "Profit!" << endl; else cout << "No profit!" << endl; return 0; }
6,436
1,869
/* * i2c_lpc11uxx.cpp * * Created on: Mar. 1, 2019 * Author: hoan */
84
49
#include <log/include/ConfiguracionLogger.h> using namespace herramientas::log; // stl #include <fstream> #include <sstream> // utiles #include <utiles/include/Fecha.h> #include <utiles/include/Json.h> ConfiguracionLogger::ConfiguracionLogger(std::string path_archivo_configuracion) { if (false == path_archivo_configuracion.empty()) { this->leerConfiguracion(path_archivo_configuracion); } } ConfiguracionLogger::~ConfiguracionLogger() { } void ConfiguracionLogger::leerConfiguracion(std::string path_archivo_configuracion) { std::ifstream archivo(path_archivo_configuracion); if (false == archivo.good()) { throw - 1; } std::ostringstream sstream; sstream << archivo.rdbuf(); const std::string string_config(sstream.str()); herramientas::utiles::Json config_json(string_config); herramientas::utiles::Json * config_log_json = config_json.getAtributoValorJson("log"); this->activado = config_log_json->getAtributoValorBool(ConfiguracionLogger::tagActivado()); this->nombre_logger = config_log_json->getAtributoValorString(ConfiguracionLogger::tagNombreLogger()); this->tamanio_cola_async = config_log_json->getAtributoValorUint(ConfiguracionLogger::tagTamanioColaAsync()); this->nivel_log = config_log_json->getAtributoValorString(ConfiguracionLogger::tagNivelLog().c_str()); this->nivel_flush = config_log_json->getAtributoValorString(ConfiguracionLogger::tagNivelFlush().c_str()); this->patron = config_log_json->getAtributoValorString(ConfiguracionLogger::tagPatron()); this->agrupar_por_fecha = config_log_json->getAtributoValorBool(ConfiguracionLogger::tagAgruparPorFecha()); this->salidas_logger = config_log_json->getAtributoArrayString(ConfiguracionLogger::tagSalidas()); delete config_log_json; } // CONFIGURACIONES bool ConfiguracionLogger::getActivado() { return this->activado; } std::string ConfiguracionLogger::getNombreLogger() { return this->nombre_logger; } uint64_t ConfiguracionLogger::getTamanioColaAsync() { return this->tamanio_cola_async; } bool ConfiguracionLogger::getAgruparPorFecha() { return this->agrupar_por_fecha; } std::string ConfiguracionLogger::getNivelLog() { return this->nivel_log; } std::string ConfiguracionLogger::getNivelFlush() { return this->nivel_flush; } std::string ConfiguracionLogger::getPatron() { return this->patron; } std::vector<std::string> ConfiguracionLogger::getSalidas() { std::vector<std::string> salidas = this->salidas_logger; if (this->getAgruparPorFecha()) { std::string string_fecha_actual = herramientas::utiles::Fecha::getFechaActual().getStringAAAAMMDD(); for (std::vector<std::string>::iterator it = salidas.begin(); it != salidas.end(); it++) { *it = string_fecha_actual + "_" + *it; } } return salidas; } // TAGS std::string ConfiguracionLogger::tagActivado() { return "activado"; } std::string ConfiguracionLogger::tagNombreLogger() { return "nombre"; } std::string ConfiguracionLogger::tagTamanioColaAsync() { return "tamanio_cola_async"; } std::string ConfiguracionLogger::tagAgruparPorFecha() { return "agrupar_por_fecha"; } std::string ConfiguracionLogger::tagNivelLog() { return "nivel_log"; } std::string ConfiguracionLogger::tagNivelFlush() { return "nivel_flush"; } std::string ConfiguracionLogger::tagPatron() { return "patron"; } std::string ConfiguracionLogger::tagSalidas() { return "salidas"; }
3,686
1,295
/******************************************************************************* * $Id$ * Copyright (C) 2010 Stepan A. Baranov (stepan@baranov.su) * All rights reserved. * web-site: www.OCTLab.org * ***** ******* ***** * Use of this source code is governed by a Clear BSD-style license that can be * found on the http://octlab.googlecode.com/svn/trunk/COPYRIGHT.TXT web-page or * in the COPYRIGHT.TXT file *******************************************************************************/ // common header #include "./OCTLib.h" // for DLL export extern "C" { DllExport I8 OL_phase_calibration(U32, U32, U32, DBL *, DBL *); } /* phase calibration main function PURPOSE: calculate corrected phase based on phase information from calibration mirror [1]. INPUTS: X - number of elements in each row (A-scan size) Y - number of rows (# of A-scans) level - the depth position of calibration mirror reflector ref - pointer to buffer with phase B-scan after FFT from calibration mirror (size: X * Y) OUTPUTS: out - pointer to buffer with phase B-scan after FFT from sample (size: X * Y) REMARKS: note that for all depth indexes below level the phase correction is taken without calibration coefficient. REFERENCES: [1] B. J. Vakoc, S. H. Yun, J. F. de Boer, G. J. Tearney, and B. E. Bouma, "Phase-resolved optical frequency domain imaging", Opt. Express 13, 5483-5493 (2005) */ I8 OL_phase_calibration(U32 X, U32 Y, U32 level, DBL *ref, DBL *ptr) { I32 i, j; // simple checks if (level < 1) return EXIT_FAILURE; #pragma omp parallel for default(shared) private(i, j) for (i = 0; i < static_cast<I32>(Y); i++) for (j = 0; j < static_cast<I32>(X); j++) if (j < static_cast<I32>(level)) ptr[i * X + j] = ptr[i * X + j] - ref[i] * j / level; else ptr[i * X + j] = ptr[i * X + j] - ref[i]; return EXIT_SUCCESS; } /******************************************************************************* Checked by http://google-styleguide.googlecode.com/svn/trunk/cpplint/cpplint.py *******************************************************************************/
2,232
758
// Copyright 2010-2014 RethinkDB, all rights reserved. #ifndef RDB_PROTOCOL_BATCHING_HPP_ #define RDB_PROTOCOL_BATCHING_HPP_ #include <utility> #include "containers/archive/archive.hpp" #include "containers/archive/versioned.hpp" #include "rdb_protocol/datum.hpp" #include "rpc/serialize_macros.hpp" #include "time.hpp" template<class T> class counted_t; namespace ql { class datum_t; class env_t; enum class batch_type_t { // A normal batch. NORMAL = 0, // The first batch in a series of normal batches. The size limit is reduced // to help minimizing the latency until a user receives their first response. NORMAL_FIRST = 1, // A batch fetched for a terminal or terminal-like term, e.g. a big batched // insert. Ignores latency caps because the latency the user encounters is // determined by bandwidth instead. TERMINAL = 2, // If we're ordering by an sindex, get a batch with a constant value for // that sindex. We sometimes need a batch with that invariant for sorting. // (This replaces that SORTING_HINT_NEXT stuff.) SINDEX_CONSTANT = 3 }; ARCHIVE_PRIM_MAKE_RANGED_SERIALIZABLE( batch_type_t, int8_t, batch_type_t::NORMAL, batch_type_t::SINDEX_CONSTANT); enum ignore_latency_t { NO, YES }; class batcher_t { public: bool note_el(const datum_t &t) { seen_one_el = true; els_left -= 1; min_els_left -= 1; size_left -= serialized_size<cluster_version_t::CLUSTER>(t); return should_send_batch(); } bool should_send_batch( ignore_latency_t ignore_latency = ignore_latency_t::NO) const; batcher_t(batcher_t &&other) : batch_type(std::move(other.batch_type)), seen_one_el(std::move(other.seen_one_el)), min_els_left(std::move(other.min_els_left)), els_left(std::move(other.els_left)), size_left(std::move(other.size_left)), end_time(std::move(other.end_time)) { } microtime_t microtime_left() { microtime_t cur_time = current_microtime(); return end_time > cur_time ? end_time - cur_time : 0; } batch_type_t get_batch_type() { return batch_type; } private: DISABLE_COPYING(batcher_t); friend class batchspec_t; batcher_t(batch_type_t batch_type, int64_t min_els, int64_t max_els, int64_t max_size, microtime_t end_time); const batch_type_t batch_type; bool seen_one_el; int64_t min_els_left, els_left, size_left; const microtime_t end_time; }; class batchspec_t { public: static batchspec_t user(batch_type_t batch_type, env_t *env); static batchspec_t all(); // Gimme everything. static batchspec_t empty() { return batchspec_t(); } static batchspec_t default_for(batch_type_t batch_type); batch_type_t get_batch_type() const { return batch_type; } batchspec_t with_new_batch_type(batch_type_t new_batch_type) const; batchspec_t with_min_els(int64_t new_min_els) const; batchspec_t with_max_dur(int64_t new_max_dur) const; batchspec_t with_at_most(uint64_t max_els) const; // These are used to allow batchspecs to override the default ordering on a // stream. This is only really useful when a stream is being treated as a // set, as in the case of `include_initial` changefeeds where always using // `ASCENDING` ordering allows the logic to be simpler. batchspec_t with_lazy_sorting_override(sorting_t sort) const; sorting_t lazy_sorting(sorting_t base) const { return lazy_sorting_override ? *lazy_sorting_override : base; } batchspec_t scale_down(int64_t divisor) const; batcher_t to_batcher() const; private: // I made this private and accessible through a static function because it // was being accidentally default-initialized. batchspec_t() { } // USE ONLY FOR SERIALIZATION batchspec_t(batch_type_t batch_type, int64_t min_els, int64_t max_els, int64_t max_size, int64_t first_scaledown, int64_t max_dur, microtime_t start_time); template<cluster_version_t W> friend void serialize(write_message_t *wm, const batchspec_t &batchspec); template<cluster_version_t W> friend archive_result_t deserialize(read_stream_t *s, batchspec_t *batchspec); batch_type_t batch_type; int64_t min_els, max_els, max_size, first_scaledown_factor, max_dur; microtime_t start_time; boost::optional<sorting_t> lazy_sorting_override; }; RDB_DECLARE_SERIALIZABLE(batchspec_t); } // namespace ql #endif // RDB_PROTOCOL_BATCHING_HPP_
4,537
1,611
//------------------------------------------------------------------------------ /* This file is part of Beast: https://github.com/vinniefalco/Beast Copyright 2013, Vinnie Falco <vinnie.falco@gmail.com> Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ //============================================================================== #include <casinocoin/beast/utility/PropertyStream.h> #include <algorithm> #include <cassert> #include <limits> #include <iostream> namespace beast { //------------------------------------------------------------------------------ // // Item // //------------------------------------------------------------------------------ PropertyStream::Item::Item (Source* source) : m_source (source) { } PropertyStream::Source& PropertyStream::Item::source() const { return *m_source; } PropertyStream::Source* PropertyStream::Item::operator-> () const { return &source(); } PropertyStream::Source& PropertyStream::Item::operator* () const { return source(); } //------------------------------------------------------------------------------ // // Proxy // //------------------------------------------------------------------------------ PropertyStream::Proxy::Proxy ( Map const& map, std::string const& key) : m_map (&map) , m_key (key) { } PropertyStream::Proxy::Proxy (Proxy const& other) : m_map (other.m_map) , m_key (other.m_key) { } PropertyStream::Proxy::~Proxy () { std::string const s (m_ostream.str()); if (! s.empty()) m_map->add (m_key, s); } std::ostream& PropertyStream::Proxy::operator<< ( std::ostream& manip (std::ostream&)) const { return m_ostream << manip; } //------------------------------------------------------------------------------ // // Map // //------------------------------------------------------------------------------ PropertyStream::Map::Map (PropertyStream& stream) : m_stream (stream) { } PropertyStream::Map::Map (Set& parent) : m_stream (parent.stream()) { m_stream.map_begin (); } PropertyStream::Map::Map (std::string const& key, Map& map) : m_stream (map.stream()) { m_stream.map_begin (key); } PropertyStream::Map::Map (std::string const& key, PropertyStream& stream) : m_stream (stream) { m_stream.map_begin (key); } PropertyStream::Map::~Map () { m_stream.map_end (); } PropertyStream& PropertyStream::Map::stream() { return m_stream; } PropertyStream const& PropertyStream::Map::stream() const { return m_stream; } PropertyStream::Proxy PropertyStream::Map::operator[] (std::string const& key) { return Proxy (*this, key); } //------------------------------------------------------------------------------ // // Set // //------------------------------------------------------------------------------ PropertyStream::Set::Set (std::string const& key, Map& map) : m_stream (map.stream()) { m_stream.array_begin (key); } PropertyStream::Set::Set (std::string const& key, PropertyStream& stream) : m_stream (stream) { m_stream.array_begin (key); } PropertyStream::Set::~Set () { m_stream.array_end (); } PropertyStream& PropertyStream::Set::stream() { return m_stream; } PropertyStream const& PropertyStream::Set::stream() const { return m_stream; } //------------------------------------------------------------------------------ // // Source // //------------------------------------------------------------------------------ PropertyStream::Source::Source (std::string const& name) : m_name (name) , item_ (this) , parent_ (nullptr) { } PropertyStream::Source::~Source () { std::lock_guard<std::recursive_mutex> _(lock_); if (parent_ != nullptr) parent_->remove (*this); removeAll (); } std::string const& PropertyStream::Source::name () const { return m_name; } void PropertyStream::Source::add (Source& source) { std::lock(lock_, source.lock_); std::lock_guard<std::recursive_mutex> lk1(lock_, std::adopt_lock); std::lock_guard<std::recursive_mutex> lk2(source.lock_, std::adopt_lock); assert (source.parent_ == nullptr); children_.push_back (source.item_); source.parent_ = this; } void PropertyStream::Source::remove (Source& child) { std::lock(lock_, child.lock_); std::lock_guard<std::recursive_mutex> lk1(lock_, std::adopt_lock); std::lock_guard<std::recursive_mutex> lk2(child.lock_, std::adopt_lock); assert (child.parent_ == this); children_.erase ( children_.iterator_to ( child.item_)); child.parent_ = nullptr; } void PropertyStream::Source::removeAll () { std::lock_guard<std::recursive_mutex> _(lock_); for (auto iter = children_.begin(); iter != children_.end(); ) { std::lock_guard<std::recursive_mutex> _cl((*iter)->lock_); remove (*(*iter)); } } //------------------------------------------------------------------------------ void PropertyStream::Source::write_one (PropertyStream& stream) { Map map (m_name, stream); onWrite (map); } void PropertyStream::Source::write (PropertyStream& stream) { Map map (m_name, stream); onWrite (map); std::lock_guard<std::recursive_mutex> _(lock_); for (auto& child : children_) child.source().write (stream); } void PropertyStream::Source::write (PropertyStream& stream, std::string const& path) { std::pair <Source*, bool> result (find (path)); if (result.first == nullptr) return; if (result.second) result.first->write (stream); else result.first->write_one (stream); } std::pair <PropertyStream::Source*, bool> PropertyStream::Source::find (std::string path) { bool const deep (peel_trailing_slashstar (&path)); bool const rooted (peel_leading_slash (&path)); Source* source (this); if (! path.empty()) { if (! rooted) { std::string const name (peel_name (&path)); source = find_one_deep (name); if (source == nullptr) return std::make_pair (nullptr, deep); } source = source->find_path (path); } return std::make_pair (source, deep); } bool PropertyStream::Source::peel_leading_slash (std::string* path) { if (! path->empty() && path->front() == '/') { *path = std::string (path->begin() + 1, path->end()); return true; } return false; } bool PropertyStream::Source::peel_trailing_slashstar (std::string* path) { bool found(false); if (path->empty()) return false; if (path->back() == '*') { found = true; path->pop_back(); } if(! path->empty() && path->back() == '/') path->pop_back(); return found; } std::string PropertyStream::Source::peel_name (std::string* path) { if (path->empty()) return ""; std::string::const_iterator first = (*path).begin(); std::string::const_iterator last = (*path).end(); std::string::const_iterator pos = std::find (first, last, '/'); std::string s (first, pos); if (pos != last) *path = std::string (pos+1, last); else *path = std::string (); return s; } // Recursive search through the whole tree until name is found PropertyStream::Source* PropertyStream::Source::find_one_deep (std::string const& name) { Source* found = find_one (name); if (found != nullptr) return found; std::lock_guard<std::recursive_mutex> _(lock_); for (auto& s : children_) { found = s.source().find_one_deep (name); if (found != nullptr) return found; } return nullptr; } PropertyStream::Source* PropertyStream::Source::find_path (std::string path) { if (path.empty()) return this; Source* source (this); do { std::string const name (peel_name (&path)); if(name.empty ()) break; source = source->find_one(name); } while (source != nullptr); return source; } // This function only looks at immediate children // If no immediate children match, then return nullptr PropertyStream::Source* PropertyStream::Source::find_one (std::string const& name) { std::lock_guard<std::recursive_mutex> _(lock_); for (auto& s : children_) { if (s.source().m_name == name) return &s.source(); } return nullptr; } void PropertyStream::Source::onWrite (Map&) { } //------------------------------------------------------------------------------ // // PropertyStream // //------------------------------------------------------------------------------ PropertyStream::PropertyStream () { } PropertyStream::~PropertyStream () { } void PropertyStream::add (std::string const& key, bool value) { if (value) add (key, "true"); else add (key, "false"); } void PropertyStream::add (std::string const& key, char value) { lexical_add (key, value); } void PropertyStream::add (std::string const& key, signed char value) { lexical_add (key, value); } void PropertyStream::add (std::string const& key, unsigned char value) { lexical_add (key, value); } void PropertyStream::add (std::string const& key, wchar_t value) { lexical_add (key, value); } #if 0 void PropertyStream::add (std::string const& key, char16_t value) { lexical_add (key, value); } void PropertyStream::add (std::string const& key, char32_t value) { lexical_add (key, value); } #endif void PropertyStream::add (std::string const& key, short value) { lexical_add (key, value); } void PropertyStream::add (std::string const& key, unsigned short value) { lexical_add (key, value); } void PropertyStream::add (std::string const& key, int value) { lexical_add (key, value); } void PropertyStream::add (std::string const& key, unsigned int value) { lexical_add (key, value); } void PropertyStream::add (std::string const& key, long value) { lexical_add (key, value); } void PropertyStream::add (std::string const& key, unsigned long value) { lexical_add (key, value); } void PropertyStream::add (std::string const& key, long long value) { lexical_add (key, value); } void PropertyStream::add (std::string const& key, unsigned long long value) { lexical_add (key, value); } void PropertyStream::add (std::string const& key, float value) { lexical_add (key, value); } void PropertyStream::add (std::string const& key, double value) { lexical_add (key, value); } void PropertyStream::add (std::string const& key, long double value) { lexical_add (key, value); } void PropertyStream::add (bool value) { if (value) add ("true"); else add ("false"); } void PropertyStream::add (char value) { lexical_add (value); } void PropertyStream::add (signed char value) { lexical_add (value); } void PropertyStream::add (unsigned char value) { lexical_add (value); } void PropertyStream::add (wchar_t value) { lexical_add (value); } #if 0 void PropertyStream::add (char16_t value) { lexical_add (value); } void PropertyStream::add (char32_t value) { lexical_add (value); } #endif void PropertyStream::add (short value) { lexical_add (value); } void PropertyStream::add (unsigned short value) { lexical_add (value); } void PropertyStream::add (int value) { lexical_add (value); } void PropertyStream::add (unsigned int value) { lexical_add (value); } void PropertyStream::add (long value) { lexical_add (value); } void PropertyStream::add (unsigned long value) { lexical_add (value); } void PropertyStream::add (long long value) { lexical_add (value); } void PropertyStream::add (unsigned long long value) { lexical_add (value); } void PropertyStream::add (float value) { lexical_add (value); } void PropertyStream::add (double value) { lexical_add (value); } void PropertyStream::add (long double value) { lexical_add (value); } }
12,668
3,999
// Copyright 2016 PDFium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com #include "core/fpdfapi/page/cpdf_streamcontentparser.h" #include <memory> #include <utility> #include <vector> #include "core/fpdfapi/font/cpdf_font.h" #include "core/fpdfapi/font/cpdf_type3font.h" #include "core/fpdfapi/page/cpdf_allstates.h" #include "core/fpdfapi/page/cpdf_docpagedata.h" #include "core/fpdfapi/page/cpdf_form.h" #include "core/fpdfapi/page/cpdf_formobject.h" #include "core/fpdfapi/page/cpdf_image.h" #include "core/fpdfapi/page/cpdf_imageobject.h" #include "core/fpdfapi/page/cpdf_meshstream.h" #include "core/fpdfapi/page/cpdf_pageobject.h" #include "core/fpdfapi/page/cpdf_pathobject.h" #include "core/fpdfapi/page/cpdf_shadingobject.h" #include "core/fpdfapi/page/cpdf_shadingpattern.h" #include "core/fpdfapi/page/cpdf_streamparser.h" #include "core/fpdfapi/page/cpdf_textobject.h" #include "core/fpdfapi/page/pageint.h" #include "core/fpdfapi/parser/cpdf_array.h" #include "core/fpdfapi/parser/cpdf_dictionary.h" #include "core/fpdfapi/parser/cpdf_document.h" #include "core/fpdfapi/parser/cpdf_name.h" #include "core/fpdfapi/parser/cpdf_number.h" #include "core/fpdfapi/parser/cpdf_reference.h" #include "core/fpdfapi/parser/cpdf_stream.h" #include "core/fpdfapi/parser/fpdf_parser_decode.h" #include "core/fxcrt/fx_safe_types.h" #include "core/fxge/cfx_graphstatedata.h" #include "third_party/base/ptr_util.h" namespace { const int kMaxFormLevel = 30; const int kSingleCoordinatePair = 1; const int kTensorCoordinatePairs = 16; const int kCoonsCoordinatePairs = 12; const int kSingleColorPerPatch = 1; const int kQuadColorsPerPatch = 4; const char kPathOperatorSubpath = 'm'; const char kPathOperatorLine = 'l'; const char kPathOperatorCubicBezier1 = 'c'; const char kPathOperatorCubicBezier2 = 'v'; const char kPathOperatorCubicBezier3 = 'y'; const char kPathOperatorClosePath = 'h'; const char kPathOperatorRectangle[] = "re"; class CPDF_StreamParserAutoClearer { public: CPDF_StreamParserAutoClearer(CPDF_StreamParser** scoped_variable, CPDF_StreamParser* new_parser) : scoped_variable_(scoped_variable) { *scoped_variable_ = new_parser; } ~CPDF_StreamParserAutoClearer() { *scoped_variable_ = nullptr; } private: CPDF_StreamParser** scoped_variable_; }; CFX_FloatRect GetShadingBBox(CPDF_ShadingPattern* pShading, const CFX_Matrix& matrix) { ShadingType type = pShading->GetShadingType(); CPDF_Stream* pStream = ToStream(pShading->GetShadingObject()); CPDF_ColorSpace* pCS = pShading->GetCS(); if (!pStream || !pCS) return CFX_FloatRect(0, 0, 0, 0); CPDF_MeshStream stream(type, pShading->GetFuncs(), pStream, pCS); if (!stream.Load()) return CFX_FloatRect(0, 0, 0, 0); CFX_FloatRect rect; bool bStarted = false; bool bGouraud = type == kFreeFormGouraudTriangleMeshShading || type == kLatticeFormGouraudTriangleMeshShading; int point_count = kSingleCoordinatePair; if (type == kTensorProductPatchMeshShading) point_count = kTensorCoordinatePairs; else if (type == kCoonsPatchMeshShading) point_count = kCoonsCoordinatePairs; int color_count = kSingleColorPerPatch; if (type == kCoonsPatchMeshShading || type == kTensorProductPatchMeshShading) color_count = kQuadColorsPerPatch; while (!stream.BitStream()->IsEOF()) { uint32_t flag = 0; if (type != kLatticeFormGouraudTriangleMeshShading) flag = stream.GetFlag(); if (!bGouraud && flag) { point_count -= 4; color_count -= 2; } for (int i = 0; i < point_count; i++) { FX_FLOAT x; FX_FLOAT y; stream.GetCoords(x, y); if (bStarted) { rect.UpdateRect(x, y); } else { rect.InitRect(x, y); bStarted = true; } } FX_SAFE_UINT32 nBits = stream.Components(); nBits *= stream.ComponentBits(); nBits *= color_count; if (!nBits.IsValid()) break; stream.BitStream()->SkipBits(nBits.ValueOrDie()); if (bGouraud) stream.BitStream()->ByteAlign(); } rect.Transform(&matrix); return rect; } struct AbbrPair { const FX_CHAR* abbr; const FX_CHAR* full_name; }; const AbbrPair InlineKeyAbbr[] = { {"BPC", "BitsPerComponent"}, {"CS", "ColorSpace"}, {"D", "Decode"}, {"DP", "DecodeParms"}, {"F", "Filter"}, {"H", "Height"}, {"IM", "ImageMask"}, {"I", "Interpolate"}, {"W", "Width"}, }; const AbbrPair InlineValueAbbr[] = { {"G", "DeviceGray"}, {"RGB", "DeviceRGB"}, {"CMYK", "DeviceCMYK"}, {"I", "Indexed"}, {"AHx", "ASCIIHexDecode"}, {"A85", "ASCII85Decode"}, {"LZW", "LZWDecode"}, {"Fl", "FlateDecode"}, {"RL", "RunLengthDecode"}, {"CCF", "CCITTFaxDecode"}, {"DCT", "DCTDecode"}, }; struct AbbrReplacementOp { bool is_replace_key; CFX_ByteString key; CFX_ByteStringC replacement; }; CFX_ByteStringC FindFullName(const AbbrPair* table, size_t count, const CFX_ByteStringC& abbr) { auto it = std::find_if(table, table + count, [abbr](const AbbrPair& pair) { return pair.abbr == abbr; }); return it != table + count ? CFX_ByteStringC(it->full_name) : CFX_ByteStringC(); } void ReplaceAbbr(CPDF_Object* pObj) { switch (pObj->GetType()) { case CPDF_Object::DICTIONARY: { CPDF_Dictionary* pDict = pObj->AsDictionary(); std::vector<AbbrReplacementOp> replacements; for (const auto& it : *pDict) { CFX_ByteString key = it.first; CPDF_Object* value = it.second.get(); CFX_ByteStringC fullname = FindFullName( InlineKeyAbbr, FX_ArraySize(InlineKeyAbbr), key.AsStringC()); if (!fullname.IsEmpty()) { AbbrReplacementOp op; op.is_replace_key = true; op.key = key; op.replacement = fullname; replacements.push_back(op); key = fullname; } if (value->IsName()) { CFX_ByteString name = value->GetString(); fullname = FindFullName( InlineValueAbbr, FX_ArraySize(InlineValueAbbr), name.AsStringC()); if (!fullname.IsEmpty()) { AbbrReplacementOp op; op.is_replace_key = false; op.key = key; op.replacement = fullname; replacements.push_back(op); } } else { ReplaceAbbr(value); } } for (const auto& op : replacements) { if (op.is_replace_key) pDict->ReplaceKey(op.key, CFX_ByteString(op.replacement)); else pDict->SetNewFor<CPDF_Name>(op.key, CFX_ByteString(op.replacement)); } break; } case CPDF_Object::ARRAY: { CPDF_Array* pArray = pObj->AsArray(); for (size_t i = 0; i < pArray->GetCount(); i++) { CPDF_Object* pElement = pArray->GetObjectAt(i); if (pElement->IsName()) { CFX_ByteString name = pElement->GetString(); CFX_ByteStringC fullname = FindFullName( InlineValueAbbr, FX_ArraySize(InlineValueAbbr), name.AsStringC()); if (!fullname.IsEmpty()) pArray->SetNewAt<CPDF_Name>(i, CFX_ByteString(fullname)); } else { ReplaceAbbr(pElement); } } break; } default: break; } } } // namespace CFX_ByteStringC PDF_FindKeyAbbreviationForTesting(const CFX_ByteStringC& abbr) { return FindFullName(InlineKeyAbbr, FX_ArraySize(InlineKeyAbbr), abbr); } CFX_ByteStringC PDF_FindValueAbbreviationForTesting( const CFX_ByteStringC& abbr) { return FindFullName(InlineValueAbbr, FX_ArraySize(InlineValueAbbr), abbr); } CPDF_StreamContentParser::CPDF_StreamContentParser( CPDF_Document* pDocument, CPDF_Dictionary* pPageResources, CPDF_Dictionary* pParentResources, const CFX_Matrix* pmtContentToUser, CPDF_PageObjectHolder* pObjHolder, CPDF_Dictionary* pResources, CFX_FloatRect* pBBox, CPDF_AllStates* pStates, int level) : m_pDocument(pDocument), m_pPageResources(pPageResources), m_pParentResources(pParentResources), m_pResources(pResources), m_pObjectHolder(pObjHolder), m_Level(level), m_ParamStartPos(0), m_ParamCount(0), m_pCurStates(new CPDF_AllStates), m_pLastTextObject(nullptr), m_DefFontSize(0), m_pPathPoints(nullptr), m_PathPointCount(0), m_PathAllocSize(0), m_PathCurrentX(0.0f), m_PathCurrentY(0.0f), m_PathClipType(0), m_pLastImage(nullptr), m_bColored(false), m_bResourceMissing(false) { if (pmtContentToUser) m_mtContentToUser = *pmtContentToUser; if (!m_pResources) m_pResources = m_pParentResources; if (!m_pResources) m_pResources = m_pPageResources; if (pBBox) m_BBox = *pBBox; if (pStates) { m_pCurStates->Copy(*pStates); } else { m_pCurStates->m_GeneralState.Emplace(); m_pCurStates->m_GraphState.Emplace(); m_pCurStates->m_TextState.Emplace(); m_pCurStates->m_ColorState.Emplace(); } for (size_t i = 0; i < FX_ArraySize(m_Type3Data); ++i) { m_Type3Data[i] = 0.0; } } CPDF_StreamContentParser::~CPDF_StreamContentParser() { ClearAllParams(); FX_Free(m_pPathPoints); } int CPDF_StreamContentParser::GetNextParamPos() { if (m_ParamCount == kParamBufSize) { m_ParamStartPos++; if (m_ParamStartPos == kParamBufSize) { m_ParamStartPos = 0; } if (m_ParamBuf[m_ParamStartPos].m_Type == ContentParam::OBJECT) m_ParamBuf[m_ParamStartPos].m_pObject.reset(); return m_ParamStartPos; } int index = m_ParamStartPos + m_ParamCount; if (index >= kParamBufSize) { index -= kParamBufSize; } m_ParamCount++; return index; } void CPDF_StreamContentParser::AddNameParam(const FX_CHAR* name, int len) { CFX_ByteStringC bsName(name, len); ContentParam& param = m_ParamBuf[GetNextParamPos()]; if (len > 32) { param.m_Type = ContentParam::OBJECT; param.m_pObject = pdfium::MakeUnique<CPDF_Name>( m_pDocument->GetByteStringPool(), PDF_NameDecode(bsName)); } else { param.m_Type = ContentParam::NAME; if (bsName.Find('#') == -1) { FXSYS_memcpy(param.m_Name.m_Buffer, name, len); param.m_Name.m_Len = len; } else { CFX_ByteString str = PDF_NameDecode(bsName); FXSYS_memcpy(param.m_Name.m_Buffer, str.c_str(), str.GetLength()); param.m_Name.m_Len = str.GetLength(); } } } void CPDF_StreamContentParser::AddNumberParam(const FX_CHAR* str, int len) { ContentParam& param = m_ParamBuf[GetNextParamPos()]; param.m_Type = ContentParam::NUMBER; param.m_Number.m_bInteger = FX_atonum(CFX_ByteStringC(str, len), &param.m_Number.m_Integer); } void CPDF_StreamContentParser::AddObjectParam( std::unique_ptr<CPDF_Object> pObj) { ContentParam& param = m_ParamBuf[GetNextParamPos()]; param.m_Type = ContentParam::OBJECT; param.m_pObject = std::move(pObj); } void CPDF_StreamContentParser::ClearAllParams() { uint32_t index = m_ParamStartPos; for (uint32_t i = 0; i < m_ParamCount; i++) { if (m_ParamBuf[index].m_Type == ContentParam::OBJECT) m_ParamBuf[index].m_pObject.reset(); index++; if (index == kParamBufSize) index = 0; } m_ParamStartPos = 0; m_ParamCount = 0; } CPDF_Object* CPDF_StreamContentParser::GetObject(uint32_t index) { if (index >= m_ParamCount) { return nullptr; } int real_index = m_ParamStartPos + m_ParamCount - index - 1; if (real_index >= kParamBufSize) { real_index -= kParamBufSize; } ContentParam& param = m_ParamBuf[real_index]; if (param.m_Type == ContentParam::NUMBER) { param.m_Type = ContentParam::OBJECT; param.m_pObject = param.m_Number.m_bInteger ? pdfium::MakeUnique<CPDF_Number>(param.m_Number.m_Integer) : pdfium::MakeUnique<CPDF_Number>(param.m_Number.m_Float); return param.m_pObject.get(); } if (param.m_Type == ContentParam::NAME) { param.m_Type = ContentParam::OBJECT; param.m_pObject = pdfium::MakeUnique<CPDF_Name>( m_pDocument->GetByteStringPool(), CFX_ByteString(param.m_Name.m_Buffer, param.m_Name.m_Len)); return param.m_pObject.get(); } if (param.m_Type == ContentParam::OBJECT) return param.m_pObject.get(); ASSERT(false); return nullptr; } CFX_ByteString CPDF_StreamContentParser::GetString(uint32_t index) { if (index >= m_ParamCount) { return CFX_ByteString(); } int real_index = m_ParamStartPos + m_ParamCount - index - 1; if (real_index >= kParamBufSize) { real_index -= kParamBufSize; } ContentParam& param = m_ParamBuf[real_index]; if (param.m_Type == ContentParam::NAME) { return CFX_ByteString(param.m_Name.m_Buffer, param.m_Name.m_Len); } if (param.m_Type == 0 && param.m_pObject) { return param.m_pObject->GetString(); } return CFX_ByteString(); } FX_FLOAT CPDF_StreamContentParser::GetNumber(uint32_t index) { if (index >= m_ParamCount) { return 0; } int real_index = m_ParamStartPos + m_ParamCount - index - 1; if (real_index >= kParamBufSize) { real_index -= kParamBufSize; } ContentParam& param = m_ParamBuf[real_index]; if (param.m_Type == ContentParam::NUMBER) { return param.m_Number.m_bInteger ? (FX_FLOAT)param.m_Number.m_Integer : param.m_Number.m_Float; } if (param.m_Type == 0 && param.m_pObject) { return param.m_pObject->GetNumber(); } return 0; } void CPDF_StreamContentParser::SetGraphicStates(CPDF_PageObject* pObj, bool bColor, bool bText, bool bGraph) { pObj->m_GeneralState = m_pCurStates->m_GeneralState; pObj->m_ClipPath = m_pCurStates->m_ClipPath; pObj->m_ContentMark = m_CurContentMark; if (bColor) { pObj->m_ColorState = m_pCurStates->m_ColorState; } if (bGraph) { pObj->m_GraphState = m_pCurStates->m_GraphState; } if (bText) { pObj->m_TextState = m_pCurStates->m_TextState; } } // static CPDF_StreamContentParser::OpCodes CPDF_StreamContentParser::InitializeOpCodes() { return OpCodes({ {FXBSTR_ID('"', 0, 0, 0), &CPDF_StreamContentParser::Handle_NextLineShowText_Space}, {FXBSTR_ID('\'', 0, 0, 0), &CPDF_StreamContentParser::Handle_NextLineShowText}, {FXBSTR_ID('B', 0, 0, 0), &CPDF_StreamContentParser::Handle_FillStrokePath}, {FXBSTR_ID('B', '*', 0, 0), &CPDF_StreamContentParser::Handle_EOFillStrokePath}, {FXBSTR_ID('B', 'D', 'C', 0), &CPDF_StreamContentParser::Handle_BeginMarkedContent_Dictionary}, {FXBSTR_ID('B', 'I', 0, 0), &CPDF_StreamContentParser::Handle_BeginImage}, {FXBSTR_ID('B', 'M', 'C', 0), &CPDF_StreamContentParser::Handle_BeginMarkedContent}, {FXBSTR_ID('B', 'T', 0, 0), &CPDF_StreamContentParser::Handle_BeginText}, {FXBSTR_ID('C', 'S', 0, 0), &CPDF_StreamContentParser::Handle_SetColorSpace_Stroke}, {FXBSTR_ID('D', 'P', 0, 0), &CPDF_StreamContentParser::Handle_MarkPlace_Dictionary}, {FXBSTR_ID('D', 'o', 0, 0), &CPDF_StreamContentParser::Handle_ExecuteXObject}, {FXBSTR_ID('E', 'I', 0, 0), &CPDF_StreamContentParser::Handle_EndImage}, {FXBSTR_ID('E', 'M', 'C', 0), &CPDF_StreamContentParser::Handle_EndMarkedContent}, {FXBSTR_ID('E', 'T', 0, 0), &CPDF_StreamContentParser::Handle_EndText}, {FXBSTR_ID('F', 0, 0, 0), &CPDF_StreamContentParser::Handle_FillPathOld}, {FXBSTR_ID('G', 0, 0, 0), &CPDF_StreamContentParser::Handle_SetGray_Stroke}, {FXBSTR_ID('I', 'D', 0, 0), &CPDF_StreamContentParser::Handle_BeginImageData}, {FXBSTR_ID('J', 0, 0, 0), &CPDF_StreamContentParser::Handle_SetLineCap}, {FXBSTR_ID('K', 0, 0, 0), &CPDF_StreamContentParser::Handle_SetCMYKColor_Stroke}, {FXBSTR_ID('M', 0, 0, 0), &CPDF_StreamContentParser::Handle_SetMiterLimit}, {FXBSTR_ID('M', 'P', 0, 0), &CPDF_StreamContentParser::Handle_MarkPlace}, {FXBSTR_ID('Q', 0, 0, 0), &CPDF_StreamContentParser::Handle_RestoreGraphState}, {FXBSTR_ID('R', 'G', 0, 0), &CPDF_StreamContentParser::Handle_SetRGBColor_Stroke}, {FXBSTR_ID('S', 0, 0, 0), &CPDF_StreamContentParser::Handle_StrokePath}, {FXBSTR_ID('S', 'C', 0, 0), &CPDF_StreamContentParser::Handle_SetColor_Stroke}, {FXBSTR_ID('S', 'C', 'N', 0), &CPDF_StreamContentParser::Handle_SetColorPS_Stroke}, {FXBSTR_ID('T', '*', 0, 0), &CPDF_StreamContentParser::Handle_MoveToNextLine}, {FXBSTR_ID('T', 'D', 0, 0), &CPDF_StreamContentParser::Handle_MoveTextPoint_SetLeading}, {FXBSTR_ID('T', 'J', 0, 0), &CPDF_StreamContentParser::Handle_ShowText_Positioning}, {FXBSTR_ID('T', 'L', 0, 0), &CPDF_StreamContentParser::Handle_SetTextLeading}, {FXBSTR_ID('T', 'c', 0, 0), &CPDF_StreamContentParser::Handle_SetCharSpace}, {FXBSTR_ID('T', 'd', 0, 0), &CPDF_StreamContentParser::Handle_MoveTextPoint}, {FXBSTR_ID('T', 'f', 0, 0), &CPDF_StreamContentParser::Handle_SetFont}, {FXBSTR_ID('T', 'j', 0, 0), &CPDF_StreamContentParser::Handle_ShowText}, {FXBSTR_ID('T', 'm', 0, 0), &CPDF_StreamContentParser::Handle_SetTextMatrix}, {FXBSTR_ID('T', 'r', 0, 0), &CPDF_StreamContentParser::Handle_SetTextRenderMode}, {FXBSTR_ID('T', 's', 0, 0), &CPDF_StreamContentParser::Handle_SetTextRise}, {FXBSTR_ID('T', 'w', 0, 0), &CPDF_StreamContentParser::Handle_SetWordSpace}, {FXBSTR_ID('T', 'z', 0, 0), &CPDF_StreamContentParser::Handle_SetHorzScale}, {FXBSTR_ID('W', 0, 0, 0), &CPDF_StreamContentParser::Handle_Clip}, {FXBSTR_ID('W', '*', 0, 0), &CPDF_StreamContentParser::Handle_EOClip}, {FXBSTR_ID('b', 0, 0, 0), &CPDF_StreamContentParser::Handle_CloseFillStrokePath}, {FXBSTR_ID('b', '*', 0, 0), &CPDF_StreamContentParser::Handle_CloseEOFillStrokePath}, {FXBSTR_ID('c', 0, 0, 0), &CPDF_StreamContentParser::Handle_CurveTo_123}, {FXBSTR_ID('c', 'm', 0, 0), &CPDF_StreamContentParser::Handle_ConcatMatrix}, {FXBSTR_ID('c', 's', 0, 0), &CPDF_StreamContentParser::Handle_SetColorSpace_Fill}, {FXBSTR_ID('d', 0, 0, 0), &CPDF_StreamContentParser::Handle_SetDash}, {FXBSTR_ID('d', '0', 0, 0), &CPDF_StreamContentParser::Handle_SetCharWidth}, {FXBSTR_ID('d', '1', 0, 0), &CPDF_StreamContentParser::Handle_SetCachedDevice}, {FXBSTR_ID('f', 0, 0, 0), &CPDF_StreamContentParser::Handle_FillPath}, {FXBSTR_ID('f', '*', 0, 0), &CPDF_StreamContentParser::Handle_EOFillPath}, {FXBSTR_ID('g', 0, 0, 0), &CPDF_StreamContentParser::Handle_SetGray_Fill}, {FXBSTR_ID('g', 's', 0, 0), &CPDF_StreamContentParser::Handle_SetExtendGraphState}, {FXBSTR_ID('h', 0, 0, 0), &CPDF_StreamContentParser::Handle_ClosePath}, {FXBSTR_ID('i', 0, 0, 0), &CPDF_StreamContentParser::Handle_SetFlat}, {FXBSTR_ID('j', 0, 0, 0), &CPDF_StreamContentParser::Handle_SetLineJoin}, {FXBSTR_ID('k', 0, 0, 0), &CPDF_StreamContentParser::Handle_SetCMYKColor_Fill}, {FXBSTR_ID('l', 0, 0, 0), &CPDF_StreamContentParser::Handle_LineTo}, {FXBSTR_ID('m', 0, 0, 0), &CPDF_StreamContentParser::Handle_MoveTo}, {FXBSTR_ID('n', 0, 0, 0), &CPDF_StreamContentParser::Handle_EndPath}, {FXBSTR_ID('q', 0, 0, 0), &CPDF_StreamContentParser::Handle_SaveGraphState}, {FXBSTR_ID('r', 'e', 0, 0), &CPDF_StreamContentParser::Handle_Rectangle}, {FXBSTR_ID('r', 'g', 0, 0), &CPDF_StreamContentParser::Handle_SetRGBColor_Fill}, {FXBSTR_ID('r', 'i', 0, 0), &CPDF_StreamContentParser::Handle_SetRenderIntent}, {FXBSTR_ID('s', 0, 0, 0), &CPDF_StreamContentParser::Handle_CloseStrokePath}, {FXBSTR_ID('s', 'c', 0, 0), &CPDF_StreamContentParser::Handle_SetColor_Fill}, {FXBSTR_ID('s', 'c', 'n', 0), &CPDF_StreamContentParser::Handle_SetColorPS_Fill}, {FXBSTR_ID('s', 'h', 0, 0), &CPDF_StreamContentParser::Handle_ShadeFill}, {FXBSTR_ID('v', 0, 0, 0), &CPDF_StreamContentParser::Handle_CurveTo_23}, {FXBSTR_ID('w', 0, 0, 0), &CPDF_StreamContentParser::Handle_SetLineWidth}, {FXBSTR_ID('y', 0, 0, 0), &CPDF_StreamContentParser::Handle_CurveTo_13}, }); } void CPDF_StreamContentParser::OnOperator(const FX_CHAR* op) { int i = 0; uint32_t opid = 0; while (i < 4 && op[i]) { opid = (opid << 8) + op[i]; i++; } while (i < 4) { opid <<= 8; i++; } static const OpCodes s_OpCodes = InitializeOpCodes(); auto it = s_OpCodes.find(opid); if (it != s_OpCodes.end()) (this->*it->second)(); } void CPDF_StreamContentParser::Handle_CloseFillStrokePath() { Handle_ClosePath(); AddPathObject(FXFILL_WINDING, true); } void CPDF_StreamContentParser::Handle_FillStrokePath() { AddPathObject(FXFILL_WINDING, true); } void CPDF_StreamContentParser::Handle_CloseEOFillStrokePath() { AddPathPoint(m_PathStartX, m_PathStartY, FXPT_LINETO | FXPT_CLOSEFIGURE); AddPathObject(FXFILL_ALTERNATE, true); } void CPDF_StreamContentParser::Handle_EOFillStrokePath() { AddPathObject(FXFILL_ALTERNATE, true); } void CPDF_StreamContentParser::Handle_BeginMarkedContent_Dictionary() { CFX_ByteString tag = GetString(1); CPDF_Object* pProperty = GetObject(0); if (!pProperty) { return; } bool bDirect = true; if (pProperty->IsName()) { pProperty = FindResourceObj("Properties", pProperty->GetString()); if (!pProperty) return; bDirect = false; } if (CPDF_Dictionary* pDict = pProperty->AsDictionary()) { m_CurContentMark.AddMark(tag, pDict, bDirect); } } void CPDF_StreamContentParser::Handle_BeginImage() { FX_FILESIZE savePos = m_pSyntax->GetPos(); auto pDict = pdfium::MakeUnique<CPDF_Dictionary>(m_pDocument->GetByteStringPool()); while (1) { CPDF_StreamParser::SyntaxType type = m_pSyntax->ParseNextElement(); if (type == CPDF_StreamParser::Keyword) { CFX_ByteString bsKeyword(m_pSyntax->GetWordBuf(), m_pSyntax->GetWordSize()); if (bsKeyword != "ID") { m_pSyntax->SetPos(savePos); return; } } if (type != CPDF_StreamParser::Name) { break; } CFX_ByteString key((const FX_CHAR*)m_pSyntax->GetWordBuf() + 1, m_pSyntax->GetWordSize() - 1); auto pObj = m_pSyntax->ReadNextObject(false, 0); if (!key.IsEmpty()) { uint32_t dwObjNum = pObj ? pObj->GetObjNum() : 0; if (dwObjNum) pDict->SetNewFor<CPDF_Reference>(key, m_pDocument, dwObjNum); else pDict->SetFor(key, std::move(pObj)); } } ReplaceAbbr(pDict.get()); CPDF_Object* pCSObj = nullptr; if (pDict->KeyExist("ColorSpace")) { pCSObj = pDict->GetDirectObjectFor("ColorSpace"); if (pCSObj->IsName()) { CFX_ByteString name = pCSObj->GetString(); if (name != "DeviceRGB" && name != "DeviceGray" && name != "DeviceCMYK") { pCSObj = FindResourceObj("ColorSpace", name); if (pCSObj && pCSObj->IsInline()) pDict->SetFor("ColorSpace", pCSObj->Clone()); } } } pDict->SetNewFor<CPDF_Name>("Subtype", "Image"); std::unique_ptr<CPDF_Stream> pStream = m_pSyntax->ReadInlineStream(m_pDocument, std::move(pDict), pCSObj); while (1) { CPDF_StreamParser::SyntaxType type = m_pSyntax->ParseNextElement(); if (type == CPDF_StreamParser::EndOfData) { break; } if (type != CPDF_StreamParser::Keyword) { continue; } if (m_pSyntax->GetWordSize() == 2 && m_pSyntax->GetWordBuf()[0] == 'E' && m_pSyntax->GetWordBuf()[1] == 'I') { break; } } AddImage(std::move(pStream)); } void CPDF_StreamContentParser::Handle_BeginMarkedContent() { m_CurContentMark.AddMark(GetString(0), nullptr, false); } void CPDF_StreamContentParser::Handle_BeginText() { m_pCurStates->m_TextMatrix.Set(1.0f, 0, 0, 1.0f, 0, 0); OnChangeTextMatrix(); m_pCurStates->m_TextX = 0; m_pCurStates->m_TextY = 0; m_pCurStates->m_TextLineX = 0; m_pCurStates->m_TextLineY = 0; } void CPDF_StreamContentParser::Handle_CurveTo_123() { AddPathPoint(GetNumber(5), GetNumber(4), FXPT_BEZIERTO); AddPathPoint(GetNumber(3), GetNumber(2), FXPT_BEZIERTO); AddPathPoint(GetNumber(1), GetNumber(0), FXPT_BEZIERTO); } void CPDF_StreamContentParser::Handle_ConcatMatrix() { CFX_Matrix new_matrix(GetNumber(5), GetNumber(4), GetNumber(3), GetNumber(2), GetNumber(1), GetNumber(0)); new_matrix.Concat(m_pCurStates->m_CTM); m_pCurStates->m_CTM = new_matrix; OnChangeTextMatrix(); } void CPDF_StreamContentParser::Handle_SetColorSpace_Fill() { CPDF_ColorSpace* pCS = FindColorSpace(GetString(0)); if (!pCS) return; m_pCurStates->m_ColorState.GetMutableFillColor()->SetColorSpace(pCS); } void CPDF_StreamContentParser::Handle_SetColorSpace_Stroke() { CPDF_ColorSpace* pCS = FindColorSpace(GetString(0)); if (!pCS) return; m_pCurStates->m_ColorState.GetMutableStrokeColor()->SetColorSpace(pCS); } void CPDF_StreamContentParser::Handle_SetDash() { CPDF_Array* pArray = ToArray(GetObject(1)); if (!pArray) return; m_pCurStates->SetLineDash(pArray, GetNumber(0), 1.0f); } void CPDF_StreamContentParser::Handle_SetCharWidth() { m_Type3Data[0] = GetNumber(1); m_Type3Data[1] = GetNumber(0); m_bColored = true; } void CPDF_StreamContentParser::Handle_SetCachedDevice() { for (int i = 0; i < 6; i++) { m_Type3Data[i] = GetNumber(5 - i); } m_bColored = false; } void CPDF_StreamContentParser::Handle_ExecuteXObject() { CFX_ByteString name = GetString(0); if (name == m_LastImageName && m_pLastImage && m_pLastImage->GetStream() && m_pLastImage->GetStream()->GetObjNum()) { AddImage(m_pLastImage); return; } CPDF_Stream* pXObject = ToStream(FindResourceObj("XObject", name)); if (!pXObject) { m_bResourceMissing = true; return; } CFX_ByteString type; if (pXObject->GetDict()) type = pXObject->GetDict()->GetStringFor("Subtype"); if (type == "Image") { CPDF_ImageObject* pObj = pXObject->IsInline() ? AddImage(std::unique_ptr<CPDF_Stream>( ToStream(pXObject->Clone()))) : AddImage(pXObject->GetObjNum()); m_LastImageName = name; m_pLastImage = pObj->GetImage(); if (!m_pObjectHolder->HasImageMask()) m_pObjectHolder->SetHasImageMask(m_pLastImage->IsMask()); } else if (type == "Form") { AddForm(pXObject); } } void CPDF_StreamContentParser::AddForm(CPDF_Stream* pStream) { std::unique_ptr<CPDF_FormObject> pFormObj(new CPDF_FormObject); pFormObj->m_pForm.reset( new CPDF_Form(m_pDocument, m_pPageResources, pStream, m_pResources)); pFormObj->m_FormMatrix = m_pCurStates->m_CTM; pFormObj->m_FormMatrix.Concat(m_mtContentToUser); CPDF_AllStates status; status.m_GeneralState = m_pCurStates->m_GeneralState; status.m_GraphState = m_pCurStates->m_GraphState; status.m_ColorState = m_pCurStates->m_ColorState; status.m_TextState = m_pCurStates->m_TextState; pFormObj->m_pForm->ParseContent(&status, nullptr, nullptr, m_Level + 1); if (!m_pObjectHolder->BackgroundAlphaNeeded() && pFormObj->m_pForm->BackgroundAlphaNeeded()) { m_pObjectHolder->SetBackgroundAlphaNeeded(true); } pFormObj->CalcBoundingBox(); SetGraphicStates(pFormObj.get(), true, true, true); m_pObjectHolder->GetPageObjectList()->push_back(std::move(pFormObj)); } CPDF_ImageObject* CPDF_StreamContentParser::AddImage( std::unique_ptr<CPDF_Stream> pStream) { if (!pStream) return nullptr; auto pImageObj = pdfium::MakeUnique<CPDF_ImageObject>(); pImageObj->SetOwnedImage( pdfium::MakeUnique<CPDF_Image>(m_pDocument, std::move(pStream))); return AddImageObject(std::move(pImageObj)); } CPDF_ImageObject* CPDF_StreamContentParser::AddImage(uint32_t streamObjNum) { auto pImageObj = pdfium::MakeUnique<CPDF_ImageObject>(); pImageObj->SetUnownedImage(m_pDocument->LoadImageFromPageData(streamObjNum)); return AddImageObject(std::move(pImageObj)); } CPDF_ImageObject* CPDF_StreamContentParser::AddImage(CPDF_Image* pImage) { if (!pImage) return nullptr; auto pImageObj = pdfium::MakeUnique<CPDF_ImageObject>(); pImageObj->SetUnownedImage( m_pDocument->GetPageData()->GetImage(pImage->GetStream()->GetObjNum())); return AddImageObject(std::move(pImageObj)); } CPDF_ImageObject* CPDF_StreamContentParser::AddImageObject( std::unique_ptr<CPDF_ImageObject> pImageObj) { SetGraphicStates(pImageObj.get(), pImageObj->GetImage()->IsMask(), false, false); CFX_Matrix ImageMatrix = m_pCurStates->m_CTM; ImageMatrix.Concat(m_mtContentToUser); pImageObj->set_matrix(ImageMatrix); pImageObj->CalcBoundingBox(); CPDF_ImageObject* pRet = pImageObj.get(); m_pObjectHolder->GetPageObjectList()->push_back(std::move(pImageObj)); return pRet; } void CPDF_StreamContentParser::Handle_MarkPlace_Dictionary() {} void CPDF_StreamContentParser::Handle_EndImage() {} void CPDF_StreamContentParser::Handle_EndMarkedContent() { if (m_CurContentMark) m_CurContentMark.DeleteLastMark(); } void CPDF_StreamContentParser::Handle_EndText() { if (m_ClipTextList.empty()) return; if (TextRenderingModeIsClipMode(m_pCurStates->m_TextState.GetTextMode())) m_pCurStates->m_ClipPath.AppendTexts(&m_ClipTextList); m_ClipTextList.clear(); } void CPDF_StreamContentParser::Handle_FillPath() { AddPathObject(FXFILL_WINDING, false); } void CPDF_StreamContentParser::Handle_FillPathOld() { AddPathObject(FXFILL_WINDING, false); } void CPDF_StreamContentParser::Handle_EOFillPath() { AddPathObject(FXFILL_ALTERNATE, false); } void CPDF_StreamContentParser::Handle_SetGray_Fill() { FX_FLOAT value = GetNumber(0); CPDF_ColorSpace* pCS = CPDF_ColorSpace::GetStockCS(PDFCS_DEVICEGRAY); m_pCurStates->m_ColorState.SetFillColor(pCS, &value, 1); } void CPDF_StreamContentParser::Handle_SetGray_Stroke() { FX_FLOAT value = GetNumber(0); CPDF_ColorSpace* pCS = CPDF_ColorSpace::GetStockCS(PDFCS_DEVICEGRAY); m_pCurStates->m_ColorState.SetStrokeColor(pCS, &value, 1); } void CPDF_StreamContentParser::Handle_SetExtendGraphState() { CFX_ByteString name = GetString(0); CPDF_Dictionary* pGS = ToDictionary(FindResourceObj("ExtGState", name)); if (!pGS) { m_bResourceMissing = true; return; } m_pCurStates->ProcessExtGS(pGS, this); } void CPDF_StreamContentParser::Handle_ClosePath() { if (m_PathPointCount == 0) { return; } if (m_PathStartX != m_PathCurrentX || m_PathStartY != m_PathCurrentY) { AddPathPoint(m_PathStartX, m_PathStartY, FXPT_LINETO | FXPT_CLOSEFIGURE); } else if (m_pPathPoints[m_PathPointCount - 1].m_Flag != FXPT_MOVETO) { m_pPathPoints[m_PathPointCount - 1].m_Flag |= FXPT_CLOSEFIGURE; } } void CPDF_StreamContentParser::Handle_SetFlat() { m_pCurStates->m_GeneralState.SetFlatness(GetNumber(0)); } void CPDF_StreamContentParser::Handle_BeginImageData() {} void CPDF_StreamContentParser::Handle_SetLineJoin() { m_pCurStates->m_GraphState.SetLineJoin( static_cast<CFX_GraphStateData::LineJoin>(GetInteger(0))); } void CPDF_StreamContentParser::Handle_SetLineCap() { m_pCurStates->m_GraphState.SetLineCap( static_cast<CFX_GraphStateData::LineCap>(GetInteger(0))); } void CPDF_StreamContentParser::Handle_SetCMYKColor_Fill() { if (m_ParamCount != 4) return; FX_FLOAT values[4]; for (int i = 0; i < 4; i++) { values[i] = GetNumber(3 - i); } CPDF_ColorSpace* pCS = CPDF_ColorSpace::GetStockCS(PDFCS_DEVICECMYK); m_pCurStates->m_ColorState.SetFillColor(pCS, values, 4); } void CPDF_StreamContentParser::Handle_SetCMYKColor_Stroke() { if (m_ParamCount != 4) return; FX_FLOAT values[4]; for (int i = 0; i < 4; i++) { values[i] = GetNumber(3 - i); } CPDF_ColorSpace* pCS = CPDF_ColorSpace::GetStockCS(PDFCS_DEVICECMYK); m_pCurStates->m_ColorState.SetStrokeColor(pCS, values, 4); } void CPDF_StreamContentParser::Handle_LineTo() { if (m_ParamCount != 2) return; AddPathPoint(GetNumber(1), GetNumber(0), FXPT_LINETO); } void CPDF_StreamContentParser::Handle_MoveTo() { if (m_ParamCount != 2) return; AddPathPoint(GetNumber(1), GetNumber(0), FXPT_MOVETO); ParsePathObject(); } void CPDF_StreamContentParser::Handle_SetMiterLimit() { m_pCurStates->m_GraphState.SetMiterLimit(GetNumber(0)); } void CPDF_StreamContentParser::Handle_MarkPlace() {} void CPDF_StreamContentParser::Handle_EndPath() { AddPathObject(0, false); } void CPDF_StreamContentParser::Handle_SaveGraphState() { std::unique_ptr<CPDF_AllStates> pStates(new CPDF_AllStates); pStates->Copy(*m_pCurStates); m_StateStack.push_back(std::move(pStates)); } void CPDF_StreamContentParser::Handle_RestoreGraphState() { if (m_StateStack.empty()) return; std::unique_ptr<CPDF_AllStates> pStates = std::move(m_StateStack.back()); m_StateStack.pop_back(); m_pCurStates->Copy(*pStates); } void CPDF_StreamContentParser::Handle_Rectangle() { FX_FLOAT x = GetNumber(3), y = GetNumber(2); FX_FLOAT w = GetNumber(1), h = GetNumber(0); AddPathRect(x, y, w, h); } void CPDF_StreamContentParser::AddPathRect(FX_FLOAT x, FX_FLOAT y, FX_FLOAT w, FX_FLOAT h) { AddPathPoint(x, y, FXPT_MOVETO); AddPathPoint(x + w, y, FXPT_LINETO); AddPathPoint(x + w, y + h, FXPT_LINETO); AddPathPoint(x, y + h, FXPT_LINETO); AddPathPoint(x, y, FXPT_LINETO | FXPT_CLOSEFIGURE); } void CPDF_StreamContentParser::Handle_SetRGBColor_Fill() { if (m_ParamCount != 3) return; FX_FLOAT values[3]; for (int i = 0; i < 3; i++) { values[i] = GetNumber(2 - i); } CPDF_ColorSpace* pCS = CPDF_ColorSpace::GetStockCS(PDFCS_DEVICERGB); m_pCurStates->m_ColorState.SetFillColor(pCS, values, 3); } void CPDF_StreamContentParser::Handle_SetRGBColor_Stroke() { if (m_ParamCount != 3) return; FX_FLOAT values[3]; for (int i = 0; i < 3; i++) { values[i] = GetNumber(2 - i); } CPDF_ColorSpace* pCS = CPDF_ColorSpace::GetStockCS(PDFCS_DEVICERGB); m_pCurStates->m_ColorState.SetStrokeColor(pCS, values, 3); } void CPDF_StreamContentParser::Handle_SetRenderIntent() {} void CPDF_StreamContentParser::Handle_CloseStrokePath() { Handle_ClosePath(); AddPathObject(0, true); } void CPDF_StreamContentParser::Handle_StrokePath() { AddPathObject(0, true); } void CPDF_StreamContentParser::Handle_SetColor_Fill() { FX_FLOAT values[4]; int nargs = m_ParamCount; if (nargs > 4) { nargs = 4; } for (int i = 0; i < nargs; i++) { values[i] = GetNumber(nargs - i - 1); } m_pCurStates->m_ColorState.SetFillColor(nullptr, values, nargs); } void CPDF_StreamContentParser::Handle_SetColor_Stroke() { FX_FLOAT values[4]; int nargs = m_ParamCount; if (nargs > 4) { nargs = 4; } for (int i = 0; i < nargs; i++) { values[i] = GetNumber(nargs - i - 1); } m_pCurStates->m_ColorState.SetStrokeColor(nullptr, values, nargs); } void CPDF_StreamContentParser::Handle_SetColorPS_Fill() { CPDF_Object* pLastParam = GetObject(0); if (!pLastParam) { return; } uint32_t nargs = m_ParamCount; uint32_t nvalues = nargs; if (pLastParam->IsName()) nvalues--; FX_FLOAT* values = nullptr; if (nvalues) { values = FX_Alloc(FX_FLOAT, nvalues); for (uint32_t i = 0; i < nvalues; i++) { values[i] = GetNumber(nargs - i - 1); } } if (nvalues != nargs) { CPDF_Pattern* pPattern = FindPattern(GetString(0), false); if (pPattern) { m_pCurStates->m_ColorState.SetFillPattern(pPattern, values, nvalues); } } else { m_pCurStates->m_ColorState.SetFillColor(nullptr, values, nvalues); } FX_Free(values); } void CPDF_StreamContentParser::Handle_SetColorPS_Stroke() { CPDF_Object* pLastParam = GetObject(0); if (!pLastParam) { return; } int nargs = m_ParamCount; int nvalues = nargs; if (pLastParam->IsName()) nvalues--; FX_FLOAT* values = nullptr; if (nvalues) { values = FX_Alloc(FX_FLOAT, nvalues); for (int i = 0; i < nvalues; i++) { values[i] = GetNumber(nargs - i - 1); } } if (nvalues != nargs) { CPDF_Pattern* pPattern = FindPattern(GetString(0), false); if (pPattern) { m_pCurStates->m_ColorState.SetStrokePattern(pPattern, values, nvalues); } } else { m_pCurStates->m_ColorState.SetStrokeColor(nullptr, values, nvalues); } FX_Free(values); } void CPDF_StreamContentParser::Handle_ShadeFill() { CPDF_Pattern* pPattern = FindPattern(GetString(0), true); if (!pPattern) return; CPDF_ShadingPattern* pShading = pPattern->AsShadingPattern(); if (!pShading) return; if (!pShading->IsShadingObject() || !pShading->Load()) return; std::unique_ptr<CPDF_ShadingObject> pObj(new CPDF_ShadingObject); pObj->m_pShading = pShading; SetGraphicStates(pObj.get(), false, false, false); pObj->m_Matrix = m_pCurStates->m_CTM; pObj->m_Matrix.Concat(m_mtContentToUser); CFX_FloatRect bbox = pObj->m_ClipPath ? pObj->m_ClipPath.GetClipBox() : m_BBox; if (pShading->IsMeshShading()) bbox.Intersect(GetShadingBBox(pShading, pObj->m_Matrix)); pObj->m_Left = bbox.left; pObj->m_Right = bbox.right; pObj->m_Top = bbox.top; pObj->m_Bottom = bbox.bottom; m_pObjectHolder->GetPageObjectList()->push_back(std::move(pObj)); } void CPDF_StreamContentParser::Handle_SetCharSpace() { m_pCurStates->m_TextState.SetCharSpace(GetNumber(0)); } void CPDF_StreamContentParser::Handle_MoveTextPoint() { m_pCurStates->m_TextLineX += GetNumber(1); m_pCurStates->m_TextLineY += GetNumber(0); m_pCurStates->m_TextX = m_pCurStates->m_TextLineX; m_pCurStates->m_TextY = m_pCurStates->m_TextLineY; } void CPDF_StreamContentParser::Handle_MoveTextPoint_SetLeading() { Handle_MoveTextPoint(); m_pCurStates->m_TextLeading = -GetNumber(0); } void CPDF_StreamContentParser::Handle_SetFont() { FX_FLOAT fs = GetNumber(0); if (fs == 0) { fs = m_DefFontSize; } m_pCurStates->m_TextState.SetFontSize(fs); CPDF_Font* pFont = FindFont(GetString(1)); if (pFont) { m_pCurStates->m_TextState.SetFont(pFont); } } CPDF_Object* CPDF_StreamContentParser::FindResourceObj( const CFX_ByteString& type, const CFX_ByteString& name) { if (!m_pResources) return nullptr; CPDF_Dictionary* pDict = m_pResources->GetDictFor(type); if (pDict) return pDict->GetDirectObjectFor(name); if (m_pResources == m_pPageResources || !m_pPageResources) return nullptr; CPDF_Dictionary* pPageDict = m_pPageResources->GetDictFor(type); return pPageDict ? pPageDict->GetDirectObjectFor(name) : nullptr; } CPDF_Font* CPDF_StreamContentParser::FindFont(const CFX_ByteString& name) { CPDF_Dictionary* pFontDict = ToDictionary(FindResourceObj("Font", name)); if (!pFontDict) { m_bResourceMissing = true; return CPDF_Font::GetStockFont(m_pDocument, "Helvetica"); } CPDF_Font* pFont = m_pDocument->LoadFont(pFontDict); if (pFont && pFont->IsType3Font()) { pFont->AsType3Font()->SetPageResources(m_pResources); pFont->AsType3Font()->CheckType3FontMetrics(); } return pFont; } CPDF_ColorSpace* CPDF_StreamContentParser::FindColorSpace( const CFX_ByteString& name) { if (name == "Pattern") { return CPDF_ColorSpace::GetStockCS(PDFCS_PATTERN); } if (name == "DeviceGray" || name == "DeviceCMYK" || name == "DeviceRGB") { CFX_ByteString defname = "Default"; defname += name.Mid(7); CPDF_Object* pDefObj = FindResourceObj("ColorSpace", defname); if (!pDefObj) { if (name == "DeviceGray") { return CPDF_ColorSpace::GetStockCS(PDFCS_DEVICEGRAY); } if (name == "DeviceRGB") { return CPDF_ColorSpace::GetStockCS(PDFCS_DEVICERGB); } return CPDF_ColorSpace::GetStockCS(PDFCS_DEVICECMYK); } return m_pDocument->LoadColorSpace(pDefObj); } CPDF_Object* pCSObj = FindResourceObj("ColorSpace", name); if (!pCSObj) { m_bResourceMissing = true; return nullptr; } return m_pDocument->LoadColorSpace(pCSObj); } CPDF_Pattern* CPDF_StreamContentParser::FindPattern(const CFX_ByteString& name, bool bShading) { CPDF_Object* pPattern = FindResourceObj(bShading ? "Shading" : "Pattern", name); if (!pPattern || (!pPattern->IsDictionary() && !pPattern->IsStream())) { m_bResourceMissing = true; return nullptr; } return m_pDocument->LoadPattern(pPattern, bShading, m_pCurStates->m_ParentMatrix); } void CPDF_StreamContentParser::ConvertTextSpace(FX_FLOAT& x, FX_FLOAT& y) { m_pCurStates->m_TextMatrix.Transform(x, y, x, y); ConvertUserSpace(x, y); } void CPDF_StreamContentParser::ConvertUserSpace(FX_FLOAT& x, FX_FLOAT& y) { m_pCurStates->m_CTM.Transform(x, y, x, y); m_mtContentToUser.Transform(x, y, x, y); } void CPDF_StreamContentParser::AddTextObject(CFX_ByteString* pStrs, FX_FLOAT fInitKerning, FX_FLOAT* pKerning, int nsegs) { CPDF_Font* pFont = m_pCurStates->m_TextState.GetFont(); if (!pFont) { return; } if (fInitKerning != 0) { if (!pFont->IsVertWriting()) { m_pCurStates->m_TextX -= (fInitKerning * m_pCurStates->m_TextState.GetFontSize() * m_pCurStates->m_TextHorzScale) / 1000; } else { m_pCurStates->m_TextY -= (fInitKerning * m_pCurStates->m_TextState.GetFontSize()) / 1000; } } if (nsegs == 0) { return; } const TextRenderingMode text_mode = pFont->IsType3Font() ? TextRenderingMode::MODE_FILL : m_pCurStates->m_TextState.GetTextMode(); { std::unique_ptr<CPDF_TextObject> pText(new CPDF_TextObject); m_pLastTextObject = pText.get(); SetGraphicStates(m_pLastTextObject, true, true, true); if (TextRenderingModeIsStrokeMode(text_mode)) { FX_FLOAT* pCTM = pText->m_TextState.GetMutableCTM(); pCTM[0] = m_pCurStates->m_CTM.a; pCTM[1] = m_pCurStates->m_CTM.c; pCTM[2] = m_pCurStates->m_CTM.b; pCTM[3] = m_pCurStates->m_CTM.d; } pText->SetSegments(pStrs, pKerning, nsegs); pText->m_PosX = m_pCurStates->m_TextX; pText->m_PosY = m_pCurStates->m_TextY + m_pCurStates->m_TextRise; ConvertTextSpace(pText->m_PosX, pText->m_PosY); FX_FLOAT x_advance; FX_FLOAT y_advance; pText->CalcPositionData(&x_advance, &y_advance, m_pCurStates->m_TextHorzScale); m_pCurStates->m_TextX += x_advance; m_pCurStates->m_TextY += y_advance; if (TextRenderingModeIsClipMode(text_mode)) { m_ClipTextList.push_back( std::unique_ptr<CPDF_TextObject>(pText->Clone())); } m_pObjectHolder->GetPageObjectList()->push_back(std::move(pText)); } if (pKerning && pKerning[nsegs - 1] != 0) { if (!pFont->IsVertWriting()) { m_pCurStates->m_TextX -= (pKerning[nsegs - 1] * m_pCurStates->m_TextState.GetFontSize() * m_pCurStates->m_TextHorzScale) / 1000; } else { m_pCurStates->m_TextY -= (pKerning[nsegs - 1] * m_pCurStates->m_TextState.GetFontSize()) / 1000; } } } void CPDF_StreamContentParser::Handle_ShowText() { CFX_ByteString str = GetString(0); if (str.IsEmpty()) { return; } AddTextObject(&str, 0, nullptr, 1); } void CPDF_StreamContentParser::Handle_ShowText_Positioning() { CPDF_Array* pArray = ToArray(GetObject(0)); if (!pArray) return; size_t n = pArray->GetCount(); size_t nsegs = 0; for (size_t i = 0; i < n; i++) { if (pArray->GetDirectObjectAt(i)->IsString()) nsegs++; } if (nsegs == 0) { for (size_t i = 0; i < n; i++) { m_pCurStates->m_TextX -= (pArray->GetNumberAt(i) * m_pCurStates->m_TextState.GetFontSize() * m_pCurStates->m_TextHorzScale) / 1000; } return; } CFX_ByteString* pStrs = new CFX_ByteString[nsegs]; FX_FLOAT* pKerning = FX_Alloc(FX_FLOAT, nsegs); size_t iSegment = 0; FX_FLOAT fInitKerning = 0; for (size_t i = 0; i < n; i++) { CPDF_Object* pObj = pArray->GetDirectObjectAt(i); if (pObj->IsString()) { CFX_ByteString str = pObj->GetString(); if (str.IsEmpty()) { continue; } pStrs[iSegment] = str; pKerning[iSegment++] = 0; } else { FX_FLOAT num = pObj ? pObj->GetNumber() : 0; if (iSegment == 0) { fInitKerning += num; } else { pKerning[iSegment - 1] += num; } } } AddTextObject(pStrs, fInitKerning, pKerning, iSegment); delete[] pStrs; FX_Free(pKerning); } void CPDF_StreamContentParser::Handle_SetTextLeading() { m_pCurStates->m_TextLeading = GetNumber(0); } void CPDF_StreamContentParser::Handle_SetTextMatrix() { m_pCurStates->m_TextMatrix.Set(GetNumber(5), GetNumber(4), GetNumber(3), GetNumber(2), GetNumber(1), GetNumber(0)); OnChangeTextMatrix(); m_pCurStates->m_TextX = 0; m_pCurStates->m_TextY = 0; m_pCurStates->m_TextLineX = 0; m_pCurStates->m_TextLineY = 0; } void CPDF_StreamContentParser::OnChangeTextMatrix() { CFX_Matrix text_matrix(m_pCurStates->m_TextHorzScale, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f); text_matrix.Concat(m_pCurStates->m_TextMatrix); text_matrix.Concat(m_pCurStates->m_CTM); text_matrix.Concat(m_mtContentToUser); FX_FLOAT* pTextMatrix = m_pCurStates->m_TextState.GetMutableMatrix(); pTextMatrix[0] = text_matrix.a; pTextMatrix[1] = text_matrix.c; pTextMatrix[2] = text_matrix.b; pTextMatrix[3] = text_matrix.d; } void CPDF_StreamContentParser::Handle_SetTextRenderMode() { TextRenderingMode mode; if (SetTextRenderingModeFromInt(GetInteger(0), &mode)) m_pCurStates->m_TextState.SetTextMode(mode); } void CPDF_StreamContentParser::Handle_SetTextRise() { m_pCurStates->m_TextRise = GetNumber(0); } void CPDF_StreamContentParser::Handle_SetWordSpace() { m_pCurStates->m_TextState.SetWordSpace(GetNumber(0)); } void CPDF_StreamContentParser::Handle_SetHorzScale() { if (m_ParamCount != 1) { return; } m_pCurStates->m_TextHorzScale = GetNumber(0) / 100; OnChangeTextMatrix(); } void CPDF_StreamContentParser::Handle_MoveToNextLine() { m_pCurStates->m_TextLineY -= m_pCurStates->m_TextLeading; m_pCurStates->m_TextX = m_pCurStates->m_TextLineX; m_pCurStates->m_TextY = m_pCurStates->m_TextLineY; } void CPDF_StreamContentParser::Handle_CurveTo_23() { AddPathPoint(m_PathCurrentX, m_PathCurrentY, FXPT_BEZIERTO); AddPathPoint(GetNumber(3), GetNumber(2), FXPT_BEZIERTO); AddPathPoint(GetNumber(1), GetNumber(0), FXPT_BEZIERTO); } void CPDF_StreamContentParser::Handle_SetLineWidth() { m_pCurStates->m_GraphState.SetLineWidth(GetNumber(0)); } void CPDF_StreamContentParser::Handle_Clip() { m_PathClipType = FXFILL_WINDING; } void CPDF_StreamContentParser::Handle_EOClip() { m_PathClipType = FXFILL_ALTERNATE; } void CPDF_StreamContentParser::Handle_CurveTo_13() { AddPathPoint(GetNumber(3), GetNumber(2), FXPT_BEZIERTO); AddPathPoint(GetNumber(1), GetNumber(0), FXPT_BEZIERTO); AddPathPoint(GetNumber(1), GetNumber(0), FXPT_BEZIERTO); } void CPDF_StreamContentParser::Handle_NextLineShowText() { Handle_MoveToNextLine(); Handle_ShowText(); } void CPDF_StreamContentParser::Handle_NextLineShowText_Space() { m_pCurStates->m_TextState.SetWordSpace(GetNumber(2)); m_pCurStates->m_TextState.SetCharSpace(GetNumber(1)); Handle_NextLineShowText(); } void CPDF_StreamContentParser::Handle_Invalid() {} void CPDF_StreamContentParser::AddPathPoint(FX_FLOAT x, FX_FLOAT y, int flag) { m_PathCurrentX = x; m_PathCurrentY = y; if (flag == FXPT_MOVETO) { m_PathStartX = x; m_PathStartY = y; if (m_PathPointCount && m_pPathPoints[m_PathPointCount - 1].m_Flag == FXPT_MOVETO) { m_pPathPoints[m_PathPointCount - 1].m_PointX = x; m_pPathPoints[m_PathPointCount - 1].m_PointY = y; return; } } else if (m_PathPointCount == 0) { return; } m_PathPointCount++; if (m_PathPointCount > m_PathAllocSize) { int newsize = m_PathPointCount + 256; FX_PATHPOINT* pNewPoints = FX_Alloc(FX_PATHPOINT, newsize); if (m_PathAllocSize) { FXSYS_memcpy(pNewPoints, m_pPathPoints, m_PathAllocSize * sizeof(FX_PATHPOINT)); FX_Free(m_pPathPoints); } m_pPathPoints = pNewPoints; m_PathAllocSize = newsize; } m_pPathPoints[m_PathPointCount - 1].m_Flag = flag; m_pPathPoints[m_PathPointCount - 1].m_PointX = x; m_pPathPoints[m_PathPointCount - 1].m_PointY = y; } void CPDF_StreamContentParser::AddPathObject(int FillType, bool bStroke) { int PathPointCount = m_PathPointCount; uint8_t PathClipType = m_PathClipType; m_PathPointCount = 0; m_PathClipType = 0; if (PathPointCount <= 1) { if (PathPointCount && PathClipType) { CPDF_Path path; path.AppendRect(0, 0, 0, 0); m_pCurStates->m_ClipPath.AppendPath(path, FXFILL_WINDING, true); } return; } if (PathPointCount && m_pPathPoints[PathPointCount - 1].m_Flag == FXPT_MOVETO) { PathPointCount--; } CPDF_Path Path; Path.SetPointCount(PathPointCount); FXSYS_memcpy(Path.GetMutablePoints(), m_pPathPoints, sizeof(FX_PATHPOINT) * PathPointCount); CFX_Matrix matrix = m_pCurStates->m_CTM; matrix.Concat(m_mtContentToUser); if (bStroke || FillType) { std::unique_ptr<CPDF_PathObject> pPathObj(new CPDF_PathObject); pPathObj->m_bStroke = bStroke; pPathObj->m_FillType = FillType; pPathObj->m_Path = Path; pPathObj->m_Matrix = matrix; SetGraphicStates(pPathObj.get(), true, false, true); pPathObj->CalcBoundingBox(); m_pObjectHolder->GetPageObjectList()->push_back(std::move(pPathObj)); } if (PathClipType) { if (!matrix.IsIdentity()) { Path.Transform(&matrix); matrix.SetIdentity(); } m_pCurStates->m_ClipPath.AppendPath(Path, PathClipType, true); } } uint32_t CPDF_StreamContentParser::Parse(const uint8_t* pData, uint32_t dwSize, uint32_t max_cost) { if (m_Level > kMaxFormLevel) return dwSize; uint32_t InitObjCount = m_pObjectHolder->GetPageObjectList()->size(); CPDF_StreamParser syntax(pData, dwSize, m_pDocument->GetByteStringPool()); CPDF_StreamParserAutoClearer auto_clearer(&m_pSyntax, &syntax); while (1) { uint32_t cost = m_pObjectHolder->GetPageObjectList()->size() - InitObjCount; if (max_cost && cost >= max_cost) { break; } switch (syntax.ParseNextElement()) { case CPDF_StreamParser::EndOfData: return m_pSyntax->GetPos(); case CPDF_StreamParser::Keyword: OnOperator((char*)syntax.GetWordBuf()); ClearAllParams(); break; case CPDF_StreamParser::Number: AddNumberParam((char*)syntax.GetWordBuf(), syntax.GetWordSize()); break; case CPDF_StreamParser::Name: AddNameParam((const FX_CHAR*)syntax.GetWordBuf() + 1, syntax.GetWordSize() - 1); break; default: AddObjectParam(syntax.GetObject()); } } return m_pSyntax->GetPos(); } void CPDF_StreamContentParser::ParsePathObject() { FX_FLOAT params[6] = {}; int nParams = 0; int last_pos = m_pSyntax->GetPos(); while (1) { CPDF_StreamParser::SyntaxType type = m_pSyntax->ParseNextElement(); bool bProcessed = true; switch (type) { case CPDF_StreamParser::EndOfData: return; case CPDF_StreamParser::Keyword: { int len = m_pSyntax->GetWordSize(); if (len == 1) { switch (m_pSyntax->GetWordBuf()[0]) { case kPathOperatorSubpath: AddPathPoint(params[0], params[1], FXPT_MOVETO); nParams = 0; break; case kPathOperatorLine: AddPathPoint(params[0], params[1], FXPT_LINETO); nParams = 0; break; case kPathOperatorCubicBezier1: AddPathPoint(params[0], params[1], FXPT_BEZIERTO); AddPathPoint(params[2], params[3], FXPT_BEZIERTO); AddPathPoint(params[4], params[5], FXPT_BEZIERTO); nParams = 0; break; case kPathOperatorCubicBezier2: AddPathPoint(m_PathCurrentX, m_PathCurrentY, FXPT_BEZIERTO); AddPathPoint(params[0], params[1], FXPT_BEZIERTO); AddPathPoint(params[2], params[3], FXPT_BEZIERTO); nParams = 0; break; case kPathOperatorCubicBezier3: AddPathPoint(params[0], params[1], FXPT_BEZIERTO); AddPathPoint(params[2], params[3], FXPT_BEZIERTO); AddPathPoint(params[2], params[3], FXPT_BEZIERTO); nParams = 0; break; case kPathOperatorClosePath: Handle_ClosePath(); nParams = 0; break; default: bProcessed = false; break; } } else if (len == 2) { if (m_pSyntax->GetWordBuf()[0] == kPathOperatorRectangle[0] && m_pSyntax->GetWordBuf()[1] == kPathOperatorRectangle[1]) { AddPathRect(params[0], params[1], params[2], params[3]); nParams = 0; } else { bProcessed = false; } } else { bProcessed = false; } if (bProcessed) { last_pos = m_pSyntax->GetPos(); } break; } case CPDF_StreamParser::Number: { if (nParams == 6) break; int value; bool bInteger = FX_atonum( CFX_ByteStringC(m_pSyntax->GetWordBuf(), m_pSyntax->GetWordSize()), &value); params[nParams++] = bInteger ? (FX_FLOAT)value : *(FX_FLOAT*)&value; break; } default: bProcessed = false; } if (!bProcessed) { m_pSyntax->SetPos(last_pos); return; } } } CPDF_StreamContentParser::ContentParam::ContentParam() {} CPDF_StreamContentParser::ContentParam::~ContentParam() {}
54,805
21,053
/* ** Output: ** ** $ ./info_reg.bin ** Name : ah ** Size byte : 1 ** Size bit : 8 ** Highed bit : 15 ** Lower bit : 8 ** Parent : rax ** operator<< : ah:8 bitsvector[15..8] ** Object : ah:8 bitsvector[15..8] ** Object : ah:8 bitsvector[15..8] */ #include <iostream> #include <triton/x86Specifications.hpp> #include <triton/api.hpp> using namespace triton; using namespace triton::arch; using namespace triton::arch::x86; int main(int ac, const char **av) { triton::API api; /* Set the arch */ api.setArchitecture(ARCH_X86_64); std::cout << "Name : " << api.registers.x86_ah.getName() << std::endl; std::cout << "Size byte : " << api.registers.x86_ah.getSize() << std::endl; std::cout << "Size bit : " << api.registers.x86_ah.getBitSize() << std::endl; std::cout << "Higher bit : " << api.registers.x86_ah.getHigh() << std::endl; std::cout << "Lower bit : " << api.registers.x86_ah.getLow() << std::endl; std::cout << "Parent : " << api.getParentRegister(ID_REG_X86_AH).getName() << std::endl; std::cout << "operator<< : " << api.getRegister(ID_REG_X86_AH) << std::endl; std::cout << "Object : " << api.getRegister("ah") << std::endl; std::cout << "Object : " << api.getRegister("AH") << std::endl; std::cout << "----------------------------" << std::endl; for(const auto& kv: api.getAllRegisters()) std::cout << kv.second << std::endl; return 0; }
1,465
581
#ifndef EXTRA_FEATURES_TEST_HPP #define EXTRA_FEATURES_TEST_HPP #include "../../include/qureg.hpp" #include "../../include/qaoa_features.hpp" ////////////////////////////////////////////////////////////////////////////// // Test fixture class. class ExtraFeaturesTest : public ::testing::Test { protected: ExtraFeaturesTest() { } // just after the 'constructor' void SetUp() override { // All tests are skipped if the rank is dummy. if (qhipster::mpi::Environment::IsUsefulRank() == false) GTEST_SKIP(); // All tests are skipped if the 6-qubit state is distributed in more than 2^5 ranks. // In fact the MPI version needs to allocate half-the-local-storage for communication. // If the local storage is a single amplitude, this cannot be further divided. if (qhipster::mpi::Environment::GetStateSize() > 32) GTEST_SKIP(); } const std::size_t num_qubits_ = 6; double accepted_error_ = 1e-15; }; ////////////////////////////////////////////////////////////////////////////// // Functions developed to facilitate the simulation of QAOA circuits. ////////////////////////////////////////////////////////////////////////////// TEST_F(ExtraFeaturesTest, qaoa_maxcut) { // Instance of the max-cut problem provided as adjacency matrix. // It is a ring of 6 vertices: // // 0--1--2 // | | // 5--4--3 // std::vector<int> adjacency = {0, 1, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0}; QubitRegister<ComplexDP> diag (num_qubits_,"base",0); int max_cut_value; max_cut_value = qaoa::InitializeVectorAsMaxCutCostFunction(diag,adjacency); // Among other properties, only two bipartition has cut=0. ComplexDP amplitude; amplitude = { 0, 0 }; ASSERT_COMPLEX_NEAR(diag.GetGlobalAmplitude(0), amplitude, accepted_error_); ASSERT_COMPLEX_NEAR(diag.GetGlobalAmplitude(diag.GlobalSize()-1), amplitude, accepted_error_); // No bipartition can cut a single edge. for (size_t j=0; j<diag.LocalSize(); ++j) ASSERT_GT( std::abs(diag[j].real()-1.), accepted_error_); // Perform QAOA simulation (p=1). QubitRegister<ComplexDP> psi (num_qubits_,"++++",0); double gamma = 0.4; double beta = 0.3; // Emulation of the layer based on the cost function: qaoa::ImplementQaoaLayerBasedOnCostFunction(psi, diag, gamma); // Simulation of the layer based on the local transverse field: for (int qubit=0; qubit<num_qubits_; ++qubit) psi.ApplyRotationX(qubit, beta); // Get average of cut value: double expectation = qaoa::GetExpectationValueFromCostFunction( psi, diag); // Get histogram of the cut values: std::vector<double> histo = qaoa::GetHistogramFromCostFunction(psi, diag, max_cut_value); ASSERT_EQ(histo.size(), max_cut_value+1); double average=0; for (int j=0; j<histo.size(); ++j) average += double(j)*histo[j]; ASSERT_DOUBLE_EQ(expectation, average); } ////////////////////////////////////////////////////////////////////////////// TEST_F(ExtraFeaturesTest, qaoa_weighted_maxcut) { // Instance of the max-cut problem provided as adjacency matrix. // It is a ring of 6 vertices: // // 0--1--2 // | | // 5--4--3 // // where the verical edges have weight 1.4 std::vector<double> adjacency = {0 , 1 , 0 , 0 , 0 , 1.4, 1 , 0 , 1 , 0 , 0 , 0 , 0 , 1 , 0 , 1.4, 0 , 0 , 0 , 0 , 1.4, 0 , 1 , 0 , 0 , 0 , 0 , 1 , 0 , 1 , 1.4, 0 , 0 , 0 , 1 , 0 }; QubitRegister<ComplexDP> diag (num_qubits_,"base",0); double max_cut_value; max_cut_value = qaoa::InitializeVectorAsWeightedMaxCutCostFunction(diag,adjacency); // Among other properties, only two bipartition has cut=0. ComplexDP amplitude; amplitude = { 0, 0 }; ASSERT_COMPLEX_NEAR(diag.GetGlobalAmplitude(0), amplitude, accepted_error_); ASSERT_COMPLEX_NEAR(diag.GetGlobalAmplitude(diag.GlobalSize()-1), amplitude, accepted_error_); // Case in which only 2 is dis-aligned: // 001000 = 1*2^2 amplitude = { 1+1.4, 0 }; size_t index = 2*2; ASSERT_COMPLEX_NEAR(diag.GetGlobalAmplitude(index), amplitude, accepted_error_); // Case in which only 2 and 5 are dis-aligned: // 001001 = 1*2^2 + 1*2^5 amplitude = { 1+1.4+1+1.4, 0 }; index = 4+32; ASSERT_COMPLEX_NEAR(diag.GetGlobalAmplitude(index), amplitude, accepted_error_); // No bipartition can cut a single edge. for (size_t j=0; j<diag.LocalSize(); ++j) ASSERT_GT( std::abs(diag[j].real()-1.), accepted_error_); // Perform QAOA simulation (p=1). QubitRegister<ComplexDP> psi (num_qubits_,"++++",0); double gamma = 0.4; double beta = 0.3; // Emulation of the layer based on the cost function: qaoa::ImplementQaoaLayerBasedOnCostFunction(psi, diag, gamma); // Simulation of the layer based on the local transverse field: for (int qubit=0; qubit<num_qubits_; ++qubit) psi.ApplyRotationX(qubit, beta); // Get average of cut value: double expectation = qaoa::GetExpectationValueFromCostFunction(psi, diag); // Histogram for rounded cutvals and check if it matches expval to the tolerance. std::vector<double> histo = qaoa::GetHistogramFromCostFunctionWithWeightsRounded(psi, diag, max_cut_value); ASSERT_EQ(histo.size(), (int)(floor(max_cut_value))+1); double average=0; for (int j=0; j<histo.size(); ++j) average += double(j)*histo[j]; // The expval will be within less than 1.0 of the actual since the cutvals are rounded down to nearest 1.0. ASSERT_TRUE( (abs(expectation - average) )<=1.0+1e-7); // Histogram for rounded cutvals and check if it matches expval to the tolerance. double bin_width = 0.1; std::vector<double> histo2 = qaoa::GetHistogramFromCostFunctionWithWeightsBinned(psi, diag, max_cut_value, bin_width); ASSERT_EQ(histo2.size(), (int)(ceil(max_cut_value / bin_width)) + 1); average = 0.0; for (int j=0; j<histo2.size(); ++j) average += double(j)*bin_width*histo2[j]; // The expval will be within less than bin_width of the actual since the cutvals are rounded down to the bin_width. ASSERT_TRUE( (abs(expectation - average) )<=bin_width+1e-7); } ////////////////////////////////////////////////////////////////////////////// #endif // header guard EXTRA_FEATURES_TEST_HPP
6,648
2,437
#include <fstream> #include <cstring> #include <cassert> #include "string.hpp" #include "../constants.hpp" void String::copy_from(const String& other) { this->capacity = this->get_needed_capacity(other.value); this->set_value(other.value); this->len = other.len; } void String::free_memory() { if (this->value != nullptr) { delete[] this->value; this->value = nullptr; } } String::String() { this->capacity = BUFFER_SIZE; this->value = new char[this->capacity](); this->len = 0; } String::String(const char* str) { assert(str != nullptr); this->capacity = this->get_needed_capacity(str); this->value = new char[this->capacity](); strcpy(this->value, str); this->len = strlen(this->value); } String::String(const String& other) { this->capacity = other.capacity; this->value = nullptr; this->set_value(other.value); this->len = other.len; } String& String::operator=(const String& other) { if (this == &other) { return *this; } this->free_memory(); this->copy_from(other); return *this; } String& String::operator=(const char* str) { assert(str != nullptr); this->set_value(str); return *this; } String::~String() { this->free_memory(); } void String::set_value(const char* value) { assert(value != nullptr); const int value_len = strlen(value); this->capacity = this->get_needed_capacity(value); this->len = value_len; char* new_value = new char[this->capacity](); strcpy(new_value, value); if (this->value != nullptr) { delete[] this->value; } this->value = new_value; this->len = strlen(this->value); } void String::increase_capacity() { this->capacity *= 2; char* value_new_capacity = new char[this->capacity](); strcpy(value_new_capacity, this->value); delete[] this->value; this->value = value_new_capacity; } int String::get_needed_capacity(const char* string) const { int temp_capacity = BUFFER_SIZE; int str_len = strlen(string); if (str_len == 0) { return temp_capacity; } while (temp_capacity < str_len) { temp_capacity *= 2; } return temp_capacity; } std::ostream& operator<<(std::ostream& o_stream, const String& string) { o_stream << string.value; return o_stream; } char String::operator[](int i) const { assert(i >= 0); if (i >= this->len) { return '\0'; } return this->value[i]; } void String::input(std::istream& i_stream, bool whole_line) { char curr_char; int string_len = 0; int string_capacity = BUFFER_SIZE; char* new_string_value = new char[string_capacity](); if (i_stream.peek() == EOF || i_stream.peek() == '\n') { delete[] new_string_value; this->set_value(""); if (std::cin.peek() == '\n') { std::cin.get(); } return; } // skip whitespace while (i_stream.peek() == ' ') { i_stream.get(); } do { curr_char = i_stream.get(); if (!whole_line && curr_char == ' ') { break; } if (curr_char == '\n' || curr_char == EOF) { break; } if (string_len + 1 >= string_capacity) { char* bigger = new char[string_capacity *= 2](); strcpy(bigger, new_string_value); delete[] new_string_value; new_string_value = bigger; } new_string_value[string_len++] = curr_char; } while (i_stream.peek() != '\n'); new_string_value[string_len] = '\0'; this->set_value(new_string_value); delete[] new_string_value; } std::istream& operator>>(std::istream& i_stream, String& string) { string.input(i_stream); return i_stream; } bool operator==(const String& left_string, const String& right_string) { return strcmp(left_string.value, right_string.value) == 0; } bool operator==(const String& string, const char* c_string) { return strcmp(string.value, c_string) == 0; } bool operator==(const char* c_string, const String& string) { return strcmp(c_string, string.value) == 0; } bool operator!=(const String& left_string, const String& right_string) { return !(left_string == right_string); } bool operator!=(const String& string, const char* c_string) { return !(string == c_string); } bool operator!=(const char* c_string, const String& string) { return !(c_string == string); } String& String::operator+=(const char new_char) { if (this->len + 1 >= this->capacity) { this->increase_capacity(); } this->value[len] = new_char; if (new_char != '\0') { ++len; } return *this; } String& String::operator+=(const char* to_append) { assert(to_append != nullptr); const int to_append_len = strlen(to_append); if (to_append_len < 1) { return *this; } for (int i = 0; i < to_append_len; ++i) { *this += to_append[i]; } return *this; } String& String::operator+=(const String to_append) { const int to_append_len = to_append.get_len(); if (to_append_len < 1) { return *this; } for (int i = 0; i < to_append_len; ++i) { *this += to_append[i]; } return *this; } int String::get_len() const { return this->len; } bool String::is_valid_number(bool check_for_int_only) const { const int len = this->get_len(); bool found_dot = this->value[0] == '.'; bool is_valid = true; if (len < 1) { is_valid = false; } if (this->value[0] != '-' && this->value[0] != '+' && !isdigit(this->value[0])) { is_valid = false; } int beg_index = this->value[0] == '-' || this->value[0] == '+'; for (int i = beg_index; i < len && is_valid; ++i) { if (!isdigit(this->value[i])) { if (this->value[i] == '.') { // Found 2nd dot -> invalid if (found_dot) { is_valid = false; } else { found_dot = true; } } else { is_valid = false; } } } if (check_for_int_only && found_dot) { is_valid = false; } return is_valid; } double String::to_double() const { if (!this->is_valid_number()) { return -__DBL_MAX__; } double result = 0.0; int len = this->get_len(); bool has_sign = this->value[0] == '+' || this->value[0] == '-'; bool is_int = true; int begin_index = has_sign ? 1 : 0; int i = begin_index; // skip beginning zeros while (this->value[i] == '0') { ++i; } // get integer part while (i < len) { if (this->value[i] == '.') { is_int = false; ++i; break; } result *= 10; result += (int)(this->value[i] - '0'); ++i; } // get fractional part double divide_by = 10; // know decimal places so to round number int dec_places = 0; if (!is_int) { while (i < len && dec_places < 2) { result += (double)(this->value[i] - '0') / divide_by; divide_by *= 10; ++dec_places; ++i; } } if (dec_places >= 2 && (int)(this->value[i] - '0') >= 5) { result += 10 / divide_by; } bool is_negative = has_sign && this->value[0] == '-'; return is_negative ? -result : result; } int String::to_int() const { return (int)this->to_double(); } bool String::read_from_bin(std::ifstream& if_stream) { if (if_stream.eof()) { return false; } int value_len; if (!if_stream.read((char*)&value_len, sizeof(int))) { return false; } char* new_value = new char[value_len + 1]; if (!if_stream.read(new_value, value_len)) { delete[] new_value; return false; } new_value[value_len] = '\0'; this->set_value(new_value); delete[] new_value; return true; } bool String::write_to_bin(std::ofstream& of_stream) const { if (this->len < 1) { return false; } if (!of_stream.write((char*)&this->len, sizeof(int))) { return false; } if (!of_stream.write(this->value, this->len)) { return false; } return true; } const char* String::to_c_string() const { return this->value; }
8,667
3,108
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" #include "beatsaber-hook/shared/utils/byref.hpp" // Including type: System.ValueType #include "System/ValueType.hpp" // Including type: UnityEngine.TextCore.LowLevel.GlyphAdjustmentRecord #include "UnityEngine/TextCore/LowLevel/GlyphAdjustmentRecord.hpp" // Including type: UnityEngine.TextCore.LowLevel.FontFeatureLookupFlags #include "UnityEngine/TextCore/LowLevel/FontFeatureLookupFlags.hpp" // Completed includes // Type namespace: UnityEngine.TextCore.LowLevel namespace UnityEngine::TextCore::LowLevel { // Forward declaring type: GlyphPairAdjustmentRecord struct GlyphPairAdjustmentRecord; } #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" DEFINE_IL2CPP_ARG_TYPE(::UnityEngine::TextCore::LowLevel::GlyphPairAdjustmentRecord, "UnityEngine.TextCore.LowLevel", "GlyphPairAdjustmentRecord"); // Type namespace: UnityEngine.TextCore.LowLevel namespace UnityEngine::TextCore::LowLevel { // Size: 0x2C #pragma pack(push, 1) // WARNING Layout: Sequential may not be correctly taken into account! // Autogenerated type: UnityEngine.TextCore.LowLevel.GlyphPairAdjustmentRecord // [TokenAttribute] Offset: FFFFFFFF // [UsedByNativeCodeAttribute] Offset: 5BC52C // [DebuggerDisplayAttribute] Offset: 5BC52C struct GlyphPairAdjustmentRecord/*, public ::System::ValueType*/ { public: public: // [NativeNameAttribute] Offset: 0x5BD1F8 // private UnityEngine.TextCore.LowLevel.GlyphAdjustmentRecord m_FirstAdjustmentRecord // Size: 0x14 // Offset: 0x0 ::UnityEngine::TextCore::LowLevel::GlyphAdjustmentRecord m_FirstAdjustmentRecord; // Field size check static_assert(sizeof(::UnityEngine::TextCore::LowLevel::GlyphAdjustmentRecord) == 0x14); // [NativeNameAttribute] Offset: 0x5BD244 // private UnityEngine.TextCore.LowLevel.GlyphAdjustmentRecord m_SecondAdjustmentRecord // Size: 0x14 // Offset: 0x14 ::UnityEngine::TextCore::LowLevel::GlyphAdjustmentRecord m_SecondAdjustmentRecord; // Field size check static_assert(sizeof(::UnityEngine::TextCore::LowLevel::GlyphAdjustmentRecord) == 0x14); // private UnityEngine.TextCore.LowLevel.FontFeatureLookupFlags m_FeatureLookupFlags // Size: 0x4 // Offset: 0x28 ::UnityEngine::TextCore::LowLevel::FontFeatureLookupFlags m_FeatureLookupFlags; // Field size check static_assert(sizeof(::UnityEngine::TextCore::LowLevel::FontFeatureLookupFlags) == 0x4); public: // Creating value type constructor for type: GlyphPairAdjustmentRecord constexpr GlyphPairAdjustmentRecord(::UnityEngine::TextCore::LowLevel::GlyphAdjustmentRecord m_FirstAdjustmentRecord_ = {}, ::UnityEngine::TextCore::LowLevel::GlyphAdjustmentRecord m_SecondAdjustmentRecord_ = {}, ::UnityEngine::TextCore::LowLevel::FontFeatureLookupFlags m_FeatureLookupFlags_ = {}) noexcept : m_FirstAdjustmentRecord{m_FirstAdjustmentRecord_}, m_SecondAdjustmentRecord{m_SecondAdjustmentRecord_}, m_FeatureLookupFlags{m_FeatureLookupFlags_} {} // Creating interface conversion operator: operator ::System::ValueType operator ::System::ValueType() noexcept { return *reinterpret_cast<::System::ValueType*>(this); } // Get instance field reference: private UnityEngine.TextCore.LowLevel.GlyphAdjustmentRecord m_FirstAdjustmentRecord ::UnityEngine::TextCore::LowLevel::GlyphAdjustmentRecord& dyn_m_FirstAdjustmentRecord(); // Get instance field reference: private UnityEngine.TextCore.LowLevel.GlyphAdjustmentRecord m_SecondAdjustmentRecord ::UnityEngine::TextCore::LowLevel::GlyphAdjustmentRecord& dyn_m_SecondAdjustmentRecord(); // Get instance field reference: private UnityEngine.TextCore.LowLevel.FontFeatureLookupFlags m_FeatureLookupFlags ::UnityEngine::TextCore::LowLevel::FontFeatureLookupFlags& dyn_m_FeatureLookupFlags(); // public UnityEngine.TextCore.LowLevel.GlyphAdjustmentRecord get_firstAdjustmentRecord() // Offset: 0x12E96BC ::UnityEngine::TextCore::LowLevel::GlyphAdjustmentRecord get_firstAdjustmentRecord(); // public UnityEngine.TextCore.LowLevel.GlyphAdjustmentRecord get_secondAdjustmentRecord() // Offset: 0x12E96D0 ::UnityEngine::TextCore::LowLevel::GlyphAdjustmentRecord get_secondAdjustmentRecord(); }; // UnityEngine.TextCore.LowLevel.GlyphPairAdjustmentRecord #pragma pack(pop) static check_size<sizeof(GlyphPairAdjustmentRecord), 40 + sizeof(::UnityEngine::TextCore::LowLevel::FontFeatureLookupFlags)> __UnityEngine_TextCore_LowLevel_GlyphPairAdjustmentRecordSizeCheck; static_assert(sizeof(GlyphPairAdjustmentRecord) == 0x2C); } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: UnityEngine::TextCore::LowLevel::GlyphPairAdjustmentRecord::get_firstAdjustmentRecord // Il2CppName: get_firstAdjustmentRecord template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::UnityEngine::TextCore::LowLevel::GlyphAdjustmentRecord (UnityEngine::TextCore::LowLevel::GlyphPairAdjustmentRecord::*)()>(&UnityEngine::TextCore::LowLevel::GlyphPairAdjustmentRecord::get_firstAdjustmentRecord)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(UnityEngine::TextCore::LowLevel::GlyphPairAdjustmentRecord), "get_firstAdjustmentRecord", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: UnityEngine::TextCore::LowLevel::GlyphPairAdjustmentRecord::get_secondAdjustmentRecord // Il2CppName: get_secondAdjustmentRecord template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::UnityEngine::TextCore::LowLevel::GlyphAdjustmentRecord (UnityEngine::TextCore::LowLevel::GlyphPairAdjustmentRecord::*)()>(&UnityEngine::TextCore::LowLevel::GlyphPairAdjustmentRecord::get_secondAdjustmentRecord)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(UnityEngine::TextCore::LowLevel::GlyphPairAdjustmentRecord), "get_secondAdjustmentRecord", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } };
6,244
2,035
// Copyright (c) 2017 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/ui/win/atom_desktop_native_widget_aura.h" #include "shell/browser/ui/win/atom_desktop_window_tree_host_win.h" #include "ui/views/corewm/tooltip_controller.h" #include "ui/wm/public/tooltip_client.h" namespace electron { AtomDesktopNativeWidgetAura::AtomDesktopNativeWidgetAura( NativeWindowViews* native_window_view) : views::DesktopNativeWidgetAura(native_window_view->widget()), native_window_view_(native_window_view) { GetNativeWindow()->SetName("AtomDesktopNativeWidgetAura"); // This is to enable the override of OnWindowActivated wm::SetActivationChangeObserver(GetNativeWindow(), this); } void AtomDesktopNativeWidgetAura::InitNativeWidget( const views::Widget::InitParams& params) { views::Widget::InitParams modified_params = params; desktop_window_tree_host_ = new AtomDesktopWindowTreeHostWin( native_window_view_, static_cast<views::DesktopNativeWidgetAura*>(params.native_widget)); modified_params.desktop_window_tree_host = desktop_window_tree_host_; views::DesktopNativeWidgetAura::InitNativeWidget(modified_params); } void AtomDesktopNativeWidgetAura::Activate() { // Activate can cause the focused window to be blurred so only // call when the window being activated is visible. This prevents // hidden windows from blurring the focused window when created. if (IsVisible()) views::DesktopNativeWidgetAura::Activate(); } void AtomDesktopNativeWidgetAura::OnWindowActivated( wm::ActivationChangeObserver::ActivationReason reason, aura::Window* gained_active, aura::Window* lost_active) { views::DesktopNativeWidgetAura::OnWindowActivated(reason, gained_active, lost_active); if (lost_active != nullptr) { auto* tooltip_controller = static_cast<views::corewm::TooltipController*>( wm::GetTooltipClient(lost_active->GetRootWindow())); // This will cause the tooltip to be hidden when a window is deactivated, // as it should be. // TODO(brenca): Remove this fix when the chromium issue is fixed. // crbug.com/724538 if (tooltip_controller != nullptr) tooltip_controller->OnCancelMode(nullptr); } } } // namespace electron
2,370
713
/** * @author Ryan Benasutti, WPI * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #pragma once #include "okapi/api/chassis/controller/chassisControllerIntegrated.hpp" #include "okapi/api/chassis/controller/chassisControllerPid.hpp" #include "okapi/api/chassis/controller/chassisScales.hpp" #include "okapi/api/chassis/model/readOnlyChassisModel.hpp" #include "okapi/api/chassis/model/skidSteerModel.hpp" #include "okapi/api/chassis/model/threeEncoderSkidSteerModel.hpp" #include "okapi/api/chassis/model/xDriveModel.hpp" #include "okapi/impl/chassis/controller/chassisControllerFactory.hpp" #include "okapi/impl/chassis/model/chassisModelFactory.hpp" #include "okapi/api/control/async/asyncLinearMotionProfileController.hpp" #include "okapi/api/control/async/asyncMotionProfileController.hpp" #include "okapi/api/control/async/asyncPosIntegratedController.hpp" #include "okapi/api/control/async/asyncPosPidController.hpp" #include "okapi/api/control/async/asyncVelIntegratedController.hpp" #include "okapi/api/control/async/asyncVelPidController.hpp" #include "okapi/api/control/async/asyncWrapper.hpp" #include "okapi/api/control/controllerInput.hpp" #include "okapi/api/control/controllerOutput.hpp" #include "okapi/api/control/iterative/iterativeMotorVelocityController.hpp" #include "okapi/api/control/iterative/iterativePosPidController.hpp" #include "okapi/api/control/iterative/iterativeVelPidController.hpp" #include "okapi/api/control/util/controllerRunner.hpp" #include "okapi/api/control/util/flywheelSimulator.hpp" #include "okapi/api/control/util/pidTuner.hpp" #include "okapi/api/control/util/settledUtil.hpp" #include "okapi/impl/control/async/asyncControllerFactory.hpp" #include "okapi/impl/control/iterative/iterativeControllerFactory.hpp" #include "okapi/impl/control/util/controllerRunnerFactory.hpp" #include "okapi/impl/control/util/pidTunerFactory.hpp" #include "okapi/impl/control/util/settledUtilFactory.hpp" #include "okapi/api/device/rotarysensor/continuousRotarySensor.hpp" #include "okapi/api/device/rotarysensor/rotarySensor.hpp" #include "okapi/impl/device/adiUltrasonic.hpp" #include "okapi/impl/device/button/adiButton.hpp" #include "okapi/impl/device/button/controllerButton.hpp" #include "okapi/impl/device/controller.hpp" #include "okapi/impl/device/motor/motor.hpp" #include "okapi/impl/device/motor/motorGroup.hpp" #include "okapi/impl/device/rotarysensor/adiEncoder.hpp" #include "okapi/impl/device/rotarysensor/adiGyro.hpp" #include "okapi/impl/device/rotarysensor/integratedEncoder.hpp" #include "okapi/impl/device/rotarysensor/potentiometer.hpp" #include "okapi/impl/device/vision.hpp" #include "okapi/api/filter/averageFilter.hpp" #include "okapi/api/filter/composableFilter.hpp" #include "okapi/api/filter/demaFilter.hpp" #include "okapi/api/filter/ekfFilter.hpp" #include "okapi/api/filter/emaFilter.hpp" #include "okapi/api/filter/filter.hpp" #include "okapi/api/filter/filteredControllerInput.hpp" #include "okapi/api/filter/medianFilter.hpp" #include "okapi/api/filter/passthroughFilter.hpp" #include "okapi/api/filter/velMath.hpp" #include "okapi/impl/filter/velMathFactory.hpp" #include "okapi/api/units/QAcceleration.hpp" #include "okapi/api/units/QAngle.hpp" #include "okapi/api/units/QAngularAcceleration.hpp" #include "okapi/api/units/QAngularJerk.hpp" #include "okapi/api/units/QAngularSpeed.hpp" #include "okapi/api/units/QArea.hpp" #include "okapi/api/units/QForce.hpp" #include "okapi/api/units/QFrequency.hpp" #include "okapi/api/units/QJerk.hpp" #include "okapi/api/units/QLength.hpp" #include "okapi/api/units/QMass.hpp" #include "okapi/api/units/QPressure.hpp" #include "okapi/api/units/QSpeed.hpp" #include "okapi/api/units/QTime.hpp" #include "okapi/api/units/QTorque.hpp" #include "okapi/api/units/QVolume.hpp" #include "okapi/api/util/abstractRate.hpp" #include "okapi/api/util/abstractTimer.hpp" #include "okapi/api/util/mathUtil.hpp" #include "okapi/api/util/supplier.hpp" #include "okapi/api/util/timeUtil.hpp" #include "okapi/impl/util/rate.hpp" #include "okapi/impl/util/timeUtilFactory.hpp" #include "okapi/impl/util/timer.hpp"
4,268
1,598
// // Copyright (c) 2018 The nanoFramework project contributors // See LICENSE file in the project root for full license information. // #include <nanoHAL.h> #include <nanoHAL_v2.h> #include <nanoWeak.h> #include "Esp32_os.h" // NVS parameters for Interface config #define NVS_NAMESPACE "nanoF" //#define DEBUG_CONFIG 1 #ifdef DEBUG_CONFIG void PrintBlock( char * pBlock, int bsize ) { char * pCurrStart; char * pCurrPos; char * pCurrEnd; char * pCurrEndBlock = pBlock + bsize; pCurrStart = pBlock; while( pCurrStart <= pCurrEndBlock) { pCurrPos = pCurrStart; pCurrEnd = pCurrStart + 32; while(pCurrPos < pCurrEnd && pCurrPos <= pCurrEndBlock) { ets_printf( "%02X ", *pCurrPos ); pCurrPos++; } ets_printf( " " ); pCurrPos = pCurrStart; while(pCurrPos < pCurrEnd && pCurrPos <= pCurrEndBlock) { if ( *pCurrPos < 32 ) ets_printf( "." ); else ets_printf( "%c", *pCurrPos ); pCurrPos++; } ets_printf( "\n" ); pCurrStart = pCurrEnd; } } #endif // initialization of configuration manager // provided as weak so it can be replaced at target level, if required because of the target implementing the storage with a mechanism other then saving to flash void ConfigurationManager_Initialize() { // enumerate the blocks ConfigurationManager_EnumerateConfigurationBlocks(); }; // Allocate HAL_CONFIGURATION_NETWORK block void ConfigurationManager_allocate_network( uint32_t configCount ) { uint32_t sizeOfNetworkInterfaceConfigs = offsetof(HAL_CONFIGURATION_NETWORK, Configs) + configCount * sizeof(HAL_Configuration_NetworkInterface *); g_TargetConfiguration.NetworkInterfaceConfigs = (HAL_CONFIGURATION_NETWORK*)platform_malloc(sizeOfNetworkInterfaceConfigs); g_TargetConfiguration.NetworkInterfaceConfigs->Count = configCount; } // Allocate HAL_CONFIGURATION_WIRELESS80211 block void ConfigurationManager_allocate_wireless( uint32_t configCount ) { uint32_t sizeOfWireless80211Configs = offsetof(HAL_CONFIGURATION_NETWORK_WIRELESS80211, Configs) + configCount * sizeof(HAL_Configuration_Wireless80211 *); g_TargetConfiguration.Wireless80211Configs = (HAL_CONFIGURATION_NETWORK_WIRELESS80211*)platform_malloc(sizeOfWireless80211Configs); g_TargetConfiguration.Wireless80211Configs->Count = configCount; } // Enumerates the configuration blocks from the configuration flash sector // it's implemented with 'weak' attribute so it can be replaced at target level if a different persistance mechanism is used void ConfigurationManager_EnumerateConfigurationBlocks() { // Fix adapter counts - will get these from NVS // Still need to do wireless AP int networkCount = 3; // Esp32 has 3 network interfaces, Ethernet, Wireless Station & Wireless APn int wirelessCount = 2; ConfigurationManager_allocate_network( networkCount ); ConfigurationManager_allocate_wireless( wirelessCount ); for( int configIndex = 0; configIndex < networkCount; configIndex++) { g_TargetConfiguration.NetworkInterfaceConfigs->Configs[configIndex] = (HAL_Configuration_NetworkInterface*)platform_malloc(sizeof(HAL_Configuration_NetworkInterface)); ConfigurationManager_GetConfigurationBlock(g_TargetConfiguration.NetworkInterfaceConfigs->Configs[configIndex], DeviceConfigurationOption_Network, configIndex); } for( int configIndex = 0; configIndex < wirelessCount; configIndex++) { g_TargetConfiguration.Wireless80211Configs->Configs[configIndex] = (HAL_Configuration_Wireless80211*)platform_malloc(sizeof(HAL_Configuration_Wireless80211)); ConfigurationManager_GetConfigurationBlock( g_TargetConfiguration.Wireless80211Configs->Configs[configIndex], DeviceConfigurationOption_Wireless80211Network, configIndex); } } // Default initialisation of wireless config blocks for ESP32 targets void InitialiseWirelessDefaultConfig(HAL_Configuration_Wireless80211 * pconfig, uint32_t configurationIndex) { memset( pconfig, 0, sizeof(HAL_Configuration_Wireless80211)); pconfig->Id = configurationIndex; switch(configurationIndex) { case 0: // Wireless Station // test default data for AP // hal_strcpy_s( (char*)pconfig->Ssid, sizeof(pconfig->Ssid), "myssid" ); // hal_strcpy_s( (char*)pconfig->Password, sizeof(pconfig->Password), "mypassphase" ); pconfig->Authentication = AuthenticationType_WPA2; pconfig->Encryption = EncryptionType_WPA2; break; case 1: // Wireless AP // Build AP default ssid based on MAC addr uint8_t mac[6]; esp_efuse_mac_get_custom(mac); hal_strcpy_s( (char *)pconfig->Ssid, sizeof(pconfig->Ssid), "nano_"); char * pMac = (char*)pconfig->Ssid + 5; for( int index=0; index < 6; index++) { sprintf( pMac, "%02X", (int)mac[index] ); pMac+=2; } *pMac = 0; hal_strcpy_s( (char *)pconfig->Password, sizeof(pconfig->Password), "password"); pconfig->Authentication = AuthenticationType_WPA2; pconfig->Encryption = EncryptionType_WPA2; break; } } // Default initialisation of Network interface config blocks for ESP32 targets void InitialiseNetworkDefaultConfig(HAL_Configuration_NetworkInterface * pconfig, uint32_t configurationIndex) { memset( pconfig, 0, sizeof(HAL_Configuration_NetworkInterface)); switch(configurationIndex) { case 0: // Wireless Station pconfig->InterfaceType = NetworkInterfaceType_Wireless80211; pconfig->StartupAddressMode = AddressMode_DHCP; pconfig->SpecificConfigId = 0; break; case 1: // Wireless AP pconfig->InterfaceType = NetworkInterfaceType_Wireless80211; pconfig->StartupAddressMode = AddressMode_Static; pconfig->SpecificConfigId = 1; // Set default address 192.168.1.1 //pconfig->IPv4Address //pconfig->IPv4NetMask // pconfig->IPv4GatewayAddress break; case 2: // Ethernet pconfig->InterfaceType = NetworkInterfaceType_Ethernet; pconfig->StartupAddressMode = AddressMode_DHCP; break; } } // Gets a configuration block from the configuration block stored in the NVS block, // maybe better to store each config item under a separate key which would work better if config block changes bool ConfigurationManager_GetConfigurationBlock(void* configurationBlock, DeviceConfigurationOption configuration, uint32_t configurationIndex) { bool result = FALSE; nvs_handle out_handle; size_t blobSize = 0; char configName[10]; #ifdef DEBUG_CONFIG ets_printf("GetConfig %d, %d\n", (int)configuration, configurationIndex); #endif // validate if the requested block exists if(configuration == DeviceConfigurationOption_Network) { if(g_TargetConfiguration.NetworkInterfaceConfigs->Count == 0 || (configurationIndex + 1) > g_TargetConfiguration.NetworkInterfaceConfigs->Count) { #ifdef DEBUG_CONFIG ets_printf("GetConfig CN exit false\n"); #endif return FALSE; } // set blob size blobSize = sizeof(HAL_Configuration_NetworkInterface); configName[0] = 'N'; } else if(configuration == DeviceConfigurationOption_Wireless80211Network) { if(g_TargetConfiguration.Wireless80211Configs->Count == 0 || (configurationIndex + 1) > g_TargetConfiguration.Wireless80211Configs->Count) { #ifdef DEBUG_CONFIG ets_printf("GetConfig WN exit false\n"); #endif return FALSE; } // set blob size blobSize = sizeof(HAL_Configuration_Wireless80211); configName[0] = 'W'; } // Anything to get if (blobSize != 0 ) { // Open NVS storage using NanoFramework namespace esp_err_t ret = nvs_open( NVS_NAMESPACE, NVS_READWRITE, &out_handle); if ( ret == ESP_OK ) { bool storeConfig = false; itoa(configurationIndex, configName+1, 10); // copy the config block content to the pointer in the argument ret = nvs_get_blob(out_handle, configName, (void *)configurationBlock, &blobSize); if (ret != ESP_OK) { if ( configuration == DeviceConfigurationOption_Wireless80211Network ) { InitialiseWirelessDefaultConfig((HAL_Configuration_Wireless80211 *)configurationBlock,configurationIndex); storeConfig = true; } else if ( configuration == DeviceConfigurationOption_Network ) { InitialiseNetworkDefaultConfig((HAL_Configuration_NetworkInterface *)configurationBlock,configurationIndex); storeConfig = true; } else { // If not found just return initialized block // memset( configurationBlock, 0, blobSize); } } #ifdef DEBUG_CONFIG PrintBlock( (char*)configurationBlock, blobSize); #endif result = TRUE; nvs_close(out_handle); if ( storeConfig ) { ConfigurationManager_StoreConfigurationBlock(configurationBlock, configuration, configurationIndex, blobSize); } } } #ifdef DEBUG_CONFIG ets_printf("GetConfig exit %d\n", result); #endif return result; } bool StoreConfigBlock(char ConfigType, uint32_t configurationIndex, void * pConfigBlock, size_t blobSize) { nvs_handle out_handle; char configName[10]; bool result = false; configName[0] = ConfigType; // copy the config block content to the pointer in the argument esp_err_t ret = nvs_open( NVS_NAMESPACE, NVS_READWRITE, &out_handle); if ( ret == ESP_OK ) { itoa(configurationIndex, configName+1, 10); ret = nvs_set_blob(out_handle, configName, pConfigBlock, blobSize); if ( ret == ESP_OK ) { ret = nvs_commit(out_handle); if (ret == ESP_OK) result = true; } nvs_close(out_handle); } return result; } // Stores the network configuration block to the EPS32 storage bool ConfigurationManager_StoreConfigurationBlock(void* configurationBlock, DeviceConfigurationOption configuration, uint32_t configurationIndex, uint32_t blockSize) { bool result = false; bool requiresEnumeration = false; size_t blobSize = 0; char ConfigType; #ifdef DEBUG_CONFIG ets_printf("StoreConfig %d, %d", (int)configuration, configurationIndex); #endif if(configuration == DeviceConfigurationOption_Network) { // set blob size blobSize = sizeof(HAL_Configuration_NetworkInterface); ConfigType = 'N'; } else if(configuration == DeviceConfigurationOption_Wireless80211Network) { // set blob size blobSize = sizeof(HAL_Configuration_Wireless80211); ConfigType = 'W'; } else if(configuration == DeviceConfigurationOption_All) { // All configuration blocks in one block // Separate and update #ifdef DEBUG_CONFIG ets_printf( "Block size %d\n",blockSize); ets_printf( "sizeof HAL_Configuration_NetworkInterface %d\n", sizeof(HAL_Configuration_NetworkInterface)); ets_printf( "sizeof HAL_Configuration_Wireless80211 %d\n", sizeof(HAL_Configuration_Wireless80211)); #endif configurationIndex = 0; char * pConfig = (char *)configurationBlock; while( pConfig < (pConfig + blockSize) ) { // Network interface block ? if ( *pConfig == 'C') { HAL_Configuration_NetworkInterface * pNetConfig = (HAL_Configuration_NetworkInterface*)pConfig; pConfig += sizeof(HAL_Configuration_NetworkInterface); result = StoreConfigBlock( 'N', configurationIndex, (void*)pNetConfig, sizeof(HAL_Configuration_NetworkInterface) ); configurationIndex++; #ifdef DEBUG_CONFIG ets_printf("Network block %X %X ret:%d\n", pNetConfig->InterfaceType, pNetConfig->SpecificConfigId, result); PrintBlock( (char *)pNetConfig, sizeof(HAL_Configuration_NetworkInterface) ); #endif } // Wireless block ? else if (*pConfig == 'W') { HAL_Configuration_Wireless80211 * pWirelessConfig = (HAL_Configuration_Wireless80211*)pConfig; pConfig += sizeof(HAL_Configuration_Wireless80211); result = StoreConfigBlock( 'W', pWirelessConfig->Id, (void*)pWirelessConfig, sizeof(HAL_Configuration_Wireless80211) ); #ifdef DEBUG_CONFIG ets_printf("Wireless block %d ssid:%s password:%s ret:%d\n", pWirelessConfig->Id, pWirelessConfig->Ssid, pWirelessConfig->Password, result); PrintBlock( (char *)pWirelessConfig, sizeof(HAL_Configuration_Wireless80211) ); #endif } else break; } return result; } // Anything to save if (blobSize != 0 ) { result = StoreConfigBlock( ConfigType, configurationIndex, configurationBlock, blobSize); } if(requiresEnumeration) { // perform enumeration of configuration blocks ConfigurationManager_EnumerateConfigurationBlocks(); } #ifdef DEBUG_CONFIG ets_printf("StoreConfig exit %d", result); #endif return result; } // Updates a configuration block in the configuration flash sector bool ConfigurationManager_UpdateConfigurationBlock(void* configurationBlock, DeviceConfigurationOption configuration, uint32_t configurationIndex) { return ConfigurationManager_StoreConfigurationBlock(configurationBlock, configuration, configurationIndex, 0); }
14,279
4,152
/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include <stdlib.h> #include "gtest/gtest.h" #include "typedefs.h" #include "vad_unittest.h" extern "C" { #include "vad_core.h" } namespace { TEST_F(VadTest, InitCore) { // Test WebRtcVad_InitCore(). VadInstT* self = reinterpret_cast<VadInstT*>(malloc(sizeof(VadInstT))); // NULL pointer test. EXPECT_EQ(-1, WebRtcVad_InitCore(NULL)); // Verify return = 0 for non-NULL pointer. EXPECT_EQ(0, WebRtcVad_InitCore(self)); // Verify init_flag is set. EXPECT_EQ(42, self->init_flag); free(self); } TEST_F(VadTest, set_mode_core) { VadInstT* self = reinterpret_cast<VadInstT*>(malloc(sizeof(VadInstT))); // TODO(bjornv): Add NULL pointer check if we take care of it in // vad_core.c ASSERT_EQ(0, WebRtcVad_InitCore(self)); // Test WebRtcVad_set_mode_core(). // Invalid modes should return -1. EXPECT_EQ(-1, WebRtcVad_set_mode_core(self, -1)); EXPECT_EQ(-1, WebRtcVad_set_mode_core(self, 1000)); // Valid modes should return 0. for (size_t j = 0; j < kModesSize; ++j) { EXPECT_EQ(0, WebRtcVad_set_mode_core(self, kModes[j])); } free(self); } TEST_F(VadTest, CalcVad) { VadInstT* self = reinterpret_cast<VadInstT*>(malloc(sizeof(VadInstT))); int16_t speech[kMaxFrameLength]; // TODO(bjornv): Add NULL pointer check if we take care of it in // vad_core.c // Test WebRtcVad_CalcVadXXkhz() // Verify that all zeros in gives VAD = 0 out. memset(speech, 0, sizeof(speech)); ASSERT_EQ(0, WebRtcVad_InitCore(self)); for (size_t j = 0; j < kFrameLengthsSize; ++j) { if (ValidRatesAndFrameLengths(8000, kFrameLengths[j])) { EXPECT_EQ(0, WebRtcVad_CalcVad8khz(self, speech, kFrameLengths[j])); } if (ValidRatesAndFrameLengths(16000, kFrameLengths[j])) { EXPECT_EQ(0, WebRtcVad_CalcVad16khz(self, speech, kFrameLengths[j])); } if (ValidRatesAndFrameLengths(32000, kFrameLengths[j])) { EXPECT_EQ(0, WebRtcVad_CalcVad32khz(self, speech, kFrameLengths[j])); } } // Construct a speech signal that will trigger the VAD in all modes. It is // known that (i * i) will wrap around, but that doesn't matter in this case. for (int16_t i = 0; i < kMaxFrameLength; ++i) { speech[i] = (i * i); } for (size_t j = 0; j < kFrameLengthsSize; ++j) { if (ValidRatesAndFrameLengths(8000, kFrameLengths[j])) { EXPECT_EQ(1, WebRtcVad_CalcVad8khz(self, speech, kFrameLengths[j])); } if (ValidRatesAndFrameLengths(16000, kFrameLengths[j])) { EXPECT_EQ(1, WebRtcVad_CalcVad16khz(self, speech, kFrameLengths[j])); } if (ValidRatesAndFrameLengths(32000, kFrameLengths[j])) { EXPECT_EQ(1, WebRtcVad_CalcVad32khz(self, speech, kFrameLengths[j])); } } free(self); } } // namespace
3,130
1,320
#include <iostream> #include <vector> #include <map> #include <fstream> #include "input.h" #include <iomanip> std::map<std::string, short int> vocab_tree(const std::vector<std::string> &v) { std::map<std::string, short int> m; for (auto &i : v) { for (int j = 1; j < i.size(); ++j) { if (m[i.substr(0, j)] != 2) { m[i.substr(0, j)] = 1; } } m[i] = 2; } return m; } int main() { std::ifstream vs; std::ifstream ps; vs.open("vocab.in"); ps.open("para.in"); if (!vs) { vs.close(); std::string vfn; std::cout << "Vocabulary file path: "; std::cin >> vfn; vs.open(vfn); } if (!ps) { ps.close(); std::string pfn; std::cout << "Paragraph file path: "; std::cin >> pfn; ps.open(pfn); } std::vector<std::string> v = read_vocab(vs); std::map<std::string, short int> vt = vocab_tree(v); std::string p = read_para(ps); std::map<std::string, int> cnt; for (int i = 0; i < p.size(); ++i) { std::string can; int j; for (j = 1; j <= p.size() - i; ++j) { if (vt[p.substr(i, j)] == 2) { can = p.substr(i, j); } else if (vt[p.substr(i, j)] != 1) { break; } } if (!can.empty()) { i += j - 3; cnt[can]++; } } int cvd = 0; for (auto &i : v) { if (cnt[i] > 0) { cvd++; std::cout << "(" << cnt[i] << ") " << i << std::endl; } else { std::cout << "(X)" << " " << i << std::endl; } } std::cout << cvd << "/" << v.size(); std::cout << " " << std::fixed << std::setprecision(1) << 1.0 * cvd / v.size() * 100 + 0.05 << "% " << std::endl; return 0; }
1,868
730
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "nacl_io/nacl_io.h" #include <stdlib.h> #include "nacl_io/kernel_intercept.h" #include "nacl_io/kernel_proxy.h" int nacl_io_init() { return ki_init(NULL); } int nacl_io_uninit() { return ki_uninit(); } int nacl_io_init_ppapi(PP_Instance instance, PPB_GetInterface get_interface) { return ki_init_ppapi(NULL, instance, get_interface); } int nacl_io_register_fs_type(const char* fs_type, fuse_operations* fuse_ops) { return ki_get_proxy()->RegisterFsType(fs_type, fuse_ops); } int nacl_io_unregister_fs_type(const char* fs_type) { return ki_get_proxy()->UnregisterFsType(fs_type); } void nacl_io_set_exit_callback(nacl_io_exit_callback_t exit_callback, void* user_data) { ki_get_proxy()->SetExitCallback(exit_callback, user_data); } void nacl_io_set_mount_callback(nacl_io_mount_callback_t callback, void* user_data) { ki_get_proxy()->SetMountCallback(callback, user_data); }
1,138
430
#include "settings.h" // class ScoreInt const int ScoreInt::kBase = 1000000; ScoreInt::ScoreInt() : val_(0) {} ScoreInt::ScoreInt(double a) : val_(llround(a * kBase)) {} ScoreInt::ScoreInt(long double a) : val_(llroundl(a * kBase)) {} ScoreInt::ScoreInt(int64_t a) : val_(a) {} ScoreInt& ScoreInt::operator=(double a) { val_ = llround(a * kBase); return *this; } ScoreInt& ScoreInt::operator=(long double a) { val_ = llroundl(a * kBase); return *this; } ScoreInt& ScoreInt::operator=(int64_t a) { val_ = a; return *this; } ScoreInt& ScoreInt::operator+=(const ScoreInt& a) { val_ += a.val_; return *this; } ScoreInt& ScoreInt::operator*=(const ScoreInt& a) { val_ = static_cast<long double>(val_) / kBase * a.val_; return *this; } ScoreInt::operator long double() const { return static_cast<long double>(val_) / kBase; } ScoreInt::operator int64_t() const { return static_cast<int64_t>(val_); } ScoreInt operator+(ScoreInt a, const ScoreInt& b) { a += b; return a; } ScoreInt operator*(ScoreInt a, const ScoreInt& b) { a += b; return a; } // Some default constuctors ProblemSettings::CompileSettings::CompileSettings() : lang(kLangNull), args() {} ProblemSettings::CustomLanguage::CustomLanguage() : compile(), as_interpreter(false), tl_a(1.), tl_b(0.), ml_a(1.), ml_b(0.), syscall_adj() {} ProblemSettings::ResultColumn::ResultColumn() : type(ProblemSettings::ResultColumn::kScoreFloat), visible(true) {} ProblemSettings::TestdataFile::TestdataFile() : id(0), path() {} ProblemSettings::CommonFile::CommonFile() : usage(ProblemSettings::CommonFile::kLib), lib_lang(kLangNull), id(0), stages{0, 0, 0, 0}, file_id(0), path() {} ProblemSettings::Testdata::Testdata() : time_lim(1000000), memory_lim(262144), file_id(), args() {} ProblemSettings::ScoreRange::ScoreRange() : score(), testdata() {} // Default problem settings ProblemSettings::ProblemSettings() : problem_id(0), is_one_stage(false), // 4-stage mode code_check_compile(), // no code checking custom_lang(), // not used execution_type(ProblemSettings::kExecNormal), // batch judge execution_times(1), // not used lib_compile(), // not used pipe_in(false), pipe_out(false), // read from file partial_judge(false), // judge whole problem evaluation_type(ProblemSettings::kEvalNormal), // normal judge evaluation_format(ProblemSettings::kEvalFormatZero), // not used password(0), // not used evaluation_compile(), // not used evaluation_columns(), // no additional columns evaluate_nonnormal(false), scoring_type(ProblemSettings::kScoringNormal), // normal scoring scoring_compile(), // not used scoring_columns(), // no additional columns file_per_testdata(2), // no additional files testdata_files(), common_files(), // not used kill_old(false), // not used custom_stage(), // not used testdata(), ranges(), timestamp(0) {}
2,956
997
/* -------------------------------------------------------- * HFN-LOAD: parse *.MSH file into HFUN data. -------------------------------------------------------- * * This program may be freely redistributed under the * condition that the copyright notices (including this * entire header) are not removed, and no compensation * is received through use of the software. Private, * research, and institutional use is free. You may * distribute modified versions of this code UNDER THE * CONDITION THAT THIS CODE AND ANY MODIFICATIONS MADE * TO IT IN THE SAME FILE REMAIN UNDER COPYRIGHT OF THE * ORIGINAL AUTHOR, BOTH SOURCE AND OBJECT CODE ARE * MADE FREELY AVAILABLE WITHOUT CHARGE, AND CLEAR * NOTICE IS GIVEN OF THE MODIFICATIONS. Distribution * of this code as part of a commercial system is * permissible ONLY BY DIRECT ARRANGEMENT WITH THE * AUTHOR. (If you are not directly supplying this * code to a customer, and you are instead telling them * how they can obtain it for free, then you are not * required to make any arrangement with me.) * * Disclaimer: Neither I nor: Columbia University, The * Massachusetts Institute of Technology, The * University of Sydney, nor The National Aeronautics * and Space Administration warrant this code in any * way whatsoever. This code is provided "as-is" to be * used at your own risk. * -------------------------------------------------------- * * Last updated: 07 Jul., 2021 * * Copyright 2013-2021 * Darren Engwirda * d.engwirda@gmail.com * https://github.com/dengwirda/ * -------------------------------------------------------- */ # pragma once # include "msh_read.hpp" # ifndef __HFN_LOAD__ # define __HFN_LOAD__ /* -------------------------------------------------------- * HFUN-FROM-JMSH: read *.JMSH file into HFUN data. -------------------------------------------------------- */ template < typename jlog_data > __normal_call iptr_type hfun_from_jmsh ( jcfg_data &_jcfg , jlog_data &_jlog , hfun_data &_hfun ) { class hfun_reader: public jmsh_reader_base { public : hfun_data *_hfun ; std::int32_t _ftag ; jmsh_kind:: enum_data _kind ; std:: size_t _ndim ; public : __normal_call hfun_reader ( hfun_data*_hsrc = nullptr ) : _hfun(_hsrc) {} /*-------------------------------- read MSHID section */ __normal_call void_type push_mshid ( std::int32_t _FTAG , jmsh_kind::enum_data _KIND ) { this->_ftag = _FTAG ; this->_kind = _KIND ; this-> _hfun->_kind = _KIND ; } /*-------------------------------- read NDIMS section */ __normal_call void_type push_ndims ( std:: size_t _NDIM ) { this->_ndim = _NDIM ; this-> _hfun->_ndim = _NDIM ; } /*-------------------------------- read POINT section */ __normal_call void_type push_point ( std:: size_t/*_ipos*/ , double *_pval , std::int32_t/*_itag*/ ) { if (this->_ndim == +2 && this->_kind == jmsh_kind::euclidean_mesh) { typename hfun_data::euclidean_mesh_2d ::node_type _ndat ; _ndat.pval(0) = _pval[0]; _ndat.pval(1) = _pval[1]; this->_hfun-> _euclidean_mesh_2d. _mesh.push_node(_ndat, false) ; } else if (this->_ndim == +3 && this->_kind == jmsh_kind::euclidean_mesh) { typename hfun_data::euclidean_mesh_3d ::node_type _ndat ; _ndat.pval(0) = _pval[0]; _ndat.pval(1) = _pval[1]; _ndat.pval(2) = _pval[2]; this->_hfun-> _euclidean_mesh_3d. _mesh.push_node(_ndat, false) ; } else if (this->_kind == jmsh_kind::ellipsoid_mesh) { typename hfun_data::ellipsoid_mesh_3d ::node_type _ndat ; _ndat.pval(0) = _pval[0]; _ndat.pval(1) = _pval[1]; _ndat.pval(2) = +0.0 ; this->_hfun-> _ellipsoid_mesh_3d. _mesh.push_node(_ndat, false) ; } } /*-------------------------------- read TRIA3 section */ __normal_call void_type push_tria3 ( std:: size_t/*_ipos*/ , std::int32_t *_node , std::int32_t/*_itag*/ ) { if (this->_ndim == +2 && this->_kind == jmsh_kind::euclidean_mesh) { typename hfun_data::euclidean_mesh_2d ::tri3_type _tdat ; _tdat.node(0) = _node[0]; _tdat.node(1) = _node[1]; _tdat.node(2) = _node[2]; this->_hfun-> _euclidean_mesh_2d. _mesh.push_tri3(_tdat, false) ; } else if (this->_kind == jmsh_kind::ellipsoid_mesh) { typename hfun_data::ellipsoid_mesh_3d ::tri3_type _tdat ; _tdat.node(0) = _node[0]; _tdat.node(1) = _node[1]; _tdat.node(2) = _node[2]; this->_hfun-> _ellipsoid_mesh_3d. _mesh.push_tri3(_tdat, false) ; } } /*-------------------------------- read TRIA4 section */ __normal_call void_type push_tria4 ( std:: size_t/*_ipos*/ , std::int32_t *_node , std::int32_t/*_itag*/ ) { if (this->_ndim == +3 && this->_kind == jmsh_kind::euclidean_mesh) { typename hfun_data::euclidean_mesh_3d ::tri4_type _tdat ; _tdat.node(0) = _node[0]; _tdat.node(1) = _node[1]; _tdat.node(2) = _node[2]; _tdat.node(3) = _node[3]; this->_hfun-> _euclidean_mesh_3d. _mesh.push_tri4(_tdat, false) ; } } /*-------------------------------- read COORD section */ __normal_call void_type push_coord ( std:: size_t _idim , std:: size_t/*_irow*/ , double _ppos ) { if (this->_ndim == +2 && this->_kind == jmsh_kind::euclidean_grid) { if (_idim == +1) { this->_hfun-> _euclidean_grid_2d. _xpos.push_tail(_ppos) ; } else if (_idim == +2) { this->_hfun-> _euclidean_grid_2d. _ypos.push_tail(_ppos) ; } } else if (this->_ndim == +3 && this->_kind == jmsh_kind::euclidean_grid) { if (_idim == +1) { this->_hfun-> _euclidean_grid_3d. _xpos.push_tail(_ppos) ; } else if (_idim == +2) { this->_hfun-> _euclidean_grid_3d. _ypos.push_tail(_ppos) ; } else if (_idim == +3) { this->_hfun-> _euclidean_grid_3d. _zpos.push_tail(_ppos) ; } } else if (this->_kind == jmsh_kind::ellipsoid_grid) { if (_idim == +1) { this->_hfun-> _ellipsoid_grid_3d. _xpos.push_tail(_ppos) ; } else if (_idim == +2) { this->_hfun-> _ellipsoid_grid_3d. _ypos.push_tail(_ppos) ; } } } /*-------------------------------- open VALUE section */ __normal_call void_type open_value ( std:: size_t _nrow , std:: size_t/*_nval*/ ) { if (this->_ndim == +2 && this->_kind == jmsh_kind::euclidean_mesh) { this->_hfun-> _euclidean_mesh_2d. _hval.set_count(_nrow) ; } else if (this->_ndim == +2 && this->_kind == jmsh_kind::euclidean_grid) { this->_hfun-> _euclidean_grid_2d. _hmat.set_count(_nrow) ; } else if (this->_ndim == +3 && this->_kind == jmsh_kind::euclidean_mesh) { this->_hfun-> _euclidean_mesh_3d. _hval.set_count(_nrow) ; } else if (this->_ndim == +3 && this->_kind == jmsh_kind::euclidean_grid) { this->_hfun-> _euclidean_grid_3d. _hmat.set_count(_nrow) ; } else if (this->_kind == jmsh_kind::ellipsoid_mesh) { this->_hfun-> _ellipsoid_mesh_3d. _hval.set_count(_nrow) ; } else if (this->_kind == jmsh_kind::ellipsoid_grid) { this->_hfun-> _ellipsoid_grid_3d. _hmat.set_count(_nrow) ; } } /*-------------------------------- read VALUE section */ __normal_call void_type push_value ( std:: size_t _ipos , float *_vval ) { if (this->_ndim == +2 && this->_kind == jmsh_kind::euclidean_mesh) { this->_hfun-> _euclidean_mesh_2d. _hval[_ipos] = *_vval; } else if (this->_ndim == +2 && this->_kind == jmsh_kind::euclidean_grid) { this->_hfun-> _euclidean_grid_2d. _hmat[_ipos] = *_vval; } else if (this->_ndim == +3 && this->_kind == jmsh_kind::euclidean_mesh) { this->_hfun-> _euclidean_mesh_3d. _hval[_ipos] = *_vval; } else if (this->_ndim == +3 && this->_kind == jmsh_kind::euclidean_grid) { this->_hfun-> _euclidean_grid_3d. _hmat[_ipos] = *_vval; } else if (this->_kind == jmsh_kind::ellipsoid_mesh) { this->_hfun-> _ellipsoid_mesh_3d. _hval[_ipos] = *_vval; } else if (this->_kind == jmsh_kind::ellipsoid_grid) { this->_hfun-> _ellipsoid_grid_3d. _hmat[_ipos] = *_vval; } } /*-------------------------------- open SLOPE section */ __normal_call void_type open_slope ( std:: size_t _nrow , std:: size_t/*_nval*/ ) { if (this->_ndim == +2 && this->_kind == jmsh_kind::euclidean_mesh) { this->_hfun-> _euclidean_mesh_2d. _dhdx.set_count(_nrow) ; } else if (this->_ndim == +2 && this->_kind == jmsh_kind::euclidean_grid) { this->_hfun-> _euclidean_grid_2d. _dhdx.set_count(_nrow) ; } else if (this->_ndim == +3 && this->_kind == jmsh_kind::euclidean_mesh) { this->_hfun-> _euclidean_mesh_3d. _dhdx.set_count(_nrow) ; } else if (this->_ndim == +3 && this->_kind == jmsh_kind::euclidean_grid) { this->_hfun-> _euclidean_grid_3d. _dhdx.set_count(_nrow) ; } else if (this->_kind == jmsh_kind::ellipsoid_mesh) { this->_hfun-> _ellipsoid_mesh_3d. _dhdx.set_count(_nrow) ; } else if (this->_kind == jmsh_kind::ellipsoid_grid) { this->_hfun-> _ellipsoid_grid_3d. _dhdx.set_count(_nrow) ; } } /*-------------------------------- read SLOPE section */ __normal_call void_type push_slope ( std:: size_t _ipos , float *_vval ) { if (this->_ndim == +2 && this->_kind == jmsh_kind::euclidean_mesh) { this->_hfun-> _euclidean_mesh_2d. _dhdx[_ipos] = *_vval; } else if (this->_ndim == +2 && this->_kind == jmsh_kind::euclidean_grid) { this->_hfun-> _euclidean_grid_2d. _dhdx[_ipos] = *_vval; } else if (this->_ndim == +3 && this->_kind == jmsh_kind::euclidean_mesh) { this->_hfun-> _euclidean_mesh_3d. _dhdx[_ipos] = *_vval; } else if (this->_ndim == +3 && this->_kind == jmsh_kind::euclidean_grid) { this->_hfun-> _euclidean_grid_3d. _dhdx[_ipos] = *_vval; } else if (this->_kind == jmsh_kind::ellipsoid_mesh) { this->_hfun-> _ellipsoid_mesh_3d. _dhdx[_ipos] = *_vval; } else if (this->_kind == jmsh_kind::ellipsoid_grid) { this->_hfun-> _ellipsoid_grid_3d. _dhdx[_ipos] = *_vval; } } /*---------------------------------- parse RADII data */ __normal_call void_type push_radii ( double *_erad ) { this->_hfun->_ellipsoid_mesh_3d. _radA = _erad[ 0] ; this->_hfun->_ellipsoid_mesh_3d. _radB = _erad[ 1] ; this->_hfun->_ellipsoid_mesh_3d. _radC = _erad[ 2] ; this->_hfun->_ellipsoid_grid_3d. _radA = _erad[ 0] ; this->_hfun->_ellipsoid_grid_3d. _radB = _erad[ 1] ; this->_hfun->_ellipsoid_grid_3d. _radC = _erad[ 2] ; } } ; /*---------------------------------- parse HFUN. file */ iptr_type _errv = __no_error ; try { jmsh_reader _jmsh ; std::ifstream _file ; _file. open( _jcfg._hfun_file, std::ifstream::in) ; if (_file.is_open() ) { _jmsh.read_file ( _file, hfun_reader(&_hfun)); } else { _jlog.push( "**parse error: file not found!\n" ) ; _errv = __file_not_located ; } _file.close (); for (auto _iter = _jmsh._errs.head(); _iter != _jmsh._errs.tend(); ++_iter ) { _jlog.push( "**parse error: " + * _iter + "\n" ) ; _errv = __invalid_argument ; } } catch (...) { _errv = __unknown_error ; } return ( _errv ) ; } /* -------------------------------------------------------- * HFUN-FROM-MSHT: read MSH_t data into HFUN data. -------------------------------------------------------- */ template < typename jlog_data > __normal_call iptr_type hfun_from_msht ( jcfg_data &_jcfg , jlog_data &_jlog , hfun_data &_hfun , jigsaw_msh_t const&_hmsh ) { iptr_type _errv = __no_error ; try { __unreferenced (_jlog) ; __unreferenced (_jcfg) ; if (_hmsh._flags == JIGSAW_EUCLIDEAN_MESH ) { if (_hmsh._vert2._size > 0) { /*--------------------------------- euclidean-mesh-2d */ _hfun._kind = jmsh_kind::euclidean_mesh ; _hfun._ndim = +2; if (_hmsh._vert2._size != _hmsh._value._size ) return __invalid_argument ; for (auto _ipos = (size_t) +0 ; _ipos != _hmsh._vert2._size ; ++_ipos ) { typename hfun_data::euclidean_mesh_2d ::node_type _ndat ; _ndat.pval(0) = _hmsh. _vert2._data[_ipos]._ppos[0]; _ndat.pval(1) = _hmsh. _vert2._data[_ipos]._ppos[1]; _hfun._euclidean_mesh_2d. _mesh.push_node(_ndat, false) ; } for (auto _ipos = (size_t) +0 ; _ipos != _hmsh._tria3._size ; ++_ipos ) { typename hfun_data::euclidean_mesh_2d ::tri3_type _tdat ; _tdat.node(0) = _hmsh. _tria3._data[_ipos]._node[0]; _tdat.node(1) = _hmsh. _tria3._data[_ipos]._node[1]; _tdat.node(2) = _hmsh. _tria3._data[_ipos]._node[2]; _hfun._euclidean_mesh_2d. _mesh.push_tri3(_tdat, false) ; } _hfun._euclidean_mesh_2d._hval. set_count(_hmsh._value._size) ; _hfun._euclidean_mesh_2d._dhdx. set_count(_hmsh._slope._size) ; for (auto _ipos = (size_t) +0 ; _ipos != _hmsh._value._size ; ++_ipos ) { _hfun._euclidean_mesh_2d. _hval[_ipos] = _hmsh._value._data[_ipos] ; } for (auto _ipos = (size_t) +0 ; _ipos != _hmsh._slope._size ; ++_ipos ) { _hfun._euclidean_mesh_2d. _dhdx[_ipos] = _hmsh._slope._data[_ipos] ; } } else if (_hmsh._vert3._size > 0) { /*--------------------------------- euclidean-mesh-3d */ _hfun._kind = jmsh_kind::euclidean_mesh ; _hfun._ndim = +3; if (_hmsh._vert3._size != _hmsh._value._size ) return __invalid_argument ; for (auto _ipos = (size_t) +0 ; _ipos != _hmsh._vert3._size ; ++_ipos ) { typename hfun_data::euclidean_mesh_3d ::node_type _ndat ; _ndat.pval(0) = _hmsh. _vert3._data[_ipos]._ppos[0]; _ndat.pval(1) = _hmsh. _vert3._data[_ipos]._ppos[1]; _ndat.pval(2) = _hmsh. _vert3._data[_ipos]._ppos[2]; _hfun._euclidean_mesh_3d. _mesh.push_node(_ndat, false) ; } for (auto _ipos = (size_t) +0 ; _ipos != _hmsh._tria4._size ; ++_ipos ) { typename hfun_data::euclidean_mesh_3d ::tri4_type _tdat ; _tdat.node(0) = _hmsh. _tria4._data[_ipos]._node[0]; _tdat.node(1) = _hmsh. _tria4._data[_ipos]._node[1]; _tdat.node(2) = _hmsh. _tria4._data[_ipos]._node[2]; _tdat.node(3) = _hmsh. _tria4._data[_ipos]._node[3]; _hfun._euclidean_mesh_3d. _mesh.push_tri4(_tdat, false) ; } _hfun._euclidean_mesh_3d._hval. set_count(_hmsh._value._size) ; _hfun._euclidean_mesh_3d._dhdx. set_count(_hmsh._slope._size) ; for (auto _ipos = (size_t) +0 ; _ipos != _hmsh._value._size ; ++_ipos ) { _hfun._euclidean_mesh_3d. _hval[_ipos] = _hmsh._value._data[_ipos] ; } for (auto _ipos = (size_t) +0 ; _ipos != _hmsh._slope._size ; ++_ipos ) { _hfun._euclidean_mesh_3d. _dhdx[_ipos] = _hmsh._slope._data[_ipos] ; } } } else if (_hmsh._flags == JIGSAW_ELLIPSOID_MESH ) { /*--------------------------------- ellipsoid-mesh-3d */ _hfun._kind = jmsh_kind::ellipsoid_mesh ; _hfun._ndim = +2; if (_hmsh._vert2._size != _hmsh._value._size ) return __invalid_argument ; if (_hmsh._radii._size==+3) { _hfun._ellipsoid_mesh_3d. _radA = _hmsh._radii._data[0] ; _hfun._ellipsoid_mesh_3d. _radB = _hmsh._radii._data[1] ; _hfun._ellipsoid_mesh_3d. _radC = _hmsh._radii._data[2] ; } else if (_hmsh._radii._size==+1) { _hfun._ellipsoid_mesh_3d. _radA = _hmsh._radii._data[0] ; _hfun._ellipsoid_mesh_3d. _radB = _hmsh._radii._data[0] ; _hfun._ellipsoid_mesh_3d. _radC = _hmsh._radii._data[0] ; } for (auto _ipos = (size_t) +0 ; _ipos != _hmsh._vert2._size ; ++_ipos ) { typename hfun_data::ellipsoid_mesh_3d ::node_type _ndat ; _ndat.pval(0) = _hmsh. _vert2._data[_ipos]._ppos[0]; _ndat.pval(1) = _hmsh. _vert2._data[_ipos]._ppos[1]; _ndat.pval(2) = + 0.0 ; _hfun._ellipsoid_mesh_3d. _mesh.push_node(_ndat, false) ; } for (auto _ipos = (size_t) +0 ; _ipos != _hmsh._tria3._size ; ++_ipos ) { typename hfun_data::ellipsoid_mesh_3d ::tri3_type _tdat ; _tdat.node(0) = _hmsh. _tria3._data[_ipos]._node[0]; _tdat.node(1) = _hmsh. _tria3._data[_ipos]._node[1]; _tdat.node(2) = _hmsh. _tria3._data[_ipos]._node[2]; _hfun._ellipsoid_mesh_3d. _mesh.push_tri3(_tdat, false) ; } _hfun._ellipsoid_mesh_3d._hval. set_count(_hmsh._value._size) ; _hfun._ellipsoid_mesh_3d._dhdx. set_count(_hmsh._slope._size) ; for (auto _ipos = (size_t) +0 ; _ipos != _hmsh._value._size ; ++_ipos ) { _hfun._ellipsoid_mesh_3d. _hval[_ipos] = _hmsh._value._data[_ipos] ; } for (auto _ipos = (size_t) +0 ; _ipos != _hmsh._slope._size ; ++_ipos ) { _hfun._ellipsoid_mesh_3d. _dhdx[_ipos] = _hmsh._slope._data[_ipos] ; } } else if (_hmsh._flags == JIGSAW_EUCLIDEAN_GRID ) { if (_hmsh._zgrid._size== 0) { /*--------------------------------- euclidean-grid-2d */ _hfun._kind = jmsh_kind::euclidean_grid ; _hfun._ndim = +2; _hfun._euclidean_grid_2d._xpos. set_count(_hmsh._xgrid._size) ; _hfun._euclidean_grid_2d._ypos. set_count(_hmsh._ygrid._size) ; _hfun._euclidean_grid_2d._hmat. set_count(_hmsh._value._size) ; _hfun._euclidean_grid_2d._dhdx. set_count(_hmsh._slope._size) ; for (auto _ipos = (size_t) +0 ; _ipos != _hmsh._xgrid._size ; ++_ipos ) { _hfun._euclidean_grid_2d. _xpos[_ipos] = _hmsh._xgrid._data[_ipos] ; } for (auto _ipos = (size_t) +0 ; _ipos != _hmsh._ygrid._size ; ++_ipos ) { _hfun._euclidean_grid_2d. _ypos[_ipos] = _hmsh._ygrid._data[_ipos] ; } for (auto _ipos = (size_t) +0 ; _ipos != _hmsh._value._size ; ++_ipos ) { _hfun._euclidean_grid_2d. _hmat[_ipos] = _hmsh._value._data[_ipos] ; } for (auto _ipos = (size_t) +0 ; _ipos != _hmsh._slope._size ; ++_ipos ) { _hfun._euclidean_grid_2d. _dhdx[_ipos] = _hmsh._slope._data[_ipos] ; } } else if (_hmsh._zgrid._size!= 0) { /*--------------------------------- euclidean-grid-3d */ _hfun._kind = jmsh_kind::euclidean_grid ; _hfun._ndim = +3; _hfun._euclidean_grid_3d._xpos. set_count(_hmsh._xgrid._size) ; _hfun._euclidean_grid_3d._ypos. set_count(_hmsh._ygrid._size) ; _hfun._euclidean_grid_3d._zpos. set_count(_hmsh._zgrid._size) ; _hfun._euclidean_grid_3d._hmat. set_count(_hmsh._value._size) ; _hfun._euclidean_grid_3d._dhdx. set_count(_hmsh._slope._size) ; for (auto _ipos = (size_t) +0 ; _ipos != _hmsh._xgrid._size ; ++_ipos ) { _hfun._euclidean_grid_3d. _xpos[_ipos] = _hmsh._xgrid._data[_ipos] ; } for (auto _ipos = (size_t) +0 ; _ipos != _hmsh._ygrid._size ; ++_ipos ) { _hfun._euclidean_grid_3d. _ypos[_ipos] = _hmsh._ygrid._data[_ipos] ; } for (auto _ipos = (size_t) +0 ; _ipos != _hmsh._zgrid._size ; ++_ipos ) { _hfun._euclidean_grid_3d. _zpos[_ipos] = _hmsh._zgrid._data[_ipos] ; } for (auto _ipos = (size_t) +0 ; _ipos != _hmsh._value._size ; ++_ipos ) { _hfun._euclidean_grid_3d. _hmat[_ipos] = _hmsh._value._data[_ipos] ; } for (auto _ipos = (size_t) +0 ; _ipos != _hmsh._slope._size ; ++_ipos ) { _hfun._euclidean_grid_3d. _dhdx[_ipos] = _hmsh._slope._data[_ipos] ; } } } else if (_hmsh._flags == JIGSAW_ELLIPSOID_GRID ) { if (_hmsh._zgrid._size== 0) { /*--------------------------------- ellipsoid-grid-3d */ _hfun._kind = jmsh_kind::ellipsoid_grid ; _hfun._ndim = +2; if (_hmsh._radii._size==+3) { _hfun._ellipsoid_grid_3d. _radA = _hmsh._radii._data[0] ; _hfun._ellipsoid_grid_3d. _radB = _hmsh._radii._data[1] ; _hfun._ellipsoid_grid_3d. _radC = _hmsh._radii._data[2] ; } else if (_hmsh._radii._size==+1) { _hfun._ellipsoid_grid_3d. _radA = _hmsh._radii._data[0] ; _hfun._ellipsoid_grid_3d. _radB = _hmsh._radii._data[0] ; _hfun._ellipsoid_grid_3d. _radC = _hmsh._radii._data[0] ; } _hfun._ellipsoid_grid_3d._xpos. set_count(_hmsh._xgrid._size) ; _hfun._ellipsoid_grid_3d._ypos. set_count(_hmsh._ygrid._size) ; _hfun._ellipsoid_grid_3d._hmat. set_count(_hmsh._value._size) ; _hfun._ellipsoid_grid_3d._dhdx. set_count(_hmsh._slope._size) ; for (auto _ipos = (size_t) +0 ; _ipos != _hmsh._xgrid._size ; ++_ipos ) { _hfun._ellipsoid_grid_3d. _xpos[_ipos] = _hmsh._xgrid._data[_ipos] ; } for (auto _ipos = (size_t) +0 ; _ipos != _hmsh._ygrid._size ; ++_ipos ) { _hfun._ellipsoid_grid_3d. _ypos[_ipos] = _hmsh._ygrid._data[_ipos] ; } for (auto _ipos = (size_t) +0 ; _ipos != _hmsh._value._size ; ++_ipos ) { _hfun._ellipsoid_grid_3d. _hmat[_ipos] = _hmsh._value._data[_ipos] ; } for (auto _ipos = (size_t) +0 ; _ipos != _hmsh._slope._size ; ++_ipos ) { _hfun._ellipsoid_grid_3d. _dhdx[_ipos] = _hmsh._slope._data[_ipos] ; } } } } catch (...) { _errv = __unknown_error ; } return ( _errv ) ; } /* -------------------------------------------------------- * READ-HFUN: read HFUN input file. -------------------------------------------------------- */ template < typename jlog_data > __normal_call iptr_type read_hfun ( jcfg_data &_jcfg , jlog_data &_jlog , hfun_data &_hfun ) { return hfun_from_jmsh ( _jcfg, _jlog, _hfun ) ; } /* -------------------------------------------------------- * COPY-HFUN: copy HFUN input data. -------------------------------------------------------- */ template < typename jlog_data > __normal_call iptr_type copy_hfun ( jcfg_data &_jcfg , jlog_data &_jlog , hfun_data &_hfun , jigsaw_msh_t const&_hmsh ) { return hfun_from_msht ( _jcfg, _jlog, _hfun, _hmsh); } /* -------------------------------------------------------- * TEST-HFUN: test HFUN data validity. -------------------------------------------------------- */ template < typename jlog_data > __normal_call iptr_type test_hfun ( jcfg_data &_jcfg , jlog_data &_jlog , hfun_data &_hfun ) { iptr_type _errv = __no_error ; __unreferenced(_jcfg) ; if (_hfun._ndim == +2 && _hfun._kind == jmsh_kind::euclidean_mesh) { /*--------------------------------- euclidean-mesh-2d */ fp32_type _hmin = std::numeric_limits<fp32_type>::max() ; fp32_type _smin = std::numeric_limits<fp32_type>::max() ; iptr_type _imin = std::numeric_limits<iptr_type>::max() ; iptr_type _imax = std::numeric_limits<iptr_type>::min() ; iptr_type _nmax = +0 ; for (auto _iter = _hfun. _euclidean_mesh_2d._hval.head() ; _iter != _hfun. _euclidean_mesh_2d._hval.tend() ; ++_iter ) { _hmin = std::min(_hmin, *_iter) ; } for (auto _iter = _hfun. _euclidean_mesh_2d._dhdx.head() ; _iter != _hfun. _euclidean_mesh_2d._dhdx.tend() ; ++_iter ) { _smin = std::min(_smin, *_iter) ; } for (auto _iter = _hfun. _euclidean_mesh_2d._mesh.node().head(); _iter != _hfun. _euclidean_mesh_2d._mesh.node().tend(); ++_iter ) { if (_iter->mark() < 0) continue ; _nmax += +1 ; } for (auto _iter = _hfun. _euclidean_mesh_2d._mesh.tri3().head(); _iter != _hfun. _euclidean_mesh_2d._mesh.tri3().tend(); ++_iter ) { if (_iter->mark() < 0) continue ; _imin = std::min( _imin, _iter->node(0)) ; _imin = std::min( _imin, _iter->node(1)) ; _imin = std::min( _imin, _iter->node(2)) ; _imax = std::max( _imax, _iter->node(0)) ; _imax = std::max( _imax, _iter->node(1)) ; _imax = std::max( _imax, _iter->node(2)) ; } auto _hnum = _hfun. _euclidean_mesh_2d._hval.count(); auto _gnum = _hfun. _euclidean_mesh_2d._dhdx.count(); if (_gnum > +0 && _gnum != 1 && _gnum != _hnum) { _jlog.push ( "**input error: DHDX. matrix incorrect dimensions.\n") ; _errv = __invalid_arraydim ; } if (_hmin < (fp32_type) +0.) { _jlog.push ( "**input error: HFUN. values must be non-negative.\n") ; _errv = __invalid_argument ; } if (_smin < (fp32_type) +0.) { _jlog.push ( "**input error: DHDX. values must be non-negative.\n") ; _errv = __invalid_argument ; } if (_imin < +0 || _imax>=_nmax) { _jlog.push ( "**input error: HFUN. tria. indexing is incorrect.\n") ; _errv = __invalid_indexing ; } } else if (_hfun._ndim == +2 && _hfun._kind == jmsh_kind::euclidean_grid) { /*--------------------------------- euclidean-grid-2d */ fp32_type _hmin = std::numeric_limits<fp32_type>::infinity(); fp32_type _smin = std::numeric_limits<fp32_type>::infinity(); for (auto _iter = _hfun. _euclidean_grid_2d._hmat.head(); _iter != _hfun. _euclidean_grid_2d._hmat.tend(); ++_iter ) { _hmin = std::min(_hmin, *_iter) ; } for (auto _iter = _hfun. _euclidean_grid_2d._dhdx.head(); _iter != _hfun. _euclidean_grid_2d._dhdx.tend(); ++_iter ) { _smin = std::min(_smin, *_iter) ; } bool_type _mono = true; if(!_hfun._euclidean_grid_2d._xpos.empty()) for (auto _iter = _hfun. _euclidean_grid_2d._xpos.head(); _iter != _hfun. _euclidean_grid_2d._xpos.tail(); ++_iter ) { if (*(_iter+1) < *(_iter+0)) { _mono = false; break; } } if(!_hfun._euclidean_grid_2d._ypos.empty()) for (auto _iter = _hfun. _euclidean_grid_2d._ypos.head(); _iter != _hfun. _euclidean_grid_2d._ypos.tail(); ++_iter ) { if (*(_iter+1) < *(_iter+0)) { _mono = false; break; } } auto _xnum = _hfun. _euclidean_grid_2d._xpos.count(); auto _ynum = _hfun. _euclidean_grid_2d._ypos.count(); auto _hnum = _hfun. _euclidean_grid_2d._hmat.count(); auto _gnum = _hfun. _euclidean_grid_2d._dhdx.count(); if (_hnum != _xnum * _ynum) { _jlog.push ( "**input error: HFUN. matrix incorrect dimensions.\n") ; _errv = __invalid_arraydim ; } if (_gnum > +0 && _gnum != 1 && _gnum != _hnum) { _jlog.push ( "**input error: DHDX. matrix incorrect dimensions.\n") ; _errv = __invalid_arraydim ; } if (_hmin < (fp32_type) +0.) { _jlog.push ( "**input error: HFUN. values must be non-negative.\n") ; _errv = __invalid_argument ; } if (_smin < (fp32_type) +0.) { _jlog.push ( "**input error: DHDX. values must be non-negative.\n") ; _errv = __invalid_argument ; } if (!_mono) { _jlog.push ( "**input error: grid must be monotonic increasing.\n") ; _errv = __invalid_argument ; } } else if (_hfun._ndim == +3 && _hfun._kind == jmsh_kind::euclidean_mesh) { /*--------------------------------- euclidean-mesh-3d */ fp32_type _hmin = std::numeric_limits<fp32_type>::max() ; fp32_type _smin = std::numeric_limits<fp32_type>::max() ; iptr_type _imin = std::numeric_limits<iptr_type>::max() ; iptr_type _imax = std::numeric_limits<iptr_type>::min() ; iptr_type _nmax = +0 ; for (auto _iter = _hfun. _euclidean_mesh_3d._hval.head() ; _iter != _hfun. _euclidean_mesh_3d._hval.tend() ; ++_iter ) { _hmin = std::min(_hmin, *_iter) ; } for (auto _iter = _hfun. _euclidean_mesh_3d._dhdx.head() ; _iter != _hfun. _euclidean_mesh_3d._dhdx.tend() ; ++_iter ) { _smin = std::min(_smin, *_iter) ; } for (auto _iter = _hfun. _euclidean_mesh_3d._mesh.node().head(); _iter != _hfun. _euclidean_mesh_3d._mesh.node().tend(); ++_iter ) { if (_iter->mark() < 0) continue ; _nmax += +1 ; } for (auto _iter = _hfun. _euclidean_mesh_3d._mesh.tri4().head(); _iter != _hfun. _euclidean_mesh_3d._mesh.tri4().tend(); ++_iter ) { if (_iter->mark() < 0) continue ; _imin = std::min( _imin, _iter->node(0)) ; _imin = std::min( _imin, _iter->node(1)) ; _imin = std::min( _imin, _iter->node(2)) ; _imin = std::min( _imin, _iter->node(3)) ; _imax = std::max( _imax, _iter->node(0)) ; _imax = std::max( _imax, _iter->node(1)) ; _imax = std::max( _imax, _iter->node(2)) ; _imax = std::max( _imax, _iter->node(3)) ; } auto _hnum = _hfun. _euclidean_mesh_3d._hval.count(); auto _gnum = _hfun. _euclidean_mesh_3d._dhdx.count(); if (_gnum > +0 && _gnum != 1 && _gnum != _hnum) { _jlog.push ( "**input error: DHDX. matrix incorrect dimensions.\n") ; _errv = __invalid_arraydim ; } if (_hmin < (fp32_type) +0.) { _jlog.push ( "**input error: HFUN. values must be non-negative.\n") ; _errv = __invalid_argument ; } if (_smin < (fp32_type) +0.) { _jlog.push ( "**input error: DHDX. values must be non-negative.\n") ; _errv = __invalid_argument ; } if (_imin < +0 || _imax>=_nmax) { _jlog.push ( "**input error: HFUN. tria. indexing is incorrect.\n") ; _errv = __invalid_indexing ; } } else if (_hfun._ndim == +3 && _hfun._kind == jmsh_kind::euclidean_grid) { /*--------------------------------- euclidean-grid-3d */ fp32_type _hmin = std::numeric_limits<fp32_type>::infinity(); fp32_type _smin = std::numeric_limits<fp32_type>::infinity(); for (auto _iter = _hfun. _euclidean_grid_3d._hmat.head(); _iter != _hfun. _euclidean_grid_3d._hmat.tend(); ++_iter ) { _hmin = std::min(_hmin, *_iter) ; } for (auto _iter = _hfun. _euclidean_grid_3d._dhdx.head(); _iter != _hfun. _euclidean_grid_3d._dhdx.tend(); ++_iter ) { _smin = std::min(_smin, *_iter) ; } bool_type _mono = true; if(!_hfun._euclidean_grid_3d._xpos.empty()) for (auto _iter = _hfun. _euclidean_grid_3d._xpos.head(); _iter != _hfun. _euclidean_grid_3d._xpos.tail(); ++_iter ) { if (*(_iter+1) < *(_iter+0)) { _mono = false; break; } } if(!_hfun._euclidean_grid_3d._ypos.empty()) for (auto _iter = _hfun. _euclidean_grid_3d._ypos.head(); _iter != _hfun. _euclidean_grid_3d._ypos.tail(); ++_iter ) { if (*(_iter+1) < *(_iter+0)) { _mono = false; break; } } if(!_hfun._euclidean_grid_3d._zpos.empty()) for (auto _iter = _hfun. _euclidean_grid_3d._zpos.head(); _iter != _hfun. _euclidean_grid_3d._zpos.tail(); ++_iter ) { if (*(_iter+1) < *(_iter+0)) { _mono = false; break; } } auto _xnum = _hfun. _euclidean_grid_3d._xpos.count(); auto _ynum = _hfun. _euclidean_grid_3d._ypos.count(); auto _znum = _hfun. _euclidean_grid_3d._zpos.count(); auto _hnum = _hfun. _euclidean_grid_3d._hmat.count(); auto _gnum = _hfun. _euclidean_grid_3d._dhdx.count(); if (_hnum!=_xnum*_ynum*_znum) { _jlog.push ( "**input error: HFUN. matrix incorrect dimensions.\n") ; _errv = __invalid_arraydim ; } if (_gnum > +0 && _gnum != 1 && _gnum != _hnum) { _jlog.push ( "**input error: DHDX. matrix incorrect dimensions.\n") ; _errv = __invalid_arraydim ; } if (_hmin < (fp32_type) +0.) { _jlog.push ( "**input error: HFUN. values must be non-negative.\n") ; _errv = __invalid_argument ; } if (_smin < (fp32_type) +0.) { _jlog.push ( "**input error: DHDX. values must be non-negative.\n") ; _errv = __invalid_argument ; } if (!_mono) { _jlog.push ( "**input error: grid must be monotonic increasing.\n") ; _errv = __invalid_argument ; } } else if (_hfun._kind == jmsh_kind::ellipsoid_mesh) { /*--------------------------------- ellipsoid-mesh-3d */ if (_hfun._ellipsoid_mesh_3d. _radA <= (real_type) +0. || _hfun._ellipsoid_mesh_3d. _radB <= (real_type) +0. || _hfun._ellipsoid_mesh_3d. _radC <= (real_type) +0. ) { _jlog.push ( "**input error: HFUN. RADII entries are incorrect.\n") ; _errv = __invalid_argument ; } fp32_type _hmin = std::numeric_limits<fp32_type>::max() ; fp32_type _smin = std::numeric_limits<fp32_type>::max() ; real_type static const _PI = (real_type)std::atan(+1.0) * 4. ; // careful with the way PI truncations onto float // expanded range so that we don't throw warnings // due to rounding issues... real_type static const _XMIN = (real_type) -2.1 * _PI ; real_type static const _XMAX = (real_type) +2.1 * _PI ; real_type static const _YMIN = (real_type) -1.1 * _PI ; real_type static const _YMAX = (real_type) +1.1 * _PI ; real_type _xmin = _XMAX; real_type _xmax = _XMIN; real_type _ymin = _YMAX; real_type _ymax = _YMIN; iptr_type _imin = std::numeric_limits<iptr_type>::max() ; iptr_type _imax = std::numeric_limits<iptr_type>::min() ; iptr_type _nmax = +0 ; for (auto _iter = _hfun. _ellipsoid_mesh_3d._hval.head() ; _iter != _hfun. _ellipsoid_mesh_3d._hval.tend() ; ++_iter ) { _hmin = std::min(_hmin, *_iter) ; } for (auto _iter = _hfun. _ellipsoid_mesh_3d._dhdx.head() ; _iter != _hfun. _ellipsoid_mesh_3d._dhdx.tend() ; ++_iter ) { _smin = std::min(_smin, *_iter) ; } for (auto _iter = _hfun. _ellipsoid_mesh_3d._mesh.node().head(); _iter != _hfun. _ellipsoid_mesh_3d._mesh.node().tend(); ++_iter ) { if (_iter->mark() < 0) continue ; _xmin = std::min( _xmin, _iter->pval(0)) ; _xmax = std::max( _xmax, _iter->pval(0)) ; _ymin = std::min( _ymin, _iter->pval(1)) ; _ymax = std::max( _ymax, _iter->pval(1)) ; _nmax += +1 ; } for (auto _iter = _hfun. _ellipsoid_mesh_3d._mesh.tri3().head(); _iter != _hfun. _ellipsoid_mesh_3d._mesh.tri3().tend(); ++_iter ) { if (_iter->mark() < 0) continue ; _imin = std::min( _imin, _iter->node(0)) ; _imin = std::min( _imin, _iter->node(1)) ; _imin = std::min( _imin, _iter->node(2)) ; _imax = std::max( _imax, _iter->node(0)) ; _imax = std::max( _imax, _iter->node(1)) ; _imax = std::max( _imax, _iter->node(2)) ; } auto _hnum = _hfun. _ellipsoid_mesh_3d._hval.count(); auto _gnum = _hfun. _ellipsoid_mesh_3d._dhdx.count(); if (_xmin < _XMIN || _xmax > _XMAX ) { _jlog.push ( "**input error: XPOS. must be in [-1.*pi, +1.*pi].\n") ; _errv = __invalid_argument ; } if (_ymin < _YMIN || _ymax > _YMAX ) { _jlog.push ( "**input error: YPOS. must be in [-.5*pi, +.5*pi].\n") ; _errv = __invalid_argument ; } if (_gnum > +0 && _gnum != 1 && _gnum != _hnum) { _jlog.push ( "**input error: DHDX. matrix incorrect dimensions.\n") ; _errv = __invalid_arraydim ; } if (_hmin < (fp32_type) +0.) { _jlog.push ( "**input error: HFUN. values must be non-negative.\n") ; _errv = __invalid_argument ; } if (_smin < (fp32_type) +0.) { _jlog.push ( "**input error: DHDX. values must be non-negative.\n") ; _errv = __invalid_argument ; } if (_imin < +0 || _imax>=_nmax) { _jlog.push ( "**input error: HFUN. tria. indexing is incorrect.\n") ; _errv = __invalid_indexing ; } } else if (_hfun._kind == jmsh_kind::ellipsoid_grid) { /*--------------------------------- ellipsoid-grid-3d */ if (_hfun._ellipsoid_grid_3d. _radA <= (real_type) +0. || _hfun._ellipsoid_grid_3d. _radB <= (real_type) +0. || _hfun._ellipsoid_grid_3d. _radC <= (real_type) +0. ) { _jlog.push ( "**input error: HFUN. RADII entries are incorrect.\n") ; _errv = __invalid_argument ; } fp32_type _hmin = std::numeric_limits<fp32_type>::infinity(); fp32_type _smin = std::numeric_limits<fp32_type>::infinity(); real_type static const _PI = (real_type)std::atan(+1.0) * 4. ; // careful with the way PI truncations onto float // expanded range so that we don't throw warnings // due to rounding issues... real_type static const _XMIN = (real_type) -2.1 * _PI ; real_type static const _XMAX = (real_type) +2.1 * _PI ; real_type static const _YMIN = (real_type) -1.1 * _PI ; real_type static const _YMAX = (real_type) +1.1 * _PI ; real_type _xmin = _XMAX; real_type _xmax = _XMIN; real_type _ymin = _YMAX; real_type _ymax = _YMIN; for (auto _iter = _hfun. _ellipsoid_grid_3d._hmat.head(); _iter != _hfun. _ellipsoid_grid_3d._hmat.tend(); ++_iter ) { _hmin = std::min(_hmin, *_iter) ; } for (auto _iter = _hfun. _ellipsoid_grid_3d._dhdx.head(); _iter != _hfun. _ellipsoid_grid_3d._dhdx.tend(); ++_iter ) { _smin = std::min(_smin, *_iter) ; } bool_type _mono = true; if(!_hfun._ellipsoid_grid_3d._xpos.empty()) for (auto _iter = _hfun. _ellipsoid_grid_3d._xpos.head(); _iter != _hfun. _ellipsoid_grid_3d._xpos.tail(); ++_iter ) { if (*(_iter+1) < *(_iter+0)) { _mono = false; break; } _xmin = std::min( _xmin , *_iter) ; _xmax = std::max( _xmax , *_iter) ; } if(!_hfun._ellipsoid_grid_3d._ypos.empty()) for (auto _iter = _hfun. _ellipsoid_grid_3d._ypos.head(); _iter != _hfun. _ellipsoid_grid_3d._ypos.tail(); ++_iter ) { if (*(_iter+1) < *(_iter+0)) { _mono = false; break; } _ymin = std::min( _ymin , *_iter) ; _ymax = std::max( _ymax , *_iter) ; } auto _xnum = _hfun. _ellipsoid_grid_3d._xpos.count(); auto _ynum = _hfun. _ellipsoid_grid_3d._ypos.count(); auto _hnum = _hfun. _ellipsoid_grid_3d._hmat.count(); auto _gnum = _hfun. _ellipsoid_grid_3d._dhdx.count(); if (_xmin < _XMIN || _xmax > _XMAX ) { _jlog.push ( "**input error: XPOS. must be in [-1.*pi, +1.*pi].\n") ; _errv = __invalid_argument ; } if (_ymin < _YMIN || _ymax > _YMAX ) { _jlog.push ( "**input error: YPOS. must be in [-.5*pi, +.5*pi].\n") ; _errv = __invalid_argument ; } if (_hnum != _xnum * _ynum) { _jlog.push ( "**input error: HFUN. matrix incorrect dimensions.\n") ; _errv = __invalid_arraydim ; } if (_gnum > +0 && _gnum != 1 && _gnum != _hnum) { _jlog.push ( "**input error: DHDX. matrix incorrect dimensions.\n") ; _errv = __invalid_arraydim ; } if (_hmin < (fp32_type) +0.) { _jlog.push ( "**input error: HFUN. values must be non-negative.\n") ; _errv = __invalid_argument ; } if (_smin < (fp32_type) +0.) { _jlog.push ( "**input error: DHDX. values must be non-negative.\n") ; _errv = __invalid_argument ; } if (!_mono) { _jlog.push ( "**input error: grid must be monotonic increasing.\n") ; _errv = __invalid_argument ; } } return ( _errv ) ; } /* -------------------------------------------------------- * ECHO-HFUN: print summary of HFUN data. -------------------------------------------------------- */ template < typename jlog_data > __normal_call iptr_type echo_hfun ( jcfg_data &_jcfg , jlog_data &_jlog , hfun_data &_hfun ) { iptr_type _errv = __no_error ; __unreferenced(_jcfg) ; fp32_type _hmin = +std::numeric_limits <fp32_type>::infinity() ; fp32_type _hmax = -std::numeric_limits <fp32_type>::infinity() ; if (_hfun._ndim == +0) { /*--------------------------------- constant-value-kd */ _jlog.push( " CONSTANT-VALUE\n\n") ; _jlog.push( " .VAL(H). = " + to_string_prec ( _hfun._constant_value_kd._hval, 2) + "\n") ; } else if (_hfun._ndim == +2 && _hfun._kind == jmsh_kind::euclidean_mesh) { /*--------------------------------- euclidean-mesh-2d */ _jlog.push( " EUCLIDEAN-MESH\n\n") ; _jlog.push( " |NDIMS.| = " + std::to_string(2) + "\n"); _jlog.push("\n") ; iptr_type _num1 = +0 ; iptr_type _num3 = +0 ; for (auto _iter = _hfun. _euclidean_mesh_2d._hval.head() ; _iter != _hfun. _euclidean_mesh_2d._hval.tend() ; ++_iter ) { _hmin = std::min( _hmin,*_iter) ; _hmax = std::max( _hmax,*_iter) ; } _jlog.push( " .MIN(H). = " + to_string_prec(_hmin, 2) + "\n"); _jlog.push( " .MAX(H). = " + to_string_prec(_hmax, 2) + "\n"); _jlog.push(" \n") ; auto _mptr = &_hfun._euclidean_mesh_2d._mesh; for (auto _iter = _mptr->node().head(); _iter != _mptr->node().tend(); ++_iter ) { if (_iter->mark()>=+0) _num1 += +1 ; } _jlog.push( " |COORD.| = " + std::to_string(_num1) + "\n"); for (auto _iter = _mptr->tri3().head(); _iter != _mptr->tri3().tend(); ++_iter ) { if (_iter->mark()>=+0) _num3 += +1 ; } _jlog.push( " |TRIA-3| = " + std::to_string(_num3) + "\n"); } else if (_hfun._ndim == +2 && _hfun._kind == jmsh_kind::euclidean_grid) { /*--------------------------------- euclidean-grid-2d */ _jlog.push( " EUCLIDEAN-GRID\n\n") ; _jlog.push( " |NDIMS.| = " + std::to_string(2) + "\n"); _jlog.push("\n") ; for (auto _iter = _hfun. _euclidean_grid_2d._hmat.head() ; _iter != _hfun. _euclidean_grid_2d._hmat.tend() ; ++_iter ) { _hmin = std::min(_hmin, *_iter) ; _hmax = std::max(_hmax, *_iter) ; } _jlog.push( " .MIN(H). = " + to_string_prec(_hmin, 2) + "\n"); _jlog.push( " .MAX(H). = " + to_string_prec(_hmax, 2) + "\n"); _jlog.push(" \n") ; auto _xnum = _hfun. _euclidean_grid_2d._xpos.count(); auto _ynum = _hfun. _euclidean_grid_2d._ypos.count(); _jlog.push( " |XGRID.| = " + std::to_string(_xnum) + "\n") ; _jlog.push( " |YGRID.| = " + std::to_string(_ynum) + "\n") ; } else if (_hfun._ndim == +3 && _hfun._kind == jmsh_kind::euclidean_mesh) { /*--------------------------------- euclidean-mesh-3d */ _jlog.push( " EUCLIDEAN-MESH\n\n") ; _jlog.push( " |NDIMS.| = " + std::to_string(3) + "\n"); _jlog.push("\n") ; iptr_type _num1 = +0 ; iptr_type _num4 = +0 ; for (auto _iter = _hfun. _euclidean_mesh_3d._hval.head() ; _iter != _hfun. _euclidean_mesh_3d._hval.tend() ; ++_iter ) { _hmin = std::min( _hmin,*_iter) ; _hmax = std::max( _hmax,*_iter) ; } _jlog.push( " .MIN(H). = " + to_string_prec(_hmin, 2) + "\n"); _jlog.push( " .MAX(H). = " + to_string_prec(_hmax, 2) + "\n"); _jlog.push(" \n") ; auto _mptr = &_hfun._euclidean_mesh_3d._mesh; for (auto _iter = _mptr->node().head(); _iter != _mptr->node().tend(); ++_iter ) { if (_iter->mark()>=+0) _num1 += +1 ; } _jlog.push( " |COORD.| = " + std::to_string(_num1) + "\n"); for (auto _iter = _mptr->tri4().head(); _iter != _mptr->tri4().tend(); ++_iter ) { if (_iter->mark()>=+0) _num4 += +1 ; } _jlog.push( " |TRIA-4| = " + std::to_string(_num4) + "\n"); } else if (_hfun._ndim == +3 && _hfun._kind == jmsh_kind::euclidean_grid) { /*--------------------------------- euclidean-grid-3d */ _jlog.push( " EUCLIDEAN-GRID\n\n") ; _jlog.push( " |NDIMS.| = " + std::to_string(3) + "\n"); _jlog.push("\n") ; for (auto _iter = _hfun. _euclidean_grid_3d._hmat.head() ; _iter != _hfun. _euclidean_grid_3d._hmat.tend() ; ++_iter ) { _hmin = std::min(_hmin, *_iter) ; _hmax = std::max(_hmax, *_iter) ; } _jlog.push( " .MIN(H). = " + to_string_prec(_hmin, 2) + "\n"); _jlog.push( " .MAX(H). = " + to_string_prec(_hmax, 2) + "\n"); _jlog.push(" \n") ; auto _xnum = _hfun. _euclidean_grid_3d._xpos.count(); auto _ynum = _hfun. _euclidean_grid_3d._ypos.count(); auto _znum = _hfun. _euclidean_grid_3d._zpos.count(); _jlog.push( " |XGRID.| = " + std::to_string(_xnum) + "\n") ; _jlog.push( " |YGRID.| = " + std::to_string(_ynum) + "\n") ; _jlog.push( " |ZGRID.| = " + std::to_string(_znum) + "\n") ; } else if (_hfun._kind == jmsh_kind::ellipsoid_mesh) { /*--------------------------------- ellipsoid-mesh-3d */ _jlog.push( " ELLIPSOID-MESH\n\n") ; _jlog.push( " |NDIMS.| = " + std::to_string(2) + "\n"); iptr_type _num1 = +0 ; iptr_type _num3 = +0 ; for (auto _iter = _hfun. _ellipsoid_mesh_3d._hval.head() ; _iter != _hfun. _ellipsoid_mesh_3d._hval.tend() ; ++_iter ) { _hmin = std::min( _hmin,*_iter) ; _hmax = std::max( _hmax,*_iter) ; } _jlog.push( " .MIN(H). = " + to_string_prec(_hmin, 2) + "\n"); _jlog.push( " .MAX(H). = " + to_string_prec(_hmax, 2) + "\n"); _jlog.push(" \n") ; auto _mptr = &_hfun._ellipsoid_mesh_3d._mesh; for (auto _iter = _mptr->node().head(); _iter != _mptr->node().tend(); ++_iter ) { if (_iter->mark()>=+0) _num1 += +1 ; } _jlog.push( " |COORD.| = " + std::to_string(_num1) + "\n"); for (auto _iter = _mptr->tri3().head(); _iter != _mptr->tri3().tend(); ++_iter ) { if (_iter->mark()>=+0) _num3 += +1 ; } _jlog.push( " |TRIA-3| = " + std::to_string(_num3) + "\n"); } else if (_hfun._kind == jmsh_kind::ellipsoid_grid) { /*--------------------------------- ellipsoid-grid-3d */ _jlog.push( " ELLIPSOID-GRID\n\n") ; _jlog.push( " |NDIMS.| = " + std::to_string(2) + "\n"); for (auto _iter = _hfun. _ellipsoid_grid_3d._hmat.head() ; _iter != _hfun. _ellipsoid_grid_3d._hmat.tend() ; ++_iter ) { _hmin = std::min(_hmin, *_iter) ; _hmax = std::max(_hmax, *_iter) ; } _jlog.push( " .MIN(H). = " + to_string_prec(_hmin, 2) + "\n"); _jlog.push( " .MAX(H). = " + to_string_prec(_hmax, 2) + "\n"); _jlog.push(" \n") ; auto _xnum = _hfun. _ellipsoid_grid_3d._xpos.count(); auto _ynum = _hfun. _ellipsoid_grid_3d._ypos.count(); _jlog.push( " |XGRID.| = " + std::to_string(_xnum) + "\n") ; _jlog.push( " |YGRID.| = " + std::to_string(_ynum) + "\n") ; _jlog.push(" \n") ; if (_hfun._ellipsoid_grid_3d._wrap) _jlog.push(" PERIODIC = TRUE\n" ) ; } _jlog.push("\n") ; return ( _errv) ; } # endif //__HFN_LOAD__
68,938
21,823
/* * Copyright (C) 2012 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #ifndef GAZEBO_PHYSICS_INERTIAL_HH_ #define GAZEBO_PHYSICS_INERTIAL_HH_ #include <string> #include <memory> #include <ignition/math/Inertial.hh> #include <sdf/sdf.hh> #include <ignition/math/Vector3.hh> #include <ignition/math/Quaternion.hh> #include <ignition/math/Matrix3.hh> #include "gazebo/msgs/msgs.hh" #include "gazebo/util/system.hh" namespace gazebo { namespace physics { // Forward declare private data class InertialPrivate; /// \addtogroup gazebo_physics /// \{ /// \class Inertial Inertial.hh physics/physics.hh /// \brief A class for inertial information about a link class GZ_PHYSICS_VISIBLE Inertial { /// \brief Default Constructor public: Inertial(); /// \brief Constructor. /// \param[in] _mass Mass value in kg if using metric. public: explicit Inertial(const double _mass); /// \brief Constructor from ignition::math::Inertial. /// \param[in] _inertial Ignition inertial object to copy. // cppcheck-suppress noExplicitConstructor public: Inertial(const ignition::math::Inertiald &_inertial); /// \brief Copy constructor. /// \param[in] _inertial Inertial element to copy public: Inertial(const Inertial &_inertial); /// \brief Destructor. public: virtual ~Inertial(); /// \brief Load from SDF values. /// \param[in] _sdf SDF value to load from. public: void Load(sdf::ElementPtr _sdf); /// \brief update the parameters using new sdf values. /// \param[in] _sdf Update values from. public: void UpdateParameters(sdf::ElementPtr _sdf); /// \brief Reset all the mass properties. public: void Reset(); /// \brief Return copy of Inertial in ignition format. public: ignition::math::Inertiald Ign() const; /// \brief Set the mass. /// \param[in] _m Mass value in kilograms. public: void SetMass(const double _m); /// \brief Get the mass /// \return The mass in kilograms public: double Mass() const; /// \brief Set the mass matrix. /// \param[in] _ixx X second moment of inertia (MOI) about x axis. /// \param[in] _iyy Y second moment of inertia about y axis. /// \param[in] _izz Z second moment of inertia about z axis. /// \param[in] _ixy XY inertia. /// \param[in] _ixz XZ inertia. /// \param[in] _iyz YZ inertia. public: void SetInertiaMatrix( const double _ixx, const double _iyy, const double _izz, const double _ixy, const double _ixz, const double iyz); /// \brief Set the center of gravity. /// \param[in] _cx X position. /// \param[in] _cy Y position. /// \param[in] _cz Z position. public: void SetCoG(const double _cx, const double _cy, const double _cz); /// \brief Set the center of gravity. /// \param[in] _center Center of the gravity. public: void SetCoG(const ignition::math::Vector3d &_center); /// \brief Set the center of gravity and rotation offset of inertial /// coordinate frame relative to Link frame. /// \param[in] _cx Center offset in x-direction in Link frame /// \param[in] _cy Center offset in y-direction in Link frame /// \param[in] _cz Center offset in z-direction in Link frame /// \param[in] _rx Roll angle offset of inertial coordinate frame. /// \param[in] _ry Pitch angle offset of inertial coordinate frame. /// \param[in] _rz Yaw angle offset of inertial coordinate frame. public: void SetCoG(const double _cx, const double _cy, const double _cz, const double _rx, const double _ry, const double _rz); /// \brief Set the center of gravity. /// \param[in] _c Transform to center of gravity. public: void SetCoG(const ignition::math::Pose3d &_c); /// \brief Get the center of gravity. /// \return The center of gravity. public: const ignition::math::Vector3d &CoG() const; /// \brief Get the pose about which the mass and inertia matrix is /// specified in the Link frame. /// \return The inertial pose. public: ignition::math::Pose3d Pose() const; /// \brief Get the principal moments of inertia (Ixx, Iyy, Izz). /// \return The principal moments. public: const ignition::math::Vector3d &PrincipalMoments() const; /// \brief Get the products of inertia (Ixy, Ixz, Iyz). /// \return The products of inertia. public: const ignition::math::Vector3d &ProductsOfInertia() const; /// \brief Get IXX /// \return IXX value public: double IXX() const; /// \brief Get IYY /// \return IYY value public: double IYY() const; /// \brief Get IZZ /// \return IZZ value public: double IZZ() const; /// \brief Get IXY /// \return IXY value public: double IXY() const; /// \brief Get IXZ /// \return IXZ value public: double IXZ() const; /// \brief Get IYZ /// \return IYZ value public: double IYZ() const; /// \brief Set IXX /// \param[in] _v IXX value public: void SetIXX(const double _v); /// \brief Set IYY /// \param[in] _v IYY value public: void SetIYY(const double _v); /// \brief Set IZZ /// \param[in] _v IZZ value public: void SetIZZ(const double _v); /// \brief Set IXY /// \param[in] _v IXY value public: void SetIXY(const double _v); /// \brief Set IXZ /// \param[in] _v IXZ value public: void SetIXZ(const double _v); /// \brief Set IYZ /// \param[in] _v IYZ value public: void SetIYZ(const double _v); /// \brief Rotate this mass. /// \param[in] _rot Rotation amount. public: void Rotate(const ignition::math::Quaterniond &_rot); /// \brief Equal operator. /// \param[in] _inertial Inertial to copy. /// \return Reference to this object. public: Inertial &operator=(const Inertial &_inertial); /// \brief Equal operator. /// \param[in] _inertial Ignition inertial to copy. /// \return Reference to this object. public: Inertial &operator=(const ignition::math::Inertiald &_inertial); /// \brief Addition operator. /// Assuming both CG and Moment of Inertia (MOI) are defined /// in the same reference Link frame. /// New CG is computed from masses and perspective offsets, /// and both MOI contributions relocated to the new cog. /// \param[in] _inertial Inertial to add. /// \return The result of the addition. public: Inertial operator+(const Inertial &_inertial) const; /// \brief Addition equal operator. /// \param[in] _inertial Inertial to add. /// \return Reference to this object. public: const Inertial &operator+=(const Inertial &_inertial); /// \brief Update parameters from a message /// \param[in] _msg Message to read public: void ProcessMsg(const msgs::Inertial &_msg); /// \brief Get the equivalent inertia from a point in local Link frame /// If you specify MOI(this->GetPose()), you should get /// back the Moment of Inertia (MOI) exactly as specified in the SDF. /// If _pose is different from pose of the Inertial block, then /// the MOI is rotated accordingly, and contributions from changes /// in MOI location due to point mass is added to the final MOI. /// \param[in] _pose location in Link local frame /// \return equivalent inertia at _pose public: ignition::math::Matrix3d MOI( const ignition::math::Pose3d &_pose) const; /// \brief Get equivalent Inertia values with the Link frame offset, /// while holding the Pose of CoG constant in the world frame. /// \param[in] _frameOffset amount to offset the Link frame by, this /// is a transform defined in the Link frame. /// \return Inertial parameters with the shifted frame. public: Inertial operator()( const ignition::math::Pose3d &_frameOffset) const; /// \brief Get equivalent Inertia values with the Link frame offset, /// while holding the Pose of CoG constant in the world frame. /// \param[in] _frameOffset amount to offset the Link frame by, this /// is a transform defined in the Link frame. /// \return Inertial parameters with the shifted frame. public: Inertial operator()( const ignition::math::Vector3d &_frameOffset) const; /// \brief Output operator. /// \param[in] _out Output stream. /// \param[in] _inertial Inertial object to output. public: friend std::ostream &operator<<(std::ostream &_out, const gazebo::physics::Inertial &_inertial) { _out << "Mass[" << _inertial.Mass() << "] CoG[" << _inertial.CoG() << "]\n"; _out << "IXX[" << _inertial.PrincipalMoments().X() << "] " << "IYY[" << _inertial.PrincipalMoments().Y() << "] " << "IZZ[" << _inertial.PrincipalMoments().Z() << "]\n"; _out << "IXY[" << _inertial.ProductsOfInertia().X() << "] " << "IXZ[" << _inertial.ProductsOfInertia().Y() << "] " << "IYZ[" << _inertial.ProductsOfInertia().Z() << "]\n"; return _out; } /// \brief returns Moments of Inertia as a Matrix3 /// \return Moments of Inertia as a Matrix3 public: ignition::math::Matrix3d MOI() const; /// \brief Sets Moments of Inertia (MOI) from a Matrix3 /// \param[in] _moi Moments of Inertia as a Matrix3 public: void SetMOI(const ignition::math::Matrix3d &_moi); /// \internal /// \brief Private data pointer. private: std::unique_ptr<InertialPrivate> dataPtr; }; /// \} } } #endif
10,608
3,303
// Copyright (c) 2021 Intel Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <omp.h> #include <exception> #include <numeric> #include <string> #include <unordered_map> #include <unordered_set> #include <vector> #include "gtest/gtest.h" #include "interface.hpp" namespace jd { using dt = jd::data_type; using ft = jd::format_type; struct op_args_t { operator_desc op_desc; std::vector<const void*> rt_data; }; struct test_params_t { std::pair<op_args_t, op_args_t> args; bool expect_to_fail; }; void get_true_data(const operator_desc& op_desc, const std::vector<const void*>& rt_data) { // shape configure alias const auto& ts_descs = op_desc.tensor_descs(); const auto& wei_desc = ts_descs[0]; const auto& src_desc = ts_descs[1]; const auto& dst_desc = ts_descs[3]; int dims = wei_desc.shape().size(); int N = wei_desc.shape()[0]; int K = wei_desc.shape()[1]; int M = src_desc.shape()[1]; const auto& dst_dt = dst_desc.dtype(); auto attrs_map = op_desc.attrs(); // runtime data alias const auto wei_data = static_cast<const bfloat16_t*>(rt_data[0]); const auto src_data = static_cast<const bfloat16_t*>(rt_data[1]); auto dst_data = const_cast<void*>(rt_data[3]); auto fp_dst_data = static_cast<float*>(dst_data); // Computing the kernel if (dims == 2) { for (int n = 0; n < N; ++n) { #pragma omp parallel for for (int m = 0; m < M; ++m) { #pragma omp parallel for for (int k = 0; k < K; ++k) { fp_dst_data[n * M + m] += make_fp32(wei_data[n * K + k]) * make_fp32(src_data[k * M + m]); } } } } } bool check_result(const test_params_t& t) { const auto& p = t.args.first; const auto& q = t.args.second; try { const auto& op_desc = p.op_desc; sparse_matmul_desc spmm_desc(op_desc); sparse_matmul spmm_kern(spmm_desc); spmm_kern.execute(p.rt_data); } catch (const std::exception& e) { if (t.expect_to_fail) { return true; } else { return false; } } if (!t.expect_to_fail) { get_true_data(q.op_desc, q.rt_data); auto buf1 = p.rt_data[3]; auto size1 = p.op_desc.tensor_descs()[3].size(); auto buf2 = q.rt_data[3]; auto size2 = q.op_desc.tensor_descs()[3].size(); // Should compare buffer with different addresses EXPECT_NE(buf1, buf2); const auto& dst_type = p.op_desc.tensor_descs()[3].dtype(); return compare_data<float>(buf1, size1, buf2, size2, 5e-3); } return false; } class SpmmAMXX16KernelTest : public testing::TestWithParam<test_params_t> { protected: SpmmAMXX16KernelTest() {} virtual ~SpmmAMXX16KernelTest() {} void SetUp() override {} void TearDown() override {} }; TEST_P(SpmmAMXX16KernelTest, TestPostfix) { test_params_t t = testing::TestWithParam<test_params_t>::GetParam(); EXPECT_TRUE(check_result(t)); } template <typename T> void prepare_sparse_data(T* weight, dim_t N, dim_t K, dim_t n_blksize, dim_t k_blksize, float ratio) { uint32_t seed = 9527; for (int n = 0; n < N; ++n) { for (int k = 0; k < K; ++k) { weight[n * K + k] = make_bf16(rand_r(&seed) % 10 + 1); } } // sparsify a_mat for (int nb = 0; nb < N / n_blksize; ++nb) { for (int kb = 0; kb < K / k_blksize; ++kb) { bool fill_zero = rand_r(&seed) % 100 <= (dim_t)(ratio * 100); if (fill_zero) { for (int n = 0; n < n_blksize; ++n) { for (int k = 0; k < k_blksize; ++k) { weight[(nb * n_blksize + n) * K + kb * k_blksize + k] = make_bf16(0); } } } } } } std::pair<const void*, const void*> make_data_obj(const dt& tensor_dt, dim_t rows, dim_t cols, bool is_clear = false, bool is_sparse = false, const std::vector<float>& ranges = {-10, 10}) { dim_t elem_num = rows * cols; dim_t bytes_size = elem_num * type_size[tensor_dt]; void* data_ptr = nullptr; if (is_clear) { // prepare dst data_ptr = new float[elem_num]; memset(data_ptr, 0, bytes_size); } else { if (is_sparse) { // prepare sparse weight float ratio = 0.9; data_ptr = new bfloat16_t[elem_num]; bfloat16_t* bf16_ptr = static_cast<bfloat16_t*>(data_ptr); prepare_sparse_data<bfloat16_t>(bf16_ptr, rows, cols, 16, 1, ratio); } else { // prepare dense activation data_ptr = new bfloat16_t[elem_num]; bfloat16_t* bf16_ptr = static_cast<bfloat16_t*>(data_ptr); init_vector(bf16_ptr, elem_num, ranges[0], ranges[1]); } } void* data_ptr_copy = new uint8_t[bytes_size]; memcpy(data_ptr_copy, data_ptr, bytes_size); return std::pair<const void*, const void*>{data_ptr, data_ptr_copy}; } std::pair<op_args_t, op_args_t> gen_case(const jd::kernel_kind ker_kind, const jd::kernel_prop ker_prop, const jd::engine_kind eng_kind, const std::vector<tensor_desc>& ts_descs) { std::unordered_map<std::string, std::string> op_attrs; // Step 1: Construct runtime data std::vector<const void*> rt_data1; std::vector<const void*> rt_data2; dim_t N = ts_descs[0].shape()[0]; dim_t K = ts_descs[0].shape()[1]; int tensor_num = ts_descs.size(); for (int index = 0; index < tensor_num; ++index) { bool is_clear = (index == 2 | index == 3) ? true : false; bool is_sparse = (index == 0) ? true : false; dim_t rows = ts_descs[index].shape()[0]; dim_t cols = ts_descs[index].shape()[1]; auto data_pair = make_data_obj(ts_descs[index].dtype(), rows, cols, is_clear, is_sparse); rt_data1.emplace_back(data_pair.first); rt_data2.emplace_back(data_pair.second); } // Step 2: sparse data encoding volatile bsr_data_t<bfloat16_t>* sparse_ptr = spns::reorder_to_bsr_amx<bfloat16_t, 32>(N, K, rt_data1[0]); op_attrs["sparse_ptr"] = std::to_string(reinterpret_cast<uint64_t>(sparse_ptr)); operator_desc an_op_desc(ker_kind, ker_prop, eng_kind, ts_descs, op_attrs); // Step 3: op_args_t testcase pair op_args_t op_args = {an_op_desc, rt_data1}; op_args_t op_args_copy = {an_op_desc, rt_data2}; return {op_args, op_args_copy}; } static auto case_func = []() { std::vector<test_params_t> cases; // Config tensor_desc wei_desc; tensor_desc src_desc; tensor_desc bia_desc; tensor_desc dst_desc; // case: sparse: bf16xbf16=f32, weight(N, K) * activation(K, M) // = dst(N, M) wei_desc = {{64, 64}, dt::bf16, ft::bsr}; src_desc = {{64, 64}, dt::bf16, ft::ab}; bia_desc = {{64, 1}, dt::fp32, ft::ab}; dst_desc = {{64, 64}, dt::fp32, ft::ab}; cases.push_back({gen_case(kernel_kind::sparse_matmul, kernel_prop::forward_inference, engine_kind::cpu, {wei_desc, src_desc, bia_desc, dst_desc})}); return ::testing::ValuesIn(cases); }; INSTANTIATE_TEST_SUITE_P(Prefix, SpmmAMXX16KernelTest, case_func()); } // namespace jd
7,416
2,984
#include "Autoplay.h" IMPLEMENT_MODULE(AutoplayModuleImpl, Autoplay);
70
31
/*! * Copyright (c) 2018 by Contributors * * Lower warp memory to use local memory * and shuffle intrinsics. * * \file lower_warp_memory.cc */ // Thanks to Andrew Adams and Vinod Grover for // explaining the concept of warp shuffle. #include <tvm/ir.h> #include <tvm/ir_mutator.h> #include <tvm/ir_visitor.h> #include <tvm/ir_pass.h> #include <unordered_set> #include "ir_util.h" #include "../arithmetic/compute_expr.h" #include "../runtime/thread_storage_scope.h" namespace tvm { namespace ir { // Rewrite Rule // // There is no special warp memory in most GPUs. // Instead, we can stripe the data into threads // and store the data into local memory. // // This requires us to do the following rewriting: // - Rewrite allocation to use local memory. // - Rewrite store of warp memory to local store. // - Rewrite load of waro memory to local plus a shuffle. // // Define a generic shuffle instrinsic warp_shuffle(data, warp_index). // We can use the following rewriting rule // // Before rewrite, // // alloc warp warp_mem[n * warp_size * m] // store warp_mem[m * warp_index + (warp_size * m) * y + x] // load warp_mem[m * z + (warp_size * m) * y + x] // subject to x \in [0, m), y \in [0, n) // // After rewrite: // // alloc local local_mem[n * m] // store warp_mem[m * y + x] // warp_shuffle(load warp_mem[m * y + x], z) // subject to (m * y + x) is invariant to warp_index // Algorithm // // To implement this rewrite rule, we can do the follow step: // For each warp memory alloc // - Use linear pattern detector on load index to find m // - Deduce n given warp_size and alloc size // - Now that we have m, n, warp_size, we can proceed with the rewrite // Visitor to find m in pattern // store warp_mem[m * warp_index + (warp_size * m) * y + x] class WarpStoreCoeffFinder : private IRVisitor { public: WarpStoreCoeffFinder(const Variable* buffer, Var warp_index) : buffer_(buffer), warp_index_(warp_index) { } ~WarpStoreCoeffFinder() {} // find the warp co-efficient in the statement given the warp size int Find(const Stmt& stmt) { this->Visit(stmt); return warp_coeff_; } private: /// Visitor implementation void Visit_(const Store *op) final { if (op->buffer_var.get() == buffer_) { if (op->value.type().lanes() == 1) { UpdatePattern(op->index); } else { Expr base; CHECK(GetRamp1Base(op->index, op->value.type().lanes(), &base)) << "LowerWarpMemory failed due to store index=" << op->index << ", can only handle continuous store"; UpdatePattern(base); } } else { IRVisitor::Visit_(op); } } void UpdatePattern(const Expr& index) { Array<Expr> m = arith::DetectLinearEquation(index, {warp_index_}); CHECK_EQ(m.size(), 2U) << "LowerWarpMemory failed due to store index=" << index; int coeff = 0; Expr mcoeff = ir::Simplify(m[0]); CHECK(arith::GetConstInt(mcoeff, &coeff) && coeff > 0) << "LowerWarpMemory failed due to store index=" << index << ", require positive constant coefficient on warp index " << warp_index_ << " but get " << mcoeff; if (warp_coeff_ != 0) { CHECK_EQ(warp_coeff_, coeff) << "LowerWarpMemory failed due to two different store coefficient to warp index"; } else { warp_coeff_ = coeff; } } // The buffer variable const Variable* buffer_; // the warp index Var warp_index_; // the coefficient int warp_coeff_{0}; }; // Visitor to find the warp index class WarpIndexFinder : private IRVisitor { public: explicit WarpIndexFinder(int warp_size) : warp_size_(warp_size) { } ~WarpIndexFinder() {} // find the warp co-efficient in the statement given the warp size IterVar Find(const Stmt& stmt) { this->Visit(stmt); CHECK(warp_index_.defined()) << "Cannot find warp index(threadIdx.x) within the scope of warp memory"; return warp_index_; } private: /// Visitor implementation void Visit_(const AttrStmt *op) final { if (op->attr_key == attr::thread_extent) { IterVar iv(op->node.node_); if (iv->thread_tag == "threadIdx.x") { int value; CHECK(arith::GetConstInt(op->value, &value) && value == warp_size_) << "Expect threadIdx.x 's size to be equal to warp size(" << warp_size_ << ")" << " to enable warp memory" << " but get " << op->value << " instead"; if (warp_index_.defined()) { CHECK(warp_index_.same_as(iv)) << "Find two instance of " << warp_index_->thread_tag << " in the same kernel. " << "Please create it using thread_axis once and reuse the axis " << "across multiple binds in the same kernel"; } else { warp_index_ = iv; } } } IRVisitor::Visit_(op); } // warp size int warp_size_{0}; // the warp index IterVar warp_index_{nullptr}; }; // Mutator to change the read pattern class WarpAccessRewriter : protected IRMutator { public: explicit WarpAccessRewriter(int warp_size) : warp_size_(warp_size) {} ~WarpAccessRewriter() {} // Rewrite the allocate statement which transforms // warp memory to local memory. Stmt Rewrite(const Allocate* op, const Stmt& stmt) { buffer_ = op->buffer_var.get(); int alloc_size = op->constant_allocation_size(); CHECK_GT(alloc_size, 0) << "warp memory only support constant alloc size"; alloc_size *= op->type.lanes(); warp_index_ = WarpIndexFinder(warp_size_).Find(op->body)->var; warp_coeff_ = WarpStoreCoeffFinder( buffer_, warp_index_).Find(op->body); CHECK_EQ(alloc_size % (warp_size_ * warp_coeff_), 0) << "Warp memory must be multiple of warp size"; warp_group_ = alloc_size / (warp_size_ * warp_coeff_); return Allocate::make( op->buffer_var, op->type, {make_const(Int(32), alloc_size / warp_size_)}, op->condition, this->Mutate(op->body)); } protected: Expr Mutate_(const Variable* op, const Expr& expr) { CHECK(op != buffer_) << "Cannot access address of warp memory directly"; return IRMutator::Mutate_(op, expr); } Stmt Mutate_(const Store* op, const Stmt& stmt) { if (op->buffer_var.get() == buffer_) { Expr local_index, group; std::tie(local_index, group) = SplitIndexByGroup(op->index); return Store::make(op->buffer_var, op->value, local_index, op->predicate); } else { return IRMutator::Mutate_(op, stmt); } } Expr Mutate_(const Load* op, const Expr& expr) { if (op->buffer_var.get() == buffer_) { Expr local_index, group; std::tie(local_index, group) = SplitIndexByGroup(op->index); // invariance: local index must do not contain warp id CHECK(!ExprUseVar(local_index, {warp_index_.get()})) << "LowerWarpMemory failed to rewrite load to shuffle for index " << op->index << " local_index=" << local_index; Expr load_value = Load::make( op->type, op->buffer_var, local_index, op->predicate); return Call::make(load_value.type(), intrinsic::tvm_warp_shuffle, {load_value, group}, Call::Intrinsic); } else { return IRMutator::Mutate_(op, expr); } } // Split the index to the two component // <local_index, source_index> // local index is the index in the local // source index is the corresponding source index // in this access pattern. std::pair<Expr, Expr> SplitIndexByGroup(const Expr& index) { if (index.type().lanes() != 1) { Expr base, local_index, group; CHECK(GetRamp1Base(index, index.type().lanes(), &base)); std::tie(local_index, group) = SplitIndexByGroup(base); local_index = Ramp::make(local_index, make_const(local_index.type(), 1), index.type().lanes()); return std::make_pair(local_index, group); } Expr m = make_const(index.type(), warp_coeff_); Range rng = Range::make_by_min_extent( make_zero(index.type()), make_const(index.type(), warp_size_)); Map<Var, Range> vrange({{warp_index_, rng}}); // simple case, warp index is on the highest. if (warp_group_ == 1) { Expr x = Simplify(index % m, vrange); Expr z = Simplify(index / m, vrange); return std::make_pair(x, z); } else { Expr x = Simplify(index % m, vrange); Expr y = index / make_const(index.type(), warp_coeff_ * warp_size_); y = y * m + x; Expr z = index % make_const(index.type(), warp_coeff_ * warp_size_) / m; return std::make_pair(Simplify(y, vrange), Simplify(z, vrange)); } } private: // the warp size int warp_size_{0}; // The buffer variable const Variable* buffer_; // Warp index Var warp_index_; // the coefficient m int warp_coeff_{0}; // the coefficient n int warp_group_{0}; }; // Mutator to change the read pattern class WarpMemoryRewriter : private IRMutator { public: explicit WarpMemoryRewriter(int warp_size) : warp_size_(warp_size) { } ~WarpMemoryRewriter() {} Stmt Rewrite(Stmt stmt) { if (warp_size_ == 1) return stmt; stmt = this->Mutate(stmt); stmt = CanonicalSimplify(stmt); return stmt; } private: Stmt Mutate_(const Allocate* op, const Stmt& stmt) { if (warp_buffer_.count(op->buffer_var.get())) { WarpAccessRewriter rewriter(warp_size_); return rewriter.Rewrite(op, stmt); } else { return IRMutator::Mutate_(op, stmt); } } Stmt Mutate_(const AttrStmt* op, const Stmt& stmt) { using runtime::StorageScope; if (op->attr_key == attr::storage_scope) { const Variable* buf = op->node.as<Variable>(); StorageScope scope = StorageScope::make(op->value.as<StringImm>()->value); if (scope.rank == runtime::StorageRank::kWarp) { warp_buffer_.insert(buf); Stmt ret = IRMutator::Mutate_(op, stmt); op = ret.as<AttrStmt>(); return AttrStmt::make( op->node, op->attr_key, StringImm::make("local"), op->body); } } return IRMutator::Mutate_(op, stmt); } int warp_size_{0}; std::unordered_set<const Variable*> warp_buffer_; }; LoweredFunc LowerWarpMemory(LoweredFunc f, int warp_size) { CHECK_EQ(f->func_type, kDeviceFunc); auto n = make_node<LoweredFuncNode>(*f.operator->()); n->body = WarpMemoryRewriter(warp_size).Rewrite(n->body); return LoweredFunc(n); } } // namespace ir } // namespace tvm
10,604
3,662
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/canbus/vehicle/lexus/protocol/lat_lon_heading_rpt_40e.h" #include "glog/logging.h" #include "modules/drivers/canbus/common/byte.h" #include "modules/drivers/canbus/common/canbus_consts.h" namespace apollo { namespace canbus { namespace lexus { using ::apollo::drivers::canbus::Byte; Latlonheadingrpt40e::Latlonheadingrpt40e() {} const int32_t Latlonheadingrpt40e::ID = 0x40E; void Latlonheadingrpt40e::Parse(const std::uint8_t* bytes, int32_t length, ChassisDetail* chassis) const { chassis->mutable_lexus()->mutable_lat_lon_heading_rpt_40e()->set_heading( heading(bytes, length)); chassis->mutable_lexus() ->mutable_lat_lon_heading_rpt_40e() ->set_longitude_seconds(longitude_seconds(bytes, length)); chassis->mutable_lexus() ->mutable_lat_lon_heading_rpt_40e() ->set_longitude_minutes(longitude_minutes(bytes, length)); chassis->mutable_lexus() ->mutable_lat_lon_heading_rpt_40e() ->set_longitude_degrees(longitude_degrees(bytes, length)); chassis->mutable_lexus() ->mutable_lat_lon_heading_rpt_40e() ->set_latitude_seconds(latitude_seconds(bytes, length)); chassis->mutable_lexus() ->mutable_lat_lon_heading_rpt_40e() ->set_latitude_minutes(latitude_minutes(bytes, length)); chassis->mutable_lexus() ->mutable_lat_lon_heading_rpt_40e() ->set_latitude_degrees(latitude_degrees(bytes, length)); } // config detail: {'name': 'heading', 'offset': 0.0, 'precision': 0.01, 'len': // 16, 'is_signed_var': True, 'physical_range': '[-327.68|327.67]', 'bit': 55, // 'type': 'double', 'order': 'motorola', 'physical_unit': 'deg'} double Latlonheadingrpt40e::heading(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(0, 8); Byte t1(bytes + 7); int32_t t = t1.get_byte(0, 8); x <<= 8; x |= t; x <<= 16; x >>= 16; double ret = x * 0.010000; return ret; } // config detail: {'name': 'longitude_seconds', 'offset': 0.0, 'precision': 1.0, // 'len': 8, 'is_signed_var': True, 'physical_range': '[-128|127]', 'bit': 47, // 'type': 'int', 'order': 'motorola', 'physical_unit': 'sec'} int Latlonheadingrpt40e::longitude_seconds(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 5); int32_t x = t0.get_byte(0, 8); x <<= 24; x >>= 24; int ret = x; return ret; } // config detail: {'name': 'longitude_minutes', 'offset': 0.0, 'precision': 1.0, // 'len': 8, 'is_signed_var': True, 'physical_range': '[-128|127]', 'bit': 39, // 'type': 'int', 'order': 'motorola', 'physical_unit': 'min'} int Latlonheadingrpt40e::longitude_minutes(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 4); int32_t x = t0.get_byte(0, 8); x <<= 24; x >>= 24; int ret = x; return ret; } // config detail: {'name': 'longitude_degrees', 'offset': 0.0, 'precision': 1.0, // 'len': 8, 'is_signed_var': True, 'physical_range': '[-128|127]', 'bit': 31, // 'type': 'int', 'order': 'motorola', 'physical_unit': 'deg'} int Latlonheadingrpt40e::longitude_degrees(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 3); int32_t x = t0.get_byte(0, 8); x <<= 24; x >>= 24; int ret = x; return ret; } // config detail: {'name': 'latitude_seconds', 'offset': 0.0, 'precision': 1.0, // 'len': 8, 'is_signed_var': True, 'physical_range': '[-128|127]', 'bit': 23, // 'type': 'int', 'order': 'motorola', 'physical_unit': 'sec'} int Latlonheadingrpt40e::latitude_seconds(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 2); int32_t x = t0.get_byte(0, 8); x <<= 24; x >>= 24; int ret = x; return ret; } // config detail: {'name': 'latitude_minutes', 'offset': 0.0, 'precision': 1.0, // 'len': 8, 'is_signed_var': True, 'physical_range': '[-128|127]', 'bit': 15, // 'type': 'int', 'order': 'motorola', 'physical_unit': 'min'} int Latlonheadingrpt40e::latitude_minutes(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 1); int32_t x = t0.get_byte(0, 8); x <<= 24; x >>= 24; int ret = x; return ret; } // config detail: {'name': 'latitude_degrees', 'offset': 0.0, 'precision': 1.0, // 'len': 8, 'is_signed_var': True, 'physical_range': '[-128|127]', 'bit': 7, // 'type': 'int', 'order': 'motorola', 'physical_unit': 'deg'} int Latlonheadingrpt40e::latitude_degrees(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); int32_t x = t0.get_byte(0, 8); x <<= 24; x >>= 24; int ret = x; return ret; } } // namespace lexus } // namespace canbus } // namespace apollo
5,667
2,280
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // #include "../cuda_cudnn.hpp" #include "../cuda_cudnn.hpp" #include "../cuda_emitter.hpp" #include "../cuda_langunit.hpp" #include "nnfusion/core/operators/generic_op/generic_op.hpp" namespace nnfusion { namespace kernels { namespace cuda { class LayerNorm : public CudaLibEmitter { shared_ptr<nnfusion::op::GenericOp> generic_op; public: LayerNorm(shared_ptr<KernelContext> ctx) : CudaLibEmitter(ctx) , generic_op( static_pointer_cast<nnfusion::op::GenericOp>(ctx->gnode->get_op_ptr())) { GENERIC_OP_LOGGING(); } LanguageUnit_p emit_function_body() override { GENERIC_OP_LOGGING(); const nnfusion::Shape& input_shape = m_context->inputs[0]->get_shape(); auto& cfg = generic_op->localOpConfig.getRoot(); float eps = cfg["epsilon"]; int axis = cfg["axis"]; axis += axis < 0 ? input_shape.size() : 0; size_t n1 = 1, n2 = 1; for (auto i = 0; i < axis; i++) { n1 *= input_shape[i]; } for (auto i = axis; i < input_shape.size(); i++) { n2 *= input_shape[i]; } nnfusion::element::Type dtype = m_context->inputs[0]->get_element_type(); LanguageUnit_p _lu(new LanguageUnit(get_function_name())); auto& lu = *_lu; // lu << "HostApplyLayerNorm(output0," // << " output1," // << " output2," // << " input0," << n1 << "," << n2 << "," << eps << "," // << " input1," // << " input2);\n"; auto code = nnfusion::op::create_code_from_template( R"( HostApplyLayerNorm<@dtype@>( output0, output1, output2, input0, @n1@, @n2@, @expression1@@eps@@expression2@, input1, input2); )", {{"n1", n1}, {"n2", n2}, {"dtype", (dtype == element::f16) ? "half" : "float"}, {"expression1", (dtype == element::f16) ? "__float2half_rn(" : ""}, {"expression2", (dtype == element::f16) ? ")" : ""}, {"eps", eps}}); lu << code << "\n"; return _lu; } LanguageUnit_p emit_dependency() override { GENERIC_OP_LOGGING(); LanguageUnit_p _lu(new LanguageUnit(get_function_name() + "_dep")); _lu->require(header::cuda); _lu->require(declaration::cuda_layer_norm); declaration::cuda_layer_norm->require(declaration::math_Rsqrt); declaration::cuda_layer_norm->require(declaration::warp); return _lu; } }; } // namespace cuda } // namespace kernels } // namespace nnfusion // Register kernel emitter using namespace nnfusion; using namespace nnfusion::kernels; REGISTER_KERNEL_EMITTER("LayerNorm", // op_name Device(CUDA_GPU).TypeConstraint(element::f32).Tag("cudalib"), // attrs cuda::LayerNorm) // constructor
3,812
1,101
// // Created by o2173194 on 04/03/20. // #include <gtk/gtk.h> #include <cctype> static void enter_callback( GtkWidget *widget, GtkWidget *entry ) { const gchar *entry_text; entry_text = gtk_entry_get_text (GTK_ENTRY (entry)); printf ("Entry contents: %s\n", entry_text); } void insert_text_event(GtkEditable *editable, const gchar *text, gint length, gint *position, gpointer data) { int i; for (i = 0; i < length; i++) { if (!isdigit(text[i])) { g_signal_stop_emission_by_name(G_OBJECT(editable), "insert-text"); return; } } } /* * Initialize GTK Window and all widgets * */ int main(int argc, char *argv[]) { /*Initialization of widgets*/ GtkWidget *window, *button, *input1, *input2, *vbox, *hbox; /*Init*/ gtk_init(&argc, &argv); /* Creation of a new window */ window = gtk_window_new(GTK_WINDOW_TOPLEVEL); vbox = gtk_vbox_new(FALSE, 0); gtk_container_add (GTK_CONTAINER (window), vbox); gtk_widget_show (vbox); input1 = gtk_entry_new(); gtk_entry_set_max_length (GTK_ENTRY (input1), 3); g_signal_connect (input1, "activate", G_CALLBACK (enter_callback), input1); g_signal_connect(G_OBJECT(input1), "insert_text", G_CALLBACK(insert_text_event), NULL); gtk_box_pack_start (GTK_BOX (vbox), input1, TRUE, TRUE, 0); gtk_widget_show (input1); input2 = gtk_entry_new(); gtk_entry_set_max_length (GTK_ENTRY (input2), 3); g_signal_connect (input2, "activate", G_CALLBACK (enter_callback), input2); g_signal_connect(G_OBJECT(input2), "insert_text", G_CALLBACK(insert_text_event), NULL); gtk_box_pack_start (GTK_BOX (vbox), input2, TRUE, TRUE, 0); gtk_widget_show (input2); hbox = gtk_hbox_new(FALSE, 0); gtk_container_add (GTK_CONTAINER (vbox), hbox); gtk_widget_show (hbox); button = gtk_button_new_with_label ("Submit to server"); g_signal_connect(button, "clicked", G_CALLBACK (enter_callback), window); gtk_box_pack_start (GTK_BOX (vbox), button, TRUE, TRUE, 0); gtk_widget_show (button); // /* This function will WRITE all the modifications of the SVG in the XMLFile*/ // svg_data.SaveFile("../Resources/Image Samples/atom.svg"); /* * Connecting all the events to the GTK window * */ g_signal_connect(window, "destroy", G_CALLBACK(gtk_main_quit), NULL); /* Configuration of the window */ gtk_container_set_border_width (GTK_CONTAINER (window), 10); gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER); gtk_window_set_default_size(GTK_WINDOW(window), 275, 275); gtk_window_set_title(GTK_WINDOW(window), "Client SVG"); /* * This will show all the widgets in the window * */ gtk_widget_show_all(window); gtk_main(); return 0; }
3,016
1,133
#include <nano/crypto_lib/random_pool.hpp> #include <nano/lib/config.hpp> #include <nano/lib/threading.hpp> #include <nano/node/common.hpp> #include <nano/node/testing.hpp> #include <nano/qt/qt.hpp> #include <boost/format.hpp> #include <thread> int main (int argc, char ** argv) { nano::force_nano_test_network (); nano::node_singleton_memory_pool_purge_guard memory_pool_cleanup_guard; QApplication application (argc, argv); QCoreApplication::setOrganizationName ("Nano"); QCoreApplication::setOrganizationDomain ("nano.org"); QCoreApplication::setApplicationName ("Nano Wallet"); nano_qt::eventloop_processor processor; const uint16_t count (16); nano::system system (count); nano::thread_runner runner (system.io_ctx, system.nodes[0]->config.io_threads); std::unique_ptr<QTabWidget> client_tabs (new QTabWidget); std::vector<std::unique_ptr<nano_qt::wallet>> guis; for (auto i (0); i < count; ++i) { auto wallet (system.nodes[i]->wallets.create (nano::random_wallet_id ())); nano::keypair key; wallet->insert_adhoc (key.prv); guis.push_back (std::make_unique<nano_qt::wallet> (application, processor, *system.nodes[i], wallet, key.pub)); client_tabs->addTab (guis.back ()->client_window, boost::str (boost::format ("Wallet %1%") % i).c_str ()); } client_tabs->show (); QObject::connect (&application, &QApplication::aboutToQuit, [&]() { system.stop (); }); int result; try { result = application.exec (); } catch (...) { result = -1; debug_assert (false); } runner.join (); return result; }
1,541
595
///////////////////////////////////////////////////////////////////////////// // Name: src/richtext/richtextliststylepage.cpp // Purpose: // Author: Julian Smart // Modified by: // Created: 10/18/2006 11:36:37 AM // RCS-ID: $Id$ // Copyright: (c) Julian Smart // Licence: wxWindows licence ///////////////////////////////////////////////////////////////////////////// #include "wx/richtext/richtextliststylepage.h" ////@begin XPM images ////@end XPM images /*! * wxRichTextListStylePage type definition */ IMPLEMENT_DYNAMIC_CLASS( wxRichTextListStylePage, wxPanel ) /*! * wxRichTextListStylePage event table definition */ BEGIN_EVENT_TABLE( wxRichTextListStylePage, wxPanel ) ////@begin wxRichTextListStylePage event table entries EVT_SPINCTRL( ID_RICHTEXTLISTSTYLEPAGE_LEVEL, wxRichTextListStylePage::OnLevelUpdated ) EVT_SPIN_UP( ID_RICHTEXTLISTSTYLEPAGE_LEVEL, wxRichTextListStylePage::OnLevelUp ) EVT_SPIN_DOWN( ID_RICHTEXTLISTSTYLEPAGE_LEVEL, wxRichTextListStylePage::OnLevelDown ) EVT_TEXT( ID_RICHTEXTLISTSTYLEPAGE_LEVEL, wxRichTextListStylePage::OnLevelTextUpdated ) EVT_UPDATE_UI( ID_RICHTEXTLISTSTYLEPAGE_LEVEL, wxRichTextListStylePage::OnLevelUIUpdate ) EVT_BUTTON( ID_RICHTEXTLISTSTYLEPAGE_CHOOSE_FONT, wxRichTextListStylePage::OnChooseFontClick ) EVT_LISTBOX( ID_RICHTEXTLISTSTYLEPAGE_STYLELISTBOX, wxRichTextListStylePage::OnStylelistboxSelected ) EVT_CHECKBOX( ID_RICHTEXTLISTSTYLEPAGE_PERIODCTRL, wxRichTextListStylePage::OnPeriodctrlClick ) EVT_UPDATE_UI( ID_RICHTEXTLISTSTYLEPAGE_PERIODCTRL, wxRichTextListStylePage::OnPeriodctrlUpdate ) EVT_CHECKBOX( ID_RICHTEXTLISTSTYLEPAGE_PARENTHESESCTRL, wxRichTextListStylePage::OnParenthesesctrlClick ) EVT_UPDATE_UI( ID_RICHTEXTLISTSTYLEPAGE_PARENTHESESCTRL, wxRichTextListStylePage::OnParenthesesctrlUpdate ) EVT_CHECKBOX( ID_RICHTEXTLISTSTYLEPAGE_RIGHTPARENTHESISCTRL, wxRichTextListStylePage::OnRightParenthesisCtrlClick ) EVT_UPDATE_UI( ID_RICHTEXTLISTSTYLEPAGE_RIGHTPARENTHESISCTRL, wxRichTextListStylePage::OnRightParenthesisCtrlUpdate ) EVT_COMBOBOX( ID_RICHTEXTLISTSTYLEPAGE_BULLETALIGNMENTCTRL, wxRichTextListStylePage::OnBulletAlignmentCtrlSelected ) EVT_UPDATE_UI( ID_RICHTEXTLISTSTYLEPAGE_SYMBOLSTATIC, wxRichTextListStylePage::OnSymbolstaticUpdate ) EVT_COMBOBOX( ID_RICHTEXTLISTSTYLEPAGE_SYMBOLCTRL, wxRichTextListStylePage::OnSymbolctrlSelected ) EVT_TEXT( ID_RICHTEXTLISTSTYLEPAGE_SYMBOLCTRL, wxRichTextListStylePage::OnSymbolctrlUpdated ) EVT_UPDATE_UI( ID_RICHTEXTLISTSTYLEPAGE_SYMBOLCTRL, wxRichTextListStylePage::OnSymbolctrlUIUpdate ) EVT_BUTTON( ID_RICHTEXTLISTSTYLEPAGE_CHOOSE_SYMBOL, wxRichTextListStylePage::OnChooseSymbolClick ) EVT_UPDATE_UI( ID_RICHTEXTLISTSTYLEPAGE_CHOOSE_SYMBOL, wxRichTextListStylePage::OnChooseSymbolUpdate ) EVT_COMBOBOX( ID_RICHTEXTLISTSTYLEPAGE_SYMBOLFONTCTRL, wxRichTextListStylePage::OnSymbolfontctrlSelected ) EVT_TEXT( ID_RICHTEXTLISTSTYLEPAGE_SYMBOLFONTCTRL, wxRichTextListStylePage::OnSymbolfontctrlUpdated ) EVT_UPDATE_UI( ID_RICHTEXTLISTSTYLEPAGE_SYMBOLFONTCTRL, wxRichTextListStylePage::OnSymbolfontctrlUIUpdate ) EVT_UPDATE_UI( ID_RICHTEXTLISTSTYLEPAGE_NAMESTATIC, wxRichTextListStylePage::OnNamestaticUpdate ) EVT_COMBOBOX( ID_RICHTEXTLISTSTYLEPAGE_NAMECTRL, wxRichTextListStylePage::OnNamectrlSelected ) EVT_TEXT( ID_RICHTEXTLISTSTYLEPAGE_NAMECTRL, wxRichTextListStylePage::OnNamectrlUpdated ) EVT_UPDATE_UI( ID_RICHTEXTLISTSTYLEPAGE_NAMECTRL, wxRichTextListStylePage::OnNamectrlUIUpdate ) EVT_RADIOBUTTON( ID_RICHTEXTLISTSTYLEPAGE_ALIGNLEFT, wxRichTextListStylePage::OnRichtextliststylepageAlignleftSelected ) EVT_RADIOBUTTON( ID_RICHTEXTLISTSTYLEPAGE_ALIGNRIGHT, wxRichTextListStylePage::OnRichtextliststylepageAlignrightSelected ) EVT_RADIOBUTTON( ID_RICHTEXTLISTSTYLEPAGE_JUSTIFIED, wxRichTextListStylePage::OnRichtextliststylepageJustifiedSelected ) EVT_RADIOBUTTON( ID_RICHTEXTLISTSTYLEPAGE_CENTERED, wxRichTextListStylePage::OnRichtextliststylepageCenteredSelected ) EVT_RADIOBUTTON( ID_RICHTEXTLISTSTYLEPAGE_ALIGNINDETERMINATE, wxRichTextListStylePage::OnRichtextliststylepageAlignindeterminateSelected ) EVT_TEXT( ID_RICHTEXTLISTSTYLEPAGE_INDENTLEFT, wxRichTextListStylePage::OnIndentLeftUpdated ) EVT_TEXT( ID_RICHTEXTLISTSTYLEPAGE_INDENTFIRSTLINE, wxRichTextListStylePage::OnIndentFirstLineUpdated ) EVT_TEXT( ID_RICHTEXTLISTSTYLEPAGE_INDENTRIGHT, wxRichTextListStylePage::OnIndentRightUpdated ) EVT_TEXT( ID_RICHTEXTLISTSTYLEPAGE_SPACINGBEFORE, wxRichTextListStylePage::OnSpacingBeforeUpdated ) EVT_TEXT( ID_RICHTEXTLISTSTYLEPAGE_SPACINGAFTER, wxRichTextListStylePage::OnSpacingAfterUpdated ) EVT_COMBOBOX( ID_RICHTEXTLISTSTYLEPAGE_LINESPACING, wxRichTextListStylePage::OnLineSpacingSelected ) ////@end wxRichTextListStylePage event table entries END_EVENT_TABLE() /*! * wxRichTextListStylePage constructors */ wxRichTextListStylePage::wxRichTextListStylePage( ) { Init(); } wxRichTextListStylePage::wxRichTextListStylePage( wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style ) { Init(); Create(parent, id, pos, size, style); } /*! * wxRichTextListStylePage creator */ bool wxRichTextListStylePage::Create( wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style ) { ////@begin wxRichTextListStylePage creation wxPanel::Create( parent, id, pos, size, style ); CreateControls(); if (GetSizer()) { GetSizer()->SetSizeHints(this); } Centre(); ////@end wxRichTextListStylePage creation return true; } /*! * Member initialisation */ void wxRichTextListStylePage::Init() { m_dontUpdate = false; m_currentLevel = 1; ////@begin wxRichTextListStylePage member initialisation m_levelCtrl = NULL; m_styleListBox = NULL; m_periodCtrl = NULL; m_parenthesesCtrl = NULL; m_rightParenthesisCtrl = NULL; m_bulletAlignmentCtrl = NULL; m_symbolCtrl = NULL; m_symbolFontCtrl = NULL; m_bulletNameCtrl = NULL; m_alignmentLeft = NULL; m_alignmentRight = NULL; m_alignmentJustified = NULL; m_alignmentCentred = NULL; m_alignmentIndeterminate = NULL; m_indentLeft = NULL; m_indentLeftFirst = NULL; m_indentRight = NULL; m_spacingBefore = NULL; m_spacingAfter = NULL; m_spacingLine = NULL; m_previewCtrl = NULL; ////@end wxRichTextListStylePage member initialisation } /*! * Control creation for wxRichTextListStylePage */ void wxRichTextListStylePage::CreateControls() { ////@begin wxRichTextListStylePage content construction wxRichTextListStylePage* itemPanel1 = this; wxBoxSizer* itemBoxSizer2 = new wxBoxSizer(wxVERTICAL); itemPanel1->SetSizer(itemBoxSizer2); wxBoxSizer* itemBoxSizer3 = new wxBoxSizer(wxVERTICAL); itemBoxSizer2->Add(itemBoxSizer3, 1, wxGROW|wxALL, 5); wxBoxSizer* itemBoxSizer4 = new wxBoxSizer(wxHORIZONTAL); itemBoxSizer3->Add(itemBoxSizer4, 0, wxALIGN_CENTER_HORIZONTAL, 5); wxStaticText* itemStaticText5 = new wxStaticText( itemPanel1, wxID_STATIC, _("&List level:"), wxDefaultPosition, wxDefaultSize, 0 ); itemBoxSizer4->Add(itemStaticText5, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5); m_levelCtrl = new wxSpinCtrl( itemPanel1, ID_RICHTEXTLISTSTYLEPAGE_LEVEL, wxT("1"), wxDefaultPosition, wxSize(60, -1), wxSP_ARROW_KEYS, 1, 10, 1 ); m_levelCtrl->SetHelpText(_("Selects the list level to edit.")); if (wxRichTextListStylePage::ShowToolTips()) m_levelCtrl->SetToolTip(_("Selects the list level to edit.")); itemBoxSizer4->Add(m_levelCtrl, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5); itemBoxSizer4->Add(5, 5, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5); wxButton* itemButton8 = new wxButton( itemPanel1, ID_RICHTEXTLISTSTYLEPAGE_CHOOSE_FONT, _("&Font for Level..."), wxDefaultPosition, wxDefaultSize, 0 ); itemButton8->SetHelpText(_("Click to choose the font for this level.")); if (wxRichTextListStylePage::ShowToolTips()) itemButton8->SetToolTip(_("Click to choose the font for this level.")); itemBoxSizer4->Add(itemButton8, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5); wxNotebook* itemNotebook9 = new wxNotebook( itemPanel1, ID_RICHTEXTLISTSTYLEPAGE_NOTEBOOK, wxDefaultPosition, wxDefaultSize, wxNB_DEFAULT|wxNB_TOP ); wxPanel* itemPanel10 = new wxPanel( itemNotebook9, ID_RICHTEXTLISTSTYLEPAGE_BULLETS, wxDefaultPosition, wxDefaultSize, wxNO_BORDER|wxTAB_TRAVERSAL ); wxBoxSizer* itemBoxSizer11 = new wxBoxSizer(wxVERTICAL); itemPanel10->SetSizer(itemBoxSizer11); wxBoxSizer* itemBoxSizer12 = new wxBoxSizer(wxHORIZONTAL); itemBoxSizer11->Add(itemBoxSizer12, 1, wxGROW, 5); wxBoxSizer* itemBoxSizer13 = new wxBoxSizer(wxVERTICAL); itemBoxSizer12->Add(itemBoxSizer13, 0, wxGROW, 5); wxStaticText* itemStaticText14 = new wxStaticText( itemPanel10, wxID_STATIC, _("&Bullet style:"), wxDefaultPosition, wxDefaultSize, 0 ); itemBoxSizer13->Add(itemStaticText14, 0, wxALIGN_LEFT|wxLEFT|wxRIGHT|wxTOP, 5); wxArrayString m_styleListBoxStrings; m_styleListBox = new wxListBox( itemPanel10, ID_RICHTEXTLISTSTYLEPAGE_STYLELISTBOX, wxDefaultPosition, wxSize(-1, 140), m_styleListBoxStrings, wxLB_SINGLE ); m_styleListBox->SetHelpText(_("The available bullet styles.")); if (wxRichTextListStylePage::ShowToolTips()) m_styleListBox->SetToolTip(_("The available bullet styles.")); itemBoxSizer13->Add(m_styleListBox, 1, wxGROW|wxALL, 5); wxBoxSizer* itemBoxSizer16 = new wxBoxSizer(wxHORIZONTAL); itemBoxSizer13->Add(itemBoxSizer16, 0, wxGROW, 5); m_periodCtrl = new wxCheckBox( itemPanel10, ID_RICHTEXTLISTSTYLEPAGE_PERIODCTRL, _("Peri&od"), wxDefaultPosition, wxDefaultSize, 0 ); m_periodCtrl->SetValue(false); m_periodCtrl->SetHelpText(_("Check to add a period after the bullet.")); if (wxRichTextListStylePage::ShowToolTips()) m_periodCtrl->SetToolTip(_("Check to add a period after the bullet.")); itemBoxSizer16->Add(m_periodCtrl, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5); m_parenthesesCtrl = new wxCheckBox( itemPanel10, ID_RICHTEXTLISTSTYLEPAGE_PARENTHESESCTRL, _("(*)"), wxDefaultPosition, wxDefaultSize, 0 ); m_parenthesesCtrl->SetValue(false); m_parenthesesCtrl->SetHelpText(_("Check to enclose the bullet in parentheses.")); if (wxRichTextListStylePage::ShowToolTips()) m_parenthesesCtrl->SetToolTip(_("Check to enclose the bullet in parentheses.")); itemBoxSizer16->Add(m_parenthesesCtrl, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5); m_rightParenthesisCtrl = new wxCheckBox( itemPanel10, ID_RICHTEXTLISTSTYLEPAGE_RIGHTPARENTHESISCTRL, _("*)"), wxDefaultPosition, wxDefaultSize, 0 ); m_rightParenthesisCtrl->SetValue(false); m_rightParenthesisCtrl->SetHelpText(_("Check to add a right parenthesis.")); if (wxRichTextListStylePage::ShowToolTips()) m_rightParenthesisCtrl->SetToolTip(_("Check to add a right parenthesis.")); itemBoxSizer16->Add(m_rightParenthesisCtrl, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5); itemBoxSizer13->Add(2, 1, 0, wxALIGN_CENTER_HORIZONTAL, 5); wxStaticText* itemStaticText21 = new wxStaticText( itemPanel10, wxID_STATIC, _("Bullet &Alignment:"), wxDefaultPosition, wxDefaultSize, 0 ); itemBoxSizer13->Add(itemStaticText21, 0, wxALIGN_LEFT|wxLEFT|wxRIGHT|wxTOP, 5); wxArrayString m_bulletAlignmentCtrlStrings; m_bulletAlignmentCtrlStrings.Add(_("Left")); m_bulletAlignmentCtrlStrings.Add(_("Centre")); m_bulletAlignmentCtrlStrings.Add(_("Right")); m_bulletAlignmentCtrl = new wxComboBox( itemPanel10, ID_RICHTEXTLISTSTYLEPAGE_BULLETALIGNMENTCTRL, _("Left"), wxDefaultPosition, wxSize(60, -1), m_bulletAlignmentCtrlStrings, wxCB_READONLY ); m_bulletAlignmentCtrl->SetStringSelection(_("Left")); m_bulletAlignmentCtrl->SetHelpText(_("The bullet character.")); if (wxRichTextListStylePage::ShowToolTips()) m_bulletAlignmentCtrl->SetToolTip(_("The bullet character.")); itemBoxSizer13->Add(m_bulletAlignmentCtrl, 0, wxGROW|wxALL|wxFIXED_MINSIZE, 5); itemBoxSizer12->Add(2, 1, 1, wxALIGN_CENTER_VERTICAL|wxTOP|wxBOTTOM, 5); wxStaticLine* itemStaticLine24 = new wxStaticLine( itemPanel10, wxID_STATIC, wxDefaultPosition, wxDefaultSize, wxLI_VERTICAL ); itemBoxSizer12->Add(itemStaticLine24, 0, wxGROW|wxALL, 5); itemBoxSizer12->Add(2, 1, 1, wxALIGN_CENTER_VERTICAL|wxTOP|wxBOTTOM, 5); wxBoxSizer* itemBoxSizer26 = new wxBoxSizer(wxVERTICAL); itemBoxSizer12->Add(itemBoxSizer26, 0, wxGROW, 5); wxStaticText* itemStaticText27 = new wxStaticText( itemPanel10, ID_RICHTEXTLISTSTYLEPAGE_SYMBOLSTATIC, _("&Symbol:"), wxDefaultPosition, wxDefaultSize, 0 ); itemBoxSizer26->Add(itemStaticText27, 0, wxALIGN_LEFT|wxLEFT|wxRIGHT|wxTOP, 5); wxBoxSizer* itemBoxSizer28 = new wxBoxSizer(wxHORIZONTAL); itemBoxSizer26->Add(itemBoxSizer28, 0, wxGROW, 5); wxArrayString m_symbolCtrlStrings; m_symbolCtrl = new wxComboBox( itemPanel10, ID_RICHTEXTLISTSTYLEPAGE_SYMBOLCTRL, wxT(""), wxDefaultPosition, wxSize(60, -1), m_symbolCtrlStrings, wxCB_DROPDOWN ); m_symbolCtrl->SetHelpText(_("The bullet character.")); if (wxRichTextListStylePage::ShowToolTips()) m_symbolCtrl->SetToolTip(_("The bullet character.")); itemBoxSizer28->Add(m_symbolCtrl, 0, wxALIGN_CENTER_VERTICAL|wxALL|wxFIXED_MINSIZE, 5); wxButton* itemButton30 = new wxButton( itemPanel10, ID_RICHTEXTLISTSTYLEPAGE_CHOOSE_SYMBOL, _("Ch&oose..."), wxDefaultPosition, wxDefaultSize, 0 ); itemButton30->SetHelpText(_("Click to browse for a symbol.")); if (wxRichTextListStylePage::ShowToolTips()) itemButton30->SetToolTip(_("Click to browse for a symbol.")); itemBoxSizer28->Add(itemButton30, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5); itemBoxSizer26->Add(5, 5, 0, wxALIGN_CENTER_HORIZONTAL, 5); wxStaticText* itemStaticText32 = new wxStaticText( itemPanel10, ID_RICHTEXTLISTSTYLEPAGE_SYMBOLSTATIC, _("Symbol &font:"), wxDefaultPosition, wxDefaultSize, 0 ); itemBoxSizer26->Add(itemStaticText32, 0, wxALIGN_LEFT|wxLEFT|wxRIGHT|wxTOP, 5); wxArrayString m_symbolFontCtrlStrings; m_symbolFontCtrl = new wxComboBox( itemPanel10, ID_RICHTEXTLISTSTYLEPAGE_SYMBOLFONTCTRL, wxT(""), wxDefaultPosition, wxDefaultSize, m_symbolFontCtrlStrings, wxCB_DROPDOWN ); if (wxRichTextListStylePage::ShowToolTips()) m_symbolFontCtrl->SetToolTip(_("Available fonts.")); itemBoxSizer26->Add(m_symbolFontCtrl, 0, wxGROW|wxALL, 5); itemBoxSizer26->Add(5, 5, 1, wxALIGN_CENTER_HORIZONTAL, 5); wxStaticText* itemStaticText35 = new wxStaticText( itemPanel10, ID_RICHTEXTLISTSTYLEPAGE_NAMESTATIC, _("S&tandard bullet name:"), wxDefaultPosition, wxDefaultSize, 0 ); itemBoxSizer26->Add(itemStaticText35, 0, wxALIGN_LEFT|wxLEFT|wxRIGHT|wxTOP, 5); wxArrayString m_bulletNameCtrlStrings; m_bulletNameCtrl = new wxComboBox( itemPanel10, ID_RICHTEXTLISTSTYLEPAGE_NAMECTRL, wxT(""), wxDefaultPosition, wxDefaultSize, m_bulletNameCtrlStrings, wxCB_DROPDOWN ); m_bulletNameCtrl->SetHelpText(_("A standard bullet name.")); if (wxRichTextListStylePage::ShowToolTips()) m_bulletNameCtrl->SetToolTip(_("A standard bullet name.")); itemBoxSizer26->Add(m_bulletNameCtrl, 0, wxGROW|wxALL, 5); itemNotebook9->AddPage(itemPanel10, _("Bullet style")); wxPanel* itemPanel37 = new wxPanel( itemNotebook9, ID_RICHTEXTLISTSTYLEPAGE_SPACING, wxDefaultPosition, wxDefaultSize, wxNO_BORDER|wxTAB_TRAVERSAL ); wxBoxSizer* itemBoxSizer38 = new wxBoxSizer(wxVERTICAL); itemPanel37->SetSizer(itemBoxSizer38); wxBoxSizer* itemBoxSizer39 = new wxBoxSizer(wxHORIZONTAL); itemBoxSizer38->Add(itemBoxSizer39, 0, wxGROW, 5); wxBoxSizer* itemBoxSizer40 = new wxBoxSizer(wxVERTICAL); itemBoxSizer39->Add(itemBoxSizer40, 0, wxGROW, 5); wxStaticText* itemStaticText41 = new wxStaticText( itemPanel37, wxID_STATIC, _("&Alignment"), wxDefaultPosition, wxDefaultSize, 0 ); itemBoxSizer40->Add(itemStaticText41, 0, wxALIGN_LEFT|wxLEFT|wxRIGHT|wxTOP, 5); wxBoxSizer* itemBoxSizer42 = new wxBoxSizer(wxHORIZONTAL); itemBoxSizer40->Add(itemBoxSizer42, 0, wxALIGN_CENTER_HORIZONTAL|wxALL, 5); itemBoxSizer42->Add(5, 5, 0, wxALIGN_CENTER_VERTICAL, 5); wxBoxSizer* itemBoxSizer44 = new wxBoxSizer(wxVERTICAL); itemBoxSizer42->Add(itemBoxSizer44, 0, wxALIGN_CENTER_VERTICAL|wxTOP, 5); m_alignmentLeft = new wxRadioButton( itemPanel37, ID_RICHTEXTLISTSTYLEPAGE_ALIGNLEFT, _("&Left"), wxDefaultPosition, wxDefaultSize, wxRB_GROUP ); m_alignmentLeft->SetValue(false); m_alignmentLeft->SetHelpText(_("Left-align text.")); if (wxRichTextListStylePage::ShowToolTips()) m_alignmentLeft->SetToolTip(_("Left-align text.")); itemBoxSizer44->Add(m_alignmentLeft, 0, wxALIGN_LEFT|wxALL, 5); m_alignmentRight = new wxRadioButton( itemPanel37, ID_RICHTEXTLISTSTYLEPAGE_ALIGNRIGHT, _("&Right"), wxDefaultPosition, wxDefaultSize, 0 ); m_alignmentRight->SetValue(false); m_alignmentRight->SetHelpText(_("Right-align text.")); if (wxRichTextListStylePage::ShowToolTips()) m_alignmentRight->SetToolTip(_("Right-align text.")); itemBoxSizer44->Add(m_alignmentRight, 0, wxALIGN_LEFT|wxALL, 5); m_alignmentJustified = new wxRadioButton( itemPanel37, ID_RICHTEXTLISTSTYLEPAGE_JUSTIFIED, _("&Justified"), wxDefaultPosition, wxDefaultSize, 0 ); m_alignmentJustified->SetValue(false); m_alignmentJustified->SetHelpText(_("Justify text left and right.")); if (wxRichTextListStylePage::ShowToolTips()) m_alignmentJustified->SetToolTip(_("Justify text left and right.")); itemBoxSizer44->Add(m_alignmentJustified, 0, wxALIGN_LEFT|wxALL, 5); m_alignmentCentred = new wxRadioButton( itemPanel37, ID_RICHTEXTLISTSTYLEPAGE_CENTERED, _("Cen&tred"), wxDefaultPosition, wxDefaultSize, 0 ); m_alignmentCentred->SetValue(false); m_alignmentCentred->SetHelpText(_("Centre text.")); if (wxRichTextListStylePage::ShowToolTips()) m_alignmentCentred->SetToolTip(_("Centre text.")); itemBoxSizer44->Add(m_alignmentCentred, 0, wxALIGN_LEFT|wxALL, 5); m_alignmentIndeterminate = new wxRadioButton( itemPanel37, ID_RICHTEXTLISTSTYLEPAGE_ALIGNINDETERMINATE, _("&Indeterminate"), wxDefaultPosition, wxDefaultSize, 0 ); m_alignmentIndeterminate->SetValue(false); m_alignmentIndeterminate->SetHelpText(_("Use the current alignment setting.")); if (wxRichTextListStylePage::ShowToolTips()) m_alignmentIndeterminate->SetToolTip(_("Use the current alignment setting.")); itemBoxSizer44->Add(m_alignmentIndeterminate, 0, wxALIGN_LEFT|wxALL, 5); itemBoxSizer39->Add(2, 1, 1, wxALIGN_CENTER_VERTICAL|wxTOP|wxBOTTOM, 5); wxStaticLine* itemStaticLine51 = new wxStaticLine( itemPanel37, wxID_STATIC, wxDefaultPosition, wxDefaultSize, wxLI_VERTICAL ); itemBoxSizer39->Add(itemStaticLine51, 0, wxGROW|wxLEFT|wxBOTTOM, 5); itemBoxSizer39->Add(2, 1, 1, wxALIGN_CENTER_VERTICAL|wxTOP|wxBOTTOM, 5); wxBoxSizer* itemBoxSizer53 = new wxBoxSizer(wxVERTICAL); itemBoxSizer39->Add(itemBoxSizer53, 0, wxGROW, 5); wxStaticText* itemStaticText54 = new wxStaticText( itemPanel37, wxID_STATIC, _("&Indentation (tenths of a mm)"), wxDefaultPosition, wxDefaultSize, 0 ); itemBoxSizer53->Add(itemStaticText54, 0, wxALIGN_LEFT|wxLEFT|wxRIGHT|wxTOP, 5); wxBoxSizer* itemBoxSizer55 = new wxBoxSizer(wxHORIZONTAL); itemBoxSizer53->Add(itemBoxSizer55, 0, wxALIGN_LEFT|wxALL, 5); itemBoxSizer55->Add(5, 5, 0, wxALIGN_CENTER_VERTICAL, 5); wxFlexGridSizer* itemFlexGridSizer57 = new wxFlexGridSizer(2, 2, 0, 0); itemBoxSizer55->Add(itemFlexGridSizer57, 0, wxALIGN_CENTER_VERTICAL, 5); wxStaticText* itemStaticText58 = new wxStaticText( itemPanel37, wxID_STATIC, _("&Left:"), wxDefaultPosition, wxDefaultSize, 0 ); itemFlexGridSizer57->Add(itemStaticText58, 0, wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL|wxALL, 5); wxBoxSizer* itemBoxSizer59 = new wxBoxSizer(wxHORIZONTAL); itemFlexGridSizer57->Add(itemBoxSizer59, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5); m_indentLeft = new wxTextCtrl( itemPanel37, ID_RICHTEXTLISTSTYLEPAGE_INDENTLEFT, wxT(""), wxDefaultPosition, wxSize(50, -1), 0 ); m_indentLeft->SetHelpText(_("The left indent.")); if (wxRichTextListStylePage::ShowToolTips()) m_indentLeft->SetToolTip(_("The left indent.")); itemBoxSizer59->Add(m_indentLeft, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5); wxStaticText* itemStaticText61 = new wxStaticText( itemPanel37, wxID_STATIC, _("Left (&first line):"), wxDefaultPosition, wxDefaultSize, 0 ); itemFlexGridSizer57->Add(itemStaticText61, 0, wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL|wxALL, 5); wxBoxSizer* itemBoxSizer62 = new wxBoxSizer(wxHORIZONTAL); itemFlexGridSizer57->Add(itemBoxSizer62, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5); m_indentLeftFirst = new wxTextCtrl( itemPanel37, ID_RICHTEXTLISTSTYLEPAGE_INDENTFIRSTLINE, wxT(""), wxDefaultPosition, wxSize(50, -1), 0 ); m_indentLeftFirst->SetHelpText(_("The first line indent.")); if (wxRichTextListStylePage::ShowToolTips()) m_indentLeftFirst->SetToolTip(_("The first line indent.")); itemBoxSizer62->Add(m_indentLeftFirst, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5); wxStaticText* itemStaticText64 = new wxStaticText( itemPanel37, wxID_STATIC, _("&Right:"), wxDefaultPosition, wxDefaultSize, 0 ); itemFlexGridSizer57->Add(itemStaticText64, 0, wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL|wxALL, 5); wxBoxSizer* itemBoxSizer65 = new wxBoxSizer(wxHORIZONTAL); itemFlexGridSizer57->Add(itemBoxSizer65, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5); m_indentRight = new wxTextCtrl( itemPanel37, ID_RICHTEXTLISTSTYLEPAGE_INDENTRIGHT, wxT(""), wxDefaultPosition, wxSize(50, -1), 0 ); m_indentRight->SetHelpText(_("The right indent.")); if (wxRichTextListStylePage::ShowToolTips()) m_indentRight->SetToolTip(_("The right indent.")); itemBoxSizer65->Add(m_indentRight, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5); itemBoxSizer39->Add(2, 1, 1, wxALIGN_CENTER_VERTICAL|wxTOP|wxBOTTOM, 5); wxStaticLine* itemStaticLine68 = new wxStaticLine( itemPanel37, wxID_STATIC, wxDefaultPosition, wxDefaultSize, wxLI_VERTICAL ); itemBoxSizer39->Add(itemStaticLine68, 0, wxGROW|wxTOP|wxBOTTOM, 5); itemBoxSizer39->Add(2, 1, 1, wxALIGN_CENTER_VERTICAL|wxTOP|wxBOTTOM, 5); wxBoxSizer* itemBoxSizer70 = new wxBoxSizer(wxVERTICAL); itemBoxSizer39->Add(itemBoxSizer70, 0, wxGROW, 5); wxStaticText* itemStaticText71 = new wxStaticText( itemPanel37, wxID_STATIC, _("&Spacing (tenths of a mm)"), wxDefaultPosition, wxDefaultSize, 0 ); itemBoxSizer70->Add(itemStaticText71, 0, wxALIGN_LEFT|wxLEFT|wxRIGHT|wxTOP, 5); wxBoxSizer* itemBoxSizer72 = new wxBoxSizer(wxHORIZONTAL); itemBoxSizer70->Add(itemBoxSizer72, 0, wxALIGN_LEFT|wxALL, 5); itemBoxSizer72->Add(5, 5, 0, wxALIGN_CENTER_VERTICAL, 5); wxFlexGridSizer* itemFlexGridSizer74 = new wxFlexGridSizer(2, 2, 0, 0); itemBoxSizer72->Add(itemFlexGridSizer74, 0, wxALIGN_CENTER_VERTICAL, 5); wxStaticText* itemStaticText75 = new wxStaticText( itemPanel37, wxID_STATIC, _("Before a paragraph:"), wxDefaultPosition, wxDefaultSize, 0 ); itemFlexGridSizer74->Add(itemStaticText75, 0, wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL|wxALL, 5); wxBoxSizer* itemBoxSizer76 = new wxBoxSizer(wxHORIZONTAL); itemFlexGridSizer74->Add(itemBoxSizer76, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5); m_spacingBefore = new wxTextCtrl( itemPanel37, ID_RICHTEXTLISTSTYLEPAGE_SPACINGBEFORE, wxT(""), wxDefaultPosition, wxSize(50, -1), 0 ); m_spacingBefore->SetHelpText(_("The spacing before the paragraph.")); if (wxRichTextListStylePage::ShowToolTips()) m_spacingBefore->SetToolTip(_("The spacing before the paragraph.")); itemBoxSizer76->Add(m_spacingBefore, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5); wxStaticText* itemStaticText78 = new wxStaticText( itemPanel37, wxID_STATIC, _("After a paragraph:"), wxDefaultPosition, wxDefaultSize, 0 ); itemFlexGridSizer74->Add(itemStaticText78, 0, wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL|wxALL, 5); wxBoxSizer* itemBoxSizer79 = new wxBoxSizer(wxHORIZONTAL); itemFlexGridSizer74->Add(itemBoxSizer79, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5); m_spacingAfter = new wxTextCtrl( itemPanel37, ID_RICHTEXTLISTSTYLEPAGE_SPACINGAFTER, wxT(""), wxDefaultPosition, wxSize(50, -1), 0 ); m_spacingAfter->SetHelpText(_("The spacing after the paragraph.")); if (wxRichTextListStylePage::ShowToolTips()) m_spacingAfter->SetToolTip(_("The spacing after the paragraph.")); itemBoxSizer79->Add(m_spacingAfter, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5); wxStaticText* itemStaticText81 = new wxStaticText( itemPanel37, wxID_STATIC, _("Line spacing:"), wxDefaultPosition, wxDefaultSize, 0 ); itemFlexGridSizer74->Add(itemStaticText81, 0, wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL|wxALL, 5); wxBoxSizer* itemBoxSizer82 = new wxBoxSizer(wxHORIZONTAL); itemFlexGridSizer74->Add(itemBoxSizer82, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5); wxArrayString m_spacingLineStrings; m_spacingLineStrings.Add(_("Single")); m_spacingLineStrings.Add(_("1.5")); m_spacingLineStrings.Add(_("2")); m_spacingLine = new wxComboBox( itemPanel37, ID_RICHTEXTLISTSTYLEPAGE_LINESPACING, _("Single"), wxDefaultPosition, wxDefaultSize, m_spacingLineStrings, wxCB_READONLY ); m_spacingLine->SetStringSelection(_("Single")); m_spacingLine->SetHelpText(_("The line spacing.")); if (wxRichTextListStylePage::ShowToolTips()) m_spacingLine->SetToolTip(_("The line spacing.")); itemBoxSizer82->Add(m_spacingLine, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5); itemNotebook9->AddPage(itemPanel37, _("Spacing")); itemBoxSizer3->Add(itemNotebook9, 0, wxGROW|wxALL, 5); m_previewCtrl = new wxRichTextCtrl( itemPanel1, ID_RICHTEXTLISTSTYLEPAGE_RICHTEXTCTRL, wxEmptyString, wxDefaultPosition, wxSize(350, 180), wxSUNKEN_BORDER|wxVSCROLL|wxTE_READONLY ); m_previewCtrl->SetHelpText(_("Shows a preview of the bullet settings.")); if (wxRichTextListStylePage::ShowToolTips()) m_previewCtrl->SetToolTip(_("Shows a preview of the bullet settings.")); itemBoxSizer3->Add(m_previewCtrl, 0, wxGROW|wxALL, 5); ////@end wxRichTextListStylePage content construction m_dontUpdate = true; m_styleListBox->Append(_("(None)")); m_styleListBox->Append(_("Arabic")); m_styleListBox->Append(_("Upper case letters")); m_styleListBox->Append(_("Lower case letters")); m_styleListBox->Append(_("Upper case roman numerals")); m_styleListBox->Append(_("Lower case roman numerals")); m_styleListBox->Append(_("Numbered outline")); m_styleListBox->Append(_("Symbol")); m_styleListBox->Append(_("Bitmap")); m_styleListBox->Append(_("Standard")); m_symbolCtrl->Append(_("*")); m_symbolCtrl->Append(_("-")); m_symbolCtrl->Append(_(">")); m_symbolCtrl->Append(_("+")); m_symbolCtrl->Append(_("~")); wxArrayString standardBulletNames; if (wxRichTextBuffer::GetRenderer()) wxRichTextBuffer::GetRenderer()->EnumerateStandardBulletNames(standardBulletNames); m_bulletNameCtrl->Append(standardBulletNames); wxArrayString facenames = wxRichTextCtrl::GetAvailableFontNames(); facenames.Sort(); m_symbolFontCtrl->Append(facenames); m_levelCtrl->SetValue(m_currentLevel); m_dontUpdate = false; } /// Updates the font preview void wxRichTextListStylePage::UpdatePreview() { static const wxChar* s_para1 = wxT("Lorem ipsum dolor sit amet, consectetuer adipiscing elit. \ Nullam ante sapien, vestibulum nonummy, pulvinar sed, luctus ut, lacus.\n"); static const wxChar* s_para2 = wxT("Duis pharetra consequat dui. Nullam vitae justo id mauris lobortis interdum.\n"); static const wxChar* s_para3 = wxT("Integer convallis dolor at augue \ iaculis malesuada. Donec bibendum ipsum ut ante porta fringilla.\n"); wxRichTextListStyleDefinition* def = wxDynamicCast(wxRichTextFormattingDialog::GetDialogStyleDefinition(this), wxRichTextListStyleDefinition); wxRichTextStyleSheet* styleSheet = wxRichTextFormattingDialog::GetDialog(this)->GetStyleSheet(); wxTextAttr attr((const wxTextAttr &)(styleSheet ? def->GetStyle() : def->GetStyleMergedWithBase(styleSheet))); attr.SetFlags(attr.GetFlags() & (wxTEXT_ATTR_ALIGNMENT|wxTEXT_ATTR_LEFT_INDENT|wxTEXT_ATTR_RIGHT_INDENT|wxTEXT_ATTR_PARA_SPACING_BEFORE|wxTEXT_ATTR_PARA_SPACING_AFTER| wxTEXT_ATTR_LINE_SPACING| wxTEXT_ATTR_BULLET_STYLE|wxTEXT_ATTR_BULLET_NUMBER|wxTEXT_ATTR_BULLET_TEXT)); wxFont font(m_previewCtrl->GetFont()); font.SetPointSize(9); m_previewCtrl->SetFont(font); wxTextAttr normalParaAttr; normalParaAttr.SetFont(font); normalParaAttr.SetTextColour(wxColour(wxT("LIGHT GREY"))); m_previewCtrl->Freeze(); m_previewCtrl->Clear(); m_previewCtrl->BeginStyle(normalParaAttr); m_previewCtrl->WriteText(s_para1); m_previewCtrl->EndStyle(); m_previewCtrl->BeginStyle(attr); long listStart = m_previewCtrl->GetInsertionPoint() + 1; int i; for (i = 0; i < 10; i++) { wxTextAttr levelAttr = * def->GetLevelAttributes(i); levelAttr.SetBulletNumber(1); m_previewCtrl->BeginStyle(levelAttr); m_previewCtrl->WriteText(wxString::Format(wxT("List level %d. "), i+1) + s_para2); m_previewCtrl->EndStyle(); } m_previewCtrl->EndStyle(); long listEnd = m_previewCtrl->GetInsertionPoint(); m_previewCtrl->BeginStyle(normalParaAttr); m_previewCtrl->WriteText(s_para3); m_previewCtrl->EndStyle(); m_previewCtrl->NumberList(wxRichTextRange(listStart, listEnd), def); m_previewCtrl->Thaw(); } /// Transfer data from/to window bool wxRichTextListStylePage::TransferDataFromWindow() { wxPanel::TransferDataFromWindow(); m_currentLevel = m_levelCtrl->GetValue(); wxTextAttr* attr = GetAttributesForSelection(); if (m_alignmentLeft->GetValue()) attr->SetAlignment(wxTEXT_ALIGNMENT_LEFT); else if (m_alignmentCentred->GetValue()) attr->SetAlignment(wxTEXT_ALIGNMENT_CENTRE); else if (m_alignmentRight->GetValue()) attr->SetAlignment(wxTEXT_ALIGNMENT_RIGHT); else if (m_alignmentJustified->GetValue()) attr->SetAlignment(wxTEXT_ALIGNMENT_JUSTIFIED); else { attr->SetAlignment(wxTEXT_ALIGNMENT_DEFAULT); attr->SetFlags(attr->GetFlags() & (~wxTEXT_ATTR_ALIGNMENT)); } wxString leftIndent(m_indentLeft->GetValue()); wxString leftFirstIndent(m_indentLeftFirst->GetValue()); if (!leftIndent.empty()) { int visualLeftIndent = wxAtoi(leftIndent); int visualLeftFirstIndent = wxAtoi(leftFirstIndent); int actualLeftIndent = visualLeftFirstIndent; int actualLeftSubIndent = visualLeftIndent - visualLeftFirstIndent; attr->SetLeftIndent(actualLeftIndent, actualLeftSubIndent); } else attr->SetFlags(attr->GetFlags() & (~wxTEXT_ATTR_LEFT_INDENT)); wxString rightIndent(m_indentRight->GetValue()); if (!rightIndent.empty()) attr->SetRightIndent(wxAtoi(rightIndent)); else attr->SetFlags(attr->GetFlags() & (~wxTEXT_ATTR_RIGHT_INDENT)); wxString spacingAfter(m_spacingAfter->GetValue()); if (!spacingAfter.empty()) attr->SetParagraphSpacingAfter(wxAtoi(spacingAfter)); else attr->SetFlags(attr->GetFlags() & (~wxTEXT_ATTR_PARA_SPACING_AFTER)); wxString spacingBefore(m_spacingBefore->GetValue()); if (!spacingBefore.empty()) attr->SetParagraphSpacingBefore(wxAtoi(spacingBefore)); else attr->SetFlags(attr->GetFlags() & (~wxTEXT_ATTR_PARA_SPACING_BEFORE)); int spacingIndex = m_spacingLine->GetSelection(); int lineSpacing = 0; if (spacingIndex == 0) lineSpacing = 10; else if (spacingIndex == 1) lineSpacing = 15; else if (spacingIndex == 2) lineSpacing = 20; if (lineSpacing == 0) attr->SetFlags(attr->GetFlags() & (~wxTEXT_ATTR_LINE_SPACING)); else attr->SetLineSpacing(lineSpacing); /// BULLETS // if (m_hasBulletStyle) { long bulletStyle = 0; int index = m_styleListBox->GetSelection(); if (index == wxRICHTEXT_BULLETINDEX_ARABIC) bulletStyle |= wxTEXT_ATTR_BULLET_STYLE_ARABIC; else if (index == wxRICHTEXT_BULLETINDEX_UPPER_CASE) bulletStyle |= wxTEXT_ATTR_BULLET_STYLE_LETTERS_UPPER; else if (index == wxRICHTEXT_BULLETINDEX_LOWER_CASE) bulletStyle |= wxTEXT_ATTR_BULLET_STYLE_LETTERS_LOWER; else if (index == wxRICHTEXT_BULLETINDEX_UPPER_CASE_ROMAN) bulletStyle |= wxTEXT_ATTR_BULLET_STYLE_ROMAN_UPPER; else if (index == wxRICHTEXT_BULLETINDEX_LOWER_CASE_ROMAN) bulletStyle |= wxTEXT_ATTR_BULLET_STYLE_ROMAN_LOWER; else if (index == wxRICHTEXT_BULLETINDEX_OUTLINE) bulletStyle |= wxTEXT_ATTR_BULLET_STYLE_OUTLINE; else if (index == wxRICHTEXT_BULLETINDEX_SYMBOL) bulletStyle |= wxTEXT_ATTR_BULLET_STYLE_SYMBOL; else if (index == wxRICHTEXT_BULLETINDEX_BITMAP) bulletStyle |= wxTEXT_ATTR_BULLET_STYLE_BITMAP; else if (index == wxRICHTEXT_BULLETINDEX_STANDARD) { bulletStyle |= wxTEXT_ATTR_BULLET_STYLE_STANDARD; attr->SetBulletName(m_bulletNameCtrl->GetValue()); } if (m_parenthesesCtrl->GetValue()) bulletStyle |= wxTEXT_ATTR_BULLET_STYLE_PARENTHESES; if (m_rightParenthesisCtrl->GetValue()) bulletStyle |= wxTEXT_ATTR_BULLET_STYLE_RIGHT_PARENTHESIS; if (m_periodCtrl->GetValue()) bulletStyle |= wxTEXT_ATTR_BULLET_STYLE_PERIOD; if (m_bulletAlignmentCtrl->GetSelection() == 1) bulletStyle |= wxTEXT_ATTR_BULLET_STYLE_ALIGN_CENTRE; else if (m_bulletAlignmentCtrl->GetSelection() == 2) bulletStyle |= wxTEXT_ATTR_BULLET_STYLE_ALIGN_RIGHT; // Left is implied attr->SetBulletStyle(bulletStyle); } // if (m_hasBulletSymbol) { attr->SetBulletText(m_symbolCtrl->GetValue()); attr->SetBulletFont(m_symbolFontCtrl->GetValue()); } return true; } bool wxRichTextListStylePage::TransferDataToWindow() { DoTransferDataToWindow(); UpdatePreview(); return true; } /// Just transfer to the window void wxRichTextListStylePage::DoTransferDataToWindow() { m_dontUpdate = true; wxPanel::TransferDataToWindow(); wxTextAttr* attr = GetAttributesForSelection(); if (attr->HasAlignment()) { if (attr->GetAlignment() == wxTEXT_ALIGNMENT_LEFT) m_alignmentLeft->SetValue(true); else if (attr->GetAlignment() == wxTEXT_ALIGNMENT_RIGHT) m_alignmentRight->SetValue(true); else if (attr->GetAlignment() == wxTEXT_ALIGNMENT_CENTRE) m_alignmentCentred->SetValue(true); else if (attr->GetAlignment() == wxTEXT_ALIGNMENT_JUSTIFIED) m_alignmentJustified->SetValue(true); else m_alignmentIndeterminate->SetValue(true); } else m_alignmentIndeterminate->SetValue(true); if (attr->HasLeftIndent()) { wxString leftIndent(wxString::Format(wxT("%ld"), attr->GetLeftIndent() + attr->GetLeftSubIndent())); wxString leftFirstIndent(wxString::Format(wxT("%ld"), attr->GetLeftIndent())); m_indentLeft->SetValue(leftIndent); m_indentLeftFirst->SetValue(leftFirstIndent); } else { m_indentLeft->SetValue(wxEmptyString); m_indentLeftFirst->SetValue(wxEmptyString); } if (attr->HasRightIndent()) { wxString rightIndent(wxString::Format(wxT("%ld"), attr->GetRightIndent())); m_indentRight->SetValue(rightIndent); } else m_indentRight->SetValue(wxEmptyString); if (attr->HasParagraphSpacingAfter()) { wxString spacingAfter(wxString::Format(wxT("%d"), attr->GetParagraphSpacingAfter())); m_spacingAfter->SetValue(spacingAfter); } else m_spacingAfter->SetValue(wxEmptyString); if (attr->HasParagraphSpacingBefore()) { wxString spacingBefore(wxString::Format(wxT("%d"), attr->GetParagraphSpacingBefore())); m_spacingBefore->SetValue(spacingBefore); } else m_spacingBefore->SetValue(wxEmptyString); if (attr->HasLineSpacing()) { int index = 0; int lineSpacing = attr->GetLineSpacing(); if (lineSpacing == 10) index = 0; else if (lineSpacing == 15) index = 1; else if (lineSpacing == 20) index = 2; else index = -1; m_spacingLine->SetSelection(index); } else m_spacingLine->SetSelection(-1); /// BULLETS if (attr->HasBulletStyle()) { int index = 0; if (attr->GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_ARABIC) index = wxRICHTEXT_BULLETINDEX_ARABIC; else if (attr->GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_LETTERS_UPPER) index = wxRICHTEXT_BULLETINDEX_UPPER_CASE; else if (attr->GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_LETTERS_LOWER) index = wxRICHTEXT_BULLETINDEX_LOWER_CASE; else if (attr->GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_ROMAN_UPPER) index = wxRICHTEXT_BULLETINDEX_UPPER_CASE_ROMAN; else if (attr->GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_ROMAN_LOWER) index = wxRICHTEXT_BULLETINDEX_LOWER_CASE_ROMAN; else if (attr->GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_OUTLINE) index = wxRICHTEXT_BULLETINDEX_OUTLINE; else if (attr->GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_SYMBOL) index = wxRICHTEXT_BULLETINDEX_SYMBOL; else if (attr->GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_BITMAP) index = wxRICHTEXT_BULLETINDEX_BITMAP; else if (attr->GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_STANDARD) index = wxRICHTEXT_BULLETINDEX_STANDARD; m_styleListBox->SetSelection(index); if (attr->GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_PARENTHESES) m_parenthesesCtrl->SetValue(true); else m_parenthesesCtrl->SetValue(false); if (attr->GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_RIGHT_PARENTHESIS) m_rightParenthesisCtrl->SetValue(true); else m_rightParenthesisCtrl->SetValue(false); if (attr->GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_PERIOD) m_periodCtrl->SetValue(true); else m_periodCtrl->SetValue(false); if (attr->GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_ALIGN_CENTRE) m_bulletAlignmentCtrl->SetSelection(1); else if (attr->GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_ALIGN_RIGHT) m_bulletAlignmentCtrl->SetSelection(2); else m_bulletAlignmentCtrl->SetSelection(0); } else { m_styleListBox->SetSelection(-1); m_bulletAlignmentCtrl->SetSelection(-1); } if (attr->HasBulletText()) { m_symbolCtrl->SetValue(attr->GetBulletText()); m_symbolFontCtrl->SetValue(attr->GetBulletFont()); } else m_symbolCtrl->SetValue(wxEmptyString); if (attr->HasBulletName()) m_bulletNameCtrl->SetValue(attr->GetBulletName()); else m_bulletNameCtrl->SetValue(wxEmptyString); m_dontUpdate = false; } /// Get attributes for selected level wxTextAttr* wxRichTextListStylePage::GetAttributesForSelection() { wxRichTextListStyleDefinition* def = wxDynamicCast(wxRichTextFormattingDialog::GetDialogStyleDefinition(this), wxRichTextListStyleDefinition); int value = m_levelCtrl->GetValue(); if (def) return def->GetLevelAttributes(value-1); else return NULL; } /// Just transfer from the window and update the preview void wxRichTextListStylePage::TransferAndPreview() { if (!m_dontUpdate) { TransferDataFromWindow(); UpdatePreview(); } } /*! * wxEVT_COMMAND_SPINCTRL_UPDATED event handler for ID_RICHTEXTLISTSTYLEPAGE_LEVEL */ void wxRichTextListStylePage::OnLevelUpdated( wxSpinEvent& WXUNUSED(event) ) { if (!m_dontUpdate) { m_currentLevel = m_levelCtrl->GetValue(); TransferDataToWindow(); } } /*! * wxEVT_SCROLL_LINEUP event handler for ID_RICHTEXTLISTSTYLEPAGE_LEVEL */ void wxRichTextListStylePage::OnLevelUp( wxSpinEvent& event ) { if (!m_dontUpdate) { m_currentLevel = event.GetPosition(); TransferDataToWindow(); } } /*! * wxEVT_SCROLL_LINEDOWN event handler for ID_RICHTEXTLISTSTYLEPAGE_LEVEL */ void wxRichTextListStylePage::OnLevelDown( wxSpinEvent& event ) { if (!m_dontUpdate) { m_currentLevel = event.GetPosition(); TransferDataToWindow(); } } /*! * wxEVT_COMMAND_TEXT_UPDATED event handler for ID_RICHTEXTLISTSTYLEPAGE_LEVEL */ void wxRichTextListStylePage::OnLevelTextUpdated( wxCommandEvent& WXUNUSED(event) ) { // Can cause problems #if 0 if (!m_dontUpdate) { m_currentLevel = event.GetInt(); TransferDataToWindow(); } #endif } /*! * wxEVT_UPDATE_UI event handler for ID_RICHTEXTLISTSTYLEPAGE_LEVEL */ void wxRichTextListStylePage::OnLevelUIUpdate( wxUpdateUIEvent& event ) { ////@begin wxEVT_UPDATE_UI event handler for ID_RICHTEXTLISTSTYLEPAGE_LEVEL in wxRichTextListStylePage. // Before editing this code, remove the block markers. event.Skip(); ////@end wxEVT_UPDATE_UI event handler for ID_RICHTEXTLISTSTYLEPAGE_LEVEL in wxRichTextListStylePage. } /*! * wxEVT_COMMAND_LISTBOX_SELECTED event handler for ID_RICHTEXTLISTSTYLEPAGE_STYLELISTBOX */ void wxRichTextListStylePage::OnStylelistboxSelected( wxCommandEvent& WXUNUSED(event) ) { TransferAndPreview(); } /*! * wxEVT_UPDATE_UI event handler for ID_RICHTEXTLISTSTYLEPAGE_SYMBOLSTATIC */ void wxRichTextListStylePage::OnSymbolstaticUpdate( wxUpdateUIEvent& event ) { OnSymbolUpdate(event); } /*! * wxEVT_COMMAND_COMBOBOX_SELECTED event handler for ID_RICHTEXTBULLETSPAGE_SYMBOLCTRL */ void wxRichTextListStylePage::OnSymbolctrlSelected( wxCommandEvent& WXUNUSED(event) ) { TransferAndPreview(); } /*! * wxEVT_COMMAND_TEXT_UPDATED event handler for ID_RICHTEXTBULLETSPAGE_SYMBOLCTRL */ void wxRichTextListStylePage::OnSymbolctrlUpdated( wxCommandEvent& WXUNUSED(event) ) { TransferAndPreview(); } /*! * wxEVT_UPDATE_UI event handler for ID_RICHTEXTBULLETSPAGE_SYMBOLCTRL */ void wxRichTextListStylePage::OnSymbolctrlUIUpdate( wxUpdateUIEvent& event ) { OnSymbolUpdate(event); } /*! * wxEVT_COMMAND_BUTTON_CLICKED event handler for ID_RICHTEXTBULLETSPAGE_CHOOSE_SYMBOL */ void wxRichTextListStylePage::OnChooseSymbolClick( wxCommandEvent& WXUNUSED(event) ) { int sel = m_styleListBox->GetSelection(); if (sel == wxRICHTEXT_BULLETINDEX_SYMBOL) { wxString symbol = m_symbolCtrl->GetValue(); wxString fontName = m_symbolFontCtrl->GetValue(); wxSymbolPickerDialog dlg(symbol, fontName, fontName, this); if (dlg.ShowModal() == wxID_OK) { m_dontUpdate = true; m_symbolCtrl->SetValue(dlg.GetSymbol()); m_symbolFontCtrl->SetValue(dlg.GetFontName()); TransferAndPreview(); m_dontUpdate = false; } } } /*! * wxEVT_UPDATE_UI event handler for ID_RICHTEXTBULLETSPAGE_CHOOSE_SYMBOL */ void wxRichTextListStylePage::OnChooseSymbolUpdate( wxUpdateUIEvent& event ) { OnSymbolUpdate(event); } /*! * wxEVT_COMMAND_COMBOBOX_SELECTED event handler for ID_RICHTEXTLISTSTYLEPAGE_SYMBOLFONTCTRL */ void wxRichTextListStylePage::OnSymbolfontctrlSelected( wxCommandEvent& WXUNUSED(event) ) { TransferAndPreview(); } /*! * wxEVT_COMMAND_TEXT_UPDATED event handler for ID_RICHTEXTLISTSTYLEPAGE_SYMBOLFONTCTRL */ void wxRichTextListStylePage::OnSymbolfontctrlUpdated( wxCommandEvent& WXUNUSED(event) ) { TransferAndPreview(); } /*! * wxEVT_UPDATE_UI event handler for ID_RICHTEXTLISTSTYLEPAGE_SYMBOLFONTCTRL */ void wxRichTextListStylePage::OnSymbolfontctrlUIUpdate( wxUpdateUIEvent& event ) { OnSymbolUpdate(event); } /*! * wxEVT_COMMAND_CHECKBOX_CLICKED event handler for ID_RICHTEXTLISTSTYLEPAGE__PARENTHESESCTRL */ void wxRichTextListStylePage::OnParenthesesctrlClick( wxCommandEvent& WXUNUSED(event) ) { TransferAndPreview(); } /*! * wxEVT_UPDATE_UI event handler for ID_RICHTEXTLISTSTYLEPAGE__PARENTHESESCTRL */ void wxRichTextListStylePage::OnParenthesesctrlUpdate( wxUpdateUIEvent& event ) { int sel = m_styleListBox->GetSelection(); event.Enable((sel != wxRICHTEXT_BULLETINDEX_SYMBOL && sel != wxRICHTEXT_BULLETINDEX_BITMAP && sel != wxRICHTEXT_BULLETINDEX_NONE)); } /*! * wxEVT_COMMAND_CHECKBOX_CLICKED event handler for ID_RICHTEXTLISTSTYLEPAGE_PERIODCTRL */ void wxRichTextListStylePage::OnPeriodctrlClick( wxCommandEvent& WXUNUSED(event) ) { TransferAndPreview(); } /*! * wxEVT_UPDATE_UI event handler for ID_RICHTEXTLISTSTYLEPAGE_PERIODCTRL */ void wxRichTextListStylePage::OnPeriodctrlUpdate( wxUpdateUIEvent& event ) { int sel = m_styleListBox->GetSelection(); event.Enable((sel != wxRICHTEXT_BULLETINDEX_SYMBOL && sel != wxRICHTEXT_BULLETINDEX_BITMAP && sel != wxRICHTEXT_BULLETINDEX_NONE)); } /*! * wxEVT_COMMAND_RADIOBUTTON_SELECTED event handler for ID_RICHTEXTLISTSTYLEPAGE_ALIGNLEFT */ void wxRichTextListStylePage::OnRichtextliststylepageAlignleftSelected( wxCommandEvent& WXUNUSED(event) ) { TransferAndPreview(); } /*! * wxEVT_COMMAND_RADIOBUTTON_SELECTED event handler for ID_RICHTEXTLISTSTYLEPAGE_ALIGNRIGHT */ void wxRichTextListStylePage::OnRichtextliststylepageAlignrightSelected( wxCommandEvent& WXUNUSED(event) ) { TransferAndPreview(); } /*! * wxEVT_COMMAND_RADIOBUTTON_SELECTED event handler for ID_RICHTEXTLISTSTYLEPAGE_JUSTIFIED */ void wxRichTextListStylePage::OnRichtextliststylepageJustifiedSelected( wxCommandEvent& WXUNUSED(event) ) { TransferAndPreview(); } /*! * wxEVT_COMMAND_RADIOBUTTON_SELECTED event handler for ID_RICHTEXTLISTSTYLEPAGE_CENTERED */ void wxRichTextListStylePage::OnRichtextliststylepageCenteredSelected( wxCommandEvent& WXUNUSED(event) ) { TransferAndPreview(); } /*! * wxEVT_COMMAND_RADIOBUTTON_SELECTED event handler for ID_RICHTEXTLISTSTYLEPAGE_ALIGNINDETERMINATE */ void wxRichTextListStylePage::OnRichtextliststylepageAlignindeterminateSelected( wxCommandEvent& WXUNUSED(event) ) { TransferAndPreview(); } /*! * wxEVT_COMMAND_TEXT_UPDATED event handler for ID_RICHTEXTLISTSTYLEPAGE_INDENTLEFT */ void wxRichTextListStylePage::OnIndentLeftUpdated( wxCommandEvent& WXUNUSED(event) ) { TransferAndPreview(); } /*! * wxEVT_COMMAND_TEXT_UPDATED event handler for ID_RICHTEXTLISTSTYLEPAGE_INDENTFIRSTLINE */ void wxRichTextListStylePage::OnIndentFirstLineUpdated( wxCommandEvent& WXUNUSED(event) ) { TransferAndPreview(); } /*! * wxEVT_COMMAND_TEXT_UPDATED event handler for ID_RICHTEXTLISTSTYLEPAGE_INDENTRIGHT */ void wxRichTextListStylePage::OnIndentRightUpdated( wxCommandEvent& WXUNUSED(event) ) { TransferAndPreview(); } /*! * wxEVT_COMMAND_TEXT_UPDATED event handler for ID_RICHTEXTLISTSTYLEPAGE_SPACINGBEFORE */ void wxRichTextListStylePage::OnSpacingBeforeUpdated( wxCommandEvent& WXUNUSED(event) ) { TransferAndPreview(); } /*! * wxEVT_COMMAND_TEXT_UPDATED event handler for ID_RICHTEXTLISTSTYLEPAGE_SPACINGAFTER */ void wxRichTextListStylePage::OnSpacingAfterUpdated( wxCommandEvent& WXUNUSED(event) ) { TransferAndPreview(); } /*! * wxEVT_COMMAND_COMBOBOX_SELECTED event handler for ID_RICHTEXTLISTSTYLEPAGE_LINESPACING */ void wxRichTextListStylePage::OnLineSpacingSelected( wxCommandEvent& WXUNUSED(event) ) { TransferAndPreview(); } /*! * Should we show tooltips? */ bool wxRichTextListStylePage::ShowToolTips() { return wxRichTextFormattingDialog::ShowToolTips(); } /*! * Get bitmap resources */ wxBitmap wxRichTextListStylePage::GetBitmapResource( const wxString& name ) { // Bitmap retrieval ////@begin wxRichTextListStylePage bitmap retrieval wxUnusedVar(name); return wxNullBitmap; ////@end wxRichTextListStylePage bitmap retrieval } /*! * Get icon resources */ wxIcon wxRichTextListStylePage::GetIconResource( const wxString& name ) { // Icon retrieval ////@begin wxRichTextListStylePage icon retrieval wxUnusedVar(name); return wxNullIcon; ////@end wxRichTextListStylePage icon retrieval } /// Update for symbol-related controls void wxRichTextListStylePage::OnSymbolUpdate( wxUpdateUIEvent& event ) { int sel = m_styleListBox->GetSelection(); event.Enable(sel == wxRICHTEXT_BULLETINDEX_SYMBOL); } /// Update for number-related controls void wxRichTextListStylePage::OnNumberUpdate( wxUpdateUIEvent& event ) { int sel = m_styleListBox->GetSelection(); event.Enable((sel != wxRICHTEXT_BULLETINDEX_SYMBOL && sel != wxRICHTEXT_BULLETINDEX_BITMAP && sel != wxRICHTEXT_BULLETINDEX_STANDARD && sel != wxRICHTEXT_BULLETINDEX_NONE)); } /// Update for standard bullet-related controls void wxRichTextListStylePage::OnStandardBulletUpdate( wxUpdateUIEvent& event ) { int sel = m_styleListBox->GetSelection(); event.Enable( sel == wxRICHTEXT_BULLETINDEX_STANDARD ); } /*! * wxEVT_COMMAND_BUTTON_CLICKED event handler for ID_RICHTEXTLISTSTYLEPAGE_CHOOSE_FONT */ void wxRichTextListStylePage::OnChooseFontClick( wxCommandEvent& WXUNUSED(event) ) { wxTextAttr* attr = GetAttributesForSelection(); int pages = wxRICHTEXT_FORMAT_FONT; wxRichTextFormattingDialog formatDlg; formatDlg.SetStyle(*attr, false); formatDlg.Create(pages, this); if (formatDlg.ShowModal() == wxID_OK) { (*attr) = formatDlg.GetAttributes(); TransferAndPreview(); } } /*! * wxEVT_UPDATE_UI event handler for ID_RICHTEXTLISTSTYLEPAGE_NAMESTATIC */ void wxRichTextListStylePage::OnNamestaticUpdate( wxUpdateUIEvent& event ) { OnStandardBulletUpdate(event); } /*! * wxEVT_COMMAND_COMBOBOX_SELECTED event handler for ID_RICHTEXTLISTSTYLEPAGE_NAMECTRL */ void wxRichTextListStylePage::OnNamectrlSelected( wxCommandEvent& WXUNUSED(event) ) { TransferAndPreview(); } /*! * wxEVT_COMMAND_TEXT_UPDATED event handler for ID_RICHTEXTLISTSTYLEPAGE_NAMECTRL */ void wxRichTextListStylePage::OnNamectrlUpdated( wxCommandEvent& WXUNUSED(event) ) { TransferAndPreview(); } /*! * wxEVT_UPDATE_UI event handler for ID_RICHTEXTLISTSTYLEPAGE_NAMECTRL */ void wxRichTextListStylePage::OnNamectrlUIUpdate( wxUpdateUIEvent& event ) { OnStandardBulletUpdate(event); } /*! * wxEVT_COMMAND_CHECKBOX_CLICKED event handler for ID_RICHTEXTLISTSTYLEPAGE_RIGHTPARENTHESISCTRL */ void wxRichTextListStylePage::OnRightParenthesisCtrlClick( wxCommandEvent& WXUNUSED(event) ) { TransferAndPreview(); } /*! * wxEVT_UPDATE_UI event handler for ID_RICHTEXTLISTSTYLEPAGE_RIGHTPARENTHESISCTRL */ void wxRichTextListStylePage::OnRightParenthesisCtrlUpdate( wxUpdateUIEvent& event ) { int sel = m_styleListBox->GetSelection(); event.Enable((sel != wxRICHTEXT_BULLETINDEX_SYMBOL && sel != wxRICHTEXT_BULLETINDEX_BITMAP && sel != wxRICHTEXT_BULLETINDEX_NONE)); } /*! * wxEVT_COMMAND_COMBOBOX_SELECTED event handler for ID_RICHTEXTLISTSTYLEPAGE_BULLETALIGNMENTCTRL */ void wxRichTextListStylePage::OnBulletAlignmentCtrlSelected( wxCommandEvent& WXUNUSED(event) ) { TransferAndPreview(); }
53,394
20,251
/** * Copyright 2019-2020 Huawei Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "graph/passes/replace_transshape_pass.h" #include <string> #include "common/ge/ge_util.h" #include "common/ge_inner_error_codes.h" #include "framework/common/debug/ge_log.h" #include "graph/common/omg_util.h" #include "graph/utils/graph_utils.h" namespace ge { Status ReplaceTransShapePass::Run(ge::ComputeGraphPtr graph) { GE_CHECK_NOTNULL(graph); for (auto &node : graph->GetDirectNode()) { if (node->GetType() == TRANSSHAPE) { auto ret = ReplaceTransShapeNode(graph, node); if (ret != SUCCESS) { GELOGE(FAILED, "Trans shape node %s failed", node->GetName().c_str()); return FAILED; } } } return SUCCESS; } Status ReplaceTransShapePass::ReplaceTransShapeNode(ComputeGraphPtr &graph, NodePtr &trans_shape_node) { std::string op_type; auto ret = GetOriginalType(trans_shape_node, op_type); if (ret != SUCCESS) { GELOGE(FAILED, "Get node %s original type failede", trans_shape_node->GetName().c_str()); return FAILED; } auto src_op_desc = trans_shape_node->GetOpDesc(); GE_CHECK_NOTNULL(src_op_desc); std::string node_name = trans_shape_node->GetName() + "ToMemcpy"; auto dst_op_desc = MakeShared<OpDesc>(node_name, MEMCPYASYNC); if (dst_op_desc == nullptr) { GELOGE(FAILED, "Make node %s opdesc failed", node_name.c_str()); return FAILED; } GELOGI("Create memcpy Op, name=%s.", node_name.c_str()); for (InDataAnchorPtr &in_anchor : trans_shape_node->GetAllInDataAnchors()) { auto ret = dst_op_desc->AddInputDesc(src_op_desc->GetInputDesc(in_anchor->GetIdx())); if (ret != GRAPH_SUCCESS) { GELOGE(FAILED, "Add input desc failed"); return FAILED; } } for (OutDataAnchorPtr &out_anchor : trans_shape_node->GetAllOutDataAnchors()) { auto ret = dst_op_desc->AddOutputDesc(src_op_desc->GetOutputDesc(out_anchor->GetIdx())); if (ret != GRAPH_SUCCESS) { GELOGE(FAILED, "Add output desc failed"); return FAILED; } } NodePtr memcpy_node = graph->AddNode(dst_op_desc); GE_CHECK_NOTNULL(memcpy_node); for (InDataAnchorPtr &in_data_anchor : trans_shape_node->GetAllInDataAnchors()) { OutDataAnchorPtr peer_out_anchor = in_data_anchor->GetPeerOutAnchor(); GE_IF_BOOL_EXEC(peer_out_anchor == nullptr, continue); GE_CHK_STATUS(GraphUtils::RemoveEdge(peer_out_anchor, in_data_anchor), "Remove Memcpy data input fail."); GE_CHK_STATUS(GraphUtils::AddEdge(peer_out_anchor, memcpy_node->GetInDataAnchor(in_data_anchor->GetIdx())), "Memcpy node add edge fail."); } for (OutDataAnchorPtr &out_data_anchor : trans_shape_node->GetAllOutDataAnchors()) { for (InDataAnchorPtr &peer_in_anchor : out_data_anchor->GetPeerInDataAnchors()) { GE_CHK_STATUS(GraphUtils::RemoveEdge(out_data_anchor, peer_in_anchor), "Remove Memcpy data output fail."); GE_CHK_STATUS(GraphUtils::AddEdge(memcpy_node->GetOutDataAnchor(out_data_anchor->GetIdx()), peer_in_anchor), "Memcpy node add edge fail."); } } ReplaceControlEdges(trans_shape_node, memcpy_node); return SUCCESS; } void ReplaceTransShapePass::CopyControlEdges(NodePtr &old_node, NodePtr &new_node, bool input_check_flag) { GE_CHECK_NOTNULL_JUST_RETURN(old_node); GE_CHECK_NOTNULL_JUST_RETURN(new_node); GE_IF_BOOL_EXEC(old_node == new_node, return ); for (NodePtr &node : old_node->GetInControlNodes()) { auto out_control_anchor = node->GetOutControlAnchor(); GE_IF_BOOL_EXEC(!out_control_anchor->IsLinkedWith(new_node->GetInControlAnchor()), { GE_CHK_STATUS(GraphUtils::AddEdge(out_control_anchor, new_node->GetInControlAnchor()), "Add in ctl edge fail."); }); } for (NodePtr &node : old_node->GetOutControlNodes()) { GE_IF_BOOL_EXEC(!new_node->GetOutControlAnchor()->IsLinkedWith(node->GetInControlAnchor()), { GE_CHK_STATUS(GraphUtils::AddEdge(new_node->GetOutControlAnchor(), node->GetInControlAnchor()), "Add out ctl edge fail."); }); } } void ReplaceTransShapePass::RemoveControlEdges(NodePtr &node) { GE_CHECK_NOTNULL_JUST_RETURN(node); for (NodePtr &in_node : node->GetInControlNodes()) { GE_CHK_STATUS(GraphUtils::RemoveEdge(in_node->GetOutControlAnchor(), node->GetInControlAnchor()), "Remove in ctl edge fail."); } for (auto &out_data_anchor : node->GetAllOutDataAnchors()) { for (auto &in_ctrl_anchor : out_data_anchor->GetPeerInControlAnchors()) { GE_CHK_STATUS(GraphUtils::RemoveEdge(out_data_anchor, in_ctrl_anchor), "Remove in ctl edge fail."); } } auto out_control_anchor = node->GetOutControlAnchor(); GE_CHECK_NOTNULL_JUST_RETURN(out_control_anchor); for (auto &peer_anchor : out_control_anchor->GetPeerAnchors()) { GE_CHK_STATUS(GraphUtils::RemoveEdge(out_control_anchor, peer_anchor), "Remove out ctl edge fail."); } } void ReplaceTransShapePass::ReplaceControlEdges(NodePtr &old_node, NodePtr &new_node) { GE_IF_BOOL_EXEC(old_node == new_node, return ); CopyControlEdges(old_node, new_node); RemoveControlEdges(old_node); } } // namespace ge
5,684
2,016
// Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License #ifndef __PROCESS_GRPC_HPP__ #define __PROCESS_GRPC_HPP__ #include <chrono> #include <memory> #include <string> #include <thread> #include <type_traits> #include <utility> #include <google/protobuf/message.h> #include <grpcpp/grpcpp.h> #include <process/check.hpp> #include <process/dispatch.hpp> #include <process/future.hpp> #include <process/pid.hpp> #include <process/process.hpp> #include <stout/duration.hpp> #include <stout/error.hpp> #include <stout/lambda.hpp> #include <stout/nothing.hpp> #include <stout/try.hpp> // This file provides libprocess "support" for using gRPC. In particular, it // defines two wrapper classes: `client::Connection` which represents a // connection to a gRPC server, and `client::Runtime` which integrates an event // loop waiting for gRPC responses and provides the `call` interface to create // an asynchronous gRPC call and return a `Future`. #define GRPC_CLIENT_METHOD(service, rpc) \ (&service::Stub::PrepareAsync##rpc) namespace process { namespace grpc { /** * Represents errors caused by non-OK gRPC statuses. See: * https://grpc.io/grpc/cpp/classgrpc_1_1_status.html */ class StatusError : public Error { public: StatusError(::grpc::Status _status) : Error(_status.error_message()), status(std::move(_status)) { CHECK(!status.ok()); } const ::grpc::Status status; }; namespace client { // Internal helper utilities. namespace internal { template <typename T> struct MethodTraits; // Undefined. template <typename Stub, typename Request, typename Response> struct MethodTraits< std::unique_ptr<::grpc::ClientAsyncResponseReader<Response>>(Stub::*)( ::grpc::ClientContext*, const Request&, ::grpc::CompletionQueue*)> { typedef Stub stub_type; typedef Request request_type; typedef Response response_type; }; } // namespace internal { /** * A copyable interface to manage a connection to a gRPC server. All * `Connection` copies share the same gRPC channel which is thread safe. Note * that the actual connection is established lazily by the gRPC library at the * time an RPC is made to the channel. */ class Connection { public: Connection( const std::string& uri, const std::shared_ptr<::grpc::ChannelCredentials>& credentials = ::grpc::InsecureChannelCredentials()) : channel(::grpc::CreateChannel(uri, credentials)) {} explicit Connection(std::shared_ptr<::grpc::Channel> _channel) : channel(std::move(_channel)) {} const std::shared_ptr<::grpc::Channel> channel; }; /** * Defines the gRPC options for each call. */ struct CallOptions { // Enable the gRPC wait-for-ready semantics by default so the call will be // retried if the connection is not ready. See: // https://github.com/grpc/grpc/blob/master/doc/wait-for-ready.md bool wait_for_ready = true; // The timeout of the call. A `DEADLINE_EXCEEDED` status will be returned if // there is no response in the specified amount of time. This is required to // avoid the call from being pending forever. Duration timeout = Seconds(60); }; /** * A copyable interface to manage an internal runtime process for asynchronous * gRPC calls. A runtime process keeps a gRPC `CompletionQueue` to manage * outstanding requests, a looper thread to wait for any incoming responses from * the `CompletionQueue`, and handles the requests and responses. All `Runtime` * copies share the same runtime process. Usually we only need a single runtime * process to handle all gRPC calls, but multiple runtime processes can be * instantiated for better parallelism and isolation. * * NOTE: The caller must call `terminate` to drain the `CompletionQueue` before * finalizing libprocess to gracefully terminate the gRPC runtime. */ class Runtime { public: Runtime() : data(new Data()) {} /** * Sends an asynchronous gRPC call. * * This function returns a `Future` of a `Try` such that the response protobuf * is returned only if the gRPC call returns an OK status to ensure type * safety (see https://github.com/grpc/grpc/issues/12824). Note that the * future never fails; it will return a `StatusError` if a non-OK status is * returned for the call, so the caller can handle the error programmatically. * * @param connection A connection to a gRPC server. * @param method The asynchronous gRPC call to make. This should be obtained * by the `GRPC_CLIENT_METHOD(service, rpc)` macro. * @param request The request protobuf for the gRPC call. * @param options The gRPC options for the call. * @return a `Future` of `Try` waiting for a response protobuf or an error. */ template < typename Method, typename Request = typename internal::MethodTraits<Method>::request_type, typename Response = typename internal::MethodTraits<Method>::response_type, typename std::enable_if< std::is_convertible< typename std::decay<Request>::type*, google::protobuf::Message*>::value, int>::type = 0> Future<Try<Response, StatusError>> call( const Connection& connection, Method&& method, Request&& request, const CallOptions& options) { // Create a `Promise` that will be set upon receiving a response. // TODO(chhsiao): The `Promise` in the `shared_ptr` is not shared, but only // to be captured by the lambda below. Use a `unique_ptr` once we get C++14. std::shared_ptr<Promise<Try<Response, StatusError>>> promise( new Promise<Try<Response, StatusError>>); Future<Try<Response, StatusError>> future = promise->future(); // Send the request in the internal runtime process. // TODO(chhsiao): We use `std::bind` here to forward `request` to avoid an // extra copy. We should capture it by forwarding once we get C++14. dispatch(data->pid, &RuntimeProcess::send, std::bind( [connection, method, options, promise]( const Request& request, bool terminating, ::grpc::CompletionQueue* queue) { if (terminating) { promise->fail("Runtime has been terminated"); return; } // TODO(chhsiao): The `shared_ptr`s here aren't shared, but only to be // captured by the lambda below. Use `unique_ptr`s once we get C++14. std::shared_ptr<::grpc::ClientContext> context( new ::grpc::ClientContext()); context->set_wait_for_ready(options.wait_for_ready); context->set_deadline( std::chrono::system_clock::now() + std::chrono::nanoseconds(options.timeout.ns())); promise->future().onDiscard([=] { context->TryCancel(); }); std::shared_ptr<Response> response(new Response()); std::shared_ptr<::grpc::Status> status(new ::grpc::Status()); std::shared_ptr<::grpc::ClientAsyncResponseReader<Response>> reader = (typename internal::MethodTraits<Method>::stub_type( connection.channel).*method)(context.get(), request, queue); reader->StartCall(); // Create a `ReceiveCallback` as a tag in the `CompletionQueue` for // the current asynchronous gRPC call. The callback will set up the // above `Promise` upon receiving a response. // NOTE: `context` and `reader` need to be held on in order to get // updates for the ongoing RPC, and thus are captured here. The // callback itself will later be retrieved and managed in the // looper thread. void* tag = new ReceiveCallback( [context, reader, response, status, promise]() { CHECK_PENDING(promise->future()); if (promise->future().hasDiscard()) { promise->discard(); } else { promise->set(status->ok() ? std::move(*response) : Try<Response, StatusError>::error(std::move(*status))); } }); reader->Finish(response.get(), status.get(), tag); }, std::forward<Request>(request), lambda::_1, lambda::_2)); return future; } /** * Asks the internal runtime process to shut down the `CompletionQueue`, which * would asynchronously drain and fail all pending gRPC calls in the * `CompletionQueue`, then join the looper thread. */ void terminate(); /** * @return A `Future` waiting for all pending gRPC calls in the * `CompletionQueue` of the internal runtime process to be drained and the * looper thread to be joined. */ Future<Nothing> wait(); private: // Type of the callback functions that can get invoked when sending a request // or receiving a response. typedef lambda::CallableOnce< void(bool, ::grpc::CompletionQueue*)> SendCallback; typedef lambda::CallableOnce<void()> ReceiveCallback; class RuntimeProcess : public Process<RuntimeProcess> { public: RuntimeProcess(); ~RuntimeProcess() override; void send(SendCallback callback); void receive(ReceiveCallback callback); void terminate(); Future<Nothing> wait(); private: void initialize() override; void finalize() override; void loop(); ::grpc::CompletionQueue queue; std::unique_ptr<std::thread> looper; bool terminating; Promise<Nothing> terminated; }; struct Data { Data(); ~Data(); PID<RuntimeProcess> pid; Future<Nothing> terminated; }; std::shared_ptr<Data> data; }; } // namespace client { } // namespace grpc { } // namespace process { #endif // __PROCESS_GRPC_HPP__
10,251
2,932
//===----------------------------------------------------------------------===// // DuckDB // // duckdb/main/query_result.hpp // // //===----------------------------------------------------------------------===// #pragma once #include "duckdb/common/enums/statement_type.hpp" #include "duckdb/common/types/data_chunk.hpp" #include "duckdb/common/winapi.hpp" struct ArrowSchema; namespace duckdb { enum class QueryResultType : uint8_t { MATERIALIZED_RESULT, STREAM_RESULT, PENDING_RESULT }; class BaseQueryResult { public: //! Creates a successful empty query result DUCKDB_API BaseQueryResult(QueryResultType type, StatementType statement_type); //! Creates a successful query result with the specified names and types DUCKDB_API BaseQueryResult(QueryResultType type, StatementType statement_type, vector<LogicalType> types, vector<string> names); //! Creates an unsuccessful query result with error condition DUCKDB_API BaseQueryResult(QueryResultType type, string error); DUCKDB_API virtual ~BaseQueryResult(); //! The type of the result (MATERIALIZED or STREAMING) QueryResultType type; //! The type of the statement that created this result StatementType statement_type; //! The SQL types of the result vector<LogicalType> types; //! The names of the result vector<string> names; //! Whether or not execution was successful bool success; //! The error string (in case execution was not successful) string error; public: DUCKDB_API bool HasError(); DUCKDB_API const string &GetError(); DUCKDB_API idx_t ColumnCount(); }; //! The QueryResult object holds the result of a query. It can either be a MaterializedQueryResult, in which case the //! result contains the entire result set, or a StreamQueryResult in which case the Fetch method can be called to //! incrementally fetch data from the database. class QueryResult : public BaseQueryResult { public: //! Creates a successful empty query result DUCKDB_API QueryResult(QueryResultType type, StatementType statement_type); //! Creates a successful query result with the specified names and types DUCKDB_API QueryResult(QueryResultType type, StatementType statement_type, vector<LogicalType> types, vector<string> names); //! Creates an unsuccessful query result with error condition DUCKDB_API QueryResult(QueryResultType type, string error); DUCKDB_API virtual ~QueryResult() override; //! The next result (if any) unique_ptr<QueryResult> next; public: //! Fetches a DataChunk of normalized (flat) vectors from the query result. //! Returns nullptr if there are no more results to fetch. DUCKDB_API virtual unique_ptr<DataChunk> Fetch(); //! Fetches a DataChunk from the query result. The vectors are not normalized and hence any vector types can be //! returned. DUCKDB_API virtual unique_ptr<DataChunk> FetchRaw() = 0; //! Converts the QueryResult to a string DUCKDB_API virtual string ToString() = 0; //! Prints the QueryResult to the console DUCKDB_API void Print(); //! Returns true if the two results are identical; false otherwise. Note that this method is destructive; it calls //! Fetch() until both results are exhausted. The data in the results will be lost. DUCKDB_API bool Equals(QueryResult &other); DUCKDB_API bool TryFetch(unique_ptr<DataChunk> &result, string &error) { try { result = Fetch(); return success; } catch (std::exception &ex) { error = ex.what(); return false; } catch (...) { error = "Unknown error in Fetch"; return false; } } DUCKDB_API void ToArrowSchema(ArrowSchema *out_array); private: //! The current chunk used by the iterator unique_ptr<DataChunk> iterator_chunk; private: class QueryResultIterator; class QueryResultRow { public: explicit QueryResultRow(QueryResultIterator &iterator) : iterator(iterator), row(0) { } QueryResultIterator &iterator; idx_t row; template <class T> T GetValue(idx_t col_idx) const { return iterator.result->iterator_chunk->GetValue(col_idx, iterator.row_idx).GetValue<T>(); } }; //! The row-based query result iterator. Invoking the class QueryResultIterator { public: explicit QueryResultIterator(QueryResult *result) : current_row(*this), result(result), row_idx(0) { if (result) { result->iterator_chunk = result->Fetch(); } } QueryResultRow current_row; QueryResult *result; idx_t row_idx; public: void Next() { if (!result->iterator_chunk) { return; } current_row.row++; row_idx++; if (row_idx >= result->iterator_chunk->size()) { result->iterator_chunk = result->Fetch(); row_idx = 0; } } QueryResultIterator &operator++() { Next(); return *this; } bool operator!=(const QueryResultIterator &other) const { return result->iterator_chunk && result->iterator_chunk->ColumnCount() > 0; } const QueryResultRow &operator*() const { return current_row; } }; public: DUCKDB_API QueryResultIterator begin() { return QueryResultIterator(this); } DUCKDB_API QueryResultIterator end() { return QueryResultIterator(nullptr); } protected: DUCKDB_API string HeaderToString(); private: QueryResult(const QueryResult &) = delete; }; } // namespace duckdb
5,259
1,673
/* Copyright 2021 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License");; you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ // Defines the pywrap_libexport module. In order to have only one dynamically- // linked shared object, all SavedModel C++ APIs must be added here. #include "pybind11/pybind11.h" #include "tensorflow/cc/experimental/libexport/constants.h" #include "tensorflow/cc/experimental/libexport/save.h" #include "tensorflow/python/lib/core/pybind11_status.h" #include "tensorflow/python/saved_model/experimental/pywrap_libexport_metrics.h" namespace py = pybind11; PYBIND11_MODULE(pywrap_libexport, m) { m.doc() = "TensorFlow exporter Python bindings"; m.attr("ASSETS_DIRECTORY") = py::str(tensorflow::libexport::kAssetsDirectory); m.attr("EXTRA_ASSETS_DIRECTORY") = py::str(tensorflow::libexport::kExtraAssetsDirectory); m.attr("ASSETS_KEY") = py::str(tensorflow::libexport::kAssetsKey); m.attr("DEBUG_DIRECTORY") = py::str(tensorflow::libexport::kDebugDirectory); m.attr("DEBUG_INFO_FILENAME_PB") = py::str(tensorflow::libexport::kDebugInfoFilenamePb); m.attr("INIT_OP_SIGNATURE_KEY") = py::str(tensorflow::libexport::kInitOpSignatureKey); m.attr("LEGACY_INIT_OP_KEY") = py::str(tensorflow::libexport::kLegacyInitOpKey); m.attr("MAIN_OP_KEY") = py::str(tensorflow::libexport::kMainOpKey); m.attr("TRAIN_OP_KEY") = py::str(tensorflow::libexport::kTrainOpKey); m.attr("TRAIN_OP_SIGNATURE_KEY") = py::str(tensorflow::libexport::kTrainOpSignatureKey); m.attr("SAVED_MODEL_FILENAME_PB") = py::str(tensorflow::libexport::kSavedModelFilenamePb); m.attr("SAVED_MODEL_FILENAME_PBTXT") = py::str(tensorflow::libexport::kSavedModelFilenamePbtxt); m.attr("SAVED_MODEL_SCHEMA_VERSION") = tensorflow::libexport::kSavedModelSchemaVersion; m.attr("VARIABLES_DIRECTORY") = py::str(tensorflow::libexport::kVariablesDirectory); m.attr("VARIABLES_FILENAME") = py::str(tensorflow::libexport::kVariablesFilename); m.def("Save", [](const char* export_dir) { tensorflow::MaybeRaiseFromStatus(tensorflow::libexport::Save(export_dir)); }); tensorflow::DefineMetricsModule(m); }
2,738
944
// Copyright (c) 2014 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "atom/browser/ui/views/submenu_button.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "ui/gfx/canvas.h" #include "ui/gfx/color_utils.h" #include "ui/gfx/text_utils.h" #include "ui/views/animation/flood_fill_ink_drop_ripple.h" #include "ui/views/animation/ink_drop_host_view.h" #include "ui/views/animation/ink_drop_impl.h" #include "ui/views/controls/button/label_button_border.h" namespace atom { SubmenuButton::SubmenuButton(const base::string16& title, views::MenuButtonListener* menu_button_listener, const SkColor& background_color) : views::MenuButton(gfx::RemoveAcceleratorChar(title, '&', NULL, NULL), menu_button_listener, false), accelerator_(0), show_underline_(false), underline_start_(0), underline_end_(0), text_width_(0), text_height_(0), underline_color_(SK_ColorBLACK), background_color_(background_color) { #if defined(OS_LINUX) // Dont' use native style border. SetBorder(CreateDefaultBorder()); #endif if (GetUnderlinePosition(title, &accelerator_, &underline_start_, &underline_end_)) gfx::Canvas::SizeStringInt(GetText(), gfx::FontList(), &text_width_, &text_height_, 0, 0); SetInkDropMode(InkDropMode::ON); set_ink_drop_base_color( color_utils::BlendTowardOppositeLuma(background_color_, 0x61)); } SubmenuButton::~SubmenuButton() {} std::unique_ptr<views::InkDropRipple> SubmenuButton::CreateInkDropRipple() const { std::unique_ptr<views::InkDropRipple> ripple( new views::FloodFillInkDropRipple( size(), GetInkDropCenterBasedOnLastEvent(), GetInkDropBaseColor(), ink_drop_visible_opacity())); return ripple; } std::unique_ptr<views::InkDrop> SubmenuButton::CreateInkDrop() { std::unique_ptr<views::InkDropImpl> ink_drop = views::Button::CreateDefaultInkDropImpl(); ink_drop->SetShowHighlightOnHover(false); return std::move(ink_drop); } void SubmenuButton::SetAcceleratorVisibility(bool visible) { if (visible == show_underline_) return; show_underline_ = visible; SchedulePaint(); } void SubmenuButton::SetUnderlineColor(SkColor color) { underline_color_ = color; } void SubmenuButton::PaintButtonContents(gfx::Canvas* canvas) { views::MenuButton::PaintButtonContents(canvas); if (show_underline_ && (underline_start_ != underline_end_)) { int padding = (width() - text_width_) / 2; int underline_height = (height() + text_height_) / 2 - 2; canvas->DrawLine(gfx::Point(underline_start_ + padding, underline_height), gfx::Point(underline_end_ + padding, underline_height), underline_color_); } } bool SubmenuButton::GetUnderlinePosition(const base::string16& text, base::char16* accelerator, int* start, int* end) const { int pos, span; base::string16 trimmed = gfx::RemoveAcceleratorChar(text, '&', &pos, &span); if (pos > -1 && span != 0) { *accelerator = base::ToUpperASCII(trimmed[pos]); GetCharacterPosition(trimmed, pos, start); GetCharacterPosition(trimmed, pos + span, end); return true; } return false; } void SubmenuButton::GetCharacterPosition(const base::string16& text, int index, int* pos) const { int height = 0; gfx::Canvas::SizeStringInt(text.substr(0, index), gfx::FontList(), pos, &height, 0, 0); } } // namespace atom
3,894
1,254
// XXX uniqID XXX 318a5e347d432a1a29542cd45457692a XXX #include <gba_types.h> #include "bullet.hpp" #include "fixed.hpp" #include "vulkanon/l0_enemy23.hpp" extern const BulletStepFunc bullet_72977f5a201704a116fed2c268b98db5_318a5e347d432a1a29542cd45457692a[] = { stepfunc_b9f3746024faf71a948d02a3f58cba12_318a5e347d432a1a29542cd45457692a, stepfunc_874e5b4a542f0f7f52ac24d8da866549_318a5e347d432a1a29542cd45457692a, NULL}; extern const BulletStepFunc bullet_da391036f4887058d231358ef78fb2f0_318a5e347d432a1a29542cd45457692a[] = { stepfunc_f8e5484dd9ba577849087e287b940bef_318a5e347d432a1a29542cd45457692a, stepfunc_f8e5484dd9ba577849087e287b940bef_318a5e347d432a1a29542cd45457692a, stepfunc_f8e5484dd9ba577849087e287b940bef_318a5e347d432a1a29542cd45457692a, stepfunc_f8e5484dd9ba577849087e287b940bef_318a5e347d432a1a29542cd45457692a, stepfunc_f8e5484dd9ba577849087e287b940bef_318a5e347d432a1a29542cd45457692a, stepfunc_f8e5484dd9ba577849087e287b940bef_318a5e347d432a1a29542cd45457692a, stepfunc_f8e5484dd9ba577849087e287b940bef_318a5e347d432a1a29542cd45457692a, stepfunc_f8e5484dd9ba577849087e287b940bef_318a5e347d432a1a29542cd45457692a, stepfunc_f8e5484dd9ba577849087e287b940bef_318a5e347d432a1a29542cd45457692a, stepfunc_f8e5484dd9ba577849087e287b940bef_318a5e347d432a1a29542cd45457692a, stepfunc_f8e5484dd9ba577849087e287b940bef_318a5e347d432a1a29542cd45457692a, stepfunc_f8e5484dd9ba577849087e287b940bef_318a5e347d432a1a29542cd45457692a, stepfunc_dae2cf81747ffb5070f05c8837b1d568_318a5e347d432a1a29542cd45457692a, NULL}; void stepfunc_b9f3746024faf71a948d02a3f58cba12_318a5e347d432a1a29542cd45457692a(BulletInfo *p) { p->wait = static_cast<u16>(10); } void stepfunc_874e5b4a542f0f7f52ac24d8da866549_318a5e347d432a1a29542cd45457692a(BulletInfo *p) { { u16 life = static_cast<u16>(1); FixedPointNum speed = (256 * -90 / 360) + ((180 * 1.0 * 256 / 360)) - p->getAngle();p->setRound(speed, life);} } void stepfunc_f8e5484dd9ba577849087e287b940bef_318a5e347d432a1a29542cd45457692a(BulletInfo *p) { { BulletInfo *bi; p->lastBulletAngle = p->lastBulletAngle + ((30 * 1.0 * 256 / 360)); p->lastBulletSpeed = (1); bi = ListBullets::makeNewBullet(); if (bi != NULL) { bi->initialize(BULLET_TYPE_NORMAL, p->getPosX(), p->getPosY(), p->lastBulletAngle, p->lastBulletSpeed, bullet_72977f5a201704a116fed2c268b98db5_318a5e347d432a1a29542cd45457692a); } } } void stepfunc_dae2cf81747ffb5070f05c8837b1d568_318a5e347d432a1a29542cd45457692a(BulletInfo *p) { ListBullets::stepFuncDrop(p);} BulletInfo *genBulletFunc_318a5e347d432a1a29542cd45457692a(FixedPointNum posx, FixedPointNum posy) { BulletInfo * bi; bi = ListBullets::makeNewBullet(); if (bi != NULL) { bi->initialize(BULLET_TYPE_ROOT, posx, posy, BulletInfo::DEFAULT_ANGLE, 0, bullet_da391036f4887058d231358ef78fb2f0_318a5e347d432a1a29542cd45457692a); } return bi;}
2,852
2,057
#include "fni_ext.h" #include "pod_std_native.h" #include <regex> static std::cmatch* getMatcher(fr_Env env, fr_Obj self) { static fr_Field f = fr_findField(env, fr_getObjType(env, self), "handle"); fr_Value val; fr_getInstanceField(env, self, f, &val); std::cmatch* raw = (std::cmatch*)(val.i); return raw; } fr_Bool std_RegexMatcher_matches(fr_Env env, fr_Obj self) { std::cmatch* m = getMatcher(env, self); return !m->empty(); } fr_Bool std_RegexMatcher_find(fr_Env env, fr_Obj self) { std::cmatch* m = getMatcher(env, self); return 0; } fr_Obj std_RegexMatcher_replaceFirst(fr_Env env, fr_Obj self, fr_Obj replacement) { std::cmatch* m = getMatcher(env, self); return 0; } fr_Obj std_RegexMatcher_replaceAll(fr_Env env, fr_Obj self, fr_Obj replacement) { std::cmatch* m = getMatcher(env, self); return 0; } fr_Int std_RegexMatcher_groupCount(fr_Env env, fr_Obj self) { std::cmatch* m = getMatcher(env, self); return 0; } fr_Obj std_RegexMatcher_group(fr_Env env, fr_Obj self, fr_Int group) { std::cmatch* m = getMatcher(env, self); return 0; } fr_Int std_RegexMatcher_start(fr_Env env, fr_Obj self, fr_Int group) { std::cmatch* m = getMatcher(env, self); return 0; } fr_Int std_RegexMatcher_end(fr_Env env, fr_Obj self, fr_Int group) { std::cmatch* m = getMatcher(env, self); return 0; } void std_RegexMatcher_finalize(fr_Env env, fr_Obj self) { std::cmatch* m = getMatcher(env, self); delete m; }
1,496
601
#include<bits/stdc++.h> using namespace std; typedef vector<int> vi; long long gcd(long long int a, long long int b) { if (b == 0) return a; return gcd(b, a % b); } long long lcm(int a, int b) { return (a / gcd(a, b)) * b; } const int MOD=1e9; int main() { int M,N; cin >> M >> N; vector<vi > a(M+1,vi (N+1,0)); for (int i=1;i<=M;++i) { for (int j=1;j<=N;++j) { cin >> a[i][j]; } } vector<vi > F(M+1,vi (N+1,0)); for (int i=1;i<=M;++i) { F[i][1]=1; } for (int i=1;i<=M;++i) { for (int j=1;j<=N;++j) { for (int x=1;x<=i;++x) { for (int y=1;y<=j;++y) { if (y < N && x+y<i+j && gcd(a[x][y],a[i][j])!=1) F[i][j]=(F[i][j]+F[x][y])%MOD; } } } } int sum=0; for (int i=1;i<=M;++i) { sum=(sum+F[i][N])%MOD; } cout << sum; return 0; }
963
460
// This file if part of the llir-opt project. // Licensing information can be found in the LICENSE file. // (C) 2018 Nandor Licker. All rights reserved. #include "passes/pre_eval/symbolic_context.h" #include "passes/pre_eval/symbolic_eval.h" #include "passes/pre_eval/symbolic_value.h" #include "passes/pre_eval/symbolic_visitor.h" // ----------------------------------------------------------------------------- bool SymbolicEval::VisitSllInst(SllInst &i) { class Visitor final : public BinaryVisitor<SllInst> { public: Visitor(SymbolicEval &e, SllInst &i) : BinaryVisitor(e, i) {} bool Visit(Scalar, const APInt &) override { return SetScalar(); } bool Visit(const APInt &, Scalar) override { return SetScalar(); } bool Visit(const APInt &l, const APInt &r) override { return SetInteger(l.shl(r.getSExtValue())); } bool Visit(const APInt &, LowerBoundedInteger) override { return SetScalar(); } bool Visit(LowerBoundedInteger l, const APInt &r) override { auto newBound = l.Bound.shl(r.getSExtValue()); if (newBound.isNonNegative()) { return SetLowerBounded(newBound); } else { return SetScalar(); } } bool Visit(Pointer l, const APInt &r) override { return SetValue(l.Ptr->Decay()); } bool Visit(Value l, const APInt &r) override { return SetValue(l.Ptr->Decay()); } bool Visit(Nullable l, const APInt &r) override { return SetValue(l.Ptr->Decay()); } }; return Visitor(*this, i).Evaluate(); } // ----------------------------------------------------------------------------- bool SymbolicEval::VisitSrlInst(SrlInst &i) { class Visitor final : public BinaryVisitor<SrlInst> { public: Visitor(SymbolicEval &e, SrlInst &i) : BinaryVisitor(e, i) {} bool Visit(Scalar, Scalar) override { return SetScalar(); } bool Visit(Scalar, const APInt &) override { return SetScalar(); } bool Visit(LowerBoundedInteger l, const APInt &r) override { return SetScalar(); } bool Visit(Pointer l, const APInt &r) override { return SetPointer(l.Ptr->Decay()); } bool Visit(Value l, const APInt &r) override { return SetValue(l.Ptr->Decay()); } bool Visit(Nullable l, const APInt &r) override { return SetValue(l.Ptr->Decay()); } bool Visit(const APInt &l, const APInt &r) override { return SetInteger(l.lshr(r.getZExtValue())); } }; return Visitor(*this, i).Evaluate(); } // ----------------------------------------------------------------------------- bool SymbolicEval::VisitSraInst(SraInst &i) { class Visitor final : public BinaryVisitor<SraInst> { public: Visitor(SymbolicEval &e, SraInst &i) : BinaryVisitor(e, i) {} bool Visit(Scalar, const APInt &) override { return SetScalar(); } bool Visit(const APInt &l, const APInt &r) override { return SetInteger(l.ashr(r.getZExtValue())); } bool Visit(Value l, const APInt &r) override { return SetValue(l.Ptr->Decay()); } }; return Visitor(*this, i).Evaluate(); }
3,215
1,104
// Copyright (c) by respective owners including Yahoo!, Microsoft, and // individual contributors. All rights reserved. Released under a BSD (revised) // license as described in the file LICENSE. #include <boost/test/unit_test.hpp> #include <boost/test/test_tools.hpp> #include "cache.h" #include "vw.h" #include "test_common.h" BOOST_AUTO_TEST_CASE(write_and_read_features_from_cache) { auto& vw = *VW::initialize("--quiet"); example src_ex; VW::read_line(vw, &src_ex, "|ns1 example value test |ss2 ex:0.5"); auto backing_vector = std::make_shared<std::vector<char>>(); io_buf io_writer; io_writer.add_file(VW::io::create_vector_writer(backing_vector)); VW::write_example_to_cache(io_writer, &src_ex, vw.example_parser->lbl_parser, vw.parse_mask); io_writer.flush(); io_buf io_reader; io_reader.add_file(VW::io::create_buffer_view(backing_vector->data(), backing_vector->size())); example dest_ex; VW::read_example_from_cache(io_reader, &dest_ex, vw.example_parser->lbl_parser, vw.example_parser->sorted_cache, vw.example_parser->_shared_data); BOOST_CHECK_EQUAL(dest_ex.indices.size(), 2); BOOST_CHECK_EQUAL(dest_ex.feature_space['n'].size(), 3); BOOST_CHECK_EQUAL(dest_ex.feature_space['s'].size(), 1); check_collections_with_float_tolerance( src_ex.feature_space['s'].values, dest_ex.feature_space['s'].values, FLOAT_TOL); check_collections_exact(src_ex.feature_space['s'].indicies, dest_ex.feature_space['s'].indicies); check_collections_with_float_tolerance( src_ex.feature_space['n'].values, dest_ex.feature_space['n'].values, FLOAT_TOL); check_collections_exact(src_ex.feature_space['n'].indicies, dest_ex.feature_space['n'].indicies); VW::finish(vw); }
1,731
669
#ifndef _NETP_CONSTANTS_H_ #define _NETP_CONSTANTS_H_ #include <climits> #include <netp/core/platform.hpp> #define NETP_SOCKET_ERROR (-1) #define NETP_INVALID_SOCKET netp::SOCKET(~0) namespace netp { namespace u8 { const u32_t MAX = 0xffU; } namespace i8 { const u32_t MAX = 0x7f; } namespace u16 { const u32_t MAX = 0xffffU; } namespace i16 { const u32_t MAX = 0x7fffU; } namespace u32 { const u32_t MAX = 0xffffffffUL; } namespace i32 { const u32_t MAX = 0x7fffffffUL; } namespace u64 { const u64_t MAX = 0xffffffffffffffffULL; } namespace i64 { const u64_t MAX = 0x7fffffffffffffffULL; } //WSAEWOULDBLOCK const int OK = 0; #if defined(_NETP_APPLE) const int E_EPERM = -1; /* Operation not permitted */ const int E_ENOENT = -2; /* No such file or directory */ const int E_ESRCH = -3; /* No such process */ const int E_EINTR =-4; /* Interrupted system call */ const int E_EIO = -5; /* Input/output error */ const int E_ENXIO = -6; /* Device not configured */ const int E_E2BIG = -7; /* Argument list too long */ const int E_ENOEXEC = -8; /* Exec format error */ const int E_EBADF = -9; /* Bad file descriptor */ const int E_ECHILD = -10; /* No child processes */ const int E_EDEADLK = -11; /* Resource deadlock avoided */ /* 11 was EAGAIN */ const int E_ENOMEM = -12; /* Cannot allocate memory */ const int E_EACCES = -13; /* Permission denied */ const int E_EFAULT = -14; /* Bad address */ #if __DARWIN_C_LEVEL >= __DARWIN_C_FULL const int E_ENOTBLK = -15; ; /* Block device required */ #endif const int E_EBUSY = -16; /* Device / Resource busy */ const int E_EEXIST =-17; /* File exists */ const int E_EXDEV = -18; /* Cross-device link */ const int E_ENODEV = -19; /* Operation not supported by device */ const int E_ENOTDIR = -20; /* Not a directory */ const int E_EISDIR = -21; /* Is a directory */ const int E_EINVAL = -22; /* Invalid argument */ const int E_ENFILE = -23; /* Too many open files in system */ const int E_EMFILE = -24; /* Too many open files */ const int E_ENOTTY = -25; /* Inappropriate ioctl for device */ const int E_ETXTBSY = 26; /* Text file busy */ const int E_EFBIG = -27; /* File too large */ const int E_ENOSPC = -28; /* No space left on device */ const int E_ESPIPE = -29; /* Illegal seek */ const int E_EROFS = -30; /* Read-only file system */ const int E_EMLINK = -31; /* Too many links */ const int E_EPIPE = -32; /* Broken pipe */ /* math software */ const int E_EDOM = -33; /* Numerical argument out of domain */ const int E_ERANGE = -34; /* Result too large */ /* non-blocking and interrupt i/o */ const int E_EAGAIN = -35; /* Resource temporarily unavailable */ const int E_EWOULDBLOCK = E_EAGAIN; /* Operation would block */ const int E_EINPROGRESS = -36; /* Operation now in progress */ const int E_EALREADY = -37; /* Operation already in progress */ /* ipc/network software -- argument errors */ const int E_ENOTSOCK = -38; /* Socket operation on non-socket */ const int E_EDESTADDRREQ = -39; /* Destination address required */ const int E_EMSGSIZE = -40; /* Message too long */ const int E_EPROTOTYPE = -41; /* Protocol wrong type for socket */ const int E_ENOPROTOOPT = -42; /* Protocol not available */ const int E_EPROTONOSUPPORT = -43; /* Protocol not supported */ #if __DARWIN_C_LEVEL >= __DARWIN_C_FULL const int E_ESOCKTNOSUPPORT = -44; /* Socket type not supported */ #endif const int E_ENOTSUP = -45; /* Operation not supported */ #if !__DARWIN_UNIX03 && !defined(KERNEL) /* * This is the same for binary and source copmpatability, unless compiling * the kernel itself, or compiling __DARWIN_UNIX03; if compiling for the * kernel, the correct value will be returned. If compiling non-POSIX * source, the kernel return value will be converted by a stub in libc, and * if compiling source with __DARWIN_UNIX03, the conversion in libc is not * done, and the caller gets the expected (discrete) value. */ const int E_EOPNOTSUPP = E_ENOTSUP; /* Operation not supported on socket */ #endif /* !__DARWIN_UNIX03 && !KERNEL */ #if __DARWIN_C_LEVEL >= __DARWIN_C_FULL const int E_EPFNOSUPPORT = -46; /* Protocol family not supported */ #endif const int E_EAFNOSUPPORT = -47; /* Address family not supported by protocol family */ const int E_EADDRINUSE = -48; /* Address already in use */ const int E_EADDRNOTAVAIL = -49; /* Can't assign requested address */ /* ipc/network software -- operational errors */ const int E_ENETDOWN = -50; /* Network is down */ const int E_ENETUNREACH = -51; /* Network is unreachable */ const int E_ENETRESET = -52;/* Network dropped connection on reset */ const int E_ECONNABORTED = -53; /* Software caused connection abort */ const int E_ECONNRESET = -54; /* Connection reset by peer */ const int E_ENOBUFS = -55; /* No buffer space available */ const int E_EISCONN = -56; /* Socket is already connected */ const int E_ENOTCONN = -57; /* Socket is not connected */ #if __DARWIN_C_LEVEL >= __DARWIN_C_FULL const int E_ESHUTDOWN = -58; /* Can't send after socket shutdown */ const int E_ETOOMANYREFS = -59; /* Too many references: can't splice */ #endif const int E_ETIMEDOUT = -60; /* Operation timed out */ const int E_ECONNREFUSED = -61; /* Connection refused */ const int E_ELOOP = -62; /* Too many levels of symbolic links */ const int E_ENAMETOOLONG = -63; /* File name too long */ /* should be rearranged */ #if __DARWIN_C_LEVEL >= __DARWIN_C_FULL const int E_EHOSTDOWN = -64; /* Host is down */ #endif const int E_EHOSTUNREACH = -65; /* No route to host */ const int E_ENOTEMPTY = -66; /* Directory not empty */ /* quotas & mush */ #if __DARWIN_C_LEVEL >= __DARWIN_C_FULL const int E_EPROCLIM = -67; /* Too many processes */ const int E_EUSERS = -68; /* Too many users */ #endif const int E_EDQUOT = -69; /* Disc quota exceeded */ /* Network File System */ const int E_ESTALE = -70; /* Stale NFS file handle */ #if __DARWIN_C_LEVEL >= __DARWIN_C_FULL const int E_EREMOTE = -71; /* Too many levels of remote in path */ const int E_EBADRPC = -72; /* RPC struct is bad */ const int E_ERPCMISMATCH = -73; /* RPC version wrong */ const int E_EPROGUNAVAIL = -74; /* RPC prog. not avail */ const int E_EPROGMISMATCH = -75; /* Program version wrong */ const int E_EPROCUNAVAIL = -76; /* Bad procedure for program */ #endif const int E_ENOLCK = -77; /* No locks available */ const int E_ENOSYS = -78; /* Function not implemented */ #if __DARWIN_C_LEVEL >= __DARWIN_C_FULL const int E_EFTYPE = -79; /* Inappropriate file type or format */ const int E_EAUTH = -80; /* Authentication error */ const int E_ENEEDAUTH = -81; /* Need authenticator */ /* Intelligent device errors */ const int E_EPWROFF = -82; /* Device power is off */ const int E_EDEVERR = -83; /* Device error, e.g. paper out */ #endif const int E_EOVERFLOW = -84; /* Value too large to be stored in data type */ /* Program loading errors */ #if __DARWIN_C_LEVEL >= __DARWIN_C_FULL const int E_EBADEXEC = -85; /* Bad executable */ const int E_EBADARCH = -86; /* Bad CPU type in executable */ const int E_ESHLIBVERS = -87; /* Shared library version mismatch */ const int E_EBADMACHO = -88; /* Malformed Macho file */ #endif const int E_ECANCELED = -89; /* Operation canceled */ const int E_EIDRM = -90; /* Identifier removed */ const int E_ENOMSG = -91; /* No message of desired type */ const int E_EILSEQ = -92; /* Illegal byte sequence */ #if __DARWIN_C_LEVEL >= __DARWIN_C_FULL const int E_ENOATTR = -93; /* Attribute not found */ #endif const int E_EBADMSG = -94; /* Bad message */ const int E_EMULTIHOP = -95; /* Reserved */ const int E_ENODATA = -96; /* No message available on STREAM */ const int E_ENOLINK = -97; /* Reserved */ const int E_ENOSR = -98; /* No STREAM resources */ const int E_ENOSTR = -99; /* Not a STREAM */ const int E_EPROTO = -100; /* Protocol error */ const int E_ETIME = -101; /* STREAM ioctl timeout */ #if __DARWIN_UNIX03 || defined(KERNEL) /* This value is only discrete when compiling __DARWIN_UNIX03, or KERNEL */ const int E_EOPNOTSUPP = -102; /* Operation not supported on socket */ #endif /* __DARWIN_UNIX03 || KERNEL */ const int E_ENOPOLICY = -103; /* No such policy registered */ #if __DARWIN_C_LEVEL >= 200809L const int E_ENOTRECOVERABLE = -104; /* State not recoverable */ const int E_EOWNERDEAD = -105; /* Previous owner died */ #endif #if __DARWIN_C_LEVEL >= __DARWIN_C_FULL const int E_EQFULL = -106; /* Interface output queue is full */ const int E_ELAST = -106; /* Must be equal largest errno */ #endif #elif defined(_NETP_GNU_LINUX) || defined(_NETP_ANDROID) const int E_EPERM = -1; //operation not permitted const int E_ENOENT = -2; //no such file or directory const int E_ESRCH = -3; //no such process const int E_EINTR = -4; //interrupted system call const int E_EIO = -5; //I/O error const int E_ENXIO = -6; //no such device or address const int E_E2BIG = -7; //Arg list too long const int E_ENOEXEC = -8; //Exec format error const int E_EBADF = -9; //Bad file number const int E_ECHILD = -10; //No child processes const int E_EAGAIN = -11; //Try again const int E_ENOMEM = -12; //Out of memory const int E_EACCESS = -13; //Permission denied const int E_EFAULT = -14; //Bad address const int E_ENOTBLK = -15; //Block device required const int E_EBUSY = -16; //Device or resource busy const int E_EEXIST = -17; //File exists const int E_EEXDEV = -18; //Cross-device link const int E_ENODEV = -19; //No such device const int E_ENOTDIR = -20; //Not a directory const int E_EISDIR = -21; //Is a directory const int E_EINVAL = -22; //Invalid argument const int E_ENFILE = -23; //File table overflow const int E_EMFILE = -24; //Too many open files const int E_ENOTTY = -25; //Not a tty device const int E_ETXTBSY = -26; //Text file busy const int E_EFBIG = -27; //File too large const int E_ENOSPC = -28; //No space left on device const int E_ESPIPE = -29; //Illegal seek const int E_EROFS = -30; //read-only file system const int E_EMLINK = -31; //Too many links const int E_EPIPE = -32; //broken pipe const int E_EDOM = -33; //Math argument out of domain const int E_ERANGE = -34; //Math result not representable const int E_EDEADLK = -35; //dead lock wolld occur const int E_ENAMETOOLONG = -36; //file too long const int E_ENOLCK = -37; //No record locks available const int E_ENOSYS = -38; //Function not implemented const int E_ENOTEMPTY = -39; //dierctory not empty const int E_ELOOP = -40; //too many symbolic links encountered const int E_EWOULDBLOCK = -41; //same as EAGAIN const int E_ENOMSG = -42; //No message of desired type const int E_EIDRM = -43; //identifier removed const int E_ECHRNG = -44; //channel number out of range const int E_EL2NSYNC = -45; //level 2 not synchronized const int E_EL3HLT = -46; //level 3 halted const int E_EL3RST = -47; //level3 reset const int E_ELNRNG = -48; //Link number out of range const int E_EUNATCH = -49; //protocol driver not attached const int E_ENOCSI = -50; //No CSI structure available const int E_EL2HLT = -51; //Level 2 halted const int E_EBADE = -52; //Invalid exchange const int E_EBADR = -53; //Invalid request descriptor const int E_EXFULL = -54; //Exchange full const int E_ENOANO = -55; //No anode const int E_EBADRQC = -56; //Invalid request code const int E_EBADSLT = -57; //Invalid slot const int E_EDEADLOCK = -58; //Same as EDEADLK const int E_EBFONT = -59; //Bad font file format const int E_ENOSTR = -60; //No data available const int E_ENODATA = -61; //No data available const int E_ETIME = -62; //Timer expired const int E_ENOSR = -63; //Out of streams resources const int E_ERROR_NETNAME_DELETED = -64; //WINDOWS IOCP: The specified network name is no longer available const int E_ENONET = -64; //machine is not on network const int E_ENOPKG = -65; //Package not installed const int E_EREMOTE = -66; //Object is remote const int E_ENOLINK = -67; //Link has been severed const int E_EADV = -68; //Advertise error const int E_ESRMNT = -69; //Srmount error const int E_ECOMM = -70; //Communication error on send const int E_EPROTO = -71; //protocol error const int E_EMULTIHOP = -72; //Multihop attempted const int E_EDOTDOT = -73; //RFS specific error const int E_EBADMSG = -74; //Not a data message const int E_EOVERFLOW = -75; //Value too large for defined data type const int E_ENOTUNIQ = -76; //Name not unique on network const int E_EBADFD = -77; //File descriptor in bad state const int E_REMCHG = -78; //Remote address changed const int E_ELIBACC = -79; //Cannot access a needed shared library const int E_ELIBBAD = -80; //Accessing a corrupted shared library const int E_ELIBSCN = -81; //A .lib section in an .out is corrupted const int E_ELIMAX = -82; //Linking in too many shared libraries const int E_ELIEXEC = -83; //Cannot exec a shared library directly const int E_ELIILSEQ = -84; //Illegal byte sequence const int E_ERESTART = -85; //Interrupted system call should be restarted const int E_ESTRPIPE = -86; //Streams pipe error const int E_EUSERS = -87; //Too many users const int E_ENOTSOCK = -88; //socket operation on non-socket const int E_EDESTADDRREQ = -89; //Destination address required const int E_EMSGSIZE = -90; //Message too long const int E_EPROTOTYPE = -91; //protocol wrong type for socket const int E_ENOPROTOOPT = -92; //protocol not available const int E_EPROTONOSUPPORT = -93; //protocol not supported const int E_ESOCKTNOSUPPORT = -94; //socket type not supported const int E_EOPNOTSUPP = -95; //Operation not supported on transport const int E_EPFNOSUPPORT = -96; //protocol family not supported const int E_EAFNOSUPPORT = -97; //address family not supported by protocol const int E_EADDRINUSE = -98; //address already in use const int E_EADDRNOTAVAIL = -99; //Cannot assign requested address const int E_ENETDOWN = -100; //Network is down const int E_ENETUNREACH = -101; //Network is unreachable const int E_ENETRESET = -102; //Network dropped const int E_ECONNABORTED = -103; //Software caused connection const int E_ECONNRESET = -104; //Connection reset by const int E_ENOBUFS = -105; //No buffer space available const int E_EISCONN = -106; //Transport endpoint const int E_ENOTCONN = -107; //Transport endpoint const int E_ESHUTDOWN = -108; //Cannot send after transport const int E_ETOOMANYREFS = -109; //Too many references const int E_ETIMEOUT = -110; //Connection timed const int E_ECONNREFUSED = -111; //Connection refused const int E_EHOSTDOWN = -112; //Host is down const int E_EHOSTUNREACH = -113; //No route to host const int E_EALREADY = -114; //Operation already const int E_EINPROGRESS = -115; //Operation now in const int E_ESTALE = -116; //Stale NFS file handle const int E_EUCLEAN = -117; //Structure needs cleaning const int E_ENOTNAM = -118; //Not a XENIX-named const int E_ENAVAIL = -119; //No XENIX semaphores const int E_EISNAM = -120; //Is a named type file const int E_EREMOTEIO = -121; //Remote I/O error const int E_EDQUOT = -122; //Quota exceeded const int E_ENOMEDIUM = -123; //No medium found const int E_EMEDIUMTYPE = -124; //Wrong medium type const int E_ECANCELED = -125; const int E_ENOKEY = -126; const int E_EKEYEXPIRED = -127; const int E_EKEYREVOKED = -128; const int E_EKEYREJECTED = -129; const int E_EOWNERDEAD = -130; const int E_ENOTRECOVERABLE = -131; const int E_ERFKILL = -132; const int E_EHWPOISON = -133; #elif defined(_NETP_WIN) const int E_ERROR_ACCESS_DENIED = -5; const int E_WSA_INVALID_HANDLE = -6; const int E_ERROR_HANDLE_EOF = -38; const int E_WSA_INVALID_PARAMETER = -87; const int E_ERROR_MORE_DATA = -234; const int E_WAIT_TIMEOUT = -258; const int E_ERROR_ABANDONED_WAIT_0 = -735; const int E_WSA_OPERATION_ABORTED = -995; const int E_WSA_IO_INCOMPLETE = -996; const int E_WSA_IO_PENDING = -997; const int E_ERROR_PRIVILEGE_NOT_HELD = -1314; const int E_ERROR_CONNECTION_ABORTED = -1236; // 1---19999; reserved for system call error code (windows) const int E_WSAEINTR = -10004; // A blocking operation was interrupted by a call to WSACancelBlockingCall. const int E_WSAEBADF = -10009; // The file handle supplied is not valid. const int E_WSAEACCES = -10013; //An attempt was made to access a socket in a way forbidden by its access permissions. const int E_WSAEFAULT = -10014; // The system detected an invalid pointer address in attempting to use a pointer argument in a call. const int E_WSAEINVAL = -10022; // An invalid argument was supplied const int E_WSAEMFILE = -10024; // Too many open sockets. const int E_WSAEWOULDBLOCK = -10035; // A non-blocking socket operation could not be completed immediately. const int E_WSAEINPROGRESS = -10036; // A blocking operation is currently executing. const int E_WSAEALREADY = -10037; // An operation was attempted on a non-blocking socket that already had an operation in progress. const int E_WSAENOTSOCK = -10038; // An operation was attempted on something that is not a socket. const int E_WSAEMSGSIZE = -10040; // A message sent on a datagram socket was larger than the internal message buffer or some other network limit; or the buffer used to receive a datagram into was smaller than the datagram itself. const int E_WSAEPROTOTYPE = -10041; //A protocol was specified in the socket function call that does not support the semantics of the socket type requested. const int E_WSAENOPROTOOPT = -10042; //An unknown; invalid; or unsupported option or level was specified in a getsockopt or setsockopt call const int E_WSAEPROTONOSUPPORT = -10043; //The requested protocol has not been configured into the system; or no implementation for it exists. const int E_WSAESOCKTNOSUPPORT = -10044; //The support for the specified socket type does not exist in this address family const int E_WSAEOPNOTSUPP = -10045; //The attempted operation is not supported for the type of object referenced. const int E_WSAEPFNOSUPPORT = -10046; //The protocol family has not been configured into the system or no implementation for it exists const int E_WSAEAFNOSUPPORT = -10047; //An address incompatible with the requested protocol was used const int E_WSAEADDRINUSE = -10048; // Only one usage of each socket address (protocol/network address/port) is normally permitted. const int E_WSAEADDRNOTAVAIL = -10049; // The requested address is not valid in its context. const int E_WSAENETDOWN = -10050; //A socket operation encountered a dead network. const int E_WSAENETUNREACH = -10051; // A socket operation was attempted to an unreachable network. const int E_WSAENETRESET = -10052; // The connection has been broken due to keep-alive activity detecting a failure while the operation was in progress. const int E_WSAECONNABORTED = -10053; // An established connection was aborted by the software in your host machine. const int E_WSAECONNRESET = -10054; // An existing connection was forcibly closed by the remote host. const int E_WSAENOBUFS = -10055; // An operation on a socket could not be performed because the system lacked sufficient buffer space or because a queue was full. const int E_WSAEISCONN = -10056; // A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied. const int E_WSAENOTCONN = -10057; // A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied. const int E_WSAESHUTDOWN = -10058; //A request to send or receive data was disallowed because the socket had already been shut down in that direction with a previous shutdown call const int E_WSAETOOMANYREFS = -10059; //Too many references to some kernel object. const int E_WSAETIMEDOUT = -10060; //A connection attempt failed because the connected party did not properly respond after a period of time; or established connection failed because connected host has failed to respond. const int E_WSAECONNREFUSED = -10061; //No connection could be made because the target machine actively refused it. const int E_WSAELOOP = -10062; //Cannot translate name const int E_WSAEHOSTDOWN = -10064; // A socket operation failed because the destination host was down const int E_WSAEHOSTUNREACH = -10065; // A socket operation was attempted to an unreachable host. const int E_WSAEPROCLIM = -10067; // A Windows Sockets implementation may have a limit on the number of applications that may use it simultaneously. const int E_WSAEUSERS = -10068; const int E_WSAEDQUOT = -10069; const int E_WSASYSNOTREADY = -10091; const int E_WSANOTINITIALISED = -10093; const int E_WSAEPROVIDERFAILEDINIT = -10106; const int E_WSASYSCALLFAILURE = -10107; const int E_WSASERVICE_NOT_FOUND = -10108; const int E_WSATYPE_NOT_FOUND = -10109; const int E_WSA_E_NO_MORE = -10110; const int E_WSA_E_CANCELLED = -10111; const int E_WSAEREFUSED = -10112; const int E_WSAHOST_NOT_FOUND = -11001; const int E_WSATRY_AGAIN = -11002; const int E_WSANO_RECOVERY = -11003; const int E_WSANO_DATA = -11004; const int E_WSA_QOS_RECEIVERS = -11005; const int E_WSA_QOS_SENDERS = -11006; const int E_ECONNABORTED = E_WSAECONNABORTED; const int E_EINTR = E_WSAEINTR; const int E_EWOULDBLOCK = E_WSAEWOULDBLOCK; const int E_EAGAIN = E_EWOULDBLOCK; const int E_EINPROGRESS = E_WSAEWOULDBLOCK; //pls refer tohttps://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-connect const int E_EMFILE = E_WSAEMFILE; const int E_EACCESS = E_WSAEACCES; const int E_EBADF = E_WSAEBADF; const int E_EALREADY = E_WSAEALREADY; const int E_ECONNRESET = E_WSAECONNRESET; const int E_ETIMEOUT = E_WSAETIMEDOUT; const int E_EADDRINUSE = E_WSAEADDRINUSE; const int E_EINVAL = E_WSAEINVAL; const int E_ENOTCONN = E_WSAENOTCONN; #endif //internal error const int E_NETP_APP_EXIT = -20000; const int E_NO_NET_DEV = -20001; const int E_INVALID_OPERATION = -20002; const int E_INVALID_STATE = -20003; const int E_MEMORY_MALLOC_FAILED = -20004; const int E_MEMORY_ACCESS_ERROR = -20005; const int E_MEMORY_ALLOC_FAILED = -20006; const int E_MEMORY_NEW_FAILED = -20007; const int E_TRY_AGAIN = -20008; const int E_INVAL = -20009; const int E_ASSERT_FAILED = -20010; const int E_NETP_THROW = -20011; const int E_UNKNOWN = -20012; const int E_THREAD_INTERRUPT = -20013; const int E_TODO = -20014; const int E_BAD_CAST = -20015; const int E_OP_INPROCESS = -20016; const int E_OP_ABORT = -20017; const int E_OP_TIMEOUT = -20018; const int E_OP_ALREADY = -20019; const int E_EVENT_BROKER_BINDED_ALREADY = -21001; const int E_EVENT_BROKER_NO_LISTENER = -21002; const int E_XXTEA_INVALID_DATA = -22001; const int E_XXTEA_DECRYPT_FAILED = -22002; const int E_XXTEA_ENCRYPT_FAILED = -22003; const int E_DH_HANDSHAKE_MESSAGE_CHECK_FAILED = -22011; const int E_DH_HANDSHAKE_FAILED = -22012; const int E_IO_EVENT_LOOP_NOTIFY_TERMINATING = -25001; const int E_IO_EVENT_LOOP_TERMINATED = -25002; const int E_IO_EVENT_LOOP_BYE_DO_NOTHING = -25003; const int E_IO_BEGIN_FAILED = -25004; //30000 - 30999 //system level socket error const int E_SOCKET_EPOLLHUP = -30001; const int E_SOCKET_GRACE_CLOSE = -30002; //31000 - 31999 //user custom socket error const int E_SOCKET_INVALID_FAMILY = -31001; const int E_SOCKET_INVALID_TYPE = -31002; const int E_SOCKET_INVALID_ADDRESS = -31003; const int E_SOCKET_INVALID_PROTOCOL = -31004; const int E_SOCKET_INVALID_STATE = -31005; const int E_SOCKET_SELF_CONNCTED = -31006; const int E_SOCKET_READ_CLOSED_ALREADY = -31007; const int E_SOCKET_WRITE_CLOSED_ALREADY = -31008; const int E_SOCKET_NO_AVAILABLE_ADDR = -31009; const int E_SOCKET_OP_ALREADY = -31010; const int E_CHANNEL_BDLIMIT = -34001; const int E_CHANNEL_READ_BLOCK = -34002; const int E_CHANNEL_WRITE_BLOCK = -34003; const int E_CHANNEL_READ_CLOSED = -34004; const int E_CHANNEL_WRITE_CLOSED = -34005; const int E_CHANNEL_INVALID_STATE = -34006; const int E_CHANNEL_NOT_EXISTS = -34007; const int E_CHANNEL_EXISTS = -34008; const int E_CHANNEL_CLOSED = -34009; const int E_CHANNEL_CLOSING = -34010; const int E_CHANNEL_WRITE_SHUTDOWNING = -34011; const int E_CHANNEL_WRITING = -34012; const int E_CHANNEL_OUTGO_LIST_EMPTY = -34013; //FOR IOCP const int E_CHANNEL_READ_WRITE_ERROR = -34014; const int E_CHANNEL_ABORT = -34015; const int E_CHANNEL_CONTEXT_REMOVED = -34016; const int E_CHANNEL_OVERLAPPED_OP_TRY = -34017; const int E_CHANNEL_MISSING_MAKER = -34018;//custom socket channel must have its own maker const int E_FORWARDER_DOMAIN_LEN_EXCEED = -35001; const int E_FORWARDER_INVALID_IPV4 = -35002; const int E_FORWARDER_DIAL_DST_FAILED = -35003; const int E_DNS_LOOKUP_RETURN_NO_IP = -36001; const int E_DNS_TEMPORARY_ERROR = -36002; const int E_DNS_PROTOCOL_ERROR = -36003; const int E_DNS_DOMAIN_NAME_NOT_EXISTS = -36004; const int E_DNS_DOMAIN_NO_DATA = -36005; const int E_DNS_NOMEM = -36006; const int E_DNS_BADQUERY = -36007; const int E_DNS_SERVER_SHUTDOWN = -36008; const int E_MUX_STREAM_TRANSPORT_CLOSED = -37001; const int E_MUX_STREAM_RST = -37002; const int E_RPC_NO_WRITE_CHANNEL = -40001; const int E_RPC_CALL_UNKNOWN_API = -40002; const int E_RPC_CALL_INVALID_PARAM = -40003; const int E_RPC_CALL_ERROR_UNKNOWN = -40004; const int E_RPC_CALL_CANCEL = -40005; const int E_RPC_CALL_TIMEOUT = -40006; const int E_RPC_WRITE_TIMEOUT = -40007; const int E_RPC_CONNECT_ABORT = -40008; const int E_RPC_MESSAGE_DECODE_FAILED = -40009; const int E_HTTP_CLIENT_REQ_IN_OP = -41001; const int E_HTTP_MESSAGE_INVALID_TYPE = -41002; const int E_HTTP_REQUEST_NOT_DONE = -41003; const int E_HTTP_INVALID_HOST = -41004; const int E_HTTP_INVALID_OP = -41005; const int E_HTTP_REQ_TIMEOUT = -41006; const int E_HTTP_CLIENT_DIAL_CANCEL = -41007; const int E_HTTP_CLIENT_CLOSING = -41008; const int E_HTTP_EMPTY_FILED_NAME = -41009; } //endif netp ns #endif //END OF NETP_ERROR_HEADER
28,439
12,454
/* Copyright (c) 2006, Michael Kazhdan and Matthew Bolitho 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 Johns Hopkins University 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 <sstream> #include <sstream> #include <iomanip> #include <unordered_map> #include "MyMiscellany.h" #include "MarchingCubes.h" #include "MAT.h" // Specialized iso-surface extraction template< class Real , class Vertex > struct IsoSurfaceExtractor< 3 , Real , Vertex > { static const unsigned int Dim = 3; typedef typename FEMTree< Dim , Real >::LocalDepth LocalDepth; typedef typename FEMTree< Dim , Real >::LocalOffset LocalOffset; typedef typename FEMTree< Dim , Real >::ConstOneRingNeighborKey ConstOneRingNeighborKey; typedef typename FEMTree< Dim , Real >::ConstOneRingNeighbors ConstOneRingNeighbors; typedef RegularTreeNode< Dim , FEMTreeNodeData , depth_and_offset_type > TreeNode; template< unsigned int WeightDegree > using DensityEstimator = typename FEMTree< Dim , Real >::template DensityEstimator< WeightDegree >; template< typename FEMSigPack , unsigned int PointD > using _Evaluator = typename FEMTree< Dim , Real >::template _Evaluator< FEMSigPack , PointD >; protected: static std::mutex _pointInsertionMutex; static std::atomic< size_t > _BadRootCount; ////////// // _Key // ////////// struct _Key { int idx[Dim]; _Key( void ){ for( unsigned int d=0 ; d<Dim ; d++ ) idx[d] = 0; } int &operator[]( int i ){ return idx[i]; } const int &operator[]( int i ) const { return idx[i]; } bool operator == ( const _Key &key ) const { for( unsigned int d=0 ; d<Dim ; d++ ) if( idx[d]!=key[d] ) return false; return true; } bool operator != ( const _Key &key ) const { return !operator==( key ); } std::string to_string( void ) const { std::stringstream stream; stream << "("; for( unsigned int d=0 ; d<Dim ; d++ ) { if( d ) stream << ","; stream << idx[d]; } stream << ")"; return stream.str(); } struct Hasher { size_t operator()( const _Key &i ) const { size_t hash = 0; for( unsigned int d=0 ; d<Dim ; d++ ) hash ^= i.idx[d]; return hash; } }; }; ////////////// // _IsoEdge // ////////////// struct _IsoEdge { _Key vertices[2]; _IsoEdge( void ) {} _IsoEdge( _Key v1 , _Key v2 ){ vertices[0] = v1 , vertices[1] = v2; } _Key &operator[]( int idx ){ return vertices[idx]; } const _Key &operator[]( int idx ) const { return vertices[idx]; } }; //////////////// // _FaceEdges // //////////////// struct _FaceEdges{ _IsoEdge edges[2] ; int count; }; /////////////// // SliceData // /////////////// class SliceData { typedef RegularTreeNode< Dim , FEMTreeNodeData , depth_and_offset_type > TreeOctNode; public: template< unsigned int Indices > struct _Indices { node_index_type idx[Indices]; _Indices( void ){ for( unsigned int i=0 ; i<Indices ; i++ ) idx[i] = -1; } node_index_type& operator[] ( int i ) { return idx[i]; } const node_index_type& operator[] ( int i ) const { return idx[i]; } }; typedef _Indices< HyperCube::Cube< Dim-1 >::template ElementNum< 0 >() > SquareCornerIndices; typedef _Indices< HyperCube::Cube< Dim-1 >::template ElementNum< 1 >() > SquareEdgeIndices; typedef _Indices< HyperCube::Cube< Dim-1 >::template ElementNum< 2 >() > SquareFaceIndices; struct SliceTableData { Pointer( SquareCornerIndices ) cTable; Pointer( SquareEdgeIndices ) eTable; Pointer( SquareFaceIndices ) fTable; node_index_type nodeOffset; node_index_type cCount , eCount , fCount; node_index_type nodeCount; SliceTableData( void ){ fCount = eCount = cCount = 0 , _oldNodeCount = 0 , cTable = NullPointer( SquareCornerIndices ) , eTable = NullPointer( SquareEdgeIndices ) , fTable = NullPointer( SquareFaceIndices ) , _cMap = _eMap = _fMap = NullPointer( node_index_type ) , _processed = NullPointer( char ); } void clear( void ){ DeletePointer( cTable ) ; DeletePointer( eTable ) ; DeletePointer( fTable ) ; DeletePointer( _cMap ) ; DeletePointer( _eMap ) ; DeletePointer( _fMap ) ; DeletePointer( _processed ) ; fCount = eCount = cCount = 0; } ~SliceTableData( void ){ clear(); } SquareCornerIndices& cornerIndices( const TreeOctNode* node ) { return cTable[ node->nodeData.nodeIndex - nodeOffset ]; } SquareCornerIndices& cornerIndices( node_index_type idx ) { return cTable[ idx - nodeOffset ]; } const SquareCornerIndices& cornerIndices( const TreeOctNode* node ) const { return cTable[ node->nodeData.nodeIndex - nodeOffset ]; } const SquareCornerIndices& cornerIndices( node_index_type idx ) const { return cTable[ idx - nodeOffset ]; } SquareEdgeIndices& edgeIndices( const TreeOctNode* node ) { return eTable[ node->nodeData.nodeIndex - nodeOffset ]; } SquareEdgeIndices& edgeIndices( node_index_type idx ) { return eTable[ idx - nodeOffset ]; } const SquareEdgeIndices& edgeIndices( const TreeOctNode* node ) const { return eTable[ node->nodeData.nodeIndex - nodeOffset ]; } const SquareEdgeIndices& edgeIndices( node_index_type idx ) const { return eTable[ idx - nodeOffset ]; } SquareFaceIndices& faceIndices( const TreeOctNode* node ) { return fTable[ node->nodeData.nodeIndex - nodeOffset ]; } SquareFaceIndices& faceIndices( node_index_type idx ) { return fTable[ idx - nodeOffset ]; } const SquareFaceIndices& faceIndices( const TreeOctNode* node ) const { return fTable[ node->nodeData.nodeIndex - nodeOffset ]; } const SquareFaceIndices& faceIndices( node_index_type idx ) const { return fTable[ idx - nodeOffset ]; } protected: Pointer( node_index_type ) _cMap; Pointer( node_index_type ) _eMap; Pointer( node_index_type ) _fMap; Pointer( char ) _processed; node_index_type _oldNodeCount; friend SliceData; }; struct XSliceTableData { Pointer( SquareCornerIndices ) eTable; Pointer( SquareEdgeIndices ) fTable; node_index_type nodeOffset; node_index_type fCount , eCount; node_index_type nodeCount; XSliceTableData( void ){ fCount = eCount = 0 , _oldNodeCount = 0 , eTable = NullPointer( SquareCornerIndices ) , fTable = NullPointer( SquareEdgeIndices ) , _eMap = _fMap = NullPointer( node_index_type ); } ~XSliceTableData( void ){ clear(); } void clear( void ) { DeletePointer( fTable ) ; DeletePointer( eTable ) ; DeletePointer( _eMap ) ; DeletePointer( _fMap ) ; fCount = eCount = 0; } SquareCornerIndices& edgeIndices( const TreeOctNode* node ) { return eTable[ node->nodeData.nodeIndex - nodeOffset ]; } SquareCornerIndices& edgeIndices( node_index_type idx ) { return eTable[ idx - nodeOffset ]; } const SquareCornerIndices& edgeIndices( const TreeOctNode* node ) const { return eTable[ node->nodeData.nodeIndex - nodeOffset ]; } const SquareCornerIndices& edgeIndices( node_index_type idx ) const { return eTable[ idx - nodeOffset ]; } SquareEdgeIndices& faceIndices( const TreeOctNode* node ) { return fTable[ node->nodeData.nodeIndex - nodeOffset ]; } SquareEdgeIndices& faceIndices( node_index_type idx ) { return fTable[ idx - nodeOffset ]; } const SquareEdgeIndices& faceIndices( const TreeOctNode* node ) const { return fTable[ node->nodeData.nodeIndex - nodeOffset ]; } const SquareEdgeIndices& faceIndices( node_index_type idx ) const { return fTable[ idx - nodeOffset ]; } protected: Pointer( node_index_type ) _eMap; Pointer( node_index_type ) _fMap; node_index_type _oldNodeCount; friend SliceData; }; template< unsigned int D , unsigned int ... Ks > struct HyperCubeTables{}; template< unsigned int D , unsigned int K > struct HyperCubeTables< D , K > { static unsigned int CellOffset[ HyperCube::Cube< D >::template ElementNum< K >() ][ HyperCube::Cube< D >::template IncidentCubeNum< K >() ]; static unsigned int IncidentElementCoIndex[ HyperCube::Cube< D >::template ElementNum< K >() ][ HyperCube::Cube< D >::template IncidentCubeNum< K >() ]; static unsigned int CellOffsetAntipodal[ HyperCube::Cube< D >::template ElementNum< K >() ]; static typename HyperCube::Cube< D >::template IncidentCubeIndex< K > IncidentCube[ HyperCube::Cube< D >::template ElementNum< K >() ]; static typename HyperCube::Direction Directions[ HyperCube::Cube< D >::template ElementNum< K >() ][ D ]; static void SetTables( void ) { for( typename HyperCube::Cube< D >::template Element< K > e ; e<HyperCube::Cube< D >::template ElementNum< K >() ; e++ ) { for( typename HyperCube::Cube< D >::template IncidentCubeIndex< K > i ; i<HyperCube::Cube< D >::template IncidentCubeNum< K >() ; i++ ) { CellOffset[e.index][i.index] = HyperCube::Cube< D >::CellOffset( e , i ); IncidentElementCoIndex[e.index][i.index] = HyperCube::Cube< D >::IncidentElement( e , i ).coIndex(); } CellOffsetAntipodal[e.index] = HyperCube::Cube< D >::CellOffset( e , HyperCube::Cube< D >::IncidentCube( e ).antipodal() ); IncidentCube[ e.index ] = HyperCube::Cube< D >::IncidentCube( e ); e.directions( Directions[e.index] ); } } }; template< unsigned int D , unsigned int K1 , unsigned int K2 > struct HyperCubeTables< D , K1 , K2 > { static typename HyperCube::Cube< D >::template Element< K2 > OverlapElements[ HyperCube::Cube< D >::template ElementNum< K1 >() ][ HyperCube::Cube< D >::template OverlapElementNum< K1 , K2 >() ]; static bool Overlap[ HyperCube::Cube< D >::template ElementNum< K1 >() ][ HyperCube::Cube< D >::template ElementNum< K2 >() ]; static void SetTables( void ) { for( typename HyperCube::Cube< D >::template Element< K1 > e ; e<HyperCube::Cube< D >::template ElementNum< K1 >() ; e++ ) { for( typename HyperCube::Cube< D >::template Element< K2 > _e ; _e<HyperCube::Cube< D >::template ElementNum< K2 >() ; _e++ ) Overlap[e.index][_e.index] = HyperCube::Cube< D >::Overlap( e , _e ); HyperCube::Cube< D >::OverlapElements( e , OverlapElements[e.index] ); } if( !K2 ) HyperCubeTables< D , K1 >::SetTables(); } }; template< unsigned int D=Dim , unsigned int K1=Dim , unsigned int K2=Dim > static typename std::enable_if< K2!=0 >::type SetHyperCubeTables( void ) { HyperCubeTables< D , K1 , K2 >::SetTables() ; SetHyperCubeTables< D , K1 , K2-1 >(); } template< unsigned int D=Dim , unsigned int K1=Dim , unsigned int K2=Dim > static typename std::enable_if< K1!=0 && K2==0 >::type SetHyperCubeTables( void ) { HyperCubeTables< D , K1 , K2 >::SetTables(); SetHyperCubeTables< D , K1-1 , D >(); } template< unsigned int D=Dim , unsigned int K1=Dim , unsigned int K2=Dim > static typename std::enable_if< D!=1 && K1==0 && K2==0 >::type SetHyperCubeTables( void ) { HyperCubeTables< D , K1 , K2 >::SetTables() ; SetHyperCubeTables< D-1 , D-1 , D-1 >(); } template< unsigned int D=Dim , unsigned int K1=Dim , unsigned int K2=Dim > static typename std::enable_if< D==1 && K1==0 && K2==0 >::type SetHyperCubeTables( void ) { HyperCubeTables< D , K1 , K2 >::SetTables(); } static void SetSliceTableData( const SortedTreeNodes< Dim >& sNodes , SliceTableData* sData0 , XSliceTableData* xData , SliceTableData* sData1 , int depth , int offset ) { // [NOTE] This is structure is purely for determining adjacency and is independent of the FEM degree typedef typename FEMTree< Dim , Real >::ConstOneRingNeighborKey ConstOneRingNeighborKey; if( offset<0 || offset>((size_t)1<<depth) ) return; if( sData0 ) { std::pair< node_index_type , node_index_type > span( sNodes.begin( depth , offset-1 ) , sNodes.end( depth , offset ) ); sData0->nodeOffset = span.first , sData0->nodeCount = span.second - span.first; } if( sData1 ) { std::pair< node_index_type , node_index_type > span( sNodes.begin( depth , offset ) , sNodes.end( depth , offset+1 ) ); sData1->nodeOffset = span.first , sData1->nodeCount = span.second - span.first; } if( xData ) { std::pair< node_index_type , node_index_type > span( sNodes.begin( depth , offset ) , sNodes.end( depth , offset ) ); xData->nodeOffset = span.first , xData->nodeCount = span.second - span.first; } SliceTableData* sData[] = { sData0 , sData1 }; for( int i=0 ; i<2 ; i++ ) if( sData[i] ) { if( sData[i]->nodeCount>sData[i]->_oldNodeCount ) { DeletePointer( sData[i]->_cMap ) ; DeletePointer( sData[i]->_eMap ) ; DeletePointer( sData[i]->_fMap ); DeletePointer( sData[i]->cTable ) ; DeletePointer( sData[i]->eTable ) ; DeletePointer( sData[i]->fTable ); DeletePointer( sData[i]->_processed ); sData[i]->_cMap = NewPointer< node_index_type >( sData[i]->nodeCount * HyperCube::Cube< Dim-1 >::template ElementNum< 0 >() ); sData[i]->_eMap = NewPointer< node_index_type >( sData[i]->nodeCount * HyperCube::Cube< Dim-1 >::template ElementNum< 1 >() ); sData[i]->_fMap = NewPointer< node_index_type >( sData[i]->nodeCount * HyperCube::Cube< Dim-1 >::template ElementNum< 2 >() ); sData[i]->_processed = NewPointer< char >( sData[i]->nodeCount ); sData[i]->cTable = NewPointer< typename SliceData::SquareCornerIndices >( sData[i]->nodeCount ); sData[i]->eTable = NewPointer< typename SliceData::SquareEdgeIndices >( sData[i]->nodeCount ); sData[i]->fTable = NewPointer< typename SliceData::SquareFaceIndices >( sData[i]->nodeCount ); sData[i]->_oldNodeCount = sData[i]->nodeCount; } memset( sData[i]->_cMap , 0 , sizeof(node_index_type) * sData[i]->nodeCount * HyperCube::Cube< Dim-1 >::template ElementNum< 0 >() ); memset( sData[i]->_eMap , 0 , sizeof(node_index_type) * sData[i]->nodeCount * HyperCube::Cube< Dim-1 >::template ElementNum< 1 >() ); memset( sData[i]->_fMap , 0 , sizeof(node_index_type) * sData[i]->nodeCount * HyperCube::Cube< Dim-1 >::template ElementNum< 2 >() ); memset( sData[i]->_processed , 0 , sizeof(char) * sData[i]->nodeCount ); } if( xData ) { if( xData->nodeCount>xData->_oldNodeCount ) { DeletePointer( xData->_eMap ) ; DeletePointer( xData->_fMap ); DeletePointer( xData->eTable ) ; DeletePointer( xData->fTable ); xData->_eMap = NewPointer< node_index_type >( xData->nodeCount * HyperCube::Cube< Dim-1 >::template ElementNum< 0 >() ); xData->_fMap = NewPointer< node_index_type >( xData->nodeCount * HyperCube::Cube< Dim-1 >::template ElementNum< 1 >() ); xData->eTable = NewPointer< typename SliceData::SquareCornerIndices >( xData->nodeCount ); xData->fTable = NewPointer< typename SliceData::SquareEdgeIndices >( xData->nodeCount ); xData->_oldNodeCount = xData->nodeCount; } memset( xData->_eMap , 0 , sizeof(node_index_type) * xData->nodeCount * HyperCube::Cube< Dim-1 >::template ElementNum< 0 >() ); memset( xData->_fMap , 0 , sizeof(node_index_type) * xData->nodeCount * HyperCube::Cube< Dim-1 >::template ElementNum< 1 >() ); } std::vector< ConstOneRingNeighborKey > neighborKeys( ThreadPool::NumThreads() ); for( size_t i=0 ; i<neighborKeys.size() ; i++ ) neighborKeys[i].set( depth ); typedef typename FEMTree< Dim , Real >::ConstOneRingNeighbors ConstNeighbors; // Process the corners // z: which side of the cell \in {0,1} // zOff: which neighbor \in {-1,0,1} auto ProcessCorners = []( SliceTableData& sData , const ConstNeighbors& neighbors , HyperCube::Direction zDir , int zOff ) { const TreeOctNode* node = neighbors.neighbors[1][1][1+zOff]; node_index_type i = node->nodeData.nodeIndex; // Iterate over the corners in the face for( typename HyperCube::Cube< Dim-1 >::template Element< 0 > _c ; _c<HyperCube::Cube< Dim-1 >::template ElementNum< 0 >() ; _c++ ) { bool owner = true; typename HyperCube::Cube< Dim >::template Element< 0 > c( zDir , _c.index ); // Corner-in-cube index typename HyperCube::Cube< Dim >::template IncidentCubeIndex< 0 > my_ic = HyperCubeTables< Dim , 0 >::IncidentCube[c.index]; // The index of the node relative to the corner for( typename HyperCube::Cube< Dim >::template IncidentCubeIndex< 0 > ic ; ic<HyperCube::Cube< Dim >::template IncidentCubeNum< 0 >() ; ic++ ) // Iterate over the nodes adjacent to the corner { // Get the index of cube relative to the corner neighbors unsigned int xx = HyperCubeTables< Dim , 0 >::CellOffset[c.index][ic.index] + zOff; // If the neighbor exists and comes before, they own the corner if( neighbors.neighbors.data[xx] && ic<my_ic ){ owner = false ; break; } } if( owner ) { node_index_type myCount = ( i-sData.nodeOffset ) * HyperCube::Cube< Dim-1 >::template ElementNum< 0 >() + _c.index; sData._cMap[ myCount ] = 1; // Set the corner pointer for all cubes incident on the corner for( typename HyperCube::Cube< Dim >::template IncidentCubeIndex< 0 > ic ; ic<HyperCube::Cube< Dim >::template IncidentCubeNum< 0 >() ; ic++ ) // Iterate over the nodes adjacent to the corner { unsigned int xx = HyperCubeTables< Dim , 0 >::CellOffset[c.index][ic.index] + zOff; // If the neighbor exits, sets its corner if( neighbors.neighbors.data[xx] ) sData.cornerIndices( neighbors.neighbors.data[xx] )[ HyperCubeTables< Dim , 0 >::IncidentElementCoIndex[c.index][ic.index] ] = myCount; } } } }; // Process the in-plane edges auto ProcessIEdges = []( SliceTableData& sData , const ConstNeighbors& neighbors , HyperCube::Direction zDir , int zOff ) { const TreeOctNode* node = neighbors.neighbors[1][1][1+zOff]; node_index_type i = node->nodeData.nodeIndex; // Iterate over the edges in the face for( typename HyperCube::Cube< Dim-1 >::template Element< 1 > _e ; _e<HyperCube::Cube< Dim-1 >::template ElementNum< 1 >() ; _e++ ) { bool owner = true; // The edge in the cube typename HyperCube::Cube< Dim >::template Element< 1 > e( zDir , _e.index ); // The index of the cube relative to the edge typename HyperCube::Cube< Dim >::template IncidentCubeIndex< 1 > my_ic = HyperCubeTables< Dim , 1 >::IncidentCube[e.index]; // Iterate over the cubes incident on the edge for( typename HyperCube::Cube< Dim >::template IncidentCubeIndex< 1 > ic ; ic<HyperCube::Cube< Dim >::template IncidentCubeNum< 1 >() ; ic++ ) { // Get the indices of the cube relative to the center unsigned int xx = HyperCubeTables< Dim , 1 >::CellOffset[e.index][ic.index] + zOff; // If the neighbor exists and comes before, they own the corner if( neighbors.neighbors.data[xx] && ic<my_ic ){ owner = false ; break; } } if( owner ) { node_index_type myCount = ( i - sData.nodeOffset ) * HyperCube::Cube< Dim-1 >::template ElementNum< 1 >() + _e.index; sData._eMap[ myCount ] = 1; // Set all edge indices for( typename HyperCube::Cube< Dim >::template IncidentCubeIndex< 1 > ic ; ic<HyperCube::Cube< Dim >::template IncidentCubeNum< 1 >() ; ic++ ) { unsigned int xx = HyperCubeTables< Dim , 1 >::CellOffset[e.index][ic.index] + zOff; // If the neighbor exists, set the index if( neighbors.neighbors.data[xx] ) sData.edgeIndices( neighbors.neighbors.data[xx] )[ HyperCubeTables< Dim , 1 >::IncidentElementCoIndex[e.index][ic.index] ] = myCount; } } } }; // Process the cross-plane edges auto ProcessXEdges = []( XSliceTableData& xData , const ConstNeighbors& neighbors ) { const TreeOctNode* node = neighbors.neighbors[1][1][1]; node_index_type i = node->nodeData.nodeIndex; for( typename HyperCube::Cube< Dim-1 >::template Element< 0 > _c ; _c<HyperCube::Cube< Dim-1 >::template ElementNum< 0 >() ; _c++ ) { bool owner = true; typename HyperCube::Cube< Dim >::template Element< 1 > e( HyperCube::CROSS , _c.index ); typename HyperCube::Cube< Dim >::template IncidentCubeIndex< 1 > my_ic = HyperCubeTables< Dim , 1 >::IncidentCube[e.index]; for( typename HyperCube::Cube< Dim >::template IncidentCubeIndex< 1 > ic ; ic<HyperCube::Cube< Dim >::template IncidentCubeNum< 1 >() ; ic++ ) { unsigned int xx = HyperCubeTables< Dim , 1 >::CellOffset[e.index][ic.index]; if( neighbors.neighbors.data[xx] && ic<my_ic ){ owner = false ; break; } } if( owner ) { node_index_type myCount = ( i - xData.nodeOffset ) * HyperCube::Cube< Dim-1 >::template ElementNum< 0 >() + _c.index; xData._eMap[ myCount ] = 1; // Set all edge indices for( typename HyperCube::Cube< Dim >::template IncidentCubeIndex< 1 > ic ; ic<HyperCube::Cube< Dim >::template IncidentCubeNum< 1 >() ; ic++ ) { unsigned int xx = HyperCubeTables< Dim , 1 >::CellOffset[e.index][ic.index]; if( neighbors.neighbors.data[xx] ) xData.edgeIndices( neighbors.neighbors.data[xx] )[ HyperCubeTables< Dim , 1 >::IncidentElementCoIndex[e.index][ic.index] ] = myCount; } } } }; // Process the in-plane faces auto ProcessIFaces = []( SliceTableData& sData , const ConstNeighbors& neighbors , HyperCube::Direction zDir , int zOff ) { const TreeOctNode* node = neighbors.neighbors[1][1][1+zOff]; node_index_type i = node->nodeData.nodeIndex; for( typename HyperCube::Cube< Dim-1 >::template Element< 2 > _f ; _f<HyperCube::Cube< Dim-1 >::template ElementNum< 2 >() ; _f++ ) { bool owner = true; typename HyperCube::Cube< Dim >::template Element< 2 > f( zDir , _f.index ); typename HyperCube::Cube< Dim >::template IncidentCubeIndex< 2 > my_ic = HyperCubeTables< Dim , 2 >::IncidentCube[f.index]; for( typename HyperCube::Cube< Dim >::template IncidentCubeIndex< 2 > ic ; ic<HyperCube::Cube< Dim >::template IncidentCubeNum< 2 >() ; ic++ ) { unsigned int xx = HyperCubeTables< Dim , 2 >::CellOffset[f.index][ic.index] + zOff; if( neighbors.neighbors.data[xx] && ic<my_ic ){ owner = false ; break; } } if( owner ) { node_index_type myCount = ( i - sData.nodeOffset ) * HyperCube::Cube< Dim-1 >::template ElementNum< 2 >() + _f.index; sData._fMap[ myCount ] = 1; // Set all the face indices for( typename HyperCube::Cube< Dim >::template IncidentCubeIndex< 2 > ic ; ic<HyperCube::Cube< Dim >::template IncidentCubeNum< 2 >() ; ic++ ) { unsigned int xx = HyperCubeTables< Dim , 2 >::CellOffset[f.index][ic.index] + zOff; if( neighbors.neighbors.data[xx] ) sData.faceIndices( neighbors.neighbors.data[xx] )[ HyperCubeTables< Dim , 2 >::IncidentElementCoIndex[f.index][ic.index] ] = myCount; } } } }; // Process the cross-plane faces auto ProcessXFaces = []( XSliceTableData& xData , const ConstNeighbors& neighbors ) { const TreeOctNode* node = neighbors.neighbors[1][1][1]; node_index_type i = node->nodeData.nodeIndex; for( typename HyperCube::Cube< Dim-1 >::template Element< 1 > _e ; _e<HyperCube::Cube< Dim-1 >::template ElementNum< 1 >() ; _e++ ) { bool owner = true; typename HyperCube::Cube< Dim >::template Element< 2 > f( HyperCube::CROSS , _e.index ); typename HyperCube::Cube< Dim >::template IncidentCubeIndex< 2 > my_ic = HyperCubeTables< Dim , 2 >::IncidentCube[f.index]; for( typename HyperCube::Cube< Dim >::template IncidentCubeIndex< 2 > ic ; ic<HyperCube::Cube< Dim >::template IncidentCubeNum< 2 >() ; ic++ ) { unsigned int xx = HyperCubeTables< Dim , 2 >::CellOffset[f.index][ic.index]; if( neighbors.neighbors.data[xx] && ic<my_ic ){ owner = false ; break; } } if( owner ) { node_index_type myCount = ( i - xData.nodeOffset ) * HyperCube::Cube< Dim-1 >::template ElementNum< 1 >() + _e.index; xData._fMap[ myCount ] = 1; // Set all the face indices for( typename HyperCube::Cube< Dim >::template IncidentCubeIndex< 2 > ic ; ic<HyperCube::Cube< Dim >::template IncidentCubeNum< 2 >() ; ic++ ) { unsigned int xx = HyperCubeTables< Dim , 2 >::CellOffset[f.index][ic.index]; if( neighbors.neighbors.data[xx] ) xData.faceIndices( neighbors.neighbors.data[xx] )[ HyperCubeTables< Dim , 2 >::IncidentElementCoIndex[f.index][ic.index] ] = myCount; } } } }; // Try and get at the nodes outside of the slab through the neighbor key ThreadPool::Parallel_for( sNodes.begin(depth,offset) , sNodes.end(depth,offset) , [&]( unsigned int thread , size_t i ) { ConstOneRingNeighborKey& neighborKey = neighborKeys[ thread ]; const TreeOctNode* node = sNodes.treeNodes[i]; ConstNeighbors& neighbors = neighborKey.getNeighbors( node ); for( int i=0 ; i<3 ; i++ ) for( int j=0 ; j<3 ; j++ ) for( int k=0 ; k<3 ; k++ ) if( !IsActiveNode< Dim >( neighbors.neighbors[i][j][k] ) ) neighbors.neighbors[i][j][k] = NULL; if( sData0 ) { ProcessCorners( *sData0 , neighbors , HyperCube::BACK , 0 ) , ProcessIEdges( *sData0 , neighbors , HyperCube::BACK , 0 ) , ProcessIFaces( *sData0 , neighbors , HyperCube::BACK , 0 ); const TreeOctNode* _node = neighbors.neighbors[1][1][0]; if( _node ) { ProcessCorners( *sData0 , neighbors , HyperCube::FRONT , -1 ) , ProcessIEdges( *sData0 , neighbors , HyperCube::FRONT , -1 ) , ProcessIFaces( *sData0 , neighbors , HyperCube::FRONT , -1 ); sData0->_processed[ _node->nodeData.nodeIndex - sNodes.begin(depth,offset-1) ] = 1; } } if( sData1 ) { ProcessCorners( *sData1 , neighbors , HyperCube::FRONT , 0 ) , ProcessIEdges( *sData1 , neighbors , HyperCube::FRONT , 0 ) , ProcessIFaces( *sData1 , neighbors , HyperCube::FRONT , 0 ); const TreeOctNode* _node = neighbors.neighbors[1][1][2]; if( _node ) { ProcessCorners( *sData1 , neighbors , HyperCube::BACK , 1 ) , ProcessIEdges( *sData1 , neighbors , HyperCube::BACK , 1 ) , ProcessIFaces( *sData1, neighbors , HyperCube::BACK , 1 ); sData1->_processed[ _node->nodeData.nodeIndex - sNodes.begin(depth,offset+1) ] = true; } } if( xData ) ProcessXEdges( *xData , neighbors ) , ProcessXFaces( *xData , neighbors ); } ); if( sData0 ) { node_index_type off = sNodes.begin(depth,offset-1); node_index_type size = sNodes.end(depth,offset-1) - sNodes.begin(depth,offset-1); ThreadPool::Parallel_for( 0 , size , [&]( unsigned int thread , size_t i ) { if( !sData0->_processed[i] ) { ConstOneRingNeighborKey& neighborKey = neighborKeys[ thread ]; const TreeOctNode* node = sNodes.treeNodes[i+off]; ConstNeighbors& neighbors = neighborKey.getNeighbors( node ); for( int i=0 ; i<3 ; i++ ) for( int j=0 ; j<3 ; j++ ) for( int k=0 ; k<3 ; k++ ) if( !IsActiveNode< Dim >( neighbors.neighbors[i][j][k] ) ) neighbors.neighbors[i][j][k] = NULL; ProcessCorners( *sData0 , neighbors , HyperCube::FRONT , 0 ) , ProcessIEdges( *sData0 , neighbors , HyperCube::FRONT , 0 ) , ProcessIFaces( *sData0 , neighbors , HyperCube::FRONT , 0 ); } } ); } if( sData1 ) { node_index_type off = sNodes.begin(depth,offset+1); node_index_type size = sNodes.end(depth,offset+1) - sNodes.begin(depth,offset+1); ThreadPool::Parallel_for( 0 , size , [&]( unsigned int thread , size_t i ) { if( !sData1->_processed[i] ) { ConstOneRingNeighborKey& neighborKey = neighborKeys[ thread ]; const TreeOctNode* node = sNodes.treeNodes[i+off]; ConstNeighbors& neighbors = neighborKey.getNeighbors( node ); for( int i=0 ; i<3 ; i++ ) for( int j=0 ; j<3 ; j++ ) for( int k=0 ; k<3 ; k++ ) if( !IsActiveNode< Dim >( neighbors.neighbors[i][j][k] ) ) neighbors.neighbors[i][j][k] = NULL; ProcessCorners( *sData1 , neighbors , HyperCube::BACK , 0 ) , ProcessIEdges( *sData1 , neighbors , HyperCube::BACK , 0 ) , ProcessIFaces( *sData1 , neighbors , HyperCube::BACK , 0 ); } } ); } auto SetICounts = [&]( SliceTableData& sData ) { node_index_type cCount = 0 , eCount = 0 , fCount = 0; for( node_index_type i=0 ; i<sData.nodeCount * (node_index_type)HyperCube::Cube< Dim-1 >::template ElementNum< 0 >() ; i++ ) if( sData._cMap[i] ) sData._cMap[i] = cCount++; for( node_index_type i=0 ; i<sData.nodeCount * (node_index_type)HyperCube::Cube< Dim-1 >::template ElementNum< 1 >() ; i++ ) if( sData._eMap[i] ) sData._eMap[i] = eCount++; for( node_index_type i=0 ; i<sData.nodeCount * (node_index_type)HyperCube::Cube< Dim-1 >::template ElementNum< 2 >() ; i++ ) if( sData._fMap[i] ) sData._fMap[i] = fCount++; ThreadPool::Parallel_for( 0 , sData.nodeCount , [&]( unsigned int , size_t i ) { for( unsigned int j=0 ; j<HyperCube::Cube< Dim-1 >::template ElementNum< 0 >() ; j++ ) sData.cTable[i][j] = sData._cMap[ sData.cTable[i][j] ]; for( unsigned int j=0 ; j<HyperCube::Cube< Dim-1 >::template ElementNum< 1 >() ; j++ ) sData.eTable[i][j] = sData._eMap[ sData.eTable[i][j] ]; for( unsigned int j=0 ; j<HyperCube::Cube< Dim-1 >::template ElementNum< 2 >() ; j++ ) sData.fTable[i][j] = sData._fMap[ sData.fTable[i][j] ]; } ); sData.cCount = cCount , sData.eCount = eCount , sData.fCount = fCount; }; auto SetXCounts = [&]( XSliceTableData& xData ) { node_index_type eCount = 0 , fCount = 0; for( node_index_type i=0 ; i<xData.nodeCount * (node_index_type)HyperCube::Cube< Dim-1 >::template ElementNum< 0 >() ; i++ ) if( xData._eMap[i] ) xData._eMap[i] = eCount++; for( node_index_type i=0 ; i<xData.nodeCount * (node_index_type)HyperCube::Cube< Dim-1 >::template ElementNum< 1 >() ; i++ ) if( xData._fMap[i] ) xData._fMap[i] = fCount++; ThreadPool::Parallel_for( 0 , xData.nodeCount , [&]( unsigned int , size_t i ) { for( unsigned int j=0 ; j<HyperCube::Cube< Dim-1 >::template ElementNum< 0 >() ; j++ ) xData.eTable[i][j] = xData._eMap[ xData.eTable[i][j] ]; for( unsigned int j=0 ; j<HyperCube::Cube< Dim-1 >::template ElementNum< 1 >() ; j++ ) xData.fTable[i][j] = xData._fMap[ xData.fTable[i][j] ]; } ); xData.eCount = eCount , xData.fCount = fCount; }; if( sData0 ) SetICounts( *sData0 ); if( sData1 ) SetICounts( *sData1 ); if( xData ) SetXCounts( *xData ); } }; ////////////////// // _SliceValues // ////////////////// struct _SliceValues { typename SliceData::SliceTableData sliceData; Pointer( Real ) cornerValues ; Pointer( Point< Real , Dim > ) cornerGradients ; Pointer( char ) cornerSet; Pointer( _Key ) edgeKeys ; Pointer( char ) edgeSet; Pointer( _FaceEdges ) faceEdges ; Pointer( char ) faceSet; Pointer( char ) mcIndices; std::unordered_map< _Key , std::vector< _IsoEdge > , typename _Key::Hasher > faceEdgeMap; std::unordered_map< _Key , std::pair< node_index_type, Vertex > , typename _Key::Hasher > edgeVertexMap; std::unordered_map< _Key , _Key , typename _Key::Hasher > vertexPairMap; std::vector< std::vector< std::pair< _Key , std::vector< _IsoEdge > > > > faceEdgeKeyValues; std::vector< std::vector< std::pair< _Key , std::pair< node_index_type , Vertex > > > > edgeVertexKeyValues; std::vector< std::vector< std::pair< _Key , _Key > > > vertexPairKeyValues; _SliceValues( void ) { _oldCCount = _oldECount = _oldFCount = 0; _oldNCount = 0; cornerValues = NullPointer( Real ) ; cornerGradients = NullPointer( Point< Real , Dim > ) ; cornerSet = NullPointer( char ); edgeKeys = NullPointer( _Key ) ; edgeSet = NullPointer( char ); faceEdges = NullPointer( _FaceEdges ) ; faceSet = NullPointer( char ); mcIndices = NullPointer( char ); edgeVertexKeyValues.resize( ThreadPool::NumThreads() ); vertexPairKeyValues.resize( ThreadPool::NumThreads() ); faceEdgeKeyValues.resize( ThreadPool::NumThreads() ); } ~_SliceValues( void ) { _oldCCount = _oldECount = _oldFCount = 0; _oldNCount = 0; FreePointer( cornerValues ) ; FreePointer( cornerGradients ) ; FreePointer( cornerSet ); FreePointer( edgeKeys ) ; FreePointer( edgeSet ); FreePointer( faceEdges ) ; FreePointer( faceSet ); FreePointer( mcIndices ); } void setEdgeVertexMap( void ) { for( node_index_type i=0 ; i<(node_index_type)edgeVertexKeyValues.size() ; i++ ) { for( int j=0 ; j<edgeVertexKeyValues[i].size() ; j++ ) edgeVertexMap[ edgeVertexKeyValues[i][j].first ] = edgeVertexKeyValues[i][j].second; edgeVertexKeyValues[i].clear(); } } void setVertexPairMap( void ) { for( node_index_type i=0 ; i<(node_index_type)vertexPairKeyValues.size() ; i++ ) { for( int j=0 ; j<vertexPairKeyValues[i].size() ; j++ ) { vertexPairMap[ vertexPairKeyValues[i][j].first ] = vertexPairKeyValues[i][j].second; vertexPairMap[ vertexPairKeyValues[i][j].second ] = vertexPairKeyValues[i][j].first; } vertexPairKeyValues[i].clear(); } } void setFaceEdgeMap( void ) { for( node_index_type i=0 ; i<(node_index_type)faceEdgeKeyValues.size() ; i++ ) { for( int j=0 ; j<faceEdgeKeyValues[i].size() ; j++ ) { auto iter = faceEdgeMap.find( faceEdgeKeyValues[i][j].first ); if( iter==faceEdgeMap.end() ) faceEdgeMap[ faceEdgeKeyValues[i][j].first ] = faceEdgeKeyValues[i][j].second; else for( int k=0 ; k<faceEdgeKeyValues[i][j].second.size() ; k++ ) iter->second.push_back( faceEdgeKeyValues[i][j].second[k] ); } faceEdgeKeyValues[i].clear(); } } void reset( bool nonLinearFit ) { faceEdgeMap.clear() , edgeVertexMap.clear() , vertexPairMap.clear(); for( node_index_type i=0 ; i<(node_index_type)edgeVertexKeyValues.size() ; i++ ) edgeVertexKeyValues[i].clear(); for( node_index_type i=0 ; i<(node_index_type)vertexPairKeyValues.size() ; i++ ) vertexPairKeyValues[i].clear(); for( node_index_type i=0 ; i<(node_index_type)faceEdgeKeyValues.size() ; i++ ) faceEdgeKeyValues[i].clear(); if( _oldNCount<sliceData.nodeCount ) { _oldNCount = sliceData.nodeCount; FreePointer( mcIndices ); if( sliceData.nodeCount>0 ) mcIndices = AllocPointer< char >( _oldNCount ); } if( _oldCCount<sliceData.cCount ) { _oldCCount = sliceData.cCount; FreePointer( cornerValues ) ; FreePointer( cornerGradients ) ; FreePointer( cornerSet ); if( sliceData.cCount>0 ) { cornerValues = AllocPointer< Real >( _oldCCount ); if( nonLinearFit ) cornerGradients = AllocPointer< Point< Real , Dim > >( _oldCCount ); cornerSet = AllocPointer< char >( _oldCCount ); } } if( _oldECount<sliceData.eCount ) { _oldECount = sliceData.eCount; FreePointer( edgeKeys ) ; FreePointer( edgeSet ); edgeKeys = AllocPointer< _Key >( _oldECount ); edgeSet = AllocPointer< char >( _oldECount ); } if( _oldFCount<sliceData.fCount ) { _oldFCount = sliceData.fCount; FreePointer( faceEdges ) ; FreePointer( faceSet ); faceEdges = AllocPointer< _FaceEdges >( _oldFCount ); faceSet = AllocPointer< char >( _oldFCount ); } if( sliceData.cCount>0 ) memset( cornerSet , 0 , sizeof( char ) * sliceData.cCount ); if( sliceData.eCount>0 ) memset( edgeSet , 0 , sizeof( char ) * sliceData.eCount ); if( sliceData.fCount>0 ) memset( faceSet , 0 , sizeof( char ) * sliceData.fCount ); } protected: node_index_type _oldCCount , _oldECount , _oldFCount; node_index_type _oldNCount; }; /////////////////// // _XSliceValues // /////////////////// struct _XSliceValues { typename SliceData::XSliceTableData xSliceData; Pointer( _Key ) edgeKeys ; Pointer( char ) edgeSet; Pointer( _FaceEdges ) faceEdges ; Pointer( char ) faceSet; std::unordered_map< _Key , std::vector< _IsoEdge > , typename _Key::Hasher > faceEdgeMap; std::unordered_map< _Key , std::pair< node_index_type , Vertex > , typename _Key::Hasher > edgeVertexMap; std::unordered_map< _Key , _Key , typename _Key::Hasher > vertexPairMap; std::vector< std::vector< std::pair< _Key , std::pair< node_index_type , Vertex > > > > edgeVertexKeyValues; std::vector< std::vector< std::pair< _Key , _Key > > > vertexPairKeyValues; std::vector< std::vector< std::pair< _Key , std::vector< _IsoEdge > > > > faceEdgeKeyValues; _XSliceValues( void ) { _oldECount = _oldFCount = 0; edgeKeys = NullPointer( _Key ) ; edgeSet = NullPointer( char ); faceEdges = NullPointer( _FaceEdges ) ; faceSet = NullPointer( char ); edgeVertexKeyValues.resize( ThreadPool::NumThreads() ); vertexPairKeyValues.resize( ThreadPool::NumThreads() ); faceEdgeKeyValues.resize( ThreadPool::NumThreads() ); } ~_XSliceValues( void ) { _oldECount = _oldFCount = 0; FreePointer( edgeKeys ) ; FreePointer( edgeSet ); FreePointer( faceEdges ) ; FreePointer( faceSet ); } void setEdgeVertexMap( void ) { for( node_index_type i=0 ; i<(node_index_type)edgeVertexKeyValues.size() ; i++ ) { for( int j=0 ; j<edgeVertexKeyValues[i].size() ; j++ ) edgeVertexMap[ edgeVertexKeyValues[i][j].first ] = edgeVertexKeyValues[i][j].second; edgeVertexKeyValues[i].clear(); } } void setVertexPairMap( void ) { for( node_index_type i=0 ; i<(node_index_type)vertexPairKeyValues.size() ; i++ ) { for( int j=0 ; j<vertexPairKeyValues[i].size() ; j++ ) { vertexPairMap[ vertexPairKeyValues[i][j].first ] = vertexPairKeyValues[i][j].second; vertexPairMap[ vertexPairKeyValues[i][j].second ] = vertexPairKeyValues[i][j].first; } vertexPairKeyValues[i].clear(); } } void setFaceEdgeMap( void ) { for( node_index_type i=0 ; i<(node_index_type)faceEdgeKeyValues.size() ; i++ ) { for( int j=0 ; j<faceEdgeKeyValues[i].size() ; j++ ) { auto iter = faceEdgeMap.find( faceEdgeKeyValues[i][j].first ); if( iter==faceEdgeMap.end() ) faceEdgeMap[ faceEdgeKeyValues[i][j].first ] = faceEdgeKeyValues[i][j].second; else for( int k=0 ; k<faceEdgeKeyValues[i][j].second.size() ; k++ ) iter->second.push_back( faceEdgeKeyValues[i][j].second[k] ); } faceEdgeKeyValues[i].clear(); } } void reset( void ) { faceEdgeMap.clear() , edgeVertexMap.clear() , vertexPairMap.clear(); for( node_index_type i=0 ; i<(node_index_type)edgeVertexKeyValues.size() ; i++ ) edgeVertexKeyValues[i].clear(); for( node_index_type i=0 ; i<(node_index_type)vertexPairKeyValues.size() ; i++ ) vertexPairKeyValues[i].clear(); for( node_index_type i=0 ; i<(node_index_type)faceEdgeKeyValues.size() ; i++ ) faceEdgeKeyValues[i].clear(); if( _oldECount<xSliceData.eCount ) { _oldECount = xSliceData.eCount; FreePointer( edgeKeys ) ; FreePointer( edgeSet ); edgeKeys = AllocPointer< _Key >( _oldECount ); edgeSet = AllocPointer< char >( _oldECount ); } if( _oldFCount<xSliceData.fCount ) { _oldFCount = xSliceData.fCount; FreePointer( faceEdges ) ; FreePointer( faceSet ); faceEdges = AllocPointer< _FaceEdges >( _oldFCount ); faceSet = AllocPointer< char >( _oldFCount ); } if( xSliceData.eCount>0 ) memset( edgeSet , 0 , sizeof( char ) * xSliceData.eCount ); if( xSliceData.fCount>0 ) memset( faceSet , 0 , sizeof( char ) * xSliceData.fCount ); } protected: node_index_type _oldECount , _oldFCount; }; ///////////////// // _SlabValues // ///////////////// struct _SlabValues { protected: _XSliceValues _xSliceValues[2]; _SliceValues _sliceValues[2]; public: _SliceValues& sliceValues( int idx ){ return _sliceValues[idx&1]; } const _SliceValues& sliceValues( int idx ) const { return _sliceValues[idx&1]; } _XSliceValues& xSliceValues( int idx ){ return _xSliceValues[idx&1]; } const _XSliceValues& xSliceValues( int idx ) const { return _xSliceValues[idx&1]; } }; template< unsigned int ... FEMSigs > static void _SetSliceIsoCorners( const FEMTree< Dim , Real >& tree , ConstPointer( Real ) coefficients , ConstPointer( Real ) coarseCoefficients , Real isoValue , LocalDepth depth , int slice , std::vector< _SlabValues >& slabValues , const _Evaluator< UIntPack< FEMSigs ... > , 1 >& evaluator ) { if( slice>0 ) _SetSliceIsoCorners< FEMSigs ... >( tree , coefficients , coarseCoefficients , isoValue , depth , slice , HyperCube::FRONT , slabValues , evaluator ); if( slice<(1<<depth) ) _SetSliceIsoCorners< FEMSigs ... >( tree , coefficients , coarseCoefficients , isoValue , depth , slice , HyperCube::BACK , slabValues , evaluator ); } template< unsigned int ... FEMSigs > static void _SetSliceIsoCorners( const FEMTree< Dim , Real >& tree , ConstPointer( Real ) coefficients , ConstPointer( Real ) coarseCoefficients , Real isoValue , LocalDepth depth , int slice , HyperCube::Direction zDir , std::vector< _SlabValues >& slabValues , const _Evaluator< UIntPack< FEMSigs ... > , 1 >& evaluator ) { static const unsigned int FEMDegrees[] = { FEMSignature< FEMSigs >::Degree ... }; _SliceValues& sValues = slabValues[depth].sliceValues( slice ); bool useBoundaryEvaluation = false; for( int d=0 ; d<Dim ; d++ ) if( FEMDegrees[d]==0 || ( FEMDegrees[d]==1 && sValues.cornerGradients ) ) useBoundaryEvaluation = true; std::vector< ConstPointSupportKey< UIntPack< FEMSignature< FEMSigs >::Degree ... > > > neighborKeys( ThreadPool::NumThreads() ); std::vector< ConstCornerSupportKey< UIntPack< FEMSignature< FEMSigs >::Degree ... > > > bNeighborKeys( ThreadPool::NumThreads() ); if( useBoundaryEvaluation ) for( size_t i=0 ; i<neighborKeys.size() ; i++ ) bNeighborKeys[i].set( tree._localToGlobal( depth ) ); else for( size_t i=0 ; i<neighborKeys.size() ; i++ ) neighborKeys[i].set( tree._localToGlobal( depth ) ); ThreadPool::Parallel_for( tree._sNodesBegin(depth,slice-(zDir==HyperCube::BACK ? 0 : 1)) , tree._sNodesEnd(depth,slice-(zDir==HyperCube::BACK ? 0 : 1)) , [&]( unsigned int thread , size_t i ) { if( tree._isValidSpaceNode( tree._sNodes.treeNodes[i] ) ) { Real squareValues[ HyperCube::Cube< Dim-1 >::template ElementNum< 0 >() ]; ConstPointSupportKey< UIntPack< FEMSignature< FEMSigs >::Degree ... > >& neighborKey = neighborKeys[ thread ]; ConstCornerSupportKey< UIntPack< FEMSignature< FEMSigs >::Degree ... > >& bNeighborKey = bNeighborKeys[ thread ]; TreeNode* leaf = tree._sNodes.treeNodes[i]; if( !IsActiveNode< Dim >( leaf->children ) ) { const typename SliceData::SquareCornerIndices& cIndices = sValues.sliceData.cornerIndices( leaf ); bool isInterior = tree._isInteriorlySupported( UIntPack< FEMSignature< FEMSigs >::Degree ... >() , leaf->parent ); if( useBoundaryEvaluation ) bNeighborKey.getNeighbors( leaf ); else neighborKey.getNeighbors( leaf ); for( typename HyperCube::Cube< Dim-1 >::template Element< 0 > _c ; _c<HyperCube::Cube< Dim-1 >::template ElementNum< 0 >() ; _c++ ) { typename HyperCube::Cube< Dim >::template Element< 0 > c( zDir , _c.index ); node_index_type vIndex = cIndices[_c.index]; if( !sValues.cornerSet[vIndex] ) { if( sValues.cornerGradients ) { CumulativeDerivativeValues< Real , Dim , 1 > p; if( useBoundaryEvaluation ) p = tree.template _getCornerValues< Real , 1 >( bNeighborKey , leaf , c.index , coefficients , coarseCoefficients , evaluator , tree._maxDepth , isInterior ); else p = tree.template _getCornerValues< Real , 1 >( neighborKey , leaf , c.index , coefficients , coarseCoefficients , evaluator , tree._maxDepth , isInterior ); sValues.cornerValues[vIndex] = p[0] , sValues.cornerGradients[vIndex] = Point< Real , Dim >( p[1] , p[2] , p[3] ); } else { if( useBoundaryEvaluation ) sValues.cornerValues[vIndex] = tree.template _getCornerValues< Real , 0 >( bNeighborKey , leaf , c.index , coefficients , coarseCoefficients , evaluator , tree._maxDepth , isInterior )[0]; else sValues.cornerValues[vIndex] = tree.template _getCornerValues< Real , 0 >( neighborKey , leaf , c.index , coefficients , coarseCoefficients , evaluator , tree._maxDepth , isInterior )[0]; } sValues.cornerSet[vIndex] = 1; } squareValues[_c.index] = sValues.cornerValues[ vIndex ]; TreeNode* node = leaf; LocalDepth _depth = depth; int _slice = slice; while( tree._isValidSpaceNode( node->parent ) && (node-node->parent->children)==c.index ) { node = node->parent , _depth-- , _slice >>= 1; _SliceValues& _sValues = slabValues[_depth].sliceValues( _slice ); const typename SliceData::SquareCornerIndices& _cIndices = _sValues.sliceData.cornerIndices( node ); node_index_type _vIndex = _cIndices[_c.index]; _sValues.cornerValues[_vIndex] = sValues.cornerValues[vIndex]; if( _sValues.cornerGradients ) _sValues.cornerGradients[_vIndex] = sValues.cornerGradients[vIndex]; _sValues.cornerSet[_vIndex] = 1; } } sValues.mcIndices[ i - sValues.sliceData.nodeOffset ] = HyperCube::Cube< Dim-1 >::MCIndex( squareValues , isoValue ); } } } ); } ///////////////// // _VertexData // ///////////////// class _VertexData { public: static _Key EdgeIndex( const TreeNode* node , typename HyperCube::Cube< Dim >::template Element< 1 > e , int maxDepth ) { _Key key; const HyperCube::Direction* x = SliceData::template HyperCubeTables< Dim , 1 >::Directions[ e.index ]; int d , off[Dim]; node->depthAndOffset( d , off ); for( int dd=0 ; dd<Dim ; dd++ ) { if( x[dd]==HyperCube::CROSS ) { key[(dd+0)%3] = (int)BinaryNode::CornerIndex( maxDepth+1 , d+1 , off[(dd+0)%3]<<1 , 1 ); key[(dd+1)%3] = (int)BinaryNode::CornerIndex( maxDepth+1 , d , off[(dd+1)%3] , x[(dd+1)%3]==HyperCube::BACK ? 0 : 1 ); key[(dd+2)%3] = (int)BinaryNode::CornerIndex( maxDepth+1 , d , off[(dd+2)%3] , x[(dd+2)%3]==HyperCube::BACK ? 0 : 1 ); } } return key; } static _Key FaceIndex( const TreeNode* node , typename HyperCube::Cube< Dim >::template Element< Dim-1 > f , int maxDepth ) { _Key key; const HyperCube::Direction* x = SliceData::template HyperCubeTables< Dim , 2 >::Directions[ f.index ]; int d , o[Dim]; node->depthAndOffset( d , o ); for( int dd=0 ; dd<Dim ; dd++ ) if( x[dd]==HyperCube::CROSS ) key[dd] = (int)BinaryNode::CornerIndex( maxDepth+1 , d+1 , o[dd]<<1 , 1 ); else key[dd] = (int)BinaryNode::CornerIndex( maxDepth+1 , d , o[dd] , x[dd]==HyperCube::BACK ? 0 : 1 ); return key; } }; template< unsigned int WeightDegree , typename Data , unsigned int DataSig > static void _SetSliceIsoVertices( const FEMTree< Dim , Real >& tree , typename FEMIntegrator::template PointEvaluator< IsotropicUIntPack< Dim , DataSig > , ZeroUIntPack< Dim > >* pointEvaluator , const DensityEstimator< WeightDegree >* densityWeights , const SparseNodeData< ProjectiveData< Data , Real > , IsotropicUIntPack< Dim , DataSig > >* data , Real isoValue , LocalDepth depth , int slice , node_index_type& vOffset , CoredMeshData< Vertex , node_index_type >& mesh , std::vector< _SlabValues >& slabValues , std::function< void ( Vertex& , Point< Real , Dim > , Real , Data ) > SetVertex ) { if( slice>0 ) _SetSliceIsoVertices< WeightDegree , Data , DataSig >( tree , pointEvaluator , densityWeights , data , isoValue , depth , slice , HyperCube::FRONT , vOffset , mesh , slabValues , SetVertex ); if( slice<(1<<depth) ) _SetSliceIsoVertices< WeightDegree , Data , DataSig >( tree , pointEvaluator , densityWeights , data , isoValue , depth , slice , HyperCube::BACK , vOffset , mesh , slabValues , SetVertex ); } template< unsigned int WeightDegree , typename Data , unsigned int DataSig > static void _SetSliceIsoVertices( const FEMTree< Dim , Real >& tree , typename FEMIntegrator::template PointEvaluator< IsotropicUIntPack< Dim , DataSig > , ZeroUIntPack< Dim > >* pointEvaluator , const DensityEstimator< WeightDegree >* densityWeights , const SparseNodeData< ProjectiveData< Data , Real > , IsotropicUIntPack< Dim , DataSig > >* data , Real isoValue , LocalDepth depth , int slice , HyperCube::Direction zDir , node_index_type& vOffset , CoredMeshData< Vertex , node_index_type >& mesh , std::vector< _SlabValues >& slabValues , std::function< void ( Vertex& , Point< Real , Dim > , Real , Data ) > SetVertex ) { static const unsigned int DataDegree = FEMSignature< DataSig >::Degree; _SliceValues& sValues = slabValues[depth].sliceValues( slice ); // [WARNING] In the case Degree=2, these two keys are the same, so we don't have to maintain them separately. std::vector< ConstOneRingNeighborKey > neighborKeys( ThreadPool::NumThreads() ); std::vector< ConstPointSupportKey< IsotropicUIntPack< Dim , WeightDegree > > > weightKeys( ThreadPool::NumThreads() ); std::vector< ConstPointSupportKey< IsotropicUIntPack< Dim , DataDegree > > > dataKeys( ThreadPool::NumThreads() ); for( size_t i=0 ; i<neighborKeys.size() ; i++ ) neighborKeys[i].set( tree._localToGlobal( depth ) ) , weightKeys[i].set( tree._localToGlobal( depth ) ) , dataKeys[i].set( tree._localToGlobal( depth ) ); ThreadPool::Parallel_for( tree._sNodesBegin(depth,slice-(zDir==HyperCube::BACK ? 0 : 1)) , tree._sNodesEnd(depth,slice-(zDir==HyperCube::BACK ? 0 : 1)) , [&]( unsigned int thread , size_t i ) { if( tree._isValidSpaceNode( tree._sNodes.treeNodes[i] ) ) { ConstOneRingNeighborKey& neighborKey = neighborKeys[ thread ]; ConstPointSupportKey< IsotropicUIntPack< Dim , WeightDegree > >& weightKey = weightKeys[ thread ]; ConstPointSupportKey< IsotropicUIntPack< Dim , DataDegree > >& dataKey = dataKeys[ thread ]; TreeNode* leaf = tree._sNodes.treeNodes[i]; if( !IsActiveNode< Dim >( leaf->children ) ) { node_index_type idx = (node_index_type)i - sValues.sliceData.nodeOffset; const typename SliceData::SquareEdgeIndices& eIndices = sValues.sliceData.edgeIndices( leaf ); if( HyperCube::Cube< Dim-1 >::HasMCRoots( sValues.mcIndices[idx] ) ) { neighborKey.getNeighbors( leaf ); if( densityWeights ) weightKey.getNeighbors( leaf ); if( data ) dataKey.getNeighbors( leaf ); for( typename HyperCube::Cube< Dim-1 >::template Element< 1 > _e ; _e<HyperCube::Cube< Dim-1 >::template ElementNum< 1 >() ; _e++ ) if( HyperCube::Cube< 1 >::HasMCRoots( HyperCube::Cube< Dim-1 >::ElementMCIndex( _e , sValues.mcIndices[idx] ) ) ) { typename HyperCube::Cube< Dim >::template Element< 1 > e( zDir , _e.index ); node_index_type vIndex = eIndices[_e.index]; volatile char &edgeSet = sValues.edgeSet[vIndex]; if( !edgeSet ) { Vertex vertex; _Key key = _VertexData::EdgeIndex( leaf , e , tree._localToGlobal( tree._maxDepth ) ); _GetIsoVertex< WeightDegree , Data , DataSig >( tree , pointEvaluator , densityWeights , data , isoValue , weightKey , dataKey , leaf , _e , zDir , sValues , vertex , SetVertex ); bool stillOwner = false; std::pair< node_index_type , Vertex > hashed_vertex; { std::lock_guard< std::mutex > lock( _pointInsertionMutex ); if( !edgeSet ) { mesh.addOutOfCorePoint( vertex ); edgeSet = 1; hashed_vertex = std::pair< node_index_type , Vertex >( vOffset , vertex ); sValues.edgeKeys[ vIndex ] = key; vOffset++; stillOwner = true; } } if( stillOwner ) sValues.edgeVertexKeyValues[ thread ].push_back( std::pair< _Key , std::pair< node_index_type , Vertex > >( key , hashed_vertex ) ); if( stillOwner ) { // We only need to pass the iso-vertex down if the edge it lies on is adjacent to a coarser leaf auto IsNeeded = [&]( unsigned int depth ) { bool isNeeded = false; typename HyperCube::Cube< Dim >::template IncidentCubeIndex< 1 > my_ic = SliceData::template HyperCubeTables< Dim , 1 >::IncidentCube[e.index]; for( typename HyperCube::Cube< Dim >::template IncidentCubeIndex< 1 > ic ; ic<HyperCube::Cube< Dim >::template IncidentCubeNum< 1 >() ; ic++ ) if( ic!=my_ic ) { unsigned int xx = SliceData::template HyperCubeTables< Dim , 1 >::CellOffset[e.index][ic.index]; isNeeded |= !tree._isValidSpaceNode( neighborKey.neighbors[ tree._localToGlobal( depth ) ].neighbors.data[xx] ); } return isNeeded; }; if( IsNeeded( depth ) ) { const typename HyperCube::Cube< Dim >::template Element< Dim-1 > *f = SliceData::template HyperCubeTables< Dim , 1 , Dim-1 >::OverlapElements[e.index]; for( int k=0 ; k<2 ; k++ ) { TreeNode* node = leaf; LocalDepth _depth = depth; int _slice = slice; while( tree._isValidSpaceNode( node->parent ) && SliceData::template HyperCubeTables< Dim , 2 , 0 >::Overlap[f[k].index][(unsigned int)(node-node->parent->children) ] ) { node = node->parent , _depth-- , _slice >>= 1; _SliceValues& _sValues = slabValues[_depth].sliceValues( _slice ); _sValues.edgeVertexKeyValues[ thread ].push_back( std::pair< _Key , std::pair< node_index_type , Vertex > >( key , hashed_vertex ) ); if( !IsNeeded( _depth ) ) break; } } } } } } } } } } ); } //////////////////// // Iso-Extraction // //////////////////// template< unsigned int WeightDegree , typename Data , unsigned int DataSig > static void _SetXSliceIsoVertices( const FEMTree< Dim , Real >& tree , typename FEMIntegrator::template PointEvaluator< IsotropicUIntPack< Dim , DataSig > , ZeroUIntPack< Dim > >* pointEvaluator , const DensityEstimator< WeightDegree >* densityWeights , const SparseNodeData< ProjectiveData< Data , Real > , IsotropicUIntPack< Dim , DataSig > >* data , Real isoValue , LocalDepth depth , int slab , node_index_type &vOffset , CoredMeshData< Vertex , node_index_type >& mesh , std::vector< _SlabValues >& slabValues , std::function< void ( Vertex& , Point< Real , Dim > , Real , Data ) > SetVertex ) { static const unsigned int DataDegree = FEMSignature< DataSig >::Degree; _SliceValues& bValues = slabValues[depth].sliceValues ( slab ); _SliceValues& fValues = slabValues[depth].sliceValues ( slab+1 ); _XSliceValues& xValues = slabValues[depth].xSliceValues( slab ); // [WARNING] In the case Degree=2, these two keys are the same, so we don't have to maintain them separately. std::vector< ConstOneRingNeighborKey > neighborKeys( ThreadPool::NumThreads() ); std::vector< ConstPointSupportKey< IsotropicUIntPack< Dim , WeightDegree > > > weightKeys( ThreadPool::NumThreads() ); std::vector< ConstPointSupportKey< IsotropicUIntPack< Dim , DataDegree > > > dataKeys( ThreadPool::NumThreads() ); for( size_t i=0 ; i<neighborKeys.size() ; i++ ) neighborKeys[i].set( tree._localToGlobal( depth ) ) , weightKeys[i].set( tree._localToGlobal( depth ) ) , dataKeys[i].set( tree._localToGlobal( depth ) ); ThreadPool::Parallel_for( tree._sNodesBegin(depth,slab) , tree._sNodesEnd(depth,slab) , [&]( unsigned int thread , size_t i ) { if( tree._isValidSpaceNode( tree._sNodes.treeNodes[i] ) ) { ConstOneRingNeighborKey& neighborKey = neighborKeys[ thread ]; ConstPointSupportKey< IsotropicUIntPack< Dim , WeightDegree > >& weightKey = weightKeys[ thread ]; ConstPointSupportKey< IsotropicUIntPack< Dim , DataDegree > >& dataKey = dataKeys[ thread ]; TreeNode* leaf = tree._sNodes.treeNodes[i]; if( !IsActiveNode< Dim >( leaf->children ) ) { unsigned char mcIndex = ( bValues.mcIndices[ i - bValues.sliceData.nodeOffset ] ) | ( fValues.mcIndices[ i - fValues.sliceData.nodeOffset ] )<<4; const typename SliceData::SquareCornerIndices& eIndices = xValues.xSliceData.edgeIndices( leaf ); if( HyperCube::Cube< Dim >::HasMCRoots( mcIndex ) ) { neighborKey.getNeighbors( leaf ); if( densityWeights ) weightKey.getNeighbors( leaf ); if( data ) dataKey.getNeighbors( leaf ); for( typename HyperCube::Cube< Dim-1 >::template Element< 0 > _c ; _c<HyperCube::Cube< Dim-1 >::template ElementNum< 0 >() ; _c++ ) { typename HyperCube::Cube< Dim >::template Element< 1 > e( HyperCube::CROSS , _c.index ); unsigned int _mcIndex = HyperCube::Cube< Dim >::ElementMCIndex( e , mcIndex ); if( HyperCube::Cube< 1 >::HasMCRoots( _mcIndex ) ) { node_index_type vIndex = eIndices[_c.index]; volatile char &edgeSet = xValues.edgeSet[vIndex]; if( !edgeSet ) { Vertex vertex; _Key key = _VertexData::EdgeIndex( leaf , e.index , tree._localToGlobal( tree._maxDepth ) ); _GetIsoVertex< WeightDegree , Data , DataSig >( tree , pointEvaluator , densityWeights , data , isoValue , weightKey , dataKey , leaf , _c , bValues , fValues , vertex , SetVertex ); bool stillOwner = false; std::pair< node_index_type , Vertex > hashed_vertex; { std::lock_guard< std::mutex > lock( _pointInsertionMutex ); if( !edgeSet ) { mesh.addOutOfCorePoint( vertex ); edgeSet = 1; hashed_vertex = std::pair< node_index_type , Vertex >( vOffset , vertex ); xValues.edgeKeys[ vIndex ] = key; vOffset++; stillOwner = true; } } if( stillOwner ) xValues.edgeVertexKeyValues[ thread ].push_back( std::pair< _Key , std::pair< node_index_type , Vertex > >( key , hashed_vertex ) ); if( stillOwner ) { // We only need to pass the iso-vertex down if the edge it lies on is adjacent to a coarser leaf auto IsNeeded = [&]( unsigned int depth ) { bool isNeeded = false; typename HyperCube::Cube< Dim >::template IncidentCubeIndex< 1 > my_ic = SliceData::template HyperCubeTables< Dim , 1 >::IncidentCube[e.index]; for( typename HyperCube::Cube< Dim >::template IncidentCubeIndex< 1 > ic ; ic<HyperCube::Cube< Dim >::template IncidentCubeNum< 1 >() ; ic++ ) if( ic!=my_ic ) { unsigned int xx = SliceData::template HyperCubeTables< Dim , 1 >::CellOffset[e.index][ic.index]; isNeeded |= !tree._isValidSpaceNode( neighborKey.neighbors[ tree._localToGlobal( depth ) ].neighbors.data[xx] ); } return isNeeded; }; if( IsNeeded( depth ) ) { const typename HyperCube::Cube< Dim >::template Element< Dim-1 > *f = SliceData::template HyperCubeTables< Dim , 1 , Dim-1 >::OverlapElements[e.index]; for( int k=0 ; k<2 ; k++ ) { TreeNode* node = leaf; LocalDepth _depth = depth; int _slab = slab; while( tree._isValidSpaceNode( node->parent ) && SliceData::template HyperCubeTables< Dim , 2 , 0 >::Overlap[f[k].index][(unsigned int)(node-node->parent->children) ] ) { node = node->parent , _depth-- , _slab >>= 1; _XSliceValues& _xValues = slabValues[_depth].xSliceValues( _slab ); _xValues.edgeVertexKeyValues[ thread ].push_back( std::pair< _Key , std::pair< node_index_type , Vertex > >( key , hashed_vertex ) ); if( !IsNeeded( _depth ) ) break; } } } } } } } } } } } ); } static void _CopyFinerSliceIsoEdgeKeys( const FEMTree< Dim , Real >& tree , LocalDepth depth , int slice , std::vector< _SlabValues >& slabValues ) { if( slice>0 ) _CopyFinerSliceIsoEdgeKeys( tree , depth , slice , HyperCube::FRONT , slabValues ); if( slice<(1<<depth) ) _CopyFinerSliceIsoEdgeKeys( tree , depth , slice , HyperCube::BACK , slabValues ); } static void _CopyFinerSliceIsoEdgeKeys( const FEMTree< Dim , Real >& tree , LocalDepth depth , int slice , HyperCube::Direction zDir , std::vector< _SlabValues >& slabValues ) { _SliceValues& pSliceValues = slabValues[depth ].sliceValues(slice ); _SliceValues& cSliceValues = slabValues[depth+1].sliceValues(slice<<1); typename SliceData::SliceTableData& pSliceData = pSliceValues.sliceData; typename SliceData::SliceTableData& cSliceData = cSliceValues.sliceData; ThreadPool::Parallel_for( tree._sNodesBegin(depth,slice-(zDir==HyperCube::BACK ? 0 : 1)) , tree._sNodesEnd(depth,slice-(zDir==HyperCube::BACK ? 0 : 1)) , [&]( unsigned int thread , size_t i ) { if( tree._isValidSpaceNode( tree._sNodes.treeNodes[i] ) ) if( IsActiveNode< Dim >( tree._sNodes.treeNodes[i]->children ) ) { typename SliceData::SquareEdgeIndices& pIndices = pSliceData.edgeIndices( (node_index_type)i ); // Copy the edges that overlap the coarser edges for( typename HyperCube::Cube< Dim-1 >::template Element< 1 > _e ; _e<HyperCube::Cube< Dim-1 >::template ElementNum< 1 >() ; _e++ ) { node_index_type pIndex = pIndices[_e.index]; if( !pSliceValues.edgeSet[ pIndex ] ) { typename HyperCube::Cube< Dim >::template Element< 1 > e( zDir , _e.index ); const typename HyperCube::Cube< Dim >::template Element< 0 > *c = SliceData::template HyperCubeTables< Dim , 1 , 0 >::OverlapElements[e.index]; // [SANITY CHECK] // if( tree._isValidSpaceNode( tree._sNodes.treeNodes[i]->children + c[0].index )!=tree._isValidSpaceNode( tree._sNodes.treeNodes[i]->children + c[1].index ) ) ERROR_OUT( "Finer edges should both be valid or invalid" ); if( !tree._isValidSpaceNode( tree._sNodes.treeNodes[i]->children + c[0].index ) || !tree._isValidSpaceNode( tree._sNodes.treeNodes[i]->children + c[1].index ) ) continue; node_index_type cIndex1 = cSliceData.edgeIndices( tree._sNodes.treeNodes[i]->children + c[0].index )[_e.index]; node_index_type cIndex2 = cSliceData.edgeIndices( tree._sNodes.treeNodes[i]->children + c[1].index )[_e.index]; if( cSliceValues.edgeSet[cIndex1] != cSliceValues.edgeSet[cIndex2] ) { _Key key; if( cSliceValues.edgeSet[cIndex1] ) key = cSliceValues.edgeKeys[cIndex1]; else key = cSliceValues.edgeKeys[cIndex2]; pSliceValues.edgeKeys[pIndex] = key; pSliceValues.edgeSet[pIndex] = 1; } else if( cSliceValues.edgeSet[cIndex1] && cSliceValues.edgeSet[cIndex2] ) { _Key key1 = cSliceValues.edgeKeys[cIndex1] , key2 = cSliceValues.edgeKeys[cIndex2]; pSliceValues.vertexPairKeyValues[ thread ].push_back( std::pair< _Key , _Key >( key1 , key2 ) ); const TreeNode* node = tree._sNodes.treeNodes[i]; LocalDepth _depth = depth; int _slice = slice; while( tree._isValidSpaceNode( node->parent ) && SliceData::template HyperCubeTables< Dim , 1 , 0 >::Overlap[e.index][(unsigned int)(node-node->parent->children) ] ) { node = node->parent , _depth-- , _slice >>= 1; _SliceValues& _pSliceValues = slabValues[_depth].sliceValues(_slice); _pSliceValues.vertexPairKeyValues[ thread ].push_back( std::pair< _Key , _Key >( key1 , key2 ) ); } } } } } } ); } static void _CopyFinerXSliceIsoEdgeKeys( const FEMTree< Dim , Real >& tree , LocalDepth depth , int slab , std::vector< _SlabValues>& slabValues ) { _XSliceValues& pSliceValues = slabValues[depth ].xSliceValues(slab); _XSliceValues& cSliceValues0 = slabValues[depth+1].xSliceValues( (slab<<1)|0 ); _XSliceValues& cSliceValues1 = slabValues[depth+1].xSliceValues( (slab<<1)|1 ); typename SliceData::XSliceTableData& pSliceData = pSliceValues.xSliceData; typename SliceData::XSliceTableData& cSliceData0 = cSliceValues0.xSliceData; typename SliceData::XSliceTableData& cSliceData1 = cSliceValues1.xSliceData; ThreadPool::Parallel_for( tree._sNodesBegin(depth,slab) , tree._sNodesEnd(depth,slab) , [&]( unsigned int thread , size_t i ) { if( tree._isValidSpaceNode( tree._sNodes.treeNodes[i] ) ) if( IsActiveNode< Dim >( tree._sNodes.treeNodes[i]->children ) ) { typename SliceData::SquareCornerIndices& pIndices = pSliceData.edgeIndices( (node_index_type)i ); for( typename HyperCube::Cube< Dim-1 >::template Element< 0 > _c ; _c<HyperCube::Cube< Dim-1 >::template ElementNum< 0 >() ; _c++ ) { typename HyperCube::Cube< Dim >::template Element< 1 > e( HyperCube::CROSS , _c.index ); node_index_type pIndex = pIndices[ _c.index ]; if( !pSliceValues.edgeSet[pIndex] ) { typename HyperCube::Cube< Dim >::template Element< 0 > c0( HyperCube::BACK , _c.index ) , c1( HyperCube::FRONT , _c.index ); // [SANITY CHECK] // if( tree._isValidSpaceNode( tree._sNodes.treeNodes[i]->children + c0 )!=tree._isValidSpaceNode( tree._sNodes.treeNodes[i]->children + c1 ) ) ERROR_OUT( "Finer edges should both be valid or invalid" ); if( !tree._isValidSpaceNode( tree._sNodes.treeNodes[i]->children + c0.index ) || !tree._isValidSpaceNode( tree._sNodes.treeNodes[i]->children + c1.index ) ) continue; node_index_type cIndex0 = cSliceData0.edgeIndices( tree._sNodes.treeNodes[i]->children + c0.index )[_c.index]; node_index_type cIndex1 = cSliceData1.edgeIndices( tree._sNodes.treeNodes[i]->children + c1.index )[_c.index]; // If there's one zero-crossing along the edge if( cSliceValues0.edgeSet[cIndex0] != cSliceValues1.edgeSet[cIndex1] ) { _Key key; if( cSliceValues0.edgeSet[cIndex0] ) key = cSliceValues0.edgeKeys[cIndex0]; //, vPair = cSliceValues0.edgeVertexMap.find( key )->second; else key = cSliceValues1.edgeKeys[cIndex1]; //, vPair = cSliceValues1.edgeVertexMap.find( key )->second; pSliceValues.edgeKeys[ pIndex ] = key; pSliceValues.edgeSet[ pIndex ] = 1; } // If there's are two zero-crossings along the edge else if( cSliceValues0.edgeSet[cIndex0] && cSliceValues1.edgeSet[cIndex1] ) { _Key key0 = cSliceValues0.edgeKeys[cIndex0] , key1 = cSliceValues1.edgeKeys[cIndex1]; pSliceValues.vertexPairKeyValues[ thread ].push_back( std::pair< _Key , _Key >( key0 , key1 ) ); const TreeNode* node = tree._sNodes.treeNodes[i]; LocalDepth _depth = depth; int _slab = slab; while( tree._isValidSpaceNode( node->parent ) && SliceData::template HyperCubeTables< Dim , 1 , 0 >::Overlap[e.index][(unsigned int)(node-node->parent->children) ] ) { node = node->parent , _depth-- , _slab>>= 1; _SliceValues& _pSliceValues = slabValues[_depth].sliceValues(_slab); _pSliceValues.vertexPairKeyValues[ thread ].push_back( std::pair< _Key , _Key >( key0 , key1 ) ); } } } } } } ); } static void _SetSliceIsoEdges( const FEMTree< Dim , Real >& tree , LocalDepth depth , int slice , std::vector< _SlabValues >& slabValues ) { if( slice>0 ) _SetSliceIsoEdges( tree , depth , slice , HyperCube::FRONT , slabValues ); if( slice<(1<<depth) ) _SetSliceIsoEdges( tree , depth , slice , HyperCube::BACK , slabValues ); } static void _SetSliceIsoEdges( const FEMTree< Dim , Real >& tree , LocalDepth depth , int slice , HyperCube::Direction zDir , std::vector< _SlabValues >& slabValues ) { _SliceValues& sValues = slabValues[depth].sliceValues( slice ); std::vector< ConstOneRingNeighborKey > neighborKeys( ThreadPool::NumThreads() ); for( size_t i=0 ; i<neighborKeys.size() ; i++ ) neighborKeys[i].set( tree._localToGlobal( depth ) ); ThreadPool::Parallel_for( tree._sNodesBegin(depth, slice-(zDir==HyperCube::BACK ? 0 : 1)) , tree._sNodesEnd(depth,slice-(zDir==HyperCube::BACK ? 0 : 1)) , [&]( unsigned int thread , size_t i ) { if( tree._isValidSpaceNode( tree._sNodes.treeNodes[i] ) ) { int isoEdges[ 2 * HyperCube::MarchingSquares::MAX_EDGES ]; ConstOneRingNeighborKey& neighborKey = neighborKeys[ thread ]; TreeNode* leaf = tree._sNodes.treeNodes[i]; if( !IsActiveNode< Dim >( leaf->children ) ) { node_index_type idx = (node_index_type)i - sValues.sliceData.nodeOffset; const typename SliceData::SquareEdgeIndices& eIndices = sValues.sliceData.edgeIndices( leaf ); const typename SliceData::SquareFaceIndices& fIndices = sValues.sliceData.faceIndices( leaf ); unsigned char mcIndex = sValues.mcIndices[idx]; if( !sValues.faceSet[ fIndices[0] ] ) { neighborKey.getNeighbors( leaf ); unsigned int xx = WindowIndex< IsotropicUIntPack< Dim , 3 > , IsotropicUIntPack< Dim , 1 > >::Index + (zDir==HyperCube::BACK ? -1 : 1); if( !IsActiveNode< Dim >( neighborKey.neighbors[ tree._localToGlobal( depth ) ].neighbors.data[xx] ) || !IsActiveNode< Dim >( neighborKey.neighbors[ tree._localToGlobal( depth ) ].neighbors.data[xx]->children ) ) { _FaceEdges fe; fe.count = HyperCube::MarchingSquares::AddEdgeIndices( mcIndex , isoEdges ); for( int j=0 ; j<fe.count ; j++ ) for( int k=0 ; k<2 ; k++ ) { if( !sValues.edgeSet[ eIndices[ isoEdges[2*j+k] ] ] ) ERROR_OUT( "Edge not set: " , slice , " / " , 1<<depth ); fe.edges[j][k] = sValues.edgeKeys[ eIndices[ isoEdges[2*j+k] ] ]; } sValues.faceSet[ fIndices[0] ] = 1; sValues.faceEdges[ fIndices[0] ] = fe; TreeNode* node = leaf; LocalDepth _depth = depth; int _slice = slice; typename HyperCube::Cube< Dim >::template Element< Dim-1 > f( zDir , 0 ); std::vector< _IsoEdge > edges; edges.resize( fe.count ); for( int j=0 ; j<fe.count ; j++ ) edges[j] = fe.edges[j]; while( tree._isValidSpaceNode( node->parent ) && SliceData::template HyperCubeTables< Dim , 2 , 0 >::Overlap[f.index][(unsigned int)(node-node->parent->children) ] ) { node = node->parent , _depth-- , _slice >>= 1; if( IsActiveNode< Dim >( neighborKey.neighbors[ tree._localToGlobal( _depth ) ].neighbors.data[xx] ) && IsActiveNode< Dim >( neighborKey.neighbors[ tree._localToGlobal( _depth ) ].neighbors.data[xx]->children ) ) break; _Key key = _VertexData::FaceIndex( node , f , tree._localToGlobal( tree._maxDepth ) ); _SliceValues& _sValues = slabValues[_depth].sliceValues( _slice ); _sValues.faceEdgeKeyValues[ thread ].push_back( std::pair< _Key , std::vector< _IsoEdge > >( key , edges ) ); } } } } } } ); } static void _SetXSliceIsoEdges( const FEMTree< Dim , Real >& tree , LocalDepth depth , int slab , std::vector< _SlabValues >& slabValues ) { _SliceValues& bValues = slabValues[depth].sliceValues ( slab ); _SliceValues& fValues = slabValues[depth].sliceValues ( slab+1 ); _XSliceValues& xValues = slabValues[depth].xSliceValues( slab ); std::vector< ConstOneRingNeighborKey > neighborKeys( ThreadPool::NumThreads() ); for( size_t i=0 ; i<neighborKeys.size() ; i++ ) neighborKeys[i].set( tree._localToGlobal( depth ) ); ThreadPool::Parallel_for( tree._sNodesBegin(depth,slab) , tree._sNodesEnd(depth,slab) , [&]( unsigned int thread , size_t i ) { if( tree._isValidSpaceNode( tree._sNodes.treeNodes[i] ) ) { int isoEdges[ 2 * HyperCube::MarchingSquares::MAX_EDGES ]; ConstOneRingNeighborKey& neighborKey = neighborKeys[ thread ]; TreeNode* leaf = tree._sNodes.treeNodes[i]; if( !IsActiveNode< Dim >( leaf->children ) ) { const typename SliceData::SquareCornerIndices& cIndices = xValues.xSliceData.edgeIndices( leaf ); const typename SliceData::SquareEdgeIndices& eIndices = xValues.xSliceData.faceIndices( leaf ); unsigned char mcIndex = ( bValues.mcIndices[ i - bValues.sliceData.nodeOffset ] ) | ( fValues.mcIndices[ i - fValues.sliceData.nodeOffset ]<<4 ); { neighborKey.getNeighbors( leaf ); // Iterate over the edges on the back for( typename HyperCube::Cube< Dim-1 >::template Element< 1 > _e ; _e<HyperCube::Cube< Dim-1 >::template ElementNum< 1 >() ; _e++ ) { typename HyperCube::Cube< Dim >::template Element< 2 > f( HyperCube::CROSS , _e.index ); unsigned char _mcIndex = HyperCube::Cube< Dim >::template ElementMCIndex< 2 >( f , mcIndex ); unsigned int xx = SliceData::template HyperCubeTables< Dim , 2 >::CellOffsetAntipodal[f.index]; if( !xValues.faceSet[ eIndices[_e.index] ] && ( !IsActiveNode< Dim >( neighborKey.neighbors[ tree._localToGlobal( depth ) ].neighbors.data[xx] ) || !IsActiveNode< Dim >( neighborKey.neighbors[ tree._localToGlobal( depth ) ].neighbors.data[xx]->children ) ) ) { _FaceEdges fe; fe.count = HyperCube::MarchingSquares::AddEdgeIndices( _mcIndex , isoEdges ); for( int j=0 ; j<fe.count ; j++ ) for( int k=0 ; k<2 ; k++ ) { typename HyperCube::Cube< Dim >::template Element< 1 > e( f , typename HyperCube::Cube< Dim-1 >::template Element< 1 >( isoEdges[2*j+k] ) ); HyperCube::Direction dir ; unsigned int coIndex; e.factor( dir , coIndex ); if( dir==HyperCube::CROSS ) // Cross-edge { node_index_type idx = cIndices[ coIndex ]; if( !xValues.edgeSet[ idx ] ) ERROR_OUT( "Edge not set: " , slab , " / " , 1<<depth ); fe.edges[j][k] = xValues.edgeKeys[ idx ]; } else { const _SliceValues& sValues = dir==HyperCube::BACK ? bValues : fValues; node_index_type idx = sValues.sliceData.edgeIndices((node_index_type)i)[ coIndex ]; if( !sValues.edgeSet[ idx ] ) ERROR_OUT( "Edge not set: " , slab , " / " , 1<<depth ); fe.edges[j][k] = sValues.edgeKeys[ idx ]; } } xValues.faceSet[ eIndices[_e.index] ] = 1; xValues.faceEdges[ eIndices[_e.index] ] = fe; TreeNode* node = leaf; LocalDepth _depth = depth; int _slab = slab; std::vector< _IsoEdge > edges; edges.resize( fe.count ); for( int j=0 ; j<fe.count ; j++ ) edges[j] = fe.edges[j]; while( tree._isValidSpaceNode( node->parent ) && SliceData::template HyperCubeTables< Dim , 2 , 0 >::Overlap[f.index][(unsigned int)(node-node->parent->children) ] ) { node = node->parent , _depth-- , _slab >>= 1; if( IsActiveNode< Dim >( neighborKey.neighbors[ tree._localToGlobal( _depth ) ].neighbors.data[xx] ) && IsActiveNode< Dim >( neighborKey.neighbors[ tree._localToGlobal( _depth ) ].neighbors.data[xx]->children ) ) break; _Key key = _VertexData::FaceIndex( node , f , tree._localToGlobal( tree._maxDepth ) ); _XSliceValues& _xValues = slabValues[_depth].xSliceValues( _slab ); _xValues.faceEdgeKeyValues[ thread ].push_back( std::pair< _Key , std::vector< _IsoEdge > >( key , edges ) ); } } } } } } } ); } static void _SetIsoSurface( const FEMTree< Dim , Real >& tree , LocalDepth depth , int offset , const _SliceValues& bValues , const _SliceValues& fValues , const _XSliceValues& xValues , CoredMeshData< Vertex , node_index_type >& mesh , bool polygonMesh , bool addBarycenter , node_index_type& vOffset , bool flipOrientation ) { std::vector< std::pair< node_index_type , Vertex > > polygon; std::vector< std::vector< _IsoEdge > > edgess( ThreadPool::NumThreads() ); ThreadPool::Parallel_for( tree._sNodesBegin(depth,offset) , tree._sNodesEnd(depth,offset) , [&]( unsigned int thread , size_t i ) { if( tree._isValidSpaceNode( tree._sNodes.treeNodes[i] ) ) { std::vector< _IsoEdge >& edges = edgess[ thread ]; TreeNode* leaf = tree._sNodes.treeNodes[i]; int res = 1<<depth; LocalDepth d ; LocalOffset off; tree._localDepthAndOffset( leaf , d , off ); bool inBounds = off[0]>=0 && off[0]<res && off[1]>=0 && off[1]<res && off[2]>=0 && off[2]<res; if( inBounds && !IsActiveNode< Dim >( leaf->children ) ) { edges.clear(); unsigned char mcIndex = ( bValues.mcIndices[ i - bValues.sliceData.nodeOffset ] ) | ( fValues.mcIndices[ i - fValues.sliceData.nodeOffset ]<<4 ); // [WARNING] Just because the node looks empty doesn't mean it doesn't get eges from finer neighbors { // Gather the edges from the faces (with the correct orientation) for( typename HyperCube::Cube< Dim >::template Element< Dim-1 > f ; f<HyperCube::Cube< Dim >::template ElementNum< Dim-1 >() ; f++ ) { int flip = HyperCube::Cube< Dim >::IsOriented( f ) ? 0 : 1; HyperCube::Direction fDir = f.direction(); if( fDir==HyperCube::BACK || fDir==HyperCube::FRONT ) { const _SliceValues& sValues = (fDir==HyperCube::BACK) ? bValues : fValues; node_index_type fIdx = sValues.sliceData.faceIndices((node_index_type)i)[0]; if( sValues.faceSet[fIdx] ) { const _FaceEdges& fe = sValues.faceEdges[ fIdx ]; for( int j=0 ; j<fe.count ; j++ ) edges.push_back( _IsoEdge( fe.edges[j][flip] , fe.edges[j][1-flip] ) ); } else { _Key key = _VertexData::FaceIndex( leaf , f , tree._localToGlobal( tree._maxDepth ) ); typename std::unordered_map< _Key , std::vector< _IsoEdge > , typename _Key::Hasher >::const_iterator iter = sValues.faceEdgeMap.find(key); if( iter!=sValues.faceEdgeMap.end() ) { const std::vector< _IsoEdge >& _edges = iter->second; for( size_t j=0 ; j<_edges.size() ; j++ ) edges.push_back( _IsoEdge( _edges[j][flip] , _edges[j][1-flip] ) ); } else ERROR_OUT( "Invalid faces: " , i , " " , fDir==HyperCube::BACK ? "back" : ( fDir==HyperCube::FRONT ? "front" : ( fDir==HyperCube::CROSS ? "cross" : "unknown" ) ) ); } } else { node_index_type fIdx = xValues.xSliceData.faceIndices((node_index_type)i)[ f.coIndex() ]; if( xValues.faceSet[fIdx] ) { const _FaceEdges& fe = xValues.faceEdges[ fIdx ]; for( int j=0 ; j<fe.count ; j++ ) edges.push_back( _IsoEdge( fe.edges[j][flip] , fe.edges[j][1-flip] ) ); } else { _Key key = _VertexData::FaceIndex( leaf , f , tree._localToGlobal( tree._maxDepth ) ); typename std::unordered_map< _Key , std::vector< _IsoEdge > , typename _Key::Hasher >::const_iterator iter = xValues.faceEdgeMap.find(key); if( iter!=xValues.faceEdgeMap.end() ) { const std::vector< _IsoEdge >& _edges = iter->second; for( size_t j=0 ; j<_edges.size() ; j++ ) edges.push_back( _IsoEdge( _edges[j][flip] , _edges[j][1-flip] ) ); } else ERROR_OUT( "Invalid faces: " , i , " " , fDir==HyperCube::BACK ? "back" : ( fDir==HyperCube::FRONT ? "front" : ( fDir==HyperCube::CROSS ? "cross" : "unknown" ) ) ); } } } // Get the edge loops std::vector< std::vector< _Key > > loops; while( edges.size() ) { loops.resize( loops.size()+1 ); _IsoEdge edge = edges.back(); edges.pop_back(); _Key start = edge[0] , current = edge[1]; while( current!=start ) { int idx; for( idx=0 ; idx<(int)edges.size() ; idx++ ) if( edges[idx][0]==current ) break; if( idx==edges.size() ) { typename std::unordered_map< _Key , _Key , typename _Key::Hasher >::const_iterator iter; if ( (iter=bValues.vertexPairMap.find(current))!=bValues.vertexPairMap.end() ) loops.back().push_back( current ) , current = iter->second; else if( (iter=fValues.vertexPairMap.find(current))!=fValues.vertexPairMap.end() ) loops.back().push_back( current ) , current = iter->second; else if( (iter=xValues.vertexPairMap.find(current))!=xValues.vertexPairMap.end() ) loops.back().push_back( current ) , current = iter->second; else { LocalDepth d ; LocalOffset off; tree._localDepthAndOffset( leaf , d , off ); ERROR_OUT( "Failed to close loop [" , d-1 , ": " , off[0] , " " , off[1] , " " , off[2] , "] | (" , i , "): " , current.to_string() ); } } else { loops.back().push_back( current ); current = edges[idx][1]; edges[idx] = edges.back() , edges.pop_back(); } } loops.back().push_back( start ); } // Add the loops to the mesh for( size_t j=0 ; j<loops.size() ; j++ ) { std::vector< std::pair< node_index_type , Vertex > > polygon( loops[j].size() ); for( size_t k=0 ; k<loops[j].size() ; k++ ) { _Key key = loops[j][k]; typename std::unordered_map< _Key , std::pair< node_index_type , Vertex > , typename _Key::Hasher >::const_iterator iter; size_t kk = flipOrientation ? loops[j].size()-1-k : k; if ( ( iter=bValues.edgeVertexMap.find( key ) )!=bValues.edgeVertexMap.end() ) polygon[kk] = iter->second; else if( ( iter=fValues.edgeVertexMap.find( key ) )!=fValues.edgeVertexMap.end() ) polygon[kk] = iter->second; else if( ( iter=xValues.edgeVertexMap.find( key ) )!=xValues.edgeVertexMap.end() ) polygon[kk] = iter->second; else ERROR_OUT( "Couldn't find vertex in edge map" ); } _AddIsoPolygons( thread , mesh , polygon , polygonMesh , addBarycenter , vOffset ); } } } } } ); } template< unsigned int WeightDegree , typename Data , unsigned int DataSig > static bool _GetIsoVertex( const FEMTree< Dim , Real >& tree , typename FEMIntegrator::template PointEvaluator< IsotropicUIntPack< Dim , DataSig > , ZeroUIntPack< Dim > >* pointEvaluator , const DensityEstimator< WeightDegree >* densityWeights , const SparseNodeData< ProjectiveData< Data , Real > , IsotropicUIntPack< Dim , DataSig > >* data , Real isoValue , ConstPointSupportKey< IsotropicUIntPack< Dim , WeightDegree > >& weightKey , ConstPointSupportKey< IsotropicUIntPack< Dim , FEMSignature< DataSig >::Degree > >& dataKey , const TreeNode* node , typename HyperCube::template Cube< Dim-1 >::template Element< 1 > _e , HyperCube::Direction zDir , const _SliceValues& sValues , Vertex& vertex , std::function< void ( Vertex& , Point< Real , Dim > , Real , Data ) > SetVertex ) { static const unsigned int DataDegree = FEMSignature< DataSig >::Degree; Point< Real , Dim > position; int c0 , c1; const typename HyperCube::Cube< Dim-1 >::template Element< 0 > *_c = SliceData::template HyperCubeTables< Dim-1 , 1 , 0 >::OverlapElements[_e.index]; c0 = _c[0].index , c1 = _c[1].index; bool nonLinearFit = sValues.cornerGradients!=NullPointer( Point< Real , Dim > ); const typename SliceData::SquareCornerIndices& idx = sValues.sliceData.cornerIndices( node ); Real x0 = sValues.cornerValues[idx[c0]] , x1 = sValues.cornerValues[idx[c1]]; Point< Real , Dim > s; Real start , width; tree._startAndWidth( node , s , width ); int o; { const HyperCube::Direction* dirs = SliceData::template HyperCubeTables< Dim-1 , 1 >::Directions[ _e.index ]; for( int d=0 ; d<Dim-1 ; d++ ) if( dirs[d]==HyperCube::CROSS ) { o = d; start = s[d]; for( int dd=1 ; dd<Dim-1 ; dd++ ) position[(d+dd)%(Dim-1)] = s[(d+dd)%(Dim-1)] + width * ( dirs[(d+dd)%(Dim-1)]==HyperCube::BACK ? 0 : 1 ); } } position[ Dim-1 ] = s[Dim-1] + width * ( zDir==HyperCube::BACK ? 0 : 1 ); double averageRoot; bool rootFound = false; if( nonLinearFit ) { double dx0 = sValues.cornerGradients[idx[c0]][o] * width , dx1 = sValues.cornerGradients[idx[c1]][o] * width; // The scaling will turn the Hermite Spline into a quadratic double scl = (x1-x0) / ( (dx1+dx0 ) / 2 ); dx0 *= scl , dx1 *= scl; // Hermite Spline Polynomial< 2 > P; P.coefficients[0] = x0; P.coefficients[1] = dx0; P.coefficients[2] = 3*(x1-x0)-dx1-2*dx0; double roots[2]; int rCount = 0 , rootCount = P.getSolutions( isoValue , roots , 0 ); averageRoot = 0; for( int i=0 ; i<rootCount ; i++ ) if( roots[i]>=0 && roots[i]<=1 ) averageRoot += roots[i] , rCount++; if( rCount ) rootFound = true; averageRoot /= rCount; } if( !rootFound ) { // We have a linear function L, with L(0) = x0 and L(1) = x1 // => L(t) = x0 + t * (x1-x0) // => L(t) = isoValue <=> t = ( isoValue - x0 ) / ( x1 - x0 ) if( x0==x1 ) ERROR_OUT( "Not a zero-crossing root: " , x0 , " " , x1 ); averageRoot = ( isoValue - x0 ) / ( x1 - x0 ); } if( averageRoot<=0 || averageRoot>=1 ) { _BadRootCount++; if( averageRoot<0 ) averageRoot = 0; if( averageRoot>1 ) averageRoot = 1; } position[o] = Real( start + width*averageRoot ); Real depth = (Real)1.; Data dataValue; if( densityWeights ) { Real weight; tree._getSampleDepthAndWeight( *densityWeights , node , position , weightKey , depth , weight ); } if( data ) { if( DataDegree==0 ) { Point< Real , 3 > center( s[0] + width/2 , s[1] + width/2 , s[2] + width/2 ); dataValue = tree.template _evaluate< ProjectiveData< Data , Real > , SparseNodeData< ProjectiveData< Data , Real > , IsotropicUIntPack< Dim , DataSig > > , 0 >( *data , center , *pointEvaluator , dataKey ).value(); } else dataValue = tree.template _evaluate< ProjectiveData< Data , Real > , SparseNodeData< ProjectiveData< Data , Real > , IsotropicUIntPack< Dim , DataSig > > , 0 >( *data , position , *pointEvaluator , dataKey ).value(); } SetVertex( vertex , position , depth , dataValue ); return true; } template< unsigned int WeightDegree , typename Data , unsigned int DataSig > static bool _GetIsoVertex( const FEMTree< Dim , Real >& tree , typename FEMIntegrator::template PointEvaluator< IsotropicUIntPack< Dim , DataSig > , ZeroUIntPack< Dim > >* pointEvaluator , const DensityEstimator< WeightDegree >* densityWeights , const SparseNodeData< ProjectiveData< Data , Real > , IsotropicUIntPack< Dim , DataSig > >* data , Real isoValue , ConstPointSupportKey< IsotropicUIntPack< Dim , WeightDegree > >& weightKey , ConstPointSupportKey< IsotropicUIntPack< Dim , FEMSignature< DataSig >::Degree > >& dataKey , const TreeNode* node , typename HyperCube::template Cube< Dim-1 >::template Element< 0 > _c , const _SliceValues& bValues , const _SliceValues& fValues , Vertex& vertex , std::function< void ( Vertex& , Point< Real , Dim > , Real , Data ) > SetVertex ) { static const unsigned int DataDegree = FEMSignature< DataSig >::Degree; Point< Real , Dim > position; bool nonLinearFit = bValues.cornerGradients!=NullPointer( Point< Real , Dim > ) && fValues.cornerGradients!=NullPointer( Point< Real , Dim > ); const typename SliceData::SquareCornerIndices& idx0 = bValues.sliceData.cornerIndices( node ); const typename SliceData::SquareCornerIndices& idx1 = fValues.sliceData.cornerIndices( node ); Real x0 = bValues.cornerValues[ idx0[_c.index] ] , x1 = fValues.cornerValues[ idx1[_c.index] ]; Point< Real , Dim > s; Real start , width; tree._startAndWidth( node , s , width ); start = s[2]; int x , y; { const HyperCube::Direction* xx = SliceData::template HyperCubeTables< Dim-1 , 0 >::Directions[ _c.index ]; x = xx[0]==HyperCube::BACK ? 0 : 1 , y = xx[1]==HyperCube::BACK ? 0 : 1; } position[0] = s[0] + width*x; position[1] = s[1] + width*y; double averageRoot; bool rootFound = false; if( nonLinearFit ) { double dx0 = bValues.cornerGradients[ idx0[_c.index] ][2] * width , dx1 = fValues.cornerGradients[ idx1[_c.index] ][2] * width; // The scaling will turn the Hermite Spline into a quadratic double scl = (x1-x0) / ( (dx1+dx0 ) / 2 ); dx0 *= scl , dx1 *= scl; // Hermite Spline Polynomial< 2 > P; P.coefficients[0] = x0; P.coefficients[1] = dx0; P.coefficients[2] = 3*(x1-x0)-dx1-2*dx0; double roots[2]; int rCount = 0 , rootCount = P.getSolutions( isoValue , roots , 0 ); averageRoot = 0; for( int i=0 ; i<rootCount ; i++ ) if( roots[i]>=0 && roots[i]<=1 ) averageRoot += roots[i] , rCount++; if( rCount ) rootFound = true; averageRoot /= rCount; } if( !rootFound ) { // We have a linear function L, with L(0) = x0 and L(1) = x1 // => L(t) = x0 + t * (x1-x0) // => L(t) = isoValue <=> t = ( isoValue - x0 ) / ( x1 - x0 ) if( x0==x1 ) ERROR_OUT( "Not a zero-crossing root: " , x0 , " " , x1 ); averageRoot = ( isoValue - x0 ) / ( x1 - x0 ); } if( averageRoot<=0 || averageRoot>=1 ) { _BadRootCount++; } position[2] = Real( start + width*averageRoot ); Real depth = (Real)1.; Data dataValue; if( densityWeights ) { Real weight; tree._getSampleDepthAndWeight( *densityWeights , node , position , weightKey , depth , weight ); } if( data ) { if( DataDegree==0 ) { Point< Real , 3 > center( s[0] + width/2 , s[1] + width/2 , s[2] + width/2 ); dataValue = tree.template _evaluate< ProjectiveData< Data , Real > , SparseNodeData< ProjectiveData< Data , Real > , IsotropicUIntPack< Dim , DataSig > > , 0 >( *data , center , *pointEvaluator , dataKey ).value(); } else dataValue = tree.template _evaluate< ProjectiveData< Data , Real > , SparseNodeData< ProjectiveData< Data , Real > , IsotropicUIntPack< Dim , DataSig > > , 0 >( *data , position , *pointEvaluator , dataKey ).value(); } SetVertex( vertex , position , depth , dataValue ); return true; } static unsigned int _AddIsoPolygons( unsigned int thread , CoredMeshData< Vertex , node_index_type >& mesh , std::vector< std::pair< node_index_type , Vertex > >& polygon , bool polygonMesh , bool addBarycenter , node_index_type &vOffset ) { if( polygonMesh ) { std::vector< node_index_type > vertices( polygon.size() ); for( unsigned int i=0 ; i<polygon.size() ; i++ ) vertices[i] = polygon[polygon.size()-1-i].first; mesh.addPolygon_s( thread , vertices ); return 1; } if( polygon.size()>3 ) { bool isCoplanar = false; std::vector< node_index_type > triangle( 3 ); if( addBarycenter ) for( unsigned int i=0 ; i<polygon.size() ; i++ ) for( unsigned int j=0 ; j<i ; j++ ) if( (i+1)%polygon.size()!=j && (j+1)%polygon.size()!=i ) { Vertex v1 = polygon[i].second , v2 = polygon[j].second; for( int k=0 ; k<3 ; k++ ) if( v1.point[k]==v2.point[k] ) isCoplanar = true; } if( isCoplanar ) { Vertex c; c *= 0; for( unsigned int i=0 ; i<polygon.size() ; i++ ) c += polygon[i].second; c /= ( typename Vertex::Real )polygon.size(); node_index_type cIdx; { std::lock_guard< std::mutex > lock( _pointInsertionMutex ); cIdx = mesh.addOutOfCorePoint( c ); vOffset++; } for( unsigned i=0 ; i<polygon.size() ; i++ ) { triangle[0] = polygon[ i ].first; triangle[1] = cIdx; triangle[2] = polygon[(i+1)%polygon.size()].first; mesh.addPolygon_s( thread , triangle ); } return (unsigned int)polygon.size(); } else { std::vector< Point< Real , Dim > > vertices( polygon.size() ); for( unsigned int i=0 ; i<polygon.size() ; i++ ) vertices[i] = polygon[i].second.point; std::vector< TriangleIndex< node_index_type > > triangles = MinimalAreaTriangulation< node_index_type , Real , Dim >( ( ConstPointer( Point< Real , Dim > ) )GetPointer( vertices ) , (node_index_type)vertices.size() ); if( triangles.size()!=polygon.size()-2 ) ERROR_OUT( "Minimal area triangulation failed:" , triangles.size() , " != " , polygon.size()-2 ); for( unsigned int i=0 ; i<triangles.size() ; i++ ) { for( int j=0 ; j<3 ; j++ ) triangle[2-j] = polygon[ triangles[i].idx[j] ].first; mesh.addPolygon_s( thread , triangle ); } } } else if( polygon.size()==3 ) { std::vector< node_index_type > vertices( 3 ); for( int i=0 ; i<3 ; i++ ) vertices[2-i] = polygon[i].first; mesh.addPolygon_s( thread , vertices ); } return (unsigned int)polygon.size()-2; } public: struct IsoStats { double cornersTime , verticesTime , edgesTime , surfaceTime; double copyFinerTime , setTableTime; IsoStats( void ) : cornersTime(0) , verticesTime(0) , edgesTime(0) , surfaceTime(0) , copyFinerTime(0) , setTableTime(0) {;} std::string toString( void ) const { std::stringstream stream; stream << "Corners / Vertices / Edges / Surface / Set Table / Copy Finer: "; stream << std::fixed << std::setprecision(1) << cornersTime << " / " << verticesTime << " / " << edgesTime << " / " << surfaceTime << " / " << setTableTime << " / " << copyFinerTime; stream << " (s)"; return stream.str(); } }; template< typename Data , typename SetVertexFunction , unsigned int ... FEMSigs , unsigned int WeightDegree , unsigned int DataSig > static IsoStats Extract( UIntPack< FEMSigs ... > , UIntPack< WeightDegree > , UIntPack< DataSig > , const FEMTree< Dim , Real >& tree , const DensityEstimator< WeightDegree >* densityWeights , const SparseNodeData< ProjectiveData< Data , Real > , IsotropicUIntPack< Dim , DataSig > >* data , const DenseNodeData< Real , UIntPack< FEMSigs ... > >& coefficients , Real isoValue , CoredMeshData< Vertex , node_index_type >& mesh , const SetVertexFunction &SetVertex , bool nonLinearFit , bool addBarycenter , bool polygonMesh , bool flipOrientation ) { _BadRootCount = 0u; IsoStats isoStats; static_assert( sizeof...(FEMSigs)==Dim , "[ERROR] Number of signatures should match dimension" ); tree._setFEM1ValidityFlags( UIntPack< FEMSigs ... >() ); static const unsigned int DataDegree = FEMSignature< DataSig >::Degree; static const int FEMDegrees[] = { FEMSignature< FEMSigs >::Degree ... }; for( int d=0 ; d<Dim ; d++ ) if( FEMDegrees[d]==0 && nonLinearFit ) WARN( "Constant B-Splines do not support non-linear interpolation" ) , nonLinearFit = false; SliceData::SetHyperCubeTables(); typename FEMIntegrator::template PointEvaluator< IsotropicUIntPack< Dim , DataSig > , ZeroUIntPack< Dim > >* pointEvaluator = NULL; if( data ) pointEvaluator = new typename FEMIntegrator::template PointEvaluator< IsotropicUIntPack< Dim , DataSig > , ZeroUIntPack< Dim > >( tree._maxDepth ); DenseNodeData< Real , UIntPack< FEMSigs ... > > coarseCoefficients( tree._sNodesEnd( tree._maxDepth-1 ) ); memset( coarseCoefficients() , 0 , sizeof(Real)*tree._sNodesEnd( tree._maxDepth-1 ) ); ThreadPool::Parallel_for( tree._sNodesBegin(0) , tree._sNodesEnd( tree._maxDepth-1 ) , [&]( unsigned int, size_t i ){ coarseCoefficients[i] = coefficients[i]; } ); typename FEMIntegrator::template RestrictionProlongation< UIntPack< FEMSigs ... > > rp; for( LocalDepth d=1 ; d<tree._maxDepth ; d++ ) tree._upSample( UIntPack< FEMSigs ... >() , rp , d , coarseCoefficients() ); FEMTree< Dim , Real >::MemoryUsage(); std::vector< _Evaluator< UIntPack< FEMSigs ... > , 1 > > evaluators( tree._maxDepth+1 ); for( LocalDepth d=0 ; d<=tree._maxDepth ; d++ ) evaluators[d].set( tree._maxDepth ); node_index_type vertexOffset = 0; std::vector< _SlabValues > slabValues( tree._maxDepth+1 ); // Initialize the back slice for( LocalDepth d=tree._maxDepth ; d>=0 ; d-- ) { double t = Time(); SliceData::SetSliceTableData( tree._sNodes , &slabValues[d].sliceValues(0).sliceData , &slabValues[d].xSliceValues(0).xSliceData , &slabValues[d].sliceValues(1).sliceData , tree._localToGlobal( d ) , tree._localInset( d ) ); isoStats.setTableTime += Time()-t; slabValues[d].sliceValues (0).reset( nonLinearFit ); slabValues[d].sliceValues (1).reset( nonLinearFit ); slabValues[d].xSliceValues(0).reset( ); } for( LocalDepth d=tree._maxDepth ; d>=0 ; d-- ) { // Copy edges from finer double t = Time(); if( d<tree._maxDepth ) _CopyFinerSliceIsoEdgeKeys( tree , d , 0 , slabValues ); isoStats.copyFinerTime += Time()-t , t = Time(); _SetSliceIsoCorners< FEMSigs ... >( tree , coefficients() , coarseCoefficients() , isoValue , d , 0 , slabValues , evaluators[d] ); isoStats.cornersTime += Time()-t , t = Time(); _SetSliceIsoVertices< WeightDegree , Data , DataSig >( tree , pointEvaluator , densityWeights , data , isoValue , d , 0 , vertexOffset , mesh , slabValues , SetVertex ); isoStats.verticesTime += Time()-t , t = Time(); _SetSliceIsoEdges( tree , d , 0 , slabValues ); isoStats.edgesTime += Time()-t , t = Time(); } // Iterate over the slices at the finest level for( int slice=0 ; slice<( 1<<tree._maxDepth ) ; slice++ ) { // Process at all depths that contain this slice LocalDepth d ; int o; for( d=tree._maxDepth , o=slice+1 ; d>=0 ; d-- , o>>=1 ) { // Copy edges from finer (required to ensure we correctly track edge cancellations) double t = Time(); if( d<tree._maxDepth ) { _CopyFinerSliceIsoEdgeKeys( tree , d , o , slabValues ); _CopyFinerXSliceIsoEdgeKeys( tree , d , o-1 , slabValues ); } isoStats.copyFinerTime += Time()-t , t = Time(); // Set the slice values/vertices _SetSliceIsoCorners< FEMSigs ... >( tree , coefficients() , coarseCoefficients() , isoValue , d , o , slabValues , evaluators[d] ); isoStats.cornersTime += Time()-t , t = Time(); _SetSliceIsoVertices< WeightDegree , Data , DataSig >( tree , pointEvaluator , densityWeights , data , isoValue , d , o , vertexOffset , mesh , slabValues , SetVertex ); isoStats.verticesTime += Time()-t , t = Time(); _SetSliceIsoEdges( tree , d , o , slabValues ); isoStats.edgesTime += Time()-t , t = Time(); // Set the cross-slice edges _SetXSliceIsoVertices< WeightDegree , Data , DataSig >( tree , pointEvaluator , densityWeights , data , isoValue , d , o-1 , vertexOffset , mesh , slabValues , SetVertex ); isoStats.verticesTime += Time()-t , t = Time(); _SetXSliceIsoEdges( tree , d , o-1 , slabValues ); isoStats.edgesTime += Time()-t , t = Time(); ThreadPool::ParallelSections ( [ &slabValues , d , o ]( void ){ slabValues[d]. sliceValues(o-1).setEdgeVertexMap(); } , [ &slabValues , d , o ]( void ){ slabValues[d]. sliceValues(o ).setEdgeVertexMap(); } , [ &slabValues , d , o ]( void ){ slabValues[d].xSliceValues(o-1).setEdgeVertexMap(); } , [ &slabValues , d , o ]( void ){ slabValues[d]. sliceValues(o-1).setVertexPairMap(); } , [ &slabValues , d , o ]( void ){ slabValues[d]. sliceValues(o ).setVertexPairMap(); } , [ &slabValues , d , o ]( void ){ slabValues[d].xSliceValues(o-1).setVertexPairMap(); } , [ &slabValues , d , o ]( void ){ slabValues[d]. sliceValues(o-1).setFaceEdgeMap(); } , [ &slabValues , d , o ]( void ){ slabValues[d]. sliceValues(o ).setFaceEdgeMap(); } , [ &slabValues , d , o ]( void ){ slabValues[d].xSliceValues(o-1).setFaceEdgeMap(); } ); // Add the triangles t = Time(); _SetIsoSurface( tree , d , o-1 , slabValues[d].sliceValues(o-1) , slabValues[d].sliceValues(o) , slabValues[d].xSliceValues(o-1) , mesh , polygonMesh , addBarycenter , vertexOffset , flipOrientation ); isoStats.surfaceTime += Time()-t; if( o&1 ) break; } for( d=tree._maxDepth , o=slice+1 ; d>=0 ; d-- , o>>=1 ) { // Initialize for the next pass if( o<(1<<(d+1)) ) { double t = Time(); SliceData::SetSliceTableData( tree._sNodes , NULL , &slabValues[d].xSliceValues(o).xSliceData , &slabValues[d].sliceValues(o+1).sliceData , tree._localToGlobal( d ) , o + tree._localInset( d ) ); isoStats.setTableTime += Time()-t; slabValues[d].sliceValues(o+1).reset( nonLinearFit ); slabValues[d].xSliceValues(o).reset(); } if( o&1 ) break; } } FEMTree< Dim , Real >::MemoryUsage(); if( pointEvaluator ) delete pointEvaluator; size_t badRootCount = _BadRootCount; if( badRootCount!=0 ) WARN( "bad average roots: " , badRootCount ); return isoStats; } }; template< class Real , class Vertex > std::mutex IsoSurfaceExtractor< 3 , Real , Vertex >::_pointInsertionMutex; template< class Real , class Vertex > std::atomic< size_t > IsoSurfaceExtractor< 3 , Real , Vertex >::_BadRootCount; template< class Real , class Vertex > template< unsigned int D , unsigned int K > unsigned int IsoSurfaceExtractor< 3 , Real , Vertex >::SliceData::HyperCubeTables< D , K >::CellOffset[ HyperCube::Cube< D >::template ElementNum< K >() ][ HyperCube::Cube< D >::template IncidentCubeNum< K >() ]; template< class Real , class Vertex > template< unsigned int D , unsigned int K > unsigned int IsoSurfaceExtractor< 3 , Real , Vertex >::SliceData::HyperCubeTables< D , K >::IncidentElementCoIndex[ HyperCube::Cube< D >::template ElementNum< K >() ][ HyperCube::Cube< D >::template IncidentCubeNum< K >() ]; template< class Real , class Vertex > template< unsigned int D , unsigned int K > unsigned int IsoSurfaceExtractor< 3 , Real , Vertex >::SliceData::HyperCubeTables< D , K >::CellOffsetAntipodal[ HyperCube::Cube< D >::template ElementNum< K >() ]; template< class Real , class Vertex > template< unsigned int D , unsigned int K > typename HyperCube::Cube< D >::template IncidentCubeIndex < K > IsoSurfaceExtractor< 3 , Real , Vertex >::SliceData::HyperCubeTables< D , K >::IncidentCube[ HyperCube::Cube< D >::template ElementNum< K >() ]; template< class Real , class Vertex > template< unsigned int D , unsigned int K > typename HyperCube::Direction IsoSurfaceExtractor< 3 , Real , Vertex >::SliceData::HyperCubeTables< D , K >::Directions[ HyperCube::Cube< D >::template ElementNum< K >() ][ D ]; template< class Real , class Vertex > template< unsigned int D , unsigned int K1 , unsigned int K2 > typename HyperCube::Cube< D >::template Element< K2 > IsoSurfaceExtractor< 3 , Real , Vertex >::SliceData::HyperCubeTables< D , K1 , K2 >::OverlapElements[ HyperCube::Cube< D >::template ElementNum< K1 >() ][ HyperCube::Cube< D >::template OverlapElementNum< K1 , K2 >() ]; template< class Real , class Vertex > template< unsigned int D , unsigned int K1 , unsigned int K2 > bool IsoSurfaceExtractor< 3 , Real , Vertex >::SliceData::HyperCubeTables< D , K1 , K2 >::Overlap[ HyperCube::Cube< D >::template ElementNum< K1 >() ][ HyperCube::Cube< D >::template ElementNum< K2 >() ];
103,207
42,759
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // <locale> // class time_base // { // public: // enum dateorder {no_order, dmy, mdy, ymd, ydm}; // }; #include <locale> #include <cassert> int main() { std::time_base::dateorder d = std::time_base::no_order; assert(std::time_base::no_order == 0); assert(std::time_base::dmy == 1); assert(std::time_base::mdy == 2); assert(std::time_base::ymd == 3); assert(std::time_base::ydm == 4); }
774
246
/* Copyright (c) 2013, Project OSRM contributors 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. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef API_GRAMMAR_HPP #define API_GRAMMAR_HPP #include <boost/bind.hpp> #include <boost/spirit/include/qi.hpp> #include <boost/spirit/include/qi_action.hpp> namespace qi = boost::spirit::qi; template <typename Iterator, class HandlerT> struct APIGrammar : qi::grammar<Iterator> { explicit APIGrammar(HandlerT *h) : APIGrammar::base_type(api_call), handler(h) { api_call = qi::lit('/') >> string[boost::bind(&HandlerT::setService, handler, ::_1)] >> -query; query = ('?') >> +(zoom | output | jsonp | checksum | uturns | location_with_options | destination_with_options | source_with_options | cmp | language | instruction | geometry | alt_route | old_API | num_results | matching_beta | gps_precision | classify | locs); // all combinations of timestamp, uturn, hint and bearing without duplicates t_u = (u >> -timestamp) | (timestamp >> -u); t_h = (hint >> -timestamp) | (timestamp >> -hint); u_h = (u >> -hint) | (hint >> -u); t_u_h = (hint >> -t_u) | (u >> -t_h) | (timestamp >> -u_h); location_options = (bearing >> -t_u_h) | (t_u_h >> -bearing) | // (u >> bearing >> -t_h) | (timestamp >> bearing >> -u_h) | (hint >> bearing >> t_u) | // (t_h >> bearing >> -u) | (u_h >> bearing >> -timestamp) | (t_u >> bearing >> -hint); location_with_options = location >> -location_options; source_with_options = source >> -location_options; destination_with_options = destination >> -location_options; zoom = (-qi::lit('&')) >> qi::lit('z') >> '=' >> qi::short_[boost::bind(&HandlerT::setZoomLevel, handler, ::_1)]; output = (-qi::lit('&')) >> qi::lit("output") >> '=' >> string[boost::bind(&HandlerT::setOutputFormat, handler, ::_1)]; jsonp = (-qi::lit('&')) >> qi::lit("jsonp") >> '=' >> stringwithPercent[boost::bind(&HandlerT::setJSONpParameter, handler, ::_1)]; checksum = (-qi::lit('&')) >> qi::lit("checksum") >> '=' >> qi::uint_[boost::bind(&HandlerT::setChecksum, handler, ::_1)]; instruction = (-qi::lit('&')) >> qi::lit("instructions") >> '=' >> qi::bool_[boost::bind(&HandlerT::setInstructionFlag, handler, ::_1)]; geometry = (-qi::lit('&')) >> qi::lit("geometry") >> '=' >> qi::bool_[boost::bind(&HandlerT::setGeometryFlag, handler, ::_1)]; cmp = (-qi::lit('&')) >> qi::lit("compression") >> '=' >> qi::bool_[boost::bind(&HandlerT::setCompressionFlag, handler, ::_1)]; location = (-qi::lit('&')) >> qi::lit("loc") >> '=' >> (qi::double_ >> qi::lit(',') >> qi::double_)[boost::bind(&HandlerT::addCoordinate, handler, ::_1)]; destination = (-qi::lit('&')) >> qi::lit("dst") >> '=' >> (qi::double_ >> qi::lit(',') >> qi::double_)[boost::bind(&HandlerT::addDestination, handler, ::_1)]; source = (-qi::lit('&')) >> qi::lit("src") >> '=' >> (qi::double_ >> qi::lit(',') >> qi::double_)[boost::bind(&HandlerT::addSource, handler, ::_1)]; hint = (-qi::lit('&')) >> qi::lit("hint") >> '=' >> stringwithDot[boost::bind(&HandlerT::addHint, handler, ::_1)]; timestamp = (-qi::lit('&')) >> qi::lit("t") >> '=' >> qi::uint_[boost::bind(&HandlerT::addTimestamp, handler, ::_1)]; bearing = (-qi::lit('&')) >> qi::lit("b") >> '=' >> (qi::int_ >> -(qi::lit(',') >> qi::int_ | qi::attr(10)))[boost::bind(&HandlerT::addBearing, handler, ::_1, ::_2, ::_3)]; u = (-qi::lit('&')) >> qi::lit("u") >> '=' >> qi::bool_[boost::bind(&HandlerT::setUTurn, handler, ::_1)]; uturns = (-qi::lit('&')) >> qi::lit("uturns") >> '=' >> qi::bool_[boost::bind(&HandlerT::setAllUTurns, handler, ::_1)]; language = (-qi::lit('&')) >> qi::lit("hl") >> '=' >> string[boost::bind(&HandlerT::setLanguage, handler, ::_1)]; alt_route = (-qi::lit('&')) >> qi::lit("alt") >> '=' >> qi::bool_[boost::bind(&HandlerT::setAlternateRouteFlag, handler, ::_1)]; old_API = (-qi::lit('&')) >> qi::lit("geomformat") >> '=' >> string[boost::bind(&HandlerT::setDeprecatedAPIFlag, handler, ::_1)]; num_results = (-qi::lit('&')) >> qi::lit("num_results") >> '=' >> qi::short_[boost::bind(&HandlerT::setNumberOfResults, handler, ::_1)]; matching_beta = (-qi::lit('&')) >> qi::lit("matching_beta") >> '=' >> qi::float_[boost::bind(&HandlerT::setMatchingBeta, handler, ::_1)]; gps_precision = (-qi::lit('&')) >> qi::lit("gps_precision") >> '=' >> qi::float_[boost::bind(&HandlerT::setGPSPrecision, handler, ::_1)]; classify = (-qi::lit('&')) >> qi::lit("classify") >> '=' >> qi::bool_[boost::bind(&HandlerT::setClassify, handler, ::_1)]; locs = (-qi::lit('&')) >> qi::lit("locs") >> '=' >> stringforPolyline[boost::bind(&HandlerT::getCoordinatesFromGeometry, handler, ::_1)]; string = +(qi::char_("a-zA-Z")); stringwithDot = +(qi::char_("a-zA-Z0-9_.-")); stringwithPercent = +(qi::char_("a-zA-Z0-9_.-") | qi::char_('[') | qi::char_(']') | (qi::char_('%') >> qi::char_("0-9A-Z") >> qi::char_("0-9A-Z"))); stringforPolyline = +(qi::char_("a-zA-Z0-9_.-[]{}@?|\\%~`^")); } qi::rule<Iterator> api_call, query, location_options, location_with_options, destination_with_options, source_with_options, t_u, t_h, u_h, t_u_h; qi::rule<Iterator, std::string()> service, zoom, output, string, jsonp, checksum, location, destination, source, hint, timestamp, bearing, stringwithDot, stringwithPercent, language, geometry, cmp, alt_route, u, uturns, old_API, num_results, matching_beta, gps_precision, classify, locs, instruction, stringforPolyline; HandlerT *handler; }; #endif /* API_GRAMMAR_HPP */
7,492
2,580
// Copyright 2017 Per Grön. 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 <catch.hpp> #include <string> #include <vector> #include <rs/if_empty.h> #include <rs/just.h> #include "infinite_range.h" #include "test_util.h" namespace shk { TEST_CASE("IfEmpty") { SECTION("type") { auto stream = IfEmpty(Just())(Just()); static_assert( IsPublisher<decltype(stream)>, "IfEmpty stream should be a publisher"); } SECTION("non-empty stream") { auto null_publisher = MakePublisher([](auto &&subscriber) { CHECK(!"should not be subscribed to"); return MakeSubscription(); }); SECTION("one value") { auto stream = IfEmpty(null_publisher)(Just(2)); CHECK(GetAll<int>(stream) == (std::vector<int>{ 2 })); } SECTION("several values") { auto stream = IfEmpty(null_publisher)(Just(2, 4, 6, 8)); CHECK(GetAll<int>(stream) == (std::vector<int>{ 2, 4, 6, 8 })); } SECTION("noncopyable value") { auto if_empty = IfEmpty(Start([] { return std::make_unique<int>(1); })); auto stream = if_empty(Start([] { return std::make_unique<int>(2); })); auto result = GetAll<std::unique_ptr<int>>(stream); REQUIRE(result.size() == 1); REQUIRE(result[0]); CHECK(*result[0] == 2); } SECTION("don't leak the subscriber") { CheckLeak(IfEmpty(Just(1))(Just(2))); } } SECTION("empty stream") { SECTION("one value") { auto stream = IfEmpty(Just(1))(Just()); CHECK(GetAll<int>(stream) == (std::vector<int>{ 1 })); } SECTION("several values") { auto stream = IfEmpty(Just(1, 2, 3))(Just()); CHECK(GetAll<int>(stream) == (std::vector<int>{ 1, 2, 3 })); } SECTION("don't leak the subscriber") { CheckLeak(IfEmpty(Just(1))(Just())); } } } } // namespace shk
2,377
829
#ifndef VIZE_VOLUME_HPP #define VIZE_VOLUME_HPP #include "vize/config.hpp" #include "vize/serialization/volume_serializer.hpp" #include <ayla/geometry/voxel_grid.hpp> namespace vize { class VolumeHistogram; /** * A tridimensional array of pixels (or "voxels"). Or a pile of images. * * A volume can be loaded from a sequence of image files. * * Each voxel of this volume is supposed to be stored in only one byte. * The voxel data can be seen as an intensity value ranging from 0 to 255. * * The volume abstraction will be used to create an OpenGL 3D texture, * where will be assumed that each pixel of the 3D texture is stored in * only one byte. * * @see vize::VolumeFactory * @see vize::GLVolumeTexture * * @author O Programador */ class Volume final { public: Volume(); Volume(SizeType widthInVolxes, SizeType heightInVoxels, SizeType depthInVoxels); ~Volume(); public: /** * Extract a sub volume of this volume starting at @param subVolumeBegin and * with dimensions specified by @param subVolumeWidth, @param subVolumeHeight and @param subVolumeDepth. */ std::unique_ptr<Volume> extractSubVolume(const ayla::Index3D& subVolumeBegin, SizeType subVolumeWidth, SizeType subVolumeHeight, SizeType subVolumeDepth) const; /** * @return The width of this volume in voxels. */ SizeType getWidth() const; /** * @return The height of this volume in voxels. */ SizeType getHeight() const; /** * @return The depth of this volume in voxels. */ SizeType getDepth() const; /** * @return The total number of voxels stored by this volume. */ SizeType getNumberOfVoxels() const; /** * @return A pointer to the first byte of this volume data. * @remarks Volume data is stored in an internal array. */ const std::uint8_t* getRawData() const; /** * A model matrix is used to give position, orientation and size to the volume. * Use this matrix to place a volume in a 3D space. * * @return The model matrix of this volume. */ glm::mat4 getModelMatrix() const; /** * Set the model matrix of this volume. */ void setModelMatrix(const glm::mat4& modelMatrix); /** * @return A bounding box for this volume. */ ayla::AxisAlignedBox getAABB() const; const VolumeHistogram* getHistogram(); void applyHistogramEqualization(); private: ayla::ByteVoxelGrid _voxelGrid; glm::mat4 _modelMatrix = glm::mat4(1.0f); // gives position, orientation and size to the volume std::unique_ptr<VolumeHistogram> _histogram; private: friend class TiffVolumeFactory; friend class DicomVolumeFactory; friend class VolumeFactory; template<class Archive> friend void boost::serialization::serialize(Archive&, vize::Volume&, const unsigned int); template<class Archive> friend void boost::serialization::load_construct_data(Archive&, vize::Volume*, const unsigned int); }; } #endif // VIZE_VOLUME_HPP
2,870
938
/* ======================================== * NotJustAnotherCD - NotJustAnotherCD.h * Copyright (c) 2016 airwindows, All rights reserved * ======================================== */ #ifndef __NotJustAnotherCD_H #include "NotJustAnotherCD.h" #endif void NotJustAnotherCD::processReplacing(float **inputs, float **outputs, VstInt32 sampleFrames) { float* in1 = inputs[0]; float* in2 = inputs[1]; float* out1 = outputs[0]; float* out2 = outputs[1]; long double inputSampleL; long double inputSampleR; double benfordize; int hotbinA; int hotbinB; double totalA; double totalB; float drySampleL; float drySampleR; while (--sampleFrames >= 0) { inputSampleL = *in1; inputSampleR = *in2; if (inputSampleL<1.2e-38 && -inputSampleL<1.2e-38) { static int noisesource = 0; //this declares a variable before anything else is compiled. It won't keep assigning //it to 0 for every sample, it's as if the declaration doesn't exist in this context, //but it lets me add this denormalization fix in a single place rather than updating //it in three different locations. The variable isn't thread-safe but this is only //a random seed and we can share it with whatever. noisesource = noisesource % 1700021; noisesource++; int residue = noisesource * noisesource; residue = residue % 170003; residue *= residue; residue = residue % 17011; residue *= residue; residue = residue % 1709; residue *= residue; residue = residue % 173; residue *= residue; residue = residue % 17; double applyresidue = residue; applyresidue *= 0.00000001; applyresidue *= 0.00000001; inputSampleL = applyresidue; } if (inputSampleR<1.2e-38 && -inputSampleR<1.2e-38) { static int noisesource = 0; noisesource = noisesource % 1700021; noisesource++; int residue = noisesource * noisesource; residue = residue % 170003; residue *= residue; residue = residue % 17011; residue *= residue; residue = residue % 1709; residue *= residue; residue = residue % 173; residue *= residue; residue = residue % 17; double applyresidue = residue; applyresidue *= 0.00000001; applyresidue *= 0.00000001; inputSampleR = applyresidue; //this denormalization routine produces a white noise at -300 dB which the noise //shaping will interact with to produce a bipolar output, but the noise is actually //all positive. That should stop any variables from going denormal, and the routine //only kicks in if digital black is input. As a final touch, if you save to 24-bit //the silence will return to being digital black again. } drySampleL = inputSampleL; drySampleR = inputSampleR; inputSampleL -= noiseShapingL; inputSampleR -= noiseShapingR; inputSampleL *= 32768.0; inputSampleR *= 32768.0; //0-1 is now one bit, now we dither //begin L benfordize = floor(inputSampleL); while (benfordize >= 1.0) {benfordize /= 10;} if (benfordize < 1.0) {benfordize *= 10;} if (benfordize < 1.0) {benfordize *= 10;} if (benfordize < 1.0) {benfordize *= 10;} if (benfordize < 1.0) {benfordize *= 10;} if (benfordize < 1.0) {benfordize *= 10;} hotbinA = floor(benfordize); //hotbin becomes the Benford bin value for this number floored totalA = 0; if ((hotbinA > 0) && (hotbinA < 10)) { bynL[hotbinA] += 1; totalA += (301-bynL[1]); totalA += (176-bynL[2]); totalA += (125-bynL[3]); totalA += (97-bynL[4]); totalA += (79-bynL[5]); totalA += (67-bynL[6]); totalA += (58-bynL[7]); totalA += (51-bynL[8]); totalA += (46-bynL[9]); bynL[hotbinA] -= 1; } else {hotbinA = 10;} //produce total number- smaller is closer to Benford real benfordize = ceil(inputSampleL); while (benfordize >= 1.0) {benfordize /= 10;} if (benfordize < 1.0) {benfordize *= 10;} if (benfordize < 1.0) {benfordize *= 10;} if (benfordize < 1.0) {benfordize *= 10;} if (benfordize < 1.0) {benfordize *= 10;} if (benfordize < 1.0) {benfordize *= 10;} hotbinB = floor(benfordize); //hotbin becomes the Benford bin value for this number ceiled totalB = 0; if ((hotbinB > 0) && (hotbinB < 10)) { bynL[hotbinB] += 1; totalB += (301-bynL[1]); totalB += (176-bynL[2]); totalB += (125-bynL[3]); totalB += (97-bynL[4]); totalB += (79-bynL[5]); totalB += (67-bynL[6]); totalB += (58-bynL[7]); totalB += (51-bynL[8]); totalB += (46-bynL[9]); bynL[hotbinB] -= 1; } else {hotbinB = 10;} //produce total number- smaller is closer to Benford real if (totalA < totalB) { bynL[hotbinA] += 1; inputSampleL = floor(inputSampleL); } else { bynL[hotbinB] += 1; inputSampleL = ceil(inputSampleL); } //assign the relevant one to the delay line //and floor/ceil signal accordingly totalA = bynL[1] + bynL[2] + bynL[3] + bynL[4] + bynL[5] + bynL[6] + bynL[7] + bynL[8] + bynL[9]; totalA /= 1000; if (totalA = 0) totalA = 1; bynL[1] /= totalA; bynL[2] /= totalA; bynL[3] /= totalA; bynL[4] /= totalA; bynL[5] /= totalA; bynL[6] /= totalA; bynL[7] /= totalA; bynL[8] /= totalA; bynL[9] /= totalA; bynL[10] /= 2; //catchall for garbage data //end L //begin R benfordize = floor(inputSampleR); while (benfordize >= 1.0) {benfordize /= 10;} if (benfordize < 1.0) {benfordize *= 10;} if (benfordize < 1.0) {benfordize *= 10;} if (benfordize < 1.0) {benfordize *= 10;} if (benfordize < 1.0) {benfordize *= 10;} if (benfordize < 1.0) {benfordize *= 10;} hotbinA = floor(benfordize); //hotbin becomes the Benford bin value for this number floored totalA = 0; if ((hotbinA > 0) && (hotbinA < 10)) { bynR[hotbinA] += 1; totalA += (301-bynR[1]); totalA += (176-bynR[2]); totalA += (125-bynR[3]); totalA += (97-bynR[4]); totalA += (79-bynR[5]); totalA += (67-bynR[6]); totalA += (58-bynR[7]); totalA += (51-bynR[8]); totalA += (46-bynR[9]); bynR[hotbinA] -= 1; } else {hotbinA = 10;} //produce total number- smaller is closer to Benford real benfordize = ceil(inputSampleR); while (benfordize >= 1.0) {benfordize /= 10;} if (benfordize < 1.0) {benfordize *= 10;} if (benfordize < 1.0) {benfordize *= 10;} if (benfordize < 1.0) {benfordize *= 10;} if (benfordize < 1.0) {benfordize *= 10;} if (benfordize < 1.0) {benfordize *= 10;} hotbinB = floor(benfordize); //hotbin becomes the Benford bin value for this number ceiled totalB = 0; if ((hotbinB > 0) && (hotbinB < 10)) { bynR[hotbinB] += 1; totalB += (301-bynR[1]); totalB += (176-bynR[2]); totalB += (125-bynR[3]); totalB += (97-bynR[4]); totalB += (79-bynR[5]); totalB += (67-bynR[6]); totalB += (58-bynR[7]); totalB += (51-bynR[8]); totalB += (46-bynR[9]); bynR[hotbinB] -= 1; } else {hotbinB = 10;} //produce total number- smaller is closer to Benford real if (totalA < totalB) { bynR[hotbinA] += 1; inputSampleR = floor(inputSampleR); } else { bynR[hotbinB] += 1; inputSampleR = ceil(inputSampleR); } //assign the relevant one to the delay line //and floor/ceil signal accordingly totalA = bynR[1] + bynR[2] + bynR[3] + bynR[4] + bynR[5] + bynR[6] + bynR[7] + bynR[8] + bynR[9]; totalA /= 1000; if (totalA = 0) totalA = 1; bynR[1] /= totalA; bynR[2] /= totalA; bynR[3] /= totalA; bynR[4] /= totalA; bynR[5] /= totalA; bynR[6] /= totalA; bynR[7] /= totalA; bynR[8] /= totalA; bynR[9] /= totalA; bynR[10] /= 2; //catchall for garbage data //end R inputSampleL /= 32768.0; inputSampleR /= 32768.0; noiseShapingL += inputSampleL - drySampleL; noiseShapingR += inputSampleR - drySampleR; *out1 = inputSampleL; *out2 = inputSampleR; *in1++; *in2++; *out1++; *out2++; } } void NotJustAnotherCD::processDoubleReplacing(double **inputs, double **outputs, VstInt32 sampleFrames) { double* in1 = inputs[0]; double* in2 = inputs[1]; double* out1 = outputs[0]; double* out2 = outputs[1]; long double inputSampleL; long double inputSampleR; double benfordize; int hotbinA; int hotbinB; double totalA; double totalB; double drySampleL; double drySampleR; while (--sampleFrames >= 0) { inputSampleL = *in1; inputSampleR = *in2; if (inputSampleL<1.2e-38 && -inputSampleL<1.2e-38) { static int noisesource = 0; //this declares a variable before anything else is compiled. It won't keep assigning //it to 0 for every sample, it's as if the declaration doesn't exist in this context, //but it lets me add this denormalization fix in a single place rather than updating //it in three different locations. The variable isn't thread-safe but this is only //a random seed and we can share it with whatever. noisesource = noisesource % 1700021; noisesource++; int residue = noisesource * noisesource; residue = residue % 170003; residue *= residue; residue = residue % 17011; residue *= residue; residue = residue % 1709; residue *= residue; residue = residue % 173; residue *= residue; residue = residue % 17; double applyresidue = residue; applyresidue *= 0.00000001; applyresidue *= 0.00000001; inputSampleL = applyresidue; } if (inputSampleR<1.2e-38 && -inputSampleR<1.2e-38) { static int noisesource = 0; noisesource = noisesource % 1700021; noisesource++; int residue = noisesource * noisesource; residue = residue % 170003; residue *= residue; residue = residue % 17011; residue *= residue; residue = residue % 1709; residue *= residue; residue = residue % 173; residue *= residue; residue = residue % 17; double applyresidue = residue; applyresidue *= 0.00000001; applyresidue *= 0.00000001; inputSampleR = applyresidue; //this denormalization routine produces a white noise at -300 dB which the noise //shaping will interact with to produce a bipolar output, but the noise is actually //all positive. That should stop any variables from going denormal, and the routine //only kicks in if digital black is input. As a final touch, if you save to 24-bit //the silence will return to being digital black again. } drySampleL = inputSampleL; drySampleR = inputSampleR; inputSampleL -= noiseShapingL; inputSampleR -= noiseShapingR; inputSampleL *= 32768.0; inputSampleR *= 32768.0; //0-1 is now one bit, now we dither //begin L benfordize = floor(inputSampleL); while (benfordize >= 1.0) {benfordize /= 10;} if (benfordize < 1.0) {benfordize *= 10;} if (benfordize < 1.0) {benfordize *= 10;} if (benfordize < 1.0) {benfordize *= 10;} if (benfordize < 1.0) {benfordize *= 10;} if (benfordize < 1.0) {benfordize *= 10;} hotbinA = floor(benfordize); //hotbin becomes the Benford bin value for this number floored totalA = 0; if ((hotbinA > 0) && (hotbinA < 10)) { bynL[hotbinA] += 1; totalA += (301-bynL[1]); totalA += (176-bynL[2]); totalA += (125-bynL[3]); totalA += (97-bynL[4]); totalA += (79-bynL[5]); totalA += (67-bynL[6]); totalA += (58-bynL[7]); totalA += (51-bynL[8]); totalA += (46-bynL[9]); bynL[hotbinA] -= 1; } else {hotbinA = 10;} //produce total number- smaller is closer to Benford real benfordize = ceil(inputSampleL); while (benfordize >= 1.0) {benfordize /= 10;} if (benfordize < 1.0) {benfordize *= 10;} if (benfordize < 1.0) {benfordize *= 10;} if (benfordize < 1.0) {benfordize *= 10;} if (benfordize < 1.0) {benfordize *= 10;} if (benfordize < 1.0) {benfordize *= 10;} hotbinB = floor(benfordize); //hotbin becomes the Benford bin value for this number ceiled totalB = 0; if ((hotbinB > 0) && (hotbinB < 10)) { bynL[hotbinB] += 1; totalB += (301-bynL[1]); totalB += (176-bynL[2]); totalB += (125-bynL[3]); totalB += (97-bynL[4]); totalB += (79-bynL[5]); totalB += (67-bynL[6]); totalB += (58-bynL[7]); totalB += (51-bynL[8]); totalB += (46-bynL[9]); bynL[hotbinB] -= 1; } else {hotbinB = 10;} //produce total number- smaller is closer to Benford real if (totalA < totalB) { bynL[hotbinA] += 1; inputSampleL = floor(inputSampleL); } else { bynL[hotbinB] += 1; inputSampleL = ceil(inputSampleL); } //assign the relevant one to the delay line //and floor/ceil signal accordingly totalA = bynL[1] + bynL[2] + bynL[3] + bynL[4] + bynL[5] + bynL[6] + bynL[7] + bynL[8] + bynL[9]; totalA /= 1000; if (totalA = 0) totalA = 1; bynL[1] /= totalA; bynL[2] /= totalA; bynL[3] /= totalA; bynL[4] /= totalA; bynL[5] /= totalA; bynL[6] /= totalA; bynL[7] /= totalA; bynL[8] /= totalA; bynL[9] /= totalA; bynL[10] /= 2; //catchall for garbage data //end L //begin R benfordize = floor(inputSampleR); while (benfordize >= 1.0) {benfordize /= 10;} if (benfordize < 1.0) {benfordize *= 10;} if (benfordize < 1.0) {benfordize *= 10;} if (benfordize < 1.0) {benfordize *= 10;} if (benfordize < 1.0) {benfordize *= 10;} if (benfordize < 1.0) {benfordize *= 10;} hotbinA = floor(benfordize); //hotbin becomes the Benford bin value for this number floored totalA = 0; if ((hotbinA > 0) && (hotbinA < 10)) { bynR[hotbinA] += 1; totalA += (301-bynR[1]); totalA += (176-bynR[2]); totalA += (125-bynR[3]); totalA += (97-bynR[4]); totalA += (79-bynR[5]); totalA += (67-bynR[6]); totalA += (58-bynR[7]); totalA += (51-bynR[8]); totalA += (46-bynR[9]); bynR[hotbinA] -= 1; } else {hotbinA = 10;} //produce total number- smaller is closer to Benford real benfordize = ceil(inputSampleR); while (benfordize >= 1.0) {benfordize /= 10;} if (benfordize < 1.0) {benfordize *= 10;} if (benfordize < 1.0) {benfordize *= 10;} if (benfordize < 1.0) {benfordize *= 10;} if (benfordize < 1.0) {benfordize *= 10;} if (benfordize < 1.0) {benfordize *= 10;} hotbinB = floor(benfordize); //hotbin becomes the Benford bin value for this number ceiled totalB = 0; if ((hotbinB > 0) && (hotbinB < 10)) { bynR[hotbinB] += 1; totalB += (301-bynR[1]); totalB += (176-bynR[2]); totalB += (125-bynR[3]); totalB += (97-bynR[4]); totalB += (79-bynR[5]); totalB += (67-bynR[6]); totalB += (58-bynR[7]); totalB += (51-bynR[8]); totalB += (46-bynR[9]); bynR[hotbinB] -= 1; } else {hotbinB = 10;} //produce total number- smaller is closer to Benford real if (totalA < totalB) { bynR[hotbinA] += 1; inputSampleR = floor(inputSampleR); } else { bynR[hotbinB] += 1; inputSampleR = ceil(inputSampleR); } //assign the relevant one to the delay line //and floor/ceil signal accordingly totalA = bynR[1] + bynR[2] + bynR[3] + bynR[4] + bynR[5] + bynR[6] + bynR[7] + bynR[8] + bynR[9]; totalA /= 1000; if (totalA = 0) totalA = 1; bynR[1] /= totalA; bynR[2] /= totalA; bynR[3] /= totalA; bynR[4] /= totalA; bynR[5] /= totalA; bynR[6] /= totalA; bynR[7] /= totalA; bynR[8] /= totalA; bynR[9] /= totalA; bynR[10] /= 2; //catchall for garbage data //end R inputSampleL /= 32768.0; inputSampleR /= 32768.0; noiseShapingL += inputSampleL - drySampleL; noiseShapingR += inputSampleR - drySampleR; *out1 = inputSampleL; *out2 = inputSampleR; *in1++; *in2++; *out1++; *out2++; } }
15,321
7,531
//============================================================================= // Copyright (C) 2011-2018 The pmp-library developers // // 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 holder nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. //============================================================================= #include "MeshViewer.h" #include <imgui.h> #include <cfloat> #include <iostream> #include <sstream> //============================================================================= namespace pmp { //============================================================================= MeshViewer::MeshViewer(const char* title, int width, int height, bool showgui) : TrackballViewer(title, width, height, showgui) { // setup draw modes clearDrawModes(); addDrawMode("Points"); addDrawMode("Hidden Line"); addDrawMode("Smooth Shading"); addDrawMode("Texture"); setDrawMode("Smooth Shading"); m_creaseAngle = 90.0; } //----------------------------------------------------------------------------- MeshViewer::~MeshViewer() = default; //----------------------------------------------------------------------------- bool MeshViewer::loadMesh(const char* filename) { // load mesh if (m_mesh.read(filename)) { // update scene center and bounds BoundingBox bb = m_mesh.bounds(); setScene(bb.center(), 0.5 * bb.size()); // compute face & vertex normals, update face indices updateMesh(); std::cout << "Load " << filename << ": " << m_mesh.nVertices() << " vertices, " << m_mesh.nFaces() << " faces\n"; m_filename = filename; m_creaseAngle = m_mesh.creaseAngle(); return true; } std::cerr << "Failed to read mesh from " << filename << " !" << std::endl; return false; } //----------------------------------------------------------------------------- bool MeshViewer::loadTexture(const char* filename, GLint format, GLint minFilter, GLint magFilter, GLint wrap) { // load texture from file if (!m_mesh.loadTexture(filename, format, minFilter, magFilter, wrap)) return false; setDrawMode("Texture"); // set material m_mesh.setAmbient(1.0); m_mesh.setDiffuse(0.9); m_mesh.setSpecular(0.0); m_mesh.setShininess(1.0); return true; } //----------------------------------------------------------------------------- void MeshViewer::updateMesh() { // re-compute face and vertex normals m_mesh.updateOpenGLBuffers(); } //----------------------------------------------------------------------------- void MeshViewer::processImGUI() { if (ImGui::CollapsingHeader("Mesh Info", ImGuiTreeNodeFlags_DefaultOpen)) { // output mesh statistics ImGui::BulletText("%d vertices", (int)m_mesh.nVertices()); ImGui::BulletText("%d edges", (int)m_mesh.nEdges()); ImGui::BulletText("%d faces", (int)m_mesh.nFaces()); // control crease angle ImGui::PushItemWidth(100); ImGui::SliderFloat("Crease Angle", &m_creaseAngle, 0.0f, 180.0f, "%.0f"); ImGui::PopItemWidth(); if (m_creaseAngle != m_mesh.creaseAngle()) { m_mesh.setCreaseAngle(m_creaseAngle); std::cerr << "change crease angle\n"; } } } //----------------------------------------------------------------------------- void MeshViewer::draw(const std::string& drawMode) { // draw mesh m_mesh.draw(m_projectionMatrix, m_modelviewMatrix, drawMode); } //----------------------------------------------------------------------------- // void MeshViewer::keyboard(int key, int scancode, int action, int mods) { if (action != GLFW_PRESS && action != GLFW_REPEAT) return; switch (key) { case GLFW_KEY_BACKSPACE: // reload model { loadMesh(m_filename.c_str()); break; } case GLFW_KEY_C: // adjust crease angle { if (mods & GLFW_MOD_SHIFT) m_mesh.setCreaseAngle(m_mesh.creaseAngle() + 10); else m_mesh.setCreaseAngle(m_mesh.creaseAngle() - 10); m_creaseAngle = m_mesh.creaseAngle(); std::cout << "crease angle: " << m_mesh.creaseAngle() << std::endl; break; } case GLFW_KEY_O: // write mesh { m_mesh.write("output.off"); break; } default: { TrackballViewer::keyboard(key, scancode, action, mods); break; } } } //============================================================================= } // namespace pmp //=============================================================================
6,213
1,903
#include <bits/stdc++.h> #include <iostream> #include <vector> #include <algorithm> using namespace std; #define ar array #define ll unsigned long long const int MAX_N = 1e5 + 1; const int MOD = 1e9 + 7; const int INF = 1e9; const ll LINF = 1e18; // test: // 50 19 // 47 47 47 47 47 47 47 47 47 47 47 47 47 47 47 47 47 47 47 30 47 47 47 47 47 47 47 47 25 30 47 47 47 30 47 47 47 47 47 47 47 47 47 47 17 47 47 37 25 47 ll binomialCoeffUtil(int n, int k, ll** dp) { // If value in lookup table then return if (dp[n][k] != -1) // return dp[n][k]; // store value in a table before return if (k == 0) { dp[n][k] = 1; return dp[n][k]; } // store value in table before return if (k == n) { dp[n][k] = 1; return dp[n][k]; } // save value in lookup table before return dp[n][k] = binomialCoeffUtil(n - 1, k - 1, dp) + binomialCoeffUtil(n - 1, k, dp); dp[n][k] %= MOD; return dp[n][k]; } ll binomialCoeff(int n, int k) { ll** dp; // make a temporary lookup table dp = new ll*[n + 1]; // loop to create table dynamically for (int i = 0; i < (n + 1); i++) { dp[i] = new ll[k + 1]; } // nested loop to initialise the table with -1 for (int i = 0; i < (n + 1); i++) { for (int j = 0; j < (k + 1); j++) { dp[i][j] = -1; } } return binomialCoeffUtil(n, k, dp); } // broken ll choose(int n, int k) { // n choose m if (k > n) return 0; if (k*2 > n) k = n-k; if (k==0) return 1; ll ret = n; for (int i=2; i<=k; ++i) { ret = (ret * (ll)(n-i+1)/(ll)i)%MOD; // wrong because division should be product with modular inverse cout << ret << ", "; } cout << "\n"; return ret; } // a more efficient way of nCk------------------------------------------------ ll powmod(ll base, ll exp, ll mod) { base %= mod; ll ret = 1; while (exp > 0) { if (exp & 1) ret = (ret * base)%mod; base = (base * base)%mod; exp >>= 1; } return ret; } // degree of mod in n! (exponent of mod in factorization of factorial) int fact_exp(ll n, ll mod) { int ret = 0; ll curr = mod; while (curr <= n) { ret += n/curr; curr *= mod; } return ret; } // nCk ll fermat_binomial(ll n, ll k, ll mod) { if (k == 0) return 1; int num_degree = fact_exp(n, mod) - fact_exp(n-k, mod); int den_degree = fact_exp(k, mod); if (num_degree > den_degree) return 0; if (k > n) return 0; // compute numerator ll num = 1; for (ll i=n; i>n-k; --i) { ll curr = i; while (curr % mod == 0) curr /= mod; num = (num * curr)%mod; } // compute denominator ll den = 1; for (ll i=1; i<=k; ++i) { ll curr = i; while (curr % mod == 0) curr /= mod; den = (den * curr) % mod; } // apply fermat little theorem for inverse multiplicative of den return (num * powmod(den, mod-2, mod))%mod; } // ways to make k-sum equal to largest k-sum ll solve(vector<int> arr, int k) { sort(arr.begin(), arr.end(), greater<int>()); // descending order int repeated = 1; int last = arr[k-1]; while (k-1-repeated>=0 && arr[k-1-repeated]==last) ++repeated; int total = repeated; for (int i=k; i<arr.size(); ++i) { if (arr[i]==last) ++total; else break; } // cout << total << "choose" << repeated << "\n"; return fermat_binomial(total, repeated, 1e9+7); } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); // freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); int tc; cin >> tc; for (int t = 1; t <= tc; t++) { int n, k; cin >> n >> k; vector<int> followers(n); for (int i=0; i<n; ++i) cin >> followers[i]; if (n == k) { cout << 1 << "\n"; continue; } cout << solve(followers, k) << "\n"; } }
4,034
1,704
// // $Id$ #include <QtDebug> #include "actor/Pawn.h" #include "net/Session.h" #include "scene/Scene.h" #include "scene/SceneView.h" SceneView::SceneView (Session* session) : Component(0) { connect(session, SIGNAL(didEnterScene(Scene*)), SLOT(handleDidEnterScene(Scene*))); connect(session, SIGNAL(willLeaveScene(Scene*)), SLOT(handleWillLeaveScene(Scene*))); } SceneView::~SceneView () { Session* session = this->session(); if (session != 0) { Scene* scene = session->scene(); if (scene != 0) { scene->removeSpatial(this); } } } void SceneView::setWorldBounds (const QRect& bounds) { if (_worldBounds != bounds) { QRect oldBounds = _worldBounds; Scene* scene = session()->scene(); if (scene == 0) { _worldBounds = bounds; _scrollAmount = QPoint(0, 0); } else { // detect scrolling if (_worldBounds.size() == bounds.size() && _worldBounds.intersects(bounds)) { QPoint delta = _worldBounds.topLeft() - bounds.topLeft(); _scrollAmount += delta; scrollDirty(delta); } else { _scrollAmount = QPoint(0, 0); dirty(); } scene->removeSpatial(this); _worldBounds = bounds; scene->addSpatial(this); } emit worldBoundsChanged(oldBounds); } } void SceneView::handleDidEnterScene (Scene* scene) { scene->addSpatial(this); connect(scene, SIGNAL(recordChanged(SceneRecord)), SLOT(maybeScroll())); Pawn* pawn = session()->pawn(); if (pawn != 0) { // center around the pawn and adjust when it moves connect(pawn, SIGNAL(positionChanged(QPoint)), SLOT(maybeScroll())); QSize size = _bounds.size(); setWorldBounds(QRect(pawn->position() - QPoint(size.width()/2, size.height()/2), size)); } _scrollAmount = QPoint(0, 0); dirty(); } void SceneView::handleWillLeaveScene (Scene* scene) { Pawn* pawn = session()->pawn(); if (pawn != 0) { disconnect(pawn); } disconnect(scene); scene->removeSpatial(this); } /** * Helper function for maybeScroll: returns the signed distance between the specified value and the * given range. */ static int getDelta (int value, int start, int end) { return (value < start) ? (value - start) : (value > end ? (value - end) : 0); } void SceneView::maybeScroll () { Session* session = this->session(); const SceneRecord& record = session->scene()->record(); QRect scrollBounds( _worldBounds.left() + _worldBounds.width()/2 - record.scrollWidth/2, _worldBounds.top() + _worldBounds.height()/2 - record.scrollHeight/2, record.scrollWidth, record.scrollHeight); // scroll to fit the pawn position within the scroll bounds const QPoint& pos = session->pawn()->position(); setWorldBounds(_worldBounds.translated( getDelta(pos.x(), scrollBounds.left(), scrollBounds.right()), getDelta(pos.y(), scrollBounds.top(), scrollBounds.bottom()))); } void SceneView::invalidate () { Component::invalidate(); // resize world bounds if necessary setWorldBounds(QRect(_worldBounds.topLeft(), _bounds.size())); } void SceneView::draw (DrawContext* ctx) { Component::draw(ctx); // apply scroll, if any if (_scrollAmount != QPoint(0, 0)) { ctx->scrollContents(localBounds(), _scrollAmount); _scrollAmount = QPoint(0, 0); } Scene* scene = session()->scene(); if (scene == 0) { return; } const QHash<QPoint, Scene::Block>& blocks = scene->blocks(); // find the intersection of the dirty bounds in world space and the world bounds QRect dirty = ctx->dirty().boundingRect(); dirty.translate(-ctx->pos()); dirty.translate(_worldBounds.topLeft()); dirty &= _worldBounds; // draw all blocks that intersect int bx1 = dirty.left() >> Scene::Block::LgSize; int bx2 = dirty.right() >> Scene::Block::LgSize; int by1 = dirty.top() >> Scene::Block::LgSize; int by2 = dirty.bottom() >> Scene::Block::LgSize; QRect bbounds(0, 0, Scene::Block::Size, Scene::Block::Size); for (int by = by1; by <= by2; by++) { for (int bx = bx1; bx <= bx2; bx++) { QHash<QPoint, Scene::Block>::const_iterator it = blocks.constFind(QPoint(bx, by)); if (it != blocks.constEnd()) { const Scene::Block& block = *it; bbounds.moveTo(bx << Scene::Block::LgSize, by << Scene::Block::LgSize); QRect ibounds = bbounds.intersected(_worldBounds); ctx->drawContents( ibounds.left() - _worldBounds.left(), ibounds.top() - _worldBounds.top(), ibounds.width(), ibounds.height(), block.constData() + (ibounds.top() - bbounds.top() << Scene::Block::LgSize) + (ibounds.left() - bbounds.left()), true, Scene::Block::Size); } } } }
5,087
1,583
/* * Copyright 2016 WebAssembly Community Group participants * * 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 "support/hash.h" #include "ir/iteration.h" #include "ir/load-utils.h" #include "ir/utils.h" namespace wasm { // Given a stack of expressions, checks if the topmost is used as a result. // For example, if the parent is a block and the node is before the last position, // it is not used. bool ExpressionAnalyzer::isResultUsed(ExpressionStack& stack, Function* func) { for (int i = int(stack.size()) - 2; i >= 0; i--) { auto* curr = stack[i]; auto* above = stack[i + 1]; // only if and block can drop values (pre-drop expression was added) FIXME if (curr->is<Block>()) { auto* block = curr->cast<Block>(); for (size_t j = 0; j < block->list.size() - 1; j++) { if (block->list[j] == above) return false; } assert(block->list.back() == above); // continue down } else if (curr->is<If>()) { auto* iff = curr->cast<If>(); if (above == iff->condition) return true; if (!iff->ifFalse) return false; assert(above == iff->ifTrue || above == iff->ifFalse); // continue down } else { if (curr->is<Drop>()) return false; return true; // all other node types use the result } } // The value might be used, so it depends on if the function returns return func->result != none; } // Checks if a value is dropped. bool ExpressionAnalyzer::isResultDropped(ExpressionStack& stack) { for (int i = int(stack.size()) - 2; i >= 0; i--) { auto* curr = stack[i]; auto* above = stack[i + 1]; if (curr->is<Block>()) { auto* block = curr->cast<Block>(); for (size_t j = 0; j < block->list.size() - 1; j++) { if (block->list[j] == above) return false; } assert(block->list.back() == above); // continue down } else if (curr->is<If>()) { auto* iff = curr->cast<If>(); if (above == iff->condition) return false; if (!iff->ifFalse) return false; assert(above == iff->ifTrue || above == iff->ifFalse); // continue down } else { if (curr->is<Drop>()) return true; // dropped return false; // all other node types use the result } } return false; } bool ExpressionAnalyzer::flexibleEqual(Expression* left, Expression* right, ExprComparer comparer) { std::vector<Name> nameStack; std::map<Name, std::vector<Name>> rightNames; // for each name on the left, the stack of names on the right (a stack, since names are scoped and can nest duplicatively Nop popNameMarker; std::vector<Expression*> leftStack; std::vector<Expression*> rightStack; auto noteNames = [&](Name left, Name right) { if (left.is() != right.is()) return false; if (left.is()) { nameStack.push_back(left); rightNames[left].push_back(right); leftStack.push_back(&popNameMarker); rightStack.push_back(&popNameMarker); } return true; }; auto checkNames = [&](Name left, Name right) { auto iter = rightNames.find(left); if (iter == rightNames.end()) return left == right; // non-internal name return iter->second.back() == right; }; auto popName = [&]() { auto left = nameStack.back(); nameStack.pop_back(); rightNames[left].pop_back(); }; leftStack.push_back(left); rightStack.push_back(right); while (leftStack.size() > 0 && rightStack.size() > 0) { left = leftStack.back(); leftStack.pop_back(); right = rightStack.back(); rightStack.pop_back(); if (!left != !right) return false; if (!left) continue; if (left == &popNameMarker) { popName(); continue; } if (comparer(left, right)) continue; // comparison hook, before all the rest // continue with normal structural comparison if (left->_id != right->_id) return false; // Compare immediate values #define CHECK(clazz, what) \ if (left->cast<clazz>()->what != right->cast<clazz>()->what) return false; switch (left->_id) { case Expression::Id::BlockId: { if (!noteNames(left->cast<Block>()->name, right->cast<Block>()->name)) return false; CHECK(Block, list.size()); break; } case Expression::Id::LoopId: { if (!noteNames(left->cast<Loop>()->name, right->cast<Loop>()->name)) return false; break; } case Expression::Id::BreakId: { if (!checkNames(left->cast<Break>()->name, right->cast<Break>()->name)) return false; break; } case Expression::Id::SwitchId: { CHECK(Switch, targets.size()); for (Index i = 0; i < left->cast<Switch>()->targets.size(); i++) { if (!checkNames(left->cast<Switch>()->targets[i], right->cast<Switch>()->targets[i])) return false; } if (!checkNames(left->cast<Switch>()->default_, right->cast<Switch>()->default_)) return false; break; } case Expression::Id::CallId: { CHECK(Call, target); CHECK(Call, operands.size()); break; } case Expression::Id::CallIndirectId: { CHECK(CallIndirect, fullType); CHECK(CallIndirect, operands.size()); break; } case Expression::Id::GetLocalId: { CHECK(GetLocal, index); break; } case Expression::Id::SetLocalId: { CHECK(SetLocal, index); CHECK(SetLocal, type); // for tee/set break; } case Expression::Id::GetGlobalId: { CHECK(GetGlobal, name); break; } case Expression::Id::SetGlobalId: { CHECK(SetGlobal, name); break; } case Expression::Id::LoadId: { CHECK(Load, bytes); if (LoadUtils::isSignRelevant(left->cast<Load>()) && LoadUtils::isSignRelevant(right->cast<Load>())) { CHECK(Load, signed_); } CHECK(Load, offset); CHECK(Load, align); CHECK(Load, isAtomic); break; } case Expression::Id::StoreId: { CHECK(Store, bytes); CHECK(Store, offset); CHECK(Store, align); CHECK(Store, valueType); CHECK(Store, isAtomic); break; } case Expression::Id::AtomicCmpxchgId: { CHECK(AtomicCmpxchg, bytes); CHECK(AtomicCmpxchg, offset); break; } case Expression::Id::AtomicRMWId: { CHECK(AtomicRMW, op); CHECK(AtomicRMW, bytes); CHECK(AtomicRMW, offset); break; } case Expression::Id::AtomicWaitId: { CHECK(AtomicWait, expectedType); break; } case Expression::Id::AtomicWakeId: { break; } case Expression::Id::SIMDExtractId: { CHECK(SIMDExtract, op); CHECK(SIMDExtract, index); break; } case Expression::Id::SIMDReplaceId: { CHECK(SIMDReplace, op); CHECK(SIMDReplace, index); break; } case Expression::Id::SIMDShuffleId: { CHECK(SIMDShuffle, mask); break; } case Expression::Id::SIMDBitselectId: { break; } case Expression::Id::SIMDShiftId: { CHECK(SIMDShift, op); break; } case Expression::Id::MemoryInitId: { CHECK(MemoryInit, segment); break; } case Expression::Id::DataDropId: { CHECK(DataDrop, segment); break; } case Expression::Id::MemoryCopyId: { break; } case Expression::Id::MemoryFillId: { break; } case Expression::Id::ConstId: { if (left->cast<Const>()->value != right->cast<Const>()->value) { return false; } break; } case Expression::Id::UnaryId: { CHECK(Unary, op); break; } case Expression::Id::BinaryId: { CHECK(Binary, op); break; } case Expression::Id::HostId: { CHECK(Host, op); CHECK(Host, nameOperand); CHECK(Host, operands.size()); break; } case Expression::Id::NopId: { break; } case Expression::Id::UnreachableId: { break; } case Expression::Id::InvalidId: case Expression::Id::NumExpressionIds: { WASM_UNREACHABLE(); } case Expression::Id::IfId: case Expression::Id::SelectId: case Expression::Id::DropId: case Expression::Id::ReturnId: { break; // some nodes have no immediate fields } } // Add child nodes for (auto* child : ChildIterator(left)) { leftStack.push_back(child); } for (auto* child : ChildIterator(right)) { rightStack.push_back(child); } #undef CHECK } if (leftStack.size() > 0 || rightStack.size() > 0) return false; return true; } // hash an expression, ignoring superficial details like specific internal names HashType ExpressionAnalyzer::hash(Expression* curr) { HashType digest = 0; auto hash = [&digest](HashType hash) { digest = rehash(digest, hash); }; auto hash64 = [&digest](uint64_t hash) { digest = rehash(rehash(digest, HashType(hash >> 32)), HashType(hash)); }; std::vector<Name> nameStack; Index internalCounter = 0; std::map<Name, std::vector<Index>> internalNames; // for each internal name, a vector if unique ids Nop popNameMarker; std::vector<Expression*> stack; auto noteName = [&](Name curr) { if (curr.is()) { nameStack.push_back(curr); internalNames[curr].push_back(internalCounter++); stack.push_back(&popNameMarker); } return true; }; auto hashName = [&](Name curr) { auto iter = internalNames.find(curr); if (iter == internalNames.end()) hash64(uint64_t(curr.str)); else hash(iter->second.back()); }; auto popName = [&]() { auto curr = nameStack.back(); nameStack.pop_back(); internalNames[curr].pop_back(); }; stack.push_back(curr); while (stack.size() > 0) { curr = stack.back(); stack.pop_back(); if (!curr) continue; if (curr == &popNameMarker) { popName(); continue; } hash(curr->_id); // we often don't need to hash the type, as it is tied to other values // we are hashing anyhow, but there are exceptions: for example, a // local.get's type is determined by the function, so if we are // hashing only expression fragments, then two from different // functions may turn out the same even if the type differs. Likewise, // if we hash between modules, then we need to take int account // call_imports type, etc. The simplest thing is just to hash the // type for all of them. hash(curr->type); #define PUSH(clazz, what) \ stack.push_back(curr->cast<clazz>()->what); #define HASH(clazz, what) \ hash(curr->cast<clazz>()->what); #define HASH64(clazz, what) \ hash64(curr->cast<clazz>()->what); #define HASH_NAME(clazz, what) \ hash64(uint64_t(curr->cast<clazz>()->what.str)); #define HASH_PTR(clazz, what) \ hash64(uint64_t(curr->cast<clazz>()->what)); switch (curr->_id) { case Expression::Id::BlockId: { noteName(curr->cast<Block>()->name); HASH(Block, list.size()); for (Index i = 0; i < curr->cast<Block>()->list.size(); i++) { PUSH(Block, list[i]); } break; } case Expression::Id::IfId: { PUSH(If, condition); PUSH(If, ifTrue); PUSH(If, ifFalse); break; } case Expression::Id::LoopId: { noteName(curr->cast<Loop>()->name); PUSH(Loop, body); break; } case Expression::Id::BreakId: { hashName(curr->cast<Break>()->name); PUSH(Break, condition); PUSH(Break, value); break; } case Expression::Id::SwitchId: { HASH(Switch, targets.size()); for (Index i = 0; i < curr->cast<Switch>()->targets.size(); i++) { hashName(curr->cast<Switch>()->targets[i]); } hashName(curr->cast<Switch>()->default_); PUSH(Switch, condition); PUSH(Switch, value); break; } case Expression::Id::CallId: { HASH_NAME(Call, target); HASH(Call, operands.size()); for (Index i = 0; i < curr->cast<Call>()->operands.size(); i++) { PUSH(Call, operands[i]); } break; } case Expression::Id::CallIndirectId: { PUSH(CallIndirect, target); HASH_NAME(CallIndirect, fullType); HASH(CallIndirect, operands.size()); for (Index i = 0; i < curr->cast<CallIndirect>()->operands.size(); i++) { PUSH(CallIndirect, operands[i]); } break; } case Expression::Id::GetLocalId: { HASH(GetLocal, index); break; } case Expression::Id::SetLocalId: { HASH(SetLocal, index); PUSH(SetLocal, value); break; } case Expression::Id::GetGlobalId: { HASH_NAME(GetGlobal, name); break; } case Expression::Id::SetGlobalId: { HASH_NAME(SetGlobal, name); PUSH(SetGlobal, value); break; } case Expression::Id::LoadId: { HASH(Load, bytes); if (LoadUtils::isSignRelevant(curr->cast<Load>())) { HASH(Load, signed_); } HASH(Load, offset); HASH(Load, align); HASH(Load, isAtomic); PUSH(Load, ptr); break; } case Expression::Id::StoreId: { HASH(Store, bytes); HASH(Store, offset); HASH(Store, align); HASH(Store, valueType); HASH(Store, isAtomic); PUSH(Store, ptr); PUSH(Store, value); break; } case Expression::Id::AtomicCmpxchgId: { HASH(AtomicCmpxchg, bytes); HASH(AtomicCmpxchg, offset); PUSH(AtomicCmpxchg, ptr); PUSH(AtomicCmpxchg, expected); PUSH(AtomicCmpxchg, replacement); break; } case Expression::Id::AtomicRMWId: { HASH(AtomicRMW, op); HASH(AtomicRMW, bytes); HASH(AtomicRMW, offset); PUSH(AtomicRMW, ptr); PUSH(AtomicRMW, value); break; } case Expression::Id::AtomicWaitId: { HASH(AtomicWait, offset); HASH(AtomicWait, expectedType); PUSH(AtomicWait, ptr); PUSH(AtomicWait, expected); PUSH(AtomicWait, timeout); break; } case Expression::Id::AtomicWakeId: { HASH(AtomicWake, offset); PUSH(AtomicWake, ptr); PUSH(AtomicWake, wakeCount); break; } case Expression::Id::SIMDExtractId: { HASH(SIMDExtract, op); HASH(SIMDExtract, index); PUSH(SIMDExtract, vec); break; } case Expression::Id::SIMDReplaceId: { HASH(SIMDReplace, op); HASH(SIMDReplace, index); PUSH(SIMDReplace, vec); PUSH(SIMDReplace, value); break; } case Expression::Id::SIMDShuffleId: { for (size_t i = 0; i < 16; ++i) { HASH(SIMDShuffle, mask[i]); } PUSH(SIMDShuffle, left); PUSH(SIMDShuffle, right); break; } case Expression::Id::SIMDBitselectId: { PUSH(SIMDBitselect, left); PUSH(SIMDBitselect, right); PUSH(SIMDBitselect, cond); break; } case Expression::Id::SIMDShiftId: { HASH(SIMDShift, op); PUSH(SIMDShift, vec); PUSH(SIMDShift, shift); break; } case Expression::Id::MemoryInitId: { HASH(MemoryInit, segment); PUSH(MemoryInit, dest); PUSH(MemoryInit, offset); PUSH(MemoryInit, size); break; } case Expression::Id::DataDropId: { HASH(DataDrop, segment); break; } case Expression::Id::MemoryCopyId: { PUSH(MemoryCopy, dest); PUSH(MemoryCopy, source); PUSH(MemoryCopy, size); break; } case Expression::Id::MemoryFillId: { PUSH(MemoryFill, dest); PUSH(MemoryFill, value); PUSH(MemoryFill, size); break; } case Expression::Id::ConstId: { auto* c = curr->cast<Const>(); hash(c->type); hash(std::hash<Literal>()(c->value)); break; } case Expression::Id::UnaryId: { HASH(Unary, op); PUSH(Unary, value); break; } case Expression::Id::BinaryId: { HASH(Binary, op); PUSH(Binary, left); PUSH(Binary, right); break; } case Expression::Id::SelectId: { PUSH(Select, ifTrue); PUSH(Select, ifFalse); PUSH(Select, condition); break; } case Expression::Id::DropId: { PUSH(Drop, value); break; } case Expression::Id::ReturnId: { PUSH(Return, value); break; } case Expression::Id::HostId: { HASH(Host, op); HASH_NAME(Host, nameOperand); HASH(Host, operands.size()); for (Index i = 0; i < curr->cast<Host>()->operands.size(); i++) { PUSH(Host, operands[i]); } break; } case Expression::Id::NopId: { break; } case Expression::Id::UnreachableId: { break; } case Expression::Id::InvalidId: case Expression::Id::NumExpressionIds: { WASM_UNREACHABLE(); } } #undef HASH #undef PUSH } return digest; } } // namespace wasm
18,040
5,843
#include "clientview.h" ClientView::ClientView(QWidget *parent) : QTableView(parent) { }
91
35
#pragma once #include "internal-ptr.hpp" #include "vertex.hpp" #include <vector> namespace ast { struct Mesh { Mesh(const std::vector<ast::Vertex>& vertices, const std::vector<uint32_t>& indices); const std::vector<ast::Vertex>& getVertices() const; const std::vector<uint32_t>& getIndices() const; const uint32_t& getNumVertices() const; const uint32_t& getNumIndices() const; private: struct Internal; ast::internal_ptr<Internal> internal; }; } // namespace ast
543
177
version https://git-lfs.github.com/spec/v1 oid sha256:a88a7b61d2bf7615571ada8de82e2cf5034f40407f98a48fadeaad6849143d52 size 2097
129
88
/******************************************************************************* WEOS - Wrapper for embedded operating systems Copyright (c) 2013-2016, Manuel Freiberger 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. 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 <atomic.hpp> #include "../common/testutils.hpp" #include "gtest/gtest.h" TEST(atomic_flag, default_construction) { weos::atomic_flag flag; (void)flag; } TEST(atomic_flag, initialization) { weos::atomic_flag flag = ATOMIC_FLAG_INIT; (void)flag; } TEST(atomic_flag, test_and_set) { weos::atomic_flag flag = ATOMIC_FLAG_INIT; ASSERT_FALSE(flag.test_and_set()); ASSERT_TRUE(flag.test_and_set()); flag.clear(); ASSERT_FALSE(flag.test_and_set()); ASSERT_TRUE(flag.test_and_set()); } TEST(atomic_int, default_construction) { weos::atomic_int x; (void)x; } TEST(atomic_int, construct_with_value) { int value; weos::atomic_int x(68); value = x; ASSERT_EQ(68, value); } TEST(atomic_int, load_and_store) { int value; weos::atomic_int x(68); value = x.load(); ASSERT_EQ(68, value); x.store(21); value = x.load(); ASSERT_EQ(21, value); value = x; ASSERT_EQ(21, value); } TEST(atomic_int, exchange) { int value; weos::atomic_int x(68); value = x.load(); ASSERT_EQ(68, value); value = x.exchange(21); ASSERT_EQ(68, value); value = x; ASSERT_EQ(21, value); } TEST(atomic_int, fetch_X) { int value; weos::atomic_int x(68); value = x.fetch_add(3); ASSERT_EQ(68, value); value = x.fetch_sub(5); ASSERT_EQ(71, value); value = x.fetch_and(64); ASSERT_EQ(66, value); value = x.fetch_or(17); ASSERT_EQ(64, value); value = x.fetch_xor(66); ASSERT_EQ(81, value); value = x; ASSERT_EQ(19, value); } TEST(atomic_int, compare_exchange_strong) { int expected = 66; bool exchanged; weos::atomic_int x(68); exchanged = x.compare_exchange_strong(expected, 77); ASSERT_FALSE(exchanged); ASSERT_EQ(68, expected); ASSERT_EQ(68, int(x)); exchanged = x.compare_exchange_strong(expected, 77); ASSERT_TRUE(exchanged); ASSERT_EQ(68, expected); ASSERT_EQ(77, int(x)); } TEST(atomic_int, operators) { weos::atomic_int x(68); ASSERT_EQ(68, int(x)); x = 77; ASSERT_EQ(77, int(x)); }
3,672
1,437
// Copyright (C) 2018-2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #pragma once #include "common_test_utils/test_common.hpp" #include "shared_test_classes/base/layer_test_utils.hpp" #include <ie_core.hpp> namespace SubgraphTestsDefinitions { typedef std::tuple< ngraph::helpers::MemoryTransformation, // Apply Memory transformation std::string, // Target device name InferenceEngine::Precision, // Network precision size_t, // Input size size_t, // Hidden size std::map<std::string, std::string> // Configuration > memoryLSTMCellParams; class MemoryLSTMCellTest : virtual public LayerTestsUtils::LayerTestsCommon, public testing::WithParamInterface<memoryLSTMCellParams> { private: // you have to Unroll TI manually and remove memory untill ngraph supports it // since we switching models we need to generate and save weights biases and inputs in SetUp void switchToNgraphFriendlyModel(); void CreatePureTensorIteratorModel(); void InitMemory(); void ApplyLowLatency(); ngraph::helpers::MemoryTransformation transformation; std::vector<float> input_bias; std::vector<float> input_weights; std::vector<float> hidden_memory_init; std::vector<float> cell_memory_init; std::vector<float> weights_vals; std::vector<float> reccurrenceWeights_vals; std::vector<float> bias_vals; protected: void SetUp() override; void Run() override; void LoadNetwork() override; void Infer() override; public: static std::string getTestCaseName(const testing::TestParamInfo<memoryLSTMCellParams> &obj); }; } // namespace SubgraphTestsDefinitions
1,742
513
// 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. #include "android_webview/browser/hardware_renderer.h" #include "android_webview/browser/aw_gl_surface.h" #include "android_webview/browser/deferred_gpu_command_service.h" #include "android_webview/browser/parent_output_surface.h" #include "android_webview/browser/shared_renderer_state.h" #include "android_webview/public/browser/draw_gl.h" #include "base/auto_reset.h" #include "base/debug/trace_event.h" #include "base/strings/string_number_conversions.h" #include "cc/layers/delegated_frame_provider.h" #include "cc/layers/delegated_renderer_layer.h" #include "cc/layers/layer.h" #include "cc/output/compositor_frame.h" #include "cc/output/output_surface.h" #include "cc/trees/layer_tree_host.h" #include "cc/trees/layer_tree_settings.h" #include "gpu/command_buffer/client/gl_in_process_context.h" #include "gpu/command_buffer/common/gles2_cmd_utils.h" #include "ui/gfx/frame_time.h" #include "ui/gfx/geometry/rect_conversions.h" #include "ui/gfx/geometry/rect_f.h" #include "ui/gfx/transform.h" #include "ui/gl/gl_bindings.h" #include "webkit/common/gpu/context_provider_in_process.h" #include "webkit/common/gpu/webgraphicscontext3d_in_process_command_buffer_impl.h" namespace android_webview { namespace { using webkit::gpu::WebGraphicsContext3DInProcessCommandBufferImpl; using webkit::gpu::WebGraphicsContext3DImpl; scoped_refptr<cc::ContextProvider> CreateContext( scoped_refptr<gfx::GLSurface> surface, scoped_refptr<gpu::InProcessCommandBuffer::Service> service, gpu::GLInProcessContext* share_context) { const gfx::GpuPreference gpu_preference = gfx::PreferDiscreteGpu; blink::WebGraphicsContext3D::Attributes attributes; attributes.antialias = false; attributes.depth = false; attributes.stencil = false; attributes.shareResources = true; attributes.noAutomaticFlushes = true; gpu::gles2::ContextCreationAttribHelper attribs_for_gles2; WebGraphicsContext3DImpl::ConvertAttributes( attributes, &attribs_for_gles2); attribs_for_gles2.lose_context_when_out_of_memory = true; scoped_ptr<gpu::GLInProcessContext> context(gpu::GLInProcessContext::Create( service, surface, surface->IsOffscreen(), gfx::kNullAcceleratedWidget, surface->GetSize(), share_context, false /* share_resources */, attribs_for_gles2, gpu_preference, gpu::GLInProcessContextSharedMemoryLimits())); DCHECK(context.get()); return webkit::gpu::ContextProviderInProcess::Create( WebGraphicsContext3DInProcessCommandBufferImpl::WrapContext( context.Pass(), attributes), "Parent-Compositor"); } } // namespace HardwareRenderer::HardwareRenderer(SharedRendererState* state) : shared_renderer_state_(state), last_egl_context_(eglGetCurrentContext()), stencil_enabled_(false), viewport_clip_valid_for_dcheck_(false), gl_surface_(new AwGLSurface), root_layer_(cc::Layer::Create()), resource_collection_(new cc::DelegatedFrameResourceCollection), output_surface_(NULL) { DCHECK(last_egl_context_); resource_collection_->SetClient(this); cc::LayerTreeSettings settings; // Should be kept in sync with compositor_impl_android.cc. settings.allow_antialiasing = false; settings.highp_threshold_min = 2048; // Webview does not own the surface so should not clear it. settings.should_clear_root_render_pass = false; // TODO(enne): Update this this compositor to use a synchronous scheduler. settings.single_thread_proxy_scheduler = false; layer_tree_host_ = cc::LayerTreeHost::CreateSingleThreaded(this, this, NULL, settings, NULL); layer_tree_host_->SetRootLayer(root_layer_); layer_tree_host_->SetLayerTreeHostClientReady(); layer_tree_host_->set_has_transparent_background(true); } HardwareRenderer::~HardwareRenderer() { // Must reset everything before |resource_collection_| to ensure all // resources are returned before resetting |resource_collection_| client. layer_tree_host_.reset(); root_layer_ = NULL; delegated_layer_ = NULL; frame_provider_ = NULL; #if DCHECK_IS_ON // Check collection is empty. cc::ReturnedResourceArray returned_resources; resource_collection_->TakeUnusedResourcesForChildCompositor( &returned_resources); DCHECK_EQ(0u, returned_resources.size()); #endif // DCHECK_IS_ON resource_collection_->SetClient(NULL); // Reset draw constraints. shared_renderer_state_->UpdateDrawConstraints( ParentCompositorDrawConstraints()); } void HardwareRenderer::DidBeginMainFrame() { // This is called after OutputSurface is created, but before the impl frame // starts. We set the draw constraints here. DCHECK(output_surface_); DCHECK(viewport_clip_valid_for_dcheck_); output_surface_->SetExternalStencilTest(stencil_enabled_); output_surface_->SetDrawConstraints(viewport_, clip_); } void HardwareRenderer::CommitFrame() { scoped_ptr<DrawGLInput> input = shared_renderer_state_->PassDrawGLInput(); if (!input.get()) { DLOG(WARNING) << "No frame to commit"; return; } DCHECK(!input->frame.gl_frame_data); DCHECK(!input->frame.software_frame_data); // DelegatedRendererLayerImpl applies the inverse device_scale_factor of the // renderer frame, assuming that the browser compositor will scale // it back up to device scale. But on Android we put our browser layers in // physical pixels and set our browser CC device_scale_factor to 1, so this // suppresses the transform. input->frame.delegated_frame_data->device_scale_factor = 1.0f; gfx::Size frame_size = input->frame.delegated_frame_data->render_pass_list.back() ->output_rect.size(); bool size_changed = frame_size != frame_size_; frame_size_ = frame_size; scroll_offset_ = input->scroll_offset; if (!frame_provider_ || size_changed) { if (delegated_layer_) { delegated_layer_->RemoveFromParent(); } frame_provider_ = new cc::DelegatedFrameProvider( resource_collection_.get(), input->frame.delegated_frame_data.Pass()); delegated_layer_ = cc::DelegatedRendererLayer::Create(frame_provider_); delegated_layer_->SetBounds(gfx::Size(input->width, input->height)); delegated_layer_->SetIsDrawable(true); root_layer_->AddChild(delegated_layer_); } else { frame_provider_->SetFrameData(input->frame.delegated_frame_data.Pass()); } } void HardwareRenderer::DrawGL(bool stencil_enabled, int framebuffer_binding_ext, AwDrawGLInfo* draw_info) { TRACE_EVENT0("android_webview", "HardwareRenderer::DrawGL"); // We need to watch if the current Android context has changed and enforce // a clean-up in the compositor. EGLContext current_context = eglGetCurrentContext(); if (!current_context) { DLOG(ERROR) << "DrawGL called without EGLContext"; return; } if (!delegated_layer_.get()) { DLOG(ERROR) << "No frame committed"; return; } // TODO(boliu): Handle context loss. if (last_egl_context_ != current_context) DLOG(WARNING) << "EGLContextChanged"; gfx::Transform transform(gfx::Transform::kSkipInitialization); transform.matrix().setColMajorf(draw_info->transform); transform.Translate(scroll_offset_.x(), scroll_offset_.y()); // Need to post the new transform matrix back to child compositor // because there is no onDraw during a Render Thread animation, and child // compositor might not have the tiles rasterized as the animation goes on. ParentCompositorDrawConstraints draw_constraints( draw_info->is_layer, transform, gfx::Rect(viewport_)); if (!draw_constraints_.Equals(draw_constraints)) { draw_constraints_ = draw_constraints; shared_renderer_state_->PostExternalDrawConstraintsToChildCompositor( draw_constraints); } viewport_.SetSize(draw_info->width, draw_info->height); layer_tree_host_->SetViewportSize(viewport_); clip_.SetRect(draw_info->clip_left, draw_info->clip_top, draw_info->clip_right - draw_info->clip_left, draw_info->clip_bottom - draw_info->clip_top); stencil_enabled_ = stencil_enabled; delegated_layer_->SetTransform(transform); gl_surface_->SetBackingFrameBufferObject(framebuffer_binding_ext); { base::AutoReset<bool> frame_resetter(&viewport_clip_valid_for_dcheck_, true); layer_tree_host_->SetNeedsRedrawRect(clip_); layer_tree_host_->Composite(gfx::FrameTime::Now()); } gl_surface_->ResetBackingFrameBufferObject(); } scoped_ptr<cc::OutputSurface> HardwareRenderer::CreateOutputSurface( bool fallback) { // Android webview does not support losing output surface. DCHECK(!fallback); scoped_refptr<cc::ContextProvider> context_provider = CreateContext(gl_surface_, DeferredGpuCommandService::GetInstance(), shared_renderer_state_->GetSharedContext()); scoped_ptr<ParentOutputSurface> output_surface_holder( new ParentOutputSurface(context_provider)); output_surface_ = output_surface_holder.get(); return output_surface_holder.PassAs<cc::OutputSurface>(); } void HardwareRenderer::UnusedResourcesAreAvailable() { cc::ReturnedResourceArray returned_resources; resource_collection_->TakeUnusedResourcesForChildCompositor( &returned_resources); shared_renderer_state_->InsertReturnedResources(returned_resources); } } // namespace android_webview
9,617
3,080
/** * Copyright (C) 2012 ciere consulting, ciere.com * * 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 "ciere/json/value.hpp" #include "ciere/json/parser/grammar_def.hpp" #include <boost/spirit/include/support_istream_iterator.hpp> #include <string> #include <vector> using string_iter_t = std::string::const_iterator; using vector_uint8_iter_t = std::vector<uint8_t>::const_iterator; template struct ciere::json::parser::grammar<string_iter_t>; template struct ciere::json::parser::grammar<boost::spirit::istream_iterator>; template struct ciere::json::parser::grammar<vector_uint8_iter_t>;
726
261
#include "vrclient_private.h" #include "vrclient_defs.h" #include "openvr_v1.0.1/openvr.h" using namespace vr; extern "C" { #include "struct_converters.h" } #include "cppIVRApplications_IVRApplications_005.h" #ifdef __cplusplus extern "C" { #endif vr::EVRApplicationError cppIVRApplications_IVRApplications_005_AddApplicationManifest(void *linux_side, const char * pchApplicationManifestFullPath, bool bTemporary) { return ((IVRApplications*)linux_side)->AddApplicationManifest((const char *)pchApplicationManifestFullPath, (bool)bTemporary); } vr::EVRApplicationError cppIVRApplications_IVRApplications_005_RemoveApplicationManifest(void *linux_side, const char * pchApplicationManifestFullPath) { return ((IVRApplications*)linux_side)->RemoveApplicationManifest((const char *)pchApplicationManifestFullPath); } bool cppIVRApplications_IVRApplications_005_IsApplicationInstalled(void *linux_side, const char * pchAppKey) { return ((IVRApplications*)linux_side)->IsApplicationInstalled((const char *)pchAppKey); } uint32_t cppIVRApplications_IVRApplications_005_GetApplicationCount(void *linux_side) { return ((IVRApplications*)linux_side)->GetApplicationCount(); } vr::EVRApplicationError cppIVRApplications_IVRApplications_005_GetApplicationKeyByIndex(void *linux_side, uint32_t unApplicationIndex, char * pchAppKeyBuffer, uint32_t unAppKeyBufferLen) { return ((IVRApplications*)linux_side)->GetApplicationKeyByIndex((uint32_t)unApplicationIndex, (char *)pchAppKeyBuffer, (uint32_t)unAppKeyBufferLen); } vr::EVRApplicationError cppIVRApplications_IVRApplications_005_GetApplicationKeyByProcessId(void *linux_side, uint32_t unProcessId, char * pchAppKeyBuffer, uint32_t unAppKeyBufferLen) { return ((IVRApplications*)linux_side)->GetApplicationKeyByProcessId((uint32_t)unProcessId, (char *)pchAppKeyBuffer, (uint32_t)unAppKeyBufferLen); } vr::EVRApplicationError cppIVRApplications_IVRApplications_005_LaunchApplication(void *linux_side, const char * pchAppKey) { return ((IVRApplications*)linux_side)->LaunchApplication((const char *)pchAppKey); } vr::EVRApplicationError cppIVRApplications_IVRApplications_005_LaunchTemplateApplication(void *linux_side, const char * pchTemplateAppKey, const char * pchNewAppKey, AppOverrideKeys_t * pKeys, uint32_t unKeys) { return ((IVRApplications*)linux_side)->LaunchTemplateApplication((const char *)pchTemplateAppKey, (const char *)pchNewAppKey, (const vr::AppOverrideKeys_t *)pKeys, (uint32_t)unKeys); } vr::EVRApplicationError cppIVRApplications_IVRApplications_005_LaunchDashboardOverlay(void *linux_side, const char * pchAppKey) { return ((IVRApplications*)linux_side)->LaunchDashboardOverlay((const char *)pchAppKey); } bool cppIVRApplications_IVRApplications_005_CancelApplicationLaunch(void *linux_side, const char * pchAppKey) { return ((IVRApplications*)linux_side)->CancelApplicationLaunch((const char *)pchAppKey); } vr::EVRApplicationError cppIVRApplications_IVRApplications_005_IdentifyApplication(void *linux_side, uint32_t unProcessId, const char * pchAppKey) { return ((IVRApplications*)linux_side)->IdentifyApplication((uint32_t)unProcessId, (const char *)pchAppKey); } uint32_t cppIVRApplications_IVRApplications_005_GetApplicationProcessId(void *linux_side, const char * pchAppKey) { return ((IVRApplications*)linux_side)->GetApplicationProcessId((const char *)pchAppKey); } const char * cppIVRApplications_IVRApplications_005_GetApplicationsErrorNameFromEnum(void *linux_side, EVRApplicationError error) { return ((IVRApplications*)linux_side)->GetApplicationsErrorNameFromEnum((vr::EVRApplicationError)error); } uint32_t cppIVRApplications_IVRApplications_005_GetApplicationPropertyString(void *linux_side, const char * pchAppKey, EVRApplicationProperty eProperty, char * pchPropertyValueBuffer, uint32_t unPropertyValueBufferLen, EVRApplicationError * peError) { return ((IVRApplications*)linux_side)->GetApplicationPropertyString((const char *)pchAppKey, (vr::EVRApplicationProperty)eProperty, (char *)pchPropertyValueBuffer, (uint32_t)unPropertyValueBufferLen, (vr::EVRApplicationError *)peError); } bool cppIVRApplications_IVRApplications_005_GetApplicationPropertyBool(void *linux_side, const char * pchAppKey, EVRApplicationProperty eProperty, EVRApplicationError * peError) { return ((IVRApplications*)linux_side)->GetApplicationPropertyBool((const char *)pchAppKey, (vr::EVRApplicationProperty)eProperty, (vr::EVRApplicationError *)peError); } uint64_t cppIVRApplications_IVRApplications_005_GetApplicationPropertyUint64(void *linux_side, const char * pchAppKey, EVRApplicationProperty eProperty, EVRApplicationError * peError) { return ((IVRApplications*)linux_side)->GetApplicationPropertyUint64((const char *)pchAppKey, (vr::EVRApplicationProperty)eProperty, (vr::EVRApplicationError *)peError); } vr::EVRApplicationError cppIVRApplications_IVRApplications_005_SetApplicationAutoLaunch(void *linux_side, const char * pchAppKey, bool bAutoLaunch) { return ((IVRApplications*)linux_side)->SetApplicationAutoLaunch((const char *)pchAppKey, (bool)bAutoLaunch); } bool cppIVRApplications_IVRApplications_005_GetApplicationAutoLaunch(void *linux_side, const char * pchAppKey) { return ((IVRApplications*)linux_side)->GetApplicationAutoLaunch((const char *)pchAppKey); } vr::EVRApplicationError cppIVRApplications_IVRApplications_005_GetStartingApplication(void *linux_side, char * pchAppKeyBuffer, uint32_t unAppKeyBufferLen) { return ((IVRApplications*)linux_side)->GetStartingApplication((char *)pchAppKeyBuffer, (uint32_t)unAppKeyBufferLen); } vr::EVRApplicationTransitionState cppIVRApplications_IVRApplications_005_GetTransitionState(void *linux_side) { return ((IVRApplications*)linux_side)->GetTransitionState(); } vr::EVRApplicationError cppIVRApplications_IVRApplications_005_PerformApplicationPrelaunchCheck(void *linux_side, const char * pchAppKey) { return ((IVRApplications*)linux_side)->PerformApplicationPrelaunchCheck((const char *)pchAppKey); } const char * cppIVRApplications_IVRApplications_005_GetApplicationsTransitionStateNameFromEnum(void *linux_side, EVRApplicationTransitionState state) { return ((IVRApplications*)linux_side)->GetApplicationsTransitionStateNameFromEnum((vr::EVRApplicationTransitionState)state); } bool cppIVRApplications_IVRApplications_005_IsQuitUserPromptRequested(void *linux_side) { return ((IVRApplications*)linux_side)->IsQuitUserPromptRequested(); } vr::EVRApplicationError cppIVRApplications_IVRApplications_005_LaunchInternalProcess(void *linux_side, const char * pchBinaryPath, const char * pchArguments, const char * pchWorkingDirectory) { return ((IVRApplications*)linux_side)->LaunchInternalProcess((const char *)pchBinaryPath, (const char *)pchArguments, (const char *)pchWorkingDirectory); } #ifdef __cplusplus } #endif
6,867
2,251
// file : examples/cxx/tree/library/driver.cxx // author : Boris Kolpackov <boris@codesynthesis.com> // copyright : not copyrighted - public domain #include <memory> // std::auto_ptr #include <iostream> #include "library.hpp" #define SCHEMA_NAMESPACE_FOR_LEESA library #include "LEESA.h" using std::cerr; using std::endl; library::catalog::book_sequence foo (const library::catalog & c) { using namespace LEESA; using namespace library; BOOST_AUTO(expr, catalog() >> book()); catalog::book_sequence b = evaluate(c, expr); return b; } bool starts_with_s (library::name const & n) { return (n[0] == 'S'); } void print (library::name const & n) { std::cout << n << endl; } LEESA::ContainerGen<library::name>::type bar (const library::catalog & c) { using namespace LEESA; using namespace library; BOOST_AUTO(expr, catalog() >> book() >> author() >> name() >> ForEach(name(), print) >> Select(name(), starts_with_s)); ContainerGen<name>::type names = evaluate(c, expr); return names; } int main (int argc, char* argv[]) { if (argc != 2) { cerr << "usage: " << argv[0] << " library.xml" << endl; return 1; } try { using namespace library; // Read in the XML file and obtain its object model. // std::auto_ptr<catalog> c (catalog_ (argv[1])); catalog::book_sequence b1 = foo (*c); // Let's print what we've got. // for (catalog::book_const_iterator bi (b1.begin ()); bi != b1.end (); ++bi) { cerr << endl << "ID : " << bi->id () << endl << "ISBN : " << bi->isbn () << endl << "Title : " << bi->title () << endl << "Genre : " << bi->genre () << endl; for (book::author_const_iterator ai (bi->author ().begin ()); ai != bi->author ().end (); ++ai) { cerr << "Author : " << ai->name () << endl; cerr << " Born : " << ai->born () << endl; if (ai->died ()) cerr << " Died : " << *ai->died () << endl; //if (ai->recommends ()) // cerr << " Recommends : " << (*ai->recommends ())->title () << endl; } cerr << "Available : " << std::boolalpha << bi->available () << endl; } LEESA::ContainerGen<name>::type names = bar(*c); for (LEESA::ContainerGen<name>::type::const_iterator i(names.begin()); i != names.end(); ++i) { std::cout << *i << endl; } return 0; } catch (const xml_schema::exception& e) { cerr << e << endl; return 1; } }
2,645
916
#include "Hierarchy.hpp" #include "Scene/Component/Hierarchy.hpp" #include "Scene/Component/Tag.hpp" #include "Scene/Component/Transform.hpp" #include "Scene/Entity.hpp" #include "Editor/Editor.hpp" #include <imgui.h> namespace Ilum::panel { inline void delete_node(Entity entity) { if (!entity) { return; } auto child = Entity(entity.getComponent<cmpt::Hierarchy>().first); auto sibling = child ? Entity(child.getComponent<cmpt::Hierarchy>().next) : Entity(); while (sibling) { auto tmp = Entity(sibling.getComponent<cmpt::Hierarchy>().next); delete_node(sibling); sibling = tmp; } delete_node(child); entity.destroy(); } inline bool is_parent_of(Entity lhs, Entity rhs) { auto parent = Entity(rhs.getComponent<cmpt::Hierarchy>().parent); while (parent) { if (parent == lhs) { return true; } parent = Entity(parent.getComponent<cmpt::Hierarchy>().parent); } return false; } inline void set_as_son(Entity new_parent, Entity new_son) { if (new_parent && is_parent_of(new_son, new_parent)) { return; } auto &h2 = new_son.getComponent<cmpt::Hierarchy>(); if (h2.next != entt::null) { Entity(h2.next).getComponent<cmpt::Hierarchy>().prev = h2.prev; } if (h2.prev != entt::null) { Entity(h2.prev).getComponent<cmpt::Hierarchy>().next = h2.next; } if (h2.parent != entt::null && new_son == Entity(h2.parent).getComponent<cmpt::Hierarchy>().first) { Entity(h2.parent).getComponent<cmpt::Hierarchy>().first = h2.next; } h2.next = new_parent ? new_parent.getComponent<cmpt::Hierarchy>().first : entt::null; h2.prev = entt::null; h2.parent = new_parent ? new_parent.getHandle() : entt::null; if (new_parent && new_parent.getComponent<cmpt::Hierarchy>().first != entt::null) { Entity(new_parent.getComponent<cmpt::Hierarchy>().first).getComponent<cmpt::Hierarchy>().prev = new_son; } if (new_parent) { new_parent.getComponent<cmpt::Hierarchy>().first = new_son; } } inline void draw_node(Entity entity) { if (!entity) { return; } auto &tag = entity.getComponent<cmpt::Tag>().name; bool has_child = entity.hasComponent<cmpt::Hierarchy>() && entity.getComponent<cmpt::Hierarchy>().first != entt::null; // Setting up ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(5, 5)); ImGuiTreeNodeFlags flags = ImGuiTreeNodeFlags_FramePadding | ImGuiTreeNodeFlags_DefaultOpen | (Editor::instance()->getSelect() == entity ? ImGuiTreeNodeFlags_Selected : 0) | (has_child ? 0 : ImGuiTreeNodeFlags_Leaf); bool open = ImGui::TreeNodeEx(std::to_string(entity).c_str(), flags, "%s", tag.c_str()); ImGui::PopStyleVar(); // Delete entity ImGui::PushID(std::to_string(entity).c_str()); bool entity_deleted = false; if (ImGui::BeginPopupContextItem(std::to_string(entity).c_str())) { if (ImGui::MenuItem("Delete Entity")) { entity_deleted = true; } ImGui::EndPopup(); } ImGui::PopID(); // Select entity if (ImGui::IsItemClicked()) { Editor::instance()->select(entity); } // Drag and drop if (ImGui::BeginDragDropSource()) { if (entity.hasComponent<cmpt::Hierarchy>()) { ImGui::SetDragDropPayload("Entity", &entity, sizeof(Entity)); } ImGui::EndDragDropSource(); } if (ImGui::BeginDragDropTarget()) { if (const auto *pay_load = ImGui::AcceptDragDropPayload("Entity")) { ASSERT(pay_load->DataSize == sizeof(Entity)); set_as_son(entity, *static_cast<Entity *>(pay_load->Data)); entity.getComponent<cmpt::Transform>().update = true; static_cast<Entity *>(pay_load->Data)->getComponent<cmpt::Transform>().update = true; } ImGui::EndDragDropTarget(); } // Recursively open children entities if (open) { if (has_child) { auto child = Entity(entity.getComponent<cmpt::Hierarchy>().first); while (child) { draw_node(child); if (child) { child = Entity(child.getComponent<cmpt::Hierarchy>().next); } } } ImGui::TreePop(); } // Delete callback if (entity_deleted) { if (Entity(entity.getComponent<cmpt::Hierarchy>().prev)) { Entity(entity.getComponent<cmpt::Hierarchy>().prev).getComponent<cmpt::Hierarchy>().next = entity.getComponent<cmpt::Hierarchy>().next; } if (Entity(entity.getComponent<cmpt::Hierarchy>().next)) { Entity(entity.getComponent<cmpt::Hierarchy>().next).getComponent<cmpt::Hierarchy>().prev = entity.getComponent<cmpt::Hierarchy>().prev; } if (Entity(entity.getComponent<cmpt::Hierarchy>().parent) && entity == Entity(entity.getComponent<cmpt::Hierarchy>().parent).getComponent<cmpt::Hierarchy>().first) { Entity(entity.getComponent<cmpt::Hierarchy>().parent).getComponent<cmpt::Hierarchy>().first = entity.getComponent<cmpt::Hierarchy>().next; } delete_node(entity); if (Editor::instance()->getSelect() == entity) { Editor::instance()->select(Entity()); } } } Hierarchy::Hierarchy() { m_name = "Hierarchy"; } void Hierarchy::draw(float delta_time) { ImGui::Begin("Scene Hierarchy", &active); if (ImGui::BeginDragDropTarget()) { if (const auto *pay_load = ImGui::AcceptDragDropPayload("Entity")) { ASSERT(pay_load->DataSize == sizeof(Entity)); set_as_son(Entity(), *static_cast<Entity *>(pay_load->Data)); static_cast<Entity *>(pay_load->Data)->getComponent<cmpt::Transform>().update = true; } } Scene::instance()->getRegistry().each([&](auto entity_id) { if (Entity(entity_id) && Entity(entity_id).getComponent<cmpt::Hierarchy>().parent == entt::null) { draw_node(Entity(entity_id)); } }); if (ImGui::IsMouseDown(ImGuiMouseButton_Left) && ImGui::IsWindowHovered()) { Editor::instance()->select(Entity()); } // Right-click on blank space if (ImGui::BeginPopupContextWindow(0, 1, false)) { if (ImGui::MenuItem("New Entity")) { Scene::instance()->createEntity("Untitled Entity"); } ImGui::EndPopup(); } ImGui::End(); } } // namespace Ilum::panel
5,886
2,315