hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f6ff86c2b5f8089466e0fbfb818e2b755a2afe86 | 28,752 | cc | C++ | deps/boringssl/crypto/trust_token/trust_token_test.cc | Koyonyong/my_quic_hevc | 4654e7ae27366680980a0b0bfc61a30b008a655b | [
"BSD-2-Clause"
] | 3 | 2020-08-11T10:00:20.000Z | 2021-05-18T03:53:21.000Z | deps/boringssl/crypto/trust_token/trust_token_test.cc | Koyonyong/my_quic_hevc | 4654e7ae27366680980a0b0bfc61a30b008a655b | [
"BSD-2-Clause"
] | null | null | null | deps/boringssl/crypto/trust_token/trust_token_test.cc | Koyonyong/my_quic_hevc | 4654e7ae27366680980a0b0bfc61a30b008a655b | [
"BSD-2-Clause"
] | 4 | 2020-08-16T12:13:08.000Z | 2022-03-28T12:08:11.000Z | /* Copyright (c) 2020, Google Inc.
*
* 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 <stdio.h>
#include <string.h>
#include <time.h>
#include <algorithm>
#include <limits>
#include <string>
#include <tuple>
#include <utility>
#include <vector>
#include <gtest/gtest.h>
#include <openssl/bytestring.h>
#include <openssl/curve25519.h>
#include <openssl/evp.h>
#include <openssl/mem.h>
#include <openssl/rand.h>
#include <openssl/sha.h>
#include <openssl/trust_token.h>
#include "../ec_extra/internal.h"
#include "../fipsmodule/ec/internal.h"
#include "../internal.h"
#include "../test/test_util.h"
#include "internal.h"
BSSL_NAMESPACE_BEGIN
namespace {
TEST(TrustTokenTest, KeyGenExp1) {
uint8_t priv_key[TRUST_TOKEN_MAX_PRIVATE_KEY_SIZE];
uint8_t pub_key[TRUST_TOKEN_MAX_PUBLIC_KEY_SIZE];
size_t priv_key_len, pub_key_len;
ASSERT_TRUE(TRUST_TOKEN_generate_key(
TRUST_TOKEN_experiment_v1(), priv_key, &priv_key_len,
TRUST_TOKEN_MAX_PRIVATE_KEY_SIZE, pub_key, &pub_key_len,
TRUST_TOKEN_MAX_PUBLIC_KEY_SIZE, 0x0001));
ASSERT_EQ(292u, priv_key_len);
ASSERT_EQ(301u, pub_key_len);
}
// Test that H in |TRUST_TOKEN_experiment_v1| was computed correctly.
TEST(TrustTokenTest, HExp1) {
const EC_GROUP *group = EC_GROUP_new_by_curve_name(NID_secp384r1);
ASSERT_TRUE(group);
const uint8_t kHGen[] = "generator";
const uint8_t kHLabel[] = "PMBTokens Experiment V1 HashH";
bssl::UniquePtr<EC_POINT> expected_h(EC_POINT_new(group));
ASSERT_TRUE(expected_h);
ASSERT_TRUE(ec_hash_to_curve_p384_xmd_sha512_sswu_draft07(
group, &expected_h->raw, kHLabel, sizeof(kHLabel), kHGen, sizeof(kHGen)));
uint8_t expected_bytes[1 + 2 * EC_MAX_BYTES];
size_t expected_len =
EC_POINT_point2oct(group, expected_h.get(), POINT_CONVERSION_UNCOMPRESSED,
expected_bytes, sizeof(expected_bytes), nullptr);
uint8_t h[97];
ASSERT_TRUE(pmbtoken_exp1_get_h_for_testing(h));
EXPECT_EQ(Bytes(h), Bytes(expected_bytes, expected_len));
}
static std::vector<const TRUST_TOKEN_METHOD *> AllMethods() {
return {TRUST_TOKEN_experiment_v1()};
}
class TrustTokenProtocolTestBase : public ::testing::Test {
public:
explicit TrustTokenProtocolTestBase(const TRUST_TOKEN_METHOD *method)
: method_(method) {}
// KeyID returns the key ID associated with key index |i|.
static uint32_t KeyID(size_t i) {
// Use a different value from the indices to that we do not mix them up.
return 7 + i;
}
const TRUST_TOKEN_METHOD *method() { return method_; }
protected:
void SetupContexts() {
client.reset(TRUST_TOKEN_CLIENT_new(method(), client_max_batchsize));
ASSERT_TRUE(client);
issuer.reset(TRUST_TOKEN_ISSUER_new(method(), issuer_max_batchsize));
ASSERT_TRUE(issuer);
for (size_t i = 0; i < 3; i++) {
uint8_t priv_key[TRUST_TOKEN_MAX_PRIVATE_KEY_SIZE];
uint8_t pub_key[TRUST_TOKEN_MAX_PUBLIC_KEY_SIZE];
size_t priv_key_len, pub_key_len, key_index;
ASSERT_TRUE(TRUST_TOKEN_generate_key(
method(), priv_key, &priv_key_len, TRUST_TOKEN_MAX_PRIVATE_KEY_SIZE,
pub_key, &pub_key_len, TRUST_TOKEN_MAX_PUBLIC_KEY_SIZE, KeyID(i)));
ASSERT_TRUE(TRUST_TOKEN_CLIENT_add_key(client.get(), &key_index, pub_key,
pub_key_len));
ASSERT_EQ(i, key_index);
ASSERT_TRUE(
TRUST_TOKEN_ISSUER_add_key(issuer.get(), priv_key, priv_key_len));
}
uint8_t public_key[32], private_key[64];
ED25519_keypair(public_key, private_key);
bssl::UniquePtr<EVP_PKEY> priv(EVP_PKEY_new_raw_private_key(
EVP_PKEY_ED25519, nullptr, private_key, 32));
ASSERT_TRUE(priv);
bssl::UniquePtr<EVP_PKEY> pub(
EVP_PKEY_new_raw_public_key(EVP_PKEY_ED25519, nullptr, public_key, 32));
ASSERT_TRUE(pub);
TRUST_TOKEN_CLIENT_set_srr_key(client.get(), pub.get());
TRUST_TOKEN_ISSUER_set_srr_key(issuer.get(), priv.get());
RAND_bytes(metadata_key, sizeof(metadata_key));
ASSERT_TRUE(TRUST_TOKEN_ISSUER_set_metadata_key(issuer.get(), metadata_key,
sizeof(metadata_key)));
}
const TRUST_TOKEN_METHOD *method_;
uint16_t client_max_batchsize = 10;
uint16_t issuer_max_batchsize = 10;
bssl::UniquePtr<TRUST_TOKEN_CLIENT> client;
bssl::UniquePtr<TRUST_TOKEN_ISSUER> issuer;
uint8_t metadata_key[32];
};
class TrustTokenProtocolTest
: public TrustTokenProtocolTestBase,
public testing::WithParamInterface<const TRUST_TOKEN_METHOD *> {
public:
TrustTokenProtocolTest() : TrustTokenProtocolTestBase(GetParam()) {}
};
INSTANTIATE_TEST_SUITE_P(TrustTokenAllProtocolTest, TrustTokenProtocolTest,
testing::ValuesIn(AllMethods()));
TEST_P(TrustTokenProtocolTest, InvalidToken) {
ASSERT_NO_FATAL_FAILURE(SetupContexts());
uint8_t *issue_msg = NULL, *issue_resp = NULL;
size_t msg_len, resp_len;
size_t key_index;
size_t tokens_issued;
ASSERT_TRUE(
TRUST_TOKEN_CLIENT_begin_issuance(client.get(), &issue_msg, &msg_len, 1));
bssl::UniquePtr<uint8_t> free_issue_msg(issue_msg);
ASSERT_TRUE(TRUST_TOKEN_ISSUER_issue(
issuer.get(), &issue_resp, &resp_len, &tokens_issued, issue_msg, msg_len,
/*public_metadata=*/KeyID(0), /*private_metadata=*/1,
/*max_issuance=*/10));
bssl::UniquePtr<uint8_t> free_msg(issue_resp);
bssl::UniquePtr<STACK_OF(TRUST_TOKEN)> tokens(
TRUST_TOKEN_CLIENT_finish_issuance(client.get(), &key_index, issue_resp,
resp_len));
ASSERT_TRUE(tokens);
for (TRUST_TOKEN *token : tokens.get()) {
// Corrupt the token.
token->data[0] ^= 0x42;
uint8_t *redeem_msg = NULL, *redeem_resp = NULL;
ASSERT_TRUE(TRUST_TOKEN_CLIENT_begin_redemption(
client.get(), &redeem_msg, &msg_len, token, NULL, 0, 0));
bssl::UniquePtr<uint8_t> free_redeem_msg(redeem_msg);
TRUST_TOKEN *rtoken;
uint8_t *client_data;
size_t client_data_len;
uint64_t redemption_time;
ASSERT_FALSE(TRUST_TOKEN_ISSUER_redeem(
issuer.get(), &redeem_resp, &resp_len, &rtoken, &client_data,
&client_data_len, &redemption_time, redeem_msg, msg_len, 600));
bssl::UniquePtr<uint8_t> free_redeem_resp(redeem_resp);
}
}
TEST_P(TrustTokenProtocolTest, TruncatedIssuanceRequest) {
ASSERT_NO_FATAL_FAILURE(SetupContexts());
uint8_t *issue_msg = NULL, *issue_resp = NULL;
size_t msg_len, resp_len;
ASSERT_TRUE(TRUST_TOKEN_CLIENT_begin_issuance(client.get(), &issue_msg,
&msg_len, 10));
bssl::UniquePtr<uint8_t> free_issue_msg(issue_msg);
msg_len = 10;
size_t tokens_issued;
ASSERT_FALSE(TRUST_TOKEN_ISSUER_issue(
issuer.get(), &issue_resp, &resp_len, &tokens_issued, issue_msg, msg_len,
/*public_metadata=*/KeyID(0), /*private_metadata=*/0,
/*max_issuance=*/10));
bssl::UniquePtr<uint8_t> free_msg(issue_resp);
}
TEST_P(TrustTokenProtocolTest, TruncatedIssuanceResponse) {
ASSERT_NO_FATAL_FAILURE(SetupContexts());
uint8_t *issue_msg = NULL, *issue_resp = NULL;
size_t msg_len, resp_len;
ASSERT_TRUE(TRUST_TOKEN_CLIENT_begin_issuance(client.get(), &issue_msg,
&msg_len, 10));
bssl::UniquePtr<uint8_t> free_issue_msg(issue_msg);
size_t tokens_issued;
ASSERT_TRUE(TRUST_TOKEN_ISSUER_issue(
issuer.get(), &issue_resp, &resp_len, &tokens_issued, issue_msg, msg_len,
/*public_metadata=*/KeyID(0), /*private_metadata=*/0,
/*max_issuance=*/10));
bssl::UniquePtr<uint8_t> free_msg(issue_resp);
resp_len = 10;
size_t key_index;
bssl::UniquePtr<STACK_OF(TRUST_TOKEN)> tokens(
TRUST_TOKEN_CLIENT_finish_issuance(client.get(), &key_index, issue_resp,
resp_len));
ASSERT_FALSE(tokens);
}
TEST_P(TrustTokenProtocolTest, ExtraDataIssuanceResponse) {
ASSERT_NO_FATAL_FAILURE(SetupContexts());
uint8_t *request = NULL, *response = NULL;
size_t request_len, response_len;
ASSERT_TRUE(TRUST_TOKEN_CLIENT_begin_issuance(client.get(), &request,
&request_len, 10));
bssl::UniquePtr<uint8_t> free_request(request);
size_t tokens_issued;
ASSERT_TRUE(TRUST_TOKEN_ISSUER_issue(issuer.get(), &response, &response_len,
&tokens_issued, request, request_len,
/*public_metadata=*/KeyID(0),
/*private_metadata=*/0,
/*max_issuance=*/10));
bssl::UniquePtr<uint8_t> free_response(response);
std::vector<uint8_t> response2(response, response + response_len);
response2.push_back(0);
size_t key_index;
bssl::UniquePtr<STACK_OF(TRUST_TOKEN)> tokens(
TRUST_TOKEN_CLIENT_finish_issuance(client.get(), &key_index,
response2.data(), response2.size()));
ASSERT_FALSE(tokens);
}
TEST_P(TrustTokenProtocolTest, TruncatedRedemptionRequest) {
ASSERT_NO_FATAL_FAILURE(SetupContexts());
uint8_t *issue_msg = NULL, *issue_resp = NULL;
size_t msg_len, resp_len;
ASSERT_TRUE(TRUST_TOKEN_CLIENT_begin_issuance(client.get(), &issue_msg,
&msg_len, 10));
bssl::UniquePtr<uint8_t> free_issue_msg(issue_msg);
size_t tokens_issued;
ASSERT_TRUE(TRUST_TOKEN_ISSUER_issue(
issuer.get(), &issue_resp, &resp_len, &tokens_issued, issue_msg, msg_len,
/*public_metadata=*/KeyID(0), /*private_metadata=*/0,
/*max_issuance=*/10));
bssl::UniquePtr<uint8_t> free_msg(issue_resp);
size_t key_index;
bssl::UniquePtr<STACK_OF(TRUST_TOKEN)> tokens(
TRUST_TOKEN_CLIENT_finish_issuance(client.get(), &key_index, issue_resp,
resp_len));
ASSERT_TRUE(tokens);
for (TRUST_TOKEN *token : tokens.get()) {
const uint8_t kClientData[] = "\x70TEST CLIENT DATA";
uint64_t kRedemptionTime = 13374242;
uint8_t *redeem_msg = NULL, *redeem_resp = NULL;
ASSERT_TRUE(TRUST_TOKEN_CLIENT_begin_redemption(
client.get(), &redeem_msg, &msg_len, token, kClientData,
sizeof(kClientData) - 1, kRedemptionTime));
bssl::UniquePtr<uint8_t> free_redeem_msg(redeem_msg);
msg_len = 10;
TRUST_TOKEN *rtoken;
uint8_t *client_data;
size_t client_data_len;
uint64_t redemption_time;
ASSERT_FALSE(TRUST_TOKEN_ISSUER_redeem(
issuer.get(), &redeem_resp, &resp_len, &rtoken, &client_data,
&client_data_len, &redemption_time, redeem_msg, msg_len, 600));
}
}
TEST_P(TrustTokenProtocolTest, TruncatedRedemptionResponse) {
ASSERT_NO_FATAL_FAILURE(SetupContexts());
uint8_t *issue_msg = NULL, *issue_resp = NULL;
size_t msg_len, resp_len;
ASSERT_TRUE(TRUST_TOKEN_CLIENT_begin_issuance(client.get(), &issue_msg,
&msg_len, 10));
bssl::UniquePtr<uint8_t> free_issue_msg(issue_msg);
size_t tokens_issued;
ASSERT_TRUE(TRUST_TOKEN_ISSUER_issue(
issuer.get(), &issue_resp, &resp_len, &tokens_issued, issue_msg, msg_len,
/*public_metadata=*/KeyID(0), /*private_metadata=*/0,
/*max_issuance=*/10));
bssl::UniquePtr<uint8_t> free_msg(issue_resp);
size_t key_index;
bssl::UniquePtr<STACK_OF(TRUST_TOKEN)> tokens(
TRUST_TOKEN_CLIENT_finish_issuance(client.get(), &key_index, issue_resp,
resp_len));
ASSERT_TRUE(tokens);
for (TRUST_TOKEN *token : tokens.get()) {
const uint8_t kClientData[] = "\x70TEST CLIENT DATA";
uint64_t kRedemptionTime = 13374242;
uint8_t *redeem_msg = NULL, *redeem_resp = NULL;
ASSERT_TRUE(TRUST_TOKEN_CLIENT_begin_redemption(
client.get(), &redeem_msg, &msg_len, token, kClientData,
sizeof(kClientData) - 1, kRedemptionTime));
bssl::UniquePtr<uint8_t> free_redeem_msg(redeem_msg);
TRUST_TOKEN *rtoken;
uint8_t *client_data;
size_t client_data_len;
uint64_t redemption_time;
ASSERT_TRUE(TRUST_TOKEN_ISSUER_redeem(
issuer.get(), &redeem_resp, &resp_len, &rtoken, &client_data,
&client_data_len, &redemption_time, redeem_msg, msg_len, 600));
bssl::UniquePtr<uint8_t> free_redeem_resp(redeem_resp);
bssl::UniquePtr<uint8_t> free_client_data(client_data);
bssl::UniquePtr<TRUST_TOKEN> free_rtoken(rtoken);
ASSERT_EQ(redemption_time, kRedemptionTime);
ASSERT_EQ(Bytes(kClientData, sizeof(kClientData) - 1),
Bytes(client_data, client_data_len));
resp_len = 10;
uint8_t *srr = NULL, *sig = NULL;
size_t srr_len, sig_len;
ASSERT_FALSE(TRUST_TOKEN_CLIENT_finish_redemption(
client.get(), &srr, &srr_len, &sig, &sig_len, redeem_resp, resp_len));
bssl::UniquePtr<uint8_t> free_srr(srr);
bssl::UniquePtr<uint8_t> free_sig(sig);
}
}
TEST_P(TrustTokenProtocolTest, IssuedWithBadKeyID) {
client.reset(TRUST_TOKEN_CLIENT_new(method(), client_max_batchsize));
ASSERT_TRUE(client);
issuer.reset(TRUST_TOKEN_ISSUER_new(method(), issuer_max_batchsize));
ASSERT_TRUE(issuer);
// We configure the client and the issuer with different key IDs and test
// that the client notices.
const uint32_t kClientKeyID = 0;
const uint32_t kIssuerKeyID = 42;
uint8_t priv_key[TRUST_TOKEN_MAX_PRIVATE_KEY_SIZE];
uint8_t pub_key[TRUST_TOKEN_MAX_PUBLIC_KEY_SIZE];
size_t priv_key_len, pub_key_len, key_index;
ASSERT_TRUE(TRUST_TOKEN_generate_key(
method(), priv_key, &priv_key_len, TRUST_TOKEN_MAX_PRIVATE_KEY_SIZE,
pub_key, &pub_key_len, TRUST_TOKEN_MAX_PUBLIC_KEY_SIZE, kClientKeyID));
ASSERT_TRUE(TRUST_TOKEN_CLIENT_add_key(client.get(), &key_index, pub_key,
pub_key_len));
ASSERT_EQ(0UL, key_index);
ASSERT_TRUE(TRUST_TOKEN_generate_key(
method(), priv_key, &priv_key_len, TRUST_TOKEN_MAX_PRIVATE_KEY_SIZE,
pub_key, &pub_key_len, TRUST_TOKEN_MAX_PUBLIC_KEY_SIZE, kIssuerKeyID));
ASSERT_TRUE(TRUST_TOKEN_ISSUER_add_key(issuer.get(), priv_key, priv_key_len));
uint8_t public_key[32], private_key[64];
ED25519_keypair(public_key, private_key);
bssl::UniquePtr<EVP_PKEY> priv(
EVP_PKEY_new_raw_private_key(EVP_PKEY_ED25519, nullptr, private_key, 32));
ASSERT_TRUE(priv);
bssl::UniquePtr<EVP_PKEY> pub(
EVP_PKEY_new_raw_public_key(EVP_PKEY_ED25519, nullptr, public_key, 32));
ASSERT_TRUE(pub);
TRUST_TOKEN_CLIENT_set_srr_key(client.get(), pub.get());
TRUST_TOKEN_ISSUER_set_srr_key(issuer.get(), priv.get());
RAND_bytes(metadata_key, sizeof(metadata_key));
ASSERT_TRUE(TRUST_TOKEN_ISSUER_set_metadata_key(issuer.get(), metadata_key,
sizeof(metadata_key)));
uint8_t *issue_msg = NULL, *issue_resp = NULL;
size_t msg_len, resp_len;
ASSERT_TRUE(TRUST_TOKEN_CLIENT_begin_issuance(client.get(), &issue_msg,
&msg_len, 10));
bssl::UniquePtr<uint8_t> free_issue_msg(issue_msg);
size_t tokens_issued;
ASSERT_TRUE(TRUST_TOKEN_ISSUER_issue(
issuer.get(), &issue_resp, &resp_len, &tokens_issued, issue_msg, msg_len,
/*public_metadata=*/42, /*private_metadata=*/0, /*max_issuance=*/10));
bssl::UniquePtr<uint8_t> free_msg(issue_resp);
bssl::UniquePtr<STACK_OF(TRUST_TOKEN)> tokens(
TRUST_TOKEN_CLIENT_finish_issuance(client.get(), &key_index, issue_resp,
resp_len));
ASSERT_FALSE(tokens);
}
class TrustTokenMetadataTest
: public TrustTokenProtocolTestBase,
public testing::WithParamInterface<
std::tuple<const TRUST_TOKEN_METHOD *, int, bool>> {
public:
TrustTokenMetadataTest()
: TrustTokenProtocolTestBase(std::get<0>(GetParam())) {}
int public_metadata() { return std::get<1>(GetParam()); }
bool private_metadata() { return std::get<2>(GetParam()); }
};
TEST_P(TrustTokenMetadataTest, SetAndGetMetadata) {
ASSERT_NO_FATAL_FAILURE(SetupContexts());
uint8_t *issue_msg = NULL, *issue_resp = NULL;
size_t msg_len, resp_len;
ASSERT_TRUE(TRUST_TOKEN_CLIENT_begin_issuance(client.get(), &issue_msg,
&msg_len, 10));
bssl::UniquePtr<uint8_t> free_issue_msg(issue_msg);
size_t tokens_issued;
ASSERT_TRUE(TRUST_TOKEN_ISSUER_issue(
issuer.get(), &issue_resp, &resp_len, &tokens_issued, issue_msg, msg_len,
public_metadata(), private_metadata(), /*max_issuance=*/1));
bssl::UniquePtr<uint8_t> free_msg(issue_resp);
size_t key_index;
bssl::UniquePtr<STACK_OF(TRUST_TOKEN)> tokens(
TRUST_TOKEN_CLIENT_finish_issuance(client.get(), &key_index, issue_resp,
resp_len));
ASSERT_TRUE(tokens);
for (TRUST_TOKEN *token : tokens.get()) {
const uint8_t kClientData[] = "\x70TEST CLIENT DATA";
uint64_t kRedemptionTime = 13374242;
const uint8_t kExpectedSRR[] =
"\xa4\x68\x6d\x65\x74\x61\x64\x61\x74\x61\xa2\x66\x70\x75\x62\x6c\x69"
"\x63\x00\x67\x70\x72\x69\x76\x61\x74\x65\x00\x6a\x74\x6f\x6b\x65\x6e"
"\x2d\x68\x61\x73\x68\x58\x20\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
"\x00\x00\x00\x00\x00\x6b\x63\x6c\x69\x65\x6e\x74\x2d\x64\x61\x74\x61"
"\x70\x54\x45\x53\x54\x20\x43\x4c\x49\x45\x4e\x54\x20\x44\x41\x54\x41"
"\x70\x65\x78\x70\x69\x72\x79\x2d\x74\x69\x6d\x65\x73\x74\x61\x6d\x70"
"\x1a\x00\xcc\x15\x7a";
uint8_t *redeem_msg = NULL, *redeem_resp = NULL;
ASSERT_TRUE(TRUST_TOKEN_CLIENT_begin_redemption(
client.get(), &redeem_msg, &msg_len, token, kClientData,
sizeof(kClientData) - 1, kRedemptionTime));
bssl::UniquePtr<uint8_t> free_redeem_msg(redeem_msg);
TRUST_TOKEN *rtoken;
uint8_t *client_data;
size_t client_data_len;
uint64_t redemption_time;
ASSERT_TRUE(TRUST_TOKEN_ISSUER_redeem(
issuer.get(), &redeem_resp, &resp_len, &rtoken, &client_data,
&client_data_len, &redemption_time, redeem_msg, msg_len, 600));
bssl::UniquePtr<uint8_t> free_redeem_resp(redeem_resp);
bssl::UniquePtr<uint8_t> free_client_data(client_data);
bssl::UniquePtr<TRUST_TOKEN> free_rtoken(rtoken);
ASSERT_EQ(redemption_time, kRedemptionTime);
ASSERT_EQ(Bytes(kClientData, sizeof(kClientData) - 1),
Bytes(client_data, client_data_len));
uint8_t *srr = NULL, *sig = NULL;
size_t srr_len, sig_len;
ASSERT_TRUE(TRUST_TOKEN_CLIENT_finish_redemption(
client.get(), &srr, &srr_len, &sig, &sig_len, redeem_resp, resp_len));
bssl::UniquePtr<uint8_t> free_srr(srr);
bssl::UniquePtr<uint8_t> free_sig(sig);
const uint8_t kTokenHashDSTLabel[] = "TrustTokenV0 TokenHash";
uint8_t token_hash[SHA256_DIGEST_LENGTH];
SHA256_CTX sha_ctx;
SHA256_Init(&sha_ctx);
SHA256_Update(&sha_ctx, kTokenHashDSTLabel, sizeof(kTokenHashDSTLabel));
SHA256_Update(&sha_ctx, token->data, token->len);
SHA256_Final(token_hash, &sha_ctx);
// Check the token hash is in the SRR.
ASSERT_EQ(Bytes(token_hash), Bytes(srr + 41, sizeof(token_hash)));
uint8_t decode_private_metadata;
ASSERT_TRUE(TRUST_TOKEN_decode_private_metadata(
method(), &decode_private_metadata, metadata_key, sizeof(metadata_key),
token_hash, sizeof(token_hash), srr[27]));
ASSERT_EQ(srr[18], public_metadata());
ASSERT_EQ(decode_private_metadata, private_metadata());
// Clear out the metadata bits.
srr[18] = 0;
srr[27] = 0;
// Clear out the token hash.
OPENSSL_memset(srr + 41, 0, sizeof(token_hash));
ASSERT_EQ(Bytes(kExpectedSRR, sizeof(kExpectedSRR) - 1),
Bytes(srr, srr_len));
}
}
TEST_P(TrustTokenMetadataTest, TooManyRequests) {
issuer_max_batchsize = 1;
ASSERT_NO_FATAL_FAILURE(SetupContexts());
uint8_t *issue_msg = NULL, *issue_resp = NULL;
size_t msg_len, resp_len;
ASSERT_TRUE(TRUST_TOKEN_CLIENT_begin_issuance(client.get(), &issue_msg,
&msg_len, 10));
bssl::UniquePtr<uint8_t> free_issue_msg(issue_msg);
size_t tokens_issued;
ASSERT_TRUE(TRUST_TOKEN_ISSUER_issue(
issuer.get(), &issue_resp, &resp_len, &tokens_issued, issue_msg, msg_len,
public_metadata(), private_metadata(), /*max_issuance=*/1));
bssl::UniquePtr<uint8_t> free_msg(issue_resp);
ASSERT_EQ(tokens_issued, issuer_max_batchsize);
size_t key_index;
bssl::UniquePtr<STACK_OF(TRUST_TOKEN)> tokens(
TRUST_TOKEN_CLIENT_finish_issuance(client.get(), &key_index, issue_resp,
resp_len));
ASSERT_TRUE(tokens);
ASSERT_EQ(sk_TRUST_TOKEN_num(tokens.get()), 1UL);
}
TEST_P(TrustTokenMetadataTest, TruncatedProof) {
ASSERT_NO_FATAL_FAILURE(SetupContexts());
uint8_t *issue_msg = NULL, *issue_resp = NULL;
size_t msg_len, resp_len;
ASSERT_TRUE(TRUST_TOKEN_CLIENT_begin_issuance(client.get(), &issue_msg,
&msg_len, 10));
bssl::UniquePtr<uint8_t> free_issue_msg(issue_msg);
size_t tokens_issued;
ASSERT_TRUE(TRUST_TOKEN_ISSUER_issue(
issuer.get(), &issue_resp, &resp_len, &tokens_issued, issue_msg, msg_len,
public_metadata(), private_metadata(), /*max_issuance=*/1));
bssl::UniquePtr<uint8_t> free_msg(issue_resp);
CBS real_response;
CBS_init(&real_response, issue_resp, resp_len);
uint16_t count;
uint32_t public_metadata;
bssl::ScopedCBB bad_response;
ASSERT_TRUE(CBB_init(bad_response.get(), 0));
ASSERT_TRUE(CBS_get_u16(&real_response, &count));
ASSERT_TRUE(CBB_add_u16(bad_response.get(), count));
ASSERT_TRUE(CBS_get_u32(&real_response, &public_metadata));
ASSERT_TRUE(CBB_add_u32(bad_response.get(), public_metadata));
for (size_t i = 0; i < count; i++) {
uint8_t s[PMBTOKEN_NONCE_SIZE];
CBS tmp;
ASSERT_TRUE(CBS_copy_bytes(&real_response, s, PMBTOKEN_NONCE_SIZE));
ASSERT_TRUE(CBB_add_bytes(bad_response.get(), s, PMBTOKEN_NONCE_SIZE));
ASSERT_TRUE(CBS_get_u16_length_prefixed(&real_response, &tmp));
ASSERT_TRUE(CBB_add_u16(bad_response.get(), CBS_len(&tmp)));
ASSERT_TRUE(
CBB_add_bytes(bad_response.get(), CBS_data(&tmp), CBS_len(&tmp)));
ASSERT_TRUE(CBS_get_u16_length_prefixed(&real_response, &tmp));
ASSERT_TRUE(CBB_add_u16(bad_response.get(), CBS_len(&tmp)));
ASSERT_TRUE(
CBB_add_bytes(bad_response.get(), CBS_data(&tmp), CBS_len(&tmp)));
}
CBS tmp;
ASSERT_TRUE(CBS_get_u16_length_prefixed(&real_response, &tmp));
CBB dleq;
ASSERT_TRUE(CBB_add_u16_length_prefixed(bad_response.get(), &dleq));
ASSERT_TRUE(CBB_add_bytes(&dleq, CBS_data(&tmp), CBS_len(&tmp) - 2));
ASSERT_TRUE(CBB_flush(bad_response.get()));
uint8_t *bad_buf;
size_t bad_len;
ASSERT_TRUE(CBB_finish(bad_response.get(), &bad_buf, &bad_len));
bssl::UniquePtr<uint8_t> free_bad(bad_buf);
size_t key_index;
bssl::UniquePtr<STACK_OF(TRUST_TOKEN)> tokens(
TRUST_TOKEN_CLIENT_finish_issuance(client.get(), &key_index, bad_buf,
bad_len));
ASSERT_FALSE(tokens);
}
TEST_P(TrustTokenMetadataTest, ExcessDataProof) {
ASSERT_NO_FATAL_FAILURE(SetupContexts());
uint8_t *issue_msg = NULL, *issue_resp = NULL;
size_t msg_len, resp_len;
ASSERT_TRUE(TRUST_TOKEN_CLIENT_begin_issuance(client.get(), &issue_msg,
&msg_len, 10));
bssl::UniquePtr<uint8_t> free_issue_msg(issue_msg);
size_t tokens_issued;
ASSERT_TRUE(TRUST_TOKEN_ISSUER_issue(
issuer.get(), &issue_resp, &resp_len, &tokens_issued, issue_msg, msg_len,
public_metadata(), private_metadata(), /*max_issuance=*/1));
bssl::UniquePtr<uint8_t> free_msg(issue_resp);
CBS real_response;
CBS_init(&real_response, issue_resp, resp_len);
uint16_t count;
uint32_t public_metadata;
bssl::ScopedCBB bad_response;
ASSERT_TRUE(CBB_init(bad_response.get(), 0));
ASSERT_TRUE(CBS_get_u16(&real_response, &count));
ASSERT_TRUE(CBB_add_u16(bad_response.get(), count));
ASSERT_TRUE(CBS_get_u32(&real_response, &public_metadata));
ASSERT_TRUE(CBB_add_u32(bad_response.get(), public_metadata));
for (size_t i = 0; i < count; i++) {
uint8_t s[PMBTOKEN_NONCE_SIZE];
CBS tmp;
ASSERT_TRUE(CBS_copy_bytes(&real_response, s, PMBTOKEN_NONCE_SIZE));
ASSERT_TRUE(CBB_add_bytes(bad_response.get(), s, PMBTOKEN_NONCE_SIZE));
ASSERT_TRUE(CBS_get_u16_length_prefixed(&real_response, &tmp));
ASSERT_TRUE(CBB_add_u16(bad_response.get(), CBS_len(&tmp)));
ASSERT_TRUE(
CBB_add_bytes(bad_response.get(), CBS_data(&tmp), CBS_len(&tmp)));
ASSERT_TRUE(CBS_get_u16_length_prefixed(&real_response, &tmp));
ASSERT_TRUE(CBB_add_u16(bad_response.get(), CBS_len(&tmp)));
ASSERT_TRUE(
CBB_add_bytes(bad_response.get(), CBS_data(&tmp), CBS_len(&tmp)));
}
CBS tmp;
ASSERT_TRUE(CBS_get_u16_length_prefixed(&real_response, &tmp));
CBB dleq;
ASSERT_TRUE(CBB_add_u16_length_prefixed(bad_response.get(), &dleq));
ASSERT_TRUE(CBB_add_bytes(&dleq, CBS_data(&tmp), CBS_len(&tmp)));
ASSERT_TRUE(CBB_add_u16(&dleq, 42));
ASSERT_TRUE(CBB_flush(bad_response.get()));
uint8_t *bad_buf;
size_t bad_len;
ASSERT_TRUE(CBB_finish(bad_response.get(), &bad_buf, &bad_len));
bssl::UniquePtr<uint8_t> free_bad(bad_buf);
size_t key_index;
bssl::UniquePtr<STACK_OF(TRUST_TOKEN)> tokens(
TRUST_TOKEN_CLIENT_finish_issuance(client.get(), &key_index, bad_buf,
bad_len));
ASSERT_FALSE(tokens);
}
INSTANTIATE_TEST_SUITE_P(
TrustTokenAllMetadataTest, TrustTokenMetadataTest,
testing::Combine(testing::ValuesIn(AllMethods()),
testing::Values(TrustTokenProtocolTest::KeyID(0),
TrustTokenProtocolTest::KeyID(1),
TrustTokenProtocolTest::KeyID(2)),
testing::Bool()));
class TrustTokenBadKeyTest
: public TrustTokenProtocolTestBase,
public testing::WithParamInterface<
std::tuple<const TRUST_TOKEN_METHOD *, bool, int>> {
public:
TrustTokenBadKeyTest()
: TrustTokenProtocolTestBase(std::get<0>(GetParam())) {}
bool private_metadata() { return std::get<1>(GetParam()); }
int corrupted_key() { return std::get<2>(GetParam()); }
};
TEST_P(TrustTokenBadKeyTest, BadKey) {
ASSERT_NO_FATAL_FAILURE(SetupContexts());
uint8_t *issue_msg = NULL, *issue_resp = NULL;
size_t msg_len, resp_len;
ASSERT_TRUE(TRUST_TOKEN_CLIENT_begin_issuance(client.get(), &issue_msg,
&msg_len, 10));
bssl::UniquePtr<uint8_t> free_issue_msg(issue_msg);
struct trust_token_issuer_key_st *key = &issuer->keys[0];
EC_SCALAR *scalars[] = {&key->key.x0, &key->key.y0, &key->key.x1,
&key->key.y1, &key->key.xs, &key->key.ys};
// Corrupt private key scalar.
scalars[corrupted_key()]->bytes[0] ^= 42;
size_t tokens_issued;
ASSERT_TRUE(TRUST_TOKEN_ISSUER_issue(
issuer.get(), &issue_resp, &resp_len, &tokens_issued, issue_msg, msg_len,
/*public_metadata=*/7, private_metadata(), /*max_issuance=*/1));
bssl::UniquePtr<uint8_t> free_msg(issue_resp);
size_t key_index;
bssl::UniquePtr<STACK_OF(TRUST_TOKEN)> tokens(
TRUST_TOKEN_CLIENT_finish_issuance(client.get(), &key_index, issue_resp,
resp_len));
// If the unused private key is corrupted, then the DLEQ proof should succeed.
if ((corrupted_key() / 2 == 0 && private_metadata() == true) ||
(corrupted_key() / 2 == 1 && private_metadata() == false)) {
ASSERT_TRUE(tokens);
} else {
ASSERT_FALSE(tokens);
}
}
INSTANTIATE_TEST_SUITE_P(TrustTokenAllBadKeyTest, TrustTokenBadKeyTest,
testing::Combine(testing::ValuesIn(AllMethods()),
testing::Bool(),
testing::Values(0, 1, 2, 3, 4, 5)));
} // namespace
BSSL_NAMESPACE_END
| 40.100418 | 80 | 0.696925 | [
"vector"
] |
f6ffc5d100ab754a2e5b084a065f2b4f19e9636b | 8,658 | cc | C++ | test/common/upstream/cds_api_impl_test.cc | kainz/envoy | f4972084c06ef4e8f657bd4a405d93d5de92f1f4 | [
"Apache-2.0"
] | 1 | 2018-10-18T10:55:03.000Z | 2018-10-18T10:55:03.000Z | test/common/upstream/cds_api_impl_test.cc | kainz/envoy | f4972084c06ef4e8f657bd4a405d93d5de92f1f4 | [
"Apache-2.0"
] | 1 | 2018-07-23T15:14:27.000Z | 2018-07-24T21:53:29.000Z | test/common/upstream/cds_api_impl_test.cc | kainz/envoy | f4972084c06ef4e8f657bd4a405d93d5de92f1f4 | [
"Apache-2.0"
] | null | null | null | #include <chrono>
#include <string>
#include <vector>
#include "common/config/utility.h"
#include "common/http/message_impl.h"
#include "common/json/json_loader.h"
#include "common/upstream/cds_api_impl.h"
#include "test/common/upstream/utility.h"
#include "test/mocks/local_info/mocks.h"
#include "test/mocks/upstream/mocks.h"
#include "test/test_common/printers.h"
#include "test/test_common/utility.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
using testing::InSequence;
using testing::Invoke;
using testing::Return;
using testing::ReturnRef;
using testing::_;
namespace Envoy {
namespace Upstream {
class CdsApiImplTest : public testing::Test {
public:
CdsApiImplTest() : request_(&cm_.async_client_) {}
void setup(bool v2_rest = false) {
v2_rest_ = v2_rest;
const std::string config_json = R"EOF(
{
"cluster": {
"name": "foo_cluster"
}
}
)EOF";
Json::ObjectSharedPtr config = Json::Factory::loadFromString(config_json);
envoy::api::v2::core::ConfigSource cds_config;
Config::Utility::translateCdsConfig(*config, cds_config);
if (v2_rest) {
cds_config.mutable_api_config_source()->set_api_type(
envoy::api::v2::core::ApiConfigSource::REST);
}
Upstream::ClusterManager::ClusterInfoMap cluster_map;
Upstream::MockCluster cluster;
cluster_map.emplace("foo_cluster", cluster);
EXPECT_CALL(cm_, clusters()).WillOnce(Return(cluster_map));
EXPECT_CALL(cluster, info());
EXPECT_CALL(*cluster.info_, addedViaApi());
EXPECT_CALL(cluster, info());
EXPECT_CALL(*cluster.info_, type());
cds_ =
CdsApiImpl::create(cds_config, eds_config_, cm_, dispatcher_, random_, local_info_, store_);
cds_->setInitializedCb([this]() -> void { initialized_.ready(); });
expectRequest();
cds_->initialize();
}
void expectAdd(const std::string& cluster_name, const std::string& version) {
EXPECT_CALL(cm_, addOrUpdateCluster(_, version))
.WillOnce(Invoke(
[cluster_name](const envoy::api::v2::Cluster& cluster, const std::string&) -> bool {
EXPECT_EQ(cluster_name, cluster.name());
return true;
}));
}
void expectRequest() {
EXPECT_CALL(cm_, httpAsyncClientForCluster("foo_cluster"));
EXPECT_CALL(cm_.async_client_, send_(_, _, _))
.WillOnce(Invoke(
[&](Http::MessagePtr& request, Http::AsyncClient::Callbacks& callbacks,
const absl::optional<std::chrono::milliseconds>&) -> Http::AsyncClient::Request* {
EXPECT_EQ((Http::TestHeaderMapImpl{
{":method", v2_rest_ ? "POST" : "GET"},
{":path", v2_rest_ ? "/v2/discovery:clusters"
: "/v1/clusters/cluster_name/node_name"},
{":authority", "foo_cluster"}}),
request->headers());
callbacks_ = &callbacks;
return &request_;
}));
}
ClusterManager::ClusterInfoMap makeClusterMap(std::vector<std::string> clusters) {
ClusterManager::ClusterInfoMap map;
for (auto cluster : clusters) {
map.emplace(cluster, cm_.thread_local_cluster_.cluster_);
}
return map;
}
bool v2_rest_{};
NiceMock<MockClusterManager> cm_;
NiceMock<Event::MockDispatcher> dispatcher_;
NiceMock<Runtime::MockRandomGenerator> random_;
NiceMock<LocalInfo::MockLocalInfo> local_info_;
Stats::IsolatedStoreImpl store_;
Http::MockAsyncClientRequest request_;
CdsApiPtr cds_;
Event::MockTimer* interval_timer_;
Http::AsyncClient::Callbacks* callbacks_{};
ReadyWatcher initialized_;
absl::optional<envoy::api::v2::core::ConfigSource> eds_config_;
};
// Negative test for protoc-gen-validate constraints.
TEST_F(CdsApiImplTest, ValidateFail) {
InSequence s;
setup(true);
Protobuf::RepeatedPtrField<envoy::api::v2::Cluster> clusters;
clusters.Add();
EXPECT_THROW(dynamic_cast<CdsApiImpl*>(cds_.get())->onConfigUpdate(clusters, ""),
ProtoValidationException);
EXPECT_CALL(request_, cancel());
}
TEST_F(CdsApiImplTest, InvalidOptions) {
const std::string config_json = R"EOF(
{
"cluster": {
"name": "foo_cluster"
}
}
)EOF";
Json::ObjectSharedPtr config = Json::Factory::loadFromString(config_json);
local_info_.node_.set_cluster("");
local_info_.node_.set_id("");
envoy::api::v2::core::ConfigSource cds_config;
Config::Utility::translateCdsConfig(*config, cds_config);
EXPECT_THROW(
CdsApiImpl::create(cds_config, eds_config_, cm_, dispatcher_, random_, local_info_, store_),
EnvoyException);
}
TEST_F(CdsApiImplTest, Basic) {
interval_timer_ = new Event::MockTimer(&dispatcher_);
InSequence s;
setup();
const std::string response1_json = fmt::sprintf(
"{%s}",
clustersJson({defaultStaticClusterJson("cluster1"), defaultStaticClusterJson("cluster2")}));
Http::MessagePtr message(new Http::ResponseMessageImpl(
Http::HeaderMapPtr{new Http::TestHeaderMapImpl{{":status", "200"}}}));
message->body().reset(new Buffer::OwnedImpl(response1_json));
EXPECT_CALL(cm_, clusters()).WillOnce(Return(ClusterManager::ClusterInfoMap{}));
expectAdd("cluster1", "hash_3845eb3523492899");
expectAdd("cluster2", "hash_3845eb3523492899");
EXPECT_CALL(initialized_, ready());
EXPECT_CALL(*interval_timer_, enableTimer(_));
EXPECT_EQ("", cds_->versionInfo());
EXPECT_EQ(0UL, store_.gauge("cluster_manager.cds.version").value());
callbacks_->onSuccess(std::move(message));
EXPECT_EQ(Config::Utility::computeHashedVersion(response1_json).first, cds_->versionInfo());
EXPECT_EQ(4054905652974790809U, store_.gauge("cluster_manager.cds.version").value());
expectRequest();
interval_timer_->callback_();
const std::string response2_json = fmt::sprintf(
"{%s}",
clustersJson({defaultStaticClusterJson("cluster1"), defaultStaticClusterJson("cluster3")}));
message.reset(new Http::ResponseMessageImpl(
Http::HeaderMapPtr{new Http::TestHeaderMapImpl{{":status", "200"}}}));
message->body().reset(new Buffer::OwnedImpl(response2_json));
EXPECT_CALL(cm_, clusters()).WillOnce(Return(makeClusterMap({"cluster1", "cluster2"})));
expectAdd("cluster1", "hash_19fd657104a2cd34");
expectAdd("cluster3", "hash_19fd657104a2cd34");
EXPECT_CALL(cm_, removeCluster("cluster2"));
EXPECT_CALL(*interval_timer_, enableTimer(_));
callbacks_->onSuccess(std::move(message));
EXPECT_EQ(2UL, store_.counter("cluster_manager.cds.update_attempt").value());
EXPECT_EQ(2UL, store_.counter("cluster_manager.cds.update_success").value());
EXPECT_EQ(Config::Utility::computeHashedVersion(response2_json).first, cds_->versionInfo());
EXPECT_EQ(1872764556139482420U, store_.gauge("cluster_manager.cds.version").value());
}
TEST_F(CdsApiImplTest, Failure) {
interval_timer_ = new Event::MockTimer(&dispatcher_);
InSequence s;
setup();
const std::string response_json = R"EOF(
{
"clusters" : {}
}
)EOF";
Http::MessagePtr message(new Http::ResponseMessageImpl(
Http::HeaderMapPtr{new Http::TestHeaderMapImpl{{":status", "200"}}}));
message->body().reset(new Buffer::OwnedImpl(response_json));
EXPECT_CALL(initialized_, ready());
EXPECT_CALL(*interval_timer_, enableTimer(_));
callbacks_->onSuccess(std::move(message));
expectRequest();
interval_timer_->callback_();
EXPECT_CALL(*interval_timer_, enableTimer(_));
callbacks_->onFailure(Http::AsyncClient::FailureReason::Reset);
EXPECT_EQ("", cds_->versionInfo());
EXPECT_EQ(2UL, store_.counter("cluster_manager.cds.update_attempt").value());
EXPECT_EQ(2UL, store_.counter("cluster_manager.cds.update_failure").value());
EXPECT_EQ(0UL, store_.gauge("cluster_manager.cds.version").value());
}
TEST_F(CdsApiImplTest, FailureArray) {
interval_timer_ = new Event::MockTimer(&dispatcher_);
InSequence s;
setup();
const std::string response_json = R"EOF(
[]
)EOF";
Http::MessagePtr message(new Http::ResponseMessageImpl(
Http::HeaderMapPtr{new Http::TestHeaderMapImpl{{":status", "200"}}}));
message->body().reset(new Buffer::OwnedImpl(response_json));
EXPECT_CALL(initialized_, ready());
EXPECT_CALL(*interval_timer_, enableTimer(_));
callbacks_->onSuccess(std::move(message));
EXPECT_EQ("", cds_->versionInfo());
EXPECT_EQ(1UL, store_.counter("cluster_manager.cds.update_attempt").value());
EXPECT_EQ(1UL, store_.counter("cluster_manager.cds.update_failure").value());
EXPECT_EQ(0UL, store_.gauge("cluster_manager.cds.version").value());
}
} // namespace Upstream
} // namespace Envoy
| 34.221344 | 100 | 0.695888 | [
"vector"
] |
10027ea7d2a07dcb713d90f338af110a65bc4d20 | 3,226 | cpp | C++ | Gui/ViewProviderSketchBased.cpp | haisenzhao/CarpentryCompiler | c9714310b7ce7523a25becd397265bfaa3ab7ea3 | [
"FSFAP"
] | 21 | 2019-12-06T09:57:10.000Z | 2021-09-22T12:58:09.000Z | Gui/ViewProviderSketchBased.cpp | haisenzhao/CarpentryCompiler | c9714310b7ce7523a25becd397265bfaa3ab7ea3 | [
"FSFAP"
] | null | null | null | Gui/ViewProviderSketchBased.cpp | haisenzhao/CarpentryCompiler | c9714310b7ce7523a25becd397265bfaa3ab7ea3 | [
"FSFAP"
] | 5 | 2020-11-18T00:09:30.000Z | 2021-01-13T04:40:47.000Z | /***************************************************************************
* Copyright (C) 2015 Alexander Golubev (Fat-Zer) <fatzer2@gmail.com> *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
#endif
#include <Gui/Application.h>
#include <Mod/Sketcher/App/SketchObject.h>
#include <Mod/PartDesign/App/FeatureSketchBased.h>
#include "ViewProviderSketchBased.h"
using namespace PartDesignGui;
PROPERTY_SOURCE(PartDesignGui::ViewProviderSketchBased, PartDesignGui::ViewProvider)
ViewProviderSketchBased::ViewProviderSketchBased()
{
}
ViewProviderSketchBased::~ViewProviderSketchBased()
{
}
std::vector<App::DocumentObject*> ViewProviderSketchBased::claimChildren(void) const {
std::vector<App::DocumentObject*> temp;
PartDesign::ProfileBased* feature = static_cast<PartDesign::ProfileBased*>(getObject());
App::DocumentObject* sketch = static_cast<PartDesign::ProfileBased*>(getObject())->Profile.getValue();
if (sketch != NULL) {
if(feature->ClaimChildren.getValue() ||
sketch->isDerivedFrom(Part::Part2DObject::getClassTypeId()))
temp.push_back(sketch);
}
return temp;
}
bool ViewProviderSketchBased::onDelete(const std::vector<std::string> &s) {
PartDesign::ProfileBased* feature = static_cast<PartDesign::ProfileBased*>(getObject());
// get the Sketch
Sketcher::SketchObject *pcSketch = 0;
if (feature->Profile.getValue())
pcSketch = static_cast<Sketcher::SketchObject*>(feature->Profile.getValue());
// if abort command deleted the object the sketch is visible again
if (pcSketch && Gui::Application::Instance->getViewProvider(pcSketch))
Gui::Application::Instance->getViewProvider(pcSketch)->show();
return ViewProvider::onDelete(s);
}
| 41.358974 | 106 | 0.573776 | [
"object",
"vector"
] |
10046081c5456cd3616ac8a2e21549cd070ae1c9 | 1,501 | cc | C++ | chaps/object_policy_data.cc | Toromino/chromiumos-platform2 | 97e6ba18f0e5ab6723f3448a66f82c1a07538d87 | [
"BSD-3-Clause"
] | null | null | null | chaps/object_policy_data.cc | Toromino/chromiumos-platform2 | 97e6ba18f0e5ab6723f3448a66f82c1a07538d87 | [
"BSD-3-Clause"
] | null | null | null | chaps/object_policy_data.cc | Toromino/chromiumos-platform2 | 97e6ba18f0e5ab6723f3448a66f82c1a07538d87 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2012 The Chromium OS 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 "chaps/object_policy_data.h"
#include <iterator>
#include <base/macros.h>
namespace chaps {
// Read policy list as follows:
// {attribute, sensitive, read-only {create, copy, modify}, required}
// sensitive - True if attribute cannot be read.
// read-only.create - True if attribute cannot be set with C_CreateObject.
// read-only.copy - True if attribute cannot be set with C_CopyObject.
// read-only.modify - True if attribute cannot be set with C_SetAttributeValue.
// required - True if attribute is required for a valid object.
static const AttributePolicy kDataPolicies[] = {
{CKA_APPLICATION, false, {false, false, true}, false},
{CKA_OBJECT_ID, false, {false, false, true}, false},
{CKA_VALUE, false, {false, false, true}, false},
};
ObjectPolicyData::ObjectPolicyData() {
AddPolicies(kDataPolicies, std::size(kDataPolicies));
}
ObjectPolicyData::~ObjectPolicyData() {}
void ObjectPolicyData::SetDefaultAttributes() {
ObjectPolicyCommon::SetDefaultAttributes();
if (!object_->IsAttributePresent(CKA_APPLICATION))
object_->SetAttributeBool(CKA_APPLICATION, "");
if (!object_->IsAttributePresent(CKA_OBJECT_ID))
object_->SetAttributeBool(CKA_OBJECT_ID, "");
if (!object_->IsAttributePresent(CKA_VALUE))
object_->SetAttributeBool(CKA_VALUE, "");
}
} // namespace chaps
| 34.906977 | 79 | 0.739507 | [
"object"
] |
1005820b5df68e1ce6d95d3a3322cf54475c8b45 | 15,900 | cpp | C++ | IlmBase/ImathTest/testMatrix.cpp | Lord-Kamina/openexr | cb16232387a8dabf75797ff8d3015594a7a87abe | [
"BSD-3-Clause"
] | 3 | 2018-01-27T03:39:59.000Z | 2018-07-16T16:03:02.000Z | IlmBase/ImathTest/testMatrix.cpp | Lord-Kamina/openexr | cb16232387a8dabf75797ff8d3015594a7a87abe | [
"BSD-3-Clause"
] | null | null | null | IlmBase/ImathTest/testMatrix.cpp | Lord-Kamina/openexr | cb16232387a8dabf75797ff8d3015594a7a87abe | [
"BSD-3-Clause"
] | 2 | 2018-07-16T04:34:40.000Z | 2021-01-26T00:51:41.000Z | ///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2002, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// 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 Industrial Light & Magic 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.
//
///////////////////////////////////////////////////////////////////////////
#ifdef NDEBUG
# undef NDEBUG
#endif
#include <testMatrix.h>
#include "ImathMatrix.h"
#include "ImathMatrixAlgo.h"
#include "ImathVec.h"
#include "ImathLimits.h"
#include "ImathMath.h"
#include "ImathInt64.h"
#include "ImathRandom.h"
#include <iostream>
#include <assert.h>
using namespace std;
using IMATH_INTERNAL_NAMESPACE::Int64;
//
// This file is not currently intended to exhaustively test
// the Imath Matrix33<T> and Matrix44<T> classes. We leave
// that to PyImathTest.
//
// Instead, in this file we test only those aspects of the
// Imath Matrix33<T> and Matrix44<T> classes that must be
// or are more convenient to test from C++.
//
void
testMatrix ()
{
cout << "Testing functions in ImathMatrix.h" << endl;
union {float f; int i;} nanf;
nanf.i = 0x7f800001; // NAN
union {double d; Int64 i;} nand;
nand.i = 0x7ff0000000000001ULL; // NAN
{
cout << "Imath::M33f shear functions" << endl;
IMATH_INTERNAL_NAMESPACE::M33f m1, m2;
m1.setShear (2.0f);
assert
(m1[0][0] == 1.0f && m1[0][1] == 0.0f && m1[0][2] == 0.0f &&
m1[1][0] == 2.0f && m1[1][1] == 1.0f && m1[1][2] == 0.0f &&
m1[2][0] == 0.0f && m1[2][1] == 0.0f && m1[2][2] == 1.0f);
m2.setShear (IMATH_INTERNAL_NAMESPACE::V2f (3.0f, 4.0f));
assert
(m2[0][0] == 1.0f && m2[0][1] == 4.0f && m2[0][2] == 0.0f &&
m2[1][0] == 3.0f && m2[1][1] == 1.0f && m2[1][2] == 0.0f &&
m2[2][0] == 0.0f && m2[2][1] == 0.0f && m2[2][2] == 1.0f);
m1.shear (IMATH_INTERNAL_NAMESPACE::V2f (5.0f, 6.0f));
assert
(m1[0][0] == 13.0f && m1[0][1] == 6.0f && m1[0][2] == 0.0f &&
m1[1][0] == 7.0f && m1[1][1] == 1.0f && m1[1][2] == 0.0f &&
m1[2][0] == 0.0f && m1[2][1] == 0.0f && m1[2][2] == 1.0f);
m2.shear (7.0f);
assert
(m2[0][0] == 1.0f && m2[0][1] == 4.0f && m2[0][2] == 0.0f &&
m2[1][0] == 10.0f && m2[1][1] == 29.0f && m2[1][2] == 0.0f &&
m2[2][0] == 0.0f && m2[2][1] == 0.0f && m2[2][2] == 1.0f);
cout << "M33f constructors and equality operators" << endl;
IMATH_INTERNAL_NAMESPACE::M33f test(m2);
assert(test == m2);
IMATH_INTERNAL_NAMESPACE::M33f test2;
assert(test != test2);
IMATH_INTERNAL_NAMESPACE::M33f test3;
test3.makeIdentity();
assert(test2 == test3);
}
{
cout << "M33d constructors and equality operators" << endl;
IMATH_INTERNAL_NAMESPACE::M33d m2;
m2[0][0] = 99.0f;
m2[1][2] = 101.0f;
IMATH_INTERNAL_NAMESPACE::M33d test(m2);
assert(test == m2);
IMATH_INTERNAL_NAMESPACE::M33d test2;
assert(test != test2);
IMATH_INTERNAL_NAMESPACE::M33d test3;
test3.makeIdentity();
assert(test2 == test3);
IMATH_INTERNAL_NAMESPACE::M33f test4 (1.0f, 2.0f, 3.0f,
4.0f, 5.0f, 6.0f,
7.0f, 8.0f, 9.0f);
IMATH_INTERNAL_NAMESPACE::M33d test5 = IMATH_INTERNAL_NAMESPACE::M33d (test4);
assert (test5[0][0] == 1.0);
assert (test5[0][1] == 2.0);
assert (test5[0][2] == 3.0);
assert (test5[1][0] == 4.0);
assert (test5[1][1] == 5.0);
assert (test5[1][2] == 6.0);
assert (test5[2][0] == 7.0);
assert (test5[2][1] == 8.0);
assert (test5[2][2] == 9.0);
}
{
IMATH_INTERNAL_NAMESPACE::M44f m2;
m2[0][0] = 99.0f;
m2[1][2] = 101.0f;
cout << "M44f constructors and equality operators" << endl;
IMATH_INTERNAL_NAMESPACE::M44f test(m2);
assert(test == m2);
IMATH_INTERNAL_NAMESPACE::M44f test2;
assert(test != test2);
IMATH_INTERNAL_NAMESPACE::M44f test3;
test3.makeIdentity();
assert(test2 == test3);
//
// Test non-equality when a NAN is in the same
// place in two identical matrices
//
test2[0][0] = nanf.f;
test3 = test2;
assert(test2 != test3);
}
{
IMATH_INTERNAL_NAMESPACE::M44d m2;
m2[0][0] = 99.0f;
m2[1][2] = 101.0f;
cout << "M44d constructors and equality operators" << endl;
IMATH_INTERNAL_NAMESPACE::M44d test(m2);
assert(test == m2);
IMATH_INTERNAL_NAMESPACE::M44d test2;
assert(test != test2);
IMATH_INTERNAL_NAMESPACE::M44d test3;
test3.makeIdentity();
assert(test2 == test3);
//
// Test non-equality when a NAN is in the same
// place in two identical matrices
//
test2[0][0] = nand.d;
test3 = test2;
assert(test2 != test3);
IMATH_INTERNAL_NAMESPACE::M44f test4 ( 1.0f, 2.0f, 3.0f, 4.0f,
5.0f, 6.0f, 7.0f, 8.0f,
9.0f, 10.0f, 11.0f, 12.0f,
13.0f, 14.0f, 15.0f, 16.0f);
IMATH_INTERNAL_NAMESPACE::M44d test5 = IMATH_INTERNAL_NAMESPACE::M44d (test4);
assert (test5[0][0] == 1.0);
assert (test5[0][1] == 2.0);
assert (test5[0][2] == 3.0);
assert (test5[0][3] == 4.0);
assert (test5[1][0] == 5.0);
assert (test5[1][1] == 6.0);
assert (test5[1][2] == 7.0);
assert (test5[1][3] == 8.0);
assert (test5[2][0] == 9.0);
assert (test5[2][1] == 10.0);
assert (test5[2][2] == 11.0);
assert (test5[2][3] == 12.0);
assert (test5[3][0] == 13.0);
assert (test5[3][1] == 14.0);
assert (test5[3][2] == 15.0);
assert (test5[3][3] == 16.0);
}
{
cout << "Converting between M33 and M44" << endl;
IMATH_INTERNAL_NAMESPACE::M44d m1;
m1[0][0] = 99;
IMATH_INTERNAL_NAMESPACE::M44f m2;
m2.setValue(m1);
assert(m2[0][0] == (float)m1[0][0]);
m1[0][0] = 101;
m1.setValue(m2);
assert(m2[0][0] == (float)m1[0][0]);
}
// Matrix minors
{
cout << "3x3 Matrix minors" << endl;
IMATH_INTERNAL_NAMESPACE::M33f a(1,2,3,4,5,6,7,8,9);
assert (a.minorOf(0,0) == a.fastMinor(1,2,1,2));
assert (a.minorOf(0,1) == a.fastMinor(1,2,0,2));
assert (a.minorOf(0,2) == a.fastMinor(1,2,0,1));
assert (a.minorOf(1,0) == a.fastMinor(0,2,1,2));
assert (a.minorOf(1,1) == a.fastMinor(0,2,0,2));
assert (a.minorOf(1,2) == a.fastMinor(0,2,0,1));
assert (a.minorOf(2,0) == a.fastMinor(0,1,1,2));
assert (a.minorOf(2,1) == a.fastMinor(0,1,0,2));
assert (a.minorOf(2,2) == a.fastMinor(0,1,0,1));
}
{
IMATH_INTERNAL_NAMESPACE::M33d a(1,2,3,4,5,6,7,8,9);
assert (a.minorOf(0,0) == a.fastMinor(1,2,1,2));
assert (a.minorOf(0,1) == a.fastMinor(1,2,0,2));
assert (a.minorOf(0,2) == a.fastMinor(1,2,0,1));
assert (a.minorOf(1,0) == a.fastMinor(0,2,1,2));
assert (a.minorOf(1,1) == a.fastMinor(0,2,0,2));
assert (a.minorOf(1,2) == a.fastMinor(0,2,0,1));
assert (a.minorOf(2,0) == a.fastMinor(0,1,1,2));
assert (a.minorOf(2,1) == a.fastMinor(0,1,0,2));
assert (a.minorOf(2,2) == a.fastMinor(0,1,0,1));
}
// Determinants (by building a random singular value decomposition)
{
cout << "3x3 determinant" << endl;
IMATH_INTERNAL_NAMESPACE::Rand32 random;
IMATH_INTERNAL_NAMESPACE::M33f u;
IMATH_INTERNAL_NAMESPACE::M33f v;
IMATH_INTERNAL_NAMESPACE::M33f s;
u.setRotation( random.nextf() );
v.setRotation( random.nextf() );
s[0][0] = random.nextf();
s[1][1] = random.nextf();
s[2][2] = random.nextf();
IMATH_INTERNAL_NAMESPACE::M33f c = u * s * v.transpose();
assert (fabsf(c.determinant() - s[0][0]*s[1][1]*s[2][2]) <= u.baseTypeEpsilon());
}
{
IMATH_INTERNAL_NAMESPACE::Rand32 random;
IMATH_INTERNAL_NAMESPACE::M33d u;
IMATH_INTERNAL_NAMESPACE::M33d v;
IMATH_INTERNAL_NAMESPACE::M33d s;
u.setRotation( (double)random.nextf() );
v.setRotation( (double)random.nextf() );
s[0][0] = (double)random.nextf();
s[1][1] = (double)random.nextf();
s[2][2] = (double)random.nextf();
IMATH_INTERNAL_NAMESPACE::M33d c = u * s * v.transpose();
assert (fabs(c.determinant() - s[0][0]*s[1][1]*s[2][2]) <= u.baseTypeEpsilon());
}
// Outer product of two 3D vectors
{
cout << "Outer product of two 3D vectors" << endl;
IMATH_INTERNAL_NAMESPACE::V3f a(1,2,3);
IMATH_INTERNAL_NAMESPACE::V3f b(4,5,6);
IMATH_INTERNAL_NAMESPACE::M33f p = IMATH_INTERNAL_NAMESPACE::outerProduct(a,b);
for (int i=0; i<3; i++ )
{
for (int j=0; j<3; j++)
{
assert (p[i][j] == a[i]*b[j]);
}
}
}
{
IMATH_INTERNAL_NAMESPACE::V3d a(1,2,3);
IMATH_INTERNAL_NAMESPACE::V3d b(4,5,6);
IMATH_INTERNAL_NAMESPACE::M33d p = IMATH_INTERNAL_NAMESPACE::outerProduct(a,b);
for (int i=0; i<3; i++ )
{
for (int j=0; j<3; j++)
{
assert (p[i][j] == a[i]*b[j]);
}
}
}
// Determinants (by building a random singular value decomposition)
{
cout << "4x4 determinants" << endl;
IMATH_INTERNAL_NAMESPACE::Rand32 random;
IMATH_INTERNAL_NAMESPACE::M44f u = IMATH_INTERNAL_NAMESPACE::rotationMatrix
( IMATH_INTERNAL_NAMESPACE::V3f(random.nextf(),random.nextf(),random.nextf()).normalize(),
IMATH_INTERNAL_NAMESPACE::V3f(random.nextf(),random.nextf(),random.nextf()).normalize() );
IMATH_INTERNAL_NAMESPACE::M44f v = IMATH_INTERNAL_NAMESPACE::rotationMatrix
( IMATH_INTERNAL_NAMESPACE::V3f(random.nextf(),random.nextf(),random.nextf()).normalize(),
IMATH_INTERNAL_NAMESPACE::V3f(random.nextf(),random.nextf(),random.nextf()).normalize() );
IMATH_INTERNAL_NAMESPACE::M44f s;
s[0][0] = random.nextf();
s[1][1] = random.nextf();
s[2][2] = random.nextf();
s[3][3] = random.nextf();
IMATH_INTERNAL_NAMESPACE::M44f c = u * s * v.transpose();
assert (fabsf(c.determinant() - s[0][0]*s[1][1]*s[2][2]*s[3][3]) <= u.baseTypeEpsilon());
}
{
IMATH_INTERNAL_NAMESPACE::Rand32 random;
IMATH_INTERNAL_NAMESPACE::M44d u = IMATH_INTERNAL_NAMESPACE::rotationMatrix
( IMATH_INTERNAL_NAMESPACE::V3d(random.nextf(),random.nextf(),random.nextf()).normalize(),
IMATH_INTERNAL_NAMESPACE::V3d(random.nextf(),random.nextf(),random.nextf()).normalize() );
IMATH_INTERNAL_NAMESPACE::M44d v = IMATH_INTERNAL_NAMESPACE::rotationMatrix
( IMATH_INTERNAL_NAMESPACE::V3d(random.nextf(),random.nextf(),random.nextf()).normalize(),
IMATH_INTERNAL_NAMESPACE::V3d(random.nextf(),random.nextf(),random.nextf()).normalize() );
IMATH_INTERNAL_NAMESPACE::M44d s;
s[0][0] = random.nextf();
s[1][1] = random.nextf();
s[2][2] = random.nextf();
s[3][3] = random.nextf();
IMATH_INTERNAL_NAMESPACE::M44d c = u * s * v.transpose();
assert (fabs(c.determinant() - s[0][0]*s[1][1]*s[2][2]*s[3][3]) <= u.baseTypeEpsilon());
}
// Matrix minors
{
cout << "4x4 matrix minors" << endl;
IMATH_INTERNAL_NAMESPACE::M44d a(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16);
assert (a.minorOf(0,0) == a.fastMinor(1,2,3,1,2,3));
assert (a.minorOf(0,1) == a.fastMinor(1,2,3,0,2,3));
assert (a.minorOf(0,2) == a.fastMinor(1,2,3,0,1,3));
assert (a.minorOf(0,3) == a.fastMinor(1,2,3,0,1,2));
assert (a.minorOf(1,0) == a.fastMinor(0,2,3,1,2,3));
assert (a.minorOf(1,1) == a.fastMinor(0,2,3,0,2,3));
assert (a.minorOf(1,2) == a.fastMinor(0,2,3,0,1,3));
assert (a.minorOf(1,3) == a.fastMinor(0,2,3,0,1,2));
assert (a.minorOf(2,0) == a.fastMinor(0,1,3,1,2,3));
assert (a.minorOf(2,1) == a.fastMinor(0,1,3,0,2,3));
assert (a.minorOf(2,2) == a.fastMinor(0,1,3,0,1,3));
assert (a.minorOf(2,3) == a.fastMinor(0,1,3,0,1,2));
assert (a.minorOf(3,0) == a.fastMinor(0,1,2,1,2,3));
assert (a.minorOf(3,1) == a.fastMinor(0,1,2,0,2,3));
assert (a.minorOf(3,2) == a.fastMinor(0,1,2,0,1,3));
assert (a.minorOf(3,3) == a.fastMinor(0,1,2,0,1,2));
}
{
IMATH_INTERNAL_NAMESPACE::M44f a(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16);
assert (a.minorOf(0,0) == a.fastMinor(1,2,3,1,2,3));
assert (a.minorOf(0,1) == a.fastMinor(1,2,3,0,2,3));
assert (a.minorOf(0,2) == a.fastMinor(1,2,3,0,1,3));
assert (a.minorOf(0,3) == a.fastMinor(1,2,3,0,1,2));
assert (a.minorOf(1,0) == a.fastMinor(0,2,3,1,2,3));
assert (a.minorOf(1,1) == a.fastMinor(0,2,3,0,2,3));
assert (a.minorOf(1,2) == a.fastMinor(0,2,3,0,1,3));
assert (a.minorOf(1,3) == a.fastMinor(0,2,3,0,1,2));
assert (a.minorOf(2,0) == a.fastMinor(0,1,3,1,2,3));
assert (a.minorOf(2,1) == a.fastMinor(0,1,3,0,2,3));
assert (a.minorOf(2,2) == a.fastMinor(0,1,3,0,1,3));
assert (a.minorOf(2,3) == a.fastMinor(0,1,3,0,1,2));
assert (a.minorOf(3,0) == a.fastMinor(0,1,2,1,2,3));
assert (a.minorOf(3,1) == a.fastMinor(0,1,2,0,2,3));
assert (a.minorOf(3,2) == a.fastMinor(0,1,2,0,1,3));
assert (a.minorOf(3,3) == a.fastMinor(0,1,2,0,1,2));
}
// VC 2005 64 bits compiler has a bug with __restrict keword.
// Pointers with __restrict should not alias the same symbol.
// But, with optimization on, VC removes intermediate temp variable
// and ignores __restrict.
{
cout << "M44 multiplicaftion test" << endl;
IMATH_INTERNAL_NAMESPACE::M44f M ( 1.0f, 2.0f, 3.0f, 4.0f,
5.0f, 6.0f, 7.0f, 8.0f,
9.0f, 10.0f, 11.0f, 12.0f,
13.0f, 14.0f, 15.0f, 16.0f);
IMATH_INTERNAL_NAMESPACE::M44f N; N.makeIdentity();
// N should be equal to M
// This typical test fails
// when __restrict is used for pointers in "multiply" function.
N = N * M;
assert(N == M);
if (N != M) {
cout << "M44 multiplication test has failed, error." << endl
<< "M" << endl << M << endl
<< "N" << endl << N << endl;
}
}
cout << "ok\n" << endl;
}
| 34.565217 | 104 | 0.568239 | [
"3d"
] |
1006f15d3476f173215358c480cfba1b865d4854 | 1,402 | hpp | C++ | lib/Chain.hpp | atfrank/PCASA | cbb71ac4c1e822e731d854c364621dc80008e1b8 | [
"MIT"
] | 3 | 2017-04-17T15:38:16.000Z | 2019-07-26T12:15:19.000Z | lib/Chain.hpp | atfrank/PCASA | cbb71ac4c1e822e731d854c364621dc80008e1b8 | [
"MIT"
] | 1 | 2019-09-23T13:44:55.000Z | 2019-09-24T04:05:17.000Z | lib/Chain.hpp | atfrank/PCASA | cbb71ac4c1e822e731d854c364621dc80008e1b8 | [
"MIT"
] | null | null | null | //Sean M. Law
//Aaron T. Frank
/*
This file is part of MoleTools.
MoleTools is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
MoleTools 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 MoleTools. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef CHAIN_H
#define CHAIN_H
#include <vector>
#include <string>
//Forward Declaration
class Residue;
class Atom;
class Chain {
private:
std::vector<Residue *> resVec; //Coor of residue pointers
std::vector<Atom *> atmVec; //Coor of atom pointers
// bool sel;
public:
Chain();
void reset();
void addResidue(Residue* resEntry);
void addAtom(Atom* atmEntry);
//Get Chain info
Atom* getAtom(const unsigned int& element);
Residue* getResidue(const unsigned int& element);
std::string getChainId();
unsigned int getAtmVecSize();
unsigned int getResVecSize();
// void setSel(bool selin);
// bool& getSel();
void selAll();
void deselAll();
};
#endif
| 24.172414 | 68 | 0.713267 | [
"vector"
] |
100786513b3920f5ef365c98c816c2f1da25fd1b | 14,483 | hpp | C++ | source/PEST++/src/libs/opt/ClpNonLinearCost.hpp | usgs/neversink_workflow | acd61435b8553e38d4a903c8cd7a3afc612446f9 | [
"CC0-1.0"
] | 90 | 2019-05-19T03:48:23.000Z | 2022-02-02T15:20:49.000Z | source/PEST++/src/libs/opt/ClpNonLinearCost.hpp | usgs/neversink_workflow | acd61435b8553e38d4a903c8cd7a3afc612446f9 | [
"CC0-1.0"
] | 11 | 2019-05-22T07:45:46.000Z | 2021-05-20T01:48:26.000Z | source/PEST++/src/libs/opt/ClpNonLinearCost.hpp | usgs/neversink_workflow | acd61435b8553e38d4a903c8cd7a3afc612446f9 | [
"CC0-1.0"
] | 18 | 2019-05-19T03:48:32.000Z | 2021-05-29T18:19:16.000Z | /* $Id: ClpNonLinearCost.hpp 1769 2011-07-26 09:31:51Z forrest $ */
// Copyright (C) 2002, International Business Machines
// Corporation and others. All Rights Reserved.
// This code is licensed under the terms of the Eclipse Public License (EPL).
#ifndef ClpNonLinearCost_H
#define ClpNonLinearCost_H
#include "CoinPragma.hpp"
class ClpSimplex;
class CoinIndexedVector;
/** Trivial class to deal with non linear costs
I don't make any explicit assumptions about convexity but I am
sure I do make implicit ones.
One interesting idea for normal LP's will be to allow non-basic
variables to come into basis as infeasible i.e. if variable at
lower bound has very large positive reduced cost (when problem
is infeasible) could it reduce overall problem infeasibility more
by bringing it into basis below its lower bound.
Another feature would be to automatically discover when problems
are convex piecewise linear and re-formulate to use non-linear.
I did some work on this many years ago on "grade" problems, but
while it improved primal interior point algorithms were much better
for that particular problem.
*/
/* status has original status and current status
0 - below lower so stored is upper
1 - in range
2 - above upper so stored is lower
4 - (for current) - same as original
*/
#define CLP_BELOW_LOWER 0
#define CLP_FEASIBLE 1
#define CLP_ABOVE_UPPER 2
#define CLP_SAME 4
inline int originalStatus(unsigned char status)
{
return (status & 15);
}
inline int currentStatus(unsigned char status)
{
return (status >> 4);
}
inline void setOriginalStatus(unsigned char & status, int value)
{
status = static_cast<unsigned char>(status & ~15);
status = static_cast<unsigned char>(status | value);
}
inline void setCurrentStatus(unsigned char &status, int value)
{
status = static_cast<unsigned char>(status & ~(15 << 4));
status = static_cast<unsigned char>(status | (value << 4));
}
inline void setInitialStatus(unsigned char &status)
{
status = static_cast<unsigned char>(CLP_FEASIBLE | (CLP_SAME << 4));
}
inline void setSameStatus(unsigned char &status)
{
status = static_cast<unsigned char>(status & ~(15 << 4));
status = static_cast<unsigned char>(status | (CLP_SAME << 4));
}
// Use second version to get more speed
//#define FAST_CLPNON
#ifndef FAST_CLPNON
#define CLP_METHOD1 ((method_&1)!=0)
#define CLP_METHOD2 ((method_&2)!=0)
#else
#define CLP_METHOD1 (false)
#define CLP_METHOD2 (true)
#endif
class ClpNonLinearCost {
public:
public:
/**@name Constructors, destructor */
//@{
/// Default constructor.
ClpNonLinearCost();
/** Constructor from simplex.
This will just set up wasteful arrays for linear, but
later may do dual analysis and even finding duplicate columns .
*/
ClpNonLinearCost(ClpSimplex * model, int method = 1);
/** Constructor from simplex and list of non-linearities (columns only)
First lower of each column has to match real lower
Last lower has to be <= upper (if == then cost ignored)
This could obviously be changed to make more user friendly
*/
ClpNonLinearCost(ClpSimplex * model, const int * starts,
const double * lower, const double * cost);
/// Destructor
~ClpNonLinearCost();
// Copy
ClpNonLinearCost(const ClpNonLinearCost&);
// Assignment
ClpNonLinearCost& operator=(const ClpNonLinearCost&);
//@}
/**@name Actual work in primal */
//@{
/** Changes infeasible costs and computes number and cost of infeas
Puts all non-basic (non free) variables to bounds
and all free variables to zero if oldTolerance is non-zero
- but does not move those <= oldTolerance away*/
void checkInfeasibilities(double oldTolerance = 0.0);
/** Changes infeasible costs for each variable
The indices are row indices and need converting to sequences
*/
void checkInfeasibilities(int numberInArray, const int * index);
/** Puts back correct infeasible costs for each variable
The input indices are row indices and need converting to sequences
for costs.
On input array is empty (but indices exist). On exit just
changed costs will be stored as normal CoinIndexedVector
*/
void checkChanged(int numberInArray, CoinIndexedVector * update);
/** Goes through one bound for each variable.
If multiplier*work[iRow]>0 goes down, otherwise up.
The indices are row indices and need converting to sequences
Temporary offsets may be set
Rhs entries are increased
*/
void goThru(int numberInArray, double multiplier,
const int * index, const double * work,
double * rhs);
/** Takes off last iteration (i.e. offsets closer to 0)
*/
void goBack(int numberInArray, const int * index,
double * rhs);
/** Puts back correct infeasible costs for each variable
The input indices are row indices and need converting to sequences
for costs.
At the end of this all temporary offsets are zero
*/
void goBackAll(const CoinIndexedVector * update);
/// Temporary zeroing of feasible costs
void zapCosts();
/// Refreshes costs always makes row costs zero
void refreshCosts(const double * columnCosts);
/// Puts feasible bounds into lower and upper
void feasibleBounds();
/// Refresh - assuming regions OK
void refresh();
/** Sets bounds and cost for one variable
Returns change in cost
May need to be inline for speed */
double setOne(int sequence, double solutionValue);
/** Sets bounds and infeasible cost and true cost for one variable
This is for gub and column generation etc */
void setOne(int sequence, double solutionValue, double lowerValue, double upperValue,
double costValue = 0.0);
/** Sets bounds and cost for outgoing variable
may change value
Returns direction */
int setOneOutgoing(int sequence, double &solutionValue);
/// Returns nearest bound
double nearest(int sequence, double solutionValue);
/** Returns change in cost - one down if alpha >0.0, up if <0.0
Value is current - new
*/
inline double changeInCost(int sequence, double alpha) const {
double returnValue = 0.0;
if (CLP_METHOD1) {
int iRange = whichRange_[sequence] + offset_[sequence];
if (alpha > 0.0)
returnValue = cost_[iRange] - cost_[iRange-1];
else
returnValue = cost_[iRange] - cost_[iRange+1];
}
if (CLP_METHOD2) {
returnValue = (alpha > 0.0) ? infeasibilityWeight_ : -infeasibilityWeight_;
}
return returnValue;
}
inline double changeUpInCost(int sequence) const {
double returnValue = 0.0;
if (CLP_METHOD1) {
int iRange = whichRange_[sequence] + offset_[sequence];
if (iRange + 1 != start_[sequence+1] && !infeasible(iRange + 1))
returnValue = cost_[iRange] - cost_[iRange+1];
else
returnValue = -1.0e100;
}
if (CLP_METHOD2) {
returnValue = -infeasibilityWeight_;
}
return returnValue;
}
inline double changeDownInCost(int sequence) const {
double returnValue = 0.0;
if (CLP_METHOD1) {
int iRange = whichRange_[sequence] + offset_[sequence];
if (iRange != start_[sequence] && !infeasible(iRange - 1))
returnValue = cost_[iRange] - cost_[iRange-1];
else
returnValue = 1.0e100;
}
if (CLP_METHOD2) {
returnValue = infeasibilityWeight_;
}
return returnValue;
}
/// This also updates next bound
inline double changeInCost(int sequence, double alpha, double &rhs) {
double returnValue = 0.0;
#ifdef NONLIN_DEBUG
double saveRhs = rhs;
#endif
if (CLP_METHOD1) {
int iRange = whichRange_[sequence] + offset_[sequence];
if (alpha > 0.0) {
assert(iRange - 1 >= start_[sequence]);
offset_[sequence]--;
rhs += lower_[iRange] - lower_[iRange-1];
returnValue = alpha * (cost_[iRange] - cost_[iRange-1]);
} else {
assert(iRange + 1 < start_[sequence+1] - 1);
offset_[sequence]++;
rhs += lower_[iRange+2] - lower_[iRange+1];
returnValue = alpha * (cost_[iRange] - cost_[iRange+1]);
}
}
if (CLP_METHOD2) {
#ifdef NONLIN_DEBUG
double saveRhs1 = rhs;
rhs = saveRhs;
#endif
unsigned char iStatus = status_[sequence];
int iWhere = currentStatus(iStatus);
if (iWhere == CLP_SAME)
iWhere = originalStatus(iStatus);
// rhs always increases
if (iWhere == CLP_FEASIBLE) {
if (alpha > 0.0) {
// going below
iWhere = CLP_BELOW_LOWER;
rhs = COIN_DBL_MAX;
} else {
// going above
iWhere = CLP_ABOVE_UPPER;
rhs = COIN_DBL_MAX;
}
} else if (iWhere == CLP_BELOW_LOWER) {
assert (alpha < 0);
// going feasible
iWhere = CLP_FEASIBLE;
rhs += bound_[sequence] - model_->upperRegion()[sequence];
} else {
assert (iWhere == CLP_ABOVE_UPPER);
// going feasible
iWhere = CLP_FEASIBLE;
rhs += model_->lowerRegion()[sequence] - bound_[sequence];
}
setCurrentStatus(status_[sequence], iWhere);
#ifdef NONLIN_DEBUG
assert(saveRhs1 == rhs);
#endif
returnValue = fabs(alpha) * infeasibilityWeight_;
}
return returnValue;
}
/// Returns current lower bound
inline double lower(int sequence) const {
return lower_[whichRange_[sequence] + offset_[sequence]];
}
/// Returns current upper bound
inline double upper(int sequence) const {
return lower_[whichRange_[sequence] + offset_[sequence] + 1];
}
/// Returns current cost
inline double cost(int sequence) const {
return cost_[whichRange_[sequence] + offset_[sequence]];
}
//@}
/**@name Gets and sets */
//@{
/// Number of infeasibilities
inline int numberInfeasibilities() const {
return numberInfeasibilities_;
}
/// Change in cost
inline double changeInCost() const {
return changeCost_;
}
/// Feasible cost
inline double feasibleCost() const {
return feasibleCost_;
}
/// Feasible cost with offset and direction (i.e. for reporting)
double feasibleReportCost() const;
/// Sum of infeasibilities
inline double sumInfeasibilities() const {
return sumInfeasibilities_;
}
/// Largest infeasibility
inline double largestInfeasibility() const {
return largestInfeasibility_;
}
/// Average theta
inline double averageTheta() const {
return averageTheta_;
}
inline void setAverageTheta(double value) {
averageTheta_ = value;
}
inline void setChangeInCost(double value) {
changeCost_ = value;
}
inline void setMethod(int value) {
method_ = value;
}
/// See if may want to look both ways
inline bool lookBothWays() const {
return bothWays_;
}
//@}
///@name Private functions to deal with infeasible regions
inline bool infeasible(int i) const {
return ((infeasible_[i>>5] >> (i & 31)) & 1) != 0;
}
inline void setInfeasible(int i, bool trueFalse) {
unsigned int & value = infeasible_[i>>5];
int bit = i & 31;
if (trueFalse)
value |= (1 << bit);
else
value &= ~(1 << bit);
}
inline unsigned char * statusArray() const {
return status_;
}
/// For debug
void validate();
//@}
private:
/**@name Data members */
//@{
/// Change in cost because of infeasibilities
double changeCost_;
/// Feasible cost
double feasibleCost_;
/// Current infeasibility weight
double infeasibilityWeight_;
/// Largest infeasibility
double largestInfeasibility_;
/// Sum of infeasibilities
double sumInfeasibilities_;
/// Average theta - kept here as only for primal
double averageTheta_;
/// Number of rows (mainly for checking and copy)
int numberRows_;
/// Number of columns (mainly for checking and copy)
int numberColumns_;
/// Starts for each entry (columns then rows)
int * start_;
/// Range for each entry (columns then rows)
int * whichRange_;
/// Temporary range offset for each entry (columns then rows)
int * offset_;
/** Lower bound for each range (upper bound is next lower).
For various reasons there is always an infeasible range
at bottom - even if lower bound is - infinity */
double * lower_;
/// Cost for each range
double * cost_;
/// Model
ClpSimplex * model_;
// Array to say which regions are infeasible
unsigned int * infeasible_;
/// Number of infeasibilities found
int numberInfeasibilities_;
// new stuff
/// Contains status at beginning and current
unsigned char * status_;
/// Bound which has been replaced in lower_ or upper_
double * bound_;
/// Feasible cost array
double * cost2_;
/// Method 1 old, 2 new, 3 both!
int method_;
/// If all non-linear costs convex
bool convex_;
/// If we should look both ways for djs
bool bothWays_;
//@}
};
#endif
| 36.027363 | 90 | 0.602085 | [
"model"
] |
1007c7355bee73251ba17b8ef15a4fd53074a2a7 | 1,883 | cpp | C++ | solved-codeforces/the_redback/contest/208/d/10745910.cpp | Maruf-Tuhin/Online_Judge | cf9b2a522e8b1a9623d3996a632caad7fd67f751 | [
"MIT"
] | 1 | 2019-03-31T05:47:30.000Z | 2019-03-31T05:47:30.000Z | solved-codeforces/the_redback/contest/208/d/10745910.cpp | the-redback/competitive-programming | cf9b2a522e8b1a9623d3996a632caad7fd67f751 | [
"MIT"
] | null | null | null | solved-codeforces/the_redback/contest/208/d/10745910.cpp | the-redback/competitive-programming | cf9b2a522e8b1a9623d3996a632caad7fd67f751 | [
"MIT"
] | null | null | null | /**
* @author : Maruf Tuhin
* @College : CUET CSE 11
* @Topcoder : the_redback
* @CodeForces : the_redback
* @UVA : the_redback
* @link : http://www.fb.com/maruf.2hin
*/
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long llu;
#define ft first
#define sd second
#define mp make_pair
#define pb(x) push_back(x)
#define all(x) x.begin(),x.end()
#define allr(x) x.rbegin(),x.rend()
#define mem(a,b) memset(a,b,sizeof(a))
#define inf 1e9
#define eps 1e-9
#define mod 1000000007
#define NN 100010
#define read(a) scanf("%lld",&a)
vector<pair<ll,ll> >v;
ll a[NN],b[10];
int main()
{
#ifdef redback
freopen("C:\\Users\\Maruf\\Desktop\\in.txt","r",stdin);
#endif
ll t=1,tc;
//read(tc);
ll i,j,k,l,m,n;
while(~read(n))
{
for(i=0;i<n;i++)
{
read(a[i]);
}
v.clear();
for(i=0;i<5;i++)
{
read(k);
v.pb(mp(k,i));
}
ll fl=0;
sort(allr(v));
mem(b,0);
k=0;
for(i=0;i<n;i++)
{
k+=a[i];
fl=0;
while(k>0)
{
fl=0;
for(j=0;j<5;j++)
{
if(v[j].ft<=k)
{
l=k/v[j].ft;
b[v[j].sd]+=l;
k-=v[j].ft*l;
fl=1;
break;
}
}
if(!fl)
break;
}
}
for(i=0;i<5;i++)
{
if(i!=0)
printf(" ");
printf("%lld",b[i]);
}
printf("\n%lld\n",k);
}
return 0;
}
| 19.214286 | 63 | 0.367499 | [
"vector"
] |
1008a281978a65de7b8da8577ccceb1a9b28a485 | 6,519 | hpp | C++ | Processors/Z80/Implementation/Z80Storage.hpp | ajacocks/CLK | 5f39938a192f976f51f54e4bbaf6d5cded03d48d | [
"MIT"
] | null | null | null | Processors/Z80/Implementation/Z80Storage.hpp | ajacocks/CLK | 5f39938a192f976f51f54e4bbaf6d5cded03d48d | [
"MIT"
] | null | null | null | Processors/Z80/Implementation/Z80Storage.hpp | ajacocks/CLK | 5f39938a192f976f51f54e4bbaf6d5cded03d48d | [
"MIT"
] | null | null | null | //
// Z80Storage.hpp
// Clock Signal
//
// Created by Thomas Harte on 01/09/2017.
// Copyright 2017 Thomas Harte. All rights reserved.
//
/*!
A repository for all the internal state of a CPU::Z80::Processor; extracted into a separate base
class in order to remove it from visibility within the main Z80.hpp.
*/
class ProcessorStorage {
protected:
struct MicroOp {
enum Type {
BusOperation,
DecodeOperation,
DecodeOperationNoRChange,
MoveToNextProgram,
Increment8NoFlags,
Increment8,
Increment16,
Decrement8,
Decrement16,
Move8,
Move16,
IncrementPC,
AssembleAF,
DisassembleAF,
And,
Or,
Xor,
TestNZ,
TestZ,
TestNC,
TestC,
TestPO,
TestPE,
TestP,
TestM,
ADD16, ADC16, SBC16,
CP8, SUB8, SBC8, ADD8, ADC8,
NEG,
ExDEHL, ExAFAFDash, EXX,
EI, DI, IM,
LDI, LDIR, LDD, LDDR,
CPI, CPIR, CPD, CPDR,
INI, INIR, IND, INDR,
OUTI, OUTD, OUT_R,
RLA, RLCA, RRA, RRCA,
RLC, RRC, RL, RR,
SLA, SRA, SLL, SRL,
RLD, RRD,
SetInstructionPage,
CalculateIndexAddress,
BeginNMI,
BeginIRQ,
BeginIRQMode0,
RETN,
JumpTo66,
HALT,
/// Decrements BC; if BC is 0 then moves to the next instruction. Otherwise allows this instruction to finish.
DJNZ,
DAA,
CPL,
SCF,
CCF,
/// Resets the bit in @c source implied by @c operation_ .
RES,
/// Tests the bit in @c source implied by @c operation_ .
BIT,
/// Sets the bit in @c source implied by @c operation_ .
SET,
/// Sets @c memptr_ to the target address implied by @c operation_ .
CalculateRSTDestination,
/// Resets subtract and carry, sets sign, zero, five and three according to the value of @c a_ and sets parity to the value of @c IFF2 .
SetAFlags,
/// Resets subtract and carry, sets sign, zero, five and three according to the value of @c operation and sets parity the same as sign.
SetInFlags,
/// Sets @c memptr_ to @c bc_.full+1 .
SetOutFlags,
/// Sets @c temp8_ to 0.
SetZero,
/// A no-op; used in instruction lists to indicate where an index calculation should go if this is an I[X/Y]+d operation.
IndexedPlaceHolder,
/// Sets @c memptr_ to (a_ << 8) + ((source_ + 1) & 0xff)
SetAddrAMemptr,
/// Resets: IFF1, IFF2, interrupt mode, the PC, I and R; sets all flags, the SP to 0xffff and a_ to 0xff.
Reset
};
Type type;
void *source = nullptr;
void *destination = nullptr;
PartialMachineCycle machine_cycle;
};
struct InstructionPage {
std::vector<MicroOp *> instructions;
std::vector<MicroOp> all_operations;
std::vector<MicroOp> fetch_decode_execute;
MicroOp *fetch_decode_execute_data = nullptr;
uint8_t r_step;
bool is_indexed;
InstructionPage() : r_step(1), is_indexed(false) {}
};
typedef MicroOp InstructionTable[256][30];
ProcessorStorage();
void install_default_instruction_set();
uint8_t a_;
RegisterPair16 bc_, de_, hl_;
RegisterPair16 afDash_, bcDash_, deDash_, hlDash_;
RegisterPair16 ix_, iy_, pc_, sp_;
RegisterPair16 ir_, refresh_addr_;
bool iff1_ = false, iff2_ = false;
int interrupt_mode_ = 0;
uint16_t pc_increment_ = 1;
uint8_t sign_result_; // the sign flag is set if the value in sign_result_ is negative
uint8_t zero_result_; // the zero flag is set if the value in zero_result_ is zero
uint8_t half_carry_result_; // the half-carry flag is set if bit 4 of half_carry_result_ is set
uint8_t bit53_result_; // the bit 3 and 5 flags are set if the corresponding bits of bit53_result_ are set
uint8_t parity_overflow_result_; // the parity/overflow flag is set if the corresponding bit of parity_overflow_result_ is set
uint8_t subtract_flag_; // contains a copy of the subtract flag in isolation
uint8_t carry_result_; // the carry flag is set if bit 0 of carry_result_ is set
uint8_t halt_mask_ = 0xff;
unsigned int flag_adjustment_history_ = 0; // a shifting record of whether each opcode set any flags; it turns out
// that knowledge of what the last opcode did is necessary to get bits 5 & 3
// correct for SCF and CCF.
HalfCycles number_of_cycles_;
enum Interrupt: uint8_t {
IRQ = 0x01,
NMI = 0x02,
Reset = 0x04,
PowerOn = 0x08
};
uint8_t request_status_ = Interrupt::PowerOn;
uint8_t last_request_status_ = Interrupt::PowerOn;
bool irq_line_ = false, nmi_line_ = false;
bool bus_request_line_ = false;
bool wait_line_ = false;
uint8_t operation_;
RegisterPair16 temp16_, memptr_;
uint8_t temp8_;
const MicroOp *scheduled_program_counter_ = nullptr;
std::vector<MicroOp> conditional_call_untaken_program_;
std::vector<MicroOp> reset_program_;
std::vector<MicroOp> irq_program_[3];
std::vector<MicroOp> nmi_program_;
InstructionPage *current_instruction_page_;
InstructionPage base_page_;
InstructionPage ed_page_;
InstructionPage fd_page_;
InstructionPage dd_page_;
InstructionPage cb_page_;
InstructionPage fdcb_page_;
InstructionPage ddcb_page_;
/*!
Gets the flags register.
@see set_flags
@returns The current value of the flags register.
*/
uint8_t get_flags() {
uint8_t result =
(sign_result_ & Flag::Sign) |
(zero_result_ ? 0 : Flag::Zero) |
(bit53_result_ & (Flag::Bit5 | Flag::Bit3)) |
(half_carry_result_ & Flag::HalfCarry) |
(parity_overflow_result_ & Flag::Parity) |
subtract_flag_ |
(carry_result_ & Flag::Carry);
return result;
}
/*!
Sets the flags register.
@see set_flags
@param flags The new value of the flags register.
*/
void set_flags(uint8_t flags) {
sign_result_ = flags;
zero_result_ = (flags & Flag::Zero) ^ Flag::Zero;
bit53_result_ = flags;
half_carry_result_ = flags;
parity_overflow_result_ = flags;
subtract_flag_ = flags & Flag::Subtract;
carry_result_ = flags;
}
virtual void assemble_page(InstructionPage &target, InstructionTable &table, bool add_offsets) = 0;
virtual void copy_program(const MicroOp *source, std::vector<MicroOp> &destination) = 0;
void assemble_fetch_decode_execute(InstructionPage &target, int length);
void assemble_ed_page(InstructionPage &target);
void assemble_cb_page(InstructionPage &target, RegisterPair16 &index, bool add_offsets);
void assemble_base_page(InstructionPage &target, RegisterPair16 &index, bool add_offsets, InstructionPage &cb_page);
};
| 27.622881 | 140 | 0.691977 | [
"vector"
] |
10095842b2e6b3362bb7c2688da0eada52ecb3eb | 245,271 | cpp | C++ | modules/imgproc/src/connectedcomponents.cpp | ghennadii/opencv | c6a4bad3692e62ff6733fe98f51b557d75ce65a0 | [
"BSD-3-Clause"
] | 163 | 2019-06-04T02:00:58.000Z | 2022-03-26T14:23:10.000Z | modules/imgproc/src/connectedcomponents.cpp | ghennadii/opencv | c6a4bad3692e62ff6733fe98f51b557d75ce65a0 | [
"BSD-3-Clause"
] | 8 | 2019-11-03T10:16:58.000Z | 2022-03-16T17:00:14.000Z | modules/imgproc/src/connectedcomponents.cpp | ghennadii/opencv | c6a4bad3692e62ff6733fe98f51b557d75ce65a0 | [
"BSD-3-Clause"
] | 29 | 2019-01-08T05:43:58.000Z | 2022-03-24T00:07:03.000Z | /*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// Intel License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000, Intel Corporation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of Intel Corporation may not 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 Intel Corporation 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.
//
// 2011 Jason Newton <nevion@gmail.com>
// 2016 Costantino Grama <costantino.grana@unimore.it>
// 2016 Federico Bolelli <federico.bolelli@hotmail.com>
// 2016 Lorenzo Baraldi <lorenzo.baraldi@unimore.it>
// 2016 Roberto Vezzani <roberto.vezzani@unimore.it>
// 2016 Michele Cancilla <cancilla.michele@gmail.com>
//M*/
//
#include "precomp.hpp"
#include <vector>
namespace cv{
namespace connectedcomponents{
struct NoOp{
NoOp(){
}
inline
void init(int /*labels*/){
}
inline
void initElement(const int /*nlabels*/){
}
inline
void operator()(int r, int c, int l){
CV_UNUSED(r);
CV_UNUSED(c);
CV_UNUSED(l);
}
void finish(){
}
inline
void setNextLoc(const int /*nextLoc*/){
}
inline static
void mergeStats(const cv::Mat& /*imgLabels*/, NoOp * /*sopArray*/, NoOp& /*sop*/, const int& /*nLabels*/){
}
};
struct Point2ui64{
uint64 x, y;
Point2ui64(uint64 _x, uint64 _y) :x(_x), y(_y){}
};
struct CCStatsOp{
const _OutputArray *_mstatsv;
cv::Mat statsv;
const _OutputArray *_mcentroidsv;
cv::Mat centroidsv;
std::vector<Point2ui64> integrals;
int _nextLoc;
CCStatsOp() : _mstatsv(0), _mcentroidsv(0), _nextLoc(0) {}
CCStatsOp(OutputArray _statsv, OutputArray _centroidsv) : _mstatsv(&_statsv), _mcentroidsv(&_centroidsv), _nextLoc(0){}
inline
void init(int nlabels){
_mstatsv->create(cv::Size(CC_STAT_MAX, nlabels), cv::DataType<int>::type);
statsv = _mstatsv->getMat();
_mcentroidsv->create(cv::Size(2, nlabels), cv::DataType<double>::type);
centroidsv = _mcentroidsv->getMat();
for (int l = 0; l < (int)nlabels; ++l){
int *row = (int *)&statsv.at<int>(l, 0);
row[CC_STAT_LEFT] = INT_MAX;
row[CC_STAT_TOP] = INT_MAX;
row[CC_STAT_WIDTH] = INT_MIN;
row[CC_STAT_HEIGHT] = INT_MIN;
row[CC_STAT_AREA] = 0;
}
integrals.resize(nlabels, Point2ui64(0, 0));
}
inline
void initElement(const int nlabels){
statsv = cv::Mat(nlabels, CC_STAT_MAX, cv::DataType<int>::type);
for (int l = 0; l < (int)nlabels; ++l){
int *row = (int *)statsv.ptr(l);
row[CC_STAT_LEFT] = INT_MAX;
row[CC_STAT_TOP] = INT_MAX;
row[CC_STAT_WIDTH] = INT_MIN;
row[CC_STAT_HEIGHT] = INT_MIN;
row[CC_STAT_AREA] = 0;
}
integrals.resize(nlabels, Point2ui64(0, 0));
}
void operator()(int r, int c, int l){
int *row =& statsv.at<int>(l, 0);
row[CC_STAT_LEFT] = MIN(row[CC_STAT_LEFT], c);
row[CC_STAT_WIDTH] = MAX(row[CC_STAT_WIDTH], c);
row[CC_STAT_TOP] = MIN(row[CC_STAT_TOP], r);
row[CC_STAT_HEIGHT] = MAX(row[CC_STAT_HEIGHT], r);
row[CC_STAT_AREA]++;
Point2ui64& integral = integrals[l];
integral.x += c;
integral.y += r;
}
void finish(){
for (int l = 0; l < statsv.rows; ++l){
int *row =& statsv.at<int>(l, 0);
row[CC_STAT_WIDTH] = row[CC_STAT_WIDTH] - row[CC_STAT_LEFT] + 1;
row[CC_STAT_HEIGHT] = row[CC_STAT_HEIGHT] - row[CC_STAT_TOP] + 1;
Point2ui64& integral = integrals[l];
double *centroid = ¢roidsv.at<double>(l, 0);
double area = ((unsigned*)row)[CC_STAT_AREA];
centroid[0] = double(integral.x) / area;
centroid[1] = double(integral.y) / area;
}
}
inline
void setNextLoc(const int nextLoc){
_nextLoc = nextLoc;
}
inline static
void mergeStats(const cv::Mat& imgLabels, CCStatsOp *sopArray, CCStatsOp& sop, const int& nLabels){
const int h = imgLabels.rows;
if (sop._nextLoc != h){
for (int nextLoc = sop._nextLoc; nextLoc < h; nextLoc = sopArray[nextLoc]._nextLoc){
//merge between sopNext and sop
for (int l = 0; l < nLabels; ++l){
int *rowNext = (int*)sopArray[nextLoc].statsv.ptr(l);
if (rowNext[CC_STAT_AREA] > 0){ //if changed merge all the stats
int *rowMerged = (int*)sop.statsv.ptr(l);
rowMerged[CC_STAT_LEFT] = MIN(rowMerged[CC_STAT_LEFT], rowNext[CC_STAT_LEFT]);
rowMerged[CC_STAT_WIDTH] = MAX(rowMerged[CC_STAT_WIDTH], rowNext[CC_STAT_WIDTH]);
rowMerged[CC_STAT_TOP] = MIN(rowMerged[CC_STAT_TOP], rowNext[CC_STAT_TOP]);
rowMerged[CC_STAT_HEIGHT] = MAX(rowMerged[CC_STAT_HEIGHT], rowNext[CC_STAT_HEIGHT]);
rowMerged[CC_STAT_AREA] += rowNext[CC_STAT_AREA];
sop.integrals[l].x += sopArray[nextLoc].integrals[l].x;
sop.integrals[l].y += sopArray[nextLoc].integrals[l].y;
}
}
}
}
}
};
//Find the root of the tree of node i
template<typename LabelT>
inline static
LabelT findRoot(const LabelT *P, LabelT i){
LabelT root = i;
while (P[root] < root){
root = P[root];
}
return root;
}
//Make all nodes in the path of node i point to root
template<typename LabelT>
inline static
void setRoot(LabelT *P, LabelT i, LabelT root){
while (P[i] < i){
LabelT j = P[i];
P[i] = root;
i = j;
}
P[i] = root;
}
//Find the root of the tree of the node i and compress the path in the process
template<typename LabelT>
inline static
LabelT find(LabelT *P, LabelT i){
LabelT root = findRoot(P, i);
setRoot(P, i, root);
return root;
}
//unite the two trees containing nodes i and j and return the new root
template<typename LabelT>
inline static
LabelT set_union(LabelT *P, LabelT i, LabelT j){
LabelT root = findRoot(P, i);
if (i != j){
LabelT rootj = findRoot(P, j);
if (root > rootj){
root = rootj;
}
setRoot(P, j, root);
}
setRoot(P, i, root);
return root;
}
//Flatten the Union Find tree and relabel the components
template<typename LabelT>
inline static
LabelT flattenL(LabelT *P, LabelT length){
LabelT k = 1;
for (LabelT i = 1; i < length; ++i){
if (P[i] < i){
P[i] = P[P[i]];
}
else{
P[i] = k; k = k + 1;
}
}
return k;
}
template<typename LabelT>
inline static
void flattenL(LabelT *P, const int start, const int nElem, LabelT& k){
for (int i = start; i < start + nElem; ++i){
if (P[i] < i){//node that point to root
P[i] = P[P[i]];
}
else{ //for root node
P[i] = k;
k = k + 1;
}
}
}
//Based on "Two Strategies to Speed up Connected Components Algorithms", the SAUF (Scan array union find) variant
//using decision trees
//Kesheng Wu, et al
template<typename LabelT, typename PixelT, typename StatsOp = NoOp >
struct LabelingWuParallel{
class FirstScan8Connectivity : public cv::ParallelLoopBody{
const cv::Mat& img_;
cv::Mat& imgLabels_;
LabelT *P_;
int *chunksSizeAndLabels_;
public:
FirstScan8Connectivity(const cv::Mat& img, cv::Mat& imgLabels, LabelT *P, int *chunksSizeAndLabels)
: img_(img), imgLabels_(imgLabels), P_(P), chunksSizeAndLabels_(chunksSizeAndLabels){}
FirstScan8Connectivity& operator=(const FirstScan8Connectivity& ) { return *this; }
void operator()(const cv::Range& range) const CV_OVERRIDE
{
int r = range.start;
chunksSizeAndLabels_[r] = range.end;
LabelT label = LabelT((r + 1) / 2) * LabelT((imgLabels_.cols + 1) / 2) + 1;
const LabelT firstLabel = label;
const int w = img_.cols;
const int limitLine = r, startR = r;
// Rosenfeld Mask
// +-+-+-+
// |p|q|r|
// +-+-+-+
// |s|x|
// +-+-+
for (; r != range.end; ++r)
{
PixelT const * const img_row = img_.ptr<PixelT>(r);
PixelT const * const img_row_prev = (PixelT *)(((char *)img_row) - img_.step.p[0]);
LabelT * const imgLabels_row = imgLabels_.ptr<LabelT>(r);
LabelT * const imgLabels_row_prev = (LabelT *)(((char *)imgLabels_row) - imgLabels_.step.p[0]);
for (int c = 0; c < w; ++c) {
#define condition_p c > 0 && r > limitLine && img_row_prev[c - 1] > 0
#define condition_q r > limitLine && img_row_prev[c] > 0
#define condition_r c < w - 1 && r > limitLine && img_row_prev[c + 1] > 0
#define condition_s c > 0 && img_row[c - 1] > 0
#define condition_x img_row[c] > 0
if (condition_x){
if (condition_q){
//copy q
imgLabels_row[c] = imgLabels_row_prev[c];
}
else{
//not q
if (condition_r){
if (condition_p){
//concavity p->x->r. Merge
imgLabels_row[c] = set_union(P_, imgLabels_row_prev[c - 1], imgLabels_row_prev[c + 1]);
}
else{ //not p and q
if (condition_s){
//step s->x->r. Merge
imgLabels_row[c] = set_union(P_, imgLabels_row[c - 1], imgLabels_row_prev[c + 1]);
}
else{ //not p, q and s
//copy r
imgLabels_row[c] = imgLabels_row_prev[c + 1];
}
}
}
else{
//not r and q
if (condition_p){
//copy p
imgLabels_row[c] = imgLabels_row_prev[c - 1];
}
else{//not r,q and p
if (condition_s){
imgLabels_row[c] = imgLabels_row[c - 1];
}
else{
//new label
imgLabels_row[c] = label;
P_[label] = label;
label = label + 1;
}
}
}
}
}
else{
//x is a background pixel
imgLabels_row[c] = 0;
}
}
}
//write in the follower memory location
chunksSizeAndLabels_[startR + 1] = label - firstLabel;
}
#undef condition_p
#undef condition_q
#undef condition_r
#undef condition_s
#undef condition_x
};
class FirstScan4Connectivity : public cv::ParallelLoopBody{
const cv::Mat& img_;
cv::Mat& imgLabels_;
LabelT *P_;
int *chunksSizeAndLabels_;
public:
FirstScan4Connectivity(const cv::Mat& img, cv::Mat& imgLabels, LabelT *P, int *chunksSizeAndLabels)
: img_(img), imgLabels_(imgLabels), P_(P), chunksSizeAndLabels_(chunksSizeAndLabels){}
FirstScan4Connectivity& operator=(const FirstScan4Connectivity& ) { return *this; }
void operator()(const cv::Range& range) const CV_OVERRIDE
{
int r = range.start;
chunksSizeAndLabels_[r] = range.end;
LabelT label = LabelT((r * imgLabels_.cols + 1) / 2 + 1);
const LabelT firstLabel = label;
const int w = img_.cols;
const int limitLine = r, startR = r;
// Rosenfeld Mask
// +-+-+-+
// |-|q|-|
// +-+-+-+
// |s|x|
// +-+-+
for (; r != range.end; ++r){
PixelT const * const img_row = img_.ptr<PixelT>(r);
PixelT const * const img_row_prev = (PixelT *)(((char *)img_row) - img_.step.p[0]);
LabelT * const imgLabels_row = imgLabels_.ptr<LabelT>(r);
LabelT * const imgLabels_row_prev = (LabelT *)(((char *)imgLabels_row) - imgLabels_.step.p[0]);
for (int c = 0; c < w; ++c) {
#define condition_q r > limitLine && img_row_prev[c] > 0
#define condition_s c > 0 && img_row[c - 1] > 0
#define condition_x img_row[c] > 0
if (condition_x){
if (condition_q){
if (condition_s){
//step s->x->q. Merge
imgLabels_row[c] = set_union(P_, imgLabels_row[c - 1], imgLabels_row_prev[c]);
}
else{
//copy q
imgLabels_row[c] = imgLabels_row_prev[c];
}
}
else{
if (condition_s){ // copy s
imgLabels_row[c] = imgLabels_row[c - 1];
}
else{
//new label
imgLabels_row[c] = label;
P_[label] = label;
label = label + 1;
}
}
}
else{
//x is a background pixel
imgLabels_row[c] = 0;
}
}
}
//write in the following memory location
chunksSizeAndLabels_[startR + 1] = label - firstLabel;
}
#undef condition_q
#undef condition_s
#undef condition_x
};
class SecondScan : public cv::ParallelLoopBody{
cv::Mat& imgLabels_;
const LabelT *P_;
StatsOp& sop_;
StatsOp *sopArray_;
LabelT& nLabels_;
public:
SecondScan(cv::Mat& imgLabels, const LabelT *P, StatsOp& sop, StatsOp *sopArray, LabelT& nLabels)
: imgLabels_(imgLabels), P_(P), sop_(sop), sopArray_(sopArray), nLabels_(nLabels){}
SecondScan& operator=(const SecondScan& ) { return *this; }
void operator()(const cv::Range& range) const CV_OVERRIDE
{
int r = range.start;
const int rowBegin = r;
const int rowEnd = range.end;
if (rowBegin > 0){
sopArray_[rowBegin].initElement(nLabels_);
sopArray_[rowBegin].setNextLoc(rowEnd); //_nextLoc = rowEnd;
for (; r < rowEnd; ++r) {
LabelT * img_row_start = imgLabels_.ptr<LabelT>(r);
LabelT * const img_row_end = img_row_start + imgLabels_.cols;
for (int c = 0; img_row_start != img_row_end; ++img_row_start, ++c){
*img_row_start = P_[*img_row_start];
sopArray_[rowBegin](r, c, *img_row_start);
}
}
}
else{
//the first thread uses sop in order to make less merges
sop_.setNextLoc(rowEnd);
for (; r < rowEnd; ++r) {
LabelT * img_row_start = imgLabels_.ptr<LabelT>(r);
LabelT * const img_row_end = img_row_start + imgLabels_.cols;
for (int c = 0; img_row_start != img_row_end; ++img_row_start, ++c){
*img_row_start = P_[*img_row_start];
sop_(r, c, *img_row_start);
}
}
}
}
};
inline static
void mergeLabels8Connectivity(cv::Mat& imgLabels, LabelT *P, const int *chunksSizeAndLabels){
// Merge Mask
// +-+-+-+
// |p|q|r|
// +-+-+-+
// |x|
// +-+
const int w = imgLabels.cols, h = imgLabels.rows;
for (int r = chunksSizeAndLabels[0]; r < h; r = chunksSizeAndLabels[r]){
LabelT * const imgLabels_row = imgLabels.ptr<LabelT>(r);
LabelT * const imgLabels_row_prev = (LabelT *)(((char *)imgLabels_row) - imgLabels.step.p[0]);
for (int c = 0; c < w; ++c){
#define condition_p c > 0 && imgLabels_row_prev[c - 1] > 0
#define condition_q imgLabels_row_prev[c] > 0
#define condition_r c < w - 1 && imgLabels_row_prev[c + 1] > 0
#define condition_x imgLabels_row[c] > 0
if (condition_x){
if (condition_p){
//merge of two label
imgLabels_row[c] = set_union(P, imgLabels_row_prev[c - 1], imgLabels_row[c]);
}
if (condition_r){
//merge of two label
imgLabels_row[c] = set_union(P, imgLabels_row_prev[c + 1], imgLabels_row[c]);
}
if (condition_q){
//merge of two label
imgLabels_row[c] = set_union(P, imgLabels_row_prev[c], imgLabels_row[c]);
}
}
}
}
#undef condition_p
#undef condition_q
#undef condition_r
#undef condition_x
}
inline static
void mergeLabels4Connectivity(cv::Mat& imgLabels, LabelT *P, const int *chunksSizeAndLabels){
// Merge Mask
// +-+-+-+
// |-|q|-|
// +-+-+-+
// |x|
// +-+
const int w = imgLabels.cols, h = imgLabels.rows;
for (int r = chunksSizeAndLabels[0]; r < h; r = chunksSizeAndLabels[r]){
LabelT * const imgLabels_row = imgLabels.ptr<LabelT>(r);
LabelT * const imgLabels_row_prev = (LabelT *)(((char *)imgLabels_row) - imgLabels.step.p[0]);
for (int c = 0; c < w; ++c){
#define condition_q imgLabels_row_prev[c] > 0
#define condition_x imgLabels_row[c] > 0
if (condition_x){
if (condition_q){
//merge of two label
imgLabels_row[c] = set_union(P, imgLabels_row_prev[c], imgLabels_row[c]);
}
}
}
}
#undef condition_q
#undef condition_x
}
LabelT operator()(const cv::Mat& img, cv::Mat& imgLabels, int connectivity, StatsOp& sop){
CV_Assert(img.rows == imgLabels.rows);
CV_Assert(img.cols == imgLabels.cols);
CV_Assert(connectivity == 8 || connectivity == 4);
const int h = img.rows;
const int w = img.cols;
//A quick and dirty upper bound for the maximum number of labels.
//Following formula comes from the fact that a 2x2 block in 4-way connectivity
//labeling can never have more than 2 new labels and 1 label for background.
//Worst case image example pattern:
//1 0 1 0 1...
//0 1 0 1 0...
//1 0 1 0 1...
//............
//Obviously, 4-way connectivity upper bound is also good for 8-way connectivity labeling
const size_t Plength = (size_t(h) * size_t(w) + 1) / 2 + 1;
//Array used to store info and labeled pixel by each thread.
//Different threads affect different memory location of chunksSizeAndLabels
int *chunksSizeAndLabels = (int *)cv::fastMalloc(h * sizeof(int));
//Tree of labels
LabelT *P = (LabelT *)cv::fastMalloc(Plength * sizeof(LabelT));
//First label is for background
P[0] = 0;
cv::Range range(0, h);
const double nParallelStripes = std::max(1, std::min(h / 2, getNumThreads()*4));
LabelT nLabels = 1;
if (connectivity == 8){
//First scan
cv::parallel_for_(range, FirstScan8Connectivity(img, imgLabels, P, chunksSizeAndLabels), nParallelStripes);
//merge labels of different chunks
mergeLabels8Connectivity(imgLabels, P, chunksSizeAndLabels);
for (int i = 0; i < h; i = chunksSizeAndLabels[i]){
flattenL(P, int((i + 1) / 2) * int((w + 1) / 2) + 1, chunksSizeAndLabels[i + 1], nLabels);
}
}
else{
//First scan
cv::parallel_for_(range, FirstScan4Connectivity(img, imgLabels, P, chunksSizeAndLabels), nParallelStripes);
//merge labels of different chunks
mergeLabels4Connectivity(imgLabels, P, chunksSizeAndLabels);
for (int i = 0; i < h; i = chunksSizeAndLabels[i]){
flattenL(P, int(i * w + 1) / 2 + 1, chunksSizeAndLabels[i + 1], nLabels);
}
}
//Array for statistics dataof threads
StatsOp *sopArray = new StatsOp[h];
sop.init(nLabels);
//Second scan
cv::parallel_for_(range, SecondScan(imgLabels, P, sop, sopArray, nLabels), nParallelStripes);
StatsOp::mergeStats(imgLabels, sopArray, sop, nLabels);
sop.finish();
delete[] sopArray;
cv::fastFree(chunksSizeAndLabels);
cv::fastFree(P);
return nLabels;
}
};//End struct LabelingWuParallel
//Based on "Two Strategies to Speed up Connected Components Algorithms", the SAUF (Scan array union find) variant
//using decision trees
//Kesheng Wu, et al
template<typename LabelT, typename PixelT, typename StatsOp = NoOp >
struct LabelingWu{
LabelT operator()(const cv::Mat& img, cv::Mat& imgLabels, int connectivity, StatsOp& sop){
CV_Assert(imgLabels.rows == img.rows);
CV_Assert(imgLabels.cols == img.cols);
CV_Assert(connectivity == 8 || connectivity == 4);
const int h = img.rows;
const int w = img.cols;
//A quick and dirty upper bound for the maximum number of labels.
//Following formula comes from the fact that a 2x2 block in 4-way connectivity
//labeling can never have more than 2 new labels and 1 label for background.
//Worst case image example pattern:
//1 0 1 0 1...
//0 1 0 1 0...
//1 0 1 0 1...
//............
//Obviously, 4-way connectivity upper bound is also good for 8-way connectivity labeling
const size_t Plength = (size_t(h) * size_t(w) + 1) / 2 + 1;
//array P for equivalences resolution
LabelT *P = (LabelT *)fastMalloc(sizeof(LabelT) *Plength);
//first label is for background pixels
P[0] = 0;
LabelT lunique = 1;
if (connectivity == 8){
for (int r = 0; r < h; ++r){
// Get row pointers
PixelT const * const img_row = img.ptr<PixelT>(r);
PixelT const * const img_row_prev = (PixelT *)(((char *)img_row) - img.step.p[0]);
LabelT * const imgLabels_row = imgLabels.ptr<LabelT>(r);
LabelT * const imgLabels_row_prev = (LabelT *)(((char *)imgLabels_row) - imgLabels.step.p[0]);
for (int c = 0; c < w; ++c){
#define condition_p c>0 && r>0 && img_row_prev[c - 1]>0
#define condition_q r>0 && img_row_prev[c]>0
#define condition_r c < w - 1 && r > 0 && img_row_prev[c + 1] > 0
#define condition_s c > 0 && img_row[c - 1] > 0
#define condition_x img_row[c] > 0
if (condition_x){
if (condition_q){
//x <- q
imgLabels_row[c] = imgLabels_row_prev[c];
}
else{
// q = 0
if (condition_r){
if (condition_p){
// x <- merge(p,r)
imgLabels_row[c] = set_union(P, imgLabels_row_prev[c - 1], imgLabels_row_prev[c + 1]);
}
else{
// p = q = 0
if (condition_s){
// x <- merge(s,r)
imgLabels_row[c] = set_union(P, imgLabels_row[c - 1], imgLabels_row_prev[c + 1]);
}
else{
// p = q = s = 0
// x <- r
imgLabels_row[c] = imgLabels_row_prev[c + 1];
}
}
}
else{
// r = q = 0
if (condition_p){
// x <- p
imgLabels_row[c] = imgLabels_row_prev[c - 1];
}
else{
// r = q = p = 0
if (condition_s){
imgLabels_row[c] = imgLabels_row[c - 1];
}
else{
//new label
imgLabels_row[c] = lunique;
P[lunique] = lunique;
lunique = lunique + 1;
}
}
}
}
}
else{
//x is a background pixel
imgLabels_row[c] = 0;
}
}
}
#undef condition_p
#undef condition_q
#undef condition_r
#undef condition_s
#undef condition_x
}
else{
for (int r = 0; r < h; ++r){
PixelT const * const img_row = img.ptr<PixelT>(r);
PixelT const * const img_row_prev = (PixelT *)(((char *)img_row) - img.step.p[0]);
LabelT * const imgLabels_row = imgLabels.ptr<LabelT>(r);
LabelT * const imgLabels_row_prev = (LabelT *)(((char *)imgLabels_row) - imgLabels.step.p[0]);
for (int c = 0; c < w; ++c) {
#define condition_q r > 0 && img_row_prev[c] > 0
#define condition_s c > 0 && img_row[c - 1] > 0
#define condition_x img_row[c] > 0
if (condition_x){
if (condition_q){
if (condition_s){
//Merge s->x->q
imgLabels_row[c] = set_union(P, imgLabels_row[c - 1], imgLabels_row_prev[c]);
}
else{
//copy q
imgLabels_row[c] = imgLabels_row_prev[c];
}
}
else{
if (condition_s){
// copy s
imgLabels_row[c] = imgLabels_row[c - 1];
}
else{
//new label
imgLabels_row[c] = lunique;
P[lunique] = lunique;
lunique = lunique + 1;
}
}
}
else{
//x is a background pixel
imgLabels_row[c] = 0;
}
}
}
#undef condition_q
#undef condition_s
#undef condition_x
}
//analysis
LabelT nLabels = flattenL(P, lunique);
sop.init(nLabels);
for (int r = 0; r < h; ++r) {
LabelT * img_row_start = imgLabels.ptr<LabelT>(r);
LabelT * const img_row_end = img_row_start + w;
for (int c = 0; img_row_start != img_row_end; ++img_row_start, ++c){
*img_row_start = P[*img_row_start];
sop(r, c, *img_row_start);
}
}
sop.finish();
fastFree(P);
return nLabels;
}//End function LabelingWu operator()
};//End struct LabelingWu
// Based on "Optimized Block-based Connected Components Labeling with Decision Trees", Costantino Grana et al
// Only for 8-connectivity
template<typename LabelT, typename PixelT, typename StatsOp = NoOp >
struct LabelingGranaParallel{
class FirstScan : public cv::ParallelLoopBody{
private:
const cv::Mat& img_;
cv::Mat& imgLabels_;
LabelT *P_;
int *chunksSizeAndLabels_;
public:
FirstScan(const cv::Mat& img, cv::Mat& imgLabels, LabelT *P, int *chunksSizeAndLabels)
: img_(img), imgLabels_(imgLabels), P_(P), chunksSizeAndLabels_(chunksSizeAndLabels){}
FirstScan& operator=(const FirstScan&) { return *this; }
void operator()(const cv::Range& range) const CV_OVERRIDE
{
int r = range.start;
r += (r % 2);
chunksSizeAndLabels_[r] = range.end + (range.end % 2);
LabelT label = LabelT((r + 1) / 2) * LabelT((imgLabels_.cols + 1) / 2) + 1;
const LabelT firstLabel = label;
const int h = img_.rows, w = img_.cols;
const int limitLine = r + 1, startR = r;
for (; r < range.end; r += 2){
// Get rows pointer
const PixelT * const img_row = img_.ptr<uchar>(r);
const PixelT * const img_row_prev = (PixelT *)(((char *)img_row) - img_.step.p[0]);
const PixelT * const img_row_prev_prev = (PixelT *)(((char *)img_row_prev) - img_.step.p[0]);
const PixelT * const img_row_fol = (PixelT *)(((char *)img_row) + img_.step.p[0]);
LabelT * const imgLabels_row = imgLabels_.ptr<LabelT>(r);
LabelT * const imgLabels_row_prev_prev = (LabelT *)(((char *)imgLabels_row) - imgLabels_.step.p[0] - imgLabels_.step.p[0]);
for (int c = 0; c < w; c += 2) {
// We work with 2x2 blocks
// +-+-+-+
// |P|Q|R|
// +-+-+-+
// |S|X|
// +-+-+
// The pixels are named as follows
// +---+---+---+
// |a b|c d|e f|
// |g h|i j|k l|
// +---+---+---+
// |m n|o p|
// |q r|s t|
// +---+---+
// Pixels a, f, l, q are not needed, since we need to understand the
// the connectivity between these blocks and those pixels only metter
// when considering the outer connectivities
// A bunch of defines used to check if the pixels are foreground,
// without going outside the image limits.
#define condition_b c-1>=0 && r > limitLine && img_row_prev_prev[c-1]>0
#define condition_c r > limitLine && img_row_prev_prev[c]>0
#define condition_d c+1<w && r > limitLine && img_row_prev_prev[c+1]>0
#define condition_e c+2<w && r > limitLine && img_row_prev_prev[c+2]>0
#define condition_g c-2>=0 && r > limitLine - 1 && img_row_prev[c-2]>0
#define condition_h c-1>=0 && r > limitLine - 1 && img_row_prev[c-1]>0
#define condition_i r > limitLine - 1 && img_row_prev[c]>0
#define condition_j c+1<w && r > limitLine - 1 && img_row_prev[c+1]>0
#define condition_k c+2<w && r > limitLine - 1 && img_row_prev[c+2]>0
#define condition_m c-2>=0 && img_row[c-2]>0
#define condition_n c-1>=0 && img_row[c-1]>0
#define condition_o img_row[c]>0
#define condition_p c+1<w && img_row[c+1]>0
#define condition_r c-1>=0 && r+1<h && img_row_fol[c-1]>0
#define condition_s r+1<h && img_row_fol[c]>0
#define condition_t c+1<w && r+1<h && img_row_fol[c+1]>0
// This is a decision tree which allows to choose which action to
// perform, checking as few conditions as possible.
// Actions are available after the tree.
if (condition_o) {
if (condition_n) {
if (condition_j) {
if (condition_i) {
//Action_6: Assign label of block S
imgLabels_row[c] = imgLabels_row[c - 2];
continue;
}
else {
if (condition_c) {
if (condition_h) {
//Action_6: Assign label of block S
imgLabels_row[c] = imgLabels_row[c - 2];
continue;
}
else {
if (condition_g) {
if (condition_b) {
//Action_6: Assign label of block S
imgLabels_row[c] = imgLabels_row[c - 2];
continue;
}
else {
//Action_11: Merge labels of block Q and S
imgLabels_row[c] = set_union(P_, imgLabels_row_prev_prev[c], imgLabels_row[c - 2]);
continue;
}
}
else {
//Action_11: Merge labels of block Q and S
imgLabels_row[c] = set_union(P_, imgLabels_row_prev_prev[c], imgLabels_row[c - 2]);
continue;
}
}
}
else {
//Action_11: Merge labels of block Q and S
imgLabels_row[c] = set_union(P_, imgLabels_row_prev_prev[c], imgLabels_row[c - 2]);
continue;
}
}
}
else {
if (condition_p) {
if (condition_k) {
if (condition_d) {
if (condition_i) {
//Action_6: Assign label of block S
imgLabels_row[c] = imgLabels_row[c - 2];
continue;
}
else {
if (condition_c) {
if (condition_h) {
//Action_6: Assign label of block S
imgLabels_row[c] = imgLabels_row[c - 2];
continue;
}
else {
if (condition_g) {
if (condition_b) {
//Action_6: Assign label of block S
imgLabels_row[c] = imgLabels_row[c - 2];
continue;
}
else {
//Action_12: Merge labels of block R and S
imgLabels_row[c] = set_union(P_, imgLabels_row_prev_prev[c + 2], imgLabels_row[c - 2]);
continue;
}
}
else {
//Action_12: Merge labels of block R and S
imgLabels_row[c] = set_union(P_, imgLabels_row_prev_prev[c + 2], imgLabels_row[c - 2]);
continue;
}
}
}
else {
//Action_12: Merge labels of block R and S
imgLabels_row[c] = set_union(P_, imgLabels_row_prev_prev[c + 2], imgLabels_row[c - 2]);
continue;
}
}
}
else {
//Action_12: Merge labels of block R and S
imgLabels_row[c] = set_union(P_, imgLabels_row_prev_prev[c + 2], imgLabels_row[c - 2]);
continue;
}
}
else {
//Action_6: Assign label of block S
imgLabels_row[c] = imgLabels_row[c - 2];
continue;
}
}
else {
//Action_6: Assign label of block S
imgLabels_row[c] = imgLabels_row[c - 2];
continue;
}
}
}
else {
if (condition_r) {
if (condition_j) {
if (condition_m) {
if (condition_h) {
if (condition_i) {
//Action_6: Assign label of block S
imgLabels_row[c] = imgLabels_row[c - 2];
continue;
}
else {
if (condition_c) {
//Action_6: Assign label of block S
imgLabels_row[c] = imgLabels_row[c - 2];
continue;
}
else {
//Action_11: Merge labels of block Q and S
imgLabels_row[c] = set_union(P_, imgLabels_row_prev_prev[c], imgLabels_row[c - 2]);
continue;
}
}
}
else {
if (condition_g) {
if (condition_b) {
if (condition_i) {
//Action_6: Assign label of block S
imgLabels_row[c] = imgLabels_row[c - 2];
continue;
}
else {
if (condition_c) {
//Action_6: Assign label of block S
imgLabels_row[c] = imgLabels_row[c - 2];
continue;
}
else {
//Action_11: Merge labels of block Q and S
imgLabels_row[c] = set_union(P_, imgLabels_row_prev_prev[c], imgLabels_row[c - 2]);
continue;
}
}
}
else {
//Action_11: Merge labels of block Q and S
imgLabels_row[c] = set_union(P_, imgLabels_row_prev_prev[c], imgLabels_row[c - 2]);
continue;
}
}
else {
//Action_11: Merge labels of block Q and S
imgLabels_row[c] = set_union(P_, imgLabels_row_prev_prev[c], imgLabels_row[c - 2]);
continue;
}
}
}
else {
if (condition_i) {
//Action_11: Merge labels of block Q and S
imgLabels_row[c] = set_union(P_, imgLabels_row_prev_prev[c], imgLabels_row[c - 2]);
continue;
}
else {
if (condition_h) {
if (condition_c) {
//Action_11: Merge labels of block Q and S
imgLabels_row[c] = set_union(P_, imgLabels_row_prev_prev[c], imgLabels_row[c - 2]);
continue;
}
else {
//Action_14: Merge labels of block P_, Q and S
imgLabels_row[c] = set_union(P_, set_union(P_, imgLabels_row_prev_prev[c - 2], imgLabels_row_prev_prev[c]), imgLabels_row[c - 2]);
continue;
}
}
else {
//Action_11: Merge labels of block Q and S
imgLabels_row[c] = set_union(P_, imgLabels_row_prev_prev[c], imgLabels_row[c - 2]);
continue;
}
}
}
}
else {
if (condition_p) {
if (condition_k) {
if (condition_m) {
if (condition_h) {
if (condition_d) {
if (condition_i) {
//Action_6: Assign label of block S
imgLabels_row[c] = imgLabels_row[c - 2];
continue;
}
else {
if (condition_c) {
//Action_6: Assign label of block S
imgLabels_row[c] = imgLabels_row[c - 2];
continue;
}
else {
//Action_12: Merge labels of block R and S
imgLabels_row[c] = set_union(P_, imgLabels_row_prev_prev[c + 2], imgLabels_row[c - 2]);
continue;
}
}
}
else {
//Action_12: Merge labels of block R and S
imgLabels_row[c] = set_union(P_, imgLabels_row_prev_prev[c + 2], imgLabels_row[c - 2]);
continue;
}
}
else {
if (condition_d) {
if (condition_g) {
if (condition_b) {
if (condition_i) {
//Action_6: Assign label of block S
imgLabels_row[c] = imgLabels_row[c - 2];
continue;
}
else {
if (condition_c) {
//Action_6: Assign label of block S
imgLabels_row[c] = imgLabels_row[c - 2];
continue;
}
else {
//Action_12: Merge labels of block R and S
imgLabels_row[c] = set_union(P_, imgLabels_row_prev_prev[c + 2], imgLabels_row[c - 2]);
continue;
}
}
}
else {
//Action_12: Merge labels of block R and S
imgLabels_row[c] = set_union(P_, imgLabels_row_prev_prev[c + 2], imgLabels_row[c - 2]);
continue;
}
}
else {
//Action_12: Merge labels of block R and S
imgLabels_row[c] = set_union(P_, imgLabels_row_prev_prev[c + 2], imgLabels_row[c - 2]);
continue;
}
}
else {
if (condition_i) {
if (condition_g) {
if (condition_b) {
//Action_12: Merge labels of block R and S
imgLabels_row[c] = set_union(P_, imgLabels_row_prev_prev[c + 2], imgLabels_row[c - 2]);
continue;
}
else {
//Action_16: labels of block Q, R and S
imgLabels_row[c] = set_union(P_, set_union(P_, imgLabels_row_prev_prev[c], imgLabels_row_prev_prev[c + 2]), imgLabels_row[c - 2]);
continue;
}
}
else {
//Action_16: labels of block Q, R and S
imgLabels_row[c] = set_union(P_, set_union(P_, imgLabels_row_prev_prev[c], imgLabels_row_prev_prev[c + 2]), imgLabels_row[c - 2]);
continue;
}
}
else {
//Action_12: Merge labels of block R and S
imgLabels_row[c] = set_union(P_, imgLabels_row_prev_prev[c + 2], imgLabels_row[c - 2]);
continue;
}
}
}
}
else {
if (condition_i) {
if (condition_d) {
//Action_12: Merge labels of block R and S
imgLabels_row[c] = set_union(P_, imgLabels_row_prev_prev[c + 2], imgLabels_row[c - 2]);
continue;
}
else {
//Action_16: labels of block Q, R and S
imgLabels_row[c] = set_union(P_, set_union(P_, imgLabels_row_prev_prev[c], imgLabels_row_prev_prev[c + 2]), imgLabels_row[c - 2]);
continue;
}
}
else {
if (condition_h) {
if (condition_d) {
if (condition_c) {
//Action_12: Merge labels of block R and S
imgLabels_row[c] = set_union(P_, imgLabels_row_prev_prev[c + 2], imgLabels_row[c - 2]);
continue;
}
else {
//Action_15: Merge labels of block P_, R and S
imgLabels_row[c] = set_union(P_, set_union(P_, imgLabels_row_prev_prev[c - 2], imgLabels_row_prev_prev[c + 2]), imgLabels_row[c - 2]);
continue;
}
}
else {
//Action_15: Merge labels of block P_, R and S
imgLabels_row[c] = set_union(P_, set_union(P_, imgLabels_row_prev_prev[c - 2], imgLabels_row_prev_prev[c + 2]), imgLabels_row[c - 2]);
continue;
}
}
else {
//Action_12: Merge labels of block R and S
imgLabels_row[c] = set_union(P_, imgLabels_row_prev_prev[c + 2], imgLabels_row[c - 2]);
continue;
}
}
}
}
else {
if (condition_h) {
if (condition_m) {
//Action_6: Assign label of block S
imgLabels_row[c] = imgLabels_row[c - 2];
continue;
}
else {
// ACTION_9 Merge labels of block P_ and S
imgLabels_row[c] = set_union(P_, imgLabels_row_prev_prev[c - 2], imgLabels_row[c - 2]);
continue;
}
}
else {
if (condition_i) {
if (condition_m) {
if (condition_g) {
if (condition_b) {
//Action_6: Assign label of block S
imgLabels_row[c] = imgLabels_row[c - 2];
continue;
}
else {
//Action_11: Merge labels of block Q and S
imgLabels_row[c] = set_union(P_, imgLabels_row_prev_prev[c], imgLabels_row[c - 2]);
continue;
}
}
else {
//Action_11: Merge labels of block Q and S
imgLabels_row[c] = set_union(P_, imgLabels_row_prev_prev[c], imgLabels_row[c - 2]);
continue;
}
}
else {
//Action_11: Merge labels of block Q and S
imgLabels_row[c] = set_union(P_, imgLabels_row_prev_prev[c], imgLabels_row[c - 2]);
continue;
}
}
else {
//Action_6: Assign label of block S
imgLabels_row[c] = imgLabels_row[c - 2];
continue;
}
}
}
}
else {
if (condition_h) {
if (condition_m) {
//Action_6: Assign label of block S
imgLabels_row[c] = imgLabels_row[c - 2];
continue;
}
else {
// ACTION_9 Merge labels of block P_ and S
imgLabels_row[c] = set_union(P_, imgLabels_row_prev_prev[c - 2], imgLabels_row[c - 2]);
continue;
}
}
else {
if (condition_i) {
if (condition_m) {
if (condition_g) {
if (condition_b) {
//Action_6: Assign label of block S
imgLabels_row[c] = imgLabels_row[c - 2];
continue;
}
else {
//Action_11: Merge labels of block Q and S
imgLabels_row[c] = set_union(P_, imgLabels_row_prev_prev[c], imgLabels_row[c - 2]);
continue;
}
}
else {
//Action_11: Merge labels of block Q and S
imgLabels_row[c] = set_union(P_, imgLabels_row_prev_prev[c], imgLabels_row[c - 2]);
continue;
}
}
else {
//Action_11: Merge labels of block Q and S
imgLabels_row[c] = set_union(P_, imgLabels_row_prev_prev[c], imgLabels_row[c - 2]);
continue;
}
}
else {
//Action_6: Assign label of block S
imgLabels_row[c] = imgLabels_row[c - 2];
continue;
}
}
}
}
}
else {
if (condition_j) {
if (condition_i) {
//Action_4: Assign label of block Q
imgLabels_row[c] = imgLabels_row_prev_prev[c];
continue;
}
else {
if (condition_h) {
if (condition_c) {
//Action_4: Assign label of block Q
imgLabels_row[c] = imgLabels_row_prev_prev[c];
continue;
}
else {
//Action_7: Merge labels of block P_ and Q
imgLabels_row[c] = set_union(P_, imgLabels_row_prev_prev[c - 2], imgLabels_row_prev_prev[c]);
continue;
}
}
else {
//Action_4: Assign label of block Q
imgLabels_row[c] = imgLabels_row_prev_prev[c];
continue;
}
}
}
else {
if (condition_p) {
if (condition_k) {
if (condition_i) {
if (condition_d) {
//Action_5: Assign label of block R
imgLabels_row[c] = imgLabels_row_prev_prev[c + 2];
continue;
}
else {
// ACTION_10 Merge labels of block Q and R
imgLabels_row[c] = set_union(P_, imgLabels_row_prev_prev[c], imgLabels_row_prev_prev[c + 2]);
continue;
}
}
else {
if (condition_h) {
if (condition_d) {
if (condition_c) {
//Action_5: Assign label of block R
imgLabels_row[c] = imgLabels_row_prev_prev[c + 2];
continue;
}
else {
//Action_8: Merge labels of block P_ and R
imgLabels_row[c] = set_union(P_, imgLabels_row_prev_prev[c - 2], imgLabels_row_prev_prev[c + 2]);
continue;
}
}
else {
//Action_8: Merge labels of block P_ and R
imgLabels_row[c] = set_union(P_, imgLabels_row_prev_prev[c - 2], imgLabels_row_prev_prev[c + 2]);
continue;
}
}
else {
//Action_5: Assign label of block R
imgLabels_row[c] = imgLabels_row_prev_prev[c + 2];
continue;
}
}
}
else {
if (condition_i) {
//Action_4: Assign label of block Q
imgLabels_row[c] = imgLabels_row_prev_prev[c];
continue;
}
else {
if (condition_h) {
//Action_3: Assign label of block P_
imgLabels_row[c] = imgLabels_row_prev_prev[c - 2];
continue;
}
else {
//Action_2: New label (the block has foreground pixels and is not connected to anything else)
imgLabels_row[c] = label;
P_[label] = label;
label = label + 1;
continue;
}
}
}
}
else {
if (condition_i) {
//Action_4: Assign label of block Q
imgLabels_row[c] = imgLabels_row_prev_prev[c];
continue;
}
else {
if (condition_h) {
//Action_3: Assign label of block P_
imgLabels_row[c] = imgLabels_row_prev_prev[c - 2];
continue;
}
else {
//Action_2: New label (the block has foreground pixels and is not connected to anything else)
imgLabels_row[c] = label;
P_[label] = label;
label = label + 1;
continue;
}
}
}
}
}
}
}
else {
if (condition_s) {
if (condition_p) {
if (condition_n) {
if (condition_j) {
if (condition_i) {
//Action_6: Assign label of block S
imgLabels_row[c] = imgLabels_row[c - 2];
continue;
}
else {
if (condition_c) {
if (condition_h) {
//Action_6: Assign label of block S
imgLabels_row[c] = imgLabels_row[c - 2];
continue;
}
else {
if (condition_g) {
if (condition_b) {
//Action_6: Assign label of block S
imgLabels_row[c] = imgLabels_row[c - 2];
continue;
}
else {
//Action_11: Merge labels of block Q and S
imgLabels_row[c] = set_union(P_, imgLabels_row_prev_prev[c], imgLabels_row[c - 2]);
continue;
}
}
else {
//Action_11: Merge labels of block Q and S
imgLabels_row[c] = set_union(P_, imgLabels_row_prev_prev[c], imgLabels_row[c - 2]);
continue;
}
}
}
else {
//Action_11: Merge labels of block Q and S
imgLabels_row[c] = set_union(P_, imgLabels_row_prev_prev[c], imgLabels_row[c - 2]);
continue;
}
}
}
else {
if (condition_k) {
if (condition_d) {
if (condition_i) {
//Action_6: Assign label of block S
imgLabels_row[c] = imgLabels_row[c - 2];
continue;
}
else {
if (condition_c) {
if (condition_h) {
//Action_6: Assign label of block S
imgLabels_row[c] = imgLabels_row[c - 2];
continue;
}
else {
if (condition_g) {
if (condition_b) {
//Action_6: Assign label of block S
imgLabels_row[c] = imgLabels_row[c - 2];
continue;
}
else {
//Action_12: Merge labels of block R and S
imgLabels_row[c] = set_union(P_, imgLabels_row_prev_prev[c + 2], imgLabels_row[c - 2]);
continue;
}
}
else {
//Action_12: Merge labels of block R and S
imgLabels_row[c] = set_union(P_, imgLabels_row_prev_prev[c + 2], imgLabels_row[c - 2]);
continue;
}
}
}
else {
//Action_12: Merge labels of block R and S
imgLabels_row[c] = set_union(P_, imgLabels_row_prev_prev[c + 2], imgLabels_row[c - 2]);
continue;
}
}
}
else {
//Action_12: Merge labels of block R and S
imgLabels_row[c] = set_union(P_, imgLabels_row_prev_prev[c + 2], imgLabels_row[c - 2]);
continue;
}
}
else {
//Action_6: Assign label of block S
imgLabels_row[c] = imgLabels_row[c - 2];
continue;
}
}
}
else {
if (condition_r) {
if (condition_j) {
if (condition_m) {
if (condition_h) {
if (condition_i) {
//Action_6: Assign label of block S
imgLabels_row[c] = imgLabels_row[c - 2];
continue;
}
else {
if (condition_c) {
//Action_6: Assign label of block S
imgLabels_row[c] = imgLabels_row[c - 2];
continue;
}
else {
//Action_11: Merge labels of block Q and S
imgLabels_row[c] = set_union(P_, imgLabels_row_prev_prev[c], imgLabels_row[c - 2]);
continue;
}
}
}
else {
if (condition_g) {
if (condition_b) {
if (condition_i) {
//Action_6: Assign label of block S
imgLabels_row[c] = imgLabels_row[c - 2];
continue;
}
else {
if (condition_c) {
//Action_6: Assign label of block S
imgLabels_row[c] = imgLabels_row[c - 2];
continue;
}
else {
//Action_11: Merge labels of block Q and S
imgLabels_row[c] = set_union(P_, imgLabels_row_prev_prev[c], imgLabels_row[c - 2]);
continue;
}
}
}
else {
//Action_11: Merge labels of block Q and S
imgLabels_row[c] = set_union(P_, imgLabels_row_prev_prev[c], imgLabels_row[c - 2]);
continue;
}
}
else {
//Action_11: Merge labels of block Q and S
imgLabels_row[c] = set_union(P_, imgLabels_row_prev_prev[c], imgLabels_row[c - 2]);
continue;
}
}
}
else {
//Action_11: Merge labels of block Q and S
imgLabels_row[c] = set_union(P_, imgLabels_row_prev_prev[c], imgLabels_row[c - 2]);
continue;
}
}
else {
if (condition_k) {
if (condition_d) {
if (condition_m) {
if (condition_h) {
if (condition_i) {
//Action_6: Assign label of block S
imgLabels_row[c] = imgLabels_row[c - 2];
continue;
}
else {
if (condition_c) {
//Action_6: Assign label of block S
imgLabels_row[c] = imgLabels_row[c - 2];
continue;
}
else {
//Action_12: Merge labels of block R and S
imgLabels_row[c] = set_union(P_, imgLabels_row_prev_prev[c + 2], imgLabels_row[c - 2]);
continue;
}
}
}
else {
if (condition_g) {
if (condition_b) {
if (condition_i) {
//Action_6: Assign label of block S
imgLabels_row[c] = imgLabels_row[c - 2];
continue;
}
else {
if (condition_c) {
//Action_6: Assign label of block S
imgLabels_row[c] = imgLabels_row[c - 2];
continue;
}
else {
//Action_12: Merge labels of block R and S
imgLabels_row[c] = set_union(P_, imgLabels_row_prev_prev[c + 2], imgLabels_row[c - 2]);
continue;
}
}
}
else {
//Action_12: Merge labels of block R and S
imgLabels_row[c] = set_union(P_, imgLabels_row_prev_prev[c + 2], imgLabels_row[c - 2]);
continue;
}
}
else {
//Action_12: Merge labels of block R and S
imgLabels_row[c] = set_union(P_, imgLabels_row_prev_prev[c + 2], imgLabels_row[c - 2]);
continue;
}
}
}
else {
//Action_12: Merge labels of block R and S
imgLabels_row[c] = set_union(P_, imgLabels_row_prev_prev[c + 2], imgLabels_row[c - 2]);
continue;
}
}
else {
if (condition_i) {
if (condition_m) {
if (condition_h) {
//Action_12: Merge labels of block R and S
imgLabels_row[c] = set_union(P_, imgLabels_row_prev_prev[c + 2], imgLabels_row[c - 2]);
continue;
}
else {
if (condition_g) {
if (condition_b) {
//Action_12: Merge labels of block R and S
imgLabels_row[c] = set_union(P_, imgLabels_row_prev_prev[c + 2], imgLabels_row[c - 2]);
continue;
}
else {
//Action_16: labels of block Q, R and S
imgLabels_row[c] = set_union(P_, set_union(P_, imgLabels_row_prev_prev[c], imgLabels_row_prev_prev[c + 2]), imgLabels_row[c - 2]);
continue;
}
}
else {
//Action_16: labels of block Q, R and S
imgLabels_row[c] = set_union(P_, set_union(P_, imgLabels_row_prev_prev[c], imgLabels_row_prev_prev[c + 2]), imgLabels_row[c - 2]);
continue;
}
}
}
else {
//Action_16: labels of block Q, R and S
imgLabels_row[c] = set_union(P_, set_union(P_, imgLabels_row_prev_prev[c], imgLabels_row_prev_prev[c + 2]), imgLabels_row[c - 2]);
continue;
}
}
else {
//Action_12: Merge labels of block R and S
imgLabels_row[c] = set_union(P_, imgLabels_row_prev_prev[c + 2], imgLabels_row[c - 2]);
continue;
}
}
}
else {
if (condition_i) {
if (condition_m) {
if (condition_h) {
//Action_6: Assign label of block S
imgLabels_row[c] = imgLabels_row[c - 2];
continue;
}
else {
if (condition_g) {
if (condition_b) {
//Action_6: Assign label of block S
imgLabels_row[c] = imgLabels_row[c - 2];
continue;
}
else {
//Action_11: Merge labels of block Q and S
imgLabels_row[c] = set_union(P_, imgLabels_row_prev_prev[c], imgLabels_row[c - 2]);
continue;
}
}
else {
//Action_11: Merge labels of block Q and S
imgLabels_row[c] = set_union(P_, imgLabels_row_prev_prev[c], imgLabels_row[c - 2]);
continue;
}
}
}
else {
//Action_11: Merge labels of block Q and S
imgLabels_row[c] = set_union(P_, imgLabels_row_prev_prev[c], imgLabels_row[c - 2]);
continue;
}
}
else {
//Action_6: Assign label of block S
imgLabels_row[c] = imgLabels_row[c - 2];
continue;
}
}
}
}
else {
if (condition_j) {
//Action_4: Assign label of block Q
imgLabels_row[c] = imgLabels_row_prev_prev[c];
continue;
}
else {
if (condition_k) {
if (condition_i) {
if (condition_d) {
//Action_5: Assign label of block R
imgLabels_row[c] = imgLabels_row_prev_prev[c + 2];
continue;
}
else {
// ACTION_10 Merge labels of block Q and R
imgLabels_row[c] = set_union(P_, imgLabels_row_prev_prev[c], imgLabels_row_prev_prev[c + 2]);
continue;
}
}
else {
//Action_5: Assign label of block R
imgLabels_row[c] = imgLabels_row_prev_prev[c + 2];
continue;
}
}
else {
if (condition_i) {
//Action_4: Assign label of block Q
imgLabels_row[c] = imgLabels_row_prev_prev[c];
continue;
}
else {
//Action_2: New label (the block has foreground pixels and is not connected to anything else)
imgLabels_row[c] = label;
P_[label] = label;
label = label + 1;
continue;
}
}
}
}
}
}
else {
if (condition_r) {
//Action_6: Assign label of block S
imgLabels_row[c] = imgLabels_row[c - 2];
continue;
}
else {
if (condition_n) {
//Action_6: Assign label of block S
imgLabels_row[c] = imgLabels_row[c - 2];
continue;
}
else {
//Action_2: New label (the block has foreground pixels and is not connected to anything else)
imgLabels_row[c] = label;
P_[label] = label;
label = label + 1;
continue;
}
}
}
}
else {
if (condition_p) {
if (condition_j) {
//Action_4: Assign label of block Q
imgLabels_row[c] = imgLabels_row_prev_prev[c];
continue;
}
else {
if (condition_k) {
if (condition_i) {
if (condition_d) {
//Action_5: Assign label of block R
imgLabels_row[c] = imgLabels_row_prev_prev[c + 2];
continue;
}
else {
// ACTION_10 Merge labels of block Q and R
imgLabels_row[c] = set_union(P_, imgLabels_row_prev_prev[c], imgLabels_row_prev_prev[c + 2]);
continue;
}
}
else {
//Action_5: Assign label of block R
imgLabels_row[c] = imgLabels_row_prev_prev[c + 2];
continue;
}
}
else {
if (condition_i) {
//Action_4: Assign label of block Q
imgLabels_row[c] = imgLabels_row_prev_prev[c];
continue;
}
else {
//Action_2: New label (the block has foreground pixels and is not connected to anything else)
imgLabels_row[c] = label;
P_[label] = label;
label = label + 1;
continue;
}
}
}
}
else {
if (condition_t) {
//Action_2: New label (the block has foreground pixels and is not connected to anything else)
imgLabels_row[c] = label;
P_[label] = label;
label = label + 1;
continue;
}
else {
// Action_1: No action (the block has no foreground pixels)
imgLabels_row[c] = 0;
continue;
}
}
}
}
}
}
//write in the follower memory location
chunksSizeAndLabels_[startR + 1] = label - firstLabel;
}
#undef condition_k
#undef condition_j
#undef condition_i
#undef condition_h
#undef condition_g
#undef condition_e
#undef condition_d
#undef condition_c
#undef condition_b
};
class SecondScan : public cv::ParallelLoopBody{
private:
const cv::Mat& img_;
cv::Mat& imgLabels_;
LabelT *P_;
StatsOp& sop_;
StatsOp *sopArray_;
LabelT& nLabels_;
public:
SecondScan(const cv::Mat& img, cv::Mat& imgLabels, LabelT *P, StatsOp& sop, StatsOp *sopArray, LabelT& nLabels)
: img_(img), imgLabels_(imgLabels), P_(P), sop_(sop), sopArray_(sopArray), nLabels_(nLabels){}
SecondScan& operator=(const SecondScan& ) { return *this; }
void operator()(const cv::Range& range) const CV_OVERRIDE
{
int r = range.start;
r += (r % 2);
const int rowBegin = r;
const int rowEnd = range.end + range.end % 2;
if (rowBegin > 0){
sopArray_[rowBegin].initElement(nLabels_);
sopArray_[rowBegin].setNextLoc(rowEnd); //_nextLoc = rowEnd;
if (imgLabels_.rows& 1){
if (imgLabels_.cols& 1){
//Case 1: both rows and cols odd
for (; r < rowEnd; r += 2){
// Get rows pointer
const PixelT * const img_row = img_.ptr<PixelT>(r);
const PixelT * const img_row_fol = (PixelT *)(((char *)img_row) + img_.step.p[0]);
LabelT * const imgLabels_row = imgLabels_.ptr<LabelT>(r);
LabelT * const imgLabels_row_fol = (LabelT *)(((char *)imgLabels_row) + imgLabels_.step.p[0]);
// Get rows pointer
for (int c = 0; c < imgLabels_.cols; c += 2) {
LabelT iLabel = imgLabels_row[c];
if (iLabel > 0) {
iLabel = P_[iLabel];
if (img_row[c] > 0){
imgLabels_row[c] = iLabel;
sopArray_[rowBegin](r, c, iLabel);
}
else{
imgLabels_row[c] = 0;
sopArray_[rowBegin](r, c, 0);
}
if (c + 1 < imgLabels_.cols) {
if (img_row[c + 1] > 0){
imgLabels_row[c + 1] = iLabel;
sopArray_[rowBegin](r, c + 1, iLabel);
}
else{
imgLabels_row[c + 1] = 0;
sopArray_[rowBegin](r, c + 1, 0);
}
if (r + 1 < imgLabels_.rows) {
if (img_row_fol[c] > 0){
imgLabels_row_fol[c] = iLabel;
sopArray_[rowBegin](r + 1, c, iLabel);
}
else{
imgLabels_row_fol[c] = 0;
sopArray_[rowBegin](r + 1, c, 0);
}
if (img_row_fol[c + 1] > 0){
imgLabels_row_fol[c + 1] = iLabel;
sopArray_[rowBegin](r + 1, c + 1, iLabel);
}
else{
imgLabels_row_fol[c + 1] = 0;
sopArray_[rowBegin](r + 1, c + 1, 0);
}
}
}
else if (r + 1 < imgLabels_.rows) {
if (img_row_fol[c] > 0){
imgLabels_row_fol[c] = iLabel;
sopArray_[rowBegin](r + 1, c, iLabel);
}
else{
imgLabels_row_fol[c] = 0;
sopArray_[rowBegin](r + 1, c, 0);
}
}
}
else {
imgLabels_row[c] = 0;
sopArray_[rowBegin](r, c, 0);
if (c + 1 < imgLabels_.cols) {
imgLabels_row[c + 1] = 0;
sopArray_[rowBegin](r, c + 1, 0);
if (r + 1 < imgLabels_.rows) {
imgLabels_row_fol[c] = 0;
imgLabels_row_fol[c + 1] = 0;
sopArray_[rowBegin](r + 1, c, 0);
sopArray_[rowBegin](r + 1, c + 1, 0);
}
}
else if (r + 1 < imgLabels_.rows) {
imgLabels_row_fol[c] = 0;
sopArray_[rowBegin](r + 1, c, 0);
}
}
}
}
}//END Case 1
else{
//Case 2: only rows odd
for (; r < rowEnd; r += 2){
// Get rows pointer
const PixelT * const img_row = img_.ptr<PixelT>(r);
const PixelT * const img_row_fol = (PixelT *)(((char *)img_row) + img_.step.p[0]);
LabelT * const imgLabels_row = imgLabels_.ptr<LabelT>(r);
LabelT * const imgLabels_row_fol = (LabelT *)(((char *)imgLabels_row) + imgLabels_.step.p[0]);
// Get rows pointer
for (int c = 0; c < imgLabels_.cols; c += 2) {
LabelT iLabel = imgLabels_row[c];
if (iLabel > 0) {
iLabel = P_[iLabel];
if (img_row[c] > 0){
imgLabels_row[c] = iLabel;
sopArray_[rowBegin](r, c, iLabel);
}
else{
imgLabels_row[c] = 0;
sopArray_[rowBegin](r, c, 0);
}
if (img_row[c + 1] > 0){
imgLabels_row[c + 1] = iLabel;
sopArray_[rowBegin](r, c + 1, iLabel);
}
else{
imgLabels_row[c + 1] = 0;
sopArray_[rowBegin](r, c + 1, 0);
}
if (r + 1 < imgLabels_.rows) {
if (img_row_fol[c] > 0){
imgLabels_row_fol[c] = iLabel;
sopArray_[rowBegin](r + 1, c, iLabel);
}
else{
imgLabels_row_fol[c] = 0;
sopArray_[rowBegin](r + 1, c, 0);
}
if (img_row_fol[c + 1] > 0){
imgLabels_row_fol[c + 1] = iLabel;
sopArray_[rowBegin](r + 1, c + 1, iLabel);
}
else{
imgLabels_row_fol[c + 1] = 0;
sopArray_[rowBegin](r + 1, c + 1, 0);
}
}
}
else {
imgLabels_row[c] = 0;
imgLabels_row[c + 1] = 0;
sopArray_[rowBegin](r, c, 0);
sopArray_[rowBegin](r, c + 1, 0);
if (r + 1 < imgLabels_.rows) {
imgLabels_row_fol[c] = 0;
imgLabels_row_fol[c + 1] = 0;
sopArray_[rowBegin](r + 1, c, 0);
sopArray_[rowBegin](r + 1, c + 1, 0);
}
}
}
}
}// END Case 2
}
else{
if (imgLabels_.cols& 1){
//Case 3: only cols odd
for (; r < rowEnd; r += 2){
// Get rows pointer
const PixelT * const img_row = img_.ptr<PixelT>(r);
const PixelT * const img_row_fol = (PixelT *)(((char *)img_row) + img_.step.p[0]);
LabelT * const imgLabels_row = imgLabels_.ptr<LabelT>(r);
LabelT * const imgLabels_row_fol = (LabelT *)(((char *)imgLabels_row) + imgLabels_.step.p[0]);
// Get rows pointer
for (int c = 0; c < imgLabels_.cols; c += 2) {
LabelT iLabel = imgLabels_row[c];
if (iLabel > 0) {
iLabel = P_[iLabel];
if (img_row[c] > 0){
imgLabels_row[c] = iLabel;
sopArray_[rowBegin](r, c, iLabel);
}
else{
imgLabels_row[c] = 0;
sopArray_[rowBegin](r, c, 0);
}
if (img_row_fol[c] > 0){
imgLabels_row_fol[c] = iLabel;
sopArray_[rowBegin](r + 1, c, iLabel);
}
else{
imgLabels_row_fol[c] = 0;
sopArray_[rowBegin](r + 1, c, 0);
}
if (c + 1 < imgLabels_.cols) {
if (img_row[c + 1] > 0){
imgLabels_row[c + 1] = iLabel;
sopArray_[rowBegin](r, c + 1, iLabel);
}
else{
imgLabels_row[c + 1] = 0;
sopArray_[rowBegin](r, c + 1, 0);
}
if (img_row_fol[c + 1] > 0){
imgLabels_row_fol[c + 1] = iLabel;
sopArray_[rowBegin](r + 1, c + 1, iLabel);
}
else{
imgLabels_row_fol[c + 1] = 0;
sopArray_[rowBegin](r + 1, c + 1, 0);
}
}
}
else{
imgLabels_row[c] = 0;
imgLabels_row_fol[c] = 0;
sopArray_[rowBegin](r, c, 0);
sopArray_[rowBegin](r + 1, c, 0);
if (c + 1 < imgLabels_.cols) {
imgLabels_row[c + 1] = 0;
imgLabels_row_fol[c + 1] = 0;
sopArray_[rowBegin](r, c + 1, 0);
sopArray_[rowBegin](r + 1, c + 1, 0);
}
}
}
}
}// END case 3
else{
//Case 4: nothing odd
for (; r < rowEnd; r += 2){
// Get rows pointer
const PixelT * const img_row = img_.ptr<PixelT>(r);
const PixelT * const img_row_fol = (PixelT *)(((char *)img_row) + img_.step.p[0]);
LabelT * const imgLabels_row = imgLabels_.ptr<LabelT>(r);
LabelT * const imgLabels_row_fol = (LabelT *)(((char *)imgLabels_row) + imgLabels_.step.p[0]);
// Get rows pointer
for (int c = 0; c < imgLabels_.cols; c += 2) {
LabelT iLabel = imgLabels_row[c];
if (iLabel > 0) {
iLabel = P_[iLabel];
if (img_row[c] > 0){
imgLabels_row[c] = iLabel;
sopArray_[rowBegin](r, c, iLabel);
}
else{
imgLabels_row[c] = 0;
sopArray_[rowBegin](r, c, 0);
}
if (img_row[c + 1] > 0){
imgLabels_row[c + 1] = iLabel;
sopArray_[rowBegin](r, c + 1, iLabel);
}
else{
imgLabels_row[c + 1] = 0;
sopArray_[rowBegin](r, c + 1, 0);
}
if (img_row_fol[c] > 0){
imgLabels_row_fol[c] = iLabel;
sopArray_[rowBegin](r + 1, c, iLabel);
}
else{
imgLabels_row_fol[c] = 0;
sopArray_[rowBegin](r + 1, c, 0);
}
if (img_row_fol[c + 1] > 0){
imgLabels_row_fol[c + 1] = iLabel;
sopArray_[rowBegin](r + 1, c + 1, iLabel);
}
else{
imgLabels_row_fol[c + 1] = 0;
sopArray_[rowBegin](r + 1, c + 1, 0);
}
}
else {
imgLabels_row[c] = 0;
imgLabels_row[c + 1] = 0;
imgLabels_row_fol[c] = 0;
imgLabels_row_fol[c + 1] = 0;
sopArray_[rowBegin](r, c, 0);
sopArray_[rowBegin](r, c + 1, 0);
sopArray_[rowBegin](r + 1, c, 0);
sopArray_[rowBegin](r + 1, c + 1, 0);
}
}
}//END case 4
}
}
}
else{
//the first thread uses sop in order to make less merges
sop_.setNextLoc(rowEnd);
if (imgLabels_.rows& 1){
if (imgLabels_.cols& 1){
//Case 1: both rows and cols odd
for (; r < rowEnd; r += 2){
// Get rows pointer
const PixelT * const img_row = img_.ptr<PixelT>(r);
const PixelT * const img_row_fol = (PixelT *)(((char *)img_row) + img_.step.p[0]);
LabelT * const imgLabels_row = imgLabels_.ptr<LabelT>(r);
LabelT * const imgLabels_row_fol = (LabelT *)(((char *)imgLabels_row) + imgLabels_.step.p[0]);
// Get rows pointer
for (int c = 0; c < imgLabels_.cols; c += 2) {
LabelT iLabel = imgLabels_row[c];
if (iLabel > 0) {
iLabel = P_[iLabel];
if (img_row[c] > 0){
imgLabels_row[c] = iLabel;
sop_(r, c, iLabel);
}
else{
imgLabels_row[c] = 0;
sop_(r, c, 0);
}
if (c + 1 < imgLabels_.cols) {
if (img_row[c + 1] > 0){
imgLabels_row[c + 1] = iLabel;
sop_(r, c + 1, iLabel);
}
else{
imgLabels_row[c + 1] = 0;
sop_(r, c + 1, 0);
}
if (r + 1 < imgLabels_.rows) {
if (img_row_fol[c] > 0){
imgLabels_row_fol[c] = iLabel;
sop_(r + 1, c, iLabel);
}
else{
imgLabels_row_fol[c] = 0;
sop_(r + 1, c, 0);
}
if (img_row_fol[c + 1] > 0){
imgLabels_row_fol[c + 1] = iLabel;
sop_(r + 1, c + 1, iLabel);
}
else{
imgLabels_row_fol[c + 1] = 0;
sop_(r + 1, c + 1, 0);
}
}
}
else if (r + 1 < imgLabels_.rows) {
if (img_row_fol[c] > 0){
imgLabels_row_fol[c] = iLabel;
sop_(r + 1, c, iLabel);
}
else{
imgLabels_row_fol[c] = 0;
sop_(r + 1, c, 0);
}
}
}
else {
imgLabels_row[c] = 0;
sop_(r, c, 0);
if (c + 1 < imgLabels_.cols) {
imgLabels_row[c + 1] = 0;
sop_(r, c + 1, 0);
if (r + 1 < imgLabels_.rows) {
imgLabels_row_fol[c] = 0;
imgLabels_row_fol[c + 1] = 0;
sop_(r + 1, c, 0);
sop_(r + 1, c + 1, 0);
}
}
else if (r + 1 < imgLabels_.rows) {
imgLabels_row_fol[c] = 0;
sop_(r + 1, c, 0);
}
}
}
}
}//END Case 1
else{
//Case 2: only rows odd
for (; r < rowEnd; r += 2){
// Get rows pointer
const PixelT * const img_row = img_.ptr<PixelT>(r);
const PixelT * const img_row_fol = (PixelT *)(((char *)img_row) + img_.step.p[0]);
LabelT * const imgLabels_row = imgLabels_.ptr<LabelT>(r);
LabelT * const imgLabels_row_fol = (LabelT *)(((char *)imgLabels_row) + imgLabels_.step.p[0]);
// Get rows pointer
for (int c = 0; c < imgLabels_.cols; c += 2) {
LabelT iLabel = imgLabels_row[c];
if (iLabel > 0) {
iLabel = P_[iLabel];
if (img_row[c] > 0){
imgLabels_row[c] = iLabel;
sop_(r, c, iLabel);
}
else{
imgLabels_row[c] = 0;
sop_(r, c, 0);
}
if (img_row[c + 1] > 0){
imgLabels_row[c + 1] = iLabel;
sop_(r, c + 1, iLabel);
}
else{
imgLabels_row[c + 1] = 0;
sop_(r, c + 1, 0);
}
if (r + 1 < imgLabels_.rows) {
if (img_row_fol[c] > 0){
imgLabels_row_fol[c] = iLabel;
sop_(r + 1, c, iLabel);
}
else{
imgLabels_row_fol[c] = 0;
sop_(r + 1, c, 0);
}
if (img_row_fol[c + 1] > 0){
imgLabels_row_fol[c + 1] = iLabel;
sop_(r + 1, c + 1, iLabel);
}
else{
imgLabels_row_fol[c + 1] = 0;
sop_(r + 1, c + 1, 0);
}
}
}
else {
imgLabels_row[c] = 0;
imgLabels_row[c + 1] = 0;
sop_(r, c, 0);
sop_(r, c + 1, 0);
if (r + 1 < imgLabels_.rows) {
imgLabels_row_fol[c] = 0;
imgLabels_row_fol[c + 1] = 0;
sop_(r + 1, c, 0);
sop_(r + 1, c + 1, 0);
}
}
}
}
}// END Case 2
}
else{
if (imgLabels_.cols& 1){
//Case 3: only cols odd
for (; r < rowEnd; r += 2){
// Get rows pointer
const PixelT * const img_row = img_.ptr<PixelT>(r);
const PixelT * const img_row_fol = (PixelT *)(((char *)img_row) + img_.step.p[0]);
LabelT * const imgLabels_row = imgLabels_.ptr<LabelT>(r);
LabelT * const imgLabels_row_fol = (LabelT *)(((char *)imgLabels_row) + imgLabels_.step.p[0]);
// Get rows pointer
for (int c = 0; c < imgLabels_.cols; c += 2) {
LabelT iLabel = imgLabels_row[c];
if (iLabel > 0) {
iLabel = P_[iLabel];
if (img_row[c] > 0){
imgLabels_row[c] = iLabel;
sop_(r, c, iLabel);
}
else{
imgLabels_row[c] = 0;
sop_(r, c, 0);
}
if (img_row_fol[c] > 0){
imgLabels_row_fol[c] = iLabel;
sop_(r + 1, c, iLabel);
}
else{
imgLabels_row_fol[c] = 0;
sop_(r + 1, c, 0);
}
if (c + 1 < imgLabels_.cols) {
if (img_row[c + 1] > 0){
imgLabels_row[c + 1] = iLabel;
sop_(r, c + 1, iLabel);
}
else{
imgLabels_row[c + 1] = 0;
sop_(r, c + 1, 0);
}
if (img_row_fol[c + 1] > 0){
imgLabels_row_fol[c + 1] = iLabel;
sop_(r + 1, c + 1, iLabel);
}
else{
imgLabels_row_fol[c + 1] = 0;
sop_(r + 1, c + 1, 0);
}
}
}
else{
imgLabels_row[c] = 0;
imgLabels_row_fol[c] = 0;
sop_(r, c, 0);
sop_(r + 1, c, 0);
if (c + 1 < imgLabels_.cols) {
imgLabels_row[c + 1] = 0;
imgLabels_row_fol[c + 1] = 0;
sop_(r, c + 1, 0);
sop_(r + 1, c + 1, 0);
}
}
}
}
}// END case 3
else{
//Case 4: nothing odd
for (; r < rowEnd; r += 2){
// Get rows pointer
const PixelT * const img_row = img_.ptr<PixelT>(r);
const PixelT * const img_row_fol = (PixelT *)(((char *)img_row) + img_.step.p[0]);
LabelT * const imgLabels_row = imgLabels_.ptr<LabelT>(r);
LabelT * const imgLabels_row_fol = (LabelT *)(((char *)imgLabels_row) + imgLabels_.step.p[0]);
// Get rows pointer
for (int c = 0; c < imgLabels_.cols; c += 2) {
LabelT iLabel = imgLabels_row[c];
if (iLabel > 0) {
iLabel = P_[iLabel];
if (img_row[c] > 0){
imgLabels_row[c] = iLabel;
sop_(r, c, iLabel);
}
else{
imgLabels_row[c] = 0;
sop_(r, c, 0);
}
if (img_row[c + 1] > 0){
imgLabels_row[c + 1] = iLabel;
sop_(r, c + 1, iLabel);
}
else{
imgLabels_row[c + 1] = 0;
sop_(r, c + 1, 0);
}
if (img_row_fol[c] > 0){
imgLabels_row_fol[c] = iLabel;
sop_(r + 1, c, iLabel);
}
else{
imgLabels_row_fol[c] = 0;
sop_(r + 1, c, 0);
}
if (img_row_fol[c + 1] > 0){
imgLabels_row_fol[c + 1] = iLabel;
sop_(r + 1, c + 1, iLabel);
}
else{
imgLabels_row_fol[c + 1] = 0;
sop_(r + 1, c + 1, 0);
}
}
else {
imgLabels_row[c] = 0;
imgLabels_row[c + 1] = 0;
imgLabels_row_fol[c] = 0;
imgLabels_row_fol[c + 1] = 0;
sop_(r, c, 0);
sop_(r, c + 1, 0);
sop_(r + 1, c, 0);
sop_(r + 1, c + 1, 0);
}
}
}//END case 4
}
}
}
}
};
inline static
void mergeLabels(const cv::Mat& img, cv::Mat& imgLabels, LabelT *P, int *chunksSizeAndLabels){
// Merge Mask
// +---+---+---+
// |P -|Q -|R -|
// |- -|- -|- -|
// +---+---+---+
// |X -|
// |- -|
// +---+
const int w = imgLabels.cols, h = imgLabels.rows;
for (int r = chunksSizeAndLabels[0]; r < h; r = chunksSizeAndLabels[r]){
LabelT * const imgLabels_row = imgLabels.ptr<LabelT>(r);
LabelT * const imgLabels_row_prev_prev = (LabelT *)(((char *)imgLabels_row) - imgLabels.step.p[0] - imgLabels.step.p[0]);
const PixelT * const img_row = img.ptr<PixelT>(r);
const PixelT * const img_row_prev = (PixelT *)(((char *)img_row) - img.step.p[0]);
for (int c = 0; c < w; c += 2){
#define condition_x imgLabels_row[c] > 0
#define condition_pppr c > 1 && imgLabels_row_prev_prev[c - 2] > 0
#define condition_qppr imgLabels_row_prev_prev[c] > 0
#define condition_qppr1 c < w - 1
#define condition_qppr2 c < w
#define condition_rppr c < w - 2 && imgLabels_row_prev_prev[c + 2] > 0
if (condition_x){
if (condition_pppr){
//check in img
if (img_row[c] > 0 && img_row_prev[c - 1] > 0)
//assign the same label
imgLabels_row[c] = set_union(P, imgLabels_row_prev_prev[c - 2], imgLabels_row[c]);
}
if (condition_qppr){
if (condition_qppr1){
if ((img_row[c] > 0 && img_row_prev[c] > 0) || (img_row[c + 1] > 0 && img_row_prev[c] > 0) ||
(img_row[c] > 0 && img_row_prev[c + 1] > 0) || (img_row[c + 1] > 0 && img_row_prev[c + 1] > 0)){
imgLabels_row[c] = set_union(P, imgLabels_row_prev_prev[c], imgLabels_row[c]);
}
}
else /*if (condition_qppr2)*/{
if (img_row[c] > 0 && img_row_prev[c] > 0)
imgLabels_row[c] = set_union(P, imgLabels_row_prev_prev[c], imgLabels_row[c]);
}
}
if (condition_rppr){
if (img_row[c + 1] > 0 && img_row_prev[c + 2] > 0)
imgLabels_row[c] = set_union(P, imgLabels_row_prev_prev[c + 2], imgLabels_row[c]);
}
}
}
}
}
LabelT operator()(const cv::Mat& img, cv::Mat& imgLabels, int connectivity, StatsOp& sop){
CV_Assert(img.rows == imgLabels.rows);
CV_Assert(img.cols == imgLabels.cols);
CV_Assert(connectivity == 8);
const int h = img.rows;
const int w = img.cols;
//A quick and dirty upper bound for the maximum number of labels.
//Following formula comes from the fact that a 2x2 block in 8-connectivity case
//can never have more than 1 new label and 1 label for background.
//Worst case image example pattern:
//1 0 1 0 1...
//0 0 0 0 0...
//1 0 1 0 1...
//............
const size_t Plength = size_t(((h + 1) / 2) * size_t((w + 1) / 2)) + 1;
//Array used to store info and labeled pixel by each thread.
//Different threads affect different memory location of chunksSizeAndLabels
int *chunksSizeAndLabels = (int *)cv::fastMalloc(h * sizeof(int));
//Tree of labels
LabelT *P = (LabelT *)cv::fastMalloc(Plength * sizeof(LabelT));
//First label is for background
P[0] = 0;
cv::Range range(0, h);
const double nParallelStripes = std::max(1, std::min(h / 2, getNumThreads()*4));
//First scan, each thread works with chunk of img.rows/nThreads rows
//e.g. 300 rows, 4 threads -> each chunks is composed of 75 rows
cv::parallel_for_(range, FirstScan(img, imgLabels, P, chunksSizeAndLabels), nParallelStripes);
//merge labels of different chunks
mergeLabels(img, imgLabels, P, chunksSizeAndLabels);
LabelT nLabels = 1;
for (int i = 0; i < h; i = chunksSizeAndLabels[i]){
flattenL(P, LabelT((i + 1) / 2) * LabelT((w + 1) / 2) + 1, chunksSizeAndLabels[i + 1], nLabels);
}
//Array for statistics data
StatsOp *sopArray = new StatsOp[h];
sop.init(nLabels);
//Second scan
cv::parallel_for_(range, SecondScan(img, imgLabels, P, sop, sopArray, nLabels), nParallelStripes);
StatsOp::mergeStats(imgLabels, sopArray, sop, nLabels);
sop.finish();
delete[] sopArray;
cv::fastFree(chunksSizeAndLabels);
cv::fastFree(P);
return nLabels;
}
};//End struct LabelingGranaParallel
// Based on "Optimized Block-based Connected Components Labeling with Decision Trees", Costantino Grana et al
// Only for 8-connectivity
template<typename LabelT, typename PixelT, typename StatsOp = NoOp >
struct LabelingGrana{
LabelT operator()(const cv::Mat& img, cv::Mat& imgLabels, int connectivity, StatsOp& sop){
CV_Assert(img.rows == imgLabels.rows);
CV_Assert(img.cols == imgLabels.cols);
CV_Assert(connectivity == 8);
const int h = img.rows;
const int w = img.cols;
//A quick and dirty upper bound for the maximum number of labels.
//Following formula comes from the fact that a 2x2 block in 8-connectivity case
//can never have more than 1 new label and 1 label for background.
//Worst case image example pattern:
//1 0 1 0 1...
//0 0 0 0 0...
//1 0 1 0 1...
//............
const size_t Plength = size_t(((h + 1) / 2) * size_t((w + 1) / 2)) + 1;
LabelT *P = (LabelT *)fastMalloc(sizeof(LabelT) *Plength);
P[0] = 0;
LabelT lunique = 1;
// First scan
for (int r = 0; r < h; r += 2) {
// Get rows pointer
const PixelT * const img_row = img.ptr<PixelT>(r);
const PixelT * const img_row_prev = (PixelT *)(((char *)img_row) - img.step.p[0]);
const PixelT * const img_row_prev_prev = (PixelT *)(((char *)img_row_prev) - img.step.p[0]);
const PixelT * const img_row_fol = (PixelT *)(((char *)img_row) + img.step.p[0]);
LabelT * const imgLabels_row = imgLabels.ptr<LabelT>(r);
LabelT * const imgLabels_row_prev_prev = (LabelT *)(((char *)imgLabels_row) - imgLabels.step.p[0] - imgLabels.step.p[0]);
for (int c = 0; c < w; c += 2) {
// We work with 2x2 blocks
// +-+-+-+
// |P|Q|R|
// +-+-+-+
// |S|X|
// +-+-+
// The pixels are named as follows
// +---+---+---+
// |a b|c d|e f|
// |g h|i j|k l|
// +---+---+---+
// |m n|o p|
// |q r|s t|
// +---+---+
// Pixels a, f, l, q are not needed, since we need to understand the
// the connectivity between these blocks and those pixels only metter
// when considering the outer connectivities
// A bunch of defines used to check if the pixels are foreground,
// without going outside the image limits.
#define condition_b c-1>=0 && r-2>=0 && img_row_prev_prev[c-1]>0
#define condition_c r-2>=0 && img_row_prev_prev[c]>0
#define condition_d c+1<w&& r-2>=0 && img_row_prev_prev[c+1]>0
#define condition_e c+2<w && r-1>=0 && img_row_prev[c-1]>0
#define condition_g c-2>=0 && r-1>=0 && img_row_prev[c-2]>0
#define condition_h c-1>=0 && r-1>=0 && img_row_prev[c-1]>0
#define condition_i r-1>=0 && img_row_prev[c]>0
#define condition_j c+1<w && r-1>=0 && img_row_prev[c+1]>0
#define condition_k c+2<w && r-1>=0 && img_row_prev[c+2]>0
#define condition_m c-2>=0 && img_row[c-2]>0
#define condition_n c-1>=0 && img_row[c-1]>0
#define condition_o img_row[c]>0
#define condition_p c+1<w && img_row[c+1]>0
#define condition_r c-1>=0 && r+1<h && img_row_fol[c-1]>0
#define condition_s r+1<h && img_row_fol[c]>0
#define condition_t c+1<w && r+1<h && img_row_fol[c+1]>0
// This is a decision tree which allows to choose which action to
// perform, checking as few conditions as possible.
// Actions: the blocks label are provisionally stored in the top left
// pixel of the block in the labels image
if (condition_o) {
if (condition_n) {
if (condition_j) {
if (condition_i) {
//Action_6: Assign label of block S
imgLabels_row[c] = imgLabels_row[c - 2];
continue;
}
else {
if (condition_c) {
if (condition_h) {
//Action_6: Assign label of block S
imgLabels_row[c] = imgLabels_row[c - 2];
continue;
}
else {
if (condition_g) {
if (condition_b) {
//Action_6: Assign label of block S
imgLabels_row[c] = imgLabels_row[c - 2];
continue;
}
else {
//Action_11: Merge labels of block Q and S
imgLabels_row[c] = set_union(P, imgLabels_row_prev_prev[c], imgLabels_row[c - 2]);
continue;
}
}
else {
//Action_11: Merge labels of block Q and S
imgLabels_row[c] = set_union(P, imgLabels_row_prev_prev[c], imgLabels_row[c - 2]);
continue;
}
}
}
else {
//Action_11: Merge labels of block Q and S
imgLabels_row[c] = set_union(P, imgLabels_row_prev_prev[c], imgLabels_row[c - 2]);
continue;
}
}
}
else {
if (condition_p) {
if (condition_k) {
if (condition_d) {
if (condition_i) {
//Action_6: Assign label of block S
imgLabels_row[c] = imgLabels_row[c - 2];
continue;
}
else {
if (condition_c) {
if (condition_h) {
//Action_6: Assign label of block S
imgLabels_row[c] = imgLabels_row[c - 2];
continue;
}
else {
if (condition_g) {
if (condition_b) {
//Action_6: Assign label of block S
imgLabels_row[c] = imgLabels_row[c - 2];
continue;
}
else {
//Action_12: Merge labels of block R and S
imgLabels_row[c] = set_union(P, imgLabels_row_prev_prev[c + 2], imgLabels_row[c - 2]);
continue;
}
}
else {
//Action_12: Merge labels of block R and S
imgLabels_row[c] = set_union(P, imgLabels_row_prev_prev[c + 2], imgLabels_row[c - 2]);
continue;
}
}
}
else {
//Action_12: Merge labels of block R and S
imgLabels_row[c] = set_union(P, imgLabels_row_prev_prev[c + 2], imgLabels_row[c - 2]);
continue;
}
}
}
else {
//Action_12: Merge labels of block R and S
imgLabels_row[c] = set_union(P, imgLabels_row_prev_prev[c + 2], imgLabels_row[c - 2]);
continue;
}
}
else {
//Action_6: Assign label of block S
imgLabels_row[c] = imgLabels_row[c - 2];
continue;
}
}
else {
//Action_6: Assign label of block S
imgLabels_row[c] = imgLabels_row[c - 2];
continue;
}
}
}
else {
if (condition_r) {
if (condition_j) {
if (condition_m) {
if (condition_h) {
if (condition_i) {
//Action_6: Assign label of block S
imgLabels_row[c] = imgLabels_row[c - 2];
continue;
}
else {
if (condition_c) {
//Action_6: Assign label of block S
imgLabels_row[c] = imgLabels_row[c - 2];
continue;
}
else {
//Action_11: Merge labels of block Q and S
imgLabels_row[c] = set_union(P, imgLabels_row_prev_prev[c], imgLabels_row[c - 2]);
continue;
}
}
}
else {
if (condition_g) {
if (condition_b) {
if (condition_i) {
//Action_6: Assign label of block S
imgLabels_row[c] = imgLabels_row[c - 2];
continue;
}
else {
if (condition_c) {
//Action_6: Assign label of block S
imgLabels_row[c] = imgLabels_row[c - 2];
continue;
}
else {
//Action_11: Merge labels of block Q and S
imgLabels_row[c] = set_union(P, imgLabels_row_prev_prev[c], imgLabels_row[c - 2]);
continue;
}
}
}
else {
//Action_11: Merge labels of block Q and S
imgLabels_row[c] = set_union(P, imgLabels_row_prev_prev[c], imgLabels_row[c - 2]);
continue;
}
}
else {
//Action_11: Merge labels of block Q and S
imgLabels_row[c] = set_union(P, imgLabels_row_prev_prev[c], imgLabels_row[c - 2]);
continue;
}
}
}
else {
if (condition_i) {
//Action_11: Merge labels of block Q and S
imgLabels_row[c] = set_union(P, imgLabels_row_prev_prev[c], imgLabels_row[c - 2]);
continue;
}
else {
if (condition_h) {
if (condition_c) {
//Action_11: Merge labels of block Q and S
imgLabels_row[c] = set_union(P, imgLabels_row_prev_prev[c], imgLabels_row[c - 2]);
continue;
}
else {
//Action_14: Merge labels of block P, Q and S
imgLabels_row[c] = set_union(P, set_union(P, imgLabels_row_prev_prev[c - 2], imgLabels_row_prev_prev[c]), imgLabels_row[c - 2]);
continue;
}
}
else {
//Action_11: Merge labels of block Q and S
imgLabels_row[c] = set_union(P, imgLabels_row_prev_prev[c], imgLabels_row[c - 2]);
continue;
}
}
}
}
else {
if (condition_p) {
if (condition_k) {
if (condition_m) {
if (condition_h) {
if (condition_d) {
if (condition_i) {
//Action_6: Assign label of block S
imgLabels_row[c] = imgLabels_row[c - 2];
continue;
}
else {
if (condition_c) {
//Action_6: Assign label of block S
imgLabels_row[c] = imgLabels_row[c - 2];
continue;
}
else {
//Action_12: Merge labels of block R and S
imgLabels_row[c] = set_union(P, imgLabels_row_prev_prev[c + 2], imgLabels_row[c - 2]);
continue;
}
}
}
else {
//Action_12: Merge labels of block R and S
imgLabels_row[c] = set_union(P, imgLabels_row_prev_prev[c + 2], imgLabels_row[c - 2]);
continue;
}
}
else {
if (condition_d) {
if (condition_g) {
if (condition_b) {
if (condition_i) {
//Action_6: Assign label of block S
imgLabels_row[c] = imgLabels_row[c - 2];
continue;
}
else {
if (condition_c) {
//Action_6: Assign label of block S
imgLabels_row[c] = imgLabels_row[c - 2];
continue;
}
else {
//Action_12: Merge labels of block R and S
imgLabels_row[c] = set_union(P, imgLabels_row_prev_prev[c + 2], imgLabels_row[c - 2]);
continue;
}
}
}
else {
//Action_12: Merge labels of block R and S
imgLabels_row[c] = set_union(P, imgLabels_row_prev_prev[c + 2], imgLabels_row[c - 2]);
continue;
}
}
else {
//Action_12: Merge labels of block R and S
imgLabels_row[c] = set_union(P, imgLabels_row_prev_prev[c + 2], imgLabels_row[c - 2]);
continue;
}
}
else {
if (condition_i) {
if (condition_g) {
if (condition_b) {
//Action_12: Merge labels of block R and S
imgLabels_row[c] = set_union(P, imgLabels_row_prev_prev[c + 2], imgLabels_row[c - 2]);
continue;
}
else {
//Action_16: labels of block Q, R and S
imgLabels_row[c] = set_union(P, set_union(P, imgLabels_row_prev_prev[c], imgLabels_row_prev_prev[c + 2]), imgLabels_row[c - 2]);
continue;
}
}
else {
//Action_16: labels of block Q, R and S
imgLabels_row[c] = set_union(P, set_union(P, imgLabels_row_prev_prev[c], imgLabels_row_prev_prev[c + 2]), imgLabels_row[c - 2]);
continue;
}
}
else {
//Action_12: Merge labels of block R and S
imgLabels_row[c] = set_union(P, imgLabels_row_prev_prev[c + 2], imgLabels_row[c - 2]);
continue;
}
}
}
}
else {
if (condition_i) {
if (condition_d) {
//Action_12: Merge labels of block R and S
imgLabels_row[c] = set_union(P, imgLabels_row_prev_prev[c + 2], imgLabels_row[c - 2]);
continue;
}
else {
//Action_16: labels of block Q, R and S
imgLabels_row[c] = set_union(P, set_union(P, imgLabels_row_prev_prev[c], imgLabels_row_prev_prev[c + 2]), imgLabels_row[c - 2]);
continue;
}
}
else {
if (condition_h) {
if (condition_d) {
if (condition_c) {
//Action_12: Merge labels of block R and S
imgLabels_row[c] = set_union(P, imgLabels_row_prev_prev[c + 2], imgLabels_row[c - 2]);
continue;
}
else {
//Action_15: Merge labels of block P, R and S
imgLabels_row[c] = set_union(P, set_union(P, imgLabels_row_prev_prev[c - 2], imgLabels_row_prev_prev[c + 2]), imgLabels_row[c - 2]);
continue;
}
}
else {
//Action_15: Merge labels of block P, R and S
imgLabels_row[c] = set_union(P, set_union(P, imgLabels_row_prev_prev[c - 2], imgLabels_row_prev_prev[c + 2]), imgLabels_row[c - 2]);
continue;
}
}
else {
//Action_12: Merge labels of block R and S
imgLabels_row[c] = set_union(P, imgLabels_row_prev_prev[c + 2], imgLabels_row[c - 2]);
continue;
}
}
}
}
else {
if (condition_h) {
if (condition_m) {
//Action_6: Assign label of block S
imgLabels_row[c] = imgLabels_row[c - 2];
continue;
}
else {
// ACTION_9 Merge labels of block P and S
imgLabels_row[c] = set_union(P, imgLabels_row_prev_prev[c - 2], imgLabels_row[c - 2]);
continue;
}
}
else {
if (condition_i) {
if (condition_m) {
if (condition_g) {
if (condition_b) {
//Action_6: Assign label of block S
imgLabels_row[c] = imgLabels_row[c - 2];
continue;
}
else {
//Action_11: Merge labels of block Q and S
imgLabels_row[c] = set_union(P, imgLabels_row_prev_prev[c], imgLabels_row[c - 2]);
continue;
}
}
else {
//Action_11: Merge labels of block Q and S
imgLabels_row[c] = set_union(P, imgLabels_row_prev_prev[c], imgLabels_row[c - 2]);
continue;
}
}
else {
//Action_11: Merge labels of block Q and S
imgLabels_row[c] = set_union(P, imgLabels_row_prev_prev[c], imgLabels_row[c - 2]);
continue;
}
}
else {
//Action_6: Assign label of block S
imgLabels_row[c] = imgLabels_row[c - 2];
continue;
}
}
}
}
else {
if (condition_h) {
if (condition_m) {
//Action_6: Assign label of block S
imgLabels_row[c] = imgLabels_row[c - 2];
continue;
}
else {
// ACTION_9 Merge labels of block P and S
imgLabels_row[c] = set_union(P, imgLabels_row_prev_prev[c - 2], imgLabels_row[c - 2]);
continue;
}
}
else {
if (condition_i) {
if (condition_m) {
if (condition_g) {
if (condition_b) {
//Action_6: Assign label of block S
imgLabels_row[c] = imgLabels_row[c - 2];
continue;
}
else {
//Action_11: Merge labels of block Q and S
imgLabels_row[c] = set_union(P, imgLabels_row_prev_prev[c], imgLabels_row[c - 2]);
continue;
}
}
else {
//Action_11: Merge labels of block Q and S
imgLabels_row[c] = set_union(P, imgLabels_row_prev_prev[c], imgLabels_row[c - 2]);
continue;
}
}
else {
//Action_11: Merge labels of block Q and S
imgLabels_row[c] = set_union(P, imgLabels_row_prev_prev[c], imgLabels_row[c - 2]);
continue;
}
}
else {
//Action_6: Assign label of block S
imgLabels_row[c] = imgLabels_row[c - 2];
continue;
}
}
}
}
}
else {
if (condition_j) {
if (condition_i) {
//Action_4: Assign label of block Q
imgLabels_row[c] = imgLabels_row_prev_prev[c];
continue;
}
else {
if (condition_h) {
if (condition_c) {
//Action_4: Assign label of block Q
imgLabels_row[c] = imgLabels_row_prev_prev[c];
continue;
}
else {
//Action_7: Merge labels of block P and Q
imgLabels_row[c] = set_union(P, imgLabels_row_prev_prev[c - 2], imgLabels_row_prev_prev[c]);
continue;
}
}
else {
//Action_4: Assign label of block Q
imgLabels_row[c] = imgLabels_row_prev_prev[c];
continue;
}
}
}
else {
if (condition_p) {
if (condition_k) {
if (condition_i) {
if (condition_d) {
//Action_5: Assign label of block R
imgLabels_row[c] = imgLabels_row_prev_prev[c + 2];
continue;
}
else {
// ACTION_10 Merge labels of block Q and R
imgLabels_row[c] = set_union(P, imgLabels_row_prev_prev[c], imgLabels_row_prev_prev[c + 2]);
continue;
}
}
else {
if (condition_h) {
if (condition_d) {
if (condition_c) {
//Action_5: Assign label of block R
imgLabels_row[c] = imgLabels_row_prev_prev[c + 2];
continue;
}
else {
//Action_8: Merge labels of block P and R
imgLabels_row[c] = set_union(P, imgLabels_row_prev_prev[c - 2], imgLabels_row_prev_prev[c + 2]);
continue;
}
}
else {
//Action_8: Merge labels of block P and R
imgLabels_row[c] = set_union(P, imgLabels_row_prev_prev[c - 2], imgLabels_row_prev_prev[c + 2]);
continue;
}
}
else {
//Action_5: Assign label of block R
imgLabels_row[c] = imgLabels_row_prev_prev[c + 2];
continue;
}
}
}
else {
if (condition_i) {
//Action_4: Assign label of block Q
imgLabels_row[c] = imgLabels_row_prev_prev[c];
continue;
}
else {
if (condition_h) {
//Action_3: Assign label of block P
imgLabels_row[c] = imgLabels_row_prev_prev[c - 2];
continue;
}
else {
//Action_2: New label (the block has foreground pixels and is not connected to anything else)
imgLabels_row[c] = lunique;
P[lunique] = lunique;
lunique = lunique + 1;
continue;
}
}
}
}
else {
if (condition_i) {
//Action_4: Assign label of block Q
imgLabels_row[c] = imgLabels_row_prev_prev[c];
continue;
}
else {
if (condition_h) {
//Action_3: Assign label of block P
imgLabels_row[c] = imgLabels_row_prev_prev[c - 2];
continue;
}
else {
//Action_2: New label (the block has foreground pixels and is not connected to anything else)
imgLabels_row[c] = lunique;
P[lunique] = lunique;
lunique = lunique + 1;
continue;
}
}
}
}
}
}
}
else {
if (condition_s) {
if (condition_p) {
if (condition_n) {
if (condition_j) {
if (condition_i) {
//Action_6: Assign label of block S
imgLabels_row[c] = imgLabels_row[c - 2];
continue;
}
else {
if (condition_c) {
if (condition_h) {
//Action_6: Assign label of block S
imgLabels_row[c] = imgLabels_row[c - 2];
continue;
}
else {
if (condition_g) {
if (condition_b) {
//Action_6: Assign label of block S
imgLabels_row[c] = imgLabels_row[c - 2];
continue;
}
else {
//Action_11: Merge labels of block Q and S
imgLabels_row[c] = set_union(P, imgLabels_row_prev_prev[c], imgLabels_row[c - 2]);
continue;
}
}
else {
//Action_11: Merge labels of block Q and S
imgLabels_row[c] = set_union(P, imgLabels_row_prev_prev[c], imgLabels_row[c - 2]);
continue;
}
}
}
else {
//Action_11: Merge labels of block Q and S
imgLabels_row[c] = set_union(P, imgLabels_row_prev_prev[c], imgLabels_row[c - 2]);
continue;
}
}
}
else {
if (condition_k) {
if (condition_d) {
if (condition_i) {
//Action_6: Assign label of block S
imgLabels_row[c] = imgLabels_row[c - 2];
continue;
}
else {
if (condition_c) {
if (condition_h) {
//Action_6: Assign label of block S
imgLabels_row[c] = imgLabels_row[c - 2];
continue;
}
else {
if (condition_g) {
if (condition_b) {
//Action_6: Assign label of block S
imgLabels_row[c] = imgLabels_row[c - 2];
continue;
}
else {
//Action_12: Merge labels of block R and S
imgLabels_row[c] = set_union(P, imgLabels_row_prev_prev[c + 2], imgLabels_row[c - 2]);
continue;
}
}
else {
//Action_12: Merge labels of block R and S
imgLabels_row[c] = set_union(P, imgLabels_row_prev_prev[c + 2], imgLabels_row[c - 2]);
continue;
}
}
}
else {
//Action_12: Merge labels of block R and S
imgLabels_row[c] = set_union(P, imgLabels_row_prev_prev[c + 2], imgLabels_row[c - 2]);
continue;
}
}
}
else {
//Action_12: Merge labels of block R and S
imgLabels_row[c] = set_union(P, imgLabels_row_prev_prev[c + 2], imgLabels_row[c - 2]);
continue;
}
}
else {
//Action_6: Assign label of block S
imgLabels_row[c] = imgLabels_row[c - 2];
continue;
}
}
}
else {
if (condition_r) {
if (condition_j) {
if (condition_m) {
if (condition_h) {
if (condition_i) {
//Action_6: Assign label of block S
imgLabels_row[c] = imgLabels_row[c - 2];
continue;
}
else {
if (condition_c) {
//Action_6: Assign label of block S
imgLabels_row[c] = imgLabels_row[c - 2];
continue;
}
else {
//Action_11: Merge labels of block Q and S
imgLabels_row[c] = set_union(P, imgLabels_row_prev_prev[c], imgLabels_row[c - 2]);
continue;
}
}
}
else {
if (condition_g) {
if (condition_b) {
if (condition_i) {
//Action_6: Assign label of block S
imgLabels_row[c] = imgLabels_row[c - 2];
continue;
}
else {
if (condition_c) {
//Action_6: Assign label of block S
imgLabels_row[c] = imgLabels_row[c - 2];
continue;
}
else {
//Action_11: Merge labels of block Q and S
imgLabels_row[c] = set_union(P, imgLabels_row_prev_prev[c], imgLabels_row[c - 2]);
continue;
}
}
}
else {
//Action_11: Merge labels of block Q and S
imgLabels_row[c] = set_union(P, imgLabels_row_prev_prev[c], imgLabels_row[c - 2]);
continue;
}
}
else {
//Action_11: Merge labels of block Q and S
imgLabels_row[c] = set_union(P, imgLabels_row_prev_prev[c], imgLabels_row[c - 2]);
continue;
}
}
}
else {
//Action_11: Merge labels of block Q and S
imgLabels_row[c] = set_union(P, imgLabels_row_prev_prev[c], imgLabels_row[c - 2]);
continue;
}
}
else {
if (condition_k) {
if (condition_d) {
if (condition_m) {
if (condition_h) {
if (condition_i) {
//Action_6: Assign label of block S
imgLabels_row[c] = imgLabels_row[c - 2];
continue;
}
else {
if (condition_c) {
//Action_6: Assign label of block S
imgLabels_row[c] = imgLabels_row[c - 2];
continue;
}
else {
//Action_12: Merge labels of block R and S
imgLabels_row[c] = set_union(P, imgLabels_row_prev_prev[c + 2], imgLabels_row[c - 2]);
continue;
}
}
}
else {
if (condition_g) {
if (condition_b) {
if (condition_i) {
//Action_6: Assign label of block S
imgLabels_row[c] = imgLabels_row[c - 2];
continue;
}
else {
if (condition_c) {
//Action_6: Assign label of block S
imgLabels_row[c] = imgLabels_row[c - 2];
continue;
}
else {
//Action_12: Merge labels of block R and S
imgLabels_row[c] = set_union(P, imgLabels_row_prev_prev[c + 2], imgLabels_row[c - 2]);
continue;
}
}
}
else {
//Action_12: Merge labels of block R and S
imgLabels_row[c] = set_union(P, imgLabels_row_prev_prev[c + 2], imgLabels_row[c - 2]);
continue;
}
}
else {
//Action_12: Merge labels of block R and S
imgLabels_row[c] = set_union(P, imgLabels_row_prev_prev[c + 2], imgLabels_row[c - 2]);
continue;
}
}
}
else {
//Action_12: Merge labels of block R and S
imgLabels_row[c] = set_union(P, imgLabels_row_prev_prev[c + 2], imgLabels_row[c - 2]);
continue;
}
}
else {
if (condition_i) {
if (condition_m) {
if (condition_h) {
//Action_12: Merge labels of block R and S
imgLabels_row[c] = set_union(P, imgLabels_row_prev_prev[c + 2], imgLabels_row[c - 2]);
continue;
}
else {
if (condition_g) {
if (condition_b) {
//Action_12: Merge labels of block R and S
imgLabels_row[c] = set_union(P, imgLabels_row_prev_prev[c + 2], imgLabels_row[c - 2]);
continue;
}
else {
//Action_16: labels of block Q, R and S
imgLabels_row[c] = set_union(P, set_union(P, imgLabels_row_prev_prev[c], imgLabels_row_prev_prev[c + 2]), imgLabels_row[c - 2]);
continue;
}
}
else {
//Action_16: labels of block Q, R and S
imgLabels_row[c] = set_union(P, set_union(P, imgLabels_row_prev_prev[c], imgLabels_row_prev_prev[c + 2]), imgLabels_row[c - 2]);
continue;
}
}
}
else {
//Action_16: labels of block Q, R and S
imgLabels_row[c] = set_union(P, set_union(P, imgLabels_row_prev_prev[c], imgLabels_row_prev_prev[c + 2]), imgLabels_row[c - 2]);
continue;
}
}
else {
//Action_12: Merge labels of block R and S
imgLabels_row[c] = set_union(P, imgLabels_row_prev_prev[c + 2], imgLabels_row[c - 2]);
continue;
}
}
}
else {
if (condition_i) {
if (condition_m) {
if (condition_h) {
//Action_6: Assign label of block S
imgLabels_row[c] = imgLabels_row[c - 2];
continue;
}
else {
if (condition_g) {
if (condition_b) {
//Action_6: Assign label of block S
imgLabels_row[c] = imgLabels_row[c - 2];
continue;
}
else {
//Action_11: Merge labels of block Q and S
imgLabels_row[c] = set_union(P, imgLabels_row_prev_prev[c], imgLabels_row[c - 2]);
continue;
}
}
else {
//Action_11: Merge labels of block Q and S
imgLabels_row[c] = set_union(P, imgLabels_row_prev_prev[c], imgLabels_row[c - 2]);
continue;
}
}
}
else {
//Action_11: Merge labels of block Q and S
imgLabels_row[c] = set_union(P, imgLabels_row_prev_prev[c], imgLabels_row[c - 2]);
continue;
}
}
else {
//Action_6: Assign label of block S
imgLabels_row[c] = imgLabels_row[c - 2];
continue;
}
}
}
}
else {
if (condition_j) {
//Action_4: Assign label of block Q
imgLabels_row[c] = imgLabels_row_prev_prev[c];
continue;
}
else {
if (condition_k) {
if (condition_i) {
if (condition_d) {
//Action_5: Assign label of block R
imgLabels_row[c] = imgLabels_row_prev_prev[c + 2];
continue;
}
else {
// ACTION_10 Merge labels of block Q and R
imgLabels_row[c] = set_union(P, imgLabels_row_prev_prev[c], imgLabels_row_prev_prev[c + 2]);
continue;
}
}
else {
//Action_5: Assign label of block R
imgLabels_row[c] = imgLabels_row_prev_prev[c + 2];
continue;
}
}
else {
if (condition_i) {
//Action_4: Assign label of block Q
imgLabels_row[c] = imgLabels_row_prev_prev[c];
continue;
}
else {
//Action_2: New label (the block has foreground pixels and is not connected to anything else)
imgLabels_row[c] = lunique;
P[lunique] = lunique;
lunique = lunique + 1;
continue;
}
}
}
}
}
}
else {
if (condition_r) {
//Action_6: Assign label of block S
imgLabels_row[c] = imgLabels_row[c - 2];
continue;
}
else {
if (condition_n) {
//Action_6: Assign label of block S
imgLabels_row[c] = imgLabels_row[c - 2];
continue;
}
else {
//Action_2: New label (the block has foreground pixels and is not connected to anything else)
imgLabels_row[c] = lunique;
P[lunique] = lunique;
lunique = lunique + 1;
continue;
}
}
}
}
else {
if (condition_p) {
if (condition_j) {
//Action_4: Assign label of block Q
imgLabels_row[c] = imgLabels_row_prev_prev[c];
continue;
}
else {
if (condition_k) {
if (condition_i) {
if (condition_d) {
//Action_5: Assign label of block R
imgLabels_row[c] = imgLabels_row_prev_prev[c + 2];
continue;
}
else {
// ACTION_10 Merge labels of block Q and R
imgLabels_row[c] = set_union(P, imgLabels_row_prev_prev[c], imgLabels_row_prev_prev[c + 2]);
continue;
}
}
else {
//Action_5: Assign label of block R
imgLabels_row[c] = imgLabels_row_prev_prev[c + 2];
continue;
}
}
else {
if (condition_i) {
//Action_4: Assign label of block Q
imgLabels_row[c] = imgLabels_row_prev_prev[c];
continue;
}
else {
//Action_2: New label (the block has foreground pixels and is not connected to anything else)
imgLabels_row[c] = lunique;
P[lunique] = lunique;
lunique = lunique + 1;
continue;
}
}
}
}
else {
if (condition_t) {
//Action_2: New label (the block has foreground pixels and is not connected to anything else)
imgLabels_row[c] = lunique;
P[lunique] = lunique;
lunique = lunique + 1;
continue;
}
else {
// Action_1: No action (the block has no foreground pixels)
imgLabels_row[c] = 0;
continue;
}
}
}
}
}
}
// Second scan + analysis
LabelT nLabels = flattenL(P, lunique);
sop.init(nLabels);
if (imgLabels.rows & 1){
if (imgLabels.cols & 1){
//Case 1: both rows and cols odd
for (int r = 0; r < imgLabels.rows; r += 2) {
// Get rows pointer
const PixelT * const img_row = img.ptr<PixelT>(r);
const PixelT * const img_row_fol = (PixelT *)(((char *)img_row) + img.step.p[0]);
LabelT * const imgLabels_row = imgLabels.ptr<LabelT>(r);
LabelT * const imgLabels_row_fol = (LabelT *)(((char *)imgLabels_row) + imgLabels.step.p[0]);
for (int c = 0; c < imgLabels.cols; c += 2) {
LabelT iLabel = imgLabels_row[c];
if (iLabel > 0) {
iLabel = P[iLabel];
if (img_row[c] > 0){
imgLabels_row[c] = iLabel;
sop(r, c, iLabel);
}
else{
imgLabels_row[c] = 0;
sop(r, c, 0);
}
if (c + 1 < imgLabels.cols) {
if (img_row[c + 1] > 0){
imgLabels_row[c + 1] = iLabel;
sop(r, c + 1, iLabel);
}
else{
imgLabels_row[c + 1] = 0;
sop(r, c + 1, 0);
}
if (r + 1 < imgLabels.rows) {
if (img_row_fol[c] > 0){
imgLabels_row_fol[c] = iLabel;
sop(r + 1, c, iLabel);
}
else{
imgLabels_row_fol[c] = 0;
sop(r + 1, c, 0);
}
if (img_row_fol[c + 1] > 0){
imgLabels_row_fol[c + 1] = iLabel;
sop(r + 1, c + 1, iLabel);
}
else{
imgLabels_row_fol[c + 1] = 0;
sop(r + 1, c + 1, 0);
}
}
}
else if (r + 1 < imgLabels.rows) {
if (img_row_fol[c] > 0){
imgLabels_row_fol[c] = iLabel;
sop(r + 1, c, iLabel);
}
else{
imgLabels_row_fol[c] = 0;
sop(r + 1, c, 0);
}
}
}
else {
imgLabels_row[c] = 0;
sop(r, c, 0);
if (c + 1 < imgLabels.cols) {
imgLabels_row[c + 1] = 0;
sop(r, c + 1, 0);
if (r + 1 < imgLabels.rows) {
imgLabels_row_fol[c] = 0;
imgLabels_row_fol[c + 1] = 0;
sop(r + 1, c, 0);
sop(r + 1, c + 1, 0);
}
}
else if (r + 1 < imgLabels.rows) {
imgLabels_row_fol[c] = 0;
sop(r + 1, c, 0);
}
}
}
}
}//END Case 1
else{
//Case 2: only rows odd
for (int r = 0; r < imgLabels.rows; r += 2) {
// Get rows pointer
const PixelT * const img_row = img.ptr<PixelT>(r);
const PixelT * const img_row_fol = (PixelT *)(((char *)img_row) + img.step.p[0]);
LabelT * const imgLabels_row = imgLabels.ptr<LabelT>(r);
LabelT * const imgLabels_row_fol = (LabelT *)(((char *)imgLabels_row) + imgLabels.step.p[0]);
for (int c = 0; c < imgLabels.cols; c += 2) {
LabelT iLabel = imgLabels_row[c];
if (iLabel > 0) {
iLabel = P[iLabel];
if (img_row[c] > 0){
imgLabels_row[c] = iLabel;
sop(r, c, iLabel);
}
else{
imgLabels_row[c] = 0;
sop(r, c, 0);
}
if (img_row[c + 1] > 0){
imgLabels_row[c + 1] = iLabel;
sop(r, c + 1, iLabel);
}
else{
imgLabels_row[c + 1] = 0;
sop(r, c + 1, 0);
}
if (r + 1 < imgLabels.rows) {
if (img_row_fol[c] > 0){
imgLabels_row_fol[c] = iLabel;
sop(r + 1, c, iLabel);
}
else{
imgLabels_row_fol[c] = 0;
sop(r + 1, c, 0);
}
if (img_row_fol[c + 1] > 0){
imgLabels_row_fol[c + 1] = iLabel;
sop(r + 1, c + 1, iLabel);
}
else{
imgLabels_row_fol[c + 1] = 0;
sop(r + 1, c + 1, 0);
}
}
}
else {
imgLabels_row[c] = 0;
imgLabels_row[c + 1] = 0;
sop(r, c, 0);
sop(r, c + 1, 0);
if (r + 1 < imgLabels.rows) {
imgLabels_row_fol[c] = 0;
imgLabels_row_fol[c + 1] = 0;
sop(r + 1, c, 0);
sop(r + 1, c + 1, 0);
}
}
}
}
}// END Case 2
}
else{
if (imgLabels.cols & 1){
//Case 3: only cols odd
for (int r = 0; r < imgLabels.rows; r += 2) {
// Get rows pointer
const PixelT * const img_row = img.ptr<PixelT>(r);
const PixelT * const img_row_fol = (PixelT *)(((char *)img_row) + img.step.p[0]);
LabelT * const imgLabels_row = imgLabels.ptr<LabelT>(r);
LabelT * const imgLabels_row_fol = (LabelT *)(((char *)imgLabels_row) + imgLabels.step.p[0]);
for (int c = 0; c < imgLabels.cols; c += 2) {
LabelT iLabel = imgLabels_row[c];
if (iLabel > 0) {
iLabel = P[iLabel];
if (img_row[c] > 0){
imgLabels_row[c] = iLabel;
sop(r, c, iLabel);
}
else{
imgLabels_row[c] = 0;
sop(r, c, 0);
}
if (img_row_fol[c] > 0){
imgLabels_row_fol[c] = iLabel;
sop(r + 1, c, iLabel);
}
else{
imgLabels_row_fol[c] = 0;
sop(r + 1, c, 0);
}
if (c + 1 < imgLabels.cols) {
if (img_row[c + 1] > 0){
imgLabels_row[c + 1] = iLabel;
sop(r, c + 1, iLabel);
}
else{
imgLabels_row[c + 1] = 0;
sop(r, c + 1, 0);
}
if (img_row_fol[c + 1] > 0){
imgLabels_row_fol[c + 1] = iLabel;
sop(r + 1, c + 1, iLabel);
}
else{
imgLabels_row_fol[c + 1] = 0;
sop(r + 1, c + 1, 0);
}
}
}
else{
imgLabels_row[c] = 0;
imgLabels_row_fol[c] = 0;
sop(r, c, 0);
sop(r + 1, c, 0);
if (c + 1 < imgLabels.cols) {
imgLabels_row[c + 1] = 0;
imgLabels_row_fol[c + 1] = 0;
sop(r, c + 1, 0);
sop(r + 1, c + 1, 0);
}
}
}
}
}// END case 3
else{
//Case 4: nothing odd
for (int r = 0; r < imgLabels.rows; r += 2) {
// Get rows pointer
const PixelT * const img_row = img.ptr<PixelT>(r);
const PixelT * const img_row_fol = (PixelT *)(((char *)img_row) + img.step.p[0]);
LabelT * const imgLabels_row = imgLabels.ptr<LabelT>(r);
LabelT * const imgLabels_row_fol = (LabelT *)(((char *)imgLabels_row) + imgLabels.step.p[0]);
for (int c = 0; c < imgLabels.cols; c += 2) {
LabelT iLabel = imgLabels_row[c];
if (iLabel > 0) {
iLabel = P[iLabel];
if (img_row[c] > 0){
imgLabels_row[c] = iLabel;
sop(r, c, iLabel);
}
else{
imgLabels_row[c] = 0;
sop(r, c, 0);
}
if (img_row[c + 1] > 0){
imgLabels_row[c + 1] = iLabel;
sop(r, c + 1, iLabel);
}
else{
imgLabels_row[c + 1] = 0;
sop(r, c + 1, 0);
}
if (img_row_fol[c] > 0){
imgLabels_row_fol[c] = iLabel;
sop(r + 1, c, iLabel);
}
else{
imgLabels_row_fol[c] = 0;
sop(r + 1, c, 0);
}
if (img_row_fol[c + 1] > 0){
imgLabels_row_fol[c + 1] = iLabel;
sop(r + 1, c + 1, iLabel);
}
else{
imgLabels_row_fol[c + 1] = 0;
sop(r + 1, c + 1, 0);
}
}
else {
imgLabels_row[c] = 0;
imgLabels_row[c + 1] = 0;
imgLabels_row_fol[c] = 0;
imgLabels_row_fol[c + 1] = 0;
sop(r, c, 0);
sop(r, c + 1, 0);
sop(r + 1, c, 0);
sop(r + 1, c + 1, 0);
}
}
}
}//END case 4
}
sop.finish();
fastFree(P);
return nLabels;
} //End function LabelingGrana operator()
};//End struct LabelingGrana
}//end namespace connectedcomponents
//L's type must have an appropriate depth for the number of pixels in I
template<typename StatsOp>
static
int connectedComponents_sub1(const cv::Mat& I, cv::Mat& L, int connectivity, int ccltype, StatsOp& sop){
CV_Assert(L.channels() == 1 && I.channels() == 1);
CV_Assert(connectivity == 8 || connectivity == 4);
CV_Assert(ccltype == CCL_GRANA || ccltype == CCL_WU || ccltype == CCL_DEFAULT);
int lDepth = L.depth();
int iDepth = I.depth();
const char *currentParallelFramework = cv::currentParallelFramework();
const int nThreads = cv::getNumThreads();
CV_Assert(iDepth == CV_8U || iDepth == CV_8S);
//Run parallel labeling only if the rows of the image are at least twice the number of available threads
const bool is_parallel = currentParallelFramework != NULL && nThreads > 1 && L.rows / nThreads >= 2;
if (ccltype == CCL_WU || connectivity == 4){
// Wu algorithm is used
using connectedcomponents::LabelingWu;
using connectedcomponents::LabelingWuParallel;
//warn if L's depth is not sufficient?
if (lDepth == CV_8U){
//Not supported yet
}
else if (lDepth == CV_16U){
return (int)LabelingWu<ushort, uchar, StatsOp>()(I, L, connectivity, sop);
}
else if (lDepth == CV_32S){
//note that signed types don't really make sense here and not being able to use unsigned matters for scientific projects
//OpenCV: how should we proceed? .at<T> typechecks in debug mode
if (!is_parallel)
return (int)LabelingWu<int, uchar, StatsOp>()(I, L, connectivity, sop);
else
return (int)LabelingWuParallel<int, uchar, StatsOp>()(I, L, connectivity, sop);
}
}
else if ((ccltype == CCL_GRANA || ccltype == CCL_DEFAULT) && connectivity == 8){
// Grana algorithm is used
using connectedcomponents::LabelingGrana;
using connectedcomponents::LabelingGranaParallel;
//warn if L's depth is not sufficient?
if (lDepth == CV_8U){
//Not supported yet
}
else if (lDepth == CV_16U){
return (int)LabelingGrana<ushort, uchar, StatsOp>()(I, L, connectivity, sop);
}
else if (lDepth == CV_32S){
//note that signed types don't really make sense here and not being able to use unsigned matters for scientific projects
//OpenCV: how should we proceed? .at<T> typechecks in debug mode
if (!is_parallel)
return (int)LabelingGrana<int, uchar, StatsOp>()(I, L, connectivity, sop);
else
return (int)LabelingGranaParallel<int, uchar, StatsOp>()(I, L, connectivity, sop);
}
}
CV_Error(CV_StsUnsupportedFormat, "unsupported label/image type");
}
}
// Simple wrapper to ensure binary and source compatibility (ABI)
int cv::connectedComponents(InputArray img_, OutputArray _labels, int connectivity, int ltype){
return cv::connectedComponents(img_, _labels, connectivity, ltype, CCL_DEFAULT);
}
int cv::connectedComponents(InputArray img_, OutputArray _labels, int connectivity, int ltype, int ccltype){
const cv::Mat img = img_.getMat();
_labels.create(img.size(), CV_MAT_DEPTH(ltype));
cv::Mat labels = _labels.getMat();
connectedcomponents::NoOp sop;
if (ltype == CV_16U){
return connectedComponents_sub1(img, labels, connectivity, ccltype, sop);
}
else if (ltype == CV_32S){
return connectedComponents_sub1(img, labels, connectivity, ccltype, sop);
}
else{
CV_Error(CV_StsUnsupportedFormat, "the type of labels must be 16u or 32s");
}
}
// Simple wrapper to ensure binary and source compatibility (ABI)
int cv::connectedComponentsWithStats(InputArray img_, OutputArray _labels, OutputArray statsv,
OutputArray centroids, int connectivity, int ltype)
{
return cv::connectedComponentsWithStats(img_, _labels, statsv, centroids, connectivity, ltype, CCL_DEFAULT);
}
int cv::connectedComponentsWithStats(InputArray img_, OutputArray _labels, OutputArray statsv,
OutputArray centroids, int connectivity, int ltype, int ccltype)
{
const cv::Mat img = img_.getMat();
_labels.create(img.size(), CV_MAT_DEPTH(ltype));
cv::Mat labels = _labels.getMat();
connectedcomponents::CCStatsOp sop(statsv, centroids);
if (ltype == CV_16U){
return connectedComponents_sub1(img, labels, connectivity, ccltype, sop);
}
else if (ltype == CV_32S){
return connectedComponents_sub1(img, labels, connectivity, ccltype, sop);
}
else{
CV_Error(CV_StsUnsupportedFormat, "the type of labels must be 16u or 32s");
return 0;
}
}
| 60.816018 | 206 | 0.271015 | [
"vector"
] |
100adec689fdb4d886ff8df3fa0f9b99e4cae27d | 778 | cpp | C++ | ch09/ex9_27.cpp | Direct-Leo/CppPrimer | 9d3993c7604377abc5a925c9fe6342ad3a062983 | [
"CC0-1.0"
] | null | null | null | ch09/ex9_27.cpp | Direct-Leo/CppPrimer | 9d3993c7604377abc5a925c9fe6342ad3a062983 | [
"CC0-1.0"
] | null | null | null | ch09/ex9_27.cpp | Direct-Leo/CppPrimer | 9d3993c7604377abc5a925c9fe6342ad3a062983 | [
"CC0-1.0"
] | null | null | null | /* Created by vleo on 21/10/18
* Copyright(c)2021 vleo. All rights reserved.
*
* find and delete the odd number in a forward_list
*/
#include <iostream>
#include <vector>
#include <string>
#include <list>
#include <deque>
#include <forward_list>
using std::cin; using std::cout; using std::endl;
using std::string ;
using std::vector ;
using std::list;
using std::deque;
using std::forward_list;
int main()
{
forward_list<int> flst = {0,1,2,3,4,5,6,7,8,9};
auto prev = flst.before_begin();
auto curr = flst.begin();
while (curr != flst.end())
{
if(*curr % 2 != 0)
{
curr = flst.erase_after(prev);
}
else
{
prev = curr;
++curr;
}
}
return 0;
} | 18.52381 | 51 | 0.557841 | [
"vector"
] |
100b9e87a346abe07499a9ae5aee957295bf1d26 | 17,343 | cpp | C++ | pmc_graph.cpp | david-ngo-sixense/pmc | f94f1674cabf0d57fd9a4d7499d6b3c3616d124f | [
"FSFAP"
] | null | null | null | pmc_graph.cpp | david-ngo-sixense/pmc | f94f1674cabf0d57fd9a4d7499d6b3c3616d124f | [
"FSFAP"
] | null | null | null | pmc_graph.cpp | david-ngo-sixense/pmc | f94f1674cabf0d57fd9a4d7499d6b3c3616d124f | [
"FSFAP"
] | null | null | null | /**
============================================================================
Name : Parallel Maximum Clique (PMC) Library
Author : Ryan A. Rossi (rrossi@purdue.edu)
Description : A general high-performance parallel framework for computing
maximum cliques. The library is designed to be fast for large
sparse graphs.
Copyright (C) 2012-2013, Ryan A. Rossi, All rights reserved.
Please cite the following paper if used:
Ryan A. Rossi, David F. Gleich, Assefaw H. Gebremedhin, Md. Mostofa
Patwary, A Fast Parallel Maximum Clique Algorithm for Large Sparse Graphs
and Temporal Strong Components, arXiv preprint 1302.6256, 2013.
See http://ryanrossi.com/pmc for more information.
============================================================================
*/
#include "pmc/pmc_graph.h"
using namespace pmc;
using namespace std;
void pmc_graph::initialize() {
max_degree = 0;
min_degree = 0;
avg_degree = 0;
max_core = 0;
is_gstats = false;
}
pmc_graph::~pmc_graph() {
}
pmc_graph::pmc_graph(const string& filename) {
initialize();
fn = filename;
read_graph(filename);
}
pmc_graph::pmc_graph(bool graph_stats, const string& filename) {
initialize();
fn = filename;
is_gstats = graph_stats;
read_graph(filename);
}
pmc_graph::pmc_graph(const string& filename, bool make_adj) {
initialize();
fn = filename;
read_graph(filename);
if (make_adj) create_adj();
}
void pmc_graph::read_graph(const string& filename) {
fn = filename;
double sec = get_time();
string ext = get_file_extension(filename);
if (ext == "edges" || ext == "eg2" || ext == "txt")
read_edges(filename);
else if (ext == "mtx")
read_mtx(filename);
else if (ext == "gr")
read_metis(filename);
else {
cout << "Unsupported graph format." <<endl;
return;
}
basic_stats(sec);
}
void pmc_graph::basic_stats(double sec) {
cout << "Reading time " << get_time() - sec << endl;
cout << "|V|: " << num_vertices() <<endl;
cout << "|E|: " << num_edges() <<endl;
cout << "p: " << density() <<endl;
cout << "d_max: " << get_max_degree() <<endl;
cout << "d_avg: " << get_avg_degree() <<endl;
}
void pmc_graph::read_edges(const string& filename) {
istringstream in_stream;
string line = "";
map< int, vector<int> > vert_list;
int v = 0, u = 0, num_es = 0, self_edges = 0;
ifstream in_check (filename.c_str());
if (!in_check) { cout << filename << "File not found!" <<endl; return; }
bool fix_start_idx = true;
while (!in_check.eof()) {
getline(in_check,line);
if (line[0] == '%' || line[0] == '#') continue;
if (line != "") {
in_stream.clear();
in_stream.str(line);
in_stream >> v >> u;
if (v == 0 || u == 0) {
fix_start_idx = false;
break;
}
}
}
ifstream in (filename.c_str());
if (!in) { cout << filename << "File not found!" <<endl; return; }
while (!in.eof()) {
getline(in,line);
if (line[0] == '%' || line[0] == '#') continue;
num_es++;
if (line != "") {
in_stream.clear();
in_stream.str(line);
in_stream >> v >> u;
if (fix_start_idx) {
v--;
u--;
}
if (v == u) self_edges++;
else {
vert_list[v].push_back(u);
vert_list[u].push_back(v);
}
}
}
vertices.push_back(edges.size());
for (int i=0; i < vert_list.size(); i++) {
edges.insert(edges.end(),vert_list[i].begin(),vert_list[i].end());
vertices.push_back(edges.size());
}
vert_list.clear();
vertex_degrees();
cout << "self-loops: " << self_edges <<endl;
}
pmc_graph::pmc_graph(long long nedges, const int *ei, const int *ej, int offset) {
initialize();
map< int, vector<int> > vert_list;
for (long long i = 0; i < nedges; i++) {
int v = ei[i] - offset;
int u = ej[i] - offset;
if ( v > u ) {
vert_list[v].push_back(u);
vert_list[u].push_back(v);
}
}
vertices.push_back(edges.size());
for (int i=0; i < vert_list.size(); i++) {
edges.insert(edges.end(),vert_list[i].begin(),vert_list[i].end());
vertices.push_back(edges.size());
}
vert_list.clear();
vertex_degrees();
}
pmc_graph::pmc_graph(map<int,vector<int> > v_map) {
vertices.push_back(edges.size());
for (int i=0;i < v_map.size(); i++) {
edges.insert(edges.end(),v_map[i].begin(),v_map[i].end());
vertices.push_back(edges.size());
}
vertex_degrees();
}
void pmc_graph::read_mtx(const string& filename) {
float connStrength = -DBL_MAX;
istringstream in2;
string line="";
map<int,vector<int> > v_map;
map<int,vector<double> > valueList;
int col=0, row=0, ridx=0, cidx=0;
int entry_counter = 0, num_of_entries = 0;
double value;
ifstream in (filename.c_str());
if(!in) {
cout<<filename<<" not Found!"<<endl;
return;
}
char data[LINE_LENGTH];
char banner[LINE_LENGTH];
char mtx[LINE_LENGTH];
char crd[LINE_LENGTH];
char data_type[LINE_LENGTH];
char storage_scheme[LINE_LENGTH];
char* p;
bool b_getValue = true;
getline(in, line);
strcpy(data, line.c_str());
if (sscanf(data, "%s %s %s %s %s", banner, mtx, crd, data_type, storage_scheme) != 5) {
cout << "ERROR: mtx header is missing" << endl;
return;
}
for (p=data_type; *p!='\0'; *p=tolower(*p),p++);
if (strcmp(data_type, "pattern") == 0) b_getValue = false;
getline(in, line);
while(line.size()>0&&line[0]=='%') getline(in,line);
in2.str(line);
in2 >> row >> col >> num_of_entries;
if(row!=col) {
cout<<"* ERROR: This is not a square matrix."<<endl;
return;
}
while(!in.eof() && entry_counter<num_of_entries) {
getline(in,line);
entry_counter++;
if(line!="") {
in2.clear();
in2.str(line);
in2 >> ridx >> cidx >> value;
ridx--;
cidx--;
if (ridx < 0 || ridx >= row) cout << "sym-mtx error: " << ridx << " row " << row << endl;
if (cidx < 0 || cidx >= col) cout << "sym-mtx error: " << cidx << " col " << col << endl;
if (ridx == cidx) continue;
if (ridx > cidx) {
if (b_getValue) {
if(value > connStrength) {
v_map[ridx].push_back(cidx);
v_map[cidx].push_back(ridx);
if (is_gstats) {
e_v.push_back(ridx);
e_u.push_back(cidx);
}
}
} else {
v_map[ridx].push_back(cidx);
v_map[cidx].push_back(ridx);
if (is_gstats) {
e_v.push_back(ridx);
e_u.push_back(cidx);
}
}
if (b_getValue && value > connStrength) {
valueList[ridx].push_back(value);
valueList[cidx].push_back(value);
}
} else {
cout << "* WARNING: Found a nonzero in the upper triangular. ";
break;
}
}
}
vertices.push_back(edges.size());
for (int i=0;i < row; i++) {
edges.insert(edges.end(),v_map[i].begin(),v_map[i].end());
vertices.push_back(edges.size());
}
v_map.clear();
valueList.clear();
vertex_degrees();
}
void pmc_graph::read_metis(const string& filename) { return; };
void pmc_graph::create_adj() {
double sec = get_time();
int size = num_vertices();
adj.resize(size);
for (int i = 0; i < size; i++) {
adj[i].resize(size);
}
for (int i = 0; i < num_vertices(); i++) {
for (long long j = vertices[i]; j < vertices[i + 1]; j++ )
adj[i][edges[j]] = true;
}
cout << "Created adjacency matrix in " << get_time() - sec << " seconds" <<endl;
}
void pmc_graph::sum_vertex_degrees() {
int n = vertices.size() - 1;
uint64_t sum = 0;
for (long long v = 0; v < n; v++) {
degree[v] = vertices[v+1] - vertices[v];
sum += (degree[v] * degree[v]-1) / 2;
}
cout << "sum of degrees: " << sum <<endl;
}
void pmc_graph::vertex_degrees() {
int n = static_cast<int>(vertices.size()) - 1;
degree.resize(n);
// initialize min and max to degree of first vertex
min_degree = static_cast<int>(vertices[1]) - static_cast<int>(vertices[0]);
max_degree = static_cast<int>(vertices[1]) - static_cast<int>(vertices[0]);
for (int v=0; v<n; v++) {
degree[v] = static_cast<int>(vertices[v+1]) - static_cast<int>(vertices[v]);
if (max_degree < degree[v]) {
max_degree = degree[v];
}
if (degree[v] < min_degree) {
min_degree = degree[v];
}
}
avg_degree = static_cast<double>(edges.size())/ static_cast<double>(n);
return;
}
// fast update
void pmc_graph::update_degrees() {
for (long long v = 0; v < num_vertices(); v++)
degree[v] = vertices[v+1] - vertices[v];
}
void pmc_graph::update_degrees(bool flag) {
int p = 0;
max_degree = vertices[1] - vertices[0];
for (long long v = 0; v < num_vertices(); v++) {
degree[v] = vertices[v+1] - vertices[v];
if (degree[v] > 0) {
if (max_degree < degree[v]) max_degree = degree[v];
p++;
}
}
avg_degree = (double)edges.size() / p;
return;
}
void pmc_graph::update_degrees(int* &pruned, int& mc) {
max_degree = -1;
min_degree = (std::numeric_limits<int>::max)();
int p = 0;
for (long long v=0; v < num_vertices(); v++) {
degree[v] = vertices[v+1] - vertices[v];
if (degree[v] < mc) {
if (!pruned[v]) pruned[v] = 1;
p++;
}
else {
if (max_degree < degree[v]) max_degree = degree[v];
if (degree[v] < min_degree) min_degree = degree[v];
}
}
avg_degree = (double)edges.size() / p;
cout << ", pruned: " << p << endl;
}
void pmc_graph::update_kcores(int* &pruned) {
long long n, d, i, j, start, num, md;
long long v, u, w, du, pu, pw, md_end;
n = vertices.size();
kcore.resize(n);
fill(kcore.begin(), kcore.end(), 0);
vector <int> pos_tmp(n);
vector <int> order_tmp(n);
md = 0;
for(v=1; v<n; v++) {
if (!pruned[v-1]) {
kcore[v] = degree[v-1];
if (kcore[v] > md) md = kcore[v];
}
}
md_end = md+1;
vector < int > bin(md_end,0);
for (v=1; v < n; v++) bin[kcore[v]]++;
start = 1;
for (d=0; d < md_end; d++) {
num = bin[d];
bin[d] = start;
start = start + num;
}
for (v=1; v<n; v++) {
pos_tmp[v] = bin[kcore[v]];
order_tmp[pos_tmp[v]] = v;
bin[kcore[v]]++;
}
for (d=md; d > 1; d--) bin[d] = bin[d-1];
bin[0] = 1;
for (i = 1; i < n; i++) {
v=order_tmp[i];
if (!pruned[v-1]) {
for (j = vertices[v-1]; j < vertices[v]; j++) {
if (!pruned[edges[j]]) {
u = edges[j] + 1;
if (kcore[u] > kcore[v]) {
du = kcore[u]; pu = pos_tmp[u];
pw = bin[du]; w = order_tmp[pw];
if (u != w) {
pos_tmp[u] = pw; order_tmp[pu] = w;
pos_tmp[w] = pu; order_tmp[pw] = u;
}
bin[du]++; kcore[u]--;
}
}
}
}
}
max_core = 0;
for (v=0; v<n-1; v++) {
if (!pruned[v]) {
kcore[v] = kcore[v+1] + 1; // K+1
order_tmp[v] = order_tmp[v+1]-1;
if (kcore[v] > max_core) max_core = kcore[v];
}
else kcore[v] = 0;
}
cout << "[pmc: updated cores] K: " << max_core <<endl;
bin.clear();
pos_tmp.clear();
order_tmp.clear();
}
string pmc_graph::get_file_extension(const string& filename) {
string::size_type result;
string fileExtension = "";
result = filename.rfind('.', filename.size() - 1);
if(result != string::npos)
fileExtension = filename.substr(result+1);
return fileExtension;
}
void pmc_graph::reduce_graph(int* &pruned) {
vector<long long> V(vertices.size(),0);
vector<int> E;
E.reserve(edges.size());
int start = 0;
for (int i = 0; i < num_vertices(); i++) {
start = E.size();
if (!pruned[i]) {
for (long long j = vertices[i]; j < vertices[i + 1]; j++ ) {
if (!pruned[edges[j]])
E.push_back(edges[j]);
}
}
V[i] = start;
V[i + 1] = E.size();
}
vertices = V;
edges = E;
}
void pmc_graph::reduce_graph(
vector<long long>& vs,
vector<int>& es,
int* &pruned,
int id,
int& mc) {
int num_vs = vs.size();
vector<long long> V(num_vs,0);
vector<int> E;
E.reserve(es.size());
int start = 0;
for (int i = 0; i < num_vs - 1; i++) {
start = E.size();
if (!pruned[i]) { //skip these V_local...
for (long long j = vs[i]; j < vs[i + 1]; j++ ) {
if (!pruned[es[j]])
E.push_back(es[j]);
}
}
V[i] = start;
V[i + 1] = E.size();
}
vs = V;
es = E;
}
void pmc_graph::bound_stats(int alg, int lb, pmc_graph& G) {
cout << "graph: " << fn <<endl;
cout << "alg: " << alg <<endl;
cout << "-------------------------------" <<endl;
cout << "Graph Stats for Max-Clique:" <<endl;
cout << "-------------------------------" <<endl;
cout << "|V|: " << num_vertices() <<endl;
cout << "|E|: " << num_edges() <<endl;
cout << "d_max: " << get_max_degree() <<endl;
cout << "d_avg: " << get_avg_degree() <<endl;
cout << "p: " << density() <<endl;
}
void pmc_graph::compute_ordering(vector<int>& bound, vector<int>& order) {
long long n, d, start, num, md;
long long v, md_end;
n = bound.size();
order.reserve(n);
vector < long long > pos(n);
md = 0;
for(v=1; v<n; v++)
if (bound[v] > md) md = bound[v];
md_end = md+1;
vector < long long > bin(md_end,0);
for (v=1; v < n; v++) bin[bound[v]]++;
start = 1;
for (d=0; d < md_end; d++) {
num = bin[d];
bin[d] = start;
start = start + num;
}
for (v=1; v<n; v++) {
pos[v] = bin[bound[v]];
order[pos[v]] = v;
bin[bound[v]]++;
}
for (d=md; d > 1; d--) bin[d] = bin[d-1];
bin[0] = 1;
for (v=0; v<n-1; v++) {
bound[v] = bound[v+1];
order[v] = order[v+1]-1;
}
}
void pmc_graph::degree_bucket_sort() {
degree_bucket_sort(false);
}
// sort neighbors by degree (largest to smallest)
void pmc_graph::degree_bucket_sort(bool desc) {
int v, u, n, md, md_end, start, d, num;
vector<int> tmp_edges;
tmp_edges.reserve(edges.size());
for (v = 0; v < num_vertices(); v++) {
n = vertices[v+1] - vertices[v] + 1;
vector<int> vert(n);
vector<int> pos(n);
vector<int> deg(n);
md = 0;
for(u=1; u<n; u++) {
deg[u] = degree[edges[vertices[v] + (u-1)]];
if (deg[u] > md)
md = deg[u];
}
md_end = md+1;
vector < int > bin(md_end,0);
for (u=1; u < n; u++) bin[deg[u]]++;
start = 1;
for (d=0; d < md_end; d++) {
num = bin[d];
bin[d] = start;
start = start + num;
}
for (u=1; u<n; u++) {
pos[u] = bin[deg[u]];
vert[pos[u]] = edges[vertices[v] + (u-1)];
bin[deg[u]]++;
}
if (desc) {
// largest to smallest
tmp_edges.insert(tmp_edges.end(),vert.rbegin(),vert.rend()-1);
}
else {
//from smallest degree to largest
tmp_edges.insert(tmp_edges.end(),vert.begin()+1,vert.end());
}
}
cout << "[pmc: sorting neighbors] |E| = " << edges.size();
cout << ", |E_sorted| = " << tmp_edges.size() <<endl;
edges = tmp_edges;
}
// note when reducing graph explicitly, then forced to read in or keep a copy
bool pmc_graph::clique_test(pmc_graph& G, vector<int> C) {
int u = 0;
vector<short> ind(G.num_vertices(),0);
for (size_t i = 0; i < C.size(); i++) ind[C[i]] = 1;
// ensure each vertex in C has |C|-1 edges between each other
for (size_t i = 0; i < C.size(); i++) {
u = C[i];
int sz = 0;
for (long long j = G.vertices[u]; j < G.vertices[u+1]; j++)
if (ind[G.edges[j]]) sz++;
// check if connected to |C|-1 vertices
if (sz != C.size()-1)
return false;
}
return true;
}
| 27.183386 | 102 | 0.489592 | [
"vector"
] |
100ee001c388dcb5e92e8be29062d12125ab20c0 | 2,093 | cpp | C++ | analysis/Mass Action/DP/22Apret/Apres 256+512/256/9/MultiTransformersDP.cpp | tee-lab/PercolationModels | 687cb8189fafeb2e0d205ea4d8a660bd953bd7b1 | [
"BSD-3-Clause"
] | null | null | null | analysis/Mass Action/DP/22Apret/Apres 256+512/256/9/MultiTransformersDP.cpp | tee-lab/PercolationModels | 687cb8189fafeb2e0d205ea4d8a660bd953bd7b1 | [
"BSD-3-Clause"
] | null | null | null | analysis/Mass Action/DP/22Apret/Apres 256+512/256/9/MultiTransformersDP.cpp | tee-lab/PercolationModels | 687cb8189fafeb2e0d205ea4d8a660bd953bd7b1 | [
"BSD-3-Clause"
] | 1 | 2021-09-11T17:25:25.000Z | 2021-09-11T17:25:25.000Z | #include "cluster_dynamics.h"
int main() {
auto start = high_resolution_clock::now();
// Auto variable deduces type of variable by itself.
increase_stack_limit(1024);
int grid_size;
//float birth_probability;
//int r_init;
int how_many;
//int lag;
//int number_of_census;
int divisions;
int t_to_eq;
/* cout << "Enter grid size: ";
cin >> grid_size;
cout << "Enter p value of contention: ";
cin >> birth_probability;
cout << "Enter number of census: ";
cin >> number_of_census;
cout << "Enter lag: ";
cin >> lag;
cout << "Enter number of random trials: ";
cin >> r_init; */
t_to_eq = 50000; grid_size = 256; //birth_probability =0.704; r_init =16; lag=1;
how_many = 1000000;
//Taken from: http://www.cplusplus.com/forum/unices/112048/
float data[40][7];
std::ifstream file("dump/15_16_KungF---U.csv");
file.ignore(140, '\n'); //ignore the first 140 characters, or until first \n, whichever is met first
for(int row = 0; row < 40; ++row)
{
std::string line;
std::getline(file, line);
if ( !file.good() )
break;
std::stringstream iss(line);
for (int col = 0; col < 7; ++col)
{
std::string val;
std::getline(iss, val, ',');
if ( !iss.good() )
break;
std::stringstream convertor(val);
convertor >> data[row][col];
}
}
std::vector<f_coordinates> pL; std::vector<transformation> transformations;
for(int i=36 ; i< 40; i++)
{
for(int j=1; j <7; j++)
{
f_coordinates temp; temp.x = data[i][0]; temp.y =data[i][j]*(grid_size*grid_size); pL.push_back(temp);
}
}
divisions = 4*6;
cout << "p\t| lag\n";
for (int i=0; i < divisions; i++)
{
cout << pL[i].x << " " << pL[i].y <<endl;
}
find_equilibrium_multi_shot_transformations_DP(grid_size, divisions, t_to_eq, how_many, transformations, pL);
auto stop = high_resolution_clock::now();
auto duration = duration_cast<seconds>(stop - start);
cout << endl << "Total CPU Time: " << duration.count() << " seconds" << endl;
}
| 24.337209 | 110 | 0.601051 | [
"vector"
] |
1015807b8b8330a09eeb0ce52af752cde858e72d | 8,401 | cpp | C++ | Source/modules/encryptedmedia/MediaKeys.cpp | prepare/Blink_only_permissive_lic_files | 8b3acc51c7ae8b074d2e2b610d0d9295d9a1ecb4 | [
"BSD-3-Clause"
] | null | null | null | Source/modules/encryptedmedia/MediaKeys.cpp | prepare/Blink_only_permissive_lic_files | 8b3acc51c7ae8b074d2e2b610d0d9295d9a1ecb4 | [
"BSD-3-Clause"
] | null | null | null | Source/modules/encryptedmedia/MediaKeys.cpp | prepare/Blink_only_permissive_lic_files | 8b3acc51c7ae8b074d2e2b610d0d9295d9a1ecb4 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (C) 2013 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "modules/encryptedmedia/MediaKeys.h"
#include "bindings/core/v8/ScriptState.h"
#include "core/dom/DOMArrayBuffer.h"
#include "core/dom/DOMException.h"
#include "core/dom/ExceptionCode.h"
#include "core/dom/ExecutionContext.h"
#include "modules/encryptedmedia/EncryptedMediaUtils.h"
#include "modules/encryptedmedia/MediaKeySession.h"
#include "modules/encryptedmedia/SimpleContentDecryptionModuleResultPromise.h"
#include "platform/Logging.h"
#include "platform/Timer.h"
#include "public/platform/WebContentDecryptionModule.h"
#include "wtf/RefPtr.h"
namespace blink {
// A class holding a pending action.
class MediaKeys::PendingAction : public GarbageCollectedFinalized<MediaKeys::PendingAction> {
public:
const Persistent<ContentDecryptionModuleResult> result() const
{
return m_result;
}
const RefPtr<DOMArrayBuffer> data() const
{
return m_data;
}
static PendingAction* CreatePendingSetServerCertificate(ContentDecryptionModuleResult* result, PassRefPtr<DOMArrayBuffer> serverCertificate)
{
ASSERT(result);
ASSERT(serverCertificate);
return new PendingAction(result, serverCertificate);
}
~PendingAction()
{
}
DEFINE_INLINE_TRACE()
{
visitor->trace(m_result);
}
private:
PendingAction(ContentDecryptionModuleResult* result, PassRefPtr<DOMArrayBuffer> data)
: m_result(result)
, m_data(data)
{
}
const Member<ContentDecryptionModuleResult> m_result;
const RefPtr<DOMArrayBuffer> m_data;
};
MediaKeys::MediaKeys(ExecutionContext* context, const String& keySystem, const WebVector<WebEncryptedMediaSessionType>& supportedSessionTypes, PassOwnPtr<WebContentDecryptionModule> cdm)
: ContextLifecycleObserver(context)
, m_keySystem(keySystem)
, m_supportedSessionTypes(supportedSessionTypes)
, m_cdm(cdm)
, m_timer(this, &MediaKeys::timerFired)
{
WTF_LOG(Media, "MediaKeys(%p)::MediaKeys", this);
// Step 4.4 of MediaKeys::create():
// 4.4.1 Set the keySystem attribute to keySystem.
ASSERT(!m_keySystem.isEmpty());
}
MediaKeys::~MediaKeys()
{
WTF_LOG(Media, "MediaKeys(%p)::~MediaKeys", this);
}
MediaKeySession* MediaKeys::createSession(ScriptState* scriptState, const String& sessionTypeString, ExceptionState& exceptionState)
{
WTF_LOG(Media, "MediaKeys(%p)::createSession", this);
// From http://w3c.github.io/encrypted-media/#createSession
// When this method is invoked, the user agent must run the following steps:
// 1. If this object's persistent state allowed value is false and
// sessionType is not "temporary", throw a new DOMException whose name is
// NotSupportedError.
// (Chromium ensures that only session types supported by the
// configuration are listed in supportedSessionTypes.)
// 2. If the Key System implementation represented by this object's cdm
// implementation value does not support sessionType, throw a new
// DOMException whose name is NotSupportedError.
WebEncryptedMediaSessionType sessionType = EncryptedMediaUtils::convertToSessionType(sessionTypeString);
if (!sessionTypeSupported(sessionType))
exceptionState.throwDOMException(NotSupportedError, "Unsupported session type.");
// 3. Let session be a new MediaKeySession object, and initialize it as
// follows:
// (Initialization is performed in the constructor.)
// 4. Return session.
return MediaKeySession::create(scriptState, this, sessionType);
}
ScriptPromise MediaKeys::setServerCertificate(ScriptState* scriptState, const DOMArrayPiece& serverCertificate)
{
// From https://dvcs.w3.org/hg/html-media/raw-file/default/encrypted-media/encrypted-media.html#dom-setservercertificate:
// The setServerCertificate(serverCertificate) method provides a server
// certificate to be used to encrypt messages to the license server.
// It must run the following steps:
// 1. If serverCertificate is an empty array, return a promise rejected
// with a new DOMException whose name is "InvalidAccessError".
if (!serverCertificate.byteLength()) {
return ScriptPromise::rejectWithDOMException(
scriptState, DOMException::create(InvalidAccessError, "The serverCertificate parameter is empty."));
}
// 2. If the keySystem does not support server certificates, return a
// promise rejected with a new DOMException whose name is
// "NotSupportedError".
// (Let the CDM decide whether to support this or not.)
// 3. Let certificate be a copy of the contents of the serverCertificate
// parameter.
RefPtr<DOMArrayBuffer> serverCertificateBuffer = DOMArrayBuffer::create(serverCertificate.data(), serverCertificate.byteLength());
// 4. Let promise be a new promise.
SimpleContentDecryptionModuleResultPromise* result = new SimpleContentDecryptionModuleResultPromise(scriptState);
ScriptPromise promise = result->promise();
// 5. Run the following steps asynchronously (documented in timerFired()).
m_pendingActions.append(PendingAction::CreatePendingSetServerCertificate(result, serverCertificateBuffer.release()));
if (!m_timer.isActive())
m_timer.startOneShot(0, FROM_HERE);
// 6. Return promise.
return promise;
}
bool MediaKeys::sessionTypeSupported(WebEncryptedMediaSessionType sessionType)
{
for (size_t i = 0; i < m_supportedSessionTypes.size(); i++) {
if (m_supportedSessionTypes[i] == sessionType)
return true;
}
return false;
}
void MediaKeys::timerFired(Timer<MediaKeys>*)
{
ASSERT(m_pendingActions.size());
// Swap the queue to a local copy to avoid problems if resolving promises
// run synchronously.
HeapDeque<Member<PendingAction>> pendingActions;
pendingActions.swap(m_pendingActions);
while (!pendingActions.isEmpty()) {
PendingAction* action = pendingActions.takeFirst();
WTF_LOG(Media, "MediaKeys(%p)::timerFired: Certificate", this);
// 5.1 Let cdm be the cdm during the initialization of this object.
WebContentDecryptionModule* cdm = contentDecryptionModule();
// 5.2 Use the cdm to process certificate.
cdm->setServerCertificate(static_cast<unsigned char*>(action->data()->data()), action->data()->byteLength(), action->result()->result());
// 5.3 If any of the preceding steps failed, reject promise with a
// new DOMException whose name is the appropriate error name.
// 5.4 Resolve promise.
// (These are handled by Chromium and the CDM.)
}
}
WebContentDecryptionModule* MediaKeys::contentDecryptionModule()
{
return m_cdm.get();
}
DEFINE_TRACE(MediaKeys)
{
visitor->trace(m_pendingActions);
ContextLifecycleObserver::trace(visitor);
}
void MediaKeys::contextDestroyed()
{
ContextLifecycleObserver::contextDestroyed();
// We don't need the CDM anymore.
m_cdm.clear();
}
} // namespace blink
| 38.360731 | 186 | 0.730508 | [
"object"
] |
1016acf0fdebc2754eb04f595b8949e549076eb8 | 17,394 | cpp | C++ | qtdomterm/browsermainwindow.cpp | csik/DomTerm | 637100b84840b7c0f3434c6f2c054ce9431675e7 | [
"BSD-3-Clause"
] | null | null | null | qtdomterm/browsermainwindow.cpp | csik/DomTerm | 637100b84840b7c0f3434c6f2c054ce9431675e7 | [
"BSD-3-Clause"
] | null | null | null | qtdomterm/browsermainwindow.cpp | csik/DomTerm | 637100b84840b7c0f3434c6f2c054ce9431675e7 | [
"BSD-3-Clause"
] | null | null | null | /****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the demonstration applications of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** BSD License Usage
** Alternatively, you may use this file under the terms of the BSD license
** as follows:
**
** "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 Qt Company Ltd 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."
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "browsermainwindow.h"
#include "browserapplication.h"
#include "webview.h"
#include "backend.h"
#include "processoptions.h"
#include <QtCore/QSettings>
#include <QtGui/QDesktopServices>
#include <QtWidgets/QShortcut>
#include <QtWidgets/QDesktopWidget>
#include <QtWidgets/QFileDialog>
#include <QtWidgets/QPlainTextEdit>
#include <QtWidgets/QMenuBar>
#include <QtWidgets/QMessageBox>
#include <QtWidgets/QDialog>
#include <QtWidgets/QInputDialog>
#include <QWebEngineProfile>
#include <QWebEngineSettings>
#include <QVBoxLayout>
#include <QUrl>
#include <QUrlQuery>
#include <QtCore/QDebug>
template<typename Arg, typename R, typename C>
struct InvokeWrapper {
R *receiver;
void (C::*memberFun)(Arg);
void operator()(Arg result) {
(receiver->*memberFun)(result);
}
};
template<typename Arg, typename R, typename C>
InvokeWrapper<Arg, R, C> invoke(R *receiver, void (C::*memberFun)(Arg))
{
InvokeWrapper<Arg, R, C> wrapper = {receiver, memberFun};
return wrapper;
}
BrowserMainWindow::BrowserMainWindow(BrowserApplication* application,
const QString& url, QSharedDataPointer<ProcessOptions> processOptions, QWidget *parent,
#if USE_KDDockWidgets
Qt::WindowFlags
#else
Qt::WindowFlags flags
#endif
)
#if USE_KDDockWidgets
: KDDockWidgets::MainWindow(BrowserApplication::uniqueNameFromUrl(url), KDDockWidgets::MainWindowOption_None, parent) // flags ingnored?
#else
: QMainWindow(parent, flags)
#endif
, m_application(application)
#if USE_KDDockWidgets
, m_webView(new WebView(processOptions, nullptr))
#else
, m_webView(new WebView(processOptions, this))
#endif
, m_width(-1)
, m_height(-1)
{
setToolButtonStyle(Qt::ToolButtonFollowStyle);
setAttribute(Qt::WA_DeleteOnClose, true);
setupMenu();
m_webView->newPage(url);
#if USE_KDDockWidgets || USE_DOCK_MANAGER
auto dockw = m_webView->setDockWidget(BrowserApplication::uniqueNameFromUrl(url));
#if USE_KDDockWidgets
this->addDockWidget(dockw, KDDockWidgets::Location_OnLeft);
#endif
#if USE_DOCK_MANAGER
ads::CDockContainerWidget* container = BrowserApplication::instance()->dockManager()->addContainer(this);
container->addDockWidget(ads::TopDockWidgetArea, dockw, nullptr);
#endif
#else /* neither USE_KDDockWidgets or USE_DOCK_MANAGER */
QWidget *centralWidget = new QWidget(this);
QVBoxLayout *layout = new QVBoxLayout;
layout->setSpacing(0);
layout->setMargin(0);
layout->addWidget(m_webView);
centralWidget->setLayout(layout);
setCentralWidget(centralWidget);
#endif
slotUpdateWindowTitle();
loadDefaultState();
}
BrowserMainWindow::~BrowserMainWindow()
{
}
void BrowserMainWindow::loadDefaultState()
{
QSettings settings;
settings.beginGroup(QLatin1String("BrowserMainWindow"));
QByteArray data = settings.value(QLatin1String("defaultState")).toByteArray();
settings.endGroup();
}
QSize BrowserMainWindow::sizeHint() const
{
if (m_width > 0 || m_height > 0)
return QSize(m_width, m_height);
#if 0
return QApplication::desktop()->screenGeometry() * qreal(0.4);
#else
return QSize(800, 600);
#endif
}
void BrowserMainWindow::setupMenu()
{
new QShortcut(QKeySequence(Qt::Key_F6), this, SLOT(slotSwapFocus()));
//connect(menuBar()->toggleViewAction(), SIGNAL(toggled(bool)),
// this, SLOT(updateMenubarActionText(bool)));
// File
QMenu *fileMenu = menuBar()->addMenu(tr("&File"));
QAction*newTerminalWindow =
fileMenu->addAction(tr("&New Window"), this,
&BrowserMainWindow::slotFileNew,
QKeySequence(Qt::CTRL | Qt::SHIFT | Qt::Key_N));
newTerminalTab = fileMenu->addAction("New terminal tab",
this, &BrowserMainWindow::slotNewTerminalTab, QKeySequence(Qt::CTRL | Qt::SHIFT | Qt::Key_T));
fileMenu->addAction(newTerminalTab);
#if 0
fileMenu->addSeparator();
fileMenu->addAction(m_tabWidget->closeTabAction());
fileMenu->addSeparator();
#endif
fileMenu->addAction(webView()->saveAsAction());
fileMenu->addSeparator();
#if defined(Q_OS_OSX)
fileMenu->addAction(tr("&Quit"), BrowserApplication::instance(), SLOT(quitBrowser()), QKeySequence(Qt::CTRL | Qt::SHIFT | Qt::Key_Q));
#else
fileMenu->addAction(tr("&Quit"), this, SLOT(close()), QKeySequence(Qt::CTRL | Qt::SHIFT | Qt::Key_Q));
#endif
// Edit
QMenu *editMenu = menuBar()->addMenu(tr("&Edit"));
m_copy = editMenu->addAction(tr("&Copy"),
this, &BrowserMainWindow::slotCopy);
m_copy->setShortcut(QKeySequence(Qt::CTRL | Qt::SHIFT | Qt::Key_C));
editMenu->addAction(tr("Copy as HTML"), this,
&BrowserMainWindow::slotCopyAsHTML);
m_paste = editMenu->addAction(tr("&Paste"),
this, &BrowserMainWindow::slotPaste);
m_paste->setShortcut(QKeySequence(Qt::CTRL | Qt::SHIFT | Qt::Key_V));
//m_tabWidget->addWebAction(m_paste, QWebEnginePage::Paste);
editMenu->addAction(tr("Clear Buffer"),
this, &BrowserMainWindow::slotClearBuffer);
editMenu->addSeparator();
QAction *m_find = editMenu->addAction(tr("&Find"), this,
&BrowserMainWindow::slotEditFind);
m_find->setShortcut(QKeySequence(Qt::CTRL | Qt::SHIFT | Qt::Key_F));
// View
QMenu *viewMenu = menuBar()->addMenu(tr("&View"));
m_viewMenubar = new QAction(this);
updateMenubarActionText(true);
connect(m_viewMenubar, SIGNAL(triggered()), this, SLOT(slotViewMenubar()));
viewMenu->addAction(m_viewMenubar);
viewMenu->addAction(tr("Zoom &In"), this, SLOT(slotViewZoomIn()), QKeySequence(Qt::CTRL | Qt::SHIFT | Qt::Key_Plus));
viewMenu->addAction(tr("Zoom &Out"), this, SLOT(slotViewZoomOut()), QKeySequence(Qt::CTRL | Qt::Key_Minus));
viewMenu->addAction(tr("Reset &Zoom"), this, SLOT(slotViewResetZoom()), QKeySequence(Qt::CTRL | Qt::Key_0));
QAction *a = viewMenu->addAction(tr("&Full Screen"), this, SLOT(slotViewFullScreen(bool)), Qt::Key_F11);
a->setCheckable(true);
#if 1
//QMenu *toolsMenu = menuBar()->addMenu(tr("&Tools"));
#if defined(QWEBENGINEINSPECTOR)
a = viewMenu->addAction(tr("Enable Web &Inspector"), this, SLOT(slotToggleInspector(bool)));
a->setCheckable(true);
#endif
#endif
newTerminalMenu = new QMenu(tr("New Terminal"), this);
newTerminalMenu->addAction(newTerminalWindow);
newTerminalMenu->addAction(newTerminalTab);
newTerminalPane = newTerminalMenu->addAction("New terminal (right/below)",
this, &BrowserMainWindow::slotNewTerminalPane);
newTerminalAbove = newTerminalMenu->addAction("New terminal above",
this, &BrowserMainWindow::slotNewTerminalAbove);
newTerminalBelow = newTerminalMenu->addAction("New terminal below",
this, &BrowserMainWindow::slotNewTerminalBelow);
newTerminalLeft = newTerminalMenu->addAction("New terminal left",
this, &BrowserMainWindow::slotNewTerminalLeft);
newTerminalRight = newTerminalMenu->addAction("New terminal right",
this, &BrowserMainWindow::slotNewTerminalRight);
inputModeGroup = new QActionGroup(this);
inputModeGroup->setExclusive(true);
charInputMode = new QAction(tr("&Char mode"), inputModeGroup);
lineInputMode = new QAction(tr("&Line mode"), inputModeGroup);
autoInputMode = new QAction(tr("&Auto mode"), inputModeGroup);
inputModeGroup->addAction(charInputMode);
inputModeGroup->addAction(lineInputMode);
inputModeGroup->addAction(autoInputMode);
inputModeMenu = new QMenu(tr("&Input mode"), this);
int nmodes = 3;
for (int i = 0; i < nmodes; i++) {
QAction *action = inputModeGroup->actions().at(i);
action->setCheckable(true);
inputModeMenu->addAction(action);
}
autoInputMode->setChecked(true);
selectedInputMode = autoInputMode;
connect(inputModeGroup, &QActionGroup::triggered,
this, &BrowserMainWindow::changeInputMode);
QMenu *terminalMenu = menuBar()->addMenu(tr("&Terminal"));
terminalMenu->addMenu(inputModeMenu);
togglePagingAction = terminalMenu->addAction("Automatic &Pager", this,
&BrowserMainWindow::slotAutoPager);
togglePagingAction->setCheckable(true);
//terminalMenu->addAction(webView()->changeCaretAction());
terminalMenu->addMenu(newTerminalMenu);
detachAction = terminalMenu->addAction("&Detach", this,
&BrowserMainWindow::slotDetach);
QMenu *helpMenu = menuBar()->addMenu(tr("&Help"));
helpMenu->addAction(tr("About QtDomTerm"), this, SLOT(slotAboutApplication()));
helpMenu->addAction(tr("DomTerm home page"), this,
&BrowserMainWindow::slotOpenHomePage);
}
void BrowserMainWindow::changeInputMode(QAction* action)
{
QActionGroup *inputMode = static_cast<QActionGroup *>(sender());
if(!inputMode)
qFatal("scrollPosition is NULL");
if (action != selectedInputMode) {
char mode = action == charInputMode ? 'c'
: action == lineInputMode ? 'l'
: 'a';
inputModeChanged(mode);
webView()->backend()->setInputMode(mode);
}
}
void BrowserMainWindow::inputModeChanged(char mode)
{
QAction* action = mode == 'a' ? autoInputMode
: mode == 'l' ? lineInputMode
: charInputMode;
#if 0
QActionGroup *inputMode = static_cast<QActionGroup *>(sender());
if(!inputMode)
qFatal("scrollPosition is NULL");
#endif
if (action != selectedInputMode) {
selectedInputMode->setChecked(false);
action->setChecked(true);
selectedInputMode = action;
}
}
void BrowserMainWindow::autoPagerChanged(bool mode)
{
autoInputMode->setChecked(mode);
}
void BrowserMainWindow::slotViewMenubar()
{
if (menuBar()->isVisible()) {
updateMenubarActionText(false);
menuBar()->hide();
} else {
updateMenubarActionText(true);
menuBar()->show();
}
}
void BrowserMainWindow::updateMenubarActionText(bool visible)
{
m_viewMenubar->setText(!visible ? tr("Show Menubar") : tr("Hide Menubar"));
}
void BrowserMainWindow::loadUrl(const QUrl &url)
{
if (!currentTab() || !url.isValid())
return;
m_webView->loadUrl(url);
m_webView->setFocus();
}
void BrowserMainWindow::slotUpdateWindowTitle(const QString &title)
{
if (title.isEmpty()) {
setWindowTitle(tr("QtDomTerm"));
} else {
setWindowTitle(title);
}
}
void BrowserMainWindow::slotNewTerminal(int paneOp)
{
emit webView()->backend()->layoutAddPane(paneOp);
}
void BrowserMainWindow::slotDetach()
{
emit webView()->backend()->handleSimpleCommand("detach-session");
}
void BrowserMainWindow::slotAutoPager()
{
emit webView()->backend()->handleSimpleCommand("toggle-auto-pager");
}
void BrowserMainWindow::slotClearBuffer()
{
emit webView()->backend()->handleSimpleCommand("clear-buffer");
}
void BrowserMainWindow::slotCopy()
{
emit webView()->backend()->handleSimpleMessage("copy");
}
void BrowserMainWindow::slotPaste()
{
webView()->backend()->paste();
}
void BrowserMainWindow::slotCopyAsHTML()
{
emit webView()->backend()->copyAsHTML();
}
void BrowserMainWindow::slotOpenHomePage()
{
QDesktopServices::openUrl(QUrl("https://domterm.org/"));
}
void BrowserMainWindow::slotAboutApplication()
{
QMessageBox::about(this, tr("About"), tr(
"Version %1"
"<p>QtDomTerm is a terminal emulator based on DomTerm (%1) and QtWebEngine (%3). "
"<p>Copyright %2 Per Bothner."
"<p>The DomTerm home page is <a href=\"https://domterm.org/\">https://domterm.org/</a>.")
.arg(QCoreApplication::applicationVersion())
.arg(QTDOMTERM_YEAR)
.arg(qVersion()));
}
void BrowserMainWindow::slotFileNew()
{
QSharedDataPointer<ProcessOptions> options = webView()->m_processOptions;
QUrl url = options->url;
if (url.hasFragment()) {
QUrlQuery fragment = QUrlQuery(url.fragment().replace(";", "&"));
fragment.removeQueryItem("session-number");
fragment.removeQueryItem("window");
url.setFragment(fragment.isEmpty() ? QString()
: fragment.toString());
}
BrowserApplication::instance()->newMainWindow(url.toString(), options);
}
void BrowserMainWindow::closeEvent(QCloseEvent *event)
{
event->accept();
deleteLater();
}
void BrowserMainWindow::slotEditFind()
{
emit webView()->backend()->handleSimpleCommand("find-text");
}
void BrowserMainWindow::slotViewZoomIn()
{
if (!currentTab())
return;
currentTab()->setZoomFactor(currentTab()->zoomFactor() + 0.1);
}
void BrowserMainWindow::slotViewZoomOut()
{
if (!currentTab())
return;
currentTab()->setZoomFactor(currentTab()->zoomFactor() - 0.1);
}
void BrowserMainWindow::slotViewResetZoom()
{
if (!currentTab())
return;
currentTab()->setZoomFactor(1.0);
}
void BrowserMainWindow::slotViewFullScreen(bool makeFullScreen)
{
if (makeFullScreen) {
showFullScreen();
} else {
if (isMinimized())
showMinimized();
else if (isMaximized())
showMaximized();
else showNormal();
}
}
void BrowserMainWindow::slotToggleInspector(bool enable)
{
#if defined(QWEBENGINEINSPECTOR)
QWebEngineSettings::globalSettings()->setAttribute(QWebEngineSettings::DeveloperExtrasEnabled, enable);
#else
Q_UNUSED(enable);
#endif
}
void BrowserMainWindow::slotSwapFocus()
{
/*
if (currentTab()->hasFocus())
m_tabWidget->currentLineEdit()->setFocus();
else
currentTab()->setFocus();
*/
}
void BrowserMainWindow::loadPage(const QString &page)
{
QUrl url = QUrl::fromUserInput(page);
loadUrl(url);
}
WebView *BrowserMainWindow::currentTab() const
{
return m_webView;
}
void BrowserMainWindow::slotShowWindow()
{
if (QAction *action = qobject_cast<QAction*>(sender())) {
QVariant v = action->data();
if (v.canConvert<int>()) {
int offset = qvariant_cast<int>(v);
QList<BrowserMainWindow*> windows = BrowserApplication::instance()->mainWindows();
windows.at(offset)->activateWindow();
windows.at(offset)->currentTab()->setFocus();
}
}
}
void BrowserMainWindow::slotOpenActionUrl(QAction *)
{
}
void BrowserMainWindow::geometryChangeRequested(const QRect &geometry)
{
setGeometry(geometry);
}
| 33.709302 | 140 | 0.665344 | [
"geometry"
] |
1017eed3af91ebf65e1453510054652d9d9f5c0b | 21,422 | cpp | C++ | IGC/VectorCompiler/lib/GenXCodeGen/GenXAggregatePseudoLowering.cpp | kurapov-peter/intel-graphics-compiler | 98f7c938df0617912288385d243d6918135f0713 | [
"Intel",
"MIT"
] | 440 | 2018-01-30T00:43:22.000Z | 2022-03-24T17:28:37.000Z | IGC/VectorCompiler/lib/GenXCodeGen/GenXAggregatePseudoLowering.cpp | kurapov-peter/intel-graphics-compiler | 98f7c938df0617912288385d243d6918135f0713 | [
"Intel",
"MIT"
] | 225 | 2018-02-02T03:10:47.000Z | 2022-03-31T10:50:37.000Z | IGC/VectorCompiler/lib/GenXCodeGen/GenXAggregatePseudoLowering.cpp | kurapov-peter/intel-graphics-compiler | 98f7c938df0617912288385d243d6918135f0713 | [
"Intel",
"MIT"
] | 138 | 2018-01-30T08:15:11.000Z | 2022-03-22T14:16:39.000Z | /*========================== begin_copyright_notice ============================
Copyright (C) 2020-2021 Intel Corporation
SPDX-License-Identifier: MIT
============================= end_copyright_notice ===========================*/
//
/// GenXAggregatePseudoLowering
/// ---------------------------
///
/// The pass is meant to replace all instructions that work with aggregate
/// values with instructions that work with elementary types (scalar, vector),
/// so there's no aggregate values in IR at all. But this pass doesn't do full
/// job, that's why it has pseudo in its name.
/// This pass replaces every instruction (except call, extract/insertvalue, etc)
/// that either has aggregate as operand, or returns an aggregate with series
/// of extractvalue instructions (if there was an aggregate operand) which
/// return only elementary values, then sequence of splits of the original
/// instruction (but now each one is working only with an elementary value) and
/// finally the sequence of insertvalues that join all elementary results back
/// to the original aggregate result.
///
/// Example:
/// Before pass:
/// %struct_t = type { <16 x float>, <16 x float>, <16 x float> }
/// %res = select i1 %c, %struct_t %arg.0, %struct_t %arg.1
/// After pass:
/// %struct_t = type { <16 x float>, <16 x float>, <16 x float> }
/// %arg.0.0 = extractvalue %struct_t %arg.0, 0
/// %arg.0.1 = extractvalue %struct_t %arg.0, 1
/// %arg.0.2 = extractvalue %struct_t %arg.0, 2
/// %arg.1.0 = extractvalue %struct_t %arg.1, 0
/// %arg.1.1 = extractvalue %struct_t %arg.1, 1
/// %arg.1.2 = extractvalue %struct_t %arg.1, 2
/// %res.0 = select i1 %c, <16 x float> %arg.0.0, <16 x float> %arg.1.0
/// %res.1 = select i1 %c, <16 x float> %arg.0.1, <16 x float> %arg.1.1
/// %res.2 = select i1 %c, <16 x float> %arg.0.2, <16 x float> %arg.1.2
/// %tmp.0 = insertvalue %struct_t undef, <16 x float> %res.0, 0
/// %tmp.1 = insertvalue %struct_t %tmp.0, <16 x float> %res.1, 1
/// %res = insertvalue %struct_t %tmp.1, <16 x float> %res.2, 2
///
/// As you can see the pass doesn't fully get rid of aggregate values, it only
/// locally replaces operations over aggregates with operations over elementary
/// fields of aggregates. But if there is the instruction combine pass after
/// this pass, it can easily merge extractvalue and insertvalue so the there's
/// no aggregate values in code anymore.
///
/// Terminology:
/// Split instructions - the instructions into which original instruction
/// is split, e.g. %res.0, %res.1, %res.2 are split insts
/// (%res is corresponding original instruction)
/// Split operands - the instructions into which original operands are split,
/// they are always extractvalue instructions, e.g.
/// %arg.0.0, %arg.0.1, %arg.0.2 are split operands
/// (%arg.0 is corresponding original operand)
///
/// Note: split instruction operands is operands of a split instruction, not
/// split operands, though split instruction operands contain at least one
/// split operand, e.g. %c, %arg.0.0, %arg.1.0 for %res.0 instruction.
///
/// TODO: Supported instructions are phi, select, load and store.
//
//===----------------------------------------------------------------------===//
#include "GenX.h"
#include "GenXModule.h"
#include "Probe/Assertion.h"
#include "llvmWrapper/Support/Alignment.h"
#include <llvm/IR/Constants.h>
#include <llvm/IR/Function.h>
#include <llvm/IR/IRBuilder.h>
#include <llvm/IR/InstIterator.h>
#include <llvm/IR/InstVisitor.h>
#include <llvm/IR/Instructions.h>
#include <llvm/IR/Module.h>
#include <llvm/Pass.h>
#include <unordered_map>
#include <vector>
using namespace llvm;
using namespace genx;
namespace {
// It is a map between original aggregate instruction operand
// and corresponding split operands.
// Split operands are always extractvalue instructions.
using SplitOpsMap = std::unordered_map<Use *, std::vector<Instruction *>>;
// For iterating over elementary values in the case of nested aggregates, it is
// convenient to use a list of indices, rather than a single index. Each index
// in the list is an index at a given nesting depth. Example:
// %struct_t = type { float, type { [5 x i32], i8 } }
// The float element will have a list of indices {0}, and the fourth element of
// the array will have a list of indices {1, 0, 3}.
using IdxListType = std::vector<unsigned>;
class GenXAggregatePseudoLowering : public FunctionPass {
std::vector<Instruction *> ToErase;
public:
static char ID;
explicit GenXAggregatePseudoLowering() : FunctionPass(ID) {}
StringRef getPassName() const override {
return "GenX aggregate pseudo lowering";
}
void getAnalysisUsage(AnalysisUsage &AU) const override;
bool runOnFunction(Function &F) override;
private:
void processInst(Instruction &Inst);
};
} // end namespace
char GenXAggregatePseudoLowering::ID = 0;
namespace llvm {
void initializeGenXAggregatePseudoLoweringPass(PassRegistry &);
}
INITIALIZE_PASS_BEGIN(GenXAggregatePseudoLowering,
"GenXAggregatePseudoLowering",
"GenXAggregatePseudoLowering", false, false)
INITIALIZE_PASS_END(GenXAggregatePseudoLowering, "GenXAggregatePseudoLowering",
"GenXAggregatePseudoLowering", false, false)
FunctionPass *llvm::createGenXAggregatePseudoLoweringPass() {
initializeGenXAggregatePseudoLoweringPass(*PassRegistry::getPassRegistry());
return new GenXAggregatePseudoLowering;
}
void GenXAggregatePseudoLowering::getAnalysisUsage(AnalysisUsage &AU) const {
AU.setPreservesCFG();
}
// is at least one of instruction's operands an aggregate value
static bool hasAggregateOperand(const Instruction &Inst) {
return llvm::any_of(Inst.operand_values(), [](const Value *V) {
return V->getType()->isAggregateType();
});
}
// does instruction have an aggregate as an operand or return value
static bool hasAggregate(const Instruction &Inst) {
return Inst.getType()->isAggregateType() || hasAggregateOperand(Inst);
}
bool GenXAggregatePseudoLowering::runOnFunction(Function &F) {
std::vector<Instruction *> WorkList;
auto WorkRange = make_filter_range(instructions(F), [](Instruction &Inst) {
return hasAggregate(Inst) && !isa<InsertValueInst>(Inst) &&
!isa<ExtractValueInst>(Inst) && !isa<CallInst>(Inst) &&
!isa<ReturnInst>(Inst);
});
llvm::transform(WorkRange, std::back_inserter(WorkList),
[](Instruction &Inst) { return &Inst; });
if (WorkList.empty())
return false;
for (auto *Inst : WorkList)
processInst(*Inst);
for (auto *Inst : ToErase)
Inst->eraseFromParent();
ToErase.clear();
return true;
}
// Returns first instruction after provided instruciton \p Inst,
// before which new instruction can be inserted.
static Instruction *getFirstInsertionPtAfter(Instruction &Inst) {
if (isa<PHINode>(Inst))
return Inst.getParent()->getFirstNonPHI();
return Inst.getNextNode();
}
// Returns first instruction before which new instruction that represent new
// operand can be inserted, so the new instruction precedes provided
// instruction. \p Inst. Operand \Op is the operator to be updated.
static Instruction *getFirstInsertionPtBefore(Use &Op, Instruction &Inst) {
if (!isa<PHINode>(Inst))
return &Inst;
return cast<PHINode>(Inst).getIncomingBlock(Op)->getTerminator();
}
// Arguments:
// \p Inst - an instruction
// \p Op - operand of the instruction \p Inst
//
// Returns an instruction before which new operand for instruction \p Inst,
// that correspond to the operand \p Op, can be inserted
static Instruction *getInsertionPtForSplitOp(Use &Op, Instruction &Inst) {
auto &OpVal = *Op.get();
if (isa<Instruction>(OpVal))
return getFirstInsertionPtAfter(cast<Instruction>(OpVal));
IGC_ASSERT_MESSAGE(isa<Constant>(OpVal) || isa<Argument>(OpVal),
"only instruction, constant or argument are expected");
return getFirstInsertionPtBefore(Op, Inst);
}
// Arguments:
// \p Inst - an instruction
// \p Op - operand of the instruction \p Inst
// \p IdxLists - lists of indices for all elementary values of \p Op (see the
// description of IdxListType)
//
// Splits operand \p Op of the instruction \p Inst into elementary values.
// Those values are extractvalue instructions. Inserts those instruction in
// proper places, so if we insert new instruction right after or right before
// \p Inst those instructions could be reached.
//
// Returns the vector of created instructions.
static std::vector<Instruction *>
createSplitOperand(Use &Op, Instruction &Inst,
const std::vector<IdxListType> &IdxLists) {
auto &OpVal = *Op.get();
IGC_ASSERT_MESSAGE(OpVal.getType()->isAggregateType(), "wrong argument");
auto *InsertionPt = getInsertionPtForSplitOp(Op, Inst);
std::vector<Instruction *> SplitOperand;
for (const auto &IdxList : IdxLists) {
SplitOperand.push_back(
ExtractValueInst::Create(&OpVal, IdxList, "", InsertionPt));
}
return SplitOperand;
}
// Arguments:
// \p Inst - an instruction
// \p IdxLists - lists of indices for all elementary values of aggregates of
// \p Inst (see the description of IdxListType).
// It is assumed that all aggregate operands of \p Inst and
// it's return value, if it is aggregate, have the same type.
//
// Splits all aggregate operands of provided \p Inst.
// Returns a map between original operands and created instructions.
static SplitOpsMap
createSplitOperands(Instruction &Inst,
const std::vector<IdxListType> &IdxLists) {
IGC_ASSERT_MESSAGE(hasAggregateOperand(Inst),
"wrong argument: inst must have aggregate operand");
auto AggregateOps = make_filter_range(Inst.operands(), [](const Use &U) {
return U->getType()->isAggregateType();
});
SplitOpsMap SplitOps;
llvm::transform(AggregateOps, std::inserter(SplitOps, SplitOps.end()),
[&Inst, &IdxLists](Use &U) {
return std::make_pair(
&U, createSplitOperand(U, Inst, IdxLists));
});
return SplitOps;
}
// Arguments:
// \p elemIdx - element index of the aggregate for which we construct
// split instruction
// \p OrigOps - original instruction operands (contain aggregates)
// \p SplitOps - map between original aggregate operands and corresponding
// split operands
//
// Returns vector of operands (as Value*) for split instruction with index \p
// elemIdx.
template <typename OpRange>
std::vector<Value *> createSplitInstOperands(int elemIdx, OpRange OrigOps,
const SplitOpsMap &SplitOps) {
std::vector<Value *> NewOps;
llvm::transform(OrigOps, std::back_inserter(NewOps),
[elemIdx, &SplitOps](Use &OrigOp) -> Value * {
if (OrigOp.get()->getType()->isAggregateType())
return SplitOps.at(&OrigOp)[elemIdx];
return OrigOp.get();
});
return NewOps;
}
class SplitInstCreator : public InstVisitor<SplitInstCreator, Instruction *> {
const std::vector<Value *> &NewOps;
// The list of indices of the currently considered element of an aggregate.
const IdxListType &IdxList;
public:
SplitInstCreator(const std::vector<Value *> &NewOpsIn,
const IdxListType &IdxListIn)
: NewOps{NewOpsIn}, IdxList{IdxListIn} {
IGC_ASSERT_MESSAGE(
!IdxList.empty(),
"the list of indices of an aggregate element cannot be of zero length");
}
Instruction *visitInstruction(Instruction &I) const {
IGC_ASSERT_MESSAGE(0, "yet unsupported instruction");
return nullptr;
}
Instruction *create(Instruction &I) {
auto *NewInst = visit(I);
IGC_ASSERT_MESSAGE(!hasAggregate(*NewInst),
"split instruction must not have aggregate as an "
"operand or a return value");
return NewInst;
}
Instruction *visitSelectInst(SelectInst &Inst) const {
IGC_ASSERT_MESSAGE(NewOps.size() == 3, "select must have 3 operands");
auto *NewSelect =
SelectInst::Create(NewOps[0], NewOps[1], NewOps[2],
Inst.getName() + ".split.aggr", &Inst, &Inst);
NewSelect->setDebugLoc(Inst.getDebugLoc());
return NewSelect;
}
Instruction *visitPHINode(PHINode &OldPHI) const {
IGC_ASSERT(OldPHI.getNumOperands() == NewOps.size());
auto *NewPHI = PHINode::Create(NewOps[0]->getType(), NewOps.size(),
OldPHI.getName() + ".split.aggr", &OldPHI);
for (auto &&Incoming : zip(NewOps, OldPHI.blocks())) {
Value *OpVal = std::get<0>(Incoming);
BasicBlock *OpBB = std::get<1>(Incoming);
IGC_ASSERT_MESSAGE(isa<ExtractValueInst>(OpVal),
"phi operands must be previously in this pass created "
"extractvalue insts");
auto *OpInst = cast<Instruction>(OpVal);
NewPHI->addIncoming(OpInst, OpBB);
}
NewPHI->setDebugLoc(OldPHI.getDebugLoc());
return NewPHI;
}
std::vector<Value *> CreateIdxListForGEP(IRBuilder<> &IRB) const {
std::vector<Value *> IdxListForGEP = {IRB.getInt32(0)};
llvm::transform(IdxList, std::back_inserter(IdxListForGEP),
[&IRB](auto Idx) { return IRB.getInt32(Idx); });
return IdxListForGEP;
}
Instruction *visitLoadInst(LoadInst &OrigLoad) const {
IGC_ASSERT_MESSAGE(NewOps.size() == 1, "load has only one operand");
IGC_ASSERT_MESSAGE(OrigLoad.getPointerOperand() == NewOps[0],
"should take the operand from the original load");
IRBuilder<> IRB{&OrigLoad};
Value *PointerOp = OrigLoad.getPointerOperand();
Type *Ty = cast<PointerType>(PointerOp->getType()->getScalarType())
->getElementType();
auto *GEP = IRB.CreateInBoundsGEP(Ty, PointerOp, CreateIdxListForGEP(IRB),
OrigLoad.getName() + "aggr.gep");
// FIXME: replace a structure alignment with an element alignment
Type *GEPPtrTy = GEP->getType()->getPointerElementType();
return IRB.CreateAlignedLoad(GEPPtrTy, GEP, IGCLLVM::getAlign(OrigLoad),
OrigLoad.isVolatile(),
OrigLoad.getName() + ".split.aggr");
}
Instruction *visitStoreInst(StoreInst &OrigStore) const {
IRBuilder<> IRB{&OrigStore};
Value *PointerOp = OrigStore.getPointerOperand();
Type *Ty = cast<PointerType>(PointerOp->getType()->getScalarType())
->getElementType();
auto *GEP = IRB.CreateInBoundsGEP(Ty, PointerOp, CreateIdxListForGEP(IRB),
OrigStore.getName() + "aggr.gep");
// FIXME: replace a structure alignment with an element alignment
return IRB.CreateAlignedStore(NewOps[0], GEP, IGCLLVM::getAlign(OrigStore),
OrigStore.isVolatile());
}
};
// Arguments:
// \p Inst - original instruction
// \p NewOps - operands for split instruction
// \p IdxList - the list of indices of the currently considered elementary
// value
//
// Creates split instruction based on the kind of original instruction.
// New instruction is inserted right before \p Inst.
// Split instruction is returned.
static Instruction *createSplitInst(Instruction &Inst,
const std::vector<Value *> &NewOps,
const IdxListType &IdxList) {
return SplitInstCreator{NewOps, IdxList}.create(Inst);
}
// Arguments:
// \p Inst - original instruction
// \p SplitOps - map between original aggregate operands and corresponding
// elementary operands
// \p IdxLists - lists of indices for all elementary values of aggregates of
// \p Inst (see the description of IdxListType).
// It is assumed that all aggregate operands of \p Inst have
// the same type.
//
// Creates all split instructions for original \p Inst, inserts them before the
// original one. Returns vector of created split instructions.
static std::vector<Instruction *>
createSplitInsts(Instruction &Inst, const SplitOpsMap &SplitOps,
const std::vector<IdxListType> &IdxLists) {
std::vector<Instruction *> NewInsts;
for (auto IdxList : enumerate(IdxLists)) {
auto NewOps =
createSplitInstOperands(IdxList.index(), Inst.operands(), SplitOps);
NewInsts.push_back(createSplitInst(Inst, NewOps, IdxList.value()));
}
return NewInsts;
}
// Arguments:
// \p SplitInsts - split instructions
// \p JoinTy - aggregate type that all split instructions together should
// form \p InsertBefore - insertion point
// \p IdxLists - lists of indices for \p SplitInsts
//
// Combines split instructions back into aggregate value with a sequence of
// inservalue instructions.
// Last insertvalue instruction that form full aggregate value is returned.
static Instruction *joinSplitInsts(const std::vector<Instruction *> &SplitInsts,
Type *JoinTy,
const std::vector<IdxListType> &IdxLists,
Instruction *InsertBefore) {
IGC_ASSERT_MESSAGE(SplitInsts.size() == IdxLists.size(),
"the number of splitted insts doesn't correspond with the "
"number of index lists");
Value *JoinInst = UndefValue::get(JoinTy);
for (auto &&[SplitInst, IdxList] : zip(SplitInsts, IdxLists)) {
JoinInst =
InsertValueInst::Create(JoinInst, SplitInst, IdxList, "", InsertBefore);
}
return cast<Instruction>(JoinInst);
}
static Type *getAggregateTypeImpl(Instruction &Inst) {
if (Inst.getType()->isAggregateType())
return Inst.getType();
auto AggrTypeIt = llvm::find_if(Inst.operands(), [](const Use &U) {
return U->getType()->isAggregateType();
});
IGC_ASSERT_MESSAGE(AggrTypeIt != Inst.operands().end(),
"no aggregate operand or return value");
return (*AggrTypeIt)->getType();
}
// Returns the type of the first aggregate operand of Inst, or the type of its
// return value, if it is aggregate. It is assumed that all aggregate operands
// of Inst and it's return value, if it is aggregate, have the same type.
static Type *getAggregateType(Instruction &Inst) {
Type *AggrTy = getAggregateTypeImpl(Inst);
IGC_ASSERT_MESSAGE(
llvm::all_of(Inst.operands(),
[AggrTy](const Use &U) {
return !U->getType()->isAggregateType() ||
U->getType() == AggrTy;
}),
"different aggregate types in the same instruction are not supported");
return AggrTy;
}
// Returns the type of an aggregate's element at specific index.
static Type *getTypeAtIndex(Type *AggrTy, unsigned Index) {
IGC_ASSERT_MESSAGE(isa<StructType>(AggrTy) || isa<ArrayType>(AggrTy),
"unexpected type");
if (isa<StructType>(AggrTy))
return cast<StructType>(AggrTy)->getTypeAtIndex(Index);
return cast<ArrayType>(AggrTy)->getElementType();
}
// Returns the number of elements of an aggregate.
static unsigned getNumElements(Type *AggrTy) {
IGC_ASSERT_MESSAGE(isa<StructType>(AggrTy) || isa<ArrayType>(AggrTy),
"unexpected type");
if (isa<StructType>(AggrTy))
return cast<StructType>(AggrTy)->getNumElements();
return cast<ArrayType>(AggrTy)->getNumElements();
}
// Returns lists of indices for all elementary values of Inst's aggregate
// operands or return value.
static std::vector<IdxListType> createIdxLists(Type *AggrTy) {
std::vector<IdxListType> IdxLists;
std::vector<std::pair<Type *, unsigned>> AggrStack = {{AggrTy, 0}};
while (!AggrStack.empty()) {
Type *CurrAggr = AggrStack.back().first;
unsigned CurrIndex = AggrStack.back().second;
if (CurrIndex == getNumElements(CurrAggr)) {
AggrStack.pop_back();
if (!AggrStack.empty())
++AggrStack.back().second;
continue;
}
Type *TypeAtIndex = getTypeAtIndex(CurrAggr, CurrIndex);
if (TypeAtIndex->isAggregateType()) {
AggrStack.emplace_back(TypeAtIndex, 0);
continue;
}
IdxListType CurrIdxList;
llvm::transform(AggrStack, std::back_inserter(CurrIdxList),
[](auto &Item) { return Item.second; });
IdxLists.push_back(std::move(CurrIdxList));
++AggrStack.back().second;
}
return IdxLists;
}
void GenXAggregatePseudoLowering::processInst(Instruction &Inst) {
IGC_ASSERT_MESSAGE(hasAggregate(Inst),
"wrong argument: instruction doesn't work with aggregates");
Type *AggrTy = getAggregateType(Inst);
auto IdxLists = createIdxLists(AggrTy);
SplitOpsMap NewOperands;
if (hasAggregateOperand(Inst))
NewOperands = createSplitOperands(Inst, IdxLists);
auto NewInsts = createSplitInsts(Inst, NewOperands, IdxLists);
if (Inst.getType()->isAggregateType()) {
auto *JoinInst = joinSplitInsts(NewInsts, Inst.getType(), IdxLists,
getFirstInsertionPtAfter(Inst));
Inst.replaceAllUsesWith(JoinInst);
JoinInst->takeName(&Inst);
}
ToErase.push_back(&Inst);
}
| 40.959847 | 80 | 0.662403 | [
"vector",
"transform"
] |
101891b35b0c63d65e86fa0847e77b7adc2a596e | 880 | cc | C++ | uva/chapter_8/1231.cc | metaflow/contests | 5e9ffcb72c3e7da54b5e0818b1afa59f5778ffa2 | [
"MIT"
] | 1 | 2019-05-12T23:41:00.000Z | 2019-05-12T23:41:00.000Z | uva/chapter_8/1231.cc | metaflow/contests | 5e9ffcb72c3e7da54b5e0818b1afa59f5778ffa2 | [
"MIT"
] | null | null | null | uva/chapter_8/1231.cc | metaflow/contests | 5e9ffcb72c3e7da54b5e0818b1afa59f5778ffa2 | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
using vi = vector<int>;
using ii = pair<int,int>;
using ll = long long;
using llu = unsigned long long;
const int INF = numeric_limits<int>::max();
int acorns[2000][2002];
int main() {
ios_base::sync_with_stdio(false);
int tcc;
cin >> tcc;
while (tcc--) {
int max_height, trees, fly;
fill(&acorns[0][0], &acorns[2000][0], 0);
cin >> trees >> max_height >> fly;
for (int t = 0; t < trees; t++) {
int a; cin >> a;
while (a--) {
int h; cin >> h;
acorns[t][h]++;
}
}
int best[2001] = {0};
for (int h = max_height; h >= 0; h--) {
for (int t = 0; t < trees; t++) {
acorns[t][h] += max(acorns[t][h + 1],
(h + fly <= max_height ? best[h + fly] : 0));
best[h] = max(best[h], acorns[t][h]);
}
}
cout << best[0] << endl;
}
}
| 23.157895 | 55 | 0.503409 | [
"vector"
] |
1019592c9be32668aeddd54bb5dda3b2cf0a98ae | 37,249 | cpp | C++ | src/rtScriptV8/rtScriptNode.cpp | madanagopaltcomcast/pxCore | c4a3a40a190521c8b6383d126c87612eca5b3c42 | [
"Apache-2.0"
] | null | null | null | src/rtScriptV8/rtScriptNode.cpp | madanagopaltcomcast/pxCore | c4a3a40a190521c8b6383d126c87612eca5b3c42 | [
"Apache-2.0"
] | 10 | 2018-07-10T20:33:01.000Z | 2018-07-17T21:31:02.000Z | src/rtScriptV8/rtScriptNode.cpp | madanagopaltcomcast/pxCore | c4a3a40a190521c8b6383d126c87612eca5b3c42 | [
"Apache-2.0"
] | 1 | 2019-10-14T22:46:29.000Z | 2019-10-14T22:46:29.000Z | /*
pxCore Copyright 2005-2018 John Robinson
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.
*/
// rtNode.cpp
#ifdef RTSCRIPT_SUPPORT_NODE
#if defined WIN32
#include <Windows.h>
#include <direct.h>
#define __PRETTY_FUNCTION__ __FUNCTION__
#else
#include <unistd.h>
#endif
#include <stdio.h>
#include <errno.h>
#include <string>
#include <fstream>
#include <iostream>
#include <sstream>
#ifndef WIN32
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"
#endif
#include "node.h"
#include "node_javascript.h"
#if NODE_VERSION_AT_LEAST(9,6,0)
#include "node_contextify.h"
#endif
#include "node_contextify_mods.h"
#include "env.h"
#include "env-inl.h"
#include "rtWrapperUtils.h"
#ifndef WIN32
#pragma GCC diagnostic pop
#endif
#include "rtScriptV8Node.h"
#include "rtCore.h"
#include "rtObject.h"
#include "rtValue.h"
#include "rtAtomic.h"
#include "rtScript.h"
#include "rtPathUtils.h"
// TODO eliminate std::string
#include <string>
#include <map>
#if !defined(WIN32) && !defined(ENABLE_DFB)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"
#pragma GCC diagnostic ignored "-Wall"
#endif
#include "uv.h"
#include "v8.h"
#include "libplatform/libplatform.h"
#include "rtObjectWrapper.h"
#include "rtFunctionWrapper.h"
using namespace rtScriptV8NodeUtils;
#define SANDBOX_IDENTIFIER ( (const char*) "_sandboxStuff" )
#define SANDBOX_JS ( (const char*) "rcvrcore/sandbox.js")
#if !defined(WIN32) & !defined(ENABLE_DFB)
#pragma GCC diagnostic pop
#endif
#ifndef DISABLE_USE_CONTEXTIFY_CLONES
# define USE_CONTEXTIFY_CLONES
#endif
#ifdef RUNINMAIN
bool gIsPumpingJavaScript = false;
#endif
#if NODE_VERSION_AT_LEAST(8,12,0)
#define USE_NODE_PLATFORM
#endif
namespace node
{
class Environment;
}
class rtScriptNode;
class rtNodeContext;
typedef rtRef<rtNodeContext> rtNodeContextRef;
class rtNodeContext: rtIScriptContext // V8
{
public:
rtNodeContext(v8::Isolate *isolate, v8::Platform* platform);
#ifdef USE_CONTEXTIFY_CLONES
rtNodeContext(v8::Isolate *isolate, rtNodeContextRef clone_me);
#endif
virtual ~rtNodeContext();
virtual rtError add(const char *name, const rtValue& val);
virtual rtValue get(const char *name);
//rtValue get(std::string name);
virtual bool has(const char *name);
bool has(std::string name);
//bool find(const char *name); //DEPRECATED
virtual rtError runScript(const char *script, rtValue* retVal = NULL, const char *args = NULL); // BLOCKS
//rtError runScript(const std::string &script, rtValue* retVal = NULL, const char *args = NULL); // BLOCKS
virtual rtError runFile (const char *file, rtValue* retVal = NULL, const char *args = NULL); // BLOCKS
unsigned long AddRef()
{
return rtAtomicInc(&mRefCount);
}
unsigned long Release();
const char *js_file;
std::string js_script;
v8::Isolate *getIsolate() const { return mIsolate; };
v8::Local<v8::Context> getLocalContext() const { return PersistentToLocal<v8::Context>(mIsolate, mContext); };
uint32_t getContextId() const { return mContextId; };
private:
v8::Isolate *mIsolate;
#if NODE_VERSION_AT_LEAST(9,8,0)
node::Persistent<v8::Context> mContext;
#else
v8::Persistent<v8::Context> mContext;
#endif
uint32_t mContextId;
node::Environment* mEnv;
#if NODE_VERSION_AT_LEAST(9,8,0)
node::Persistent<v8::Object> mRtWrappers;
#else
v8::Persistent<v8::Object> mRtWrappers;
#endif
void createEnvironment();
#ifdef USE_CONTEXTIFY_CLONES
void clonedEnvironment(rtNodeContextRef clone_me);
#endif
int mRefCount;
rtAtomic mId;
v8::Platform *mPlatform;
void* mContextifyContext;
};
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
typedef std::map<uint32_t, rtNodeContextRef> rtNodeContexts;
typedef std::map<uint32_t, rtNodeContextRef>::const_iterator rtNodeContexts_iterator;
class rtScriptNode: public rtIScript
{
public:
rtScriptNode();
rtScriptNode(bool initialize);
virtual ~rtScriptNode();
unsigned long AddRef()
{
return rtAtomicInc(&mRefCount);
}
unsigned long Release();
rtError init();
rtString engine() { return "node/v8"; }
rtError pump();
rtNodeContextRef getGlobalContext() const;
rtNodeContextRef createContext(bool ownThread = false);
rtError createContext(const char *lang, rtScriptContextRef& ctx);
#if 0
#ifndef RUNINMAIN
bool isInitialized();
bool needsToEnd() { /*rtLogDebug("needsToEnd returning %d\n",mNeedsToEnd);*/ return mNeedsToEnd;};
void setNeedsToEnd(bool end) { /*rtLogDebug("needsToEnd being set to %d\n",end);*/ mNeedsToEnd = end;}
#endif
#endif
v8::Isolate *getIsolate() { return mIsolate; };
v8::Platform *getPlatform() { return mPlatform; };
rtError collectGarbage();
void* getParameter(rtString param);
private:
#if 0
#ifdef ENABLE_DEBUG_MODE
void init();
#else
void init(int argc, char** argv);
#endif
#endif
rtError term();
void nodePath();
v8::Isolate *mIsolate;
v8::Platform *mPlatform;
#if NODE_VERSION_AT_LEAST(9,8,0)
node::Persistent<v8::Context> mContext;
#else
v8::Persistent<v8::Context> mContext;
#endif
#ifdef USE_CONTEXTIFY_CLONES
rtNodeContextRef mRefContext;
#endif
bool mTestGc;
#ifndef RUNINMAIN
bool mNeedsToEnd;
#endif
#ifdef ENABLE_DEBUG_MODE
void init2();
#else
void init2(int argc, char** argv);
#endif
int mRefCount;
};
#ifndef RUNINMAIN
extern uv_loop_t *nodeLoop;
#endif
//#include "rtThreadQueue.h"
//extern rtThreadQueue gUIThreadQueue;
#ifdef RUNINMAIN
//#include "pxEventLoop.h"
//extern pxEventLoop* gLoop;
#define ENTERSCENELOCK()
#define EXITSCENELOCK()
#else
#define ENTERSCENELOCK() rtWrapperSceneUpdateEnter();
#define EXITSCENELOCK() rtWrapperSceneUpdateExit();
#endif
using namespace v8;
using namespace node;
#ifdef ENABLE_DEBUG_MODE
int g_argc = 0;
char** g_argv;
#endif
#ifndef ENABLE_DEBUG_MODE
extern args_t *s_gArgs;
#endif
namespace node
{
#if NODE_VERSION_AT_LEAST(8,9,4)
extern DebugOptions debug_options;
#else
extern bool use_debug_agent;
#if HAVE_INSPECTOR
extern bool use_inspector;
#endif
extern bool debug_wait_connect;
#endif
}
static int exec_argc;
static const char** exec_argv;
static rtAtomic sNextId = 100;
#ifdef RUNINMAIN
//extern rtNode script;
#endif
rtNodeContexts mNodeContexts;
#ifdef ENABLE_NODE_V_6_9
ArrayBufferAllocator* array_buffer_allocator = NULL;
bool bufferAllocatorIsSet = false;
#endif
bool nodeTerminated = false;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#ifdef RUNINMAIN
#ifdef WIN32
static DWORD __rt_main_thread__;
#else
static pthread_t __rt_main_thread__;
#endif
// rtIsMainThread() - Previously: identify the MAIN thread of 'node' which running JS code.
//
// rtIsMainThread() - Currently: identify BACKGROUND thread which running JS code.
//
bool rtIsMainThreadNode()
{
// Since this is single threaded version we're always on the js thread
return true;
}
#endif
#if 0
static inline bool file_exists(const char *file)
{
struct stat buffer;
return (stat (file, &buffer) == 0);
}
#endif
rtNodeContext::rtNodeContext(Isolate *isolate,Platform* platform) :
js_file(NULL), mIsolate(isolate), mEnv(NULL), mRefCount(0),mPlatform(platform), mContextifyContext(NULL)
{
assert(isolate); // MUST HAVE !
mId = rtAtomicInc(&sNextId);
createEnvironment();
}
#ifdef USE_CONTEXTIFY_CLONES
rtNodeContext::rtNodeContext(Isolate *isolate, rtNodeContextRef clone_me) :
js_file(NULL), mIsolate(isolate), mEnv(NULL), mRefCount(0), mPlatform(NULL), mContextifyContext(NULL)
{
assert(mIsolate); // MUST HAVE !
mId = rtAtomicInc(&sNextId);
clonedEnvironment(clone_me);
}
#endif
void rtNodeContext::createEnvironment()
{
rtLogDebug(__FUNCTION__);
Locker locker(mIsolate);
Isolate::Scope isolate_scope(mIsolate);
HandleScope handle_scope(mIsolate);
// Create a new context.
Local<Context> local_context = Context::New(mIsolate);
#ifdef ENABLE_NODE_V_6_9
local_context->SetEmbedderData(HandleMap::kContextIdIndex, Integer::New(mIsolate, mId));
mContextId = GetContextId(local_context);
mContext.Reset(mIsolate, local_context); // local to persistent
Context::Scope context_scope(local_context);
Handle<Object> global = local_context->Global();
mRtWrappers.Reset(mIsolate, global);
// Create Environment.
#if NODE_VERSION_AT_LEAST(8,9,4)
#ifdef USE_NODE_PLATFORM
node::MultiIsolatePlatform* platform = static_cast<node::MultiIsolatePlatform*>(mPlatform);
IsolateData *isolateData = new IsolateData(mIsolate,uv_default_loop(),platform,array_buffer_allocator->zero_fill_field());
#else
IsolateData *isolateData = new IsolateData(mIsolate,uv_default_loop(),array_buffer_allocator->zero_fill_field());
#endif //USE_NODE_PLATFORM
mEnv = CreateEnvironment(isolateData,
#else
mEnv = CreateEnvironment(mIsolate,
uv_default_loop(),
#endif
local_context,
#ifdef ENABLE_DEBUG_MODE
g_argc,
g_argv,
#else
s_gArgs->argc,
s_gArgs->argv,
#endif
exec_argc,
exec_argv);
#if !NODE_VERSION_AT_LEAST(8,9,4)
array_buffer_allocator->set_env(mEnv);
#endif
mIsolate->SetAbortOnUncaughtExceptionCallback(
ShouldAbortOnUncaughtException);
#ifdef ENABLE_DEBUG_MODE
#if !NODE_VERSION_AT_LEAST(8,9,4)
// Start debug agent when argv has --debug
if (use_debug_agent)
{
rtLogWarn("use_debug_agent\n");
#if HAVE_INSPECTOR
if (use_inspector)
{
char currentPath[100];
memset(currentPath,0,sizeof(currentPath));
const char *rv = getcwd(currentPath,sizeof(currentPath));
(void)rv;
StartDebug(mEnv, currentPath, debug_wait_connect, mPlatform);
}
else
#endif
{
StartDebug(mEnv, NULL, debug_wait_connect);
}
}
#else
#if HAVE_INSPECTOR
#ifdef USE_NODE_PLATFORM
rtString currentPath;
rtGetCurrentDirectory(currentPath);
node::InspectorStart(mEnv, currentPath.cString(), platform);
#endif //USE_NODE_PLATFORM
#endif
#endif
#endif
// Load Environment.
{
Environment::AsyncCallbackScope callback_scope(mEnv);
LoadEnvironment(mEnv);
}
#if defined(ENABLE_DEBUG_MODE) && !NODE_VERSION_AT_LEAST( 8, 9, 4 )
if (use_debug_agent)
{
rtLogWarn("use_debug_agent\n");
EnableDebug(mEnv);
}
#endif
rtObjectWrapper::exportPrototype(mIsolate, global);
rtFunctionWrapper::exportPrototype(mIsolate, global);
{
SealHandleScope seal(mIsolate);
#ifndef RUNINMAIN
EmitBeforeExit(mEnv);
#else
bool more;
#ifdef ENABLE_NODE_V_6_9
#ifndef USE_NODE_PLATFORM
v8::platform::PumpMessageLoop(mPlatform, mIsolate);
#endif //USE_NODE_PLATFORM
#endif //ENABLE_NODE_V_6_9
more = uv_run(mEnv->event_loop(), UV_RUN_ONCE);
#ifdef USE_NODE_PLATFORM
node::MultiIsolatePlatform* platform = static_cast<node::MultiIsolatePlatform*>(mPlatform);
platform->DrainBackgroundTasks(mIsolate);
#endif //USE_NODE_PLATFORM
if (more == false)
{
EmitBeforeExit(mEnv);
}
#endif
}
#else
local_context->SetEmbedderData(HandleMap::kContextIdIndex, Integer::New(mIsolate, mId));
mContextId = GetContextId(local_context);
mContext.Reset(mIsolate, local_context); // local to persistent
Context::Scope context_scope(local_context);
Handle<Object> global = local_context->Global();
// Register wrappers.
rtObjectWrapper::exportPrototype(mIsolate, global);
rtFunctionWrapper::exportPrototype(mIsolate, global);
mRtWrappers.Reset(mIsolate, global);
// Create Environment.
mEnv = CreateEnvironment(mIsolate,
uv_default_loop(),
local_context,
#ifdef ENABLE_DEBUG_MODE
g_argc,
g_argv,
#else
s_gArgs->argc,
s_gArgs->argv,
#endif
exec_argc,
exec_argv);
// Start debug agent when argv has --debug
#ifdef ENABLE_DEBUG_MODE
if (use_debug_agent)
{
rtLogWarn("use_debug_agent\n");
StartDebug(mEnv, debug_wait_connect);
}
#endif
// Load Environment.
LoadEnvironment(mEnv);
// Enable debugger
if (use_debug_agent)
{
EnableDebug(mEnv);
}
#endif //ENABLE_NODE_V_6_9
}
#ifdef USE_CONTEXTIFY_CLONES
void rtNodeContext::clonedEnvironment(rtNodeContextRef clone_me)
{
rtLogDebug(__FUNCTION__);
Locker locker(mIsolate);
Isolate::Scope isolate_scope(mIsolate);
HandleScope handle_scope(mIsolate);
// Get parent Local context...
Local<Context> local_context = clone_me->getLocalContext();
Context::Scope context_scope(local_context);
// Create dummy sandbox for ContextifyContext::makeContext() ...
Local<Object> sandbox = Object::New(mIsolate);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
if( clone_me->has(SANDBOX_IDENTIFIER) )
{
rtValue val_array = clone_me->get(SANDBOX_IDENTIFIER);
rtObjectRef array = val_array.toObject();
int len = array.get<int>("length");
rtString s;
for(int i = 0; i < len; i++)
{
array.get<rtString>( (uint32_t) i, s); // get 'name' for object
rtValue obj = clone_me->get(s); // get object for 'name'
if( obj.isEmpty() == false)
{
// Copy to var/module 'sandbox' under construction...
Local<Value> module = local_context->Global()->Get( String::NewFromUtf8(mIsolate, s.cString() ) );
sandbox->Set( String::NewFromUtf8(mIsolate, s.cString()), module);
}
else
{
rtLogError("## FATAL: '%s' is empty !! - UNEXPECTED", s.cString());
}
}
}
else
{
rtLogWarn("## WARNING: '%s' is undefined !! - UNEXPECTED", SANDBOX_IDENTIFIER);
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
//
// Clone a new context.
{
#if NODE_VERSION_AT_LEAST(10,0,0)
contextify::ContextOptions options;
std::stringstream ctxname;
ctxname << "SparkContext:" << mId;
rtString currentPath;
rtGetCurrentDirectory(currentPath);
options.name = String::NewFromUtf8(mIsolate, ctxname.str().c_str() );
options.origin = String::NewFromUtf8(mIsolate, currentPath.cString() );
options.allow_code_gen_strings = Boolean::New(mIsolate, true);
options.allow_code_gen_wasm = Boolean::New(mIsolate, true);
Local<Context> clone_local = node::contextify::makeContext(mIsolate, sandbox, options); // contextify context with 'sandbox'
#else
Local<Context> clone_local = node::makeContext(mIsolate, sandbox); // contextify context with 'sandbox'
#endif
clone_local->SetEmbedderData(HandleMap::kContextIdIndex, Integer::New(mIsolate, mId));
#ifdef ENABLE_NODE_V_6_9
Local<Context> envCtx = Environment::GetCurrent(mIsolate)->context();
Local<String> symbol_name = FIXED_ONE_BYTE_STRING(mIsolate, "_contextifyPrivate");
Local<Private> private_symbol_name = Private::ForApi(mIsolate, symbol_name);
MaybeLocal<Value> maybe_value = sandbox->GetPrivate(envCtx,private_symbol_name);
Local<Value> decorated;
if (true == maybe_value.ToLocal(&decorated))
{
mContextifyContext = decorated.As<External>()->Value();
}
#else
Local<String> hidden_name = FIXED_ONE_BYTE_STRING(mIsolate, "_contextifyHidden");
mContextifyContext = sandbox->GetHiddenValue(hidden_name).As<External>()->Value();
#endif
mContextId = GetContextId(clone_local);
mContext.Reset(mIsolate, clone_local); // local to persistent
// commenting below code as templates are isolcate specific
/*
Context::Scope context_scope(clone_local);
Handle<Object> clone_global = clone_local->Global();
// Register wrappers in this cloned context...
rtObjectWrapper::exportPrototype(mIsolate, clone_global);
rtFunctionWrapper::exportPrototype(mIsolate, clone_global);
mRtWrappers.Reset(mIsolate, clone_global);
*/
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
}
#endif // USE_CONTEXTIFY_CLONES
rtNodeContext::~rtNodeContext()
{
rtLogDebug(__FUNCTION__);
//Make sure node is not destroyed abnormally
if (true == node_is_initialized)
{
if(mEnv)
{
Locker locker(mIsolate);
Isolate::Scope isolate_scope(mIsolate);
HandleScope handle_scope(mIsolate);
RunAtExit(mEnv);
#if !NODE_VERSION_AT_LEAST(8,9,4)
#ifdef ENABLE_NODE_V_6_9
if (nodeTerminated)
{
array_buffer_allocator->set_env(NULL);
}
else
{
mEnv->Dispose();
}
#else
mEnv->Dispose();
#endif // ENABLE_NODE_V_6_9
#endif
mEnv = NULL;
#ifndef USE_CONTEXTIFY_CLONES
HandleMap::clearAllForContext(mId);
#endif
}
else
{
// clear out persistent javascript handles
HandleMap::clearAllForContext(mId);
#if defined(ENABLE_NODE_V_6_9) && defined(USE_CONTEXTIFY_CLONES)
// JRJR This was causing HTTPS to crash in gl content reloads
// what does this do exactly... am I leaking now why is this only a 6.9 thing?
#ifndef USE_NODE_10
node::deleteContextifyContext(mContextifyContext);
#endif
#endif
mContextifyContext = NULL;
}
if(exec_argv)
{
#ifdef USE_NODE_10
for (int i=0; i<exec_argc; i++) {
if (NULL != exec_argv[i]) {
free((void*)exec_argv[i]);
exec_argv[i] = NULL;
}
}
#endif
delete[] exec_argv;
exec_argv = NULL;
exec_argc = 0;
}
// TODO: Might not be needed in ST case...
//
// Un-Register wrappers.
// rtObjectWrapper::destroyPrototype();
// rtFunctionWrapper::destroyPrototype();
mContext.Reset();
mRtWrappers.Reset();
Release();
}
// NOTE: 'mIsolate' is owned by rtNode. Don't destroy here !
}
rtError rtNodeContext::add(const char *name, rtValue const& val)
{
if(name == NULL)
{
rtLogDebug(" rtNodeContext::add() - no symbolic name for rtValue");
return RT_FAIL;
}
else if(this->has(name))
{
rtLogDebug(" rtNodeContext::add() - ALREADY HAS '%s' ... over-writing.", name);
// return; // Allow for "Null"-ing erasure.
}
if(val.isEmpty())
{
rtLogDebug(" rtNodeContext::add() - rtValue is empty");
return RT_FAIL;
}
Locker locker(mIsolate);
Isolate::Scope isolate_scope(mIsolate);
HandleScope handle_scope(mIsolate); // Create a stack-allocated handle scope.
// Get a Local context...
Local<Context> local_context = node::PersistentToLocal<Context>(mIsolate, mContext);
Context::Scope context_scope(local_context);
local_context->Global()->Set( String::NewFromUtf8(mIsolate, name), rt2js(local_context, val));
return RT_OK;
}
#if 0
rtValue rtNodeContext::get(std::string name)
{
return get( name.c_str() );
}
#endif
rtValue rtNodeContext::get(const char *name)
{
if(name == NULL)
{
rtLogError(" rtNodeContext::get() - no symbolic name for rtValue");
return rtValue();
}
Locker locker(mIsolate);
Isolate::Scope isolate_scope(mIsolate);
HandleScope handle_scope(mIsolate); // Create a stack-allocated handle scope.
// Get a Local context...
Local<Context> local_context = node::PersistentToLocal<Context>(mIsolate, mContext);
Context::Scope context_scope(local_context);
Handle<Object> global = local_context->Global();
// Get the object
Local<Value> object = global->Get( String::NewFromUtf8(mIsolate, name) );
if(object->IsUndefined() || object->IsNull() )
{
rtLogError("FATAL: '%s' is Undefined ", name);
return rtValue();
}
else
{
rtWrapperError error; // TODO - handle error
return js2rt(local_context, object, &error);
}
}
#if 0
bool rtNodeContext::has(std::string name)
{
return has( name.c_str() );
}
#endif
bool rtNodeContext::has(const char *name)
{
if(name == NULL)
{
rtLogError(" rtNodeContext::has() - no symbolic name for rtValue");
return false;
}
Locker locker(mIsolate);
Isolate::Scope isolate_scope(mIsolate);
HandleScope handle_scope(mIsolate); // Create a stack-allocated handle scope.
// Get a Local context...
Local<Context> local_context = node::PersistentToLocal<Context>(mIsolate, mContext);
Context::Scope context_scope(local_context);
Handle<Object> global = local_context->Global();
#ifdef ENABLE_NODE_V_6_9
TryCatch try_catch(mIsolate);
#else
TryCatch try_catch;
#endif // ENABLE_NODE_V_6_9
Handle<Value> value = global->Get(String::NewFromUtf8(mIsolate, name) );
if (try_catch.HasCaught())
{
rtLogError("\n ## has() - HasCaught() ... ERROR");
return false;
}
// No need to check if |value| is empty because it's taken care of
// by TryCatch above.
return ( !value->IsUndefined() && !value->IsNull() );
}
// DEPRECATED - 'has()' is replacement for 'find()'
//
// bool rtNodeContext::find(const char *name)
// {
// rtNodeContexts_iterator it = mNodeContexts.begin();
//
// while(it != mNodeContexts.end())
// {
// rtNodeContextRef ctx = it->second;
//
// rtLogWarn("\n ######## CONTEXT !!! ID: %d %s '%s'",
// ctx->getContextId(),
// (ctx->has(name) ? "*HAS*" : "does NOT have"),
// name);
//
// it++;
// }
//
// rtLogWarn("\n ");
//
// return false;
// }
#if 0
rtError rtNodeContext::runScript(const char* script, rtValue* retVal /*= NULL*/, const char *args /*= NULL*/)
{
if(script == NULL)
{
rtLogError(" %s ... no script given.",__PRETTY_FUNCTION__);
return RT_FAIL;
}
// rtLogDebug(" %s ... Running...",__PRETTY_FUNCTION__);
return runScript(std::string(script), retVal, args);
}
#endif
#if 1
//rtError rtNodeContext::runScript(const std::string &script, rtValue* retVal /*= NULL*/, const char* /* args = NULL*/)
rtError rtNodeContext::runScript(const char* script, rtValue* retVal /*= NULL*/, const char *args /*= NULL*/)
{
rtLogDebug(__FUNCTION__);
if(!script || strlen(script) == 0)
{
rtLogError(" %s ... no script given.",__PRETTY_FUNCTION__);
return RT_FAIL;
}
{//scope
Locker locker(mIsolate);
Isolate::Scope isolate_scope(mIsolate);
HandleScope handle_scope(mIsolate); // Create a stack-allocated handle scope.
// Get a Local context...
Local<Context> local_context = node::PersistentToLocal<Context>(mIsolate, mContext);
Context::Scope context_scope(local_context);
// !CLF TODO: TEST FOR MT
#ifdef RUNINMAIN
#ifdef ENABLE_NODE_V_6_9
TryCatch tryCatch(mIsolate);
#else
TryCatch tryCatch;
#endif // ENABLE_NODE_V_6_9
#endif
Local<String> source = String::NewFromUtf8(mIsolate, script);
// Compile the source code.
MaybeLocal<Script> run_script = Script::Compile(local_context, source);
if (run_script.IsEmpty()) {
#if NODE_VERSION_AT_LEAST(8,10,0)
String::Utf8Value trace(mIsolate, tryCatch.StackTrace(local_context).ToLocalChecked());
#else
String::Utf8Value trace(tryCatch.StackTrace(local_context).ToLocalChecked());
#endif
rtLogWarn("%s", *trace);
return RT_FAIL;
}
// Run the script to get the result.
MaybeLocal<Value> result = (run_script.ToLocalChecked())->Run(local_context);
// !CLF TODO: TEST FOR MT
#ifdef RUNINMAIN
if (tryCatch.HasCaught())
{
#if NODE_VERSION_AT_LEAST(8,10,0)
String::Utf8Value trace(mIsolate, tryCatch.StackTrace(local_context).ToLocalChecked());
#else
String::Utf8Value trace(tryCatch.StackTrace(local_context).ToLocalChecked());
#endif
rtLogWarn("%s", *trace);
return RT_FAIL;
}
#endif
if(retVal)
{
// Return val
rtWrapperError error;
*retVal = js2rt(local_context, result.ToLocalChecked(), &error);
if(error.hasError())
{
rtLogError("js2rt() - return from script error");
return RT_FAIL;
}
}
return RT_OK;
}//scope
return RT_FAIL;
}
#endif
static std::string readFile(const char *file)
{
std::string s("");
try {
std::ifstream src_file(file);
std::stringstream src_script;
src_script << src_file.rdbuf(); // slurp up file
s = src_script.str();
}
catch (std::ifstream::failure e) {
rtLogError("Exception opening/reading/closing file [%s]\n", e.what());
}
catch(...) {
rtLogError("Exception opening/reading/closing file \n");
}
return s;
}
rtError rtNodeContext::runFile(const char *file, rtValue* retVal /*= NULL*/, const char* args /*= NULL*/)
{
if(file == NULL)
{
rtLogError(" %s ... file == NULL ... no script given.",__PRETTY_FUNCTION__);
return RT_FAIL;
}
// Read the script file
js_file = file;
js_script = readFile(file);
if( js_script.empty() ) // load error
{
rtLogError(" %s ... [%s] load error / not found.",__PRETTY_FUNCTION__, file);
return RT_FAIL;
}
return runScript(js_script.c_str(), retVal, args);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
rtScriptNode::rtScriptNode():mRefCount(0)
#ifndef RUNINMAIN
#ifdef USE_CONTEXTIFY_CLONES
: mRefContext(), mNeedsToEnd(false)
#else
: mNeedsToEnd(false)
#endif
#endif
{
rtLogDebug(__FUNCTION__);
mTestGc = false;
mIsolate = NULL;
mPlatform = NULL;
init();
}
rtScriptNode::rtScriptNode(bool initialize):mRefCount(0)
#ifndef RUNINMAIN
#ifdef USE_CONTEXTIFY_CLONES
: mRefContext(), mNeedsToEnd(false)
#else
: mNeedsToEnd(false)
#endif
#endif
{
rtLogDebug(__FUNCTION__);
mTestGc = false;
mIsolate = NULL;
mPlatform = NULL;
if (initialize)
{
init();
}
}
unsigned long rtScriptNode::Release()
{
long l = rtAtomicDec(&mRefCount);
if (l == 0)
{
delete this;
}
return l;
}
rtError rtScriptNode::init()
{
rtLogDebug(__FUNCTION__);
char const* s = getenv("RT_TEST_GC");
if (s && strlen(s) > 0)
mTestGc = true;
else
mTestGc = false;
if (mTestGc)
rtLogWarn("*** PERFORMANCE WARNING *** : gc being invoked in render thread");
// TODO Please make this better... less hard coded...
//0123456 789ABCDEF012 345 67890ABCDEF
#if ENABLE_V8_HEAP_PARAMS
#ifdef ENABLE_NODE_V_6_9
static const char *args2 = "rtNode\0--experimental-vm-modules\0-e\0console.log(\"rtNode Initalized\");\0\0";
static const char *argv2[] = {&args2[0], &args2[7], &args2[33], &args2[36], NULL};
#else
rtLogWarn("v8 old heap space configured to 64mb\n");
static const char *args2 = "rtNode\0--experimental-vm-modules\0--expose-gc\0--max_old_space_size=64\0-e\0console.log(\"rtNode Initalized\");\0\0";
static const char *argv2[] = {&args2[0], &args2[7], &args2[33], &args2[45], &args2[69], &args2[72], NULL};
#endif // ENABLE_NODE_V_6_9
#else
#ifdef ENABLE_NODE_V_6_9
#ifndef ENABLE_DEBUG_MODE
static const char *args2 = "rtNode\0--experimental-vm-modules\0-e\0console.log(\"rtNode Initalized\");\0\0";
static const char *argv2[] = {&args2[0], &args2[7], &args2[33], &args2[36], NULL};
#endif //!ENABLE_DEBUG_MODE
#else
static const char *args2 = "rtNode\0--experimental-vm-modules\0--expose-gc\0-e\0console.log(\"rtNode Initalized\");\0\0";
static const char *argv2[] = {&args2[0], &args2[7], &args2[33], &args2[45], &args2[48], NULL};
#endif // ENABLE_NODE_V_6_9
#endif //ENABLE_V8_HEAP_PARAMS
#ifndef ENABLE_DEBUG_MODE
int argc = sizeof(argv2)/sizeof(char*) - 1;
static args_t aa(argc, (char**)argv2);
s_gArgs = &aa;
char **argv = aa.argv;
#endif
#ifdef RUNINMAIN
#ifdef WIN32
__rt_main_thread__ = GetCurrentThreadId();
#else
__rt_main_thread__ = pthread_self(); // NB
#endif
#endif
nodePath();
#ifdef ENABLE_NODE_V_6_9
rtLogWarn("rtNode::rtNode() calling init \n");
#ifdef ENABLE_DEBUG_MODE
init2();
#else
init2(argc, argv);
#endif
#else
mIsolate = Isolate::New();
node_isolate = mIsolate; // Must come first !!
#ifdef ENABLE_DEBUG_MODE
init2();
#else
init2(argc, argv);
#endif
#endif // ENABLE_NODE_V_6_9
return RT_OK;
}
rtScriptNode::~rtScriptNode()
{
// rtLogInfo(__FUNCTION__);
term();
}
rtError rtScriptNode::pump()
{
//#ifndef RUNINMAIN
// return;
//#else
#ifdef RUNINMAIN
// found a problem where if promise triggered by one event loop gets resolved by other event loop.
// It is causing the dependencies between data running between two event loops failed, if one one
// loop didn't complete before other. So, promise not registered by first event loop, before the second
// event looop sends back the ready event
if (gIsPumpingJavaScript == false)
{
gIsPumpingJavaScript = true;
#endif
Locker locker(mIsolate);
Isolate::Scope isolate_scope(mIsolate);
HandleScope handle_scope(mIsolate); // Create a stack-allocated handle scope.
#ifdef ENABLE_NODE_V_6_9
#ifndef USE_NODE_PLATFORM
v8::platform::PumpMessageLoop(mPlatform, mIsolate);
#endif //USE_NODE_PLATFORM
#endif //ENABLE_NODE_V_6_9
mIsolate->RunMicrotasks();
uv_run(uv_default_loop(), UV_RUN_NOWAIT);//UV_RUN_ONCE);
#ifdef USE_NODE_PLATFORM
node::MultiIsolatePlatform* platform = static_cast<node::MultiIsolatePlatform*>(mPlatform);
platform->DrainBackgroundTasks(mIsolate);
#endif //USE_NODE_PLATFORM
// Enable this to expedite garbage collection for testing... warning perf hit
if (mTestGc)
{
static int sGcTickCount = 0;
if (sGcTickCount++ > 60)
{
Local<Context> local_context = Context::New(mIsolate);
Context::Scope contextScope(local_context);
mIsolate->RequestGarbageCollectionForTesting(Isolate::kFullGarbageCollection);
sGcTickCount = 0;
}
}
#ifdef RUNINMAIN
gIsPumpingJavaScript = false;
}
#endif
//#endif // RUNINMAIN
return RT_OK;
}
rtError rtScriptNode::collectGarbage()
{
//#ifndef RUNINMAIN
// return;
//#else
Locker locker(mIsolate);
Isolate::Scope isolate_scope(mIsolate);
HandleScope handle_scope(mIsolate); // Create a stack-allocated handle scope.
Local<Context> local_context = Context::New(mIsolate);
Context::Scope contextScope(local_context);
mIsolate->LowMemoryNotification();
//#endif // RUNINMAIN
return RT_OK;
}
void* rtScriptNode::getParameter(rtString param)
{
if (param.compare("isolate") == 0)
return getIsolate();
return NULL;
}
#if 0
rtNode::forceGC()
{
mIsolate->RequestGarbageCollectionForTesting(Isolate::kFullGarbageCollection);
}
#endif
void rtScriptNode::nodePath()
{
const char* NODE_PATH = ::getenv("NODE_PATH");
if(NODE_PATH == NULL)
{
char cwd[1024] = {};
if (getcwd(cwd, sizeof(cwd)) != NULL)
{
#ifdef WIN32
_putenv_s("NODE_PATH", cwd);
#else
::setenv("NODE_PATH", cwd, 1); // last arg is 'overwrite' ... 0 means DON'T !
#endif
rtLogInfo("NODE_PATH=%s", cwd);
}
else
{
rtLogError(" - failed to set NODE_PATH");
}
}
}
#ifndef RUNINMAIN
bool rtNode::isInitialized()
{
//rtLogDebug("rtNode::isInitialized returning %d\n",node_is_initialized);
return node_is_initialized;
}
#endif
#if 1
#ifdef ENABLE_DEBUG_MODE
void rtScriptNode::init2()
#else
void rtScriptNode::init2(int argc, char** argv)
#endif
{
// Hack around with the argv pointer. Used for process.title = "blah".
#ifdef ENABLE_DEBUG_MODE
g_argv = uv_setup_args(g_argc, g_argv);
#else
argv = uv_setup_args(argc, argv);
#endif
rtLogInfo(__FUNCTION__);
#if 0
#warning Using DEBUG AGENT...
use_debug_agent = true; // JUNK
#endif
if(node_is_initialized == false)
{
rtLogWarn("About to Init\n");
#ifdef ENABLE_DEBUG_MODE
Init(&g_argc, const_cast<const char**>(g_argv), &exec_argc, &exec_argv);
#else
Init(&argc, const_cast<const char**>(argv), &exec_argc, &exec_argv);
#endif
#ifdef ENABLE_NODE_V_6_9
rtLogWarn("using node version %s\n", NODE_VERSION);
v8::V8::InitializeICU();
#ifdef ENABLE_DEBUG_MODE
V8::InitializeExternalStartupData(g_argv[0]);
#else
V8::InitializeExternalStartupData(argv[0]);
#endif
#ifdef USE_NODE_PLATFORM
Platform* platform = node::CreatePlatform(0, NULL);
#else
Platform* platform = platform::CreateDefaultPlatform();
#endif // USE_NODE_PLATFORM
mPlatform = platform;
#ifndef USE_NODE_10
v8::V8::InitializePlatform(platform);
#endif
V8::Initialize();
Isolate::CreateParams params;
array_buffer_allocator = new ArrayBufferAllocator();
const char* source1 = "function pxSceneFooFunction(){ return 0;}";
static v8::StartupData data = v8::V8::CreateSnapshotDataBlob(source1);
params.snapshot_blob = &data;
params.array_buffer_allocator = array_buffer_allocator;
mIsolate = Isolate::New(params);
node_isolate = mIsolate; // Must come first !!
#else
V8::Initialize();
#endif // ENABLE_NODE_V_6_9
rtLogWarn("rtNode::init() node_is_initialized=%d\n",node_is_initialized);
node_is_initialized = true;
Locker locker(mIsolate);
Isolate::Scope isolate_scope(mIsolate);
HandleScope handle_scope(mIsolate); // Create a stack-allocated handle scope.
Local<Context> ctx = Context::New(mIsolate);
ctx->SetEmbedderData(HandleMap::kContextIdIndex, Integer::New(mIsolate, 99));
mContext.Reset(mIsolate, ctx);
rtLogWarn("DONE in rtNode::init()\n");
}
}
#endif
rtError rtScriptNode::term()
{
rtLogInfo(__FUNCTION__);
nodeTerminated = true;
#if 0
#ifdef USE_CONTEXTIFY_CLONES
if( mRefContext.getPtr() )
{
mRefContext->Release();
}
#endif
#endif
if(node_isolate)
{
rtLogWarn("\n++++++++++++++++++ DISPOSE\n\n");
node_isolate = NULL;
mIsolate = NULL;
}
if(node_is_initialized)
{
//V8::Dispose();
node_is_initialized = false;
//V8::ShutdownPlatform();
if(mPlatform)
{
#ifdef USE_NODE_PLATFORM
#ifndef USE_NODE_10
node::NodePlatform* platform_ = static_cast<node::NodePlatform*>(mPlatform);
platform_->Shutdown();
node::FreePlatform(platform_);
#endif
#else
delete mPlatform;
#endif // USE_NODE_PLATFORM
mPlatform = NULL;
}
// if(mPxNodeExtension)
// {
// delete mPxNodeExtension;
// mPxNodeExtension = NULL;
// }
}
//HandleMap::printAll();
return RT_OK;
}
inline bool fileExists(const std::string& name)
{
struct stat buffer;
return (stat (name.c_str(), &buffer) == 0);
}
rtNodeContextRef rtScriptNode::getGlobalContext() const
{
return rtNodeContextRef();
}
rtNodeContextRef rtScriptNode::createContext(bool ownThread)
{
UNUSED_PARAM(ownThread); // not implemented yet.
rtNodeContextRef ctxref;
#ifdef USE_CONTEXTIFY_CLONES
if(mRefContext.getPtr() == NULL)
{
mRefContext = new rtNodeContext(mIsolate,mPlatform);
ctxref = mRefContext;
static std::string sandbox_path = rtGetRootModulePath(SANDBOX_JS);
// Populate 'sandbox' vars in JS...
if(fileExists(sandbox_path.c_str()))
{
mRefContext->runFile(sandbox_path.c_str());
}
else
{
rtLogError("## ERROR: Could not find \"%s\" ...", sandbox_path.c_str());
}
// !CLF: TODO Why is ctxref being reassigned from the mRefContext already assigned?
//ctxref = new rtNodeContext(mIsolate, mRefContext);
}
else
{
// rtLogInfo("\n createContext() >> CLONE CREATED !!!!!!");
ctxref = new rtNodeContext(mIsolate, mRefContext); // CLONE !!!
}
#else
ctxref = new rtNodeContext(mIsolate,mPlatform);
#endif
// TODO: Handle refs in map ... don't leak !
// mNodeContexts[ ctxref->getContextId() ] = ctxref; // ADD to map
return ctxref;
}
rtError rtScriptNode::createContext(const char *lang, rtScriptContextRef& ctx)
{
rtNodeContextRef nodeCtx = createContext();
ctx = (rtIScriptContext*)nodeCtx.getPtr();
return RT_OK;
}
unsigned long rtNodeContext::Release()
{
long l = rtAtomicDec(&mRefCount);
if (l == 0)
{
delete this;
}
return l;
}
rtError createScriptNode(rtScriptRef& script)
{
script = new rtScriptNode(false);
return RT_OK;
}
#endif // RTSCRIPT_SUPPORT_NODE
| 25.583104 | 150 | 0.664018 | [
"render",
"object"
] |
101cff2ee9d2ed0be3bbf97ba0f43bd1fcd93c24 | 8,303 | cpp | C++ | Code/GraphMol/FileParsers/MaeMolSupplier.cpp | marcwittke/rdkit | 576506206a7b3366d626d2e5ec50cebcf7a5bda4 | [
"PostgreSQL"
] | 1 | 2020-10-15T20:39:27.000Z | 2020-10-15T20:39:27.000Z | Code/GraphMol/FileParsers/MaeMolSupplier.cpp | marcwittke/rdkit | 576506206a7b3366d626d2e5ec50cebcf7a5bda4 | [
"PostgreSQL"
] | null | null | null | Code/GraphMol/FileParsers/MaeMolSupplier.cpp | marcwittke/rdkit | 576506206a7b3366d626d2e5ec50cebcf7a5bda4 | [
"PostgreSQL"
] | null | null | null | //
// Copyright (C) 2018 Pat Lorton
//
// @@ All Rights Reserved @@
// This file is part of the RDKit.
// The contents are covered by the terms of the BSD license
// which is included in the file license.txt, found at the root
// of the RDKit source tree.
//
#include <iostream>
#include <fstream>
#include <map>
#include <RDGeneral/BadFileException.h>
#include <RDGeneral/FileParseException.h>
#include <GraphMol/MolInterchange/details.h>
#include <GraphMol/MolOps.h>
#include <GraphMol/MonomerInfo.h>
#include <GraphMol/RWMol.h>
#include <GraphMol/FileParsers/MolSupplier.h>
#include <maeparser/Reader.hpp>
using std::shared_ptr;
using namespace schrodinger::mae;
namespace RDKit {
using RDKit::MolInterchange::bolookup;
MaeMolSupplier::MaeMolSupplier(shared_ptr<std::istream> inStream,
bool sanitize, bool removeHs) {
PRECONDITION(inStream, "bad stream");
dp_sInStream = inStream;
dp_inStream = inStream.get();
df_owner = true;
df_sanitize = sanitize;
df_removeHs = removeHs;
d_reader.reset(new Reader(dp_sInStream));
d_next_struct = d_reader->next("f_m_ct");
}
MaeMolSupplier::MaeMolSupplier(std::istream *inStream, bool takeOwnership,
bool sanitize, bool removeHs) {
PRECONDITION(inStream, "bad stream");
PRECONDITION(takeOwnership, "takeOwnership is required for MaeMolSupplier");
dp_inStream = inStream;
dp_sInStream.reset(dp_inStream);
df_owner = takeOwnership; // always true
df_sanitize = sanitize;
df_removeHs = removeHs;
d_reader.reset(new Reader(dp_sInStream));
d_next_struct = d_reader->next("f_m_ct");
}
MaeMolSupplier::MaeMolSupplier(const std::string &fileName, bool sanitize,
bool removeHs) {
df_owner = true;
auto *ifs = new std::ifstream(fileName.c_str(), std::ios_base::binary);
if (!ifs || !(*ifs) || ifs->bad()) {
std::ostringstream errout;
errout << "Bad input file " << fileName;
throw BadFileException(errout.str());
}
dp_inStream = static_cast<std::istream *>(ifs);
dp_sInStream.reset(dp_inStream);
df_sanitize = sanitize;
df_removeHs = removeHs;
d_reader.reset(new Reader(dp_sInStream));
d_next_struct = d_reader->next("f_m_ct");
}
void MaeMolSupplier::init() {}
void MaeMolSupplier::reset() {}
class PDBInfo
{
public:
PDBInfo(const shared_ptr<const IndexedBlock>& atom_data);
shared_ptr<IndexedStringProperty> m_atom_name;
shared_ptr<IndexedStringProperty> m_residue_name;
shared_ptr<IndexedStringProperty> m_chain_id;
shared_ptr<IndexedStringProperty> m_insertion_code;
shared_ptr<IndexedIntProperty> m_resnum;
shared_ptr<IndexedRealProperty> m_occupancy;
shared_ptr<IndexedRealProperty> m_tempfac;
};
PDBInfo::PDBInfo(const shared_ptr<const IndexedBlock>& atom_data)
{
try {
m_atom_name = atom_data->getStringProperty("s_m_pdb_atom_name");
} catch (std::out_of_range &) { }
try {
m_residue_name = atom_data->getStringProperty("s_m_pdb_residue_name");
} catch (std::out_of_range &) { }
try {
m_chain_id = atom_data->getStringProperty("s_m_chain_name");
} catch (std::out_of_range &) { }
try {
m_insertion_code = atom_data->getStringProperty("s_m_insertion_code");
} catch (std::out_of_range &) { }
try {
m_resnum = atom_data->getIntProperty("i_m_residue_number");
} catch (std::out_of_range &) { }
try {
m_occupancy = atom_data->getRealProperty("r_m_pdb_occupancy");
} catch (std::out_of_range &) { }
try {
m_tempfac = atom_data->getRealProperty("r_m_pdb_tfactor");
} catch (std::out_of_range &) { }
}
void addAtomPDBData(const PDBInfo& pdb_info, Atom* atom, size_t atom_num)
{
if(!pdb_info.m_atom_name->isDefined(atom_num)) {
return; // Need a PDB atom name to populate info
}
AtomPDBResidueInfo *rd_info = new AtomPDBResidueInfo(
pdb_info.m_atom_name->at(atom_num));
atom->setMonomerInfo(rd_info);
if(pdb_info.m_residue_name && pdb_info.m_residue_name->isDefined(atom_num))
{
rd_info->setResidueName(pdb_info.m_residue_name->at(atom_num));
}
if(pdb_info.m_chain_id && pdb_info.m_chain_id->isDefined(atom_num))
{
rd_info->setChainId(pdb_info.m_chain_id->at(atom_num));
}
if(pdb_info.m_insertion_code &&
pdb_info.m_insertion_code->isDefined(atom_num))
{
rd_info->setInsertionCode(pdb_info.m_insertion_code->at(atom_num));
}
if(pdb_info.m_resnum && pdb_info.m_resnum->isDefined(atom_num))
{
rd_info->setResidueNumber(pdb_info.m_resnum->at(atom_num));
}
if(pdb_info.m_occupancy && pdb_info.m_occupancy->isDefined(atom_num))
{
rd_info->setOccupancy(pdb_info.m_occupancy->at(atom_num));
}
if(pdb_info.m_tempfac && pdb_info.m_tempfac->isDefined(atom_num))
{
rd_info->setTempFactor(pdb_info.m_tempfac->at(atom_num));
}
}
void addAtoms(shared_ptr<Block>& current_struct, RWMol& mol)
{
// Atom data is in the m_atom indexed block
{
const auto atom_data = current_struct->getIndexedBlock("m_atom");
// All atoms are guaranteed to have these three field names:
const auto atomic_numbers = atom_data->getIntProperty("i_m_atomic_number");
const auto xs = atom_data->getRealProperty("r_m_x_coord");
const auto ys = atom_data->getRealProperty("r_m_y_coord");
const auto zs = atom_data->getRealProperty("r_m_z_coord");
const auto atom_count = atomic_numbers->size();
shared_ptr<IndexedIntProperty> atomic_charges;
try {
atomic_charges = atom_data->getIntProperty("i_m_formal_charge");
} catch (std::out_of_range &) {
}
// atomic numbers, and x, y, and z coordinates
auto conf = new RDKit::Conformer(atom_count);
conf->set3D(true);
conf->setId(0);
PDBInfo pdb_info(atom_data);
for (size_t i = 0; i < atom_count; ++i) {
Atom *atom = new Atom(atomic_numbers->at(i));
mol.addAtom(atom, true, true);
if (atomic_charges) {
atom->setFormalCharge(atomic_charges->at(i));
}
RDGeom::Point3D pos;
pos.x = xs->at(i);
pos.y = ys->at(i);
pos.z = zs->at(i);
conf->setAtomPos(i, pos);
if(pdb_info.m_atom_name) {
addAtomPDBData(pdb_info, atom, i);
}
}
mol.addConformer(conf, false);
}
}
void addBonds(shared_ptr<Block>& current_struct, RWMol& mol)
{
const auto bond_data = current_struct->getIndexedBlock("m_bond");
// All bonds are guaranteed to have these three field names:
auto from_atoms = bond_data->getIntProperty("i_m_from");
auto to_atoms = bond_data->getIntProperty("i_m_to");
auto orders = bond_data->getIntProperty("i_m_order");
const auto size = from_atoms->size();
for (size_t i = 0; i < size; ++i) {
// Maestro atoms are 1 indexed!
const auto from_atom = from_atoms->at(i) - 1;
const auto to_atom = to_atoms->at(i) - 1;
const auto order = bolookup.find(orders->at(i))->second;
if (from_atom > to_atom) continue; // Maestro files double-list bonds
auto bond = new Bond(order);
bond->setOwningMol(mol);
bond->setBeginAtomIdx(from_atom);
bond->setEndAtomIdx(to_atom);
mol.addBond(bond, true);
}
}
ROMol *MaeMolSupplier::next() {
if (d_next_struct == nullptr) {
throw FileParseException("All structures read from Maestro file");
}
// Make sure even if later calls except, we're ready to read the next struct
auto current_struct = d_next_struct;
d_next_struct = d_reader->next("f_m_ct");
auto mol = new RWMol();
auto mol_title = current_struct->getStringProperty("s_m_title");
mol->setProp(common_properties::_Name, mol_title);
addAtoms(current_struct, *mol);
addBonds(current_struct, *mol);
if (df_sanitize) {
if (df_removeHs) {
MolOps::removeHs(*mol, false, false);
} else {
MolOps::sanitizeMol(*mol);
}
} else {
// we need some properties for the chiral setup
mol->updatePropertyCache(false);
}
/* Set tetrahedral chirality from 3D co-ordinates */
MolOps::assignChiralTypesFrom3D(*mol);
MolOps::detectBondStereochemistry(*mol);
return (ROMol *)mol;
}
bool MaeMolSupplier::atEnd() { return d_next_struct == nullptr; }
} // namespace RDKit
| 30.638376 | 79 | 0.682645 | [
"3d"
] |
101d74776bcefda99294b5c3e6b7ea0e48abd03e | 23,930 | cc | C++ | chrome/browser/sync/glue/data_type_manager_impl_unittest.cc | 1065672644894730302/Chromium | 239dd49e906be4909e293d8991e998c9816eaa35 | [
"BSD-3-Clause"
] | 1 | 2019-04-23T15:57:04.000Z | 2019-04-23T15:57:04.000Z | chrome/browser/sync/glue/data_type_manager_impl_unittest.cc | 1065672644894730302/Chromium | 239dd49e906be4909e293d8991e998c9816eaa35 | [
"BSD-3-Clause"
] | null | null | null | chrome/browser/sync/glue/data_type_manager_impl_unittest.cc | 1065672644894730302/Chromium | 239dd49e906be4909e293d8991e998c9816eaa35 | [
"BSD-3-Clause"
] | null | null | null | // 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 "chrome/browser/sync/glue/data_type_manager_impl.h"
#include "base/compiler_specific.h"
#include "base/message_loop.h"
#include "chrome/browser/sync/glue/backend_data_type_configurer.h"
#include "chrome/browser/sync/glue/data_type_controller.h"
#include "chrome/browser/sync/glue/fake_data_type_controller.h"
#include "chrome/common/chrome_notification_types.h"
#include "content/public/browser/notification_details.h"
#include "content/public/browser/notification_registrar.h"
#include "content/public/browser/notification_service.h"
#include "content/test/notification_observer_mock.h"
#include "content/test/test_browser_thread.h"
#include "sync/internal_api/configure_reason.h"
#include "sync/syncable/model_type.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace browser_sync {
using syncable::ModelType;
using syncable::ModelTypeSet;
using syncable::ModelTypeToString;
using syncable::BOOKMARKS;
using syncable::APPS;
using syncable::PASSWORDS;
using syncable::PREFERENCES;
using testing::_;
using testing::Mock;
using testing::ResultOf;
// Fake BackendDataTypeConfigurer implementation that simply stores
// away the nigori state and callback passed into ConfigureDataTypes.
class FakeBackendDataTypeConfigurer : public BackendDataTypeConfigurer {
public:
FakeBackendDataTypeConfigurer() : last_nigori_state_(WITHOUT_NIGORI) {}
virtual ~FakeBackendDataTypeConfigurer() {}
virtual void ConfigureDataTypes(
sync_api::ConfigureReason reason,
ModelTypeSet types_to_add,
ModelTypeSet types_to_remove,
NigoriState nigori_state,
base::Callback<void(ModelTypeSet)> ready_task,
base::Callback<void()> retry_callback) OVERRIDE {
last_nigori_state_ = nigori_state;
last_ready_task_ = ready_task;
}
base::Callback<void(ModelTypeSet)> last_ready_task() const {
return last_ready_task_;
}
NigoriState last_nigori_state() const {
return last_nigori_state_;
}
private:
base::Callback<void(ModelTypeSet)> last_ready_task_;
NigoriState last_nigori_state_;
};
// Used by SetConfigureDoneExpectation.
DataTypeManager::ConfigureStatus GetStatus(
const content::NotificationDetails& details) {
const DataTypeManager::ConfigureResult* result =
content::Details<const DataTypeManager::ConfigureResult>(
details).ptr();
return result->status;
}
// The actual test harness class, parametrized on NigoriState (i.e.,
// tests are run both configuring with nigori, and configuring
// without).
class SyncDataTypeManagerImplTest
: public testing::TestWithParam<BackendDataTypeConfigurer::NigoriState> {
public:
SyncDataTypeManagerImplTest()
: ui_thread_(content::BrowserThread::UI, &ui_loop_) {}
virtual ~SyncDataTypeManagerImplTest() {
}
protected:
virtual void SetUp() {
registrar_.Add(&observer_,
chrome::NOTIFICATION_SYNC_CONFIGURE_START,
content::NotificationService::AllSources());
registrar_.Add(&observer_,
chrome::NOTIFICATION_SYNC_CONFIGURE_DONE,
content::NotificationService::AllSources());
}
// A clearer name for the param accessor.
BackendDataTypeConfigurer::NigoriState GetNigoriState() {
return GetParam();
}
void SetConfigureStartExpectation() {
EXPECT_CALL(
observer_,
Observe(int(chrome::NOTIFICATION_SYNC_CONFIGURE_START),
_, _));
}
void SetConfigureDoneExpectation(DataTypeManager::ConfigureStatus status) {
EXPECT_CALL(
observer_,
Observe(int(chrome::NOTIFICATION_SYNC_CONFIGURE_DONE), _,
ResultOf(&GetStatus, status)));
}
// Configure the given DTM with the given desired types.
void Configure(DataTypeManagerImpl* dtm,
const DataTypeManager::TypeSet& desired_types) {
const sync_api::ConfigureReason kReason =
sync_api::CONFIGURE_REASON_RECONFIGURATION;
if (GetNigoriState() == BackendDataTypeConfigurer::WITH_NIGORI) {
dtm->Configure(desired_types, kReason);
} else {
dtm->ConfigureWithoutNigori(desired_types, kReason);
}
}
// Finish downloading for the given DTM. Should be done only after
// a call to Configure().
void FinishDownload(const DataTypeManager& dtm,
ModelTypeSet failed_download_types) {
EXPECT_EQ(DataTypeManager::DOWNLOAD_PENDING, dtm.state());
EXPECT_EQ(GetNigoriState(), configurer_.last_nigori_state());
ASSERT_FALSE(configurer_.last_ready_task().is_null());
configurer_.last_ready_task().Run(failed_download_types);
}
// Adds a fake controller for the given type to |controllers_|.
// Should be called only before setting up the DTM.
void AddController(ModelType model_type) {
controllers_[model_type] = new FakeDataTypeController(model_type);
}
// Gets the fake controller for the given type, which should have
// been previously added via AddController().
scoped_refptr<FakeDataTypeController> GetController(
ModelType model_type) const {
DataTypeController::TypeMap::const_iterator it =
controllers_.find(model_type);
if (it == controllers_.end()) {
return NULL;
}
return make_scoped_refptr(
static_cast<FakeDataTypeController*>(it->second.get()));
}
MessageLoopForUI ui_loop_;
content::TestBrowserThread ui_thread_;
DataTypeController::TypeMap controllers_;
FakeBackendDataTypeConfigurer configurer_;
content::NotificationObserverMock observer_;
content::NotificationRegistrar registrar_;
};
// Set up a DTM with no controllers, configure it, finish downloading,
// and then stop it.
TEST_P(SyncDataTypeManagerImplTest, NoControllers) {
DataTypeManagerImpl dtm(&configurer_, &controllers_);
SetConfigureStartExpectation();
SetConfigureDoneExpectation(DataTypeManager::OK);
Configure(&dtm, ModelTypeSet());
EXPECT_EQ(DataTypeManager::DOWNLOAD_PENDING, dtm.state());
FinishDownload(dtm, ModelTypeSet());
EXPECT_EQ(DataTypeManager::CONFIGURED, dtm.state());
dtm.Stop();
EXPECT_EQ(DataTypeManager::STOPPED, dtm.state());
}
// Set up a DTM with a single controller, configure it, finish
// downloading, finish starting the controller, and then stop the DTM.
TEST_P(SyncDataTypeManagerImplTest, ConfigureOne) {
AddController(BOOKMARKS);
DataTypeManagerImpl dtm(&configurer_, &controllers_);
SetConfigureStartExpectation();
SetConfigureDoneExpectation(DataTypeManager::OK);
Configure(&dtm, ModelTypeSet(BOOKMARKS));
EXPECT_EQ(DataTypeManager::DOWNLOAD_PENDING, dtm.state());
FinishDownload(dtm, ModelTypeSet());
EXPECT_EQ(DataTypeManager::CONFIGURING, dtm.state());
GetController(BOOKMARKS)->FinishStart(DataTypeController::OK);
EXPECT_EQ(DataTypeManager::CONFIGURED, dtm.state());
dtm.Stop();
EXPECT_EQ(DataTypeManager::STOPPED, dtm.state());
}
// Set up a DTM with 2 controllers. configure it. One of them finishes loading
// after the timeout. Make sure eventually all are configured.
TEST_P(SyncDataTypeManagerImplTest, ConfigureSlowLoadingType) {
AddController(BOOKMARKS);
AddController(APPS);
GetController(BOOKMARKS)->SetDelayModelLoad();
DataTypeManagerImpl dtm(&configurer_, &controllers_);
SetConfigureStartExpectation();
SetConfigureDoneExpectation(DataTypeManager::PARTIAL_SUCCESS);
syncable::ModelTypeSet types;
types.Put(BOOKMARKS);
types.Put(APPS);
Configure(&dtm, types);
EXPECT_EQ(DataTypeManager::DOWNLOAD_PENDING, dtm.state());
FinishDownload(dtm, ModelTypeSet());
EXPECT_EQ(DataTypeManager::CONFIGURING, dtm.state());
base::OneShotTimer<ModelAssociationManager>* timer =
dtm.GetModelAssociationManagerForTesting()->GetTimerForTesting();
base::Closure task = timer->user_task();
timer->Stop();
task.Run();
SetConfigureDoneExpectation(DataTypeManager::OK);
GetController(APPS)->FinishStart(DataTypeController::OK);
SetConfigureStartExpectation();
GetController(BOOKMARKS)->SimulateModelLoadFinishing();
FinishDownload(dtm, ModelTypeSet());
GetController(BOOKMARKS)->SimulateModelLoadFinishing();
GetController(BOOKMARKS)->FinishStart(DataTypeController::OK);
EXPECT_EQ(DataTypeManager::CONFIGURED, dtm.state());
dtm.Stop();
EXPECT_EQ(DataTypeManager::STOPPED, dtm.state());
}
// Set up a DTM with a single controller, configure it, but stop it
// before finishing the download. It should still be safe to run the
// download callback even after the DTM is stopped and destroyed.
TEST_P(SyncDataTypeManagerImplTest, ConfigureOneStopWhileDownloadPending) {
AddController(BOOKMARKS);
{
DataTypeManagerImpl dtm(&configurer_, &controllers_);
SetConfigureStartExpectation();
SetConfigureDoneExpectation(DataTypeManager::ABORTED);
Configure(&dtm, ModelTypeSet(BOOKMARKS));
EXPECT_EQ(DataTypeManager::DOWNLOAD_PENDING, dtm.state());
dtm.Stop();
EXPECT_EQ(DataTypeManager::STOPPED, dtm.state());
}
configurer_.last_ready_task().Run(ModelTypeSet());
}
// Set up a DTM with a single controller, configure it, finish
// downloading, but stop the DTM before the controller finishes
// starting up. It should still be safe to finish starting up the
// controller even after the DTM is stopped and destroyed.
TEST_P(SyncDataTypeManagerImplTest, ConfigureOneStopWhileStartingModel) {
AddController(BOOKMARKS);
{
DataTypeManagerImpl dtm(&configurer_, &controllers_);
SetConfigureStartExpectation();
SetConfigureDoneExpectation(DataTypeManager::ABORTED);
Configure(&dtm, ModelTypeSet(BOOKMARKS));
EXPECT_EQ(DataTypeManager::DOWNLOAD_PENDING, dtm.state());
FinishDownload(dtm, ModelTypeSet());
EXPECT_EQ(DataTypeManager::CONFIGURING, dtm.state());
dtm.Stop();
EXPECT_EQ(DataTypeManager::STOPPED, dtm.state());
}
GetController(BOOKMARKS)->FinishStart(DataTypeController::OK);
}
// Set up a DTM with a single controller, configure it, finish
// downloading, start the controller's model, but stop the DTM before
// the controller finishes starting up. It should still be safe to
// finish starting up the controller even after the DTM is stopped and
// destroyed.
TEST_P(SyncDataTypeManagerImplTest, ConfigureOneStopWhileAssociating) {
AddController(BOOKMARKS);
{
DataTypeManagerImpl dtm(&configurer_, &controllers_);
SetConfigureStartExpectation();
SetConfigureDoneExpectation(DataTypeManager::ABORTED);
Configure(&dtm, ModelTypeSet(BOOKMARKS));
EXPECT_EQ(DataTypeManager::DOWNLOAD_PENDING, dtm.state());
FinishDownload(dtm, ModelTypeSet());
EXPECT_EQ(DataTypeManager::CONFIGURING, dtm.state());
dtm.Stop();
EXPECT_EQ(DataTypeManager::STOPPED, dtm.state());
}
GetController(BOOKMARKS)->FinishStart(DataTypeController::OK);
}
// Set up a DTM with a single controller. Then:
//
// 1) Configure.
// 2) Finish the download for step 1.
// 3) Finish starting the controller with the NEEDS_CRYPTO status.
// 4) Configure again.
// 5) Finish the download for step 4.
// 6) Finish starting the controller successfully.
// 7) Stop the DTM.
TEST_P(SyncDataTypeManagerImplTest, OneWaitingForCrypto) {
AddController(PASSWORDS);
DataTypeManagerImpl dtm(&configurer_, &controllers_);
SetConfigureStartExpectation();
const ModelTypeSet types(PASSWORDS);
// Step 1.
Configure(&dtm, types);
EXPECT_EQ(DataTypeManager::DOWNLOAD_PENDING, dtm.state());
// Step 2.
FinishDownload(dtm, ModelTypeSet());
EXPECT_EQ(DataTypeManager::CONFIGURING, dtm.state());
// Step 3.
GetController(PASSWORDS)->FinishStart(DataTypeController::NEEDS_CRYPTO);
EXPECT_EQ(DataTypeManager::BLOCKED, dtm.state());
Mock::VerifyAndClearExpectations(&observer_);
SetConfigureDoneExpectation(DataTypeManager::OK);
// Step 4.
Configure(&dtm, types);
EXPECT_EQ(DataTypeManager::DOWNLOAD_PENDING, dtm.state());
// Step 5.
FinishDownload(dtm, ModelTypeSet());
EXPECT_EQ(DataTypeManager::CONFIGURING, dtm.state());
// Step 6.
GetController(PASSWORDS)->FinishStart(DataTypeController::OK);
EXPECT_EQ(DataTypeManager::CONFIGURED, dtm.state());
// Step 7.
dtm.Stop();
EXPECT_EQ(DataTypeManager::STOPPED, dtm.state());
}
// Set up a DTM with two controllers. Then:
//
// 1) Configure with first controller.
// 2) Finish the download for step 1.
// 3) Finish starting the first controller.
// 4) Configure with both controllers.
// 5) Finish the download for step 4.
// 6) Finish starting the second controller.
// 7) Stop the DTM.
TEST_P(SyncDataTypeManagerImplTest, ConfigureOneThenBoth) {
AddController(BOOKMARKS);
AddController(PREFERENCES);
DataTypeManagerImpl dtm(&configurer_, &controllers_);
SetConfigureStartExpectation();
SetConfigureDoneExpectation(DataTypeManager::OK);
// Step 1.
Configure(&dtm, ModelTypeSet(BOOKMARKS));
EXPECT_EQ(DataTypeManager::DOWNLOAD_PENDING, dtm.state());
// Step 2.
FinishDownload(dtm, ModelTypeSet());
EXPECT_EQ(DataTypeManager::CONFIGURING, dtm.state());
// Step 3.
GetController(BOOKMARKS)->FinishStart(DataTypeController::OK);
EXPECT_EQ(DataTypeManager::CONFIGURED, dtm.state());
Mock::VerifyAndClearExpectations(&observer_);
SetConfigureStartExpectation();
SetConfigureDoneExpectation(DataTypeManager::OK);
// Step 4.
Configure(&dtm, ModelTypeSet(BOOKMARKS, PREFERENCES));
EXPECT_EQ(DataTypeManager::DOWNLOAD_PENDING, dtm.state());
// Step 5.
FinishDownload(dtm, ModelTypeSet());
EXPECT_EQ(DataTypeManager::CONFIGURING, dtm.state());
// Step 6.
GetController(PREFERENCES)->FinishStart(DataTypeController::OK);
EXPECT_EQ(DataTypeManager::CONFIGURED, dtm.state());
// Step 7.
dtm.Stop();
EXPECT_EQ(DataTypeManager::STOPPED, dtm.state());
}
// Set up a DTM with two controllers. Then:
//
// 1) Configure with first controller.
// 2) Finish the download for step 1.
// 3) Finish starting the first controller.
// 4) Configure with second controller.
// 5) Finish the download for step 4.
// 6) Finish starting the second controller.
// 7) Stop the DTM.
TEST_P(SyncDataTypeManagerImplTest, ConfigureOneThenSwitch) {
AddController(BOOKMARKS);
AddController(PREFERENCES);
DataTypeManagerImpl dtm(&configurer_, &controllers_);
SetConfigureStartExpectation();
SetConfigureDoneExpectation(DataTypeManager::OK);
// Step 1.
Configure(&dtm, ModelTypeSet(BOOKMARKS));
EXPECT_EQ(DataTypeManager::DOWNLOAD_PENDING, dtm.state());
// Step 2.
FinishDownload(dtm, ModelTypeSet());
EXPECT_EQ(DataTypeManager::CONFIGURING, dtm.state());
// Step 3.
GetController(BOOKMARKS)->FinishStart(DataTypeController::OK);
EXPECT_EQ(DataTypeManager::CONFIGURED, dtm.state());
Mock::VerifyAndClearExpectations(&observer_);
SetConfigureStartExpectation();
SetConfigureDoneExpectation(DataTypeManager::OK);
// Step 4.
Configure(&dtm, ModelTypeSet(PREFERENCES));
EXPECT_EQ(DataTypeManager::DOWNLOAD_PENDING, dtm.state());
// Step 5.
FinishDownload(dtm, ModelTypeSet());
EXPECT_EQ(DataTypeManager::CONFIGURING, dtm.state());
// Step 6.
GetController(PREFERENCES)->FinishStart(DataTypeController::OK);
EXPECT_EQ(DataTypeManager::CONFIGURED, dtm.state());
// Step 7.
dtm.Stop();
EXPECT_EQ(DataTypeManager::STOPPED, dtm.state());
}
// Set up a DTM with two controllers. Then:
//
// 1) Configure with first controller.
// 2) Finish the download for step 1.
// 3) Configure with both controllers.
// 4) Finish starting the first controller.
// 5) Finish the download for step 3.
// 6) Finish starting the second controller.
// 7) Stop the DTM.
TEST_P(SyncDataTypeManagerImplTest, ConfigureWhileOneInFlight) {
AddController(BOOKMARKS);
AddController(PREFERENCES);
DataTypeManagerImpl dtm(&configurer_, &controllers_);
SetConfigureStartExpectation();
SetConfigureDoneExpectation(DataTypeManager::OK);
// Step 1.
Configure(&dtm, ModelTypeSet(BOOKMARKS));
EXPECT_EQ(DataTypeManager::DOWNLOAD_PENDING, dtm.state());
// Step 2.
FinishDownload(dtm, ModelTypeSet());
EXPECT_EQ(DataTypeManager::CONFIGURING, dtm.state());
// Step 3.
Configure(&dtm, ModelTypeSet(BOOKMARKS, PREFERENCES));
EXPECT_EQ(DataTypeManager::CONFIGURING, dtm.state());
// Step 4.
GetController(BOOKMARKS)->FinishStart(DataTypeController::OK);
EXPECT_EQ(DataTypeManager::BLOCKED, dtm.state());
// Pump the loop to run the posted DTMI::ConfigureImpl() task from
// DTMI::ProcessReconfigure() (triggered by FinishStart()).
ui_loop_.RunAllPending();
EXPECT_EQ(DataTypeManager::DOWNLOAD_PENDING, dtm.state());
// Step 5.
FinishDownload(dtm, ModelTypeSet());
EXPECT_EQ(DataTypeManager::CONFIGURING, dtm.state());
// Step 6.
GetController(PREFERENCES)->FinishStart(DataTypeController::OK);
EXPECT_EQ(DataTypeManager::CONFIGURED, dtm.state());
// Step 7.
dtm.Stop();
EXPECT_EQ(DataTypeManager::STOPPED, dtm.state());
}
// Set up a DTM with one controller. Then configure, finish
// downloading, and start the controller with an unrecoverable error.
// The unrecoverable error should cause the DTM to stop.
TEST_P(SyncDataTypeManagerImplTest, OneFailingController) {
AddController(BOOKMARKS);
DataTypeManagerImpl dtm(&configurer_, &controllers_);
SetConfigureStartExpectation();
SetConfigureDoneExpectation(DataTypeManager::UNRECOVERABLE_ERROR);
Configure(&dtm, ModelTypeSet(BOOKMARKS));
EXPECT_EQ(DataTypeManager::DOWNLOAD_PENDING, dtm.state());
FinishDownload(dtm, ModelTypeSet());
EXPECT_EQ(DataTypeManager::CONFIGURING, dtm.state());
GetController(BOOKMARKS)->FinishStart(
DataTypeController::UNRECOVERABLE_ERROR);
EXPECT_EQ(DataTypeManager::STOPPED, dtm.state());
}
// Set up a DTM with two controllers. Then:
//
// 1) Configure with both controllers.
// 2) Finish the download for step 1.
// 3) Finish starting the first controller successfully.
// 4) Finish starting the second controller with an unrecoverable error.
//
// The failure from step 4 should cause the DTM to stop.
TEST_P(SyncDataTypeManagerImplTest, SecondControllerFails) {
AddController(BOOKMARKS);
AddController(PREFERENCES);
DataTypeManagerImpl dtm(&configurer_, &controllers_);
SetConfigureStartExpectation();
SetConfigureDoneExpectation(DataTypeManager::UNRECOVERABLE_ERROR);
// Step 1.
Configure(&dtm, ModelTypeSet(BOOKMARKS, PREFERENCES));
EXPECT_EQ(DataTypeManager::DOWNLOAD_PENDING, dtm.state());
// Step 2.
FinishDownload(dtm, ModelTypeSet());
EXPECT_EQ(DataTypeManager::CONFIGURING, dtm.state());
// Step 3.
GetController(BOOKMARKS)->FinishStart(DataTypeController::OK);
EXPECT_EQ(DataTypeManager::CONFIGURING, dtm.state());
// Step 4.
GetController(PREFERENCES)->FinishStart(
DataTypeController::UNRECOVERABLE_ERROR);
EXPECT_EQ(DataTypeManager::STOPPED, dtm.state());
}
// Set up a DTM with two controllers. Then:
//
// 1) Configure with both controllers.
// 2) Finish the download for step 1.
// 3) Finish starting the first controller with an association failure.
// 4) Finish starting the second controller successfully.
// 5) Stop the DTM.
//
// The association failure from step 3 should be ignored.
//
// TODO(akalin): Check that the data type that failed association is
// recorded in the CONFIGURE_DONE notification.
TEST_P(SyncDataTypeManagerImplTest, OneControllerFailsAssociation) {
AddController(BOOKMARKS);
AddController(PREFERENCES);
DataTypeManagerImpl dtm(&configurer_, &controllers_);
SetConfigureStartExpectation();
SetConfigureDoneExpectation(DataTypeManager::PARTIAL_SUCCESS);
// Step 1.
Configure(&dtm, ModelTypeSet(BOOKMARKS, PREFERENCES));
EXPECT_EQ(DataTypeManager::DOWNLOAD_PENDING, dtm.state());
// Step 2.
FinishDownload(dtm, ModelTypeSet());
EXPECT_EQ(DataTypeManager::CONFIGURING, dtm.state());
// Step 3.
GetController(BOOKMARKS)->FinishStart(DataTypeController::OK);
EXPECT_EQ(DataTypeManager::CONFIGURING, dtm.state());
// Step 4.
GetController(PREFERENCES)->FinishStart(
DataTypeController::ASSOCIATION_FAILED);
EXPECT_EQ(DataTypeManager::CONFIGURED, dtm.state());
// Step 5.
dtm.Stop();
EXPECT_EQ(DataTypeManager::STOPPED, dtm.state());
}
// Set up a DTM with two controllers. Then:
//
// 1) Configure with first controller.
// 2) Configure with both controllers.
// 3) Finish the download for step 1.
// 4) Finish the download for step 2.
// 5) Finish starting both controllers.
// 6) Stop the DTM.
TEST_P(SyncDataTypeManagerImplTest, ConfigureWhileDownloadPending) {
AddController(BOOKMARKS);
AddController(PREFERENCES);
DataTypeManagerImpl dtm(&configurer_, &controllers_);
SetConfigureStartExpectation();
SetConfigureDoneExpectation(DataTypeManager::OK);
// Step 1.
Configure(&dtm, ModelTypeSet(BOOKMARKS));
EXPECT_EQ(DataTypeManager::DOWNLOAD_PENDING, dtm.state());
// Step 2.
Configure(&dtm, ModelTypeSet(BOOKMARKS, PREFERENCES));
EXPECT_EQ(DataTypeManager::DOWNLOAD_PENDING, dtm.state());
// Step 3.
FinishDownload(dtm, ModelTypeSet());
EXPECT_EQ(DataTypeManager::BLOCKED, dtm.state());
// Pump the loop to run the posted DTMI::ConfigureImpl() task from
// DTMI::ProcessReconfigure() (triggered by step 3).
ui_loop_.RunAllPending();
EXPECT_EQ(DataTypeManager::DOWNLOAD_PENDING, dtm.state());
// Step 4.
FinishDownload(dtm, ModelTypeSet());
EXPECT_EQ(DataTypeManager::CONFIGURING, dtm.state());
// Step 5.
GetController(BOOKMARKS)->FinishStart(DataTypeController::OK);
EXPECT_EQ(DataTypeManager::CONFIGURING, dtm.state());
GetController(PREFERENCES)->FinishStart(DataTypeController::OK);
EXPECT_EQ(DataTypeManager::CONFIGURED, dtm.state());
// Step 6.
dtm.Stop();
EXPECT_EQ(DataTypeManager::STOPPED, dtm.state());
}
// Set up a DTM with two controllers. Then:
//
// 1) Configure with first controller.
// 2) Configure with both controllers.
// 3) Finish the download for step 1 with a failed data type.
// 4) Finish the download for step 2 successfully.
// 5) Finish starting both controllers.
// 6) Stop the DTM.
//
// The failure from step 3 should be ignored since there's a
// reconfigure pending from step 2.
TEST_P(SyncDataTypeManagerImplTest, ConfigureWhileDownloadPendingWithFailure) {
AddController(BOOKMARKS);
AddController(PREFERENCES);
DataTypeManagerImpl dtm(&configurer_, &controllers_);
SetConfigureStartExpectation();
SetConfigureDoneExpectation(DataTypeManager::OK);
// Step 1.
Configure(&dtm, ModelTypeSet(BOOKMARKS));
EXPECT_EQ(DataTypeManager::DOWNLOAD_PENDING, dtm.state());
// Step 2.
Configure(&dtm, ModelTypeSet(BOOKMARKS, PREFERENCES));
EXPECT_EQ(DataTypeManager::DOWNLOAD_PENDING, dtm.state());
// Step 3.
FinishDownload(dtm, ModelTypeSet(BOOKMARKS));
EXPECT_EQ(DataTypeManager::BLOCKED, dtm.state());
// Pump the loop to run the posted DTMI::ConfigureImpl() task from
// DTMI::ProcessReconfigure() (triggered by step 3).
ui_loop_.RunAllPending();
EXPECT_EQ(DataTypeManager::DOWNLOAD_PENDING, dtm.state());
// Step 4.
FinishDownload(dtm, ModelTypeSet());
EXPECT_EQ(DataTypeManager::CONFIGURING, dtm.state());
// Step 5.
GetController(BOOKMARKS)->FinishStart(DataTypeController::OK);
EXPECT_EQ(DataTypeManager::CONFIGURING, dtm.state());
GetController(PREFERENCES)->FinishStart(DataTypeController::OK);
EXPECT_EQ(DataTypeManager::CONFIGURED, dtm.state());
// Step 6.
dtm.Stop();
EXPECT_EQ(DataTypeManager::STOPPED, dtm.state());
}
INSTANTIATE_TEST_CASE_P(
WithoutNigori, SyncDataTypeManagerImplTest,
::testing::Values(BackendDataTypeConfigurer::WITHOUT_NIGORI));
INSTANTIATE_TEST_CASE_P(
WithNigori, SyncDataTypeManagerImplTest,
::testing::Values(BackendDataTypeConfigurer::WITH_NIGORI));
} // namespace browser_sync
| 32.870879 | 79 | 0.747388 | [
"model"
] |
101ed45eff2fcd0723f0acb328b20264c01ea2e4 | 2,911 | cpp | C++ | MCTNode.cpp | ProgrammingIncluded/MTC-TFE | 7d3b58dc4970154ed7854a020de61fad8f9fee5d | [
"MIT"
] | null | null | null | MCTNode.cpp | ProgrammingIncluded/MTC-TFE | 7d3b58dc4970154ed7854a020de61fad8f9fee5d | [
"MIT"
] | null | null | null | MCTNode.cpp | ProgrammingIncluded/MTC-TFE | 7d3b58dc4970154ed7854a020de61fad8f9fee5d | [
"MIT"
] | 1 | 2020-09-28T02:46:46.000Z | 2020-09-28T02:46:46.000Z | #include "MCTNode.hpp"
/******************************************
* Project: MCT-TFE
* File: MCTNode.cpp
* By: ProgrammingIncluded
* Website: ProgrammingIncluded.github.io
*******************************************/
MCTNode::MCTNode(MCTNode *parent, uint option, uint *grid) {
this->parent = parent;
this->option = option;
this->grid = grid;
this->total_games = 0;
this->total_wins = 0;
// Create children options, must call after grid is set
genOpt();
// Check to see if we should adjust value.
if(VAL_H) {
if(children_options.size() != 0)
val = valueFromGrid(grid);
else if(max_grid(grid) == WIN_REQ)
val = LEAF_WEIGHT;
else
val = -LEAF_WEIGHT;
}
}
MCTNode::~MCTNode() {
delete[] grid;
}
MCTNode* MCTNode::createChild() {
if(children_options.size() == 0)
return nullptr;
// Find a random child.
int randNumber = 0;
if(children_options.size() > 1)
randNumber = rand() % (children_options.size() - 1);
uint opt = children_options[randNumber];
// Delete option
children_options.erase(children_options.begin() + randNumber);
uint *optGrid = optToGrid(opt);
MCTNode* resNode = new MCTNode(this, opt, optGrid);
children.push_back(resNode);
return resNode;
}
uint * MCTNode::optToGrid(uint opt) {
uint v = (uint) (opt / (DIR_SIZE * GRID_SIZE));
opt -= (v * DIR_SIZE * GRID_SIZE);
uint loc = (uint) (opt / DIR_SIZE);
char d = DIR[opt % DIR_SIZE];
uint *res = copy_grid(grid);
move_grid(res, d);
if(v == 0)
res[loc] = 2;
else
res[loc] = 4;
return res;
}
void MCTNode::genOpt() {
std::vector<uint> res;
// Generate all available options.
// Assumes grid is available.
auto avail = avail_dir(grid);
for(uint x = 0; x < avail.size(); ++x){
std::vector<uint> where = get_cells_where(avail[x].second, 0);
for(uint i = 0; i < where.size(); ++i) {
res.push_back(DIR_TO_NUM[avail[x].first] + DIR_SIZE * (where[i]));
res.push_back(DIR_TO_NUM[avail[x].first] + DIR_SIZE * (where[i] + GRID_SIZE));
}
}
// Delete the generated avail
for(auto i : avail)
delete[] i.second;
children_options = res;
}
long long int MCTNode::valueFromGrid(uint *A) {
long long int res = 0;
uint *fil = copy_grid(A);
// Size after difference
uint size = (GRID_WIDTH - 1) * GRID_WIDTH;
long long int *d = diff_grid(fil);
clip(d, 0, 1, size);
res += sum(d, size);
delete[] d;
// Rotate and do again.
rotate_grid_90(fil);
d = diff_grid(fil);
clip(d, 0, 1, size);
res += sum(d, size);
delete[] d;
delete[] fil;
return res;
} | 25.313043 | 91 | 0.542425 | [
"vector"
] |
102095162ebf9816b65a97d5fb2099abb6449554 | 3,485 | hpp | C++ | include/poplibs_test/CTCUtil.hpp | graphcore/poplibs | 3fe5a3ecafe995eddb72675d1b4a7af8a622009e | [
"MIT"
] | 95 | 2020-07-06T17:11:23.000Z | 2022-03-12T14:42:28.000Z | include/poplibs_test/CTCUtil.hpp | graphcore/poplibs | 3fe5a3ecafe995eddb72675d1b4a7af8a622009e | [
"MIT"
] | null | null | null | include/poplibs_test/CTCUtil.hpp | graphcore/poplibs | 3fe5a3ecafe995eddb72675d1b4a7af8a622009e | [
"MIT"
] | 14 | 2020-07-15T12:32:57.000Z | 2022-01-26T14:58:45.000Z | // Copyright (c) 2020 Graphcore Ltd. All rights reserved.
#ifndef poplibs_test_ctc_util_hpp
#define poplibs_test_ctc_util_hpp
#include <poputil/exceptions.hpp>
#include <boost/multi_array.hpp>
#include <boost/optional.hpp>
#include <random>
#include <vector>
namespace poplibs_test {
namespace ctc {
class RandomUtil {
std::mt19937 gen;
template <typename T> static void checkMinMax(T min, T max) {
if (max < min) {
poputil::poplibs_error(
"max must be greater than min when specifying random range");
}
}
public:
RandomUtil(unsigned s) { gen.seed(s); }
template <typename T> T range(T min, T max) {
std::uniform_int_distribution<> range(min, max);
return range(gen);
}
template <typename T> std::function<T()> generator(T min, T max) {
checkMinMax(min, max);
if constexpr (std::is_integral<T>::value) {
return [&, min, max]() -> T {
std::uniform_int_distribution<T> range(min, max);
return range(gen);
};
} else {
return [&, min, max]() -> T {
std::uniform_real_distribution<T> range(min, max);
return range(gen);
};
}
}
};
// Converts input sequence to ctc loss extendedLabels version, e.g.
// `a` -> `- a -`
// `aabb` -> `- a - b -`
// Optionally remove duplicates then insert blanks
std::vector<unsigned> extendedLabels(const std::vector<unsigned> &input,
unsigned blankSymbol,
bool stripDuplicates = false);
void print(const std::vector<unsigned> &sequence);
void print(const std::vector<unsigned> &sequence, unsigned blank);
template <typename FPType>
void printInput(const boost::multi_array<FPType, 2> &in, unsigned blank);
template <typename FPType>
void printBeams(
const std::vector<std::pair<std::vector<unsigned>, FPType>> &beams,
unsigned blank);
void validateTimeAndLabelBounds(
const boost::optional<unsigned> &minRandomTime,
const boost::optional<unsigned> &fixedTime, unsigned maxTime,
const boost::optional<unsigned> &minRandomLabelLength,
const boost::optional<unsigned> &fixedLabelLength, unsigned maxLabelLength);
// Return pair {T, LabelLength} for given min/fixed/max values of T and label
// length. It may be no combination is guaranteed that the label is
// representable for a given t (satisfy t >= labelLength * 2 - 1), which can
// cause confusing outputs (probabilties ~0). An error can be thrown for these
// cases (toggleable via `disableAlwaysSatisfiableError`)
std::pair<unsigned, unsigned>
getRandomSize(const boost::optional<unsigned> &minT,
const boost::optional<unsigned> &fixedT, unsigned maxT,
const boost::optional<unsigned> &minLabelLength,
const boost::optional<unsigned> &fixedLabelLength,
unsigned maxLabelLength, bool disableAlwaysSatisfiableError,
RandomUtil &rand);
// Create an input sequence of random data, and if the input sequence is a
// compatible length, increase its probability to stop the loss getting very
// small (important in large tests)
template <typename FPType>
std::pair<boost::multi_array<FPType, 2>, std::vector<unsigned>>
getRandomTestInput(unsigned timesteps, unsigned maxT, unsigned labelLength,
unsigned numClassesIncBlank, unsigned blankClass,
bool isLogits, RandomUtil &rand);
} // namespace ctc
} // namespace poplibs_test
#endif // poplibs_test_ctc_util_hpp
| 34.50495 | 80 | 0.683214 | [
"vector"
] |
1023abb50689f23ef454a05e76158e75d3c19e4c | 765 | cpp | C++ | igl/bounding_box_diagonal.cpp | aviadtzemah/animation2 | 9a3f980fbe27672fe71f8f61f73b5713f2af5089 | [
"Apache-2.0"
] | 2,392 | 2016-12-17T14:14:12.000Z | 2022-03-30T19:40:40.000Z | igl/bounding_box_diagonal.cpp | aviadtzemah/animation2 | 9a3f980fbe27672fe71f8f61f73b5713f2af5089 | [
"Apache-2.0"
] | 106 | 2018-04-19T17:47:31.000Z | 2022-03-01T19:44:11.000Z | igl/bounding_box_diagonal.cpp | aviadtzemah/animation2 | 9a3f980fbe27672fe71f8f61f73b5713f2af5089 | [
"Apache-2.0"
] | 184 | 2017-11-15T09:55:37.000Z | 2022-02-21T16:30:46.000Z | // This file is part of libigl, a simple c++ geometry processing library.
//
// Copyright (C) 2013 Alec Jacobson <alecjacobson@gmail.com>
//
// 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/.
#include "bounding_box_diagonal.h"
#include "mat_max.h"
#include "mat_min.h"
#include <cmath>
IGL_INLINE double igl::bounding_box_diagonal(
const Eigen::MatrixXd & V)
{
using namespace Eigen;
VectorXd maxV,minV;
VectorXi maxVI,minVI;
mat_max(V,1,maxV,maxVI);
mat_min(V,1,minV,minVI);
return sqrt((maxV-minV).array().square().sum());
}
#ifdef IGL_STATIC_LIBRARY
// Explicit template instantiation
#endif
| 28.333333 | 79 | 0.724183 | [
"geometry"
] |
1025c7bebc6c4eecbe9ee2b412403d8dfbf6f929 | 1,651 | cpp | C++ | csrc/src/node_index_project.cpp | Ray0089/PSGMN | 0363d558add24034e035d26121e2e1b61d97c198 | [
"Apache-2.0"
] | 18 | 2021-02-05T05:30:15.000Z | 2022-03-13T03:40:25.000Z | csrc/src/node_index_project.cpp | Ray0089/PSGMN | 0363d558add24034e035d26121e2e1b61d97c198 | [
"Apache-2.0"
] | 2 | 2021-04-17T02:20:42.000Z | 2021-09-11T07:05:13.000Z | csrc/src/node_index_project.cpp | Ray0089/PSGMN | 0363d558add24034e035d26121e2e1b61d97c198 | [
"Apache-2.0"
] | 5 | 2021-04-19T00:21:20.000Z | 2022-01-17T07:30:27.000Z | #include <torch/extension.h>
#include <torch/torch.h>
#include <vector>
#include <iostream>
extern THCState* state;
#define CHECK_CUDA(x) AT_ASSERTM(x.type().is_cuda(), #x " must be a CUDA tensor")
#define CHECK_CONTIGUOUS(x) AT_ASSERTM(x.is_contiguous(), #x " must be contiguous")
#define CHECK_INPUT(x) CHECK_CUDA(x); CHECK_CONTIGUOUS(x)
using namespace std;
at::Tensor node_project(
at::Tensor mask_u,
at::Tensor mask_v,
at::Tensor face_idx,
at::Tensor mesh_projected_pts,
at::Tensor mesh_projected_z
);
at::Tensor resize_mask(
at::Tensor mat,
int target_h,
int target_w
);
at::Tensor resize_img(
at::Tensor mat,
int target_h,
int target_w
);
at::Tensor node_project_launch(
at::Tensor mask_u,
at::Tensor mask_v,
at::Tensor face_idx,
at::Tensor mesh_projected_pts,
at::Tensor mesh_projected_z
){
auto result = node_project(
mask_u,
mask_v,
face_idx,
mesh_projected_pts,
mesh_projected_z);
return result;
}
at::Tensor resize_mask_launch(
at::Tensor mat,
int target_h,
int target_w
){
CHECK_INPUT(mat);
auto result = resize_mask(
mat,
target_h,
target_w);
return result;
}
at::Tensor resize_img_launch(
at::Tensor mat,
int target_h,
int target_w
){
auto result = resize_img(
mat,
target_h,
target_w);
return result;
}
PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
m.def("node_project", &node_project_launch, "project mesh node to image pixels");
m.def("resize_mask",&resize_mask_launch,"resize a 2d array");
m.def("resize_img",&resize_img_launch,"resize a 2d array");
} | 20.382716 | 85 | 0.679588 | [
"mesh",
"vector"
] |
10268b142d18ce95b5445399f6f62e6b0769252d | 10,236 | cpp | C++ | AppCUI/src/Graphics/ProgressStatus.cpp | rzaharia/AppCUI | 9aa37b154e04d0aa3e69a75798a698f591b0c8ca | [
"MIT"
] | null | null | null | AppCUI/src/Graphics/ProgressStatus.cpp | rzaharia/AppCUI | 9aa37b154e04d0aa3e69a75798a698f591b0c8ca | [
"MIT"
] | null | null | null | AppCUI/src/Graphics/ProgressStatus.cpp | rzaharia/AppCUI | 9aa37b154e04d0aa3e69a75798a698f591b0c8ca | [
"MIT"
] | null | null | null | #include "Internal.hpp"
#include <chrono>
using namespace AppCUI::Graphics;
using namespace AppCUI::Internal;
using namespace std::chrono;
#define MAX_PROGRESS_STATUS_TITLE 36
#define MAX_PROGRESS_STATUS_TEXT 52
#define PROGRESS_STATUS_PANEL_WIDTH 60
#define MAX_PROGRESS_TIME_TEXT 50
#define PROGRESS_STATUS_PANEL_HEIGHT 8
#define MIN_SECONDS_BEFORE_SHOWING_PROGRESS 2
// remove MessageBox definition that comes with Windows.h header
#ifdef MessageBox
# undef MessageBox
#endif
struct ProgressStatusData
{
CharacterBuffer Title;
CharacterBuffer Text;
unsigned long long MaxValue;
bool Showed;
time_point<steady_clock> StartTime;
unsigned long long Ellapsed, LastEllapsed;
Clip WindowClip;
Application* App;
char progressString[5];
char timeString[MAX_PROGRESS_TIME_TEXT];
int timeStringSize;
unsigned int Progress;
};
static ProgressStatusData PSData = { };
bool progress_inited = false;
void ProgressStatus_Paint_Panel()
{
auto canvas = &PSData.App->terminal->ScreenCanvas;
canvas->DarkenScreen();
canvas->SetAbsoluteClip(PSData.WindowClip);
canvas->SetTranslate(PSData.WindowClip.ScreenPosition.X, PSData.WindowClip.ScreenPosition.Y);
canvas->HideCursor();
canvas->Clear(' ', PSData.App->config.ProgressStatus.Border);
canvas->DrawRectSize(
0,
0,
PROGRESS_STATUS_PANEL_WIDTH,
PROGRESS_STATUS_PANEL_HEIGHT,
PSData.App->config.ProgressStatus.Border,
false);
WriteTextParams params(
WriteTextFlags::SingleLine | WriteTextFlags::OverwriteColors | WriteTextFlags::ClipToWidth |
WriteTextFlags::LeftMargin | WriteTextFlags::RightMargin,
TextAlignament::Center);
params.X = 5;
params.Y = 0;
params.Color = PSData.App->config.ProgressStatus.Title;
params.Width = PROGRESS_STATUS_PANEL_WIDTH - 10;
canvas->WriteText(PSData.Title, params);
PSData.Showed = true;
PSData.App->terminal->Update();
}
void ProgressStatus_Paint_Status()
{
auto canvas = &PSData.App->terminal->ScreenCanvas;
canvas->SetAbsoluteClip(PSData.WindowClip);
canvas->SetTranslate(PSData.WindowClip.ScreenPosition.X, PSData.WindowClip.ScreenPosition.Y);
canvas->FillHorizontalLine(
2, 3, PROGRESS_STATUS_PANEL_WIDTH - 3, ' ', PSData.App->config.ProgressStatus.EmptyProgressBar);
canvas->WriteSingleLineText(2, 2, PSData.Text, PSData.App->config.ProgressStatus.Text);
if (PSData.MaxValue > 0)
{
canvas->WriteSingleLineText(
PROGRESS_STATUS_PANEL_WIDTH - 6,
2,
std::string_view(PSData.progressString,4),
PSData.App->config.ProgressStatus.Percentage);
canvas->FillHorizontalLine(
2,
3,
((PSData.Progress * (PROGRESS_STATUS_PANEL_WIDTH - 4)) / 100) + 1,
' ',
PSData.App->config.ProgressStatus.FullProgressBar);
canvas->WriteSingleLineText(2, 4, "ETA:", PSData.App->config.ProgressStatus.Text);
}
else
{
canvas->WriteSingleLineText(2, 4, "Ellapsed:", PSData.App->config.ProgressStatus.Text);
}
canvas->WriteSingleLineText(
(PROGRESS_STATUS_PANEL_WIDTH - 2) - PSData.timeStringSize,
4,
std::string_view(PSData.timeString,PSData.timeStringSize),
PSData.App->config.ProgressStatus.Time);
PSData.App->terminal->Update();
}
void ProgressStatus_ComputeTime(unsigned long long time)
{
if (time == 0)
{
PSData.timeString[0] = 0;
PSData.timeStringSize = 0;
return;
}
unsigned int days = (unsigned int) (time / (24 * 60 * 60));
time = time % (24 * 60 * 60);
unsigned int hours = (unsigned int) (time / (60 * 60));
time = time % (60 * 60);
unsigned int min = (unsigned int) (time / 60);
unsigned int sec = (unsigned int) (time % 60);
if (days >= 10)
{
AppCUI::Utils::String::Set(PSData.timeString, "More than 10 days", MAX_PROGRESS_TIME_TEXT);
PSData.timeStringSize = 17;
return;
}
int index = 0;
if (days > 0)
{
PSData.timeString[0] = '0' + days;
PSData.timeString[1] = 'd';
PSData.timeString[2] = ' ';
index = 3;
}
PSData.timeString[index++] = '0' + hours / 10;
PSData.timeString[index++] = '0' + hours % 10;
PSData.timeString[index++] = ':';
PSData.timeString[index++] = '0' + min / 10;
PSData.timeString[index++] = '0' + min % 10;
PSData.timeString[index++] = ':';
PSData.timeString[index++] = '0' + sec / 10;
PSData.timeString[index++] = '0' + sec % 10;
PSData.timeString[index] = 0;
PSData.timeStringSize = index;
}
void ProgressStatus::Init(const AppCUI::Utils::ConstString& Title, unsigned long long maxValue)
{
Size appSize = { 0, 0 };
Application::GetApplicationSize(appSize);
PSData.MaxValue = maxValue;
PSData.Showed = false;
PSData.WindowClip.Reset();
PSData.WindowClip.Set(
(appSize.Width - PROGRESS_STATUS_PANEL_WIDTH) / 2,
(appSize.Height - PROGRESS_STATUS_PANEL_HEIGHT) / 2,
PROGRESS_STATUS_PANEL_WIDTH,
PROGRESS_STATUS_PANEL_HEIGHT);
PSData.App = AppCUI::Application::GetApplication();
PSData.progressString[0] = ' ';
PSData.progressString[1] = ' ';
PSData.progressString[2] = '0';
PSData.progressString[3] = '%';
PSData.progressString[4] = 0;
PSData.Progress = 0;
PSData.Ellapsed = 0;
PSData.LastEllapsed = 0;
PSData.timeString[0] = 0;
if (PSData.Title.Set(Title)==false)
{
LOG_WARNING("Fail to set title for progress status object !");
PSData.Title.Clear();
}
PSData.App->RepaintStatus = REPAINT_STATUS_ALL; // once the progress is over, all screen will be re-drawn
PSData.StartTime = std::chrono::steady_clock::now();
progress_inited = true;
}
bool __ProgressStatus_Update(unsigned long long value, const AppCUI::Utils::ConstString* content)
{
CHECK(progress_inited,
true,
"Progress status was not initialized ! Have you called ProgressStatus::Init(...) before calling "
"ProgressStatus::Update(...) ?");
unsigned int newProgress;
bool showStatus = false;
if (PSData.MaxValue > 0)
{
if (value < PSData.MaxValue)
newProgress = (unsigned int) ((value * (unsigned long long) 100) / PSData.MaxValue);
else
newProgress = 100;
if (newProgress != PSData.Progress)
{
PSData.Progress = newProgress;
if (newProgress >= 100)
{
PSData.progressString[0] = '1';
PSData.progressString[1] = '0';
PSData.progressString[2] = '0';
}
else
{
PSData.progressString[0] = ' ';
if (newProgress > 9)
{
PSData.progressString[1] = (newProgress / 10) + '0';
newProgress %= 10;
}
else
{
PSData.progressString[1] = ' ';
}
PSData.progressString[2] = newProgress + '0';
}
showStatus = true;
}
}
if (content)
{
if (!PSData.Text.Set(*content))
PSData.Text.Clear();
showStatus = true;
}
PSData.Ellapsed =
std::chrono::duration_cast<std::chrono::seconds>(std::chrono::steady_clock::now() - PSData.StartTime).count();
if (PSData.Ellapsed >= MIN_SECONDS_BEFORE_SHOWING_PROGRESS)
{
if (PSData.LastEllapsed != PSData.Ellapsed)
{
// only compute time if it's different from the previous display (meaning once per second)
if (PSData.MaxValue > 0)
{
if (PSData.Progress == 0)
ProgressStatus_ComputeTime(0);
else
ProgressStatus_ComputeTime(
(((unsigned long long) (100 - PSData.Progress)) * PSData.Ellapsed) /
((unsigned long long) PSData.Progress));
}
else
ProgressStatus_ComputeTime(PSData.Ellapsed);
showStatus = true;
PSData.LastEllapsed = PSData.Ellapsed;
}
if (PSData.Showed == false)
{
ProgressStatus_Paint_Panel();
ProgressStatus_Paint_Status();
}
else
{
// update screen if (message or progress have changed or at least one second has passed from the previous
// screen update)
if (showStatus)
ProgressStatus_Paint_Status();
}
}
if (PSData.App->terminal->IsEventAvailable())
{
AppCUI::Internal::SystemEvent evnt;
bool requestQuit = false;
// read up to 100 events
for (int tr = 0; tr < 100; tr++)
{
if (PSData.App->terminal->IsEventAvailable() == false)
break;
PSData.App->terminal->GetSystemEvent(evnt);
if ((evnt.eventType == AppCUI::Internal::SystemEventType::KeyPressed) &&
(evnt.keyCode == AppCUI::Input::Key::Escape))
{
requestQuit = true;
break;
}
}
if (requestQuit)
{
if (AppCUI::Dialogs::MessageBox::ShowOkCancel("Terminate", "Terminate current task ?") ==
AppCUI::Dialogs::Result::Ok)
{
progress_inited = false; // loop has ended
return true;
}
// repaint
ProgressStatus_Paint_Panel();
}
}
return false;
}
bool ProgressStatus::Update(unsigned long long value, const AppCUI::Utils::ConstString& content)
{
return __ProgressStatus_Update(value, &content);
}
bool ProgressStatus::Update(unsigned long long value)
{
return __ProgressStatus_Update(value, nullptr);
} | 34.348993 | 120 | 0.587339 | [
"object"
] |
1029e09ff54f065ba2d5d29bce4be81a552e9bfd | 5,914 | cpp | C++ | Source/XDK/hooker/Processors/ia32/idt/IdtTableHooker.cpp | eladraz/XDK | 232845680608c736d551e0a012e74269c4e3d207 | [
"BSD-3-Clause"
] | 23 | 2016-02-20T14:18:24.000Z | 2022-02-18T14:45:35.000Z | Source/XDK/hooker/Processors/ia32/idt/IdtTableHooker.cpp | eladraz/XDK | 232845680608c736d551e0a012e74269c4e3d207 | [
"BSD-3-Clause"
] | null | null | null | Source/XDK/hooker/Processors/ia32/idt/IdtTableHooker.cpp | eladraz/XDK | 232845680608c736d551e0a012e74269c4e3d207 | [
"BSD-3-Clause"
] | 13 | 2016-01-21T05:21:37.000Z | 2020-11-05T15:52:03.000Z | /*
* Copyright (c) 2008-2016, Integrity Project Ltd. 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 Integrity Project 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
*/
/*
* IdtTableHooker.cpp
*
* Implementation file
*
* Author: Elad Raz <e@eladraz.com>
*/
#include "xStl/types.h"
#include "xStl/os/os.h"
#include "xStl/data/datastream.h"
#include "xStl/except/trace.h"
#include "xStl/stream/traceStream.h"
#include "xdk/utils/processorLock.h"
#include "xdk/hooker/ProcessorsThread.h"
#include "xdk/hooker/ProcessorsThreadManager.h"
#include "xdk/hooker/Processors/ia32/idt/hookIdt.h"
#include "xdk/hooker/Processors/ia32/idt/IdtTableHooker.h"
IdtTableHooker::IdtTableHooker(InterruptListenerPtr callbackClass,
uint startRange /* = 0*/,
uint endRange /* = MAX_VECTOR_COUNT*/) :
m_startRange(startRange),
m_endRange(endRange),
m_jobReasonIsHook(true),
m_tableSize(endRange - startRange + 1),
m_numberOfProcessors(ProcessorsThread::getNumberOfProcessors()),
m_processorTaskNumber(ProcessorsThread::getNumberOfProcessors()),
m_tempCallbackClass(callbackClass)
{
CHECK(m_startRange <= m_endRange);
CHECK(m_endRange < MAX_VECTOR_COUNT);
//traceHigh("[*] Initializing IDtTableHooker" << endl);
// Generate the dispatch table
m_hooking.changeSize(m_tableSize * m_numberOfProcessors);
// Add the job
ProcessorsThreadManager::getInstance().addJob(
ProcessorJobPtr(this, SMARTPTR_DESTRUCT_NONE));
// Wait until finish
while (m_processorTaskNumber.getValue() > 0)
{
cOS::sleepMillisecond(10);
/*
if (m_processorTaskNumber.getValue() > 0)
{
traceHigh("IdtTableHooker: Ctor wait" << endl);
}
*/
}
// Free the allocated resource
m_tempCallbackClass = InterruptListenerPtr();
}
IdtTableHooker::~IdtTableHooker()
{
testPageableCode();
m_jobReasonIsHook = false;
// Wait until constructor will done.
while (m_processorTaskNumber.getValue() > 0)
cOS::sleepMillisecond(10);
m_processorTaskNumber.setValue(ProcessorsThread::getNumberOfProcessors());
// Add the a new remove job
ProcessorsThreadManager::getInstance().addJob(
ProcessorJobPtr(this, SMARTPTR_DESTRUCT_NONE));
// Wait until finish
while (m_processorTaskNumber.getValue() > 0)
{
cOS::sleepMillisecond(10);
/*
if (m_processorTaskNumber.getValue() > 0)
{
traceHigh("IdtTableHooker: Dtor wait" << endl);
}
*/
}
}
void IdtTableHooker::run(const uint processorID,
const uint numberOfProcessors)
{
uint i;
// TODO! I think that this code is irrelevant.
// And the memory-manager should be optimized!
// cProcessorLock processorLock;
// cLock lock(processorLock);
// Lock the hooking lock
//cLock lock(m_hookLock);
if (m_jobReasonIsHook)
{
//traceHigh("[*] Hooking IDT for processor: " << (processorID + 1) << "\\" << numberOfProcessors << endl);
// This code is protected from exceptions...
for (i = m_startRange; i <= m_endRange; i++)
{
// Try to hook
XSTL_TRY
{
getEntry(i, processorID) =
HookIdtPtr(new HookIdt(i, m_tempCallbackClass));
} XSTL_CATCH_ALL
{
// Interrupt #I couldn't be hooked.
traceHigh("[!] IdtTableHooker: Cannot hook interrupt #" <<
HEXBYTE(i) << " for processor #" << processorID <<
endl);
}
}
} else
{
cString unhookMessage;
unhookMessage << "[*] Unhooking IDT for processor: " << (processorID + 1) << "\\" << numberOfProcessors << endl;
traceHigh(unhookMessage);
for (i = m_startRange; i <= m_endRange; i++)
{
getEntry(i, processorID) = HookIdtPtr();
}
}
--m_processorTaskNumber;
}
bool IdtTableHooker::isInterruptHooked(uint vector) const
{
bool ret = false;
for (uint i = 0; i < m_numberOfProcessors; i++)
{
bool isHooked = !getEntry(vector, i).isEmpty();
ret = ret || isHooked;
}
return ret;
}
HookIdtPtr& IdtTableHooker::getEntry(uint vector, uint processorID) const
{
uint position = (vector - m_startRange) + (processorID * m_tableSize);
return m_hooking[position];
}
| 32.855556 | 120 | 0.657761 | [
"vector"
] |
102b5399c2acad4bc4c83b4340ed1b3d986ed539 | 6,441 | cpp | C++ | CmdExample/SystemOutputParseResult.cpp | shaglund/CmdParser4Cpp | 08a7bc8960009add6e73f41477374ab4c7048086 | [
"MIT"
] | 1 | 2017-08-30T02:40:29.000Z | 2017-08-30T02:40:29.000Z | CmdExample/SystemOutputParseResult.cpp | shaglund/CmdParser4Cpp | 08a7bc8960009add6e73f41477374ab4c7048086 | [
"MIT"
] | 4 | 2016-02-15T07:19:44.000Z | 2019-09-05T08:09:11.000Z | CmdExample/SystemOutputParseResult.cpp | shaglund/CmdParser4Cpp | 08a7bc8960009add6e73f41477374ab4c7048086 | [
"MIT"
] | 1 | 2019-07-03T08:50:39.000Z | 2019-07-03T08:50:39.000Z | // Copyright (c) 2016 Per Malmberg
// Licensed under MIT, see LICENSE file.
#include <iostream>
#include <sstream>
#include "SystemOutputParseResult.h"
//////////////////////////////////////////////////////////////////////////
//
//
//////////////////////////////////////////////////////////////////////////
SystemOutputParseResult::SystemOutputParseResult()
: myLines()
{
}
//////////////////////////////////////////////////////////////////////////
//
//
//////////////////////////////////////////////////////////////////////////
SystemOutputParseResult::~SystemOutputParseResult()
{
}
//////////////////////////////////////////////////////////////////////////
//
//
//////////////////////////////////////////////////////////////////////////
std::string
SystemOutputParseResult::GetParseResult() const
{
std::string res;
for( auto& s : myLines ) {
res.append( s ).append( "\r\n" );
}
return res;
}
//////////////////////////////////////////////////////////////////////////
//
//
//////////////////////////////////////////////////////////////////////////
void
SystemOutputParseResult::UnknownArguments( const std::vector<std::string>& leftovers )
{
std::string line = "Unknown arguments:";
for( auto s : leftovers ) {
line.append( " " ).append( s );
}
myLines.push_back( line );
}
//////////////////////////////////////////////////////////////////////////
//
//
//////////////////////////////////////////////////////////////////////////
void
SystemOutputParseResult::NotEnoughParameters( const std::string& argument, int minParameterCount )
{
std::string line = "Not enough parameters, argument '";
line.append( argument ).append( "' requires " ).append( std::to_string( minParameterCount ) );
myLines.push_back( line );
}
//////////////////////////////////////////////////////////////////////////
//
//
//////////////////////////////////////////////////////////////////////////
void
SystemOutputParseResult::FailedToParseArgument( const std::string& argument )
{
std::string line = "Failed to parse argument '";
line.append( argument ).append( "'" );
myLines.push_back( line );
}
//////////////////////////////////////////////////////////////////////////
//
//
//////////////////////////////////////////////////////////////////////////
void
SystemOutputParseResult::ArgumentSpecifiedMultipleTimes( const std::string& argument )
{
std::string line = "The argument '";
line.append( argument );
line.append( "' is specified multiple times." );
myLines.push_back( line );
}
//////////////////////////////////////////////////////////////////////////
//
//
//////////////////////////////////////////////////////////////////////////
void
SystemOutputParseResult::MissingMandatoryArgument( const std::string& argument )
{
std::string line = "The mandatory argument '";
line.append( argument );
line.append( "' is missing" );
myLines.push_back( line );
}
//////////////////////////////////////////////////////////////////////////
//
//
//////////////////////////////////////////////////////////////////////////
void
SystemOutputParseResult::NoSuchArgumentDefined( const std::string& argument, const std::string& dependsOn )
{
std::stringstream line;
line << "Argument '" << argument << "' depends on '" << dependsOn << "', but no such argument is defined - contact the author of the application";
myLines.push_back( line.str() );
}
//////////////////////////////////////////////////////////////////////////
//
//
//////////////////////////////////////////////////////////////////////////
void
SystemOutputParseResult::MissingDependentArgument( const std::string& argument, const std::string& dependsOn )
{
std::stringstream line;
line << "Argument '" << argument << "' depends on '" << dependsOn << "', but the latter is missing";
myLines.push_back( line.str() );
}
//////////////////////////////////////////////////////////////////////////
//
//
//////////////////////////////////////////////////////////////////////////
void
SystemOutputParseResult::NoSuchMutuallyExclusiveArgumentDefined( const std::string& argument, const std::string& missing )
{
std::stringstream line;
line << "Argument '" << argument << "' is mutually exclusive to '" << missing << "', but no such argument is defined - contact the author of the application";
myLines.push_back( line.str() );
}
//////////////////////////////////////////////////////////////////////////
//
//
//////////////////////////////////////////////////////////////////////////
void
SystemOutputParseResult::ArgumentsAreMutuallyExclusive( const std::string& argument, const std::string& blocker )
{
std::stringstream line;
line << "Arguments '" << argument << "' and '" << blocker << "' are mutually exclusive.";
myLines.push_back( line.str() );
}
//////////////////////////////////////////////////////////////////////////
//
//
//////////////////////////////////////////////////////////////////////////
void SystemOutputParseResult::ArgumentMissingType( const std::string& argument )
{
std::stringstream line;
line << "Argument '" << argument << "' is missing type information. This is a programming error - contact the author of the application";
myLines.push_back( line.str() );
}
//////////////////////////////////////////////////////////////////////////
//
//
//////////////////////////////////////////////////////////////////////////
void SystemOutputParseResult::FailedToLoadConfiguration( const std::string& fileNameArgument )
{
std::stringstream line;
line << "Could not load the configuration specified by argument '" << fileNameArgument;
myLines.push_back( line.str() );
}
//////////////////////////////////////////////////////////////////////////
//
//
//////////////////////////////////////////////////////////////////////////
void SystemOutputParseResult::InvalidStringLength( const std::string& argument, int lower, int upper )
{
std::stringstream line;
line << "String length of argument '" << argument << "' is outside limits " << lower << " - " << upper;
myLines.push_back( line.str() );
}
//////////////////////////////////////////////////////////////////////////
//
//
//////////////////////////////////////////////////////////////////////////
void SystemOutputParseResult::InvalidParameterValue( const std::string& argument, int lower, int upper )
{
std::stringstream line;
line << "Parameter of argument '" << argument << "' is outside limits " << lower << " - " << upper;
myLines.push_back( line.str() );
}
| 32.862245 | 159 | 0.438286 | [
"vector"
] |
102c33ffba565012afb2ea58564ef50b6d160ca0 | 4,088 | cpp | C++ | hiro/extension/fixed-layout.cpp | 13824125580/higan | fbdd3f980b65412c362096579869ae76730e4118 | [
"Intel",
"ISC"
] | 10 | 2019-12-19T01:19:41.000Z | 2021-02-18T16:30:29.000Z | hiro/extension/fixed-layout.cpp | 13824125580/higan | fbdd3f980b65412c362096579869ae76730e4118 | [
"Intel",
"ISC"
] | null | null | null | hiro/extension/fixed-layout.cpp | 13824125580/higan | fbdd3f980b65412c362096579869ae76730e4118 | [
"Intel",
"ISC"
] | null | null | null | #if defined(Hiro_FixedLayout)
auto mFixedLayout::append(sSizable sizable, Geometry geometry) -> type& {
for(auto& cell : state.cells) {
if(cell->state.sizable == sizable) return *this;
}
FixedLayoutCell cell;
cell->setSizable(sizable);
cell->setGeometry(geometry);
cell->setParent(this, cellCount());
state.cells.append(cell);
return synchronize();
}
auto mFixedLayout::cell(uint position) const -> FixedLayoutCell {
return state.cells(position, {});
}
auto mFixedLayout::cell(sSizable sizable) const -> FixedLayoutCell {
for(auto& cell : state.cells) {
if(cell->state.sizable == sizable) return cell;
}
return {};
}
auto mFixedLayout::cellCount() const -> uint {
return state.cells.size();
}
auto mFixedLayout::destruct() -> void {
for(auto& cell : state.cells) cell->destruct();
return mSizable::destruct();
}
auto mFixedLayout::minimumSize() const -> Size {
float width = 0, height = 0;
for(auto& cell : state.cells) {
width = max(width, cell.sizable().minimumSize().width());
height = max(height, cell.sizable().minimumSize().height());
}
return {width, height};
}
auto mFixedLayout::remove(sSizable sizable) -> type& {
for(auto& cell : state.cells) {
if(cell->state.sizable == sizable) return remove(cell);
}
return *this;
}
auto mFixedLayout::remove(sFixedLayoutCell cell) -> type& {
if(cell->parent() != this) return *this;
auto offset = cell->offset();
cell->setParent();
state.cells.remove(offset);
for(uint n : range(offset, cellCount())) state.cells[n]->adjustOffset(-1);
return synchronize();
}
auto mFixedLayout::reset() -> type& {
while(state.cells) remove(state.cells.right());
return synchronize();
}
auto mFixedLayout::setEnabled(bool enabled) -> type& {
mSizable::setEnabled(enabled);
for(auto& cell : state.cells) cell.sizable().setEnabled(cell.sizable().enabled());
return *this;
}
auto mFixedLayout::setFont(const Font& font) -> type& {
mSizable::setFont(font);
for(auto& cell : state.cells) cell.sizable().setFont(cell.sizable().font());
return *this;
}
auto mFixedLayout::setParent(mObject* parent, int offset) -> type& {
for(auto& cell : reverse(state.cells)) cell->destruct();
mSizable::setParent(parent, offset);
for(auto& cell : state.cells) cell->setParent(this, cell->offset());
return *this;
}
auto mFixedLayout::setVisible(bool visible) -> type& {
mSizable::setVisible(visible);
for(auto& cell : state.cells) cell.sizable().setVisible(cell.sizable().visible());
return synchronize();
}
auto mFixedLayout::synchronize() -> type& {
setGeometry(geometry());
return *this;
}
//
auto mFixedLayoutCell::destruct() -> void {
if(auto& sizable = state.sizable) sizable->destruct();
mObject::destruct();
}
auto mFixedLayoutCell::geometry() const -> Geometry {
return state.geometry;
}
auto mFixedLayoutCell::setEnabled(bool enabled) -> type& {
mObject::setEnabled(enabled);
state.sizable->setEnabled(state.sizable->enabled());
return *this;
}
auto mFixedLayoutCell::setFont(const Font& font) -> type& {
mObject::setFont(font);
state.sizable->setFont(state.sizable->font());
return *this;
}
auto mFixedLayoutCell::setGeometry(Geometry geometry) -> type& {
state.geometry = geometry;
return synchronize();
}
auto mFixedLayoutCell::setParent(mObject* parent, int offset) -> type& {
state.sizable->destruct();
mObject::setParent(parent, offset);
state.sizable->setParent(this, 0);
return *this;
}
auto mFixedLayoutCell::setSizable(sSizable sizable) -> type& {
state.sizable = sizable;
return synchronize();
}
auto mFixedLayoutCell::setVisible(bool visible) -> type& {
mObject::setVisible(visible);
state.sizable->setVisible(state.sizable->visible());
return *this;
}
auto mFixedLayoutCell::sizable() const -> Sizable {
return state.sizable ? state.sizable : Sizable();
}
auto mFixedLayoutCell::synchronize() -> type& {
if(auto parent = this->parent()) {
if(auto fixedLayout = dynamic_cast<mFixedLayout*>(parent)) {
fixedLayout->synchronize();
}
}
return *this;
}
#endif
| 26.205128 | 84 | 0.689824 | [
"geometry"
] |
1030390a190858dd56753fd2b4b86c39c94c3271 | 514 | cpp | C++ | src/the-k-weakest-rows-in-a-matrix.cpp | Liuchang0812/leetcode | d71f87b0035e661d0009f4382b39c4787c355f89 | [
"MIT"
] | 9 | 2015-09-09T20:28:31.000Z | 2019-05-15T09:13:07.000Z | src/the-k-weakest-rows-in-a-matrix.cpp | liuchang0812/leetcode | d71f87b0035e661d0009f4382b39c4787c355f89 | [
"MIT"
] | 1 | 2015-02-25T13:10:09.000Z | 2015-02-25T13:10:09.000Z | src/the-k-weakest-rows-in-a-matrix.cpp | liuchang0812/leetcode | d71f87b0035e661d0009f4382b39c4787c355f89 | [
"MIT"
] | 1 | 2016-08-31T19:14:52.000Z | 2016-08-31T19:14:52.000Z | class Solution {
public:
vector<int> kWeakestRows(vector<vector<int>>& mat, int k) {
vector<pair<int,int>> sol2id;
for (int i=0;i<mat.size();++i) {
int tmp = 0;
for (int j=0;j<mat[i].size();++j)
if (mat[i][j] == 1) tmp++;
sol2id.push_back(make_pair(tmp, i));
}
sort(sol2id.begin(), sol2id.end());
vector<int> ans;
for (int i=0;i<k;++i)
ans.push_back(sol2id[i].second);
return ans;
}
};
| 28.555556 | 63 | 0.478599 | [
"vector"
] |
1033b93abf43e7e673284fd9be4f7f958c764811 | 684 | cpp | C++ | cpp_practice/vector_erase.cpp | williamfdevine/hackerrank | 80045f708d84feafd9af9094c02ce5b08ba43797 | [
"MIT"
] | null | null | null | cpp_practice/vector_erase.cpp | williamfdevine/hackerrank | 80045f708d84feafd9af9094c02ce5b08ba43797 | [
"MIT"
] | null | null | null | cpp_practice/vector_erase.cpp | williamfdevine/hackerrank | 80045f708d84feafd9af9094c02ce5b08ba43797 | [
"MIT"
] | null | null | null | /**
@file vector_erase.cpp
*/
#include <iostream>
#include <vector>
#include <stdint.h>
int main(void)
{
std::vector<uint32_t> vals;
uint32_t num_vals;
std::cin >> num_vals;
uint32_t curr_val;
for(int i = 0; i < num_vals; i++)
{
std::cin >> curr_val;
vals.push_back(curr_val);
}
uint32_t element;
uint32_t range_begin;
uint32_t range_end;
std::cin >> element >> range_begin >> range_end;
vals.erase(vals.begin() + element - 1);
vals.erase(vals.begin() + range_begin - 1, vals.begin() + range_end - 1);
std::cout << vals.size() << std::endl;
for(int i = 0; i < vals.size(); i++)
{
std::cout << vals.at(i) << " ";
}
std::cout << std::endl;
return 0;
} | 17.538462 | 74 | 0.622807 | [
"vector"
] |
1033cff5aa279090133f0be97872ad1a66a24de4 | 1,468 | hpp | C++ | core/runtime/binaryen/runtime_api/core_impl.hpp | iceseer/kagome | a405921659cc19e9fdb851e5f13f1e607fdf8af4 | [
"Apache-2.0"
] | null | null | null | core/runtime/binaryen/runtime_api/core_impl.hpp | iceseer/kagome | a405921659cc19e9fdb851e5f13f1e607fdf8af4 | [
"Apache-2.0"
] | null | null | null | core/runtime/binaryen/runtime_api/core_impl.hpp | iceseer/kagome | a405921659cc19e9fdb851e5f13f1e607fdf8af4 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright Soramitsu Co., Ltd. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef CORE_RUNTIME_BINARYEN_CORE_IMPL_HPP
#define CORE_RUNTIME_BINARYEN_CORE_IMPL_HPP
#include "runtime/binaryen/runtime_api/runtime_api.hpp"
#include "runtime/core.hpp"
#include "blockchain/block_header_repository.hpp"
#include "storage/changes_trie/changes_tracker.hpp"
namespace kagome::runtime::binaryen {
class CoreImpl : public RuntimeApi, public Core {
public:
explicit CoreImpl(
const std::shared_ptr<RuntimeManager> &runtime_manager,
std::shared_ptr<storage::changes_trie::ChangesTracker> changes_tracker,
std::shared_ptr<blockchain::BlockHeaderRepository> header_repo);
~CoreImpl() override = default;
outcome::result<primitives::Version> version(
const boost::optional<primitives::BlockHash> &block_hash) override;
outcome::result<void> execute_block(
const primitives::Block &block) override;
outcome::result<void> initialise_block(
const kagome::primitives::BlockHeader &header) override;
outcome::result<std::vector<primitives::AuthorityId>> authorities(
const primitives::BlockId &block_id) override;
private:
std::shared_ptr<storage::changes_trie::ChangesTracker> changes_tracker_;
std::shared_ptr<blockchain::BlockHeaderRepository> header_repo_;
};
} // namespace kagome::runtime::binaryen
#endif // CORE_RUNTIME_BINARYEN_CORE_IMPL_HPP
| 32.622222 | 79 | 0.752044 | [
"vector"
] |
10363f0bfc11c979a61af45968c5f44c952719bb | 1,417 | hpp | C++ | include/cb/scene.hpp | blitterfly/critterbits | fdfc696ac01c4ce95a1e96f0314f11eeccdde588 | [
"MIT"
] | 1 | 2017-11-25T20:35:55.000Z | 2017-11-25T20:35:55.000Z | include/cb/scene.hpp | taxes-dev/critterbits | fdfc696ac01c4ce95a1e96f0314f11eeccdde588 | [
"MIT"
] | null | null | null | include/cb/scene.hpp | taxes-dev/critterbits | fdfc696ac01c4ce95a1e96f0314f11eeccdde588 | [
"MIT"
] | null | null | null | #pragma once
#ifndef CBSCENE_HPP
#define CBSCENE_HPP
#include <memory>
#include <string>
#include <vector>
#include "sprite.hpp"
#include "tilemap.hpp"
#define CB_SCENE_PATH "scenes"
#define CB_FIRST_SCENE "startup"
#define CB_SCENE_EXT ".toml"
namespace Critterbits {
enum class SceneState { New, Active, Inactive, Unloaded };
class Scene {
public:
bool persistent{false};
std::string scene_name;
std::string map_path;
float map_scale{1.0f};
std::string script_path;
SceneState state{SceneState::New};
SpriteManager sprites;
Scene(){};
~Scene();
std::shared_ptr<Tilemap> GetTilemap() { return this->tilemap; };
bool HasTilemap() { return this->tilemap != nullptr; };
void NotifyLoaded();
void NotifyUnloaded(bool);
private:
std::shared_ptr<Tilemap> tilemap;
};
class SceneManager {
public:
std::shared_ptr<Scene> current_scene;
SceneManager(){};
~SceneManager();
bool IsCurrentSceneActive() {
return this->current_scene != nullptr && this->current_scene->state == SceneState::Active;
};
bool LoadScene(const std::string &);
std::string GetScenePath(const std::string &) const;
private:
std::string scene_path;
std::vector<std::shared_ptr<Scene>> loaded_scenes;
SceneManager(const SceneManager &) = delete;
SceneManager(SceneManager &&) = delete;
void UnloadCurrentScene();
};
}
#endif | 22.854839 | 98 | 0.685956 | [
"vector"
] |
10366cdba47a8dfeaa964bec728df916dd07f4c8 | 2,105 | cpp | C++ | code/core/rttbStructureSet.cpp | MIC-DKFZ/RTTB | 8b772501fd3fffcb67233a9307661b03dff72785 | [
"BSD-3-Clause"
] | 18 | 2018-04-19T12:57:32.000Z | 2022-03-12T17:43:02.000Z | code/core/rttbStructureSet.cpp | MIC-DKFZ/RTTB | 8b772501fd3fffcb67233a9307661b03dff72785 | [
"BSD-3-Clause"
] | null | null | null | code/core/rttbStructureSet.cpp | MIC-DKFZ/RTTB | 8b772501fd3fffcb67233a9307661b03dff72785 | [
"BSD-3-Clause"
] | 7 | 2018-06-24T21:09:56.000Z | 2021-09-09T09:30:49.000Z | // -----------------------------------------------------------------------
// RTToolbox - DKFZ radiotherapy quantitative evaluation library
//
// Copyright (c) German Cancer Research Center (DKFZ),
// Software development for Integrated Diagnostics and Therapy (SIDT).
// ALL RIGHTS RESERVED.
// See rttbCopyright.txt or
// http://www.dkfz.de/en/sidt/projects/rttb/copyright.html
//
// This software is distributed WITHOUT ANY WARRANTY; without even
// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE. See the above copyright notices for more information.
//
//------------------------------------------------------------------------
#include <iostream>
#include <sstream>
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <boost/uuid/uuid_io.hpp>
#include "rttbStructureSet.h"
#include "rttbInvalidParameterException.h"
namespace rttb
{
namespace core
{
StructureSet::StructureSet(const std::vector<Structure::Pointer>& aStructureVector,
IDType aPatientUID, IDType aUID)
{
_structureSetVector = aStructureVector;
_patientUID = aPatientUID;
_UID = aUID;
if (_UID == "")
{
boost::uuids::uuid id;
boost::uuids::random_generator generator;
id = generator();
std::stringstream ss;
ss << id;
_UID = ss.str();
}
}
Structure::Pointer StructureSet::getStructure(size_t aStructureNo) const
{
auto size = this->getNumberOfStructures();
if (aStructureNo >= size)
{
std::stringstream sstr;
sstr << "aStructureNo must be between 0 and " << size;
throw InvalidParameterException(sstr.str());
}
return _structureSetVector.at(aStructureNo);
}
StructureSet::NumberOfStructuresType StructureSet::getNumberOfStructures() const
{
return _structureSetVector.size();
}
IDType StructureSet::getUID() const
{
return _UID;
}
IDType StructureSet::getPatientUID() const
{
return _patientUID;
}
}//end namespace core
}//end namespace rttb
| 26.64557 | 86 | 0.630404 | [
"vector"
] |
1037bf0a4bbffdd75766e467722d1bfac3fe3196 | 46,505 | cpp | C++ | src/model/LifeCycleCostParameters.cpp | mehrdad-shokri/OpenStudio | 1773b54ce1cb660818ac0114dd7eefae6639ca36 | [
"blessing"
] | null | null | null | src/model/LifeCycleCostParameters.cpp | mehrdad-shokri/OpenStudio | 1773b54ce1cb660818ac0114dd7eefae6639ca36 | [
"blessing"
] | null | null | null | src/model/LifeCycleCostParameters.cpp | mehrdad-shokri/OpenStudio | 1773b54ce1cb660818ac0114dd7eefae6639ca36 | [
"blessing"
] | null | null | null | /***********************************************************************************************************************
* OpenStudio(R), Copyright (c) 2008-2020, Alliance for Sustainable Energy, LLC, and other 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:
*
* (1) Redistributions of source code must retain the above copyright notice, this list of conditions and the following
* disclaimer.
*
* (2) Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided with the distribution.
*
* (3) Neither the name of the copyright holder nor the names of any contributors may be used to endorse or promote products
* derived from this software without specific prior written permission from the respective party.
*
* (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative works
* may not use the "OpenStudio" trademark, "OS", "os", or any other confusingly similar designation without specific prior
* written permission from Alliance for Sustainable Energy, LLC.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) AND ANY 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(S), ANY CONTRIBUTORS, THE UNITED STATES GOVERNMENT, OR THE UNITED
* STATES DEPARTMENT OF ENERGY, NOR ANY OF THEIR EMPLOYEES, 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 "LifeCycleCostParameters.hpp"
#include "LifeCycleCostParameters_Impl.hpp"
#include "Model_Impl.hpp"
#include <utilities/idd/OS_LifeCycleCost_Parameters_FieldEnums.hxx>
#include <utilities/idd/IddEnums.hxx>
#include <utilities/idd/IddFactory.hxx>
#include "../utilities/time/Date.hpp"
#include "../utilities/core/Assert.hpp"
#include <boost/algorithm/string.hpp>
namespace openstudio {
namespace model {
namespace detail {
LifeCycleCostParameters_Impl::LifeCycleCostParameters_Impl(const IdfObject& idfObject, Model_Impl* model, bool keepHandle)
: ParentObject_Impl(idfObject, model, keepHandle)
{
OS_ASSERT(idfObject.iddObject().type() == LifeCycleCostParameters::iddObjectType());
}
LifeCycleCostParameters_Impl::LifeCycleCostParameters_Impl(const openstudio::detail::WorkspaceObject_Impl& other,
Model_Impl* model,
bool keepHandle)
: ParentObject_Impl(other,model,keepHandle)
{
OS_ASSERT(other.iddObject().type() == LifeCycleCostParameters::iddObjectType());
}
LifeCycleCostParameters_Impl::LifeCycleCostParameters_Impl(const LifeCycleCostParameters_Impl& other,Model_Impl* model,bool keepHandle)
: ParentObject_Impl(other,model,keepHandle)
{
}
// return the parent object in the hierarchy
boost::optional<ParentObject> LifeCycleCostParameters_Impl::parent() const
{
return boost::optional<ParentObject>();
}
// return any children objects in the hierarchy
std::vector<ModelObject> LifeCycleCostParameters_Impl::children() const
{
std::vector<ModelObject> result;
return result;
}
std::vector<IddObjectType> LifeCycleCostParameters_Impl::allowableChildTypes() const {
IddObjectTypeVector result;
return result;
}
// Get all output variable names that could be associated with this object.
const std::vector<std::string>& LifeCycleCostParameters_Impl::outputVariableNames() const
{
static const std::vector<std::string> result;
// Not appropriate: no specific variables available
return result;
}
std::string LifeCycleCostParameters_Impl::analysisType() const{
OptionalString os = getString(OS_LifeCycleCost_ParametersFields::AnalysisType,true);
OS_ASSERT(os); OS_ASSERT(!os->empty());
return *os;
}
bool LifeCycleCostParameters_Impl::isAnalysisTypeDefaulted() const{
return isEmpty(OS_LifeCycleCost_ParametersFields::AnalysisType);
}
bool LifeCycleCostParameters_Impl::isFEMPAnalysis() const{
return ("FEMP" == this->analysisType());
}
std::string LifeCycleCostParameters_Impl::discountingConvention() const {
OptionalString os = getString(OS_LifeCycleCost_ParametersFields::DiscountingConvention,true);
OS_ASSERT(os); OS_ASSERT(!os->empty());
return *os;
}
bool LifeCycleCostParameters_Impl::isDiscountingConventionDefaulted() const{
return isEmpty(OS_LifeCycleCost_ParametersFields::DiscountingConvention);
}
std::string LifeCycleCostParameters_Impl::inflationApproach() const {
OptionalString os = getString(OS_LifeCycleCost_ParametersFields::InflationApproach,true);
OS_ASSERT(os); OS_ASSERT(!os->empty());
return *os;
}
bool LifeCycleCostParameters_Impl::isInflationApproachDefaulted() const{
return isEmpty(OS_LifeCycleCost_ParametersFields::InflationApproach);
}
bool LifeCycleCostParameters_Impl::isConstantDollarAnalysis() const{
return ("ConstantDollar" == this->inflationApproach());
}
boost::optional<double> LifeCycleCostParameters_Impl::realDiscountRate() const {
boost::optional<double> result;
if (this->isConstantDollarAnalysis()){
result = getDouble(OS_LifeCycleCost_ParametersFields::RealDiscountRate,true);
if (!result){
// default is not in the IDD, act like it is here
result = LifeCycleCostParameters::fempRealDiscountRate();
}
}
return result;
}
boost::optional<double> LifeCycleCostParameters_Impl::nominalDiscountRate() const {
boost::optional<double> result;
if (!this->isConstantDollarAnalysis()){
result = getDouble(OS_LifeCycleCost_ParametersFields::NominalDiscountRate,true);
if (!result){
// default is not in the IDD, act like it is here
result = LifeCycleCostParameters::fempNominalDiscountRate();
}
}
return result;
}
boost::optional<double> LifeCycleCostParameters_Impl::inflation() const {
boost::optional<double> result;
if (!this->isConstantDollarAnalysis()){
result = getDouble(OS_LifeCycleCost_ParametersFields::Inflation,true);
if (!result){
// default is not in the IDD, act like it is here
result = LifeCycleCostParameters::fempInflation();
}
}
return result;
}
MonthOfYear LifeCycleCostParameters_Impl::baseDateMonth() const {
OptionalString os = getString(OS_LifeCycleCost_ParametersFields::BaseDateMonth,true);
OS_ASSERT(os); OS_ASSERT(!os->empty());
return MonthOfYear(*os);
}
bool LifeCycleCostParameters_Impl::isBaseDateMonthDefaulted() const{
return isEmpty(OS_LifeCycleCost_ParametersFields::BaseDateMonth);
}
int LifeCycleCostParameters_Impl::baseDateYear() const {
boost::optional<int> result = getInt(OS_LifeCycleCost_ParametersFields::BaseDateYear,true);
if (!result){
result = LifeCycleCostParameters::nistYear();
}
return *result;
}
bool LifeCycleCostParameters_Impl::isBaseDateYearDefaulted() const{
return isEmpty(OS_LifeCycleCost_ParametersFields::BaseDateYear);
}
MonthOfYear LifeCycleCostParameters_Impl::serviceDateMonth() const {
OptionalString os = getString(OS_LifeCycleCost_ParametersFields::ServiceDateMonth,true);
OS_ASSERT(os); OS_ASSERT(!os->empty());
return MonthOfYear(*os);
}
bool LifeCycleCostParameters_Impl::isServiceDateMonthDefaulted() const{
return isEmpty(OS_LifeCycleCost_ParametersFields::BaseDateMonth);
}
int LifeCycleCostParameters_Impl::serviceDateYear() const {
boost::optional<int> result = getInt(OS_LifeCycleCost_ParametersFields::ServiceDateYear,true);
if (!result){
result = LifeCycleCostParameters::nistYear();
}
return *result;
}
bool LifeCycleCostParameters_Impl::isServiceDateYearDefaulted() const{
return isEmpty(OS_LifeCycleCost_ParametersFields::ServiceDateYear);
}
int LifeCycleCostParameters_Impl::lengthOfStudyPeriodInYears() const {
OptionalInt result = getInt(OS_LifeCycleCost_ParametersFields::LengthofStudyPeriodinYears,true);
OS_ASSERT(result);
return *result;
}
bool LifeCycleCostParameters_Impl::isLengthOfStudyPeriodInYearsDefaulted() const{
return isEmpty(OS_LifeCycleCost_ParametersFields::LengthofStudyPeriodinYears);
}
boost::optional<double> LifeCycleCostParameters_Impl::taxRate() const {
return getDouble(OS_LifeCycleCost_ParametersFields::TaxRate,true);
}
std::string LifeCycleCostParameters_Impl::depreciationMethod() const {
OptionalString os = getString(OS_LifeCycleCost_ParametersFields::DepreciationMethod,true);
OS_ASSERT(os); OS_ASSERT(!os->empty());
return *os;
}
bool LifeCycleCostParameters_Impl::isDepreciationMethodDefaulted() const{
return isEmpty(OS_LifeCycleCost_ParametersFields::DepreciationMethod);
}
bool LifeCycleCostParameters_Impl::useNISTFuelEscalationRates() const {
OptionalString os = getString(OS_LifeCycleCost_ParametersFields::UseNISTFuelEscalationRates, true);
OS_ASSERT(os); OS_ASSERT(!os->empty());
return ("Yes" == *os);
}
bool LifeCycleCostParameters_Impl::isUseNISTFuelEscalationRatesDefaulted() const{
return isEmpty(OS_LifeCycleCost_ParametersFields::UseNISTFuelEscalationRates);
}
boost::optional<std::string> LifeCycleCostParameters_Impl::nistRegion() const
{
boost::optional<std::string> result;
if (this->useNISTFuelEscalationRates()){
result = getString(OS_LifeCycleCost_ParametersFields::NISTRegion, true);
}
return result;
}
std::vector<std::string> LifeCycleCostParameters_Impl::validNistRegionValues() const
{
return getIddKeyNames(IddFactory::instance().getObject(iddObjectType()).get(),
OS_LifeCycleCost_ParametersFields::NISTRegion);
}
bool LifeCycleCostParameters_Impl::isNISTRegionDefaulted() const{
return isEmpty(OS_LifeCycleCost_ParametersFields::NISTRegion);
}
boost::optional<std::string> LifeCycleCostParameters_Impl::nistSector() const
{
boost::optional<std::string> result;
if (this->useNISTFuelEscalationRates()){
result = getString(OS_LifeCycleCost_ParametersFields::NISTSector, true);
}
return result;
}
std::vector<std::string> LifeCycleCostParameters_Impl::validNistSectorValues() const
{
return getIddKeyNames(IddFactory::instance().getObject(iddObjectType()).get(),
OS_LifeCycleCost_ParametersFields::NISTSector);
}
bool LifeCycleCostParameters_Impl::isNISTSectorDefaulted() const{
return isEmpty(OS_LifeCycleCost_ParametersFields::NISTSector);
}
boost::optional<double> LifeCycleCostParameters_Impl::electricityInflation() const
{
boost::optional<double> result;
if (!this->useNISTFuelEscalationRates()){
result = getDouble(OS_LifeCycleCost_ParametersFields::ElectricityInflation, true);
// DLM: provide "equivalent" FEMP fuel escalation rates based on nist data and analysis length if no result?
}
return result;
}
boost::optional<double> LifeCycleCostParameters_Impl::naturalGasInflation() const
{
boost::optional<double> result;
if (!this->useNISTFuelEscalationRates()){
result = getDouble(OS_LifeCycleCost_ParametersFields::NaturalGasInflation, true);
// DLM: provide "equivalent" FEMP fuel escalation rates based on nist data and analysis length if no result?
}
return result;
}
boost::optional<double> LifeCycleCostParameters_Impl::steamInflation() const
{
boost::optional<double> result;
if (!this->useNISTFuelEscalationRates()){
result = getDouble(OS_LifeCycleCost_ParametersFields::SteamInflation, true);
// DLM: provide "equivalent" FEMP fuel escalation rates based on nist data and analysis length if no result?
}
return result;
}
boost::optional<double> LifeCycleCostParameters_Impl::gasolineInflation() const
{
boost::optional<double> result;
if (!this->useNISTFuelEscalationRates()){
result = getDouble(OS_LifeCycleCost_ParametersFields::GasolineInflation, true);
// DLM: provide "equivalent" FEMP fuel escalation rates based on nist data and analysis length if no result?
}
return result;
}
boost::optional<double> LifeCycleCostParameters_Impl::dieselInflation() const
{
boost::optional<double> result;
if (!this->useNISTFuelEscalationRates()){
result = getDouble(OS_LifeCycleCost_ParametersFields::DieselInflation, true);
// DLM: provide "equivalent" FEMP fuel escalation rates based on nist data and analysis length if no result?
}
return result;
}
boost::optional<double> LifeCycleCostParameters_Impl::coalInflation() const
{
boost::optional<double> result;
if (!this->useNISTFuelEscalationRates()){
result = getDouble(OS_LifeCycleCost_ParametersFields::CoalInflation, true);
// DLM: provide "equivalent" FEMP fuel escalation rates based on nist data and analysis length if no result?
}
return result;
}
boost::optional<double> LifeCycleCostParameters_Impl::fuelOil1Inflation() const
{
boost::optional<double> result;
if (!this->useNISTFuelEscalationRates()){
result = getDouble(OS_LifeCycleCost_ParametersFields::FuelOil1Inflation, true);
// DLM: provide "equivalent" FEMP fuel escalation rates based on nist data and analysis length if no result?
}
return result;
}
boost::optional<double> LifeCycleCostParameters_Impl::fuelOil2Inflation() const
{
boost::optional<double> result;
if (!this->useNISTFuelEscalationRates()){
result = getDouble(OS_LifeCycleCost_ParametersFields::FuelOil2Inflation, true);
// DLM: provide "equivalent" FEMP fuel escalation rates based on nist data and analysis length if no result?
}
return result;
}
boost::optional<double> LifeCycleCostParameters_Impl::propaneInflation() const
{
boost::optional<double> result;
if (!this->useNISTFuelEscalationRates()){
result = getDouble(OS_LifeCycleCost_ParametersFields::PropaneInflation, true);
// DLM: provide "equivalent" FEMP fuel escalation rates based on nist data and analysis length if no result?
}
return result;
}
boost::optional<double> LifeCycleCostParameters_Impl::waterInflation() const
{
boost::optional<double> result;
if (!this->useNISTFuelEscalationRates()){
result = getDouble(OS_LifeCycleCost_ParametersFields::WaterInflation, true);
// DLM: provide "equivalent" FEMP fuel escalation rates based on nist data and analysis length if no result?
}
return result;
}
// set the parent, child may have to call methods on the parent
bool LifeCycleCostParameters_Impl::setParent(ParentObject& newParent) {
return false;
}
bool LifeCycleCostParameters_Impl::setAnalysisType(const std::string& analysisType)
{
bool changed = (this->analysisType() != analysisType);
bool result = setString(OS_LifeCycleCost_ParametersFields::AnalysisType, analysisType, false);
if (result && changed){
if (isFEMPAnalysis()){
if (isConstantDollarAnalysis()){
// DLM: this call has logic that prevents it from working if isFEMPAnalysis
// DLM: don't emit change signals until end
//setRealDiscountRate(LifeCycleCostParameters::fempRealDiscountRate());
setDouble(OS_LifeCycleCost_ParametersFields::RealDiscountRate,LifeCycleCostParameters::fempRealDiscountRate(), false);
setString(OS_LifeCycleCost_ParametersFields::NominalDiscountRate, "", false);
setString(OS_LifeCycleCost_ParametersFields::Inflation, "", false);
}else{
// DLM: this call has logic that prevents it from working if isFEMPAnalysis
// DLM: don't emit change signals until end
//setNominalDiscountRate(LifeCycleCostParameters::fempNominalDiscountRate());
//setInflation(LifeCycleCostParameters::fempInflation());
setString(OS_LifeCycleCost_ParametersFields::RealDiscountRate, "", false);
setDouble(OS_LifeCycleCost_ParametersFields::NominalDiscountRate, LifeCycleCostParameters::fempNominalDiscountRate(), false);
setDouble(OS_LifeCycleCost_ParametersFields::Inflation, LifeCycleCostParameters::fempInflation(), false);
}
if (lengthOfStudyPeriodInYears() > 25){
setLengthOfStudyPeriodInYears(25);
}
}
}
emitChangeSignals();
return result;
}
void LifeCycleCostParameters_Impl::resetAnalysisType()
{
bool test = setAnalysisType("FEMP");
OS_ASSERT(test);
test = setString(OS_LifeCycleCost_ParametersFields::AnalysisType, "");
OS_ASSERT(test);
}
bool LifeCycleCostParameters_Impl::setDiscountingConvention(const std::string& discountingConvention)
{
return setString(OS_LifeCycleCost_ParametersFields::DiscountingConvention,discountingConvention);
}
void LifeCycleCostParameters_Impl::resetDiscountingConvention()
{
bool test = setString(OS_LifeCycleCost_ParametersFields::DiscountingConvention,"");
OS_ASSERT(test);
}
bool LifeCycleCostParameters_Impl::setInflationApproach(const std::string& inflationApproach)
{
bool changed = (this->inflationApproach() != inflationApproach);
bool result = setString(OS_LifeCycleCost_ParametersFields::InflationApproach, inflationApproach);
if (result && changed){
if (isConstantDollarAnalysis()){
setRealDiscountRate(LifeCycleCostParameters::fempRealDiscountRate());
setString(OS_LifeCycleCost_ParametersFields::NominalDiscountRate, "");
setString(OS_LifeCycleCost_ParametersFields::Inflation, "");
}else{
setString(OS_LifeCycleCost_ParametersFields::RealDiscountRate, "");
setNominalDiscountRate(LifeCycleCostParameters::fempNominalDiscountRate());
setInflation(LifeCycleCostParameters::fempInflation());
}
}
return result;
}
void LifeCycleCostParameters_Impl::resetInflationApproach()
{
bool test = setAnalysisType("ConstantDollar");
OS_ASSERT(test);
test = setString(OS_LifeCycleCost_ParametersFields::AnalysisType, "");
OS_ASSERT(test);
}
bool LifeCycleCostParameters_Impl::setRealDiscountRate(double realDiscountRate)
{
bool result = false;
if (isConstantDollarAnalysis()){
if (!isFEMPAnalysis()){
result = setDouble(OS_LifeCycleCost_ParametersFields::RealDiscountRate,realDiscountRate);
}
}
return result;
}
bool LifeCycleCostParameters_Impl::setNominalDiscountRate(double nominalDiscountRate)
{
bool result = false;
if (!isConstantDollarAnalysis()){
if (!isFEMPAnalysis()){
result = setDouble(OS_LifeCycleCost_ParametersFields::NominalDiscountRate,nominalDiscountRate);
}
}
return result;
}
bool LifeCycleCostParameters_Impl::setInflation(double inflation)
{
bool result = false;
if (!isConstantDollarAnalysis()){
if (!isFEMPAnalysis()){
result = setDouble(OS_LifeCycleCost_ParametersFields::Inflation,inflation);
}
}
return result;
}
bool LifeCycleCostParameters_Impl::setBaseDateMonth(const MonthOfYear& baseDateMonth)
{
return setString(OS_LifeCycleCost_ParametersFields::BaseDateMonth,baseDateMonth.valueDescription());
}
void LifeCycleCostParameters_Impl::resetBaseDateMonth()
{
bool test = setString(OS_LifeCycleCost_ParametersFields::BaseDateMonth,"");
OS_ASSERT(test);
}
bool LifeCycleCostParameters_Impl::setBaseDateYear(int baseDateYear)
{
return setInt(OS_LifeCycleCost_ParametersFields::BaseDateYear,baseDateYear);
}
void LifeCycleCostParameters_Impl::resetBaseDateYear()
{
bool test = setString(OS_LifeCycleCost_ParametersFields::BaseDateYear,"");
OS_ASSERT(test);
}
bool LifeCycleCostParameters_Impl::setServiceDateMonth(const MonthOfYear& serviceDateMonth)
{
return setString(OS_LifeCycleCost_ParametersFields::ServiceDateMonth,serviceDateMonth.valueDescription());
}
void LifeCycleCostParameters_Impl::resetServiceDateMonth()
{
bool test = setString(OS_LifeCycleCost_ParametersFields::ServiceDateMonth,"");
OS_ASSERT(test);
}
bool LifeCycleCostParameters_Impl::setServiceDateYear(int serviceDateYear)
{
return setInt(OS_LifeCycleCost_ParametersFields::ServiceDateYear,serviceDateYear);
}
void LifeCycleCostParameters_Impl::resetServiceDateYear()
{
bool test = setString(OS_LifeCycleCost_ParametersFields::ServiceDateYear,"");
OS_ASSERT(test);
}
bool LifeCycleCostParameters_Impl::setLengthOfStudyPeriodInYears(int lengthOfStudyPeriodInYears)
{
bool result = false;
if (isFEMPAnalysis()){
if (lengthOfStudyPeriodInYears <= 25){
result = setInt(OS_LifeCycleCost_ParametersFields::LengthofStudyPeriodinYears,lengthOfStudyPeriodInYears);
}
}else if (useNISTFuelEscalationRates()){
if (lengthOfStudyPeriodInYears <= 30){
result = setInt(OS_LifeCycleCost_ParametersFields::LengthofStudyPeriodinYears,lengthOfStudyPeriodInYears);
}
}else{
result = setInt(OS_LifeCycleCost_ParametersFields::LengthofStudyPeriodinYears,lengthOfStudyPeriodInYears);
}
return result;
}
void LifeCycleCostParameters_Impl::resetLengthOfStudyPeriodInYears()
{
bool test = setString(OS_LifeCycleCost_ParametersFields::LengthofStudyPeriodinYears,"");
OS_ASSERT(test);
}
bool LifeCycleCostParameters_Impl::setTaxRate(double TaxRate)
{
return setDouble(OS_LifeCycleCost_ParametersFields::TaxRate,TaxRate);
}
void LifeCycleCostParameters_Impl::resetTaxRate()
{
bool test = setString(OS_LifeCycleCost_ParametersFields::TaxRate,"");
OS_ASSERT(test);
}
bool LifeCycleCostParameters_Impl::setDepreciationMethod(const std::string& depreciationMethod)
{
return setString(OS_LifeCycleCost_ParametersFields::DepreciationMethod,depreciationMethod);
}
void LifeCycleCostParameters_Impl::resetDepreciationMethod()
{
bool test = setString(OS_LifeCycleCost_ParametersFields::DepreciationMethod,"");
OS_ASSERT(test);
}
bool LifeCycleCostParameters_Impl::setUseNISTFuelEscalationRates(bool useNISTFuelEscalationRates)
{
bool changed = (useNISTFuelEscalationRates != this->useNISTFuelEscalationRates());
bool result = false;
if (useNISTFuelEscalationRates){
result = setString(OS_LifeCycleCost_ParametersFields::UseNISTFuelEscalationRates,"Yes");
OS_ASSERT(result);
if (lengthOfStudyPeriodInYears() > 30){
setLengthOfStudyPeriodInYears(30);
}
}else{
result = setString(OS_LifeCycleCost_ParametersFields::UseNISTFuelEscalationRates,"No");
OS_ASSERT(result);
}
// DLM: provide "equivalent" FEMP fuel escalation rates based on nist data and analysis length?
if (changed){
result = setString(OS_LifeCycleCost_ParametersFields::NISTRegion,"");
OS_ASSERT(result);
result = setString(OS_LifeCycleCost_ParametersFields::NISTSector,"");
OS_ASSERT(result);
result = setString(OS_LifeCycleCost_ParametersFields::ElectricityInflation,"");
OS_ASSERT(result);
result = setString(OS_LifeCycleCost_ParametersFields::NaturalGasInflation,"");
OS_ASSERT(result);
result = setString(OS_LifeCycleCost_ParametersFields::SteamInflation,"");
OS_ASSERT(result);
result = setString(OS_LifeCycleCost_ParametersFields::GasolineInflation,"");
OS_ASSERT(result);
result = setString(OS_LifeCycleCost_ParametersFields::DieselInflation,"");
OS_ASSERT(result);
result = setString(OS_LifeCycleCost_ParametersFields::CoalInflation,"");
OS_ASSERT(result);
result = setString(OS_LifeCycleCost_ParametersFields::FuelOil1Inflation,"");
OS_ASSERT(result);
result = setString(OS_LifeCycleCost_ParametersFields::FuelOil2Inflation,"");
OS_ASSERT(result);
result = setString(OS_LifeCycleCost_ParametersFields::PropaneInflation,"");
OS_ASSERT(result);
result = setString(OS_LifeCycleCost_ParametersFields::WaterInflation,"");
OS_ASSERT(result);
}
return result;
}
void LifeCycleCostParameters_Impl::resetUseNISTFuelEscalationRates()
{
bool test = setString(OS_LifeCycleCost_ParametersFields::UseNISTFuelEscalationRates,"");
OS_ASSERT(test);
}
bool LifeCycleCostParameters_Impl::setNISTRegion(const std::string& nistRegion)
{
bool result = false;
if (useNISTFuelEscalationRates()){
result = setString(OS_LifeCycleCost_ParametersFields::NISTRegion,nistRegion);
}
return result;
}
void LifeCycleCostParameters_Impl::resetNISTRegion()
{
bool test = setString(OS_LifeCycleCost_ParametersFields::NISTRegion,"");
OS_ASSERT(test);
}
bool LifeCycleCostParameters_Impl::setNISTSector(const std::string& nistSector)
{
bool result = false;
if (useNISTFuelEscalationRates()){
result = setString(OS_LifeCycleCost_ParametersFields::NISTSector,nistSector);
}
return result;
}
void LifeCycleCostParameters_Impl::resetNISTSector()
{
bool test = setString(OS_LifeCycleCost_ParametersFields::NISTSector,"");
OS_ASSERT(test);
}
bool LifeCycleCostParameters_Impl::setElectricityInflation(double electricityInflation)
{
bool result = false;
if (!useNISTFuelEscalationRates()){
result = setDouble(OS_LifeCycleCost_ParametersFields::ElectricityInflation,electricityInflation);
}
return result;
}
void LifeCycleCostParameters_Impl::resetElectricityInflation()
{
bool test = setString(OS_LifeCycleCost_ParametersFields::ElectricityInflation,"");
OS_ASSERT(test);
}
bool LifeCycleCostParameters_Impl::setNaturalGasInflation(double naturalGasInflation)
{
bool result = false;
if (!useNISTFuelEscalationRates()){
result = setDouble(OS_LifeCycleCost_ParametersFields::NaturalGasInflation,naturalGasInflation);
}
return result;
}
void LifeCycleCostParameters_Impl::resetNaturalGasInflation()
{
bool test = setString(OS_LifeCycleCost_ParametersFields::NaturalGasInflation,"");
OS_ASSERT(test);
}
bool LifeCycleCostParameters_Impl::setSteamInflation(double steamInflation)
{
bool result = false;
if (!useNISTFuelEscalationRates()){
result = setDouble(OS_LifeCycleCost_ParametersFields::SteamInflation,steamInflation);
}
return result;
}
void LifeCycleCostParameters_Impl::resetSteamInflation()
{
bool test = setString(OS_LifeCycleCost_ParametersFields::SteamInflation,"");
OS_ASSERT(test);
}
bool LifeCycleCostParameters_Impl::setGasolineInflation(double gasolineInflation)
{
bool result = false;
if (!useNISTFuelEscalationRates()){
result = setDouble(OS_LifeCycleCost_ParametersFields::GasolineInflation,gasolineInflation);
}
return result;
}
void LifeCycleCostParameters_Impl::resetGasolineInflation()
{
bool test = setString(OS_LifeCycleCost_ParametersFields::GasolineInflation,"");
OS_ASSERT(test);
}
bool LifeCycleCostParameters_Impl::setDieselInflation(double dieselInflation)
{
bool result = false;
if (!useNISTFuelEscalationRates()){
result = setDouble(OS_LifeCycleCost_ParametersFields::DieselInflation,dieselInflation);
}
return result;
}
void LifeCycleCostParameters_Impl::resetDieselInflation()
{
bool test = setString(OS_LifeCycleCost_ParametersFields::DieselInflation,"");
OS_ASSERT(test);
}
bool LifeCycleCostParameters_Impl::setCoalInflation(double coalInflation)
{
bool result = false;
if (!useNISTFuelEscalationRates()){
result = setDouble(OS_LifeCycleCost_ParametersFields::CoalInflation,coalInflation);
}
return result;
}
void LifeCycleCostParameters_Impl::resetCoalInflation()
{
bool test = setString(OS_LifeCycleCost_ParametersFields::CoalInflation,"");
OS_ASSERT(test);
}
bool LifeCycleCostParameters_Impl::setFuelOil1Inflation(double fuelOil1Inflation)
{
bool result = false;
if (!useNISTFuelEscalationRates()){
result = setDouble(OS_LifeCycleCost_ParametersFields::FuelOil1Inflation,fuelOil1Inflation);
}
return result;
}
void LifeCycleCostParameters_Impl::resetFuelOil1Inflation()
{
bool test = setString(OS_LifeCycleCost_ParametersFields::FuelOil1Inflation,"");
OS_ASSERT(test);
}
bool LifeCycleCostParameters_Impl::setFuelOil2Inflation(double fuelOil2Inflation)
{
bool result = false;
if (!useNISTFuelEscalationRates()){
result = setDouble(OS_LifeCycleCost_ParametersFields::FuelOil2Inflation,fuelOil2Inflation);
}
return result;
}
void LifeCycleCostParameters_Impl::resetFuelOil2Inflation()
{
bool test = setString(OS_LifeCycleCost_ParametersFields::FuelOil2Inflation,"");
OS_ASSERT(test);
}
bool LifeCycleCostParameters_Impl::setPropaneInflation(double propaneInflation)
{
bool result = false;
if (!useNISTFuelEscalationRates()){
result = setDouble(OS_LifeCycleCost_ParametersFields::PropaneInflation,propaneInflation);
}
return result;
}
void LifeCycleCostParameters_Impl::resetPropaneInflation()
{
bool test = setString(OS_LifeCycleCost_ParametersFields::PropaneInflation,"");
OS_ASSERT(test);
}
bool LifeCycleCostParameters_Impl::setWaterInflation(double waterInflation)
{
bool result = false;
if (!useNISTFuelEscalationRates()){
result = setDouble(OS_LifeCycleCost_ParametersFields::WaterInflation,waterInflation);
}
return result;
}
void LifeCycleCostParameters_Impl::resetWaterInflation()
{
bool test = setString(OS_LifeCycleCost_ParametersFields::WaterInflation,"");
OS_ASSERT(test);
}
} // detail
/// constructor
LifeCycleCostParameters::LifeCycleCostParameters(const Model& model)
: ParentObject(LifeCycleCostParameters::iddObjectType(),model)
{
OS_ASSERT(getImpl<detail::LifeCycleCostParameters_Impl>());
}
// constructor
LifeCycleCostParameters::LifeCycleCostParameters(std::shared_ptr<detail::LifeCycleCostParameters_Impl> impl)
: ParentObject(std::move(impl))
{}
int LifeCycleCostParameters::nistYear()
{
return 2011;
}
double LifeCycleCostParameters::fempRealDiscountRate()
{
return 0.03;
}
double LifeCycleCostParameters::fempNominalDiscountRate()
{
return 0.035;
}
double LifeCycleCostParameters::fempInflation()
{
return 0.005;
}
std::string LifeCycleCostParameters::analysisType() const{
return getImpl<detail::LifeCycleCostParameters_Impl>()->analysisType();
}
bool LifeCycleCostParameters::isAnalysisTypeDefaulted() const{
return getImpl<detail::LifeCycleCostParameters_Impl>()->isAnalysisTypeDefaulted();
}
bool LifeCycleCostParameters::isFEMPAnalysis() const{
return getImpl<detail::LifeCycleCostParameters_Impl>()->isFEMPAnalysis();
}
std::string LifeCycleCostParameters::discountingConvention() const{
return getImpl<detail::LifeCycleCostParameters_Impl>()->discountingConvention();
}
bool LifeCycleCostParameters::isDiscountingConventionDefaulted() const{
return getImpl<detail::LifeCycleCostParameters_Impl>()->isDiscountingConventionDefaulted();
}
std::string LifeCycleCostParameters::inflationApproach() const {
return getImpl<detail::LifeCycleCostParameters_Impl>()->inflationApproach();
}
bool LifeCycleCostParameters::isInflationApproachDefaulted() const {
return getImpl<detail::LifeCycleCostParameters_Impl>()->isInflationApproachDefaulted();
}
bool LifeCycleCostParameters::isConstantDollarAnalysis() const {
return getImpl<detail::LifeCycleCostParameters_Impl>()->isConstantDollarAnalysis();
}
boost::optional<double> LifeCycleCostParameters::realDiscountRate() const {
return getImpl<detail::LifeCycleCostParameters_Impl>()->realDiscountRate();
}
boost::optional<double> LifeCycleCostParameters::nominalDiscountRate() const {
return getImpl<detail::LifeCycleCostParameters_Impl>()->nominalDiscountRate();
}
boost::optional<double> LifeCycleCostParameters::inflation() const {
return getImpl<detail::LifeCycleCostParameters_Impl>()->inflation();
}
MonthOfYear LifeCycleCostParameters::baseDateMonth() const {
return getImpl<detail::LifeCycleCostParameters_Impl>()->baseDateMonth();
}
bool LifeCycleCostParameters::isBaseDateMonthDefaulted() const {
return getImpl<detail::LifeCycleCostParameters_Impl>()->isBaseDateMonthDefaulted();
}
int LifeCycleCostParameters::baseDateYear() const {
return getImpl<detail::LifeCycleCostParameters_Impl>()->baseDateYear();
}
bool LifeCycleCostParameters::isBaseDateYearDefaulted() const {
return getImpl<detail::LifeCycleCostParameters_Impl>()->isBaseDateYearDefaulted();
}
MonthOfYear LifeCycleCostParameters::serviceDateMonth() const {
return getImpl<detail::LifeCycleCostParameters_Impl>()->serviceDateMonth();
}
bool LifeCycleCostParameters::isServiceDateMonthDefaulted() const {
return getImpl<detail::LifeCycleCostParameters_Impl>()->isServiceDateMonthDefaulted();
}
int LifeCycleCostParameters::serviceDateYear() const {
return getImpl<detail::LifeCycleCostParameters_Impl>()->serviceDateYear();
}
bool LifeCycleCostParameters::isServiceDateYearDefaulted() const {
return getImpl<detail::LifeCycleCostParameters_Impl>()->isServiceDateYearDefaulted();
}
int LifeCycleCostParameters::lengthOfStudyPeriodInYears() const {
return getImpl<detail::LifeCycleCostParameters_Impl>()->lengthOfStudyPeriodInYears();
}
bool LifeCycleCostParameters::isLengthOfStudyPeriodInYearsDefaulted() const {
return getImpl<detail::LifeCycleCostParameters_Impl>()->isLengthOfStudyPeriodInYearsDefaulted();
}
boost::optional<double> LifeCycleCostParameters::taxRate() const {
return getImpl<detail::LifeCycleCostParameters_Impl>()->taxRate();
}
std::string LifeCycleCostParameters::depreciationMethod() const {
return getImpl<detail::LifeCycleCostParameters_Impl>()->depreciationMethod();
}
bool LifeCycleCostParameters::isDepreciationMethodDefaulted() const {
return getImpl<detail::LifeCycleCostParameters_Impl>()->isDepreciationMethodDefaulted();
}
bool LifeCycleCostParameters::useNISTFuelEscalationRates() const {
return getImpl<detail::LifeCycleCostParameters_Impl>()->useNISTFuelEscalationRates();
}
bool LifeCycleCostParameters::isUseNISTFuelEscalationRatesDefaulted() const {
return getImpl<detail::LifeCycleCostParameters_Impl>()->isUseNISTFuelEscalationRatesDefaulted();
}
boost::optional<std::string> LifeCycleCostParameters::nistRegion() const {
return getImpl<detail::LifeCycleCostParameters_Impl>()->nistRegion();
}
std::vector<std::string> LifeCycleCostParameters::validNistRegionValues() const
{
return getImpl<detail::LifeCycleCostParameters_Impl>()->validNistRegionValues();
}
bool LifeCycleCostParameters::isNISTRegionDefaulted() const {
return getImpl<detail::LifeCycleCostParameters_Impl>()->isNISTRegionDefaulted();
}
boost::optional<std::string> LifeCycleCostParameters::nistSector() const {
return getImpl<detail::LifeCycleCostParameters_Impl>()->nistSector();
}
std::vector<std::string> LifeCycleCostParameters::validNistSectorValues() const
{
return getImpl<detail::LifeCycleCostParameters_Impl>()->validNistSectorValues();
}
bool LifeCycleCostParameters::isNISTSectorDefaulted() const {
return getImpl<detail::LifeCycleCostParameters_Impl>()->isNISTSectorDefaulted();
}
boost::optional<double> LifeCycleCostParameters::electricityInflation() const {
return getImpl<detail::LifeCycleCostParameters_Impl>()->electricityInflation();
}
boost::optional<double> LifeCycleCostParameters::naturalGasInflation() const {
return getImpl<detail::LifeCycleCostParameters_Impl>()->naturalGasInflation();
}
boost::optional<double> LifeCycleCostParameters::steamInflation() const {
return getImpl<detail::LifeCycleCostParameters_Impl>()->steamInflation();
}
boost::optional<double> LifeCycleCostParameters::gasolineInflation() const {
return getImpl<detail::LifeCycleCostParameters_Impl>()->gasolineInflation();
}
boost::optional<double> LifeCycleCostParameters::dieselInflation() const {
return getImpl<detail::LifeCycleCostParameters_Impl>()->dieselInflation();
}
boost::optional<double> LifeCycleCostParameters::coalInflation() const {
return getImpl<detail::LifeCycleCostParameters_Impl>()->coalInflation();
}
boost::optional<double> LifeCycleCostParameters::fuelOil1Inflation() const {
return getImpl<detail::LifeCycleCostParameters_Impl>()->fuelOil1Inflation();
}
boost::optional<double> LifeCycleCostParameters::fuelOil2Inflation() const {
return getImpl<detail::LifeCycleCostParameters_Impl>()->fuelOil2Inflation();
}
boost::optional<double> LifeCycleCostParameters::propaneInflation() const {
return getImpl<detail::LifeCycleCostParameters_Impl>()->propaneInflation();
}
boost::optional<double> LifeCycleCostParameters::waterInflation() const {
return getImpl<detail::LifeCycleCostParameters_Impl>()->waterInflation();
}
bool LifeCycleCostParameters::setAnalysisType(const std::string& analysisType){
return getImpl<detail::LifeCycleCostParameters_Impl>()->setAnalysisType(analysisType);
}
void LifeCycleCostParameters::resetAnalysisType(){
getImpl<detail::LifeCycleCostParameters_Impl>()->resetAnalysisType();
}
bool LifeCycleCostParameters::setDiscountingConvention(const std::string& discountingConvention){
return getImpl<detail::LifeCycleCostParameters_Impl>()->setDiscountingConvention(discountingConvention);
}
void LifeCycleCostParameters::resetDiscountingConvention(){
getImpl<detail::LifeCycleCostParameters_Impl>()->resetDiscountingConvention();
}
bool LifeCycleCostParameters::setInflationApproach(const std::string& inflationApproach) {
return getImpl<detail::LifeCycleCostParameters_Impl>()->setInflationApproach(inflationApproach);
}
void LifeCycleCostParameters::resetInflationApproach() {
getImpl<detail::LifeCycleCostParameters_Impl>()->resetInflationApproach();
}
bool LifeCycleCostParameters::setRealDiscountRate(double realDiscountRate) {
return getImpl<detail::LifeCycleCostParameters_Impl>()->setRealDiscountRate(realDiscountRate);
}
bool LifeCycleCostParameters::setNominalDiscountRate(double nominalDiscountRate) {
return getImpl<detail::LifeCycleCostParameters_Impl>()->setNominalDiscountRate(nominalDiscountRate);
}
bool LifeCycleCostParameters::setInflation(double inflation) {
return getImpl<detail::LifeCycleCostParameters_Impl>()->setInflation(inflation);
}
bool LifeCycleCostParameters::setBaseDateMonth(const MonthOfYear& baseDateMonth) {
return getImpl<detail::LifeCycleCostParameters_Impl>()->setBaseDateMonth(baseDateMonth);
}
void LifeCycleCostParameters::resetBaseDateMonth() {
getImpl<detail::LifeCycleCostParameters_Impl>()->resetBaseDateMonth();
}
bool LifeCycleCostParameters::setBaseDateYear(int baseDateYear) {
return getImpl<detail::LifeCycleCostParameters_Impl>()->setBaseDateYear(baseDateYear);
}
void LifeCycleCostParameters::resetBaseDateYear() {
getImpl<detail::LifeCycleCostParameters_Impl>()->resetBaseDateYear();
}
bool LifeCycleCostParameters::setServiceDateMonth(const MonthOfYear& serviceDateMonth) {
return getImpl<detail::LifeCycleCostParameters_Impl>()->setServiceDateMonth(serviceDateMonth);
}
void LifeCycleCostParameters::resetServiceDateMonth() {
getImpl<detail::LifeCycleCostParameters_Impl>()->resetServiceDateMonth();
}
bool LifeCycleCostParameters::setServiceDateYear(int serviceDateYear) {
return getImpl<detail::LifeCycleCostParameters_Impl>()->setServiceDateYear(serviceDateYear);
}
void LifeCycleCostParameters::resetServiceDateYear() {
getImpl<detail::LifeCycleCostParameters_Impl>()->resetServiceDateYear();
}
bool LifeCycleCostParameters::setLengthOfStudyPeriodInYears(int lengthOfStudyPeriodInYears) {
return getImpl<detail::LifeCycleCostParameters_Impl>()->setLengthOfStudyPeriodInYears(lengthOfStudyPeriodInYears);
}
void LifeCycleCostParameters::resetLengthOfStudyPeriodInYears() {
getImpl<detail::LifeCycleCostParameters_Impl>()->resetLengthOfStudyPeriodInYears();
}
bool LifeCycleCostParameters::setTaxRate(double taxRate) {
return getImpl<detail::LifeCycleCostParameters_Impl>()->setTaxRate(taxRate);
}
void LifeCycleCostParameters::resetTaxRate() {
getImpl<detail::LifeCycleCostParameters_Impl>()->resetTaxRate();
}
bool LifeCycleCostParameters::setDepreciationMethod(const std::string& depreciationMethod) {
return getImpl<detail::LifeCycleCostParameters_Impl>()->setDepreciationMethod(depreciationMethod);
}
void LifeCycleCostParameters::resetDepreciationMethod() {
getImpl<detail::LifeCycleCostParameters_Impl>()->resetDepreciationMethod();
}
bool LifeCycleCostParameters::setUseNISTFuelEscalationRates(bool useNISTFuelEscalationRates) {
return getImpl<detail::LifeCycleCostParameters_Impl>()->setUseNISTFuelEscalationRates(useNISTFuelEscalationRates);
}
void LifeCycleCostParameters::resetUseNISTFuelEscalationRates() {
getImpl<detail::LifeCycleCostParameters_Impl>()->resetUseNISTFuelEscalationRates();
}
bool LifeCycleCostParameters::setNISTRegion(const std::string& nistRegion) {
return getImpl<detail::LifeCycleCostParameters_Impl>()->setNISTRegion(nistRegion);
}
void LifeCycleCostParameters::resetNISTRegion() {
getImpl<detail::LifeCycleCostParameters_Impl>()->resetNISTRegion();
}
bool LifeCycleCostParameters::setNISTSector(const std::string& nistSector) {
return getImpl<detail::LifeCycleCostParameters_Impl>()->setNISTSector(nistSector);
}
void LifeCycleCostParameters::resetNISTSector() {
getImpl<detail::LifeCycleCostParameters_Impl>()->resetNISTSector();
}
bool LifeCycleCostParameters::setElectricityInflation(double electricityInflation) {
return getImpl<detail::LifeCycleCostParameters_Impl>()->setElectricityInflation(electricityInflation);
}
void LifeCycleCostParameters::resetElectricityInflation() {
getImpl<detail::LifeCycleCostParameters_Impl>()->resetElectricityInflation();
}
bool LifeCycleCostParameters::setNaturalGasInflation(double naturalGasInflation) {
return getImpl<detail::LifeCycleCostParameters_Impl>()->setNaturalGasInflation(naturalGasInflation);
}
void LifeCycleCostParameters::resetNaturalGasInflation() {
getImpl<detail::LifeCycleCostParameters_Impl>()->resetNaturalGasInflation();
}
bool LifeCycleCostParameters::setSteamInflation(double steamInflation) {
return getImpl<detail::LifeCycleCostParameters_Impl>()->setSteamInflation(steamInflation);
}
void LifeCycleCostParameters::resetSteamInflation() {
getImpl<detail::LifeCycleCostParameters_Impl>()->resetSteamInflation();
}
bool LifeCycleCostParameters::setGasolineInflation(double gasolineInflation) {
return getImpl<detail::LifeCycleCostParameters_Impl>()->setGasolineInflation(gasolineInflation);
}
void LifeCycleCostParameters::resetGasolineInflation() {
getImpl<detail::LifeCycleCostParameters_Impl>()->resetGasolineInflation();
}
bool LifeCycleCostParameters::setDieselInflation(double dieselInflation) {
return getImpl<detail::LifeCycleCostParameters_Impl>()->setDieselInflation(dieselInflation);
}
void LifeCycleCostParameters::resetDieselInflation() {
getImpl<detail::LifeCycleCostParameters_Impl>()->resetDieselInflation();
}
bool LifeCycleCostParameters::setCoalInflation(double coalInflation) {
return getImpl<detail::LifeCycleCostParameters_Impl>()->setCoalInflation(coalInflation);
}
void LifeCycleCostParameters::resetCoalInflation() {
getImpl<detail::LifeCycleCostParameters_Impl>()->resetCoalInflation();
}
bool LifeCycleCostParameters::setFuelOil1Inflation(double fuelOil1Inflation) {
return getImpl<detail::LifeCycleCostParameters_Impl>()->setFuelOil1Inflation(fuelOil1Inflation);
}
void LifeCycleCostParameters::resetFuelOil1Inflation() {
getImpl<detail::LifeCycleCostParameters_Impl>()->resetFuelOil1Inflation();
}
bool LifeCycleCostParameters::setFuelOil2Inflation(double fuelOil2Inflation) {
return getImpl<detail::LifeCycleCostParameters_Impl>()->setFuelOil2Inflation(fuelOil2Inflation);
}
void LifeCycleCostParameters::resetFuelOil2Inflation() {
getImpl<detail::LifeCycleCostParameters_Impl>()->resetFuelOil2Inflation();
}
bool LifeCycleCostParameters::setPropaneInflation(double propaneInflation) {
return getImpl<detail::LifeCycleCostParameters_Impl>()->setPropaneInflation(propaneInflation);
}
void LifeCycleCostParameters::resetPropaneInflation() {
getImpl<detail::LifeCycleCostParameters_Impl>()->resetPropaneInflation();
}
bool LifeCycleCostParameters::setWaterInflation(double waterInflation) {
return getImpl<detail::LifeCycleCostParameters_Impl>()->setWaterInflation(waterInflation);
}
void LifeCycleCostParameters::resetWaterInflation() {
getImpl<detail::LifeCycleCostParameters_Impl>()->resetWaterInflation();
}
std::vector<std::string> LifeCycleCostParameters::validAnalysisTypeValues() {
return getIddKeyNames(IddFactory::instance().getObject(iddObjectType()).get(),
OS_LifeCycleCost_ParametersFields::AnalysisType);
}
std::vector<std::string> LifeCycleCostParameters::validDiscountingConventionValues() {
return getIddKeyNames(IddFactory::instance().getObject(iddObjectType()).get(),
OS_LifeCycleCost_ParametersFields::DiscountingConvention);
}
std::vector<std::string> LifeCycleCostParameters::validInflationApproachValues() {
return getIddKeyNames(IddFactory::instance().getObject(iddObjectType()).get(),
OS_LifeCycleCost_ParametersFields::InflationApproach);
}
std::vector<std::string> LifeCycleCostParameters::validDepreciationMethodValues() {
return getIddKeyNames(IddFactory::instance().getObject(iddObjectType()).get(),
OS_LifeCycleCost_ParametersFields::DepreciationMethod);
}
IddObjectType LifeCycleCostParameters::iddObjectType()
{
IddObjectType result(IddObjectType::OS_LifeCycleCost_Parameters);
return result;
}
} // model
} // openstudio
| 36.704815 | 137 | 0.766993 | [
"object",
"vector",
"model"
] |
1038de4961695ff74b63d2c8e922e1a8e106b548 | 1,684 | hpp | C++ | qt/common_ops.hpp | storm-ptr/bark | e4cd481183aba72ec6cf996eff3ac144c88b79b6 | [
"MIT"
] | 3 | 2019-11-05T10:27:35.000Z | 2019-12-02T06:25:53.000Z | qt/common_ops.hpp | storm-ptr/bark | e4cd481183aba72ec6cf996eff3ac144c88b79b6 | [
"MIT"
] | null | null | null | qt/common_ops.hpp | storm-ptr/bark | e4cd481183aba72ec6cf996eff3ac144c88b79b6 | [
"MIT"
] | 2 | 2019-12-01T18:01:02.000Z | 2021-04-07T08:34:04.000Z | // Andrew Naplavkov
#ifndef BARK_QT_COMMON_OPS_HPP
#define BARK_QT_COMMON_OPS_HPP
#include <bark/db/provider.hpp>
#include <bark/qt/common.hpp>
#include <bark/qt/detail/adapt.hpp>
#include <bark/qt/detail/georeference_proj.hpp>
#include <boost/range/adaptor/filtered.hpp>
namespace bark::qt {
inline bool queryable(const link& lnk)
{
return lnk.queryable;
}
inline auto projection(const layer& lr)
{
return lr.provider->projection(lr.name);
}
inline auto extent(const layer& lr)
{
return lr.provider->extent(lr.name);
}
inline auto table(const layer& lr)
{
return lr.provider->table(qualifier(lr.name));
}
inline auto ddl(const layer& from, const link& to)
{
return to.provider->ddl(table(from));
}
inline auto attr_names(const layer& lr)
{
return db::names(table(lr).columns |
boost::adaptors::filtered(
std::not_fn(same{db::meta::column_type::Geometry})));
}
inline auto tile_coverage(const layer& lr,
const geometry::box& ext,
const geometry::box& px)
{
return lr.provider->tile_coverage(lr.name, ext, px);
}
inline auto spatial_objects(const layer& lr,
const geometry::box& ext,
const geometry::box& px)
{
return lr.provider->spatial_objects(lr.name, ext, px);
}
inline geometry::box pixel(const georeference& ref)
{
auto pos = adapt(ref.center);
return {pos, {pos.x() + ref.scale, pos.y() + ref.scale}};
}
inline geometry::box extent(const georeference& ref)
{
return backward(ref, QRectF{{}, ref.size});
}
} // namespace bark::qt
#endif // BARK_QT_COMMON_OPS_HPP
| 22.756757 | 78 | 0.646081 | [
"geometry"
] |
1040a091d37034ff37e5326a39057c4246ffed34 | 10,681 | cc | C++ | L1Trigger/TrackerDTC/src/Stub.cc | AFJohan92/cmssw | c5b36f05986c35998ddd4c873dc6812646579744 | [
"Apache-2.0"
] | 2 | 2020-01-21T11:23:39.000Z | 2020-01-21T11:23:42.000Z | L1Trigger/TrackerDTC/src/Stub.cc | AFJohan92/cmssw | c5b36f05986c35998ddd4c873dc6812646579744 | [
"Apache-2.0"
] | null | null | null | L1Trigger/TrackerDTC/src/Stub.cc | AFJohan92/cmssw | c5b36f05986c35998ddd4c873dc6812646579744 | [
"Apache-2.0"
] | 3 | 2019-03-09T13:06:43.000Z | 2020-07-03T00:47:30.000Z | #include "L1Trigger/TrackerDTC/interface/Stub.h"
#include "L1Trigger/TrackerDTC/interface/Settings.h"
#include "L1Trigger/TrackerDTC/interface/Module.h"
#include <cmath>
#include <iterator>
#include <algorithm>
#include <utility>
#include <vector>
using namespace std;
namespace trackerDTC {
Stub::Stub(Settings* settings, Module* module, const TTStubRef& ttStubRef)
: settings_(settings), ttStubRef_(ttStubRef), module_(module), valid_(true) {
regions_.reserve(settings_->numOverlappingRegions());
// get stub local coordinates
const MeasurementPoint& mp = ttStubRef->clusterRef(0)->findAverageLocalCoordinatesCentered();
// convert to uniformed local coordinates
// column number in pitch units
col_ = (int)floor(pow(-1, module->signCol_) * (mp.y() - module->numColumns_ / 2) / settings_->baseCol());
// row number in half pitch units
row_ = (int)floor(pow(-1, module->signRow_) * (mp.x() - module->numRows_ / 2) / settings_->baseRow());
// bend number in quarter pitch units
bend_ = (int)floor(pow(-1, module->signBend_) * (ttStubRef->bendBE()) / settings_->baseBend());
// reduced row number for look up
rowLUT_ = (int)floor((double)row_ / pow(2., settings_->widthRow() - settings_->widthRowLUT()));
// sub row number inside reduced row number
rowSub_ = row_ - (rowLUT_ + .5) * pow(2, settings_->widthRow() - settings_->widthRowLUT());
// convert local to global coordinates
const double y = (col_ + .5) * settings_->baseCol() * module->pitchCol_;
// radius of a column of strips/pixel in cm
d_ = module->R_ + y * module->sin_;
// stub z in cm
z_ = module->Z_ + y * module->cos_;
const double x0 = rowLUT_ * settings_->baseRow() * settings_->numMergedRows() * module->pitchRow_;
const double x1 = (rowLUT_ + 1) * settings_->baseRow() * settings_->numMergedRows() * module->pitchRow_;
const double x = (rowLUT_ + .5) * settings_->baseRow() * settings_->numMergedRows() * module->pitchRow_;
// stub r in cm
r_ = sqrt(d_ * d_ + x * x);
const double phi0 = module->Phi_ + atan2(x0, d_);
const double phi1 = module->Phi_ + atan2(x1, d_);
const double c = (phi0 + phi1) / 2.;
const double m = (phi1 - phi0) / settings_->numMergedRows();
// intercept of linearized stub phi in rad
c_ = digi(c, settings_->baseC());
// slope of linearized stub phi in rad / strip
m_ = digi(m, settings_->baseM());
if (settings_->dataFormat() == "TMTT") {
// extrapolated z at radius T assuming z0=0
const double zT = settings_->tmtt()->chosenRofZ() * z_ / r_;
// extrapolated z0 window at radius T
const double dZT = settings_->tmtt()->beamWindowZ() * abs(1. - settings_->tmtt()->chosenRofZ() / r_);
double zTMin = zT - dZT;
double zTMax = zT + dZT;
if (zTMin >= settings_->tmtt()->maxZT() || zTMax < -settings_->tmtt()->maxZT())
// did not pass "eta" cut
valid_ = false;
else {
zTMin = max(zTMin, -settings_->tmtt()->maxZT());
zTMax = min(zTMax, settings_->tmtt()->maxZT());
}
// range of stub cot(theta)
cot_ = {zTMin / settings_->tmtt()->chosenRofZ(), zTMax / settings_->tmtt()->chosenRofZ()};
} else if (settings_->dataFormat() == "Hybrid") {
if (abs(z_ / r_) > settings_->maxCot())
// did not pass eta cut
valid_ = false;
}
// stub r w.r.t. chosenRofPhi in cm
r_ = digi(r_ - settings_->chosenRofPhi(), settings_->baseR());
// radial (cylindrical) component of sensor separation
const double dr = module->sep_ / (module->cos_ - module->sin_ * z_ / d_);
// converts bend into qOverPt in 1/cm
const double qOverPtOverBend = module->pitchRow_ / dr / d_;
// qOverPt in 1/cm
const double qOverPt = bend_ * settings_->baseBend() * qOverPtOverBend;
// qOverPt uncertainty in 1/cm
const double dQoverPt = settings_->bendCut() * qOverPtOverBend;
double qOverPtMin = digi(qOverPt - dQoverPt, settings_->baseQoverPt());
double qOverPtMax = digi(qOverPt + dQoverPt, settings_->baseQoverPt());
if (qOverPtMin >= settings_->maxQoverPt() || qOverPtMax < -settings_->maxQoverPt())
// did not pass pt cut
valid_ = false;
else {
qOverPtMin = max(qOverPtMin, -settings_->maxQoverPt());
qOverPtMax = min(qOverPtMax, settings_->maxQoverPt());
}
// range of stub qOverPt in 1/cm
qOverPt_ = {qOverPtMin, qOverPtMax};
// stub phi w.r.t. detector region centre in rad
phi_ = c_ + rowSub_ * m_;
// range of stub extrapolated phi to radius chosenRofPhi in rad
phiT_.first = phi_ + r_ * qOverPt_.first;
phiT_.second = phi_ + r_ * qOverPt_.second;
if (phiT_.first > phiT_.second)
swap(phiT_.first, phiT_.second);
if (phiT_.first < 0.)
regions_.push_back(0);
if (phiT_.second >= 0.)
regions_.push_back(1);
// apply data format specific manipulations
if (settings_->dataFormat() != "Hybrid")
return;
// stub r w.r.t. an offset in cm
r_ -= module->offsetR_;
// stub z w.r.t. an offset in cm
z_ -= module->offsetZ_;
if (module->type_ == SettingsHybrid::disk2S)
// decoded r
r_ = (module->decodedR_ + .5) * settings_->hybrid()->baseR(module->type_);
// decode bend
const vector<double>& bendEncoding = module->bendEncoding_;
const int uBend = distance(bendEncoding.begin(), find(bendEncoding.begin(), bendEncoding.end(), abs(bend_)));
bend_ = pow(-1, signbit(bend_)) * (uBend - (int)bendEncoding.size() / 2);
}
// returns bit accurate representation of Stub
TTDTC::BV Stub::frame(int region) const {
return settings_->dataFormat() == "Hybrid" ? formatHybrid(region) : formatTMTT(region);
}
// outer tracker dtc routing block id [0-1]
int Stub::blockId() const { return module_->blockId_; }
// outer tracker dtc routing block channel id [0-35]
int Stub::channelId() const { return module_->blockChannelId_; }
// returns true if stub belongs to region
bool Stub::inRegion(int region) const { return find(regions_.begin(), regions_.end(), region) != regions_.end(); }
// truncates double precision to f/w integer equivalent
double Stub::digi(double value, double precision) const { return (floor(value / precision) + .5) * precision; }
// returns 64 bit stub in hybrid data format
TTDTC::BV Stub::formatHybrid(int region) const {
SettingsHybrid* format = settings_->hybrid();
SettingsHybrid::SensorType type = module_->type_;
// stub phi w.r.t. processing region centre in rad
const double phi = phi_ - (region - .5) * settings_->baseRegion();
// convert stub variables into bit vectors
const TTBV hwR(r_, format->baseR(type), format->widthR(type), true);
const TTBV hwPhi(phi, format->basePhi(type), format->widthPhi(type), true);
const TTBV hwZ(z_, format->baseZ(type), format->widthZ(type), true);
const TTBV hwAlpha(row_, format->baseAlpha(type), format->widthAlpha(type), true);
const TTBV hwBend(bend_, format->widthBend(type), true);
const TTBV hwLayer(module_->layerId_, settings_->widthLayer());
const TTBV hwGap(0, format->numUnusedBits(type));
const TTBV hwValid(1, 1);
// assemble final bitset
return TTDTC::BV(hwGap.str() + hwR.str() + hwZ.str() + hwPhi.str() + hwAlpha.str() + hwBend.str() + hwLayer.str() +
hwValid.str());
}
TTDTC::BV Stub::formatTMTT(int region) const {
SettingsTMTT* format = settings_->tmtt();
int layerM = module_->layerId_;
// convert unique layer id [1-6,11-15] into reduced layer id [0-6]
// a fiducial track may not cross more then 7 detector layers, for stubs from a given track the reduced layer id is actually unique
int layer(-1);
if (layerM == 1)
layer = 0;
else if (layerM == 2)
layer = 1;
else if (layerM == 6 || layerM == 11)
layer = 2;
else if (layerM == 5 || layerM == 12)
layer = 3;
else if (layerM == 4 || layerM == 13)
layer = 4;
else if (layerM == 14)
layer = 5;
else if (layerM == 3 || layerM == 15)
layer = 6;
// assign stub to phi sectors within a processing region, to be generalized
TTBV sectorsPhi(0, settings_->numOverlappingRegions() * format->numSectorsPhi());
if (phiT_.first < 0.) {
if (phiT_.first < -format->baseSector())
sectorsPhi.set(0);
else
sectorsPhi.set(1);
if (phiT_.second < 0. && phiT_.second >= -format->baseSector())
sectorsPhi.set(1);
}
if (phiT_.second >= 0.) {
if (phiT_.second < format->baseSector())
sectorsPhi.set(2);
else
sectorsPhi.set(3);
if (phiT_.first >= 0. && phiT_.first < format->baseSector())
sectorsPhi.set(2);
}
// assign stub to eta sectors within a processing region
pair<int, int> setcorEta({0, format->numSectorsEta() - 1});
for (int bin = 0; bin < format->numSectorsEta(); bin++)
if (asinh(cot_.first) < format->boundariesEta(bin + 1)) {
setcorEta.first = bin;
break;
}
for (int bin = setcorEta.first; bin < format->numSectorsEta(); bin++)
if (asinh(cot_.second) < format->boundariesEta(bin + 1)) {
setcorEta.second = bin;
break;
}
// stub phi w.r.t. processing region centre in rad
const double phi = phi_ - (region - .5) * settings_->baseRegion();
// convert stub variables into bit vectors
const TTBV hwValid(1, 1);
const TTBV hwGap(0, format->numUnusedBits());
const TTBV hwLayer(layer, settings_->widthLayer());
const TTBV hwSectorEtaMin(setcorEta.first, settings_->widthEta());
const TTBV hwSectorEtaMax(setcorEta.second, settings_->widthEta());
const TTBV hwR(r_, settings_->baseR(), settings_->widthR(), true);
const TTBV hwPhi(phi, settings_->basePhi(), settings_->widthPhi(), true);
const TTBV hwZ(z_, settings_->baseZ(), settings_->widthZ(), true);
const TTBV hwQoverPtMin(qOverPt_.first, format->baseQoverPt(), format->widthQoverPtBin(), true);
const TTBV hwQoverPtMax(qOverPt_.second, format->baseQoverPt(), format->widthQoverPtBin(), true);
TTBV hwSectorPhis(0, format->numSectorsPhi());
for (int sectorPhi = 0; sectorPhi < format->numSectorsPhi(); sectorPhi++)
hwSectorPhis[sectorPhi] = sectorsPhi[region * format->numSectorsPhi() + sectorPhi];
// assemble final bitset
return TTDTC::BV(hwGap.str() + hwValid.str() + hwR.str() + hwPhi.str() + hwZ.str() + hwQoverPtMin.str() +
hwQoverPtMax.str() + hwSectorEtaMin.str() + hwSectorEtaMax.str() + hwSectorPhis.str() +
hwLayer.str());
}
} // namespace trackerDTC | 43.595918 | 135 | 0.640577 | [
"vector"
] |
10477306569dd6650ecdd3dd0632bea898b40753 | 63,833 | cc | C++ | mysql-server/storage/innobase/lock/lock0wait.cc | silenc3502/MYSQL-Arch-Doc-Summary | fcc6bb65f72a385b9f56debc9b2c00cee5914bae | [
"MIT"
] | null | null | null | mysql-server/storage/innobase/lock/lock0wait.cc | silenc3502/MYSQL-Arch-Doc-Summary | fcc6bb65f72a385b9f56debc9b2c00cee5914bae | [
"MIT"
] | null | null | null | mysql-server/storage/innobase/lock/lock0wait.cc | silenc3502/MYSQL-Arch-Doc-Summary | fcc6bb65f72a385b9f56debc9b2c00cee5914bae | [
"MIT"
] | null | null | null | /*****************************************************************************
Copyright (c) 1996, 2020, Oracle and/or its affiliates. All Rights Reserved.
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License, version 2.0, as published by the
Free Software Foundation.
This program is also distributed with certain software (including but not
limited to OpenSSL) that is licensed under separate terms, as designated in a
particular file or component or in included license documentation. The authors
of MySQL hereby grant you an additional permission to link the program and
your derivative works with the separately licensed software that they have
included with MySQL.
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, version 2.0,
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.,
51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*****************************************************************************/
/** @file lock/lock0wait.cc
The transaction lock system
Created 25/5/2010 Sunny Bains
*******************************************************/
#define LOCK_MODULE_IMPLEMENTATION
#include <mysql/service_thd_wait.h>
#include <sys/types.h>
#include "ha_prototypes.h"
#include "lock0lock.h"
#include "lock0priv.h"
#include "os0thread-create.h"
#include "que0que.h"
#include "row0mysql.h"
#include "srv0mon.h"
#include "srv0start.h"
#include "my_dbug.h"
/** Print the contents of the lock_sys_t::waiting_threads array. */
static void lock_wait_table_print(void) {
ut_ad(lock_wait_mutex_own());
const srv_slot_t *slot = lock_sys->waiting_threads;
for (uint32_t i = 0; i < srv_max_n_threads; i++, ++slot) {
fprintf(stderr,
"Slot %lu: thread type %lu,"
" in use %lu, susp %lu, timeout %lu, time %lu\n",
(ulong)i, (ulong)slot->type, (ulong)slot->in_use,
(ulong)slot->suspended, slot->wait_timeout,
(ulong)(ut_time_monotonic() - slot->suspend_time));
}
}
/** Release a slot in the lock_sys_t::waiting_threads. Adjust the array last
pointer if there are empty slots towards the end of the table. */
static void lock_wait_table_release_slot(
srv_slot_t *slot) /*!< in: slot to release */
{
#ifdef UNIV_DEBUG
srv_slot_t *upper = lock_sys->waiting_threads + srv_max_n_threads;
#endif /* UNIV_DEBUG */
lock_wait_mutex_enter();
/* We omit trx_mutex_enter and a lock_sys latches here, because we are only
going to touch thr->slot, which is a member used only by lock0wait.cc and is
sufficiently protected by lock_wait_mutex. Yes, there are readers who read
the thr->slot holding only trx->mutex and a lock_sys latch, but they do so,
when they are sure that we were not woken up yet, so our thread can't be here.
See comments in lock_wait_release_thread_if_suspended() for more details. */
ut_ad(slot->in_use);
ut_ad(slot->thr != nullptr);
ut_ad(slot->thr->slot != nullptr);
ut_ad(slot->thr->slot == slot);
/* Must be within the array boundaries. */
ut_ad(slot >= lock_sys->waiting_threads);
ut_ad(slot < upper);
slot->thr->slot = nullptr;
slot->thr = nullptr;
slot->in_use = FALSE;
/* Scan backwards and adjust the last free slot pointer. */
for (slot = lock_sys->last_slot;
slot > lock_sys->waiting_threads && !slot->in_use; --slot) {
/* No op */
}
/* Either the array is empty or the last scanned slot is in use. */
ut_ad(slot->in_use || slot == lock_sys->waiting_threads);
lock_sys->last_slot = slot + 1;
/* The last slot is either outside of the array boundary or it's
on an empty slot. */
ut_ad(lock_sys->last_slot == upper || !lock_sys->last_slot->in_use);
ut_ad(lock_sys->last_slot >= lock_sys->waiting_threads);
ut_ad(lock_sys->last_slot <= upper);
lock_wait_mutex_exit();
}
/** Counts number of calls to lock_wait_table_reserve_slot.
It is protected by lock_wait_mutex.
Current value of this counter is stored in the slot a transaction has chosen
for sleeping during suspension, and thus serves as "reservation number" which
can be used to check if the owner of the slot has changed (perhaps multiple
times, in "ABA" manner). */
static uint64_t lock_wait_table_reservations = 0;
/** Reserves a slot in the thread table for the current user OS thread.
@return reserved slot */
static srv_slot_t *lock_wait_table_reserve_slot(
que_thr_t *thr, /*!< in: query thread associated
with the user OS thread */
ulong wait_timeout) /*!< in: lock wait timeout value */
{
srv_slot_t *slot;
ut_ad(lock_wait_mutex_own());
ut_ad(trx_mutex_own(thr_get_trx(thr)));
slot = lock_sys->waiting_threads;
for (uint32_t i = srv_max_n_threads; i--; ++slot) {
if (!slot->in_use) {
slot->reservation_no = lock_wait_table_reservations++;
slot->in_use = TRUE;
slot->thr = thr;
slot->thr->slot = slot;
if (slot->event == nullptr) {
slot->event = os_event_create();
ut_a(slot->event);
}
os_event_reset(slot->event);
slot->suspended = TRUE;
slot->suspend_time = ut_time_monotonic();
slot->wait_timeout = wait_timeout;
if (slot == lock_sys->last_slot) {
++lock_sys->last_slot;
}
ut_ad(lock_sys->last_slot <=
lock_sys->waiting_threads + srv_max_n_threads);
/* We call lock_wait_request_check_for_cycles() because the
node representing the `thr` only now becomes visible to the thread which
analyzes contents of lock_sys->waiting_threads. The edge itself was
created by lock_create_wait_for_edge() during RecLock::add_to_waitq() or
lock_table(), but at that moment the source of the edge was not yet in the
lock_sys->waiting_threads, so the node and the outgoing edge were not yet
visible.
I hope this explains why we do waste time on calling
lock_wait_request_check_for_cycles() from lock_create_wait_for_edge().*/
lock_wait_request_check_for_cycles();
return (slot);
}
}
ib::error(ER_IB_MSG_646)
<< "There appear to be " << srv_max_n_threads
<< " user"
" threads currently waiting inside InnoDB, which is the upper"
" limit. Cannot continue operation. Before aborting, we print"
" a list of waiting threads.";
lock_wait_table_print();
ut_error;
}
void lock_wait_request_check_for_cycles() { lock_set_timeout_event(); }
/** Puts a user OS thread to wait for a lock to be released. If an error
occurs during the wait trx->error_state associated with thr is
!= DB_SUCCESS when we return. DB_LOCK_WAIT_TIMEOUT and DB_DEADLOCK
are possible errors. DB_DEADLOCK is returned if selective deadlock
resolution chose this transaction as a victim. */
void lock_wait_suspend_thread(que_thr_t *thr) /*!< in: query thread associated
with the user OS thread */
{
srv_slot_t *slot;
trx_t *trx;
ibool was_declared_inside_innodb;
ib_time_monotonic_ms_t start_time = 0;
ulong lock_wait_timeout;
trx = thr_get_trx(thr);
if (trx->mysql_thd != nullptr) {
DEBUG_SYNC_C("lock_wait_suspend_thread_enter");
}
/* InnoDB system transactions (such as the purge, and
incomplete transactions that are being rolled back after crash
recovery) will use the global value of
innodb_lock_wait_timeout, because trx->mysql_thd == NULL. */
lock_wait_timeout = trx_lock_wait_timeout_get(trx);
lock_wait_mutex_enter();
trx_mutex_enter(trx);
trx->error_state = DB_SUCCESS;
if (thr->state == QUE_THR_RUNNING) {
ut_ad(thr->is_active);
/* The lock has already been released or this transaction
was chosen as a deadlock victim: no need to suspend */
if (trx->lock.was_chosen_as_deadlock_victim) {
trx->error_state = DB_DEADLOCK;
trx->lock.was_chosen_as_deadlock_victim = false;
ut_d(trx->lock.in_rollback = true);
}
lock_wait_mutex_exit();
trx_mutex_exit(trx);
return;
}
ut_ad(!thr->is_active);
slot = lock_wait_table_reserve_slot(thr, lock_wait_timeout);
if (thr->lock_state == QUE_THR_LOCK_ROW) {
srv_stats.n_lock_wait_count.inc();
srv_stats.n_lock_wait_current_count.inc();
start_time = ut_time_monotonic_us();
}
lock_wait_mutex_exit();
/* We hold trx->mutex here, which is required to call
lock_set_lock_and_trx_wait. This means that the value in
trx->lock.wait_lock_type which we are about to read comes from the latest
call to lock_set_lock_and_trx_wait before we obtained the trx->mutex, which is
precisely what we want for our stats */
auto lock_type = trx->lock.wait_lock_type;
trx_mutex_exit(trx);
ulint had_dict_lock = trx->dict_operation_lock_mode;
switch (had_dict_lock) {
case 0:
break;
case RW_S_LATCH:
/* Release foreign key check latch */
row_mysql_unfreeze_data_dictionary(trx);
DEBUG_SYNC_C("lock_wait_release_s_latch_before_sleep");
break;
case RW_X_LATCH:
/* We may wait for rec lock in dd holding
dict_operation_lock for creating FTS AUX table */
ut_ad(!mutex_own(&dict_sys->mutex));
rw_lock_x_unlock(dict_operation_lock);
break;
}
/* Suspend this thread and wait for the event. */
was_declared_inside_innodb = trx->declared_to_be_inside_innodb;
if (was_declared_inside_innodb) {
/* We must declare this OS thread to exit InnoDB, since a
possible other thread holding a lock which this thread waits
for must be allowed to enter, sooner or later */
srv_conc_force_exit_innodb(trx);
}
ut_a(lock_type == LOCK_REC || lock_type == LOCK_TABLE);
thd_wait_begin(trx->mysql_thd, lock_type == LOCK_REC ? THD_WAIT_ROW_LOCK
: THD_WAIT_TABLE_LOCK);
DEBUG_SYNC_C("lock_wait_will_wait");
os_event_wait(slot->event);
DEBUG_SYNC_C("lock_wait_has_finished_waiting");
thd_wait_end(trx->mysql_thd);
/* After resuming, reacquire the data dictionary latch if
necessary. */
if (was_declared_inside_innodb) {
/* Return back inside InnoDB */
srv_conc_force_enter_innodb(trx);
}
if (had_dict_lock == RW_S_LATCH) {
row_mysql_freeze_data_dictionary(trx);
} else if (had_dict_lock == RW_X_LATCH) {
rw_lock_x_lock(dict_operation_lock);
}
const auto wait_time = ut_time_monotonic() - slot->suspend_time;
/* Release the slot for others to use */
lock_wait_table_release_slot(slot);
if (thr->lock_state == QUE_THR_LOCK_ROW) {
const auto finish_time = ut_time_monotonic_us();
const uint64_t diff_time =
(finish_time > start_time) ? (uint64_t)(finish_time - start_time) : 0;
srv_stats.n_lock_wait_current_count.dec();
srv_stats.n_lock_wait_time.add(diff_time);
/* Only update the variable if we successfully
retrieved the start and finish times. See Bug#36819. */
if (diff_time > lock_sys->n_lock_max_wait_time && start_time != 0) {
lock_sys->n_lock_max_wait_time = diff_time;
}
/* Record the lock wait time for this thread */
thd_set_lock_wait_time(trx->mysql_thd, diff_time);
DBUG_EXECUTE_IF("lock_instrument_slow_query_log", os_thread_sleep(1000););
}
/* The transaction is chosen as deadlock victim during sleep. */
if (trx->error_state == DB_DEADLOCK) {
ut_d(trx->lock.in_rollback = true);
return;
}
if (lock_wait_timeout < 100000000 && wait_time > (double)lock_wait_timeout &&
!trx_is_high_priority(trx)) {
trx->error_state = DB_LOCK_WAIT_TIMEOUT;
MONITOR_INC(MONITOR_TIMEOUT);
}
if (trx_is_interrupted(trx)) {
trx->error_state = DB_INTERRUPTED;
}
}
/** Releases a user OS thread waiting for a lock to be released, if the
thread is already suspended. Please do not call it directly, but rather use the
lock_reset_wait_and_release_thread_if_suspended() wrapper.
@param[in] thr query thread associated with the user OS thread */
static void lock_wait_release_thread_if_suspended(que_thr_t *thr) {
auto trx = thr_get_trx(thr);
/* We need a guarantee that for each time a thread is suspended there is at
most one time it gets released - or more precisely: that there is at most
one reason for it to be woken up. Otherwise it could happen that two
different threads will think that they successfully woken up the transaction
and that the transaction understands the reason it was woken up is the one
they had in mind, say: one thread woken it up because of deadlock and another
because of timeout. If the two reasons require different behavior after
waking up, then we will be in trouble. Current implementation makes sure
that we wake up a thread only once by observing several rules:
1. the only way to wake up a trx is to call os_event_set
2. the only call to os_event_set is in lock_wait_release_thread_if_suspended
3. calls to lock_wait_release_thread_if_suspended are always performed after
a call to lock_reset_lock_and_trx_wait(lock), and the sequence of the two is
in a critical section guarded by lock_sys latch for the shard containing the
waiting lock
4. the lock_reset_lock_and_trx_wait(lock) asserts that
lock->trx->lock.wait_lock == lock and sets lock->trx->lock.wait_lock = NULL
Together all this facts imply, that it is impossible for a single trx to be
woken up twice (unless it got to sleep again) because doing so requires
reseting wait_lock to NULL.
We now hold either an exclusive lock_sys latch, or just for the shard which
contains the lock which used to be trx->lock.wait_lock, but we can not assert
that because trx->lock.wait_lock is now NULL so we don't know for which shard
we hold the latch here. So, please imagine something like:
ut_ad(locksys::owns_lock_shard(lock->trx->lock.wait_lock));
*/
ut_ad(trx_mutex_own(trx));
/* We don't need the lock_wait_mutex here, because we know that the thread
had a reason to go to sleep (we have seen trx->lock.wait_lock !=NULL), and we
know that we are the first ones to wake it up (we are the thread which has
changed the trx->lock.wait_lock to NULL), so it either sleeps, or did not
yet started the sleep. We hold the trx->mutex which is required to go to
sleep. So, while holding the trx->mutex we can check if thr->slot is already
assigned and if so, then we need to wake up the thread. If the thr->slot is
not yet assigned, then we know that the thread had not yet gone to sleep, and
we know that before doing so, it will need to acquire trx->mutex and will
verify once more if it has to go to sleep by checking if thr->state is
QUE_THR_RUNNING which we indeed have already set before calling
lock_wait_release_thread_if_suspended, so we don't need to do anything in this
case - trx will simply not go to sleep. */
ut_ad(thr->state == QUE_THR_RUNNING);
ut_ad(trx->lock.wait_lock == nullptr);
if (thr->slot != nullptr && thr->slot->in_use && thr->slot->thr == thr) {
if (trx->lock.was_chosen_as_deadlock_victim) {
trx->error_state = DB_DEADLOCK;
trx->lock.was_chosen_as_deadlock_victim = false;
ut_d(trx->lock.in_rollback = true);
}
os_event_set(thr->slot->event);
}
}
void lock_reset_wait_and_release_thread_if_suspended(lock_t *lock) {
ut_ad(locksys::owns_lock_shard(lock));
ut_ad(trx_mutex_own(lock->trx));
ut_ad(lock->trx->lock.wait_lock == lock);
/* We clear blocking_trx here and not in lock_reset_lock_and_trx_wait(), as
lock_reset_lock_and_trx_wait() is called also when the wait_lock is being
moved from one page to another during B-tree reorganization, in which case
blocking_trx should not change - in such cases a new wait lock is created
and assigned to trx->lock.wait_lock, but the information about blocking trx
is not so easy to restore, so it is easier to simply not clear blocking_trx
until we are 100% sure that we want to wake up the trx, which is now.
Clearing blocking_trx helps with:
1. performance optimization, as lock_wait_snapshot_waiting_threads() can omit
this trx when building wait-for-graph
2. debugging, as reseting blocking_trx makes it easier to spot it was not
properly set on subsequent waits.
3. helping lock_make_trx_hit_list() notice that HP trx is no longer waiting
for a lock, so it can take a fast path */
lock->trx->lock.blocking_trx.store(nullptr);
/* We only release locks for which someone is waiting, and we posses a latch
on the shard in which the lock is stored, and the trx which decided to wait
for the lock should have already set trx->lock.que_state to TRX_QUE_LOCK_WAIT
and called que_thr_stop() before releasing the latch on this shard. */
ut_ad(lock->trx_que_state() == TRX_QUE_LOCK_WAIT);
/* The following function releases the trx from lock wait */
que_thr_t *thr = que_thr_end_lock_wait(lock->trx);
/* Reset the wait flag and the back pointer to lock in trx.
It is important to call it only after we obtain lock->trx->mutex, because
trx_mutex_enter makes some assertions based on trx->lock.wait_lock value */
lock_reset_lock_and_trx_wait(lock);
if (thr != nullptr) {
lock_wait_release_thread_if_suspended(thr);
}
}
/** Check if the thread lock wait has timed out. Release its locks if the
wait has actually timed out. */
static void lock_wait_check_and_cancel(
const srv_slot_t *slot) /*!< in: slot reserved by a user
thread when the wait started */
{
trx_t *trx;
const auto suspend_time = slot->suspend_time;
ut_ad(lock_wait_mutex_own());
ut_ad(slot->in_use);
ut_ad(slot->suspended);
const auto wait_time = ut_time_monotonic() - suspend_time;
trx = thr_get_trx(slot->thr);
if (trx_is_interrupted(trx) ||
(slot->wait_timeout < 100000000 &&
(wait_time > (int64_t)slot->wait_timeout || wait_time < 0))) {
/* Timeout exceeded or a wrap-around in system time counter: cancel the lock
request queued by the transaction and release possible other transactions
waiting behind; it is possible that the lock has already been granted: in
that case do nothing.
The lock_cancel_waiting_and_release() needs exclusive global latch.
Also, we need to latch the shard containing wait_lock to read the field and
access the lock itself. */
locksys::Global_exclusive_latch_guard guard{};
trx_mutex_enter(trx);
if (trx->lock.wait_lock != nullptr && !trx_is_high_priority(trx)) {
ut_a(trx->lock.que_state == TRX_QUE_LOCK_WAIT);
lock_cancel_waiting_and_release(trx->lock.wait_lock);
}
trx_mutex_exit(trx);
}
}
/** A snapshot of information about a single slot which was in use at the moment
of taking the snapshot */
struct waiting_trx_info_t {
/** The transaction which was using this slot. */
trx_t *trx;
/** The transaction for which the owner of the slot is waiting for. */
trx_t *waits_for;
/** The slot this info is about */
srv_slot_t *slot;
/** The slot->reservation_no at the moment of taking the snapshot */
uint64_t reservation_no;
};
/** As we want to quickly find a given trx_t within the snapshot, we use a
sorting criterion which is based on trx only. We use the pointer address, as
any deterministic rule without ties will do. */
bool operator<(const waiting_trx_info_t &a, const waiting_trx_info_t &b) {
return std::less<trx_t *>{}(a.trx, b.trx);
}
/** Check all slots for user threads that are waiting on locks, and if they have
exceeded the time limit. */
static void lock_wait_check_slots_for_timeouts() {
ut_ad(!lock_wait_mutex_own());
lock_wait_mutex_enter();
for (auto slot = lock_sys->waiting_threads; slot < lock_sys->last_slot;
++slot) {
/* We are doing a read without latching the lock_sys or the trx mutex.
This is OK, because a slot can't be freed or reserved without the lock wait
mutex. */
if (slot->in_use) {
lock_wait_check_and_cancel(slot);
}
}
lock_wait_mutex_exit();
}
/** Takes a snapshot of the content of slots which are in use
@param[out] infos Will contain the information about slots which are in use
@return value of lock_wait_table_reservations before taking the snapshot
*/
static uint64_t lock_wait_snapshot_waiting_threads(
ut::vector<waiting_trx_info_t> &infos) {
ut_ad(!lock_wait_mutex_own());
infos.clear();
lock_wait_mutex_enter();
/*
We own lock_wait_mutex, which protects lock_wait_table_reservations and
reservation_no.
We want to make a snapshot of the wait-for graph as quick as possible to not
keep the lock_wait_mutex too long.
Anything more fancy than push_back seems to impact performance.
Note: one should be able to prove that we don't really need a "consistent"
snapshot - the algorithm should still work if we split the loop into several
smaller "chunks" snapshotted independently and stitch them together. Care must
be taken to "merge" duplicates keeping the freshest version (reservation_no)
of slot for each trx.
So, if (in future) this loop turns out to be a bottleneck (say, by increasing
congestion on lock_wait_mutex), one can try to release and require the lock
every X iterations and modify the lock_wait_build_wait_for_graph() to handle
duplicates in a smart way.
*/
const auto table_reservations = lock_wait_table_reservations;
for (auto slot = lock_sys->waiting_threads; slot < lock_sys->last_slot;
++slot) {
if (slot->in_use) {
auto from = thr_get_trx(slot->thr);
auto to = from->lock.blocking_trx.load();
if (to != nullptr) {
infos.push_back({from, to, slot, slot->reservation_no});
}
}
}
lock_wait_mutex_exit();
return table_reservations;
}
/** Used to initialize schedule weights of nodes in wait-for-graph for the
computation. Initially all nodes have weight 1, except for nodes which waited
very long, for which we set the weight to WEIGHT_BOOST
@param[in] infos information about all waiting transactions
@param[in] table_reservations value of lock_wait_table_reservations at
before taking the `infos` snapshot
@param[out] new_weights place to store initial weights of nodes
*/
static void lock_wait_compute_initial_weights(
const ut::vector<waiting_trx_info_t> &infos,
const uint64_t table_reservations,
ut::vector<trx_schedule_weight_t> &new_weights) {
const size_t n = infos.size();
ut_ad(n <= std::numeric_limits<trx_schedule_weight_t>::max());
/*
We want to boost transactions which waited too long, according to a heuristic,
that if 2*n transactions got suspended during our wait, and the current number
of waiters is n, then it means that at least n transactions bypassed us, which
seems unfair. Also, in a fair world, where suspensions and wake-ups are
balanced, 2*n suspensions mean around 2*n wake-ups, and one would expect
around n other transactions to wake up, until it is our turn to wake up.
A boost increases weight from 1 to WEIGHT_BOOST for the node.
We want a boosted transaction to have weight higher than weight of any other
transaction which is not boosted and does not cause any boosted trx to wait.
For this it would suffice to set WEIGHT_BOOST to n.
But, we sum weights of nodes that wait for us, to come up with final value of
schedule_weight, so to avoid overflow, we must ensure that WEIGHT_BOOST*n is
small enough to fit in signed 32-bit.
We thus clamp WEIGHT_BOOST to 1e9 / n just to be safe.
*/
const trx_schedule_weight_t WEIGHT_BOOST =
n == 0 ? 1 : std::min<trx_schedule_weight_t>(n, 1e9 / n);
new_weights.clear();
new_weights.resize(n, 1);
const uint64_t MAX_FAIR_WAIT = 2 * n;
for (size_t from = 0; from < n; ++from) {
if (infos[from].reservation_no + MAX_FAIR_WAIT < table_reservations) {
new_weights[from] = WEIGHT_BOOST;
}
}
}
/** Analyzes content of the snapshot with information about slots in use, and
builds a (subset of) list of edges from waiting transactions to blocking
transactions, such that for each waiter we have one outgoing edge.
@param[in] infos information about all waiting transactions
@param[out] outgoing The outgoing[from] will contain either the index such
that infos[outgoing[from]].trx is the reason
infos[from].trx has to wait, or -1 if the reason for
waiting is not among transactions in infos[].trx. */
static void lock_wait_build_wait_for_graph(
ut::vector<waiting_trx_info_t> &infos, ut::vector<int> &outgoing) {
/** We are going to use int and uint to store positions within infos */
ut_ad(infos.size() < std::numeric_limits<uint>::max());
const auto n = static_cast<uint>(infos.size());
ut_ad(n < static_cast<uint>(std::numeric_limits<int>::max()));
outgoing.clear();
outgoing.resize(n, -1);
/* This particular implementation sorts infos by ::trx, and then uses
lower_bound to find index in infos corresponding to ::wait_for, which has
O(nlgn) complexity and modifies infos, but has a nice property of avoiding any
allocations.
An alternative O(n) approach would be to use a hash table to map infos[i].trx
to i.
Using unordered_map<trx_t*,int> however causes too much (de)allocations as
its bucket chains are implemented as a linked lists - overall it works much
slower than sort.
The fastest implementation was to use custom implementation of a hash table
with open addressing and double hashing with a statically allocated
2 * srv_max_n_threads buckets. This however did not increase transactions per
second, so introducing a custom implementation seems unjustified here. */
sort(infos.begin(), infos.end());
waiting_trx_info_t needle{};
for (uint from = 0; from < n; ++from) {
/* Assert that the order used by sort and lower_bound depends only on the
trx field, as this is the only one we will initialize in the needle. */
ut_ad(from == 0 ||
std::less<trx_t *>{}(infos[from - 1].trx, infos[from].trx));
needle.trx = infos[from].waits_for;
auto it = std::lower_bound(infos.begin(), infos.end(), needle);
if (it == infos.end() || it->trx != needle.trx) {
continue;
}
auto to = it - infos.begin();
ut_ad(from != static_cast<uint>(to));
outgoing[from] = static_cast<int>(to);
}
}
/** Notifies the chosen_victim that it should roll back
@param[in,out] chosen_victim the transaction that should be rolled back */
static void lock_wait_rollback_deadlock_victim(trx_t *chosen_victim) {
ut_ad(!trx_mutex_own(chosen_victim));
/* The call to lock_cancel_waiting_and_release requires exclusive latch on
whole lock_sys.
Also, we need to latch the shard containing wait_lock to read it and access
the lock itself.*/
ut_ad(locksys::owns_exclusive_global_latch());
trx_mutex_enter(chosen_victim);
chosen_victim->lock.was_chosen_as_deadlock_victim = true;
ut_a(chosen_victim->lock.wait_lock != nullptr);
ut_a(chosen_victim->lock.que_state == TRX_QUE_LOCK_WAIT);
lock_cancel_waiting_and_release(chosen_victim->lock.wait_lock);
trx_mutex_exit(chosen_victim);
}
/** Given the `infos` about transactions and indexes in `infos` which form a
deadlock cycle, identifies the transaction with the largest `reservation_no`,
that is the one which was the latest to join the cycle.
@param[in] cycle_ids indexes in `infos` array, of transactions forming the
deadlock cycle
@param[in] infos information about all waiting transactions
@return position in cycle_ids, such that infos[cycle_ids[pos]].reservation_no is
the largest */
static size_t lock_wait_find_latest_pos_on_cycle(
const ut::vector<uint> &cycle_ids,
const ut::vector<waiting_trx_info_t> &infos) {
size_t latest_pos = 0;
for (size_t pos = 1; pos < cycle_ids.size(); ++pos) {
if (infos[cycle_ids[latest_pos]].reservation_no <
infos[cycle_ids[pos]].reservation_no) {
latest_pos = pos;
}
}
return latest_pos;
}
/** Rotates the deadlock cycle so that it starts from desired item.
@param[in] first_pos the position which should become first after rotation
@param[in] cycle_ids the array to rotate
@return a copy of cycle_ids rotated in such a way, that the element which
was at position `first_pos` is now the first */
static ut::vector<uint> lock_wait_rotate_so_pos_is_first(
size_t first_pos, const ut::vector<uint> &cycle_ids) {
ut_ad(first_pos < cycle_ids.size());
auto rotated_ids = cycle_ids;
std::rotate(rotated_ids.begin(), rotated_ids.begin() + first_pos,
rotated_ids.end());
return rotated_ids;
}
/** A helper, which extracts transactions with given indexes from the `infos`
array.
@param[in] ids indexes of transactions in the `infos` array to extract
@param[in] infos information about all waiting transactions
@return An array formed by infos[ids[i]].trx */
template <typename T>
static ut::vector<T> lock_wait_map_ids_to_trxs(
const ut::vector<uint> &ids, const ut::vector<waiting_trx_info_t> &infos) {
ut::vector<T> trxs;
trxs.reserve(ids.size());
for (auto id : ids) {
trxs.push_back(infos[id].trx);
}
return trxs;
}
/** Orders the transactions from deadlock cycle in such a backward-compatible
way, from the point of view of algorithm with picks the victim. From correctness
point of view this could be a no-op, but we have test cases which assume some
determinism in that which trx is selected as the victim. These tests usually
depend on the old behaviour in which the order in which trxs attempted to wait
was meaningful. In the past we have only considered two candidates for victim:
(a) the transaction which closed the cycle by adding last wait-for edge
(b) the transaction which is waiting for (a)
and it favored to pick (a) in case of ties.
To make these test pass we find the trx with most recent reservation_no (a),
and the one before it in the cycle (b), and move them to the end of collection
So that we consider them in order: ...,...,...,(b),(a), resolving ties by
picking the latest one as victim.
In other words we rotate the cycle so that the most recent waiter becomes the
last.
@param[in] cycle_ids indexes in `infos` array, of transactions forming the
deadlock cycle
@param[in] infos information about all waiting transactions
@return transactions from the deadlock cycle sorted in the optimal way for
choosing a victim */
static ut::vector<trx_t *> lock_wait_order_for_choosing_victim(
const ut::vector<uint> &cycle_ids,
const ut::vector<waiting_trx_info_t> &infos) {
size_t latest_pos = lock_wait_find_latest_pos_on_cycle(cycle_ids, infos);
size_t first_pos = (latest_pos + 1) % cycle_ids.size();
return lock_wait_map_ids_to_trxs<trx_t *>(
lock_wait_rotate_so_pos_is_first(first_pos, cycle_ids), infos);
}
/** Performs new_weights[parent_id] += new_weights[child_id] with sanity checks.
@param[in,out] new_weights schedule weights of transactions initialized and
perhaps partially accumulated already.
This function will modify new_weights[parent_id]
by adding new_weights[child_id] to it.
@param[in] parent_id index of the node to update
@param[in] child_id index of the node which weight should be added
to the parent's weight.
*/
static void lock_wait_add_subtree_weight(
ut::vector<trx_schedule_weight_t> &new_weights, const size_t parent_id,
const size_t child_id) {
const trx_schedule_weight_t child_weight = new_weights[child_id];
trx_schedule_weight_t &old_parent_weight = new_weights[parent_id];
/* We expect incoming_weight to be positive
@see lock_wait_compute_initial_weights() */
ut_ad(0 < child_weight);
/* The trx_schedule_weight_t is unsigned type, so overflows are well defined,
but we don't expect them as lock_wait_compute_initial_weights() sets the
initial weights to small enough that sum of whole subtree should never
overflow */
static_assert(
std::is_unsigned<trx_schedule_weight_t>::value,
"The trx_schedule_weight_t should be unsigned to minimize impact "
"of overflows");
ut_ad(old_parent_weight < old_parent_weight + child_weight);
old_parent_weight += child_weight;
}
/** Given a graph with at most one outgoing edge per node, and initial weight
for each node, this function will compute for each node a partial sum of initial
weights of the node and all nodes that can reach it in the graph.
@param[in,out] incoming_count The value of incoming_count[id] should match
the number of edges incoming to the node id.
In other words |x : outgoing[x] == id|.
This function will modify entries in this
array, so that after the call, nodes on cycles
will have value 1, and others will have 0.
@param[in,out] new_weights Should contain initial weight for each node.
This function will modify entries for nodes
which are not on cycles, so that
new_weights[id] will be the sum of initial
weights of the node `id` and all nodes that
can reach it by one or more outgoing[] edges.
@param[in] outgoing The ids of edge endpoints.
If outgoing[id] == -1, then there is no edge
going out of id, otherwise there is an edge
from id to outgoing[id].
*/
static void lock_wait_accumulate_weights(
ut::vector<uint> &incoming_count,
ut::vector<trx_schedule_weight_t> &new_weights,
const ut::vector<int> &outgoing) {
ut_a(incoming_count.size() == outgoing.size());
ut::vector<size_t> ready;
ready.clear();
const size_t n = incoming_count.size();
for (size_t id = 0; id < n; ++id) {
if (!incoming_count[id]) {
ready.push_back(id);
}
}
while (!ready.empty()) {
size_t id = ready.back();
ready.pop_back();
if (outgoing[id] != -1) {
lock_wait_add_subtree_weight(new_weights, outgoing[id], id);
if (!--incoming_count[outgoing[id]]) {
ready.push_back(outgoing[id]);
}
}
}
}
/** Checks if info[id].slot is still in use and has not been freed and reserved
again since we took the info snapshot ("ABA" type of race condition).
@param[in] infos information about all waiting transactions
@param[in] id index to retrieve
@return info[id].slot if the slot was reserved whole time since taking the info
snapshot. Otherwise: nullptr.
*/
static const srv_slot_t *lock_wait_get_slot_if_still_reserved(
const ut::vector<waiting_trx_info_t> &infos, const size_t id) {
ut_ad(lock_wait_mutex_own());
const auto slot = infos[id].slot;
if (slot->in_use && slot->reservation_no == infos[id].reservation_no) {
return slot;
}
return nullptr;
}
/** Copies the newly computed schedule weights to the transactions fields.
Ignores transactions which take part in cycles, because for them we don't have a
final value of the schedule weight yet.
@param[in] is_on_cycle A positive value is_on_cycle[id] means that `id` is on
a cycle in the graph.
@param[in] infos information about all waiting transactions
@param[in] new_weights schedule weights of transactions computed for all
transactions except those which are on a cycle.
*/
static void lock_wait_publish_new_weights(
const ut::vector<uint> &is_on_cycle,
const ut::vector<waiting_trx_info_t> &infos,
const ut::vector<trx_schedule_weight_t> &new_weights) {
ut_ad(!lock_wait_mutex_own());
ut_a(infos.size() == new_weights.size());
ut_a(infos.size() == is_on_cycle.size());
const size_t n = infos.size();
lock_wait_mutex_enter();
for (size_t id = 0; id < n; ++id) {
if (is_on_cycle[id]) {
continue;
}
const auto slot = lock_wait_get_slot_if_still_reserved(infos, id);
if (!slot) {
continue;
}
ut_ad(thr_get_trx(slot->thr) == infos[id].trx);
const auto schedule_weight = new_weights[id];
infos[id].trx->lock.schedule_weight.store(schedule_weight,
std::memory_order_relaxed);
}
lock_wait_mutex_exit();
}
/** Given an array with information about all waiting transactions and indexes
in it which form a deadlock cycle, picks the transaction to rollback.
@param[in] cycle_ids indexes in `infos` array, of transactions forming the
deadlock cycle
@param[in] infos information about all waiting transactions
@return the transaction chosen as a victim */
static trx_t *lock_wait_choose_victim(
const ut::vector<uint> &cycle_ids,
const ut::vector<waiting_trx_info_t> &infos) {
/* We are iterating over various transactions comparing their trx_weight_ge,
which is computed based on number of locks held thus we need exclusive latch
on the whole lock_sys. In theory number of locks should not change while the
transaction is waiting, but instead of proving that they can not wake up, it
is easier to assert that we hold the mutex */
ut_ad(locksys::owns_exclusive_global_latch());
ut_ad(!cycle_ids.empty());
trx_t *chosen_victim = nullptr;
auto sorted_trxs = lock_wait_order_for_choosing_victim(cycle_ids, infos);
for (auto *trx : sorted_trxs) {
if (chosen_victim == nullptr) {
chosen_victim = trx;
continue;
}
if (trx_is_high_priority(chosen_victim) || trx_is_high_priority(trx)) {
auto victim = trx_arbitrate(trx, chosen_victim);
if (victim != nullptr) {
if (victim == trx) {
chosen_victim = trx;
} else {
ut_a(victim == chosen_victim);
}
continue;
}
}
if (trx_weight_ge(chosen_victim, trx)) {
/* The joining transaction is 'smaller',
choose it as the victim and roll it back. */
chosen_victim = trx;
}
}
ut_a(chosen_victim);
return chosen_victim;
}
/** Given an array with information about all waiting transactions and indexes
in it which form a deadlock cycle, checks if the transactions allegedly forming
the deadlock have actually stayed in slots since we've last checked, as opposed
to say, not leaving a slot, and/or re-entering the slot ("ABA" situation).
This is done by comparing the current reservation_no for each slot, with the
reservation_no from the `info` snapshot.
@param[in] cycle_ids indexes in `infos` array, of transactions forming the
deadlock cycle
@param[in] infos information about all waiting transactions
@return true if all given transactions resided in their slots for the whole time
since the snapshot was taken, and in particular are still there right now */
static bool lock_wait_trxs_are_still_in_slots(
const ut::vector<uint> &cycle_ids,
const ut::vector<waiting_trx_info_t> &infos) {
ut_ad(lock_wait_mutex_own());
for (auto id : cycle_ids) {
const auto slot = lock_wait_get_slot_if_still_reserved(infos, id);
if (!slot) {
return false;
}
ut_ad(thr_get_trx(slot->thr) == infos[id].trx);
}
return true;
}
/** Given an array with information about all waiting transactions and indexes
in it which form a deadlock cycle, checks if the transactions allegedly forming
the deadlock have actually still wait for a lock, as opposed to being already
notified about lock being granted or timeout, but still being present in the
slot. This is done by checking trx->lock.wait_lock under exclusive global
lock_sys latch.
@param[in] cycle_ids indexes in `infos` array, of transactions forming the
deadlock cycle
@param[in] infos information about all waiting transactions
@return true if all given transactions are still waiting for locks*/
static bool lock_wait_trxs_are_still_waiting(
const ut::vector<uint> &cycle_ids,
const ut::vector<waiting_trx_info_t> &infos) {
ut_ad(lock_wait_mutex_own());
/* We are iterating over various transaction which may have locks in different
tables/rows, thus we need exclusive latch on the whole lock_sys to make sure
no one will wake them up (say, a high priority trx could abort them) or change
the wait_lock to NULL temporarily during B-tree page reorganization. */
ut_ad(locksys::owns_exclusive_global_latch());
for (auto id : cycle_ids) {
const auto trx = infos[id].trx;
if (trx->lock.wait_lock == nullptr) {
/* trx is on its way to being woken up, so this cycle is a false positive.
As this particular cycle will resolve itself, we ignore it. */
return false;
}
ut_a(trx->lock.que_state == TRX_QUE_LOCK_WAIT);
}
return true;
}
/* A helper function which rotates the deadlock cycle, so that the order of
transactions in it is suitable for notification. From correctness perspective
this could be a no-op, but we have test cases which assume some determinism in
that in which order trx from cycle are reported. These tests usually depend on
the old behaviour in which the order in which transactions attempted to wait was
meaningful. In the past we reported:
- the transaction which closed the cycle by adding last wait-for edge as (2)
- the transaction which is waiting for (2) as (1)
To make these test pass we find the trx with most recent reservation_no (2),
and the one before it in the cycle (1), and move (1) to the beginning.
@param[in] cycle_ids indexes in `infos` array, of transactions forming the
deadlock cycle
@param[in] infos information about all waiting transactions
@return the indexes from cycle_ids sorted rotated in backward-compatible way
*/
static ut::vector<uint> lock_wait_rotate_cycle_ids_for_notification(
const ut::vector<uint> &cycle_ids,
const ut::vector<waiting_trx_info_t> &infos) {
size_t latest_pos = lock_wait_find_latest_pos_on_cycle(cycle_ids, infos);
size_t previous_pos = (latest_pos - 1 + cycle_ids.size()) % cycle_ids.size();
return lock_wait_rotate_so_pos_is_first(previous_pos, cycle_ids);
}
/** A helper function which rotates the deadlock cycle, so that the specified
trx is the first one on the cycle.
@param[in] trx The transaction we wish to be the first after the
rotation. There must exist x, such that
infos[cycle_ids[x]].trx == trx.
@param[in] cycle_ids indexes in `infos` array, of transactions forming the
deadlock cycle
@param[in] infos information about all waiting transactions
@return Assuming that infos[cycle_ids[x]].trx == trx the result will be a copy
of [cycle_ids[x],cycle_ids[x+1 mod N],...,cycle_ids[x-1+N mod N]].
*/
static ut::vector<uint> lock_wait_rotate_cycle_ids_to_so_trx_is_first(
const trx_t *trx, const ut::vector<uint> &cycle_ids,
const ut::vector<waiting_trx_info_t> &infos) {
auto first_pos = std::distance(
cycle_ids.begin(),
std::find_if(cycle_ids.begin(), cycle_ids.end(),
[&](uint id) { return infos[id].trx == trx; }));
return lock_wait_rotate_so_pos_is_first(first_pos, cycle_ids);
}
/** Finalizes the computation of new schedule weights, by providing missing
information about transactions located on a deadlock cycle. Assuming that we
know the list of transactions on a cycle, which transaction will be chosen as a
victim, and what are the weights of trees hanging off the cycle, it computes
the final schedule weight for each of transactions to be equal to its weight in
a graph with the victim's node missing
@param[in] chosen_victim The transaction chosen to be rolled back
@param[in] cycle_ids indexes in `infos` array, of transactions
forming the deadlock cycle
@param[in] infos information about all waiting transactions
@param[in,out] new_weights schedule weights of transactions computed for
all transactions except those which are on a
cycle. This function will update the new_weights
entries for transactions involved in deadlock
cycle (as it will unfold to a path, and schedule
weight can be thus computed)
*/
static void lock_wait_update_weights_on_cycle(
const trx_t *chosen_victim, const ut::vector<uint> &cycle_ids,
const ut::vector<waiting_trx_info_t> &infos,
ut::vector<trx_schedule_weight_t> &new_weights) {
auto rotated_cycle_id = lock_wait_rotate_cycle_ids_to_so_trx_is_first(
chosen_victim, cycle_ids, infos);
ut_ad(infos[rotated_cycle_id[0]].trx == chosen_victim);
/* Recall that chosen_victim is in rotated_cycle_id[0].
Imagine that it will become rolled back, which means that it will vanish,
and the cycle will unfold into a path. This path will start with the
transaction for which chosen_victim was waiting, and for which the computed
new_weight is already correct. We need to update the new_weights[] for
following transactions, accumulating their weights along the path.
We also need to publish the new_weights to trx->cat_weight fields for
all transactions on the path.
*/
new_weights[rotated_cycle_id[0]] = 0;
for (uint i = 1; i + 1 < rotated_cycle_id.size(); ++i) {
lock_wait_add_subtree_weight(new_weights, rotated_cycle_id[i + 1],
rotated_cycle_id[i]);
}
for (auto id : rotated_cycle_id) {
infos[id].trx->lock.schedule_weight.store(new_weights[id],
std::memory_order_relaxed);
}
}
/** A helper function which rotates the deadlock cycle, so that the order of
transactions in it is suitable for notification. From correctness perspective
this could be a no-op, but we have tests which depend on deterministic output
from such notifications, and we want to be backward compatible.
@param[in] cycle_ids indexes in `infos` array, of transactions forming the
deadlock cycle
@param[in] infos information about all waiting transactions
@return the transactions from cycle_ids rotated in backward-compatible way */
static ut::vector<const trx_t *> lock_wait_trxs_rotated_for_notification(
const ut::vector<uint> &cycle_ids,
const ut::vector<waiting_trx_info_t> &infos) {
return lock_wait_map_ids_to_trxs<const trx_t *>(
lock_wait_rotate_cycle_ids_for_notification(cycle_ids, infos), infos);
}
/** Handles a deadlock found, by notifying about it, rolling back the chosen
victim and updating schedule weights of transactions on the deadlock cycle.
@param[in,out] chosen_victim the transaction to roll back
@param[in] cycle_ids indexes in `infos` array, of transactions forming
the deadlock cycle
@param[in] infos information about all waiting transactions
@param[in,out] new_weights schedule weights of transactions computed for all
transactions except those which are on a cycle.
This function will update the new_weights entries
for transactions involved in deadlock cycle (as it
will unfold to a path, and schedule weight can be
thus computed) */
static void lock_wait_handle_deadlock(
trx_t *chosen_victim, const ut::vector<uint> &cycle_ids,
const ut::vector<waiting_trx_info_t> &infos,
ut::vector<trx_schedule_weight_t> &new_weights) {
/* We now update the `schedule_weight`s on the cycle taking into account that
chosen_victim will be rolled back.
This is mostly for "correctness" as the impact on performance is negligible
(actually it looks like it is slowing us down). */
lock_wait_update_weights_on_cycle(chosen_victim, cycle_ids, infos,
new_weights);
lock_notify_about_deadlock(
lock_wait_trxs_rotated_for_notification(cycle_ids, infos), chosen_victim);
lock_wait_rollback_deadlock_victim(chosen_victim);
}
/** Given an array with information about all waiting transactions and indexes
in it which form a deadlock cycle, checks if the transactions allegedly forming
the deadlock cycle, indeed are still waiting, and if so, chooses a victim and
handles the deadlock.
@param[in] cycle_ids indexes in `infos` array, of transactions forming
the deadlock cycle
@param[in] infos information about all waiting transactions
@param[in,out] new_weights schedule weights of transactions computed for all
transactions except those which are on the cycle.
In case it is a real deadlock cycle, this function
will update the new_weights entries for transactions
involved in this cycle (as it will unfold to a path,
and schedule weight can be thus computed)
@return true if the cycle found was indeed a deadlock cycle, false if it was a
false positive */
static bool lock_wait_check_candidate_cycle(
ut::vector<uint> &cycle_ids, const ut::vector<waiting_trx_info_t> &infos,
ut::vector<trx_schedule_weight_t> &new_weights) {
ut_ad(!lock_wait_mutex_own());
ut_ad(!locksys::owns_exclusive_global_latch());
lock_wait_mutex_enter();
/*
We have released all mutexes after we have built the `infos` snapshot and
before we've got here. So, while it is true that the edges form a cycle, it
may also be true that some of these transactions were already rolled back, and
memory pointed by infos[i].trx or infos[i].waits_for is no longer the trx it
used to be (as we reuse trx_t objects). It may even segfault if we try to
access it (because trx_t object could be freed). So we need to somehow verify
that the pointer is still valid without accessing it. We do that by checking
if slot->reservation_no has changed since taking a snapshot.
If it has not changed, then we know that the trx's pointer still points to the
same trx as the trx is sleeping, and thus has not finished and wasn't freed.
So, we start by first checking that the slots still contain the trxs we are
interested in. This requires lock_wait_mutex, but does not require the
exclusive global latch. */
if (!lock_wait_trxs_are_still_in_slots(cycle_ids, infos)) {
lock_wait_mutex_exit();
return false;
}
/*
At this point we are sure that we can access memory pointed by infos[i].trx
and that transactions are still in their slots. (And, as `cycle_ids` is a
cycle, we also know that infos[cycle_ids[i]].wait_for is equal to
infos[cycle_ids[i+1]].trx, so infos[cycle_ids[i]].wait_for can also be safely
accessed).
This however does not mean necessarily that they are still waiting.
They might have been already notified that they should wake up (by calling
lock_wait_release_thread_if_suspended()), but they had not yet chance to act
upon it (it is the trx being woken up who is responsible for cleaning up the
`slot` it used).
So, the slot can be still in use and contain a transaction, which was already
decided to be rolled back for example. However, we can recognize this
situation by looking at trx->lock.wait_lock, as each call to
lock_wait_release_thread_if_suspended() is performed only after
lock_reset_lock_and_trx_wait() resets trx->lock.wait_lock to NULL.
Checking trx->lock.wait_lock in reliable way requires global exclusive latch.
*/
locksys::Global_exclusive_latch_guard gurad{};
if (!lock_wait_trxs_are_still_waiting(cycle_ids, infos)) {
lock_wait_mutex_exit();
return false;
}
/*
We can now release lock_wait_mutex, because:
1. we have verified that trx->lock.wait_lock is not NULL for cycle_ids
2. we hold exclusive global lock_sys latch
3. lock_sys latch is required to change trx->lock.wait_lock to NULL
4. only after changing trx->lock.wait_lock to NULL a trx can finish
So as long as we hold exclusive global lock_sys latch we can access trxs.
*/
lock_wait_mutex_exit();
trx_t *const chosen_victim = lock_wait_choose_victim(cycle_ids, infos);
ut_a(chosen_victim);
lock_wait_handle_deadlock(chosen_victim, cycle_ids, infos, new_weights);
return true;
}
/** Generates a list of `cycle_ids` by following `outgoing` edges from the
`start`.
@param[in,out] cycle_ids will contain the list of ids on cycle
@param[in] start the first id on the cycle
@param[in] outgoing the ids of edge endpoints: id -> outgoing[id] */
static void lock_wait_extract_cycle_ids(ut::vector<uint> &cycle_ids,
const uint start,
const ut::vector<int> &outgoing) {
cycle_ids.clear();
uint id = start;
do {
cycle_ids.push_back(id);
id = outgoing[id];
} while (id != start);
}
/** Assuming that `infos` contains information about all waiting transactions,
and `outgoing[i]` is the endpoint of wait-for edge going out of infos[i].trx,
or -1 if the transaction is not waiting, it identifies and handles all cycles
in the wait-for graph
@param[in] infos Information about all waiting transactions
@param[in] outgoing The ids of edge endpoints. If outgoing[id] == -1,
then there is no edge going out of id, otherwise
infos[id].trx waits for infos[outgoing[id]].trx
@param[in,out] new_weights schedule weights of transactions computed for all
transactions except those which are on a cycle.
In case we find a real deadlock cycle, and decide
to rollback one of transactions, this function
will update the new_weights entries for
transactions involved in this cycle (as it will
unfold to a path, and schedule weight can be thus
computed) */
static void lock_wait_find_and_handle_deadlocks(
const ut::vector<waiting_trx_info_t> &infos,
const ut::vector<int> &outgoing,
ut::vector<trx_schedule_weight_t> &new_weights) {
ut_ad(infos.size() == new_weights.size());
ut_ad(infos.size() == outgoing.size());
/** We are going to use int and uint to store positions within infos */
ut_ad(infos.size() < std::numeric_limits<uint>::max());
const auto n = static_cast<uint>(infos.size());
ut_ad(n < static_cast<uint>(std::numeric_limits<int>::max()));
ut::vector<uint> cycle_ids;
cycle_ids.clear();
ut::vector<uint> colors;
colors.clear();
colors.resize(n, 0);
uint current_color = 0;
for (uint start = 0; start < n; ++start) {
if (colors[start] != 0) {
/* This node was already fully processed*/
continue;
}
++current_color;
for (int id = start; 0 <= id; id = outgoing[id]) {
/* We don't expect transaction to deadlock with itself only
and we do not handle cycles of length=1 correctly */
ut_ad(id != outgoing[id]);
if (colors[id] == 0) {
/* This node was never visited yet */
colors[id] = current_color;
continue;
}
/* This node was already visited:
- either it has current_color which means we've visited it during current
DFS descend, which means we have found a cycle, which we need to verify,
- or, it has a color used in a previous DFS which means that current DFS
path merges into an already processed portion of wait-for graph, so we
can stop now */
if (colors[id] == current_color) {
/* found a candidate cycle! */
lock_wait_extract_cycle_ids(cycle_ids, id, outgoing);
if (lock_wait_check_candidate_cycle(cycle_ids, infos, new_weights)) {
MONITOR_INC(MONITOR_DEADLOCK);
} else {
MONITOR_INC(MONITOR_DEADLOCK_FALSE_POSITIVES);
}
}
break;
}
}
MONITOR_INC(MONITOR_DEADLOCK_ROUNDS);
MONITOR_SET(MONITOR_LOCK_THREADS_WAITING, n);
}
/** Computes the number of incoming edges for each node of a given graph, in
which each node has zero or one outgoing edge.
@param[in] outgoing The ids of edge endpoints. If outgoing[id] == -1,
then there is no edge going out of id, otherwise
there is an edge from id to outgoing[id].
@param[out] incoming_count The place to store the results. After the call the
incoming_count[id] will be the number of edges
ending in id.
*/
static void lock_wait_compute_incoming_count(const ut::vector<int> &outgoing,
ut::vector<uint> &incoming_count) {
incoming_count.clear();
const size_t n = outgoing.size();
incoming_count.resize(n, 0);
for (size_t id = 0; id < n; ++id) {
const auto to = outgoing[id];
if (to != -1) {
incoming_count[to]++;
}
}
}
/** Given the `infos` snapshot about transactions, the value of
lock_wait_table_reservations before taking the snapshot and the edges of the
wait-for-graph relation between the transactions in the snapshot, computes the
schedule weight for each transaction, which is the sum of initial weight of the
transaction and all transactions that are blocked by it. This definition does
not apply to transactions on deadlock cycles, thus this function will not
compute the final schedule weight for transactions on the cycle, but rather
leave it as the partial sum of the tree rooted at the transaction hanging off
the cycle.
@param[in] infos Information about all waiting transactions
@param[in] table_reservations value of lock_wait_table_reservations at
before taking the `infos`snapshot
@param[in] outgoing The ids of edge endpoints.
If outgoing[id] == -1, then there is no edge
going out of id, otherwise infos[id].trx
waits for infos[outgoing[id]].trx
@param[out] new_weights schedule weights of transactions computed
for all transactions except those which are
on a cycle. For those on cycle we only
compute the partial sum of the weights in
the tree hanging off the cycle.
*/
static void lock_wait_compute_and_publish_weights_except_cycles(
const ut::vector<waiting_trx_info_t> &infos,
const uint64_t table_reservations, const ut::vector<int> &outgoing,
ut::vector<trx_schedule_weight_t> &new_weights) {
lock_wait_compute_initial_weights(infos, table_reservations, new_weights);
ut::vector<uint> incoming_count;
lock_wait_compute_incoming_count(outgoing, incoming_count);
lock_wait_accumulate_weights(incoming_count, new_weights, outgoing);
/* We don't update trx->lock.schedule_weight for trx on a cycle */
lock_wait_publish_new_weights(incoming_count, infos, new_weights);
MONITOR_INC(MONITOR_SCHEDULE_REFRESHES);
}
/** Takes a snapshot of transactions in waiting currently in slots, updates
their schedule weights, searches for deadlocks among them and resolves them. */
static void lock_wait_update_schedule_and_check_for_deadlocks() {
/*
Note: I was tempted to declare `infos` as `static`, or at least
declare it in lock_wait_timeout_thread() and reuse the same instance
over and over again to avoid allocator calls caused by push_back()
calls inside lock_wait_snapshot_waiting_threads() while we hold
lock_sys->lock_wait_mutex. I was afraid, that allocator might need
to block on some internal mutex in order to synchronize with other
threads using allocator, and this could in turn cause contention on
lock_wait_mutex. I hoped, that since vectors never shrink,
and only grow, then keeping a single instance of `infos` alive for the whole
lifetime of the thread should increase performance, because after some
initial period of growing, the allocations will never have to occur again.
But, I've run many many various experiments, with/without static,
with infos declared outside, with reserve(n) using various values of n
(128, srv_max_n_threads, even a simple ML predictor), and nothing, NOTHING
was faster than just using local vector as we do here (at least on
tetra01, tetra02, when comparing ~70 runs of each algorithm on uniform,
pareto, 128 and 1024 usrs).
This was counter-intuitive to me, so I've checked how malloc is implemented
and it turns out that modern malloc is a variant of ptmalloc2 and uses a
large number of independent arenas (larger than number of threads), and
various smart heuristics to map threads to these arenas in a way which
avoids blocking.
So, before changing the way we handle allocation of memory in these
lock_wait_* routines, please, PLEASE, first check empirically if it really
helps by running many tests and checking for statistical significance,
as variance seems to be large.
(And the downside of using `static` is that it is not very obvious
how our custom deallocator, which tries to update some stats, would
behave during shutdown).
Anyway, in case some tests will indicate that taking a snapshot is a
bottleneck, one can check if declaring this vectors as static solves the
issue.
*/
ut::vector<waiting_trx_info_t> infos;
ut::vector<int> outgoing;
ut::vector<trx_schedule_weight_t> new_weights;
auto table_reservations = lock_wait_snapshot_waiting_threads(infos);
lock_wait_build_wait_for_graph(infos, outgoing);
/* We don't update trx->lock.schedule_weight for trxs on cycles. */
lock_wait_compute_and_publish_weights_except_cycles(infos, table_reservations,
outgoing, new_weights);
if (innobase_deadlock_detect) {
/* This will also update trx->lock.schedule_weight for trxs on cycles. */
lock_wait_find_and_handle_deadlocks(infos, outgoing, new_weights);
}
}
/** A thread which wakes up threads whose lock wait may have lasted too long,
analyzes wait-for-graph changes, checks for deadlocks and resolves them, and
updates schedule weights. */
void lock_wait_timeout_thread() {
int64_t sig_count = 0;
os_event_t event = lock_sys->timeout_event;
ut_ad(!srv_read_only_mode);
/** The last time we've checked for timeouts. */
auto last_checked_for_timeouts_at = ut_time();
do {
auto now = ut_time();
if (0.5 < ut_difftime(now, last_checked_for_timeouts_at)) {
last_checked_for_timeouts_at = now;
lock_wait_check_slots_for_timeouts();
}
lock_wait_update_schedule_and_check_for_deadlocks();
/* When someone is waiting for a lock, we wake up every second (at worst)
and check if a timeout has passed for a lock wait */
os_event_wait_time_low(event, 1000000, sig_count);
sig_count = os_event_reset(event);
} while (srv_shutdown_state.load() < SRV_SHUTDOWN_CLEANUP);
}
| 43.962121 | 80 | 0.702709 | [
"object",
"vector"
] |
104e48bd0f0228c36e75812cd893b605cb6a30f1 | 34,175 | cpp | C++ | src/tools/imgtool/modules/os9.cpp | Robbbert/messui | 49b756e2140d8831bc81335298ee8c5471045e79 | [
"BSD-3-Clause"
] | 26 | 2015-03-31T06:25:51.000Z | 2021-12-14T09:29:04.000Z | src/tools/imgtool/modules/os9.cpp | Robbbert/messui | 49b756e2140d8831bc81335298ee8c5471045e79 | [
"BSD-3-Clause"
] | null | null | null | src/tools/imgtool/modules/os9.cpp | Robbbert/messui | 49b756e2140d8831bc81335298ee8c5471045e79 | [
"BSD-3-Clause"
] | 10 | 2015-03-27T05:45:51.000Z | 2022-02-04T06:57:36.000Z | // license:BSD-3-Clause
// copyright-holders:Nathan Woods
/****************************************************************************
os9.cpp
CoCo OS-9 disk images
****************************************************************************/
#include "imgtool.h"
#include "iflopimg.h"
#include "formats/imageutl.h"
#include "formats/coco_dsk.h"
#include "opresolv.h"
#include <cstdio>
#include <ctime>
enum creation_policy_t
{
CREATE_NONE,
CREATE_FILE,
CREATE_DIR
};
struct os9_diskinfo
{
uint32_t total_sectors;
uint32_t sectors_per_track;
uint32_t allocation_bitmap_bytes;
uint32_t cluster_size;
uint32_t root_dir_lsn;
uint32_t owner_id;
uint32_t attributes;
uint32_t disk_id;
uint32_t format_flags;
uint32_t bootstrap_lsn;
uint32_t bootstrap_size;
uint32_t sector_size;
unsigned int sides : 2;
unsigned int double_density : 1;
unsigned int double_track : 1;
unsigned int quad_track_density : 1;
unsigned int octal_track_density : 1;
char name[33];
uint8_t allocation_bitmap[65536];
};
struct os9_fileinfo
{
unsigned int directory : 1;
unsigned int non_sharable : 1;
unsigned int public_execute : 1;
unsigned int public_write : 1;
unsigned int public_read : 1;
unsigned int user_execute : 1;
unsigned int user_write : 1;
unsigned int user_read : 1;
uint32_t lsn;
uint32_t owner_id;
uint32_t link_count;
uint32_t file_size;
struct
{
uint32_t lsn;
uint32_t count;
} sector_map[48];
};
struct os9_direnum
{
struct os9_fileinfo dir_info;
uint32_t index;
};
static void pick_string(const void *ptr, size_t offset, size_t length, char *dest)
{
uint8_t b;
while(length--)
{
b = ((uint8_t *) ptr)[offset++];
*(dest++) = b & 0x7F;
if (b & 0x80)
length = 0;
}
*dest = '\0';
}
static void place_string(void *ptr, size_t offset, size_t length, const char *s)
{
size_t i;
uint8_t b;
uint8_t *bptr;
bptr = (uint8_t *) ptr;
bptr += offset;
bptr[0] = 0x80;
for (i = 0; s[i] && (i < length); i++)
{
b = ((uint8_t) s[i]) & 0x7F;
if (s[i+1] == '\0')
b |= 0x80;
bptr[i] = b;
}
}
static os9_diskinfo *os9_get_diskinfo(imgtool::image &image)
{
return (os9_diskinfo *) imgtool_floppy_extrabytes(image);
}
static struct os9_direnum *os9_get_dirinfo(imgtool::directory &directory)
{
return (struct os9_direnum *) directory.extra_bytes();
}
static imgtoolerr_t os9_locate_lsn(imgtool::image &image, uint32_t lsn, uint32_t *head, uint32_t *track, uint32_t *sector)
{
const os9_diskinfo *disk_info;
disk_info = os9_get_diskinfo(image);
if (lsn > disk_info->total_sectors)
return IMGTOOLERR_CORRUPTIMAGE;
*track = lsn / (disk_info->sectors_per_track * disk_info->sides);
*head = (lsn / disk_info->sectors_per_track) % disk_info->sides;
*sector = (lsn % disk_info->sectors_per_track) + 1;
return IMGTOOLERR_SUCCESS;
}
static imgtoolerr_t os9_read_lsn(imgtool::image &img, uint32_t lsn, int offset, void *buffer, size_t buffer_len)
{
imgtoolerr_t err;
floperr_t ferr;
uint32_t head, track, sector;
err = os9_locate_lsn(img, lsn, &head, &track, §or);
if (err)
return err;
ferr = floppy_read_sector(imgtool_floppy(img), head, track, sector, offset, buffer, buffer_len);
if (ferr)
return imgtool_floppy_error(ferr);
return IMGTOOLERR_SUCCESS;
}
static imgtoolerr_t os9_write_lsn(imgtool::image &img, uint32_t lsn, int offset, const void *buffer, size_t buffer_len)
{
imgtoolerr_t err;
floperr_t ferr;
uint32_t head, track, sector;
err = os9_locate_lsn(img, lsn, &head, &track, §or);
if (err)
return err;
ferr = floppy_write_sector(imgtool_floppy(img), head, track, sector, offset, buffer, buffer_len, 0); /* TODO: pass ddam argument from imgtool */
if (ferr)
return imgtool_floppy_error(ferr);
return IMGTOOLERR_SUCCESS;
}
static uint32_t os9_lookup_lsn(imgtool::image &img,
const struct os9_fileinfo *file_info, uint32_t *index)
{
int i;
uint32_t lsn;
const os9_diskinfo *disk_info;
disk_info = os9_get_diskinfo(img);
lsn = *index / disk_info->sector_size;
i = 0;
while(lsn >= file_info->sector_map[i].count)
lsn -= file_info->sector_map[i++].count;
lsn = file_info->sector_map[i].lsn + lsn;
*index %= disk_info->sector_size;
return lsn;
}
static int os9_interpret_dirent(void *entry, char **filename, uint32_t *lsn, int *corrupt)
{
int i;
char *entry_b = (char *) entry;
*filename = NULL;
*lsn = 0;
if (corrupt)
*corrupt = false;
if (entry_b[28] != '\0')
{
if (corrupt)
*corrupt = true;
}
for (i = 0; (i < 28) && !(entry_b[i] & 0x80); i++)
;
entry_b[i] &= 0x7F;
entry_b[i+1] = '\0';
*lsn = pick_integer_be(entry, 29, 3);
if (strcmp(entry_b, ".") && strcmp(entry_b, ".."))
*filename = entry_b;
return *filename != NULL;
}
/*-------------------------------------------------
os9_decode_file_header - reads a file/directory
entry from an LSN, and decodes it
-------------------------------------------------*/
static imgtoolerr_t os9_decode_file_header(imgtool::image &image,
int lsn, struct os9_fileinfo *info)
{
imgtoolerr_t err;
uint32_t attributes, count;
int max_entries, i;
const os9_diskinfo *disk_info;
uint8_t header[256];
disk_info = os9_get_diskinfo(image);
err = os9_read_lsn(image, lsn, 0, header, sizeof(header));
if (err)
return err;
info->lsn = lsn;
attributes = pick_integer_be(header, 0, 1);
info->owner_id = pick_integer_be(header, 1, 2);
info->link_count = pick_integer_be(header, 8, 1);
info->file_size = pick_integer_be(header, 9, 4);
info->directory = (attributes & 0x80) ? 1 : 0;
info->non_sharable = (attributes & 0x40) ? 1 : 0;
info->public_execute = (attributes & 0x20) ? 1 : 0;
info->public_write = (attributes & 0x10) ? 1 : 0;
info->public_read = (attributes & 0x08) ? 1 : 0;
info->user_execute = (attributes & 0x04) ? 1 : 0;
info->user_write = (attributes & 0x02) ? 1 : 0;
info->user_read = (attributes & 0x01) ? 1 : 0;
if (info->directory && (info->file_size % 32 != 0))
return IMGTOOLERR_CORRUPTIMAGE;
/* read all sector map entries */
max_entries = (disk_info->sector_size - 16) / 5;
max_entries = (std::min<std::size_t>)(max_entries, std::size(info->sector_map) - 1);
for (i = 0; i < max_entries; i++)
{
lsn = pick_integer_be(header, 16 + (i * 5) + 0, 3);
count = pick_integer_be(header, 16 + (i * 5) + 3, 2);
if (count <= 0)
break;
info->sector_map[i].lsn = lsn;
info->sector_map[i].count = count;
}
info->sector_map[i].lsn = 0;
info->sector_map[i].count = 0;
return IMGTOOLERR_SUCCESS;
}
static imgtoolerr_t os9_allocate_lsn(imgtool::image &image, uint32_t *lsn)
{
uint32_t i;
os9_diskinfo *disk_info;
uint8_t b, mask;
disk_info = os9_get_diskinfo(image);
for (i = 0; i < disk_info->total_sectors; i++)
{
b = disk_info->allocation_bitmap[i / 8];
mask = 1 << (7 - (i % 8));
if ((b & mask) == 0)
{
disk_info->allocation_bitmap[i / 8] |= mask;
*lsn = i;
return os9_write_lsn(image, 1, 0, disk_info->allocation_bitmap, disk_info->allocation_bitmap_bytes);
}
}
return IMGTOOLERR_NOSPACE;
}
static imgtoolerr_t os9_deallocate_lsn(imgtool::image &image, uint32_t lsn)
{
uint8_t mask;
os9_diskinfo *disk_info;
disk_info = os9_get_diskinfo(image);
mask = 1 << (7 - (lsn % 8));
disk_info->allocation_bitmap[lsn / 8] &= ~mask;
return os9_write_lsn(image, 1, 0, disk_info->allocation_bitmap, disk_info->allocation_bitmap_bytes);
}
static uint32_t os9_get_free_lsns(imgtool::image &image)
{
const os9_diskinfo *disk_info;
uint32_t i, free_lsns;
uint8_t b;
disk_info = os9_get_diskinfo(image);
free_lsns = 0;
for (i = 0; i < disk_info->total_sectors; i++)
{
b = disk_info->allocation_bitmap[i / 8];
b >>= (7 - (i % 8));
free_lsns += ~b & 1;
}
return free_lsns;
}
static imgtoolerr_t os9_corrupt_file_error(const struct os9_fileinfo *file_info)
{
imgtoolerr_t err;
if (file_info->directory)
err = IMGTOOLERR_CORRUPTDIR;
else
err = IMGTOOLERR_CORRUPTFILE;
return err;
}
static imgtoolerr_t os9_set_file_size(imgtool::image &image,
struct os9_fileinfo *file_info, uint32_t new_size)
{
imgtoolerr_t err;
const os9_diskinfo *disk_info;
uint32_t new_lsn_count, current_lsn_count;
uint32_t free_lsns, lsn, i;
int sector_map_length = -1;
uint8_t header[256];
/* easy way out? */
if (file_info->file_size == new_size)
return IMGTOOLERR_SUCCESS;
disk_info = os9_get_diskinfo(image);
free_lsns = os9_get_free_lsns(image);
current_lsn_count = (file_info->file_size + disk_info->sector_size - 1) / disk_info->sector_size;
new_lsn_count = (new_size + disk_info->sector_size - 1) / disk_info->sector_size;
/* check to see if the file is growing and we do not have enough space */
if ((new_lsn_count > current_lsn_count) && (new_lsn_count - current_lsn_count > free_lsns))
return IMGTOOLERR_NOSPACE;
if (current_lsn_count != new_lsn_count)
{
/* first find out the size of our sector map */
sector_map_length = 0;
lsn = 0;
while((lsn < current_lsn_count) && (sector_map_length < std::size(file_info->sector_map)))
{
if (file_info->sector_map[sector_map_length].count == 0)
return os9_corrupt_file_error(file_info);
lsn += file_info->sector_map[sector_map_length].count;
sector_map_length++;
}
/* keep in mind that the sector_map might not parallel our expected
* current LSN count; we should tolerate this abnormality */
current_lsn_count = lsn;
while(current_lsn_count > new_lsn_count)
{
/* shrink this file */
lsn = file_info->sector_map[sector_map_length - 1].lsn +
file_info->sector_map[sector_map_length - 1].count - 1;
err = os9_deallocate_lsn(image, lsn);
if (err)
return err;
file_info->sector_map[sector_map_length - 1].count--;
while(sector_map_length > 0 && (file_info->sector_map[sector_map_length - 1].count == 0))
sector_map_length--;
current_lsn_count--;
}
while(current_lsn_count < new_lsn_count)
{
/* grow this file */
err = os9_allocate_lsn(image, &lsn);
if (err)
return err;
if ((sector_map_length > 0) && ((file_info->sector_map[sector_map_length - 1].lsn +
file_info->sector_map[sector_map_length - 1].count) == lsn))
{
file_info->sector_map[sector_map_length - 1].count++;
}
else if (sector_map_length >= std::size(file_info->sector_map))
{
return IMGTOOLERR_NOSPACE;
}
else
{
file_info->sector_map[sector_map_length].lsn = lsn;
file_info->sector_map[sector_map_length].count = 1;
sector_map_length++;
file_info->sector_map[sector_map_length].lsn = 0;
file_info->sector_map[sector_map_length].count = 0;
}
current_lsn_count++;
}
}
/* now lets write back the sector */
err = os9_read_lsn(image, file_info->lsn, 0, header, sizeof(header));
if (err)
return err;
file_info->file_size = new_size;
place_integer_be(header, 9, 4, file_info->file_size);
/* do we have to write the sector map? */
if (sector_map_length >= 0)
{
for (i = 0; i < (std::min<std::size_t>)(sector_map_length + 1, std::size(file_info->sector_map)); i++)
{
place_integer_be(header, 16 + (i * 5) + 0, 3, file_info->sector_map[i].lsn);
place_integer_be(header, 16 + (i * 5) + 3, 2, file_info->sector_map[i].count);
}
}
err = os9_write_lsn(image, file_info->lsn, 0, header, disk_info->sector_size);
if (err)
return err;
return IMGTOOLERR_SUCCESS;
}
/*-------------------------------------------------
os9_lookup_path - walks an OS-9 directory
structure to find a file, or optionally, create
a file
-------------------------------------------------*/
static imgtoolerr_t os9_lookup_path(imgtool::image &img, const char *path,
creation_policy_t create, struct os9_fileinfo *file_info,
uint32_t *parent_lsn, uint32_t *dirent_lsn, uint32_t *dirent_index)
{
imgtoolerr_t err = IMGTOOLERR_SUCCESS;
struct os9_fileinfo dir_info;
uint32_t index, current_lsn, dir_size;
uint32_t entry_index = 0;
uint32_t free_entry_index = 0xffffffff;
uint32_t entry_lsn = 0;
uint32_t allocated_lsn = 0;
uint8_t entry[32];
uint8_t block[64];
char *filename;
const os9_diskinfo *disk_info;
disk_info = os9_get_diskinfo(img);
current_lsn = disk_info->root_dir_lsn;
if (parent_lsn)
*parent_lsn = 0;
/* we have to transverse each path element */
while(*path)
{
if (parent_lsn)
*parent_lsn = current_lsn;
/* decode the directory header of this directory */
err = os9_decode_file_header(img, current_lsn, &dir_info);
if (err)
goto done;
dir_size = dir_info.file_size;
/* sanity check directory */
if (!dir_info.directory)
{
err = (current_lsn == disk_info->root_dir_lsn) ? IMGTOOLERR_CORRUPTIMAGE : IMGTOOLERR_INVALIDPATH;
goto done;
}
/* walk the directory */
for (index = 0; index < dir_size; index += 32)
{
entry_index = index;
entry_lsn = os9_lookup_lsn(img, &dir_info, &entry_index);
err = os9_read_lsn(img, entry_lsn, entry_index, entry, sizeof(entry));
if (err)
goto done;
/* remember first free entry found */
if( free_entry_index == 0xffffffff )
{
if( entry[0] == 0 )
free_entry_index = index;
}
if (os9_interpret_dirent(entry, &filename, ¤t_lsn, NULL))
{
if (!strcmp(path, filename))
break;
}
}
/* at the end of the file? */
if (index >= dir_size)
{
/* if we're not creating, or we are creating but we have not fully
* transversed the directory, error out */
if (!create || path[strlen(path) + 1])
{
err = IMGTOOLERR_PATHNOTFOUND;
goto done;
}
/* allocate a new LSN */
err = os9_allocate_lsn(img, &allocated_lsn);
if (err)
goto done;
/* write the file */
memset(block, 0, sizeof(block));
place_integer_be(block, 0, 1, 0x1B | ((create == CREATE_DIR) ? 0x80 : 0x00));
err = os9_write_lsn(img, allocated_lsn, 0, block, sizeof(block));
if (err)
goto done;
if( free_entry_index == 0xffffffff )
{
/* expand the directory to hold the new entry */
err = os9_set_file_size(img, &dir_info, dir_size + 32);
if (err)
goto done;
}
else
/* use first unused entry in directory */
dir_size = free_entry_index;
/* now prepare the directory entry */
memset(entry, 0, sizeof(entry));
place_string(entry, 0, 28, path);
place_integer_be(entry, 29, 3, allocated_lsn);
/* now write the directory entry */
entry_index = dir_size;
entry_lsn = os9_lookup_lsn(img, &dir_info, &entry_index);
err = os9_write_lsn(img, entry_lsn, entry_index, entry, 32);
if (err)
goto done;
/* directory entry append complete; no need to hold this lsn */
current_lsn = allocated_lsn;
allocated_lsn = 0;
}
path += strlen(path) + 1;
}
if (file_info)
{
err = os9_decode_file_header(img, current_lsn, file_info);
if (err)
goto done;
}
if (dirent_lsn)
*dirent_lsn = entry_lsn;
if (dirent_index)
*dirent_index = entry_index;
done:
if (allocated_lsn != 0)
os9_deallocate_lsn(img, allocated_lsn);
return err;
}
static imgtoolerr_t os9_diskimage_open(imgtool::image &image, imgtool::stream::ptr &&dummy)
{
imgtoolerr_t err;
floperr_t ferr;
os9_diskinfo *info;
uint32_t track_size_in_sectors, i; //, attributes;
uint8_t header[256];
uint32_t allocation_bitmap_lsns;
uint8_t b, mask;
info = os9_get_diskinfo(image);
ferr = floppy_read_sector(imgtool_floppy(image), 0, 0, 1, 0, header, sizeof(header));
if (ferr)
return imgtool_floppy_error(ferr);
info->total_sectors = pick_integer_be(header, 0, 3);
track_size_in_sectors = pick_integer_be(header, 3, 1);
info->allocation_bitmap_bytes = pick_integer_be(header, 4, 2);
info->cluster_size = pick_integer_be(header, 6, 2);
info->root_dir_lsn = pick_integer_be(header, 8, 3);
info->owner_id = pick_integer_be(header, 11, 2);
// attributes =
pick_integer_be(header, 13, 1);
info->disk_id = pick_integer_be(header, 14, 2);
info->format_flags = pick_integer_be(header, 16, 1);
info->sectors_per_track = pick_integer_be(header, 17, 2);
info->bootstrap_lsn = pick_integer_be(header, 21, 3);
info->bootstrap_size = pick_integer_be(header, 24, 2);
info->sector_size = pick_integer_be(header, 104, 2);
info->sides = (info->format_flags & 0x01) ? 2 : 1;
info->double_density = (info->format_flags & 0x02) ? 1 : 0;
info->double_track = (info->format_flags & 0x04) ? 1 : 0;
info->quad_track_density = (info->format_flags & 0x08) ? 1 : 0;
info->octal_track_density = (info->format_flags & 0x10) ? 1 : 0;
pick_string(header, 31, 32, info->name);
if (info->sector_size == 0)
info->sector_size = 256;
/* does the root directory and allocation bitmap collide? */
allocation_bitmap_lsns = (info->allocation_bitmap_bytes + info->sector_size - 1) / info->sector_size;
if (1 + allocation_bitmap_lsns > info->root_dir_lsn)
return IMGTOOLERR_CORRUPTIMAGE;
/* is the allocation bitmap too big? */
memset(&info->allocation_bitmap[0], 0, info->allocation_bitmap_bytes);
/* sectors per track and track size don't jive? */
if (info->sectors_per_track != track_size_in_sectors)
return IMGTOOLERR_CORRUPTIMAGE;
/* zero sectors per track? */
if (info->sectors_per_track == 0)
return IMGTOOLERR_CORRUPTIMAGE;
/* do we have an odd number of sectors? */
if (info->total_sectors % info->sectors_per_track)
return IMGTOOLERR_CORRUPTIMAGE;
/* read the allocation bitmap */
for (i = 0; i < allocation_bitmap_lsns; i++)
{
err = os9_read_lsn(image, 1 + i, 0, &info->allocation_bitmap[i * info->sector_size],
std::min(info->allocation_bitmap_bytes - (i * info->sector_size), info->sector_size));
if (err)
return err;
}
/* check to make sure that the allocation bitmap and root sector are reserved */
for (i = 0; i <= allocation_bitmap_lsns; i++)
{
b = info->allocation_bitmap[i / 8];
mask = 1 << (7 - (i % 8));
if ((b & mask) == 0)
return IMGTOOLERR_CORRUPTIMAGE;
}
return IMGTOOLERR_SUCCESS;
}
static imgtoolerr_t os9_diskimage_create(imgtool::image &img, imgtool::stream::ptr &&stream, util::option_resolution *opts)
{
imgtoolerr_t err;
std::vector<uint8_t> header;
uint32_t heads, tracks, sectors, sector_bytes, first_sector_id;
uint32_t cluster_size, owner_id;
uint32_t allocation_bitmap_bits, allocation_bitmap_lsns;
uint32_t attributes, format_flags, disk_id;
uint32_t i;
int32_t total_allocated_sectors;
const char *title;
time_t t;
struct tm *ltime;
time(&t);
ltime = localtime(&t);
heads = opts->lookup_int('H');
tracks = opts->lookup_int('T');
sectors = opts->lookup_int('S');
sector_bytes = opts->lookup_int('L');
first_sector_id = opts->lookup_int('F');
title = "";
header.resize(sector_bytes);
if (sector_bytes > 256)
sector_bytes = 256;
cluster_size = 1;
owner_id = 1;
disk_id = 1;
attributes = 0;
allocation_bitmap_bits = heads * tracks * sectors / cluster_size;
allocation_bitmap_lsns = (allocation_bitmap_bits / 8 + sector_bytes - 1) / sector_bytes;
format_flags = ((heads > 1) ? 0x01 : 0x00) | ((tracks > 40) ? 0x02 : 0x00);
memset(&header[0], 0, sector_bytes);
place_integer_be(&header[0], 0, 3, heads * tracks * sectors);
place_integer_be(&header[0], 3, 1, sectors);
place_integer_be(&header[0], 4, 2, (allocation_bitmap_bits + 7) / 8);
place_integer_be(&header[0], 6, 2, cluster_size);
place_integer_be(&header[0], 8, 3, 1 + allocation_bitmap_lsns);
place_integer_be(&header[0], 11, 2, owner_id);
place_integer_be(&header[0], 13, 1, attributes);
place_integer_be(&header[0], 14, 2, disk_id);
place_integer_be(&header[0], 16, 1, format_flags);
place_integer_be(&header[0], 17, 2, sectors);
place_string(&header[0], 31, 32, title);
place_integer_be(&header[0], 103, 2, sector_bytes / 256);
/* path descriptor options */
place_integer_be(&header[0], 0x3f+0x00, 1, 1); /* device class */
place_integer_be(&header[0], 0x3f+0x01, 1, 1); /* drive number */
place_integer_be(&header[0], 0x3f+0x03, 1, 0x20); /* device type */
place_integer_be(&header[0], 0x3f+0x04, 1, 1); /* density capability */
place_integer_be(&header[0], 0x3f+0x05, 2, tracks); /* number of tracks */
place_integer_be(&header[0], 0x3f+0x07, 1, heads); /* number of sides */
place_integer_be(&header[0], 0x3f+0x09, 2, sectors); /* sectors per track */
place_integer_be(&header[0], 0x3f+0x0b, 2, sectors); /* sectors on track zero */
place_integer_be(&header[0], 0x3f+0x0d, 1, 3); /* sector interleave factor */
place_integer_be(&header[0], 0x3f+0x0e, 1, 8); /* default sectors per allocation */
err = (imgtoolerr_t)floppy_write_sector(imgtool_floppy(img), 0, 0, first_sector_id, 0, &header[0], sector_bytes, 0); /* TODO: pass ddam argument from imgtool */
if (err)
goto done;
total_allocated_sectors = 1 + allocation_bitmap_lsns + 1 + 7;
for (i = 0; i < allocation_bitmap_lsns; i++)
{
memset(&header[0], 0x00, sector_bytes);
if (total_allocated_sectors > (8 * 256))
{
memset(&header[0], 0xff, sector_bytes);
total_allocated_sectors -= (8 * 256);
}
else if (total_allocated_sectors > 1 )
{
int offset;
uint8_t mask;
while( total_allocated_sectors >= 0 )
{
offset = total_allocated_sectors / 8;
mask = 1 << (7 - ( total_allocated_sectors % 8 ) );
header[offset] |= mask;
total_allocated_sectors--;
}
}
err = (imgtoolerr_t)floppy_write_sector(imgtool_floppy(img), 0, 0, first_sector_id + 1 + i, 0, &header[0], sector_bytes, 0); /* TODO: pass ddam argument from imgtool */
if (err)
goto done;
}
memset(&header[0], 0, sector_bytes);
header[0x00] = 0xBF;
header[0x01] = 0x00;
header[0x02] = 0x00;
header[0x03] = (uint8_t) ltime->tm_year;
header[0x04] = (uint8_t) ltime->tm_mon + 1;
header[0x05] = (uint8_t) ltime->tm_mday;
header[0x06] = (uint8_t) ltime->tm_hour;
header[0x07] = (uint8_t) ltime->tm_min;
header[0x08] = 0x02;
header[0x09] = 0x00;
header[0x0A] = 0x00;
header[0x0B] = 0x00;
header[0x0C] = 0x40;
header[0x0D] = (uint8_t) (ltime->tm_year % 100);
header[0x0E] = (uint8_t) ltime->tm_mon;
header[0x0F] = (uint8_t) ltime->tm_mday;
place_integer_be(&header[0], 0x10, 3, 1 + allocation_bitmap_lsns + 1);
place_integer_be(&header[0], 0x13, 2, 8);
err = (imgtoolerr_t)floppy_write_sector(imgtool_floppy(img), 0, 0, first_sector_id + 1 + allocation_bitmap_lsns, 0, &header[0], sector_bytes, 0); /* TODO: pass ddam argument from imgtool */
if (err)
goto done;
memset(&header[0], 0, sector_bytes);
header[0x00] = 0x2E;
header[0x01] = 0xAE;
header[0x1F] = 1 + allocation_bitmap_lsns;
header[0x20] = 0xAE;
header[0x3F] = 1 + allocation_bitmap_lsns;
err = (imgtoolerr_t)floppy_write_sector(imgtool_floppy(img), 0, 0, first_sector_id + 2 + allocation_bitmap_lsns, 0, &header[0], sector_bytes, 0); /* TOOD: pass ddam argument from imgtool */
if (err)
goto done;
done:
return err;
}
static imgtoolerr_t os9_diskimage_beginenum(imgtool::directory &enumeration, const char *path)
{
imgtoolerr_t err = IMGTOOLERR_SUCCESS;
struct os9_direnum *os9enum;
imgtool::image &image(enumeration.image());
os9enum = os9_get_dirinfo(enumeration);
err = os9_lookup_path(image, path, CREATE_NONE, &os9enum->dir_info, NULL, NULL, NULL);
if (err)
goto done;
/* this had better be a directory */
if (!os9enum->dir_info.directory)
{
err = IMGTOOLERR_CORRUPTIMAGE;
goto done;
}
done:
return err;
}
static imgtoolerr_t os9_diskimage_nextenum(imgtool::directory &enumeration, imgtool_dirent &ent)
{
struct os9_direnum *os9enum;
uint32_t lsn, index;
imgtoolerr_t err;
uint8_t dir_entry[32];
char filename[29];
struct os9_fileinfo file_info;
imgtool::image &image(enumeration.image());
os9enum = os9_get_dirinfo(enumeration);
do
{
/* check for EOF */
if (os9enum->index >= os9enum->dir_info.file_size)
{
ent.eof = 1;
return IMGTOOLERR_SUCCESS;
}
/* locate the LSN and offset for this directory entry */
index = os9enum->index;
lsn = os9_lookup_lsn(image, &os9enum->dir_info, &index);
/* read the directory entry out of the lSN */
err = os9_read_lsn(image, lsn, index, dir_entry, sizeof(dir_entry));
if (err)
return err;
if (dir_entry[0])
{
/* read the file or directory name */
pick_string(dir_entry, 0, 28, filename);
/* we have certain expectations of the directory contents; the
* first directory entry should be "..", the second ".", and
* subsequent entries should never be "." or ".." */
switch(os9enum->index)
{
case 0:
if (strcmp(filename, ".."))
imgtool_warn("First entry in directory should be \"..\" and not \"%s\"", filename);
break;
case 32:
if (strcmp(filename, "."))
imgtool_warn("Second entry in directory should be \".\" and not \"%s\"", filename);
break;
default:
if (!strcmp(filename, ".") || !strcmp(filename, ".."))
imgtool_warn("Directory entry %d should not be \"%s\"", index / 32, filename);
break;
}
/* if the filename is ".", the file should point to the current directory */
if (!strcmp(filename, ".") && (pick_integer_be(dir_entry, 29, 3) != os9enum->dir_info.lsn))
{
imgtool_warn("Directory \".\" does not point back to same directory");
}
}
else
{
/* no more directory entries */
filename[0] = '\0';
}
/* move on to the next directory entry */
os9enum->index += 32;
}
while(!filename[0] || !strcmp(filename, ".") || !strcmp(filename, ".."));
/* read file attributes */
lsn = pick_integer_be(dir_entry, 29, 3);
err = os9_decode_file_header(enumeration.image(), lsn, &file_info);
if (err)
return err;
/* fill out imgtool_dirent structure */
snprintf(ent.filename, std::size(ent.filename), "%s", filename);
snprintf(ent.attr, std::size(ent.attr), "%c%c%c%c%c%c%c%c",
file_info.directory ? 'd' : '-',
file_info.non_sharable ? 's' : '-',
file_info.public_execute ? 'x' : '-',
file_info.public_write ? 'w' : '-',
file_info.public_read ? 'r' : '-',
file_info.user_execute ? 'x' : '-',
file_info.user_write ? 'w' : '-',
file_info.user_read ? 'r' : '-');
ent.directory = file_info.directory;
ent.corrupt = (dir_entry[28] != 0);
ent.filesize = file_info.file_size;
return IMGTOOLERR_SUCCESS;
}
static imgtoolerr_t os9_diskimage_freespace(imgtool::partition &partition, uint64_t *size)
{
imgtool::image &image(partition.image());
const os9_diskinfo *disk_info;
uint32_t free_lsns;
disk_info = os9_get_diskinfo(image);
free_lsns = os9_get_free_lsns(image);
*size = free_lsns * disk_info->sector_size;
return IMGTOOLERR_SUCCESS;
}
static imgtoolerr_t os9_diskimage_readfile(imgtool::partition &partition, const char *filename, const char *fork, imgtool::stream &destf)
{
imgtoolerr_t err;
imgtool::image &img(partition.image());
const os9_diskinfo *disk_info;
struct os9_fileinfo file_info;
uint8_t buffer[256];
int i, j;
uint32_t file_size;
uint32_t used_size;
disk_info = os9_get_diskinfo(img);
err = os9_lookup_path(img, filename, CREATE_NONE, &file_info, NULL, NULL, NULL);
if (err)
return err;
if (file_info.directory)
return IMGTOOLERR_FILENOTFOUND;
file_size = file_info.file_size;
for (i = 0; file_info.sector_map[i].count > 0; i++)
{
for (j = 0; j < file_info.sector_map[i].count; j++)
{
used_size = std::min(file_size, disk_info->sector_size);
err = os9_read_lsn(img, file_info.sector_map[i].lsn + j, 0,
buffer, used_size);
if (err)
return err;
destf.write(buffer, used_size);
file_size -= used_size;
}
}
return IMGTOOLERR_SUCCESS;
}
static imgtoolerr_t os9_diskimage_writefile(imgtool::partition &partition, const char *path, const char *fork, imgtool::stream &sourcef, util::option_resolution *opts)
{
imgtoolerr_t err;
imgtool::image &image(partition.image());
struct os9_fileinfo file_info;
size_t write_size;
std::vector<uint8_t> buf;
int i = -1;
uint32_t lsn = 0;
uint32_t count = 0;
uint32_t sz;
const os9_diskinfo *disk_info;
disk_info = os9_get_diskinfo(image);
buf.resize(disk_info->sector_size);
err = os9_lookup_path(image, path, CREATE_FILE, &file_info, NULL, NULL, NULL);
if (err)
goto done;
sz = (uint32_t) sourcef.size();
err = os9_set_file_size(image, &file_info, sz);
if (err)
goto done;
while(sz > 0)
{
write_size = (std::min<uint64_t>)(sz, disk_info->sector_size);
sourcef.read(&buf[0], write_size);
while(count == 0)
{
i++;
lsn = file_info.sector_map[i].lsn;
count = file_info.sector_map[i].count;
}
err = os9_write_lsn(image, lsn, 0, &buf[0], write_size);
if (err)
goto done;
lsn++;
count--;
sz -= write_size;
}
done:
return err;
}
static imgtoolerr_t os9_diskimage_delete(imgtool::partition &partition, const char *path,
unsigned int delete_directory)
{
imgtoolerr_t err;
imgtool::image &image(partition.image());
struct os9_fileinfo file_info;
uint32_t dirent_lsn, dirent_index;
uint32_t entry_lsn, entry_index;
uint32_t i, j, lsn;
uint8_t b;
//disk_info = os9_get_diskinfo(image);
err = os9_lookup_path(image, path, CREATE_NONE, &file_info, NULL, &dirent_lsn, &dirent_index);
if (err)
return err;
if (file_info.directory != delete_directory)
return IMGTOOLERR_FILENOTFOUND;
/* make sure that if we are deleting a directory, it is empty */
if (delete_directory)
{
for (i = 64; i < file_info.file_size; i += 32)
{
entry_index = i;
entry_lsn = os9_lookup_lsn(image, &file_info, &entry_index);
err = os9_read_lsn(image, entry_lsn, entry_index, &b, 1);
if (err)
return err;
/* this had better be a deleted file, if not we can't delete */
if (b != 0)
return IMGTOOLERR_DIRNOTEMPTY;
}
}
/* zero out the file entry */
b = '\0';
err = os9_write_lsn(image, dirent_lsn, dirent_index, &b, 1);
if (err)
return err;
/* get the link count */
err = os9_read_lsn(image, file_info.lsn, 8, &b, 1);
if (err)
return err;
if (b > 0)
b--;
if (b > 0)
{
/* link count is greater than zero */
err = os9_write_lsn(image, file_info.lsn, 8, &b, 1);
if (err)
return err;
}
else
{
/* no more links; outright delete the file */
err = os9_deallocate_lsn(image, file_info.lsn);
if (err)
return err;
for (i = 0; (i < std::size(file_info.sector_map)) && file_info.sector_map[i].count; i++)
{
lsn = file_info.sector_map[i].lsn;
for (j = 0; j < file_info.sector_map[i].count; j++)
{
err = os9_deallocate_lsn(image, lsn + j);
if (err)
return err;
}
}
}
return IMGTOOLERR_SUCCESS;
}
static imgtoolerr_t os9_diskimage_deletefile(imgtool::partition &partition, const char *path)
{
return os9_diskimage_delete(partition, path, 0);
}
static imgtoolerr_t os9_diskimage_createdir(imgtool::partition &partition, const char *path)
{
imgtoolerr_t err;
imgtool::image &image(partition.image());
struct os9_fileinfo file_info;
uint8_t dir_data[64];
uint32_t parent_lsn;
err = os9_lookup_path(image, path, CREATE_DIR, &file_info, &parent_lsn, NULL, NULL);
if (err)
goto done;
err = os9_set_file_size(image, &file_info, 64);
if (err)
goto done;
/* create intial directories */
memset(dir_data, 0, sizeof(dir_data));
place_string(dir_data, 0, 32, "..");
place_integer_be(dir_data, 29, 3, parent_lsn);
place_string(dir_data, 32, 32, ".");
place_integer_be(dir_data, 61, 3, file_info.lsn);
err = os9_write_lsn(image, file_info.sector_map[0].lsn, 0, dir_data, sizeof(dir_data));
if (err)
goto done;
done:
return err;
}
static imgtoolerr_t os9_diskimage_deletedir(imgtool::partition &partition, const char *path)
{
return os9_diskimage_delete(partition, path, 1);
}
void os9_get_info(const imgtool_class *imgclass, uint32_t state, union imgtoolinfo *info)
{
switch(state)
{
/* --- the following bits of info are returned as 64-bit signed integers --- */
case IMGTOOLINFO_INT_INITIAL_PATH_SEPARATOR: info->i = 1; break;
case IMGTOOLINFO_INT_OPEN_IS_STRICT: info->i = 1; break;
case IMGTOOLINFO_INT_IMAGE_EXTRA_BYTES: info->i = sizeof(os9_diskinfo); break;
case IMGTOOLINFO_INT_DIRECTORY_EXTRA_BYTES: info->i = sizeof(struct os9_direnum); break;
case IMGTOOLINFO_INT_PATH_SEPARATOR: info->i = '/'; break;
/* --- the following bits of info are returned as NULL-terminated strings --- */
case IMGTOOLINFO_STR_NAME: strcpy(info->s = imgtool_temp_str(), "os9"); break;
case IMGTOOLINFO_STR_DESCRIPTION: strcpy(info->s = imgtool_temp_str(), "OS-9 format"); break;
case IMGTOOLINFO_STR_FILE: strcpy(info->s = imgtool_temp_str(), __FILE__); break;
case IMGTOOLINFO_STR_EOLN: strcpy(info->s = imgtool_temp_str(), "\r"); break;
/* --- the following bits of info are returned as pointers to data or functions --- */
case IMGTOOLINFO_PTR_MAKE_CLASS: info->make_class = imgtool_floppy_make_class; break;
case IMGTOOLINFO_PTR_FLOPPY_CREATE: info->create = os9_diskimage_create; break;
case IMGTOOLINFO_PTR_FLOPPY_OPEN: info->open = os9_diskimage_open; break;
case IMGTOOLINFO_PTR_BEGIN_ENUM: info->begin_enum = os9_diskimage_beginenum; break;
case IMGTOOLINFO_PTR_NEXT_ENUM: info->next_enum = os9_diskimage_nextenum; break;
case IMGTOOLINFO_PTR_FREE_SPACE: info->free_space = os9_diskimage_freespace; break;
case IMGTOOLINFO_PTR_READ_FILE: info->read_file = os9_diskimage_readfile; break;
case IMGTOOLINFO_PTR_WRITE_FILE: info->write_file = os9_diskimage_writefile; break;
case IMGTOOLINFO_PTR_DELETE_FILE: info->delete_file = os9_diskimage_deletefile; break;
case IMGTOOLINFO_PTR_CREATE_DIR: info->create_dir = os9_diskimage_createdir; break;
case IMGTOOLINFO_PTR_DELETE_DIR: info->delete_dir = os9_diskimage_deletedir; break;
case IMGTOOLINFO_PTR_FLOPPY_FORMAT: info->p = (void *) floppyoptions_coco; break;
}
}
| 27.516103 | 192 | 0.673182 | [
"vector"
] |
1050131ab3769182625f8a6e1b164f7bc6212e40 | 12,456 | cpp | C++ | xercesc/xerces-c1_7_0-SolForCC/samples/MemParse/MemParse.cpp | anjingbin/starccm | 70db48004aa20bbb82cc24de80802b40c7024eff | [
"BSD-3-Clause"
] | 2 | 2020-01-06T07:43:30.000Z | 2020-07-11T20:53:53.000Z | xercesc/xerces-c1_7_0-SolForCC/samples/MemParse/MemParse.cpp | anjingbin/starccm | 70db48004aa20bbb82cc24de80802b40c7024eff | [
"BSD-3-Clause"
] | null | null | null | xercesc/xerces-c1_7_0-SolForCC/samples/MemParse/MemParse.cpp | anjingbin/starccm | 70db48004aa20bbb82cc24de80802b40c7024eff | [
"BSD-3-Clause"
] | null | null | null | /*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2001 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache\@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation, and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/*
* $Log: MemParse.cpp,v $
* Revision 1.1 2004/07/13 02:38:10 WangKeBo
* Component implementation
*
* Revision 1.13 2002/02/01 22:37:14 peiyongz
* sane_include
*
* Revision 1.12 2001/10/25 15:18:33 tng
* delete the parser before XMLPlatformUtils::Terminate.
*
* Revision 1.11 2001/10/19 18:56:08 tng
* Pulled the hardcoded "encoding" out of the document itself and made it a #define
* to make it easier to support other encodings. Patch from David McCreedy.
* And other modification for consistent help display and return code across samples.
*
* Revision 1.10 2001/08/01 19:11:01 tng
* Add full schema constraint checking flag to the samples and the parser.
*
* Revision 1.9 2001/05/11 13:24:55 tng
* Copyright update.
*
* Revision 1.8 2001/05/03 15:59:40 tng
* Schema: samples update with schema
*
* Revision 1.7 2000/09/11 18:43:48 aruna1
* OS390 related updates
*
* Revision 1.6 2000/03/02 19:53:42 roddey
* This checkin includes many changes done while waiting for the
* 1.1.0 code to be finished. I can't list them all here, but a list is
* available elsewhere.
*
* Revision 1.5 2000/02/11 02:37:01 abagchi
* Removed StrX::transcode
*
* Revision 1.4 2000/02/06 07:47:19 rahulj
* Year 2K copyright swat.
*
* Revision 1.3 2000/01/12 00:27:00 roddey
* Updates to work with the new URL and input source scheme.
*
* Revision 1.2 1999/11/20 01:09:55 rahulj
* Fixed usage message.
*
* Revision 1.1.1.1 1999/11/09 01:09:49 twl
* Initial checkin
*
* Revision 1.7 1999/11/08 20:43:36 rahul
* Swat for adding in Product name and CVS comment log variable.
*
*/
/**
* This sample program illustrates how one can use a memory buffer as the
* input to parser. The memory buffer contains raw bytes representing XML
* statements.
*
* Look at the API documentation for 'MemBufInputSource' for more information
* on parameters to the constructor.
*
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <xercesc/parsers/SAXParser.hpp>
#include <xercesc/framework/MemBufInputSource.hpp>
#include "MemParse.hpp"
// ---------------------------------------------------------------------------
// Local const data
//
// gXMLInMemBuf
// Defines the memory buffer contents here which parsed by the XML
// parser. This is the cheap way to do it, instead of reading it from
// somewhere. For this demo, its fine.
//
// NOTE: If your encoding is not ascii you will need to change
// the MEMPARSE_ENCODING #define
//
// gMemBufId
// A simple name to give as the system id for the memory buffer. This
// just for indentification purposes in case of errors. Its not a real
// system id (and the parser knows that.)
// ---------------------------------------------------------------------------
#ifndef MEMPARSE_ENCODING
#if defined(OS390)
#define MEMPARSE_ENCODING "ibm-1047-s390"
#else
#define MEMPARSE_ENCODING "ascii"
#endif
#endif /* ifndef MEMPARSE_ENCODING */
static const char* gXMLInMemBuf =
"\
<?xml version='1.0' encoding='" MEMPARSE_ENCODING "'?>\n\
<!DOCTYPE company [\n\
<!ELEMENT company (product,category,developedAt)>\n\
<!ELEMENT product (#PCDATA)>\n\
<!ELEMENT category (#PCDATA)>\n\
<!ATTLIST category idea CDATA #IMPLIED>\n\
<!ELEMENT developedAt (#PCDATA)>\n\
]>\n\n\
<company>\n\
<product>XML4C</product>\n\
<category idea='great'>XML Parsing Tools</category>\n\
<developedAt>\n\
IBM Center for Java Technology, Silicon Valley, Cupertino, CA\n\
</developedAt>\n\
</company>\
";
static const char* gMemBufId = "prodInfo";
// ---------------------------------------------------------------------------
// Local helper methods
// ---------------------------------------------------------------------------
void usage()
{
cout << "\nUsage:\n"
" MemParse [options]\n\n"
"This program uses the SAX Parser to parse a memory buffer\n"
"containing XML statements, and reports the number of\n"
"elements and attributes found.\n\n"
"Options:\n"
" -v=xxx Validation scheme [always | never | auto*].\n"
" -n Enable namespace processing. Defaults to off.\n"
" -s Enable schema processing. Defaults to off.\n"
" -f Enable full schema constraint checking. Defaults to off.\n"
" -? Show this help.\n\n"
" * = Default if not provided explicitly.\n"
<< endl;
}
// ---------------------------------------------------------------------------
// Program entry point
// ---------------------------------------------------------------------------
int main(int argC, char* argV[])
{
// Initialize the XML4C2 system
try
{
XMLPlatformUtils::Initialize();
}
catch (const XMLException& toCatch)
{
cerr << "Error during initialization! Message:\n"
<< StrX(toCatch.getMessage()) << endl;
return 1;
}
SAXParser::ValSchemes valScheme = SAXParser::Val_Auto;
bool doNamespaces = false;
bool doSchema = false;
bool schemaFullChecking = false;
int argInd;
for (argInd = 1; argInd < argC; argInd++)
{
// Break out on first parm not starting with a dash
if (argV[argInd][0] != '-')
{
usage();
XMLPlatformUtils::Terminate();
return 1;
}
// Watch for special case help request
if (!strcmp(argV[argInd], "-?"))
{
usage();
XMLPlatformUtils::Terminate();
return 1;
}
else if (!strncmp(argV[argInd], "-v=", 3)
|| !strncmp(argV[argInd], "-V=", 3))
{
const char* const parm = &argV[argInd][3];
if (!strcmp(parm, "never"))
valScheme = SAXParser::Val_Never;
else if (!strcmp(parm, "auto"))
valScheme = SAXParser::Val_Auto;
else if (!strcmp(parm, "always"))
valScheme = SAXParser::Val_Always;
else
{
cerr << "Unknown -v= value: " << parm << endl;
return 2;
}
}
else if (!strcmp(argV[argInd], "-n")
|| !strcmp(argV[argInd], "-N"))
{
doNamespaces = true;
}
else if (!strcmp(argV[argInd], "-s")
|| !strcmp(argV[argInd], "-S"))
{
doSchema = true;
}
else if (!strcmp(argV[argInd], "-f")
|| !strcmp(argV[argInd], "-F"))
{
schemaFullChecking = true;
}
else
{
cerr << "Unknown option '" << argV[argInd]
<< "', ignoring it\n" << endl;
}
}
//
// Create a SAX parser object. Then, according to what we were told on
// the command line, set it to validate or not.
//
SAXParser* parser = new SAXParser;
parser->setValidationScheme(valScheme);
parser->setDoNamespaces(doNamespaces);
parser->setDoSchema(doSchema);
parser->setValidationSchemaFullChecking(schemaFullChecking);
//
// Create our SAX handler object and install it on the parser, as the
// document and error handlers.
//
MemParseHandlers handler;
parser->setDocumentHandler(&handler);
parser->setErrorHandler(&handler);
//
// Create MemBufferInputSource from the buffer containing the XML
// statements.
//
// NOTE: We are using strlen() here, since we know that the chars in
// our hard coded buffer are single byte chars!!! The parameter wants
// the number of BYTES, not chars, so when you create a memory buffer
// give it the byte size (which just happens to be the same here.)
//
MemBufInputSource* memBufIS = new MemBufInputSource
(
(const XMLByte*)gXMLInMemBuf
, strlen(gXMLInMemBuf)
, gMemBufId
, false
);
//
// Get the starting time and kick off the parse of the indicated
// file. Catch any exceptions that might propogate out of it.
//
unsigned long duration;
int errorCount = 0;
try
{
const unsigned long startMillis = XMLPlatformUtils::getCurrentMillis();
parser->parse(*memBufIS);
const unsigned long endMillis = XMLPlatformUtils::getCurrentMillis();
duration = endMillis - startMillis;
errorCount = parser->getErrorCount();
}
catch (const XMLException& e)
{
cerr << "\nError during parsing memory stream:\n"
<< "Exception message is: \n"
<< StrX(e.getMessage()) << "\n" << endl;
return 4;
}
// Print out the stats that we collected and time taken.
if (!errorCount) {
cout << "\nFinished parsing the memory buffer containing the following "
<< "XML statements:\n\n"
<< gXMLInMemBuf
<< "\n\n\n"
<< "Parsing took " << duration << " ms ("
<< handler.getElementCount() << " elements, "
<< handler.getAttrCount() << " attributes, "
<< handler.getSpaceCount() << " spaces, "
<< handler.getCharacterCount() << " characters).\n" << endl;
}
//
// Delete the parser itself. Must be done prior to calling Terminate, below.
//
delete parser;
delete memBufIS;
// And call the termination method
XMLPlatformUtils::Terminate();
if (errorCount > 0)
return 4;
else
return 0;
}
| 34.032787 | 88 | 0.592405 | [
"object"
] |
105436b2f70b3577f1f54ce5cedcc35d8aa25ac1 | 25,461 | cpp | C++ | python-ios/src/matplotlib_files/sources/delaunay/_delaunay.cpp | ktraunmueller/Computable | 5a6a872c4c0f5e122c24c321cd877a949877dcf7 | [
"MIT"
] | 26 | 2018-02-14T23:52:58.000Z | 2021-08-16T13:50:03.000Z | python-ios/src/matplotlib_files/sources/delaunay/_delaunay.cpp | preslavrachev/Computable | 2f802ff5a14628e425aae4ec14667d2f98c1fd75 | [
"MIT"
] | null | null | null | python-ios/src/matplotlib_files/sources/delaunay/_delaunay.cpp | preslavrachev/Computable | 2f802ff5a14628e425aae4ec14667d2f98c1fd75 | [
"MIT"
] | 10 | 2018-08-13T19:38:39.000Z | 2020-04-19T03:02:00.000Z | #include "Python.h"
#include <stdlib.h>
#include <map>
#include <iostream>
#include "VoronoiDiagramGenerator.h"
#include "delaunay_utils.h"
#include "natneighbors.h"
#define PY_ARRAY_UNIQUE_SYMBOL delaunay_ARRAY_API
#undef NO_IMPORT_ARRAY
#include "numpy/arrayobject.h"
#include "numpy/__multiarray_api.h"
#include "numpy/noprefix.h"
using namespace std;
extern "C" {
static void reorder_edges(int npoints, int ntriangles,
double *x, double *y,
int *edge_db, int *tri_edges, int *tri_nbrs)
{
int neighbors[3], nodes[3];
int i, tmp;
int case1, case2;
for (i=0; i<ntriangles; i++) {
nodes[0] = INDEX2(edge_db, INDEX3(tri_edges,i,0), 0);
nodes[1] = INDEX2(edge_db, INDEX3(tri_edges,i,0), 1);
tmp = INDEX2(edge_db, INDEX3(tri_edges,i,1), 0);
if (tmp == nodes[0]) {
case1 = 1;
nodes[2] = INDEX2(edge_db, INDEX3(tri_edges,i,1), 1);
} else if (tmp == nodes[1]) {
case1 = 0;
nodes[2] = INDEX2(edge_db, INDEX3(tri_edges,i,1), 1);
} else if (INDEX2(edge_db, INDEX3(tri_edges,i,1), 1) == nodes[0]) {
case1 = 1;
nodes[2] = tmp;
} else {
case1 = 0;
nodes[2] = tmp;
}
if (ONRIGHT(x[nodes[0]], y[nodes[0]],
x[nodes[1]], y[nodes[1]],
x[nodes[2]], y[nodes[2]])) {
// flip to make counter-clockwise
tmp = nodes[2];
nodes[2] = nodes[1];
nodes[1] = tmp;
case2 = 1;
} else case2 = 0;
// I worked it out on paper. You're just gonna have to trust me on this.
if (!case1 && !case2) {
neighbors[0] = INDEX3(tri_nbrs, i, 1);
neighbors[1] = INDEX3(tri_nbrs, i, 2);
neighbors[2] = INDEX3(tri_nbrs, i, 0);
} else if (case1 && !case2) {
neighbors[0] = INDEX3(tri_nbrs, i, 2);
neighbors[1] = INDEX3(tri_nbrs, i, 1);
neighbors[2] = INDEX3(tri_nbrs, i, 0);
} else if (!case1 && case2) {
neighbors[0] = INDEX3(tri_nbrs, i, 1);
neighbors[1] = INDEX3(tri_nbrs, i, 0);
neighbors[2] = INDEX3(tri_nbrs, i, 2);
} else {
neighbors[0] = INDEX3(tri_nbrs, i, 2);
neighbors[1] = INDEX3(tri_nbrs, i, 0);
neighbors[2] = INDEX3(tri_nbrs, i, 1);
}
// Not trusting me? Okay, let's go through it:
// We have three edges to deal with and three nodes. Without loss
// of generality, let's label the nodes A, B, and C with (A, B)
// forming the first edge in the order they arrive on input.
// Then there are eight possibilities as to how the other edge-tuples
// may be labeled, but only two variations that are going to affect the
// output:
//
// AB AB
// BC (CB) AC (CA)
// CA (AC) BC (CB)
//
// The distinction is whether A is in the second edge or B is.
// This is the test "case1" above.
//
// The second test we need to perform is for counter-clockwiseness.
// Again, there are only two variations that will affect the outcome:
// either ABC is counter-clockwise, or it isn't. In the former case,
// we're done setting the node order, we just need to associate the
// appropriate neighbor triangles with their opposite nodes, something
// which can be done by inspection. In the latter case, to order the
// nodes counter-clockwise, we only have to switch B and C to get
// nodes ACB. Then we simply set the neighbor list by inspection again.
//
// CCW CW
// AB
// BC 120 102 -+
// CA |
// +- neighbor order
// AB |
// AC 210 201 -+
// BC
// ABC ACB -+- node order
INDEX3(tri_edges,i,0) = nodes[0];
INDEX3(tri_edges,i,1) = nodes[1];
INDEX3(tri_edges,i,2) = nodes[2];
INDEX3(tri_nbrs,i,0) = neighbors[0];
INDEX3(tri_nbrs,i,1) = neighbors[1];
INDEX3(tri_nbrs,i,2) = neighbors[2];
}
}
static PyObject* getMesh(int npoints, double *x, double *y)
{
PyObject *vertices = NULL, *edge_db = NULL, *tri_edges = NULL, *tri_nbrs = NULL;
PyObject *temp;
int tri0, tri1, reg0, reg1;
double tri0x, tri0y, tri1x, tri1y;
int length, numtri, i, j;
intp dim[MAX_DIMS];
int *edge_db_ptr, *tri_edges_ptr, *tri_nbrs_ptr;
double *vertices_ptr;
VoronoiDiagramGenerator vdg;
vdg.generateVoronoi(x, y, npoints, -100, 100, -100, 100, 0);
vdg.getNumbers(length, numtri);
// Count the actual number of edges
i = 0;
vdg.resetEdgeListIter();
while (vdg.getNextDelaunay(tri0, tri0x, tri0y, tri1, tri1x, tri1y, reg0, reg1))
i++;
length = i;
dim[0] = length;
dim[1] = 2;
edge_db = PyArray_SimpleNew(2, dim, PyArray_INT);
if (!edge_db) goto fail;
edge_db_ptr = (int*)PyArray_DATA(edge_db);
dim[0] = numtri;
vertices = PyArray_SimpleNew(2, dim, PyArray_DOUBLE);
if (!vertices) goto fail;
vertices_ptr = (double*)PyArray_DATA(vertices);
dim[1] = 3;
tri_edges = PyArray_SimpleNew(2, dim, PyArray_INT);
if (!tri_edges) goto fail;
tri_edges_ptr = (int*)PyArray_DATA(tri_edges);
tri_nbrs = PyArray_SimpleNew(2, dim, PyArray_INT);
if (!tri_nbrs) goto fail;
tri_nbrs_ptr = (int*)PyArray_DATA(tri_nbrs);
for (i=0; i<(3*numtri); i++) {
tri_edges_ptr[i] = tri_nbrs_ptr[i] = -1;
}
vdg.resetEdgeListIter();
i = -1;
while (vdg.getNextDelaunay(tri0, tri0x, tri0y, tri1, tri1x, tri1y, reg0, reg1)) {
i++;
INDEX2(edge_db_ptr,i,0) = reg0;
INDEX2(edge_db_ptr,i,1) = reg1;
if (tri0 > -1) {
INDEX2(vertices_ptr,tri0,0) = tri0x;
INDEX2(vertices_ptr,tri0,1) = tri0y;
for (j=0; j<3; j++) {
if (INDEX3(tri_edges_ptr,tri0,j) == i) break;
if (INDEX3(tri_edges_ptr,tri0,j) == -1) {
INDEX3(tri_edges_ptr,tri0,j) = i;
INDEX3(tri_nbrs_ptr,tri0,j) = tri1;
break;
}
}
}
if (tri1 > -1) {
INDEX2(vertices_ptr,tri1,0) = tri1x;
INDEX2(vertices_ptr,tri1,1) = tri1y;
for (j=0; j<3; j++) {
if (INDEX3(tri_edges_ptr,tri1,j) == i) break;
if (INDEX3(tri_edges_ptr,tri1,j) == -1) {
INDEX3(tri_edges_ptr,tri1,j) = i;
INDEX3(tri_nbrs_ptr,tri1,j) = tri0;
break;
}
}
}
}
// tri_edges contains lists of edges; convert to lists of nodes in
// counterclockwise order and reorder tri_nbrs to match. Each node
// corresponds to the edge opposite it in the triangle.
reorder_edges(npoints, numtri, x, y, edge_db_ptr, tri_edges_ptr,
tri_nbrs_ptr);
temp = Py_BuildValue("(OOOO)", vertices, edge_db, tri_edges, tri_nbrs);
if (!temp) goto fail;
Py_DECREF(vertices);
Py_DECREF(edge_db);
Py_DECREF(tri_edges);
Py_DECREF(tri_nbrs);
return temp;
fail:
Py_XDECREF(vertices);
Py_XDECREF(edge_db);
Py_XDECREF(tri_edges);
Py_XDECREF(tri_nbrs);
return NULL;
}
static PyObject *linear_planes(int ntriangles, double *x, double *y, double *z,
int *nodes)
{
intp dims[2];
PyObject *planes;
int i;
double *planes_ptr;
double x02, y02, z02, x12, y12, z12, xy0212;
dims[0] = ntriangles;
dims[1] = 3;
planes = PyArray_SimpleNew(2, dims, PyArray_DOUBLE);
if (!planes) return NULL;
planes_ptr = (double *)PyArray_DATA(planes);
for (i=0; i<ntriangles; i++) {
x02 = x[INDEX3(nodes,i,0)] - x[INDEX3(nodes,i,2)];
y02 = y[INDEX3(nodes,i,0)] - y[INDEX3(nodes,i,2)];
z02 = z[INDEX3(nodes,i,0)] - z[INDEX3(nodes,i,2)];
x12 = x[INDEX3(nodes,i,1)] - x[INDEX3(nodes,i,2)];
y12 = y[INDEX3(nodes,i,1)] - y[INDEX3(nodes,i,2)];
z12 = z[INDEX3(nodes,i,1)] - z[INDEX3(nodes,i,2)];
if (y12 != 0.0) {
xy0212 = y02/y12;
INDEX3(planes_ptr,i,0) = (z02 - z12 * xy0212) / (x02 - x12 * xy0212);
INDEX3(planes_ptr,i,1) = (z12 - INDEX3(planes_ptr,i,0)*x12) / y12;
INDEX3(planes_ptr,i,2) = (z[INDEX3(nodes,i,2)] -
INDEX3(planes_ptr,i,0)*x[INDEX3(nodes,i,2)] -
INDEX3(planes_ptr,i,1)*y[INDEX3(nodes,i,2)]);
} else {
xy0212 = x02/x12;
INDEX3(planes_ptr,i,1) = (z02 - z12 * xy0212) / (y02 - y12 * xy0212);
INDEX3(planes_ptr,i,0) = (z12 - INDEX3(planes_ptr,i,1)*y12) / x12;
INDEX3(planes_ptr,i,2) = (z[INDEX3(nodes,i,2)] -
INDEX3(planes_ptr,i,0)*x[INDEX3(nodes,i,2)] -
INDEX3(planes_ptr,i,1)*y[INDEX3(nodes,i,2)]);
}
}
return (PyObject*)planes;
}
static double linear_interpolate_single(double targetx, double targety,
double *x, double *y, int *nodes, int *neighbors,
PyObject *planes, double defvalue, int start_triangle, int *end_triangle)
{
double *planes_ptr;
planes_ptr = (double*)PyArray_DATA(planes);
if (start_triangle == -1) start_triangle = 0;
*end_triangle = walking_triangles(start_triangle, targetx, targety,
x, y, nodes, neighbors);
if (*end_triangle == -1) return defvalue;
return (targetx*INDEX3(planes_ptr,*end_triangle,0) +
targety*INDEX3(planes_ptr,*end_triangle,1) +
INDEX3(planes_ptr,*end_triangle,2));
}
static PyObject *linear_interpolate_grid(double x0, double x1, int xsteps,
double y0, double y1, int ysteps,
PyObject *planes, double defvalue,
int npoints, double *x, double *y, int *nodes, int *neighbors)
{
int ix, iy;
double dx, dy, targetx, targety;
int rowtri, coltri, tri;
PyObject *z;
double *z_ptr;
intp dims[2];
dims[0] = ysteps;
dims[1] = xsteps;
z = PyArray_SimpleNew(2, dims, PyArray_DOUBLE);
if (!z) return NULL;
z_ptr = (double*)PyArray_DATA(z);
dx = ( xsteps==1 ? 0 : (x1 - x0) / (xsteps-1) );
dy = ( ysteps==1 ? 0 : (y1 - y0) / (ysteps-1) );
rowtri = 0;
for (iy=0; iy<ysteps; iy++) {
targety = y0 + dy*iy;
rowtri = walking_triangles(rowtri, x0, targety, x, y, nodes, neighbors);
tri = rowtri;
for (ix=0; ix<xsteps; ix++) {
targetx = x0 + dx*ix;
INDEXN(z_ptr, xsteps, iy, ix) = linear_interpolate_single(
targetx, targety,
x, y, nodes, neighbors, planes, defvalue, tri, &coltri);
if (coltri != -1) tri = coltri;
}
}
return z;
}
static PyObject *compute_planes_method(PyObject *self, PyObject *args)
{
PyObject *pyx, *pyy, *pyz, *pynodes;
PyObject *x = NULL, *y = NULL, *z = NULL, *nodes = NULL;
int npoints, ntriangles;
PyObject *planes;
if (!PyArg_ParseTuple(args, "OOOO", &pyx, &pyy, &pyz, &pynodes)) {
return NULL;
}
x = PyArray_FROMANY(pyx, PyArray_DOUBLE, 1, 1, NPY_IN_ARRAY);
if (!x) {
PyErr_SetString(PyExc_ValueError, "x must be a 1-D array of floats");
goto fail;
}
y = PyArray_FROMANY(pyy, PyArray_DOUBLE, 1, 1, NPY_IN_ARRAY);
if (!y) {
PyErr_SetString(PyExc_ValueError, "y must be a 1-D array of floats");
goto fail;
}
z = PyArray_FROMANY(pyz, PyArray_DOUBLE, 1, 1, NPY_IN_ARRAY);
if (!z) {
PyErr_SetString(PyExc_ValueError, "z must be a 1-D array of floats");
goto fail;
}
npoints = PyArray_DIM(x, 0);
if ((PyArray_DIM(y, 0) != npoints) || (PyArray_DIM(z, 0) != npoints)) {
PyErr_SetString(PyExc_ValueError, "x,y,z arrays must be of equal length");
goto fail;
}
nodes = PyArray_FROMANY(pynodes, PyArray_INT, 2, 2, NPY_IN_ARRAY);
if (!nodes) {
PyErr_SetString(PyExc_ValueError, "nodes must be a 2-D array of ints");
goto fail;
}
ntriangles = PyArray_DIM(nodes, 0);
if (PyArray_DIM(nodes, 1) != 3) {
PyErr_SetString(PyExc_ValueError, "nodes must have shape (ntriangles, 3)");
goto fail;
}
planes = linear_planes(ntriangles, (double*)PyArray_DATA(x),
(double*)PyArray_DATA(y), (double*)PyArray_DATA(z), (int*)PyArray_DATA(nodes));
Py_DECREF(x);
Py_DECREF(y);
Py_DECREF(z);
Py_DECREF(nodes);
return planes;
fail:
Py_XDECREF(x);
Py_XDECREF(y);
Py_XDECREF(z);
Py_XDECREF(nodes);
return NULL;
}
static PyObject *linear_interpolate_method(PyObject *self, PyObject *args)
{
double x0, x1, y0, y1, defvalue;
int xsteps, ysteps;
PyObject *pyplanes, *pyx, *pyy, *pynodes, *pyneighbors, *grid;
PyObject *planes = NULL, *x = NULL, *y = NULL, *nodes = NULL, *neighbors = NULL;
int npoints;
if (!PyArg_ParseTuple(args, "ddiddidOOOOO", &x0, &x1, &xsteps, &y0, &y1, &ysteps,
&defvalue, &pyplanes, &pyx, &pyy, &pynodes, &pyneighbors)) {
return NULL;
}
x = PyArray_FROMANY(pyx, PyArray_DOUBLE, 1, 1, NPY_IN_ARRAY);
if (!x) {
PyErr_SetString(PyExc_ValueError, "x must be a 1-D array of floats");
goto fail;
}
y = PyArray_FROMANY(pyy, PyArray_DOUBLE, 1, 1, NPY_IN_ARRAY);
if (!y) {
PyErr_SetString(PyExc_ValueError, "y must be a 1-D array of floats");
goto fail;
}
npoints = PyArray_DIM(x, 0);
if (PyArray_DIM(y, 0) != npoints) {
PyErr_SetString(PyExc_ValueError, "x,y arrays must be of equal length");
goto fail;
}
planes = PyArray_FROMANY(pyplanes, PyArray_DOUBLE, 2, 2, NPY_IN_ARRAY);
if (!planes) {
PyErr_SetString(PyExc_ValueError, "planes must be a 2-D array of floats");
goto fail;
}
nodes = PyArray_FROMANY(pynodes, PyArray_INT, 2, 2, NPY_IN_ARRAY);
if (!nodes) {
PyErr_SetString(PyExc_ValueError, "nodes must be a 2-D array of ints");
goto fail;
}
neighbors = PyArray_FROMANY(pyneighbors, PyArray_INT, 2, 2, NPY_IN_ARRAY);
if (!neighbors) {
PyErr_SetString(PyExc_ValueError, "neighbors must be a 2-D array of ints");
goto fail;
}
grid = linear_interpolate_grid(x0, x1, xsteps, y0, y1, ysteps,
(PyObject*)planes, defvalue, npoints,
(double*)PyArray_DATA(x), (double*)PyArray_DATA(y),
(int*)PyArray_DATA(nodes), (int*)PyArray_DATA(neighbors));
Py_DECREF(x);
Py_DECREF(y);
Py_DECREF(planes);
Py_DECREF(nodes);
Py_DECREF(neighbors);
return grid;
fail:
Py_XDECREF(x);
Py_XDECREF(y);
Py_XDECREF(planes);
Py_XDECREF(nodes);
Py_XDECREF(neighbors);
return NULL;
}
// Thanks to C++'s memory rules, we can't use the usual "goto fail;" method of
// error handling.
#define CLEANUP \
Py_XDECREF(x);\
Py_XDECREF(y);\
Py_XDECREF(z);\
Py_XDECREF(intx);\
Py_XDECREF(inty);\
Py_XDECREF(centers);\
Py_XDECREF(nodes);\
Py_XDECREF(neighbors);\
Py_XDECREF(intz);
#define PyArray_ND(arr) (((PyArrayObject*)arr)->nd)
static PyObject *nn_interpolate_unstructured_method(PyObject *self, PyObject *args)
{
PyObject *pyx, *pyy, *pyz, *pycenters, *pynodes, *pyneighbors, *pyintx, *pyinty;
PyObject *x = NULL, *y = NULL, *z = NULL, *centers = NULL, *nodes = NULL,
*neighbors = NULL, *intx = NULL, *inty = NULL, *intz = NULL;
double defvalue;
int size, npoints, ntriangles;
if (!PyArg_ParseTuple(args, "OOdOOOOOO", &pyintx, &pyinty, &defvalue,
&pyx, &pyy, &pyz, &pycenters, &pynodes, &pyneighbors)) {
return NULL;
}
x = PyArray_FROMANY(pyx, PyArray_DOUBLE, 1, 1, NPY_IN_ARRAY);
if (!x) {
PyErr_SetString(PyExc_ValueError, "x must be a 1-D array of floats");
CLEANUP
return NULL;
}
y = PyArray_FROMANY(pyy, PyArray_DOUBLE, 1, 1, NPY_IN_ARRAY);
if (!y) {
PyErr_SetString(PyExc_ValueError, "y must be a 1-D array of floats");
CLEANUP
return NULL;
}
z = PyArray_FROMANY(pyz, PyArray_DOUBLE, 1, 1, NPY_IN_ARRAY);
if (!z) {
PyErr_SetString(PyExc_ValueError, "z must be a 1-D array of floats");
CLEANUP
return NULL;
}
npoints = PyArray_DIM(x, 0);
if ((PyArray_DIM(y, 0) != npoints) || (PyArray_DIM(z, 0) != npoints)) {
PyErr_SetString(PyExc_ValueError, "x,y,z arrays must be of equal length");
CLEANUP
return NULL;
}
centers = PyArray_FROMANY(pycenters, PyArray_DOUBLE, 2, 2, NPY_IN_ARRAY);
if (!centers) {
PyErr_SetString(PyExc_ValueError, "centers must be a 2-D array of ints");
CLEANUP
return NULL;
}
nodes = PyArray_FROMANY(pynodes, PyArray_INT, 2, 2, NPY_IN_ARRAY);
if (!nodes) {
PyErr_SetString(PyExc_ValueError, "nodes must be a 2-D array of ints");
CLEANUP
return NULL;
}
neighbors = PyArray_FROMANY(pyneighbors, PyArray_INT, 2, 2, NPY_IN_ARRAY);
if (!neighbors) {
PyErr_SetString(PyExc_ValueError, "neighbors must be a 2-D array of ints");
CLEANUP
return NULL;
}
ntriangles = PyArray_DIM(neighbors, 0);
if ((PyArray_DIM(nodes, 0) != ntriangles) ||
(PyArray_DIM(centers, 0) != ntriangles)) {
PyErr_SetString(PyExc_ValueError, "centers,nodes,neighbors must be of equal length");
CLEANUP
return NULL;
}
intx = PyArray_FROM_OTF(pyintx, PyArray_DOUBLE, NPY_IN_ARRAY);
if (!intx) {
PyErr_SetString(PyExc_ValueError, "intx must be an array of floats");
CLEANUP
return NULL;
}
inty = PyArray_FROM_OTF(pyinty, PyArray_DOUBLE, NPY_IN_ARRAY);
if (!inty) {
PyErr_SetString(PyExc_ValueError, "inty must be an array of floats");
CLEANUP
return NULL;
}
if (PyArray_ND(intx) != PyArray_ND(inty)) {
PyErr_SetString(PyExc_ValueError, "intx,inty must have same shapes");
CLEANUP
return NULL;
}
for (int i=0; i<PyArray_ND(intx); i++) {
if (PyArray_DIM(intx, i) != PyArray_DIM(inty, i)) {
PyErr_SetString(PyExc_ValueError, "intx,inty must have same shapes");
CLEANUP
return NULL;
}
}
intz = PyArray_SimpleNew(PyArray_ND(intx), PyArray_DIMS(intx), PyArray_DOUBLE);
if (!intz) {
CLEANUP
return NULL;
}
NaturalNeighbors nn(npoints, ntriangles,
(double*)PyArray_DATA(x), (double*)PyArray_DATA(y),
(double*)PyArray_DATA(centers), (int*)PyArray_DATA(nodes),
(int*)PyArray_DATA(neighbors));
size = PyArray_Size(intx);
nn.interpolate_unstructured((double*)PyArray_DATA(z), size,
(double*)PyArray_DATA(intx), (double*)PyArray_DATA(inty),
(double*)PyArray_DATA(intz), defvalue);
Py_XDECREF(x);
Py_XDECREF(y);
Py_XDECREF(z);
Py_XDECREF(intx);
Py_XDECREF(inty);
Py_XDECREF(centers);
Py_XDECREF(nodes);
Py_XDECREF(neighbors);
return intz;
}
#undef CLEANUP
#define CLEANUP \
Py_XDECREF(x);\
Py_XDECREF(y);\
Py_XDECREF(z);\
Py_XDECREF(centers);\
Py_XDECREF(nodes);\
Py_XDECREF(neighbors);
static PyObject *nn_interpolate_method(PyObject *self, PyObject *args)
{
PyObject *pyx, *pyy, *pyz, *pycenters, *pynodes, *pyneighbors, *grid;
PyObject *x = NULL, *y = NULL, *z = NULL, *centers = NULL, *nodes = NULL, *neighbors = NULL;
double x0, x1, y0, y1, defvalue;
int xsteps, ysteps;
int npoints, ntriangles;
intp dims[2];
if (!PyArg_ParseTuple(args, "ddiddidOOOOOO", &x0, &x1, &xsteps,
&y0, &y1, &ysteps, &defvalue, &pyx, &pyy, &pyz, &pycenters, &pynodes,
&pyneighbors)) {
return NULL;
}
x = PyArray_FROMANY(pyx, PyArray_DOUBLE, 1, 1, NPY_IN_ARRAY);
if (!x) {
PyErr_SetString(PyExc_ValueError, "x must be a 1-D array of floats");
CLEANUP
return NULL;
}
y = PyArray_FROMANY(pyy, PyArray_DOUBLE, 1, 1, NPY_IN_ARRAY);
if (!y) {
PyErr_SetString(PyExc_ValueError, "y must be a 1-D array of floats");
CLEANUP
return NULL;
}
z = PyArray_FROMANY(pyz, PyArray_DOUBLE, 1, 1, NPY_IN_ARRAY);
if (!z) {
PyErr_SetString(PyExc_ValueError, "z must be a 1-D array of floats");
CLEANUP
return NULL;
}
npoints = PyArray_DIM(x, 0);
if (PyArray_DIM(y, 0) != npoints) {
PyErr_SetString(PyExc_ValueError, "x,y arrays must be of equal length");
CLEANUP
return NULL;
}
centers = PyArray_FROMANY(pycenters, PyArray_DOUBLE, 2, 2, NPY_IN_ARRAY);
if (!centers) {
PyErr_SetString(PyExc_ValueError, "centers must be a 2-D array of ints");
CLEANUP
return NULL;
}
nodes = PyArray_FROMANY(pynodes, PyArray_INT, 2, 2, NPY_IN_ARRAY);
if (!nodes) {
PyErr_SetString(PyExc_ValueError, "nodes must be a 2-D array of ints");
CLEANUP
return NULL;
}
neighbors = PyArray_FROMANY(pyneighbors, PyArray_INT, 2, 2, NPY_IN_ARRAY);
if (!neighbors) {
PyErr_SetString(PyExc_ValueError, "neighbors must be a 2-D array of ints");
CLEANUP
return NULL;
}
ntriangles = PyArray_DIM(neighbors, 0);
if ((PyArray_DIM(nodes, 0) != ntriangles) ||
(PyArray_DIM(centers, 0) != ntriangles)) {
PyErr_SetString(PyExc_ValueError, "centers,nodes,neighbors must be of equal length");
CLEANUP
return NULL;
}
dims[0] = ysteps;
dims[1] = xsteps;
grid = PyArray_SimpleNew(2, dims, PyArray_DOUBLE);
if (!grid) {
CLEANUP
return NULL;
}
NaturalNeighbors nn(npoints, ntriangles,
(double*)PyArray_DATA(x), (double*)PyArray_DATA(y),
(double*)PyArray_DATA(centers), (int*)PyArray_DATA(nodes),
(int*)PyArray_DATA(neighbors));
nn.interpolate_grid((double*)PyArray_DATA(z),
x0, x1, xsteps,
y0, y1, ysteps,
(double*)PyArray_DATA(grid),
defvalue, 0);
CLEANUP
return grid;
}
#undef CLEANUP
static PyObject *delaunay_method(PyObject *self, PyObject *args)
{
PyObject *pyx, *pyy, *mesh;
PyObject *x = NULL, *y = NULL;
int npoints;
if (!PyArg_ParseTuple(args, "OO", &pyx, &pyy)) {
return NULL;
}
x = PyArray_FROMANY(pyx, PyArray_DOUBLE, 1, 1, NPY_IN_ARRAY);
if (!x) {
PyErr_SetString(PyExc_ValueError, "x must be a 1-D array of floats");
goto fail;
}
y = PyArray_FROMANY(pyy, PyArray_DOUBLE, 1, 1, NPY_IN_ARRAY);
if (!y) {
PyErr_SetString(PyExc_ValueError, "y must be a 1-D array of floats");
goto fail;
}
npoints = PyArray_DIM(x, 0);
if (PyArray_DIM(y, 0) != npoints) {
PyErr_SetString(PyExc_ValueError, "x and y must have the same length");
goto fail;
}
mesh = getMesh(npoints, (double*)PyArray_DATA(x), (double*)PyArray_DATA(y));
if (!mesh) goto fail;
Py_DECREF(x);
Py_DECREF(y);
return mesh;
fail:
Py_XDECREF(x);
Py_XDECREF(y);
return NULL;
}
static PyMethodDef delaunay_methods[] = {
{"delaunay", (PyCFunction)delaunay_method, METH_VARARGS,
"Compute the Delaunay triangulation of a cloud of 2-D points.\n\n"
"circumcenters, edges, tri_points, tri_neighbors = delaunay(x, y)\n\n"
"x, y -- shape-(npoints,) arrays of floats giving the X and Y coordinates of the points\n"
"circumcenters -- shape-(numtri,2) array of floats giving the coordinates of the\n"
" circumcenters of each triangle (numtri being the number of triangles)\n"
"edges -- shape-(nedges,2) array of integers giving the indices into x and y\n"
" of each edge in the triangulation\n"
"tri_points -- shape-(numtri,3) array of integers giving the indices into x and y\n"
" of each node in each triangle\n"
"tri_neighbors -- shape-(numtri,3) array of integers giving the indices into circumcenters\n"
" tri_points, and tri_neighbors of the neighbors of each triangle\n"},
{"compute_planes", (PyCFunction)compute_planes_method, METH_VARARGS,
""},
{"linear_interpolate_grid", (PyCFunction)linear_interpolate_method, METH_VARARGS,
""},
{"nn_interpolate_grid", (PyCFunction)nn_interpolate_method, METH_VARARGS,
""},
{"nn_interpolate_unstructured", (PyCFunction)nn_interpolate_unstructured_method, METH_VARARGS,
""},
{NULL, NULL, 0, NULL}
};
#if PY_MAJOR_VERSION >= 3
static struct PyModuleDef delaunay_module = {
PyModuleDef_HEAD_INIT,
"_delaunay",
"Tools for computing the Delaunay triangulation and some operations on it.\n",
-1,
delaunay_methods,
NULL, NULL, NULL, NULL
};
PyMODINIT_FUNC
PyInit__delaunay(void)
{
PyObject* m;
import_array();
m = PyModule_Create(&delaunay_module);
if (m == NULL)
return NULL;
return m;
}
#else
PyMODINIT_FUNC init_delaunay(void)
{
PyObject* m;
import_array();
m = Py_InitModule3("_delaunay", delaunay_methods,
"Tools for computing the Delaunay triangulation and some operations on it.\n"
);
if (m == NULL)
return;
}
#endif
} // extern "C"
| 33.023346 | 101 | 0.595342 | [
"mesh",
"shape"
] |
1056dad7e241bbf0a17a29e8e9007af09408e269 | 6,311 | hpp | C++ | include/VROSC/AnimatedAppearMaterialHolder.hpp | v0idp/virtuoso-codegen | 6f560f04822c67f092d438a3f484249072c1d21d | [
"Unlicense"
] | null | null | null | include/VROSC/AnimatedAppearMaterialHolder.hpp | v0idp/virtuoso-codegen | 6f560f04822c67f092d438a3f484249072c1d21d | [
"Unlicense"
] | null | null | null | include/VROSC/AnimatedAppearMaterialHolder.hpp | v0idp/virtuoso-codegen | 6f560f04822c67f092d438a3f484249072c1d21d | [
"Unlicense"
] | 1 | 2022-03-30T21:07:35.000Z | 2022-03-30T21:07:35.000Z | // 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: UnityEngine.MonoBehaviour
#include "UnityEngine/MonoBehaviour.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: TMPro
namespace TMPro {
// Forward declaring type: TextMeshPro
class TextMeshPro;
}
// Forward declaring namespace: UnityEngine
namespace UnityEngine {
// Forward declaring type: Renderer
class Renderer;
// Forward declaring type: Material
class Material;
}
// Completed forward declares
// Type namespace: VROSC
namespace VROSC {
// Forward declaring type: AnimatedAppearMaterialHolder
class AnimatedAppearMaterialHolder;
}
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(::VROSC::AnimatedAppearMaterialHolder);
DEFINE_IL2CPP_ARG_TYPE(::VROSC::AnimatedAppearMaterialHolder*, "VROSC", "AnimatedAppearMaterialHolder");
// Type namespace: VROSC
namespace VROSC {
// Size: 0x30
#pragma pack(push, 1)
// Autogenerated type: VROSC.AnimatedAppearMaterialHolder
// [TokenAttribute] Offset: FFFFFFFF
class AnimatedAppearMaterialHolder : public ::UnityEngine::MonoBehaviour {
public:
public:
// private TMPro.TextMeshPro _textMesh
// Size: 0x8
// Offset: 0x18
::TMPro::TextMeshPro* textMesh;
// Field size check
static_assert(sizeof(::TMPro::TextMeshPro*) == 0x8);
// private UnityEngine.Renderer _renderer
// Size: 0x8
// Offset: 0x20
::UnityEngine::Renderer* renderer;
// Field size check
static_assert(sizeof(::UnityEngine::Renderer*) == 0x8);
// private UnityEngine.Material _material
// Size: 0x8
// Offset: 0x28
::UnityEngine::Material* material;
// Field size check
static_assert(sizeof(::UnityEngine::Material*) == 0x8);
public:
// Deleting conversion operator: operator ::System::IntPtr
constexpr operator ::System::IntPtr() const noexcept = delete;
// Get instance field reference: private TMPro.TextMeshPro _textMesh
[[deprecated("Use field access instead!")]] ::TMPro::TextMeshPro*& dyn__textMesh();
// Get instance field reference: private UnityEngine.Renderer _renderer
[[deprecated("Use field access instead!")]] ::UnityEngine::Renderer*& dyn__renderer();
// Get instance field reference: private UnityEngine.Material _material
[[deprecated("Use field access instead!")]] ::UnityEngine::Material*& dyn__material();
// public System.Void .ctor()
// Offset: 0x96AA14
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static AnimatedAppearMaterialHolder* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("::VROSC::AnimatedAppearMaterialHolder::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<AnimatedAppearMaterialHolder*, creationType>()));
}
// public System.Void Setup(TMPro.TextMeshPro textMesh, UnityEngine.Material material)
// Offset: 0x96A8F0
void Setup(::TMPro::TextMeshPro* textMesh, ::UnityEngine::Material* material);
// public System.Void Setup(UnityEngine.Renderer renderer, UnityEngine.Material material)
// Offset: 0x96A8FC
void Setup(::UnityEngine::Renderer* renderer, ::UnityEngine::Material* material);
// public System.Void Reset()
// Offset: 0x96A904
void Reset();
}; // VROSC.AnimatedAppearMaterialHolder
#pragma pack(pop)
static check_size<sizeof(AnimatedAppearMaterialHolder), 40 + sizeof(::UnityEngine::Material*)> __VROSC_AnimatedAppearMaterialHolderSizeCheck;
static_assert(sizeof(AnimatedAppearMaterialHolder) == 0x30);
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: VROSC::AnimatedAppearMaterialHolder::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
// Writing MetadataGetter for method: VROSC::AnimatedAppearMaterialHolder::Setup
// Il2CppName: Setup
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::AnimatedAppearMaterialHolder::*)(::TMPro::TextMeshPro*, ::UnityEngine::Material*)>(&VROSC::AnimatedAppearMaterialHolder::Setup)> {
static const MethodInfo* get() {
static auto* textMesh = &::il2cpp_utils::GetClassFromName("TMPro", "TextMeshPro")->byval_arg;
static auto* material = &::il2cpp_utils::GetClassFromName("UnityEngine", "Material")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(VROSC::AnimatedAppearMaterialHolder*), "Setup", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{textMesh, material});
}
};
// Writing MetadataGetter for method: VROSC::AnimatedAppearMaterialHolder::Setup
// Il2CppName: Setup
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::AnimatedAppearMaterialHolder::*)(::UnityEngine::Renderer*, ::UnityEngine::Material*)>(&VROSC::AnimatedAppearMaterialHolder::Setup)> {
static const MethodInfo* get() {
static auto* renderer = &::il2cpp_utils::GetClassFromName("UnityEngine", "Renderer")->byval_arg;
static auto* material = &::il2cpp_utils::GetClassFromName("UnityEngine", "Material")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(VROSC::AnimatedAppearMaterialHolder*), "Setup", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{renderer, material});
}
};
// Writing MetadataGetter for method: VROSC::AnimatedAppearMaterialHolder::Reset
// Il2CppName: Reset
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::AnimatedAppearMaterialHolder::*)()>(&VROSC::AnimatedAppearMaterialHolder::Reset)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(VROSC::AnimatedAppearMaterialHolder*), "Reset", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
| 49.692913 | 215 | 0.740136 | [
"vector"
] |
10578476ffcaed8598b600813e129dc93abf6730 | 6,798 | hpp | C++ | include/rsvd/RandomizedSvd.hpp | valerii-filev-picsart/rsvd | 348b10c0930a137ede14a40548ec1e0956420318 | [
"BSD-3-Clause"
] | null | null | null | include/rsvd/RandomizedSvd.hpp | valerii-filev-picsart/rsvd | 348b10c0930a137ede14a40548ec1e0956420318 | [
"BSD-3-Clause"
] | null | null | null | include/rsvd/RandomizedSvd.hpp | valerii-filev-picsart/rsvd | 348b10c0930a137ede14a40548ec1e0956420318 | [
"BSD-3-Clause"
] | null | null | null | #ifndef RSVD_RANDOMIZED_SVD_HPP_
#define RSVD_RANDOMIZED_SVD_HPP_
// BSD 3-Clause License
//
// Copyright (c) 2018, Mikhail Pak
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright 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 <eigen3/Eigen/Dense>
#include <algorithm>
#include <rsvd/Constants.hpp>
#include <rsvd/RandomizedRangeFinder.hpp>
using Eigen::ComputeThinU;
using Eigen::ComputeThinV;
using Eigen::Index;
using Eigen::JacobiSVD;
using std::min;
namespace Rsvd {
/// \brief Randomized singular value decomposition.
///
/// \long Let \f$\mathbb{F}\f$ be a field of complex or real numbers, \f$\mathbb{F}=\mathbb{C}\f$
/// or \f$\mathbb{F}=\mathbb{R}\f$.
///
/// Let \f$ A \in \mathbb{F}^{m \times n}\f$, \f$\mathrm{rank}(A) = r\f$. Its economic singular
/// value decomposition (SVD) is given by \f[ A = U \Sigma V^* \f] with \f$ U \in \mathbb{F}^{m
/// \times r} \f$, \f$ \Sigma \in \mathbb{F}^{r \times r} \f$, and \f$ V \in \mathbb{F}^{n \times
/// r} \f$. The left and right singular vector matrices have orthonormal columns: \f$ U^* U = I_{r
/// \times r} \f$, \f$ V^* V = I_{r \times r} \f$. The singular values matrix \f$\Sigma\f$ is
/// diagonal and has sorted singular values on its principal diagonal.
///
/// When \f$m\f$ and \f$n\f$ are very large, we want to approximate this SVD using the randomized
/// range approximation \f$Q \in \mathbb{F}^{m \times r}\f$ s.t. \f$ \| A - Q Q^* A \|_2 <
/// \varepsilon \f$. Then, the problem can be projected onto a smaller subspace as follows: \f$ B =
/// Q^* A\f$, \f$ B \in \mathbb{F}^{r \times n}\f$. After the SVD of the smaller problem \f$ B =
/// \tilde{U} \Sigma V^* \f$, the solution to the original problem can be recovered as \f$ U = Q
/// \tilde{U} \f$.
///
/// The range \f$Q\f$ is approximated using random sampling. In order to capture the largest
/// singular values, randomized subspace iterations can be used. However, as any power iteration
/// methods, they suffer from numerical problems. To mitigate this problem, the user can select an
/// appropriate conditioner based on the modified Gram--Schmidt process, the LU decomposition, and
/// the QR decomposition. The conditioner choice is a trade-off between runtime and numerical
/// properties, see #SubspaceIterationConditioner.
///
/// Usage example:
/// ```cpp
/// const MatrixXd a = ... ;
///
/// std::mt19937_64 randomEngine;
/// randomEngine.seed(777);
///
/// Rsvd::RandomizedSvd<MatrixXd, std::mt19937_64, Rsvd::LuConditioner>
/// rsvd(randomEngine); rsvd.compute(a, reducedRank);
/// // Recover matrix a
/// const MatrixXd rsvdApprox =
/// rsvd.matrixU() * rsvd.singularValues().asDiagonal() *
/// rsvd.matrixV().adjoint();
/// ```
///
/// \tparam MatrixType Eigen matrix type.
/// \tparam RandomEngineType Type of the random engine, e.g. \c std::default_random_engine or \c
/// std::mt19937_64.
/// \tparam Conditioner Which conditioner to use for subspace iterations, see
/// #SubspaceIterationConditioner.
template <typename MatrixType, typename RandomEngineType, SubspaceIterationConditioner Conditioner>
class RandomizedSvd {
public:
/// \brief Create an object for the randomized singular value decomposition.
///
/// \param engine Random engine to use for sampling from standard normal distribution.
explicit RandomizedSvd(RandomEngineType &engine) : m_randomEngine(engine){};
/// \brief Return the vector of singular values.
MatrixType singularValues() const { return m_singularValues; }
/// \brief Return the matrix with the left singular vectors.
MatrixType matrixU() const { return m_leftSingularVectors; }
/// \brief Return the matrix with the right singular vectors.
MatrixType matrixV() const { return m_rightSingularVectors; }
/// \brief Compute the randomized singular value decomposition.
///
/// \param a Matrix \f$A\f$ to be decomposed, \f$A = U \Sigma V^*\f$.
/// \param rank Rank of the decomposition.
/// \param oversamples Number of additionally sampled range directions. Increase it to improve
/// the approximation. Default value: 5.
/// \param numIter Number of randomized subspace iterations. Increase it to improve
/// the approximation. Default value: 2.
void compute(const MatrixType &a, const Index rank, const Index oversamples = 5,
const unsigned int numIter = 2) {
using Rsvd::Internal::RandomizedSubspaceIterations;
using Rsvd::Internal::singleShot;
/// \todo Handle matrices with m < n correctly.
const Index matrixShortSize = min(a.rows(), a.cols());
const Index rangeApproximationDim = min(matrixShortSize, rank + oversamples);
const MatrixType q =
(numIter == 0)
? singleShot<MatrixType, RandomEngineType>(a, rangeApproximationDim, m_randomEngine)
: RandomizedSubspaceIterations<MatrixType, RandomEngineType, Conditioner>::compute(
a, rangeApproximationDim, numIter, m_randomEngine);
const auto b = q.adjoint() * a;
JacobiSVD<MatrixType> svd(b, ComputeThinU | ComputeThinV);
m_leftSingularVectors.noalias() = q * svd.matrixU().leftCols(rank);
m_singularValues = svd.singularValues().head(rank);
m_rightSingularVectors = svd.matrixV().leftCols(rank);
}
private:
RandomEngineType &m_randomEngine;
MatrixType m_leftSingularVectors, m_singularValues, m_rightSingularVectors;
};
} // namespace Rsvd
#endif
| 45.932432 | 99 | 0.71727 | [
"object",
"vector"
] |
10582c3ce7d443e6cc52547a527aa51f0ba913e8 | 77,320 | cpp | C++ | lib/HLSL/DxilGenerationPass.cpp | Surfndez/DirectXShaderCompiler | c29a83b6bf7ede6adafd9798b048ca208ee1c3d4 | [
"NCSA"
] | null | null | null | lib/HLSL/DxilGenerationPass.cpp | Surfndez/DirectXShaderCompiler | c29a83b6bf7ede6adafd9798b048ca208ee1c3d4 | [
"NCSA"
] | 1 | 2021-01-21T11:55:58.000Z | 2021-01-21T11:55:58.000Z | lib/HLSL/DxilGenerationPass.cpp | Surfndez/DirectXShaderCompiler | c29a83b6bf7ede6adafd9798b048ca208ee1c3d4 | [
"NCSA"
] | null | null | null | ///////////////////////////////////////////////////////////////////////////////
// //
// DxilGenerationPass.cpp //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// DxilGenerationPass implementation. //
// //
///////////////////////////////////////////////////////////////////////////////
#include "dxc/HLSL/DxilGenerationPass.h"
#include "dxc/HLSL/DxilOperations.h"
#include "dxc/HLSL/DxilModule.h"
#include "dxc/HLSL/HLModule.h"
#include "dxc/HLSL/HLOperations.h"
#include "dxc/HLSL/HLMatrixLowerHelper.h"
#include "dxc/HlslIntrinsicOp.h"
#include "dxc/Support/Global.h"
#include "dxc/HLSL/DxilTypeSystem.h"
#include "dxc/HLSL/HLOperationLower.h"
#include "HLSignatureLower.h"
#include "dxc/HLSL/DxilUtil.h"
#include "dxc/Support/exception.h"
#include "llvm/IR/GetElementPtrTypeIterator.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/InstIterator.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/DebugInfo.h"
#include "llvm/IR/PassManager.h"
#include "llvm/ADT/BitVector.h"
#include "llvm/Pass.h"
#include "llvm/Transforms/Utils/SSAUpdater.h"
#include "llvm/Analysis/AssumptionCache.h"
#include "llvm/Transforms/Utils/PromoteMemToReg.h"
#include <memory>
#include <unordered_set>
#include <iterator>
using namespace llvm;
using namespace hlsl;
// TODO: use hlsl namespace for the most of this file.
namespace {
// Collect unused phi of resources and remove them.
class ResourceRemover : public LoadAndStorePromoter {
AllocaInst *AI;
mutable std::unordered_set<PHINode *> unusedPhis;
public:
ResourceRemover(ArrayRef<Instruction *> Insts, SSAUpdater &S)
: LoadAndStorePromoter(Insts, S), AI(nullptr) {}
void run(AllocaInst *AI, const SmallVectorImpl<Instruction *> &Insts) {
// Remember which alloca we're promoting (for isInstInList).
this->AI = AI;
LoadAndStorePromoter::run(Insts);
for (PHINode *P : unusedPhis) {
P->eraseFromParent();
}
}
bool
isInstInList(Instruction *I,
const SmallVectorImpl<Instruction *> &Insts) const override {
if (LoadInst *LI = dyn_cast<LoadInst>(I))
return LI->getOperand(0) == AI;
return cast<StoreInst>(I)->getPointerOperand() == AI;
}
void replaceLoadWithValue(LoadInst *LI, Value *V) const override {
if (PHINode *PHI = dyn_cast<PHINode>(V)) {
if (PHI->user_empty())
unusedPhis.insert(PHI);
}
LI->replaceAllUsesWith(UndefValue::get(LI->getType()));
}
};
void InitResourceBase(const DxilResourceBase *pSource, DxilResourceBase *pDest) {
DXASSERT_NOMSG(pSource->GetClass() == pDest->GetClass());
pDest->SetKind(pSource->GetKind());
pDest->SetID(pSource->GetID());
pDest->SetSpaceID(pSource->GetSpaceID());
pDest->SetLowerBound(pSource->GetLowerBound());
pDest->SetRangeSize(pSource->GetRangeSize());
pDest->SetGlobalSymbol(pSource->GetGlobalSymbol());
pDest->SetGlobalName(pSource->GetGlobalName());
pDest->SetHandle(pSource->GetHandle());
}
void InitResource(const DxilResource *pSource, DxilResource *pDest) {
pDest->SetCompType(pSource->GetCompType());
pDest->SetSampleCount(pSource->GetSampleCount());
pDest->SetElementStride(pSource->GetElementStride());
pDest->SetGloballyCoherent(pSource->IsGloballyCoherent());
pDest->SetHasCounter(pSource->HasCounter());
pDest->SetRW(pSource->IsRW());
pDest->SetROV(pSource->IsROV());
InitResourceBase(pSource, pDest);
}
void InitDxilModuleFromHLModule(HLModule &H, DxilModule &M, DxilEntrySignature *pSig, bool HasDebugInfo) {
std::unique_ptr<DxilEntrySignature> pSigPtr(pSig);
// Subsystems.
unsigned ValMajor, ValMinor;
H.GetValidatorVersion(ValMajor, ValMinor);
M.SetValidatorVersion(ValMajor, ValMinor);
M.SetShaderModel(H.GetShaderModel());
// Entry function.
Function *EntryFn = H.GetEntryFunction();
DxilFunctionProps *FnProps = H.HasDxilFunctionProps(EntryFn) ? &H.GetDxilFunctionProps(EntryFn) : nullptr;
M.SetEntryFunction(EntryFn);
M.SetEntryFunctionName(H.GetEntryFunctionName());
std::vector<GlobalVariable* > &LLVMUsed = M.GetLLVMUsed();
// Resources
for (auto && C : H.GetCBuffers()) {
auto b = llvm::make_unique<DxilCBuffer>();
InitResourceBase(C.get(), b.get());
b->SetSize(C->GetSize());
if (HasDebugInfo)
LLVMUsed.emplace_back(cast<GlobalVariable>(b->GetGlobalSymbol()));
b->SetGlobalSymbol(UndefValue::get(b->GetGlobalSymbol()->getType()));
M.AddCBuffer(std::move(b));
}
for (auto && C : H.GetUAVs()) {
auto b = llvm::make_unique<DxilResource>();
InitResource(C.get(), b.get());
if (HasDebugInfo)
LLVMUsed.emplace_back(cast<GlobalVariable>(b->GetGlobalSymbol()));
b->SetGlobalSymbol(UndefValue::get(b->GetGlobalSymbol()->getType()));
M.AddUAV(std::move(b));
}
for (auto && C : H.GetSRVs()) {
auto b = llvm::make_unique<DxilResource>();
InitResource(C.get(), b.get());
if (HasDebugInfo)
LLVMUsed.emplace_back(cast<GlobalVariable>(b->GetGlobalSymbol()));
b->SetGlobalSymbol(UndefValue::get(b->GetGlobalSymbol()->getType()));
M.AddSRV(std::move(b));
}
for (auto && C : H.GetSamplers()) {
auto b = llvm::make_unique<DxilSampler>();
InitResourceBase(C.get(), b.get());
b->SetSamplerKind(C->GetSamplerKind());
if (HasDebugInfo)
LLVMUsed.emplace_back(cast<GlobalVariable>(b->GetGlobalSymbol()));
b->SetGlobalSymbol(UndefValue::get(b->GetGlobalSymbol()->getType()));
M.AddSampler(std::move(b));
}
// Signatures.
M.ResetEntrySignature(pSigPtr.release());
M.ResetRootSignature(H.ReleaseRootSignature());
// Shader properties.
//bool m_bDisableOptimizations;
M.m_ShaderFlags.SetDisableOptimizations(H.GetHLOptions().bDisableOptimizations);
//bool m_bDisableMathRefactoring;
//bool m_bEnableDoublePrecision;
//bool m_bEnableDoubleExtensions;
//M.CollectShaderFlags();
//bool m_bForceEarlyDepthStencil;
//bool m_bEnableRawAndStructuredBuffers;
//bool m_bEnableMSAD;
//M.m_ShaderFlags.SetAllResourcesBound(H.GetHLOptions().bAllResourcesBound);
M.m_ShaderFlags.SetUseNativeLowPrecision(!H.GetHLOptions().bUseMinPrecision);
if (FnProps)
M.SetShaderProperties(FnProps);
// Move function props.
if (M.GetShaderModel()->IsLib())
M.ResetFunctionPropsMap(H.ReleaseFunctionPropsMap());
// DXIL type system.
M.ResetTypeSystem(H.ReleaseTypeSystem());
// Dxil OP.
M.ResetOP(H.ReleaseOP());
// Keep llvm used.
M.EmitLLVMUsed();
M.m_ShaderFlags.SetAllResourcesBound(H.GetHLOptions().bAllResourcesBound);
// Update Validator Version
M.UpgradeToMinValidatorVersion();
}
class DxilGenerationPass : public ModulePass {
HLModule *m_pHLModule;
bool m_HasDbgInfo;
HLSLExtensionsCodegenHelper *m_extensionsCodegenHelper;
public:
static char ID; // Pass identification, replacement for typeid
explicit DxilGenerationPass(bool NoOpt = false)
: ModulePass(ID), m_pHLModule(nullptr), m_extensionsCodegenHelper(nullptr), NotOptimized(NoOpt) {}
const char *getPassName() const override { return "DXIL Generator"; }
void SetExtensionsHelper(HLSLExtensionsCodegenHelper *helper) {
m_extensionsCodegenHelper = helper;
}
bool runOnModule(Module &M) override {
m_pHLModule = &M.GetOrCreateHLModule();
const ShaderModel *SM = m_pHLModule->GetShaderModel();
// Load up debug information, to cross-reference values and the instructions
// used to load them.
m_HasDbgInfo = getDebugMetadataVersionFromModule(M) != 0;
std::unique_ptr<DxilEntrySignature> pSig =
llvm::make_unique<DxilEntrySignature>(SM->GetKind(), M.GetHLModule().GetHLOptions().bUseMinPrecision);
// EntrySig for shader functions.
std::unordered_map<llvm::Function *, std::unique_ptr<DxilEntrySignature>>
DxilEntrySignatureMap;
if (!SM->IsLib()) {
HLSignatureLower sigLower(m_pHLModule->GetEntryFunction(), *m_pHLModule,
*pSig);
sigLower.Run();
} else {
for (auto It = M.begin(); It != M.end();) {
Function &F = *(It++);
// Lower signature for each entry function.
if (m_pHLModule->HasDxilFunctionProps(&F)) {
DxilFunctionProps &props = m_pHLModule->GetDxilFunctionProps(&F);
std::unique_ptr<DxilEntrySignature> pSig =
llvm::make_unique<DxilEntrySignature>(props.shaderKind, m_pHLModule->GetHLOptions().bUseMinPrecision);
HLSignatureLower sigLower(&F, *m_pHLModule, *pSig);
sigLower.Run();
DxilEntrySignatureMap[&F] = std::move(pSig);
}
}
}
std::unordered_set<LoadInst *> UpdateCounterSet;
std::unordered_set<Value *> NonUniformSet;
GenerateDxilOperations(M, UpdateCounterSet, NonUniformSet);
std::unordered_map<Instruction *, Value *> handleMap;
GenerateDxilCBufferHandles(NonUniformSet);
GenerateParamDxilResourceHandles(handleMap);
GenerateDxilResourceHandles(UpdateCounterSet, NonUniformSet);
AddCreateHandleForPhiNodeAndSelect(m_pHLModule->GetOP());
// For module which not promote mem2reg.
// Remove local resource alloca/load/store/phi.
for (auto It = M.begin(); It != M.end();) {
Function &F = *(It++);
if (!F.isDeclaration()) {
RemoveLocalDxilResourceAllocas(&F);
if (hlsl::GetHLOpcodeGroupByName(&F) == HLOpcodeGroup::HLCreateHandle) {
if (F.user_empty()) {
F.eraseFromParent();
} else {
M.getContext().emitError("Fail to lower createHandle.");
}
}
}
}
// Translate precise on allocas into function call to keep the information after mem2reg.
// The function calls will be removed after propagate precise attribute.
TranslatePreciseAttribute();
// Change struct type to legacy layout for cbuf and struct buf for min precision data types.
if (M.GetHLModule().GetHLOptions().bUseMinPrecision)
UpdateStructTypeForLegacyLayout();
// High-level metadata should now be turned into low-level metadata.
const bool SkipInit = true;
hlsl::DxilModule &DxilMod = M.GetOrCreateDxilModule(SkipInit);
InitDxilModuleFromHLModule(*m_pHLModule, DxilMod, pSig.release(),
m_HasDbgInfo);
if (SM->IsLib())
DxilMod.ResetEntrySignatureMap(std::move(DxilEntrySignatureMap));
HLModule::ClearHLMetadata(M);
M.ResetHLModule();
// We now have a DXIL representation - record this.
SetPauseResumePasses(M, "hlsl-dxilemit", "hlsl-dxilload");
// Remove debug code when not debug info.
if (!m_HasDbgInfo)
DxilMod.StripDebugRelatedCode();
(void)NotOptimized; // Dummy out unused member to silence warnings
return true;
}
private:
void RemoveLocalDxilResourceAllocas(Function *F);
void
TranslateDxilResourceUses(DxilResourceBase &res,
std::unordered_set<LoadInst *> &UpdateCounterSet,
std::unordered_set<Value *> &NonUniformSet);
void
GenerateDxilResourceHandles(std::unordered_set<LoadInst *> &UpdateCounterSet,
std::unordered_set<Value *> &NonUniformSet);
void AddCreateHandleForPhiNodeAndSelect(OP *hlslOP);
void TranslateParamDxilResourceHandles(Function *F, std::unordered_map<Instruction *, Value *> &handleMap);
void GenerateParamDxilResourceHandles(
std::unordered_map<Instruction *, Value *> &handleMap);
// Generate DXIL cbuffer handles.
void
GenerateDxilCBufferHandles(std::unordered_set<Value *> &NonUniformSet);
// change built-in funtion into DXIL operations
void GenerateDxilOperations(Module &M,
std::unordered_set<LoadInst *> &UpdateCounterSet,
std::unordered_set<Value *> &NonUniformSet);
// Change struct type to legacy layout for cbuf and struct buf.
void UpdateStructTypeForLegacyLayout();
// Translate precise attribute into HL function call.
void TranslatePreciseAttribute();
// Input module is not optimized.
bool NotOptimized;
};
}
static const StringRef kResourceMapErrorMsg = "local resource not guaranteed to map to unique global resource.";
static void EmitResMappingError(Instruction *Res) {
const DebugLoc &DL = Res->getDebugLoc();
if (DL.get()) {
Res->getContext().emitError("line:" + std::to_string(DL.getLine()) +
" col:" + std::to_string(DL.getCol()) + " " +
Twine(kResourceMapErrorMsg));
} else {
Res->getContext().emitError(Twine(kResourceMapErrorMsg) + " With /Zi to show more information.");
}
}
static void ReplaceResourceUserWithHandle(LoadInst *Res, Value *handle) {
for (auto resUser = Res->user_begin(); resUser != Res->user_end();) {
CallInst *CI = dyn_cast<CallInst>(*(resUser++));
DXASSERT(GetHLOpcodeGroupByName(CI->getCalledFunction()) ==
HLOpcodeGroup::HLCreateHandle,
"must be createHandle");
CI->replaceAllUsesWith(handle);
CI->eraseFromParent();
}
Res->eraseFromParent();
}
static bool IsResourceType(Type *Ty) {
bool isResource = HLModule::IsHLSLObjectType(Ty);
if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Type *EltTy = AT->getElementType();
while (isa<ArrayType>(EltTy)) {
EltTy = EltTy->getArrayElementType();
}
isResource = HLModule::IsHLSLObjectType(EltTy);
// TODO: support local resource array.
DXASSERT(!isResource, "local resource array");
}
return isResource;
}
void DxilGenerationPass::RemoveLocalDxilResourceAllocas(Function *F) {
BasicBlock &BB = F->getEntryBlock(); // Get the entry node for the function
std::unordered_set<AllocaInst *> localResources;
for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) { // Is it an alloca?
if (IsResourceType(AI->getAllocatedType())) {
localResources.insert(AI);
}
}
SSAUpdater SSA;
SmallVector<Instruction *, 4> Insts;
for (AllocaInst *AI : localResources) {
// Build list of instructions to promote.
for (User *U : AI->users())
Insts.emplace_back(cast<Instruction>(U));
ResourceRemover(Insts, SSA).run(AI, Insts);
Insts.clear();
}
}
void DxilGenerationPass::TranslateParamDxilResourceHandles(Function *F, std::unordered_map<Instruction *, Value *> &handleMap) {
Type *handleTy = m_pHLModule->GetOP()->GetHandleType();
IRBuilder<> Builder(F->getEntryBlock().getFirstInsertionPt());
for (Argument &arg : F->args()) {
Type *Ty = arg.getType();
if (isa<PointerType>(Ty))
Ty = Ty->getPointerElementType();
SmallVector<unsigned,4> arraySizeList;
while (isa<ArrayType>(Ty)) {
arraySizeList.push_back(Ty->getArrayNumElements());
Ty = Ty->getArrayElementType();
}
DXIL::ResourceClass RC = m_pHLModule->GetResourceClass(Ty);
if (RC != DXIL::ResourceClass::Invalid) {
Type *curTy = handleTy;
for (auto it = arraySizeList.rbegin(), E = arraySizeList.rend(); it != E;
it++) {
curTy = ArrayType::get(curTy, *it);
}
curTy = PointerType::get(curTy, 0);
CallInst *castToHandle = cast<CallInst>(HLModule::EmitHLOperationCall(
Builder, HLOpcodeGroup::HLCast, 0, curTy,
{UndefValue::get(arg.getType())}, *F->getParent()));
for (User *U : arg.users()) {
Instruction *I = cast<Instruction>(U);
IRBuilder<> userBuilder(I);
if (LoadInst *ldInst = dyn_cast<LoadInst>(U)) {
Value *handleLd = userBuilder.CreateLoad(castToHandle);
handleMap[ldInst] = handleLd;
} else if (StoreInst *stInst = dyn_cast<StoreInst>(U)) {
Value *res = stInst->getValueOperand();
Value *handle = HLModule::EmitHLOperationCall(
userBuilder, HLOpcodeGroup::HLCast, 0, handleTy, {res},
*F->getParent());
userBuilder.CreateStore(handle, castToHandle);
} else if (dyn_cast<CallInst>(U)) {
// Don't flatten argument here.
continue;
} else {
DXASSERT(
dyn_cast<GEPOperator>(U) != nullptr,
"else AddOpcodeParamForIntrinsic in CodeGen did not patch uses "
"to only have ld/st refer to temp object");
GEPOperator *GEP = cast<GEPOperator>(U);
std::vector<Value *> idxList(GEP->idx_begin(), GEP->idx_end());
Value *handleGEP = userBuilder.CreateGEP(castToHandle, idxList);
for (auto GEPU : GEP->users()) {
Instruction *GEPI = cast<Instruction>(GEPU);
IRBuilder<> gepUserBuilder(GEPI);
if (LoadInst *ldInst = dyn_cast<LoadInst>(GEPU)) {
handleMap[ldInst] = gepUserBuilder.CreateLoad(handleGEP);
} else {
StoreInst *stInst = cast<StoreInst>(GEPU);
Value *res = stInst->getValueOperand();
Value *handle = HLModule::EmitHLOperationCall(
gepUserBuilder, HLOpcodeGroup::HLCast, 0, handleTy, {res},
*F->getParent());
gepUserBuilder.CreateStore(handle, handleGEP);
}
}
}
}
castToHandle->setArgOperand(0, &arg);
}
}
}
void DxilGenerationPass::GenerateParamDxilResourceHandles(
std::unordered_map<Instruction *, Value *> &handleMap) {
Module &M = *m_pHLModule->GetModule();
for (Function &F : M.functions()) {
if (!F.isDeclaration())
TranslateParamDxilResourceHandles(&F, handleMap);
}
}
void DxilGenerationPass::TranslateDxilResourceUses(
DxilResourceBase &res, std::unordered_set<LoadInst *> &UpdateCounterSet,
std::unordered_set<Value *> &NonUniformSet) {
OP *hlslOP = m_pHLModule->GetOP();
Function *createHandle = hlslOP->GetOpFunc(
OP::OpCode::CreateHandle, llvm::Type::getVoidTy(m_pHLModule->GetCtx()));
Value *opArg = hlslOP->GetU32Const((unsigned)OP::OpCode::CreateHandle);
bool isViewResource = res.GetClass() == DXIL::ResourceClass::SRV || res.GetClass() == DXIL::ResourceClass::UAV;
bool isROV = isViewResource && static_cast<DxilResource &>(res).IsROV();
std::string handleName = (res.GetGlobalName() + Twine("_") + Twine(res.GetResClassName())).str();
if (isViewResource)
handleName += (Twine("_") + Twine(res.GetResDimName())).str();
if (isROV)
handleName += "_ROV";
Value *resClassArg = hlslOP->GetU8Const(
static_cast<std::underlying_type<DxilResourceBase::Class>::type>(
res.GetClass()));
Value *resIDArg = hlslOP->GetU32Const(res.GetID());
// resLowerBound will be added after allocation in DxilCondenseResources.
Value *resLowerBound = hlslOP->GetU32Const(0);
// TODO: Set Non-uniform resource bit based on whether index comes from IOP_NonUniformResourceIndex.
Value *isUniformRes = hlslOP->GetI1Const(0);
Value *GV = res.GetGlobalSymbol();
Module *pM = m_pHLModule->GetModule();
// TODO: add debug info to create handle.
DIVariable *DIV = nullptr;
DILocation *DL = nullptr;
if (m_HasDbgInfo) {
DebugInfoFinder &Finder = m_pHLModule->GetOrCreateDebugInfoFinder();
DIV =
HLModule::FindGlobalVariableDebugInfo(cast<GlobalVariable>(GV), Finder);
if (DIV)
// TODO: how to get col?
DL =
DILocation::get(pM->getContext(), DIV->getLine(), 1, DIV->getScope());
}
bool isResArray = res.GetRangeSize() > 1;
std::unordered_map<Function *, Instruction *> handleMapOnFunction;
Value *createHandleArgs[] = {opArg, resClassArg, resIDArg, resLowerBound,
isUniformRes};
for (iplist<Function>::iterator F : pM->getFunctionList()) {
if (!F->isDeclaration()) {
if (!isResArray) {
IRBuilder<> Builder(F->getEntryBlock().getFirstInsertionPt());
if (m_HasDbgInfo) {
// TODO: set debug info.
//Builder.SetCurrentDebugLocation(DL);
(void)(DL);
}
handleMapOnFunction[F] = Builder.CreateCall(createHandle, createHandleArgs, handleName);
}
}
}
for (auto U = GV->user_begin(), E = GV->user_end(); U != E; ) {
User *user = *(U++);
// Skip unused user.
if (user->user_empty())
continue;
if (LoadInst *ldInst = dyn_cast<LoadInst>(user)) {
if (UpdateCounterSet.count(ldInst)) {
DxilResource *resource = llvm::dyn_cast<DxilResource>(&res);
DXASSERT_NOMSG(resource);
DXASSERT_NOMSG(resource->GetClass() == DXIL::ResourceClass::UAV);
resource->SetHasCounter(true);
}
Function *userF = ldInst->getParent()->getParent();
DXASSERT(handleMapOnFunction.count(userF), "must exist");
Value *handle = handleMapOnFunction[userF];
ReplaceResourceUserWithHandle(ldInst, handle);
} else {
DXASSERT(dyn_cast<GEPOperator>(user) != nullptr,
"else AddOpcodeParamForIntrinsic in CodeGen did not patch uses "
"to only have ld/st refer to temp object");
GEPOperator *GEP = cast<GEPOperator>(user);
Value *idx = nullptr;
if (GEP->getNumIndices() == 2) {
// one dim array of resource
idx = (GEP->idx_begin() + 1)->get();
} else {
gep_type_iterator GEPIt = gep_type_begin(GEP), E = gep_type_end(GEP);
// Must be instruction for multi dim array.
std::unique_ptr<IRBuilder<> > Builder;
if (GetElementPtrInst *GEPInst = dyn_cast<GetElementPtrInst>(GEP)) {
Builder = llvm::make_unique<IRBuilder<> >(GEPInst);
} else {
Builder = llvm::make_unique<IRBuilder<> >(GV->getContext());
}
for (; GEPIt != E; ++GEPIt) {
if (GEPIt->isArrayTy()) {
unsigned arraySize = GEPIt->getArrayNumElements();
Value * tmpIdx = GEPIt.getOperand();
if (idx == nullptr)
idx = tmpIdx;
else {
idx = Builder->CreateMul(idx, Builder->getInt32(arraySize));
idx = Builder->CreateAdd(idx, tmpIdx);
}
}
}
}
createHandleArgs[DXIL::OperandIndex::kCreateHandleResIndexOpIdx] = idx;
if (!NonUniformSet.count(idx))
createHandleArgs[DXIL::OperandIndex::kCreateHandleIsUniformOpIdx] =
isUniformRes;
else
createHandleArgs[DXIL::OperandIndex::kCreateHandleIsUniformOpIdx] =
hlslOP->GetI1Const(1);
Value *handle = nullptr;
if (GetElementPtrInst *GEPInst = dyn_cast<GetElementPtrInst>(GEP)) {
IRBuilder<> Builder = IRBuilder<>(GEPInst);
handle = Builder.CreateCall(createHandle, createHandleArgs, handleName);
}
for (auto GEPU = GEP->user_begin(), GEPE = GEP->user_end(); GEPU != GEPE; ) {
// Must be load inst.
LoadInst *ldInst = cast<LoadInst>(*(GEPU++));
if (UpdateCounterSet.count(ldInst)) {
DxilResource *resource = dyn_cast<DxilResource>(&res);
DXASSERT_NOMSG(resource);
DXASSERT_NOMSG(resource->GetClass() == DXIL::ResourceClass::UAV);
resource->SetHasCounter(true);
}
if (handle) {
ReplaceResourceUserWithHandle(ldInst, handle);
}
else {
IRBuilder<> Builder = IRBuilder<>(ldInst);
Value *localHandle = Builder.CreateCall(createHandle, createHandleArgs, handleName);
ReplaceResourceUserWithHandle(ldInst, localHandle);
}
}
}
}
// Erase unused handle.
for (auto It : handleMapOnFunction) {
Instruction *I = It.second;
if (I->user_empty())
I->eraseFromParent();
}
}
void DxilGenerationPass::GenerateDxilResourceHandles(
std::unordered_set<LoadInst *> &UpdateCounterSet,
std::unordered_set<Value *> &NonUniformSet) {
// Create sampler handle first, may be used by SRV operations.
for (size_t i = 0; i < m_pHLModule->GetSamplers().size(); i++) {
DxilSampler &S = m_pHLModule->GetSampler(i);
TranslateDxilResourceUses(S, UpdateCounterSet, NonUniformSet);
}
for (size_t i = 0; i < m_pHLModule->GetSRVs().size(); i++) {
HLResource &SRV = m_pHLModule->GetSRV(i);
TranslateDxilResourceUses(SRV, UpdateCounterSet, NonUniformSet);
}
for (size_t i = 0; i < m_pHLModule->GetUAVs().size(); i++) {
HLResource &UAV = m_pHLModule->GetUAV(i);
TranslateDxilResourceUses(UAV, UpdateCounterSet, NonUniformSet);
}
}
static void
AddResourceToSet(Instruction *Res, std::unordered_set<Instruction *> &resSet) {
unsigned startOpIdx = 0;
// Skip Cond for Select.
if (isa<SelectInst>(Res))
startOpIdx = 1;
else if (!isa<PHINode>(Res))
// Only check phi and select here.
return;
// Already add.
if (resSet.count(Res))
return;
resSet.insert(Res);
// Scan operand to add resource node which only used by phi/select.
unsigned numOperands = Res->getNumOperands();
for (unsigned i = startOpIdx; i < numOperands; i++) {
Value *V = Res->getOperand(i);
if (Instruction *I = dyn_cast<Instruction>(V)) {
AddResourceToSet(I, resSet);
}
}
}
// Transform
//
// %g_texture_texture_2d1 = call %dx.types.Handle @dx.op.createHandle(i32 57, i8 0, i32 0, i32 0, i1 false)
// %g_texture_texture_2d = call %dx.types.Handle @dx.op.createHandle(i32 57, i8 0, i32 0, i32 2, i1 false)
// %13 = select i1 %cmp, %dx.types.Handle %g_texture_texture_2d1, %dx.types.Handle %g_texture_texture_2d
// Into
// %11 = select i1 %cmp, i32 0, i32 2
// %12 = call %dx.types.Handle @dx.op.createHandle(i32 57, i8 0, i32 0, i32 %11, i1 false)
//
static bool MergeHandleOpWithSameValue(Instruction *HandleOp,
unsigned startOpIdx,
unsigned numOperands) {
Value *op0 = nullptr;
for (unsigned i = startOpIdx; i < numOperands; i++) {
Value *op = HandleOp->getOperand(i);
if (i == startOpIdx) {
op0 = op;
} else {
if (op0 != op)
op0 = nullptr;
}
}
if (op0) {
HandleOp->replaceAllUsesWith(op0);
return true;
}
return false;
}
static void
UpdateHandleOperands(Instruction *Res,
std::unordered_map<Instruction *, CallInst *> &handleMap,
std::unordered_set<Instruction *> &nonUniformOps) {
unsigned numOperands = Res->getNumOperands();
unsigned startOpIdx = 0;
// Skip Cond for Select.
if (dyn_cast<SelectInst>(Res))
startOpIdx = 1;
CallInst *Handle = handleMap[Res];
Instruction *resClass = cast<Instruction>(
Handle->getArgOperand(DXIL::OperandIndex::kCreateHandleResClassOpIdx));
Instruction *resID = cast<Instruction>(
Handle->getArgOperand(DXIL::OperandIndex::kCreateHandleResIDOpIdx));
Instruction *resAddr = cast<Instruction>(
Handle->getArgOperand(DXIL::OperandIndex::kCreateHandleResIndexOpIdx));
for (unsigned i = startOpIdx; i < numOperands; i++) {
if (!isa<Instruction>(Res->getOperand(i))) {
EmitResMappingError(Res);
continue;
}
Instruction *ResOp = cast<Instruction>(Res->getOperand(i));
CallInst *HandleOp = dyn_cast<CallInst>(ResOp);
if (!HandleOp) {
if (handleMap.count(ResOp)) {
EmitResMappingError(Res);
continue;
}
HandleOp = handleMap[ResOp];
}
Value *resClassOp =
HandleOp->getArgOperand(DXIL::OperandIndex::kCreateHandleResClassOpIdx);
Value *resIDOp =
HandleOp->getArgOperand(DXIL::OperandIndex::kCreateHandleResIDOpIdx);
Value *resAddrOp =
HandleOp->getArgOperand(DXIL::OperandIndex::kCreateHandleResIndexOpIdx);
resClass->setOperand(i, resClassOp);
resID->setOperand(i, resIDOp);
resAddr->setOperand(i, resAddrOp);
}
if (!MergeHandleOpWithSameValue(resClass, startOpIdx, numOperands))
nonUniformOps.insert(resClass);
if (!MergeHandleOpWithSameValue(resID, startOpIdx, numOperands))
nonUniformOps.insert(resID);
MergeHandleOpWithSameValue(resAddr, startOpIdx, numOperands);
}
void DxilGenerationPass::AddCreateHandleForPhiNodeAndSelect(OP *hlslOP) {
Function *createHandle = hlslOP->GetOpFunc(
OP::OpCode::CreateHandle, llvm::Type::getVoidTy(hlslOP->GetCtx()));
std::unordered_set<PHINode *> objPhiList;
std::unordered_set<SelectInst *> objSelectList;
std::unordered_set<Instruction *> resSelectSet;
for (User *U : createHandle->users()) {
for (User *HandleU : U->users()) {
Instruction *I = cast<Instruction>(HandleU);
if (!isa<CallInst>(I))
AddResourceToSet(I, resSelectSet);
}
}
// Generate Handle inst for Res inst.
FunctionType *FT = createHandle->getFunctionType();
Value *opArg = hlslOP->GetU32Const((unsigned)OP::OpCode::CreateHandle);
Type *resClassTy =
FT->getParamType(DXIL::OperandIndex::kCreateHandleResClassOpIdx);
Type *resIDTy = FT->getParamType(DXIL::OperandIndex::kCreateHandleResIDOpIdx);
Type *resAddrTy =
FT->getParamType(DXIL::OperandIndex::kCreateHandleResIndexOpIdx);
Value *UndefResClass = UndefValue::get(resClassTy);
Value *UndefResID = UndefValue::get(resIDTy);
Value *UndefResAddr = UndefValue::get(resAddrTy);
// phi/select node resource is not uniform
Value *nonUniformRes = hlslOP->GetI1Const(1);
std::unordered_map<Instruction *, CallInst *> handleMap;
for (Instruction *Res : resSelectSet) {
unsigned numOperands = Res->getNumOperands();
IRBuilder<> Builder(Res);
// Skip Cond for Select.
if (SelectInst *Sel = dyn_cast<SelectInst>(Res)) {
Value *Cond = Sel->getCondition();
Value *resClassSel =
Builder.CreateSelect(Cond, UndefResClass, UndefResClass);
Value *resIDSel = Builder.CreateSelect(Cond, UndefResID, UndefResID);
Value *resAddrSel =
Builder.CreateSelect(Cond, UndefResAddr, UndefResAddr);
CallInst *HandleSel =
Builder.CreateCall(createHandle, {opArg, resClassSel, resIDSel,
resAddrSel, nonUniformRes});
handleMap[Res] = HandleSel;
Res->replaceAllUsesWith(HandleSel);
} else {
PHINode *Phi = cast<PHINode>(Res); // res class must be same.
PHINode *resClassPhi = Builder.CreatePHI(resClassTy, numOperands);
PHINode *resIDPhi = Builder.CreatePHI(resIDTy, numOperands);
PHINode *resAddrPhi = Builder.CreatePHI(resAddrTy, numOperands);
for (unsigned i = 0; i < numOperands; i++) {
BasicBlock *BB = Phi->getIncomingBlock(i);
resClassPhi->addIncoming(UndefResClass, BB);
resIDPhi->addIncoming(UndefResID, BB);
resAddrPhi->addIncoming(UndefResAddr, BB);
}
IRBuilder<> HandleBuilder(Phi->getParent()->getFirstNonPHI());
CallInst *HandlePhi =
HandleBuilder.CreateCall(createHandle, {opArg, resClassPhi, resIDPhi,
resAddrPhi, nonUniformRes});
handleMap[Res] = HandlePhi;
Res->replaceAllUsesWith(HandlePhi);
}
}
// Update operand for Handle phi/select.
// If ResClass or ResID is phi/select, save to nonUniformOps.
std::unordered_set<Instruction *> nonUniformOps;
for (Instruction *Res : resSelectSet) {
UpdateHandleOperands(Res, handleMap, nonUniformOps);
}
bool bIsLib = m_pHLModule->GetShaderModel()->IsLib();
// ResClass and ResID must be uniform.
// Try to merge res class, res id into imm.
while (1) {
bool bUpdated = false;
for (auto It = nonUniformOps.begin(); It != nonUniformOps.end();) {
Instruction *I = *(It++);
unsigned numOperands = I->getNumOperands();
unsigned startOpIdx = 0;
// Skip Cond for Select.
if (dyn_cast<SelectInst>(I))
startOpIdx = 1;
if (MergeHandleOpWithSameValue(I, startOpIdx, numOperands)) {
nonUniformOps.erase(I);
bUpdated = true;
}
}
if (!bUpdated) {
if (!nonUniformOps.empty() && !bIsLib) {
for (Instruction *I : nonUniformOps) {
// Non uniform res class or res id.
EmitResMappingError(I);
}
return;
}
break;
}
}
// Remove useless select/phi.
for (Instruction *Res : resSelectSet) {
Res->eraseFromParent();
}
}
void DxilGenerationPass::GenerateDxilCBufferHandles(
std::unordered_set<Value *> &NonUniformSet) {
// For CBuffer, handle are mapped to HLCreateHandle.
OP *hlslOP = m_pHLModule->GetOP();
Function *createHandle = hlslOP->GetOpFunc(
OP::OpCode::CreateHandle, llvm::Type::getVoidTy(m_pHLModule->GetCtx()));
Value *opArg = hlslOP->GetU32Const((unsigned)OP::OpCode::CreateHandle);
Value *resClassArg = hlslOP->GetU8Const(
static_cast<std::underlying_type<DxilResourceBase::Class>::type>(
DXIL::ResourceClass::CBuffer));
for (size_t i = 0; i < m_pHLModule->GetCBuffers().size(); i++) {
DxilCBuffer &CB = m_pHLModule->GetCBuffer(i);
GlobalVariable *GV = cast<GlobalVariable>(CB.GetGlobalSymbol());
// Remove GEP created in HLObjectOperationLowerHelper::UniformCbPtr.
GV->removeDeadConstantUsers();
std::string handleName = std::string(GV->getName()) + "_buffer";
Value *args[] = {opArg, resClassArg, nullptr, nullptr,
hlslOP->GetI1Const(0)};
DIVariable *DIV = nullptr;
DILocation *DL = nullptr;
if (m_HasDbgInfo) {
DebugInfoFinder &Finder = m_pHLModule->GetOrCreateDebugInfoFinder();
DIV = HLModule::FindGlobalVariableDebugInfo(GV, Finder);
if (DIV)
// TODO: how to get col?
DL = DILocation::get(createHandle->getContext(), DIV->getLine(), 1,
DIV->getScope());
}
Value *resIDArg = hlslOP->GetU32Const(CB.GetID());
args[DXIL::OperandIndex::kCreateHandleResIDOpIdx] = resIDArg;
// resLowerBound will be added after allocation in DxilCondenseResources.
Value *resLowerBound = hlslOP->GetU32Const(0);
if (CB.GetRangeSize() == 1) {
args[DXIL::OperandIndex::kCreateHandleResIndexOpIdx] = resLowerBound;
for (auto U = GV->user_begin(); U != GV->user_end(); ) {
// Must HLCreateHandle.
CallInst *CI = cast<CallInst>(*(U++));
// Put createHandle to entry block.
auto InsertPt =
CI->getParent()->getParent()->getEntryBlock().getFirstInsertionPt();
IRBuilder<> Builder(InsertPt);
CallInst *handle = Builder.CreateCall(createHandle, args, handleName);
if (m_HasDbgInfo) {
// TODO: add debug info.
//handle->setDebugLoc(DL);
(void)(DL);
}
CI->replaceAllUsesWith(handle);
CI->eraseFromParent();
}
} else {
for (auto U = GV->user_begin(); U != GV->user_end(); ) {
// Must HLCreateHandle.
CallInst *CI = cast<CallInst>(*(U++));
IRBuilder<> Builder(CI);
Value *CBIndex = CI->getArgOperand(HLOperandIndex::kCreateHandleIndexOpIdx);
args[DXIL::OperandIndex::kCreateHandleResIndexOpIdx] =
CBIndex;
if (isa<ConstantInt>(CBIndex)) {
// Put createHandle to entry block for const index.
auto InsertPt = CI->getParent()
->getParent()
->getEntryBlock()
.getFirstInsertionPt();
Builder.SetInsertPoint(InsertPt);
}
if (!NonUniformSet.count(CBIndex))
args[DXIL::OperandIndex::kCreateHandleIsUniformOpIdx] =
hlslOP->GetI1Const(0);
else
args[DXIL::OperandIndex::kCreateHandleIsUniformOpIdx] =
hlslOP->GetI1Const(1);
CallInst *handle = Builder.CreateCall(createHandle, args, handleName);
CI->replaceAllUsesWith(handle);
CI->eraseFromParent();
}
}
}
}
void DxilGenerationPass::GenerateDxilOperations(
Module &M, std::unordered_set<LoadInst *> &UpdateCounterSet,
std::unordered_set<Value *> &NonUniformSet) {
// remove all functions except entry function
Function *entry = m_pHLModule->GetEntryFunction();
const ShaderModel *pSM = m_pHLModule->GetShaderModel();
Function *patchConstantFunc = nullptr;
if (pSM->IsHS()) {
DxilFunctionProps &funcProps = m_pHLModule->GetDxilFunctionProps(entry);
patchConstantFunc = funcProps.ShaderProps.HS.patchConstantFunc;
}
if (!pSM->IsLib()) {
for (auto F = M.begin(); F != M.end();) {
Function *func = F++;
if (func->isDeclaration())
continue;
if (func == entry)
continue;
if (func == patchConstantFunc)
continue;
if (func->user_empty())
func->eraseFromParent();
}
}
TranslateBuiltinOperations(*m_pHLModule, m_extensionsCodegenHelper,
UpdateCounterSet, NonUniformSet);
// Remove unused HL Operation functions.
std::vector<Function *> deadList;
for (iplist<Function>::iterator F : M.getFunctionList()) {
hlsl::HLOpcodeGroup group = hlsl::GetHLOpcodeGroupByName(F);
if (group != HLOpcodeGroup::NotHL || F->isIntrinsic())
if (F->user_empty())
deadList.emplace_back(F);
}
for (Function *F : deadList)
F->eraseFromParent();
}
static void TranslatePreciseAttributeOnFunction(Function &F, Module &M) {
BasicBlock &BB = F.getEntryBlock(); // Get the entry node for the function
// Find allocas that has precise attribute, by looking at all instructions in
// the entry node
for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E;) {
Instruction *Inst = (I++);
if (AllocaInst *AI = dyn_cast<AllocaInst>(Inst)) {
if (HLModule::HasPreciseAttributeWithMetadata(AI)) {
HLModule::MarkPreciseAttributeOnPtrWithFunctionCall(AI, M);
}
} else {
DXASSERT(!HLModule::HasPreciseAttributeWithMetadata(Inst), "Only alloca can has precise metadata.");
}
}
FastMathFlags FMF;
FMF.setUnsafeAlgebra();
// Set fast math for all FPMathOperators.
// Already set FastMath in options. But that only enable things like fadd.
// Every inst which type is float can be cast to FPMathOperator.
for (Function::iterator BBI = F.begin(), BBE = F.end(); BBI != BBE; ++BBI) {
BasicBlock *BB = BBI;
for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
if (dyn_cast<FPMathOperator>(I)) {
// Set precise fast math on those instructions that support it.
if (DxilModule::PreservesFastMathFlags(I))
I->copyFastMathFlags(FMF);
}
}
}
}
void DxilGenerationPass::TranslatePreciseAttribute() {
bool bIEEEStrict = m_pHLModule->GetHLOptions().bIEEEStrict;
// If IEEE strict, everying is precise, don't need to mark it.
if (bIEEEStrict)
return;
Module &M = *m_pHLModule->GetModule();
// TODO: If not inline every function, for function has call site with precise
// argument and call site without precise argument, need to clone the function
// to propagate the precise for the precise call site.
// This should be done at CGMSHLSLRuntime::FinishCodeGen.
Function *EntryFn = m_pHLModule->GetEntryFunction();
if (!m_pHLModule->GetShaderModel()->IsLib()) {
TranslatePreciseAttributeOnFunction(*EntryFn, M);
}
if (m_pHLModule->GetShaderModel()->IsHS()) {
DxilFunctionProps &EntryQual = m_pHLModule->GetDxilFunctionProps(EntryFn);
Function *patchConstantFunc = EntryQual.ShaderProps.HS.patchConstantFunc;
TranslatePreciseAttributeOnFunction(*patchConstantFunc, M);
}
}
char DxilGenerationPass::ID = 0;
ModulePass *llvm::createDxilGenerationPass(bool NotOptimized, hlsl::HLSLExtensionsCodegenHelper *extensionsHelper) {
DxilGenerationPass *dxilPass = new DxilGenerationPass(NotOptimized);
dxilPass->SetExtensionsHelper(extensionsHelper);
return dxilPass;
}
INITIALIZE_PASS(DxilGenerationPass, "dxilgen", "HLSL DXIL Generation", false, false)
///////////////////////////////////////////////////////////////////////////////
namespace {
StructType *UpdateStructTypeForLegacyLayout(StructType *ST, bool IsCBuf,
DxilTypeSystem &TypeSys, Module &M);
Type *UpdateFieldTypeForLegacyLayout(Type *Ty, bool IsCBuf, DxilFieldAnnotation &annotation,
DxilTypeSystem &TypeSys, Module &M) {
DXASSERT(!Ty->isPointerTy(), "struct field should not be a pointer");
if (Ty->isArrayTy()) {
Type *EltTy = Ty->getArrayElementType();
Type *UpdatedTy = UpdateFieldTypeForLegacyLayout(EltTy, IsCBuf, annotation, TypeSys, M);
if (EltTy == UpdatedTy)
return Ty;
else
return ArrayType::get(UpdatedTy, Ty->getArrayNumElements());
} else if (HLMatrixLower::IsMatrixType(Ty)) {
DXASSERT(annotation.HasMatrixAnnotation(), "must a matrix");
unsigned rows, cols;
Type *EltTy = HLMatrixLower::GetMatrixInfo(Ty, cols, rows);
// Get cols and rows from annotation.
const DxilMatrixAnnotation &matrix = annotation.GetMatrixAnnotation();
if (matrix.Orientation == MatrixOrientation::RowMajor) {
rows = matrix.Rows;
cols = matrix.Cols;
} else {
DXASSERT_NOMSG(matrix.Orientation == MatrixOrientation::ColumnMajor);
cols = matrix.Rows;
rows = matrix.Cols;
}
// CBuffer matrix must 4 * 4 bytes align.
if (IsCBuf)
cols = 4;
EltTy = UpdateFieldTypeForLegacyLayout(EltTy, IsCBuf, annotation, TypeSys, M);
Type *rowTy = VectorType::get(EltTy, cols);
return ArrayType::get(rowTy, rows);
} else if (StructType *ST = dyn_cast<StructType>(Ty)) {
return UpdateStructTypeForLegacyLayout(ST, IsCBuf, TypeSys, M);
} else if (Ty->isVectorTy()) {
Type *EltTy = Ty->getVectorElementType();
Type *UpdatedTy = UpdateFieldTypeForLegacyLayout(EltTy, IsCBuf, annotation, TypeSys, M);
if (EltTy == UpdatedTy)
return Ty;
else
return VectorType::get(UpdatedTy, Ty->getVectorNumElements());
} else {
Type *i32Ty = Type::getInt32Ty(Ty->getContext());
// Basic types.
if (Ty->isHalfTy()) {
return Type::getFloatTy(Ty->getContext());
} else if (IntegerType *ITy = dyn_cast<IntegerType>(Ty)) {
if (ITy->getBitWidth() < 32)
return i32Ty;
else
return Ty;
} else
return Ty;
}
}
StructType *UpdateStructTypeForLegacyLayout(StructType *ST, bool IsCBuf,
DxilTypeSystem &TypeSys, Module &M) {
bool bUpdated = false;
unsigned fieldsCount = ST->getNumElements();
std::vector<Type *> fieldTypes(fieldsCount);
DxilStructAnnotation *SA = TypeSys.GetStructAnnotation(ST);
DXASSERT(SA, "must have annotation for struct type");
for (unsigned i = 0; i < fieldsCount; i++) {
Type *EltTy = ST->getElementType(i);
Type *UpdatedTy =
UpdateFieldTypeForLegacyLayout(EltTy, IsCBuf, SA->GetFieldAnnotation(i), TypeSys, M);
fieldTypes[i] = UpdatedTy;
if (EltTy != UpdatedTy)
bUpdated = true;
}
if (!bUpdated) {
return ST;
} else {
std::string legacyName = "dx.alignment.legacy." + ST->getName().str();
if (StructType *legacyST = M.getTypeByName(legacyName))
return legacyST;
StructType *NewST = StructType::create(ST->getContext(), fieldTypes, legacyName);
DxilStructAnnotation *NewSA = TypeSys.AddStructAnnotation(NewST);
// Clone annotation.
*NewSA = *SA;
return NewST;
}
}
void UpdateStructTypeForLegacyLayout(DxilResourceBase &Res, DxilTypeSystem &TypeSys, Module &M) {
GlobalVariable *GV = cast<GlobalVariable>(Res.GetGlobalSymbol());
Type *Ty = GV->getType()->getPointerElementType();
bool IsResourceArray = Res.GetRangeSize() != 1;
if (IsResourceArray) {
// Support Array of struct buffer.
if (Ty->isArrayTy())
Ty = Ty->getArrayElementType();
}
StructType *ST = cast<StructType>(Ty);
if (ST->isOpaque()) {
DXASSERT(Res.GetClass() == DxilResourceBase::Class::CBuffer,
"Only cbuffer can have opaque struct.");
return;
}
Type *UpdatedST = UpdateStructTypeForLegacyLayout(ST, IsResourceArray, TypeSys, M);
if (ST != UpdatedST) {
Type *Ty = GV->getType()->getPointerElementType();
if (IsResourceArray) {
// Support Array of struct buffer.
if (Ty->isArrayTy()) {
UpdatedST = ArrayType::get(UpdatedST, Ty->getArrayNumElements());
}
}
GlobalVariable *NewGV = cast<GlobalVariable>(M.getOrInsertGlobal(GV->getName().str() + "_legacy", UpdatedST));
Res.SetGlobalSymbol(NewGV);
// Delete old GV.
for (auto UserIt = GV->user_begin(); UserIt != GV->user_end(); ) {
Value *User = *(UserIt++);
if (Instruction *I = dyn_cast<Instruction>(User)) {
if (!User->user_empty())
I->replaceAllUsesWith(UndefValue::get(I->getType()));
I->eraseFromParent();
} else {
ConstantExpr *CE = cast<ConstantExpr>(User);
if (!CE->user_empty())
CE->replaceAllUsesWith(UndefValue::get(CE->getType()));
}
}
GV->removeDeadConstantUsers();
GV->eraseFromParent();
}
}
void UpdateStructTypeForLegacyLayoutOnHLM(HLModule &HLM) {
DxilTypeSystem &TypeSys = HLM.GetTypeSystem();
Module &M = *HLM.GetModule();
for (auto &CBuf : HLM.GetCBuffers()) {
UpdateStructTypeForLegacyLayout(*CBuf.get(), TypeSys, M);
}
for (auto &UAV : HLM.GetUAVs()) {
if (UAV->GetKind() == DxilResourceBase::Kind::StructuredBuffer)
UpdateStructTypeForLegacyLayout(*UAV.get(), TypeSys, M);
}
for (auto &SRV : HLM.GetSRVs()) {
if (SRV->GetKind() == DxilResourceBase::Kind::StructuredBuffer)
UpdateStructTypeForLegacyLayout(*SRV.get(), TypeSys, M);
}
}
}
void DxilGenerationPass::UpdateStructTypeForLegacyLayout() {
UpdateStructTypeForLegacyLayoutOnHLM(*m_pHLModule);
}
///////////////////////////////////////////////////////////////////////////////
namespace {
class HLEmitMetadata : public ModulePass {
public:
static char ID; // Pass identification, replacement for typeid
explicit HLEmitMetadata() : ModulePass(ID) {}
const char *getPassName() const override { return "HLSL High-Level Metadata Emit"; }
bool runOnModule(Module &M) override {
if (M.HasHLModule()) {
HLModule::ClearHLMetadata(M);
M.GetHLModule().EmitHLMetadata();
return true;
}
return false;
}
};
}
char HLEmitMetadata::ID = 0;
ModulePass *llvm::createHLEmitMetadataPass() {
return new HLEmitMetadata();
}
INITIALIZE_PASS(HLEmitMetadata, "hlsl-hlemit", "HLSL High-Level Metadata Emit", false, false)
///////////////////////////////////////////////////////////////////////////////
namespace {
class HLEnsureMetadata : public ModulePass {
public:
static char ID; // Pass identification, replacement for typeid
explicit HLEnsureMetadata() : ModulePass(ID) {}
const char *getPassName() const override { return "HLSL High-Level Metadata Ensure"; }
bool runOnModule(Module &M) override {
if (!M.HasHLModule()) {
M.GetOrCreateHLModule();
return true;
}
return false;
}
};
}
char HLEnsureMetadata::ID = 0;
ModulePass *llvm::createHLEnsureMetadataPass() {
return new HLEnsureMetadata();
}
INITIALIZE_PASS(HLEnsureMetadata, "hlsl-hlensure", "HLSL High-Level Metadata Ensure", false, false)
///////////////////////////////////////////////////////////////////////////////
// Precise propagate.
namespace {
class DxilPrecisePropagatePass : public ModulePass {
public:
static char ID; // Pass identification, replacement for typeid
explicit DxilPrecisePropagatePass() : ModulePass(ID) {}
const char *getPassName() const override { return "DXIL Precise Propagate"; }
bool runOnModule(Module &M) override {
DxilModule &dxilModule = M.GetOrCreateDxilModule();
DxilTypeSystem &typeSys = dxilModule.GetTypeSystem();
std::unordered_set<Instruction*> processedSet;
std::vector<Function*> deadList;
for (Function &F : M.functions()) {
if (HLModule::HasPreciseAttribute(&F)) {
PropagatePreciseOnFunctionUser(F, typeSys, processedSet);
deadList.emplace_back(&F);
}
}
for (Function *F : deadList)
F->eraseFromParent();
return true;
}
private:
void PropagatePreciseOnFunctionUser(
Function &F, DxilTypeSystem &typeSys,
std::unordered_set<Instruction *> &processedSet);
};
char DxilPrecisePropagatePass::ID = 0;
}
static void PropagatePreciseAttribute(Instruction *I, DxilTypeSystem &typeSys,
std::unordered_set<Instruction *> &processedSet);
static void PropagatePreciseAttributeOnOperand(
Value *V, DxilTypeSystem &typeSys, LLVMContext &Context,
std::unordered_set<Instruction *> &processedSet) {
Instruction *I = dyn_cast<Instruction>(V);
// Skip none inst.
if (!I)
return;
FPMathOperator *FPMath = dyn_cast<FPMathOperator>(I);
// Skip none FPMath
if (!FPMath)
return;
// Skip inst already marked.
if (processedSet.count(I) > 0)
return;
// TODO: skip precise on integer type, sample instruction...
processedSet.insert(I);
// Set precise fast math on those instructions that support it.
if (DxilModule::PreservesFastMathFlags(I))
DxilModule::SetPreciseFastMathFlags(I);
// Fast math not work on call, use metadata.
if (CallInst *CI = dyn_cast<CallInst>(I))
HLModule::MarkPreciseAttributeWithMetadata(CI);
PropagatePreciseAttribute(I, typeSys, processedSet);
}
static void PropagatePreciseAttributeOnPointer(
Value *Ptr, DxilTypeSystem &typeSys, LLVMContext &Context,
std::unordered_set<Instruction *> &processedSet) {
// Find all store and propagate on the val operand of store.
// For CallInst, if Ptr is used as out parameter, mark it.
for (User *U : Ptr->users()) {
Instruction *user = cast<Instruction>(U);
if (StoreInst *stInst = dyn_cast<StoreInst>(user)) {
Value *val = stInst->getValueOperand();
PropagatePreciseAttributeOnOperand(val, typeSys, Context, processedSet);
} else if (CallInst *CI = dyn_cast<CallInst>(user)) {
bool bReadOnly = true;
Function *F = CI->getCalledFunction();
const DxilFunctionAnnotation *funcAnnotation =
typeSys.GetFunctionAnnotation(F);
for (unsigned i = 0; i < CI->getNumArgOperands(); ++i) {
if (Ptr != CI->getArgOperand(i))
continue;
const DxilParameterAnnotation ¶mAnnotation =
funcAnnotation->GetParameterAnnotation(i);
// OutputPatch and OutputStream will be checked after scalar repl.
// Here only check out/inout
if (paramAnnotation.GetParamInputQual() == DxilParamInputQual::Out ||
paramAnnotation.GetParamInputQual() == DxilParamInputQual::Inout) {
bReadOnly = false;
break;
}
}
if (!bReadOnly)
PropagatePreciseAttributeOnOperand(CI, typeSys, Context, processedSet);
}
}
}
static void
PropagatePreciseAttribute(Instruction *I, DxilTypeSystem &typeSys,
std::unordered_set<Instruction *> &processedSet) {
LLVMContext &Context = I->getContext();
if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) {
PropagatePreciseAttributeOnPointer(AI, typeSys, Context, processedSet);
} else if (dyn_cast<CallInst>(I)) {
// Propagate every argument.
// TODO: only propagate precise argument.
for (Value *src : I->operands())
PropagatePreciseAttributeOnOperand(src, typeSys, Context, processedSet);
} else if (dyn_cast<FPMathOperator>(I)) {
// TODO: only propagate precise argument.
for (Value *src : I->operands())
PropagatePreciseAttributeOnOperand(src, typeSys, Context, processedSet);
} else if (LoadInst *ldInst = dyn_cast<LoadInst>(I)) {
Value *Ptr = ldInst->getPointerOperand();
PropagatePreciseAttributeOnPointer(Ptr, typeSys, Context, processedSet);
} else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I))
PropagatePreciseAttributeOnPointer(GEP, typeSys, Context, processedSet);
// TODO: support more case which need
}
void DxilPrecisePropagatePass::PropagatePreciseOnFunctionUser(
Function &F, DxilTypeSystem &typeSys,
std::unordered_set<Instruction *> &processedSet) {
LLVMContext &Context = F.getContext();
for (auto U = F.user_begin(), E = F.user_end(); U != E;) {
CallInst *CI = cast<CallInst>(*(U++));
Value *V = CI->getArgOperand(0);
PropagatePreciseAttributeOnOperand(V, typeSys, Context, processedSet);
CI->eraseFromParent();
}
}
ModulePass *llvm::createDxilPrecisePropagatePass() {
return new DxilPrecisePropagatePass();
}
INITIALIZE_PASS(DxilPrecisePropagatePass, "hlsl-dxil-precise", "DXIL precise attribute propagate", false, false)
///////////////////////////////////////////////////////////////////////////////
namespace {
class HLDeadFunctionElimination : public ModulePass {
public:
static char ID; // Pass identification, replacement for typeid
explicit HLDeadFunctionElimination () : ModulePass(ID) {}
const char *getPassName() const override { return "Remove all unused function except entry from HLModule"; }
bool runOnModule(Module &M) override {
if (M.HasHLModule()) {
HLModule &HLM = M.GetHLModule();
bool IsLib = HLM.GetShaderModel()->IsLib();
// Remove unused functions except entry and patch constant func.
// For library profile, only remove unused external functions.
Function *EntryFunc = HLM.GetEntryFunction();
Function *PatchConstantFunc = HLM.GetPatchConstantFunction();
return dxilutil::RemoveUnusedFunctions(M, EntryFunc, PatchConstantFunc,
IsLib);
}
return false;
}
};
}
char HLDeadFunctionElimination::ID = 0;
ModulePass *llvm::createHLDeadFunctionEliminationPass() {
return new HLDeadFunctionElimination();
}
INITIALIZE_PASS(HLDeadFunctionElimination, "hl-dfe", "Remove all unused function except entry from HLModule", false, false)
///////////////////////////////////////////////////////////////////////////////
// Legalize resource use.
// Map local or static global resource to global resource.
// Require inline for static global resource.
namespace {
class DxilLegalizeStaticResourceUsePass : public ModulePass {
public:
static char ID; // Pass identification, replacement for typeid
explicit DxilLegalizeStaticResourceUsePass()
: ModulePass(ID) {}
const char *getPassName() const override {
return "DXIL Legalize Static Resource Use";
}
bool runOnModule(Module &M) override {
HLModule &HLM = M.GetOrCreateHLModule();
OP *hlslOP = HLM.GetOP();
Type *HandleTy = hlslOP->GetHandleType();
// Promote static global variables.
PromoteStaticGlobalResources(M);
// Lower handle cast.
for (Function &F : M.functions()) {
if (!F.isDeclaration())
continue;
HLOpcodeGroup group = hlsl::GetHLOpcodeGroupByName(&F);
if (group != HLOpcodeGroup::HLCast)
continue;
Type *Ty = F.getFunctionType()->getReturnType();
if (Ty->isPointerTy())
Ty = Ty->getPointerElementType();
if (HLModule::IsHLSLObjectType(Ty)) {
TransformHandleCast(F);
}
}
Value *UndefHandle = UndefValue::get(HandleTy);
if (!UndefHandle->user_empty()) {
for (User *U : UndefHandle->users()) {
// Report error if undef handle used for function call.
if (isa<CallInst>(U)) {
if (Instruction *UI = dyn_cast<Instruction>(U))
EmitResMappingError(UI);
else
M.getContext().emitError(kResourceMapErrorMsg);
}
}
}
return true;
}
private:
void PromoteStaticGlobalResources(Module &M);
void TransformHandleCast(Function &F);
};
char DxilLegalizeStaticResourceUsePass::ID = 0;
class DxilLegalizeResourceUsePass : public FunctionPass {
void getAnalysisUsage(AnalysisUsage &AU) const override;
public:
static char ID; // Pass identification, replacement for typeid
explicit DxilLegalizeResourceUsePass()
: FunctionPass(ID) {}
const char *getPassName() const override {
return "DXIL Legalize Resource Use";
}
bool runOnFunction(Function &F) override {
// Promote local resource first.
PromoteLocalResource(F);
return true;
}
private:
void PromoteLocalResource(Function &F);
};
char DxilLegalizeResourceUsePass::ID = 0;
}
void DxilLegalizeResourceUsePass::getAnalysisUsage(AnalysisUsage &AU) const {
AU.addRequired<AssumptionCacheTracker>();
AU.addRequired<DominatorTreeWrapperPass>();
AU.setPreservesAll();
}
void DxilLegalizeResourceUsePass::PromoteLocalResource(Function &F) {
std::vector<AllocaInst *> Allocas;
DominatorTree *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
AssumptionCache &AC =
getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
HLModule &HLM = F.getParent()->GetOrCreateHLModule();
OP *hlslOP = HLM.GetOP();
Type *HandleTy = hlslOP->GetHandleType();
bool IsLib = HLM.GetShaderModel()->IsLib();
BasicBlock &BB = F.getEntryBlock();
unsigned allocaSize = 0;
while (1) {
Allocas.clear();
// Find allocas that are safe to promote, by looking at all instructions in
// the entry node
for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) { // Is it an alloca?
if (HandleTy == dxilutil::GetArrayEltTy(AI->getAllocatedType())) {
// Skip for unpromotable for lib.
if (!isAllocaPromotable(AI) && IsLib)
continue;
if (!isAllocaPromotable(AI)) {
static const StringRef kNonPromotableLocalResourceErrorMsg =
"non-promotable local resource found.";
F.getContext().emitError(kNonPromotableLocalResourceErrorMsg);
throw hlsl::Exception(DXC_E_ABORT_COMPILATION_ERROR,
kNonPromotableLocalResourceErrorMsg);
continue;
}
Allocas.push_back(AI);
}
}
if (Allocas.empty())
break;
// No update.
// Report error and break.
if (allocaSize == Allocas.size()) {
F.getContext().emitError(kResourceMapErrorMsg);
break;
}
allocaSize = Allocas.size();
PromoteMemToReg(Allocas, *DT, nullptr, &AC);
}
return;
}
FunctionPass *llvm::createDxilLegalizeResourceUsePass() {
return new DxilLegalizeResourceUsePass();
}
INITIALIZE_PASS_BEGIN(DxilLegalizeResourceUsePass,
"hlsl-dxil-legalize-resource-use",
"DXIL legalize resource use", false, true)
INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
INITIALIZE_PASS_END(DxilLegalizeResourceUsePass,
"hlsl-dxil-legalize-resource-use",
"DXIL legalize resource use", false, true)
void DxilLegalizeStaticResourceUsePass::PromoteStaticGlobalResources(
Module &M) {
HLModule &HLM = M.GetOrCreateHLModule();
Type *HandleTy = HLM.GetOP()->GetHandleType();
std::set<GlobalVariable *> staticResources;
for (auto &GV : M.globals()) {
if (GV.getLinkage() == GlobalValue::LinkageTypes::InternalLinkage &&
HandleTy == dxilutil::GetArrayEltTy(GV.getType())) {
staticResources.insert(&GV);
}
}
SSAUpdater SSA;
SmallVector<Instruction *, 4> Insts;
// Make sure every resource load has mapped to global variable.
while (!staticResources.empty()) {
bool bUpdated = false;
for (auto it = staticResources.begin(); it != staticResources.end();) {
GlobalVariable *GV = *(it++);
// Build list of instructions to promote.
for (User *U : GV->users()) {
Instruction *I = cast<Instruction>(U);
Insts.emplace_back(I);
}
LoadAndStorePromoter(Insts, SSA).run(Insts);
if (GV->user_empty()) {
bUpdated = true;
staticResources.erase(GV);
}
Insts.clear();
}
if (!bUpdated) {
M.getContext().emitError(kResourceMapErrorMsg);
break;
}
}
}
static void ReplaceResUseWithHandle(Instruction *Res, Value *Handle) {
Type *HandleTy = Handle->getType();
for (auto ResU = Res->user_begin(); ResU != Res->user_end();) {
Instruction *I = cast<Instruction>(*(ResU++));
if (isa<LoadInst>(I)) {
ReplaceResUseWithHandle(I, Handle);
} else if (isa<CallInst>(I)) {
if (I->getType() == HandleTy)
I->replaceAllUsesWith(Handle);
else {
DXASSERT(0, "must createHandle here");
}
} else {
DXASSERT(0, "should only used by load and createHandle");
}
if (I->user_empty()) {
I->eraseFromParent();
}
}
}
void DxilLegalizeStaticResourceUsePass::TransformHandleCast(Function &F) {
for (auto U = F.user_begin(); U != F.user_end(); ) {
CallInst *CI = cast<CallInst>(*(U++));
Value *Handle = CI->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx);
ReplaceResUseWithHandle(CI, Handle);
if (CI->user_empty())
CI->eraseFromParent();
}
}
ModulePass *llvm::createDxilLegalizeStaticResourceUsePass() {
return new DxilLegalizeStaticResourceUsePass();
}
INITIALIZE_PASS(DxilLegalizeStaticResourceUsePass,
"hlsl-dxil-legalize-static-resource-use",
"DXIL legalize static resource use", false, false)
///////////////////////////////////////////////////////////////////////////////
// Legalize EvalOperations.
// Make sure src of EvalOperations are from function parameter.
// This is needed in order to translate EvaluateAttribute operations that traces
// back to LoadInput operations during translation stage. Promoting load/store
// instructions beforehand will allow us to easily trace back to loadInput from
// function call.
namespace {
class DxilLegalizeEvalOperations : public ModulePass {
public:
static char ID; // Pass identification, replacement for typeid
explicit DxilLegalizeEvalOperations() : ModulePass(ID) {}
const char *getPassName() const override {
return "DXIL Legalize EvalOperations";
}
bool runOnModule(Module &M) override {
for (Function &F : M.getFunctionList()) {
hlsl::HLOpcodeGroup group = hlsl::GetHLOpcodeGroup(&F);
if (group != HLOpcodeGroup::NotHL) {
std::vector<CallInst *> EvalFunctionCalls;
// Find all EvaluateAttribute calls
for (User *U : F.users()) {
if (CallInst *CI = dyn_cast<CallInst>(U)) {
IntrinsicOp evalOp =
static_cast<IntrinsicOp>(hlsl::GetHLOpcode(CI));
if (evalOp == IntrinsicOp::IOP_EvaluateAttributeAtSample ||
evalOp == IntrinsicOp::IOP_EvaluateAttributeCentroid ||
evalOp == IntrinsicOp::IOP_EvaluateAttributeSnapped ||
evalOp == IntrinsicOp::IOP_GetAttributeAtVertex) {
EvalFunctionCalls.push_back(CI);
}
}
}
if (EvalFunctionCalls.empty()) {
continue;
}
// Start from the call instruction, find all allocas that this call
// uses.
std::unordered_set<AllocaInst *> allocas;
for (CallInst *CI : EvalFunctionCalls) {
FindAllocasForEvalOperations(CI, allocas);
}
SSAUpdater SSA;
SmallVector<Instruction *, 4> Insts;
for (AllocaInst *AI : allocas) {
for (User *user : AI->users()) {
if (isa<LoadInst>(user) || isa<StoreInst>(user)) {
Insts.emplace_back(cast<Instruction>(user));
}
}
LoadAndStorePromoter(Insts, SSA).run(Insts);
Insts.clear();
}
}
}
return true;
}
private:
void FindAllocasForEvalOperations(Value *val,
std::unordered_set<AllocaInst *> &allocas);
};
char DxilLegalizeEvalOperations::ID = 0;
// Find allocas for EvaluateAttribute operations
void DxilLegalizeEvalOperations::FindAllocasForEvalOperations(
Value *val, std::unordered_set<AllocaInst *> &allocas) {
Value *CurVal = val;
while (!isa<AllocaInst>(CurVal)) {
if (CallInst *CI = dyn_cast<CallInst>(CurVal)) {
CurVal = CI->getOperand(HLOperandIndex::kUnaryOpSrc0Idx);
} else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(CurVal)) {
Value *arg0 =
IE->getOperand(0); // Could be another insertelement or undef
Value *arg1 = IE->getOperand(1);
FindAllocasForEvalOperations(arg0, allocas);
CurVal = arg1;
} else if (ShuffleVectorInst *SV = dyn_cast<ShuffleVectorInst>(CurVal)) {
Value *arg0 = SV->getOperand(0);
Value *arg1 = SV->getOperand(1);
FindAllocasForEvalOperations(
arg0, allocas); // Shuffle vector could come from different allocas
CurVal = arg1;
} else if (ExtractElementInst *EE = dyn_cast<ExtractElementInst>(CurVal)) {
CurVal = EE->getOperand(0);
} else if (LoadInst *LI = dyn_cast<LoadInst>(CurVal)) {
CurVal = LI->getOperand(0);
} else {
break;
}
}
if (AllocaInst *AI = dyn_cast<AllocaInst>(CurVal)) {
allocas.insert(AI);
}
}
} // namespace
ModulePass *llvm::createDxilLegalizeEvalOperationsPass() {
return new DxilLegalizeEvalOperations();
}
INITIALIZE_PASS(DxilLegalizeEvalOperations,
"hlsl-dxil-legalize-eval-operations",
"DXIL legalize eval operations", false, false)
///////////////////////////////////////////////////////////////////////////////
// Translate RawBufferLoad/RawBufferStore
// This pass is to make sure that we generate correct buffer load for DXIL
// For DXIL < 1.2, rawBufferLoad will be translated to BufferLoad instruction
// without mask.
// For DXIL >= 1.2, if min precision is enabled, currently generation pass is
// producing i16/f16 return type for min precisions. For rawBuffer, we will
// change this so that min precisions are returning its actual scalar type (i32/f32)
// and will be truncated to their corresponding types after loading / before storing.
namespace {
class DxilTranslateRawBuffer : public ModulePass {
public:
static char ID;
explicit DxilTranslateRawBuffer() : ModulePass(ID) {}
bool runOnModule(Module &M) {
unsigned major, minor;
M.GetDxilModule().GetDxilVersion(major, minor);
DxilModule::ShaderFlags flag = M.GetDxilModule().m_ShaderFlags;
if (major == 1 && minor < 2) {
for (auto F = M.functions().begin(), E = M.functions().end(); F != E;) {
Function *func = &*(F++);
if (func->hasName()) {
if (func->getName().startswith("dx.op.rawBufferLoad")) {
ReplaceRawBufferLoad(func, M);
func->eraseFromParent();
} else if (func->getName().startswith("dx.op.rawBufferStore")) {
ReplaceRawBufferStore(func, M);
func->eraseFromParent();
}
}
}
} else if (!flag.GetUseNativeLowPrecision()) {
for (auto F = M.functions().begin(), E = M.functions().end(); F != E;) {
Function *func = &*(F++);
if (func->hasName()) {
if (func->getName().startswith("dx.op.rawBufferLoad")) {
ReplaceMinPrecisionRawBufferLoad(func, M);
} else if (func->getName().startswith("dx.op.rawBufferStore")) {
ReplaceMinPrecisionRawBufferStore(func, M);
}
}
}
}
return true;
}
private:
// Replace RawBufferLoad/Store to BufferLoad/Store for DXIL < 1.2
void ReplaceRawBufferLoad(Function *F, Module &M);
void ReplaceRawBufferStore(Function *F, Module &M);
// Replace RawBufferLoad/Store of min-precision types to have its actual storage size
void ReplaceMinPrecisionRawBufferLoad(Function *F, Module &M);
void ReplaceMinPrecisionRawBufferStore(Function *F, Module &M);
void ReplaceMinPrecisionRawBufferLoadByType(Function *F, Type *FromTy,
Type *ToTy, OP *Op,
const DataLayout &DL);
};
} // namespace
void DxilTranslateRawBuffer::ReplaceRawBufferLoad(Function *F,
Module &M) {
OP *op = M.GetDxilModule().GetOP();
Type *RTy = F->getReturnType();
if (StructType *STy = dyn_cast<StructType>(RTy)) {
Type *ETy = STy->getElementType(0);
Function *newFunction = op->GetOpFunc(hlsl::DXIL::OpCode::BufferLoad, ETy);
for (auto U = F->user_begin(), E = F->user_end(); U != E;) {
User *user = *(U++);
if (CallInst *CI = dyn_cast<CallInst>(user)) {
IRBuilder<> Builder(CI);
SmallVector<Value *, 4> args;
args.emplace_back(op->GetI32Const((unsigned)DXIL::OpCode::BufferLoad));
for (unsigned i = 1; i < 4; ++i) {
args.emplace_back(CI->getArgOperand(i));
}
CallInst *newCall = Builder.CreateCall(newFunction, args);
CI->replaceAllUsesWith(newCall);
CI->eraseFromParent();
} else {
DXASSERT(false, "function can only be used with call instructions.");
}
}
} else {
DXASSERT(false, "RawBufferLoad should return struct type.");
}
}
void DxilTranslateRawBuffer::ReplaceRawBufferStore(Function *F,
Module &M) {
OP *op = M.GetDxilModule().GetOP();
DXASSERT(F->getReturnType()->isVoidTy(), "rawBufferStore should return a void type.");
Type *ETy = F->getFunctionType()->getParamType(4); // value
Function *newFunction = op->GetOpFunc(hlsl::DXIL::OpCode::BufferStore, ETy);
for (auto U = F->user_begin(), E = F->user_end(); U != E;) {
User *user = *(U++);
if (CallInst *CI = dyn_cast<CallInst>(user)) {
IRBuilder<> Builder(CI);
SmallVector<Value *, 4> args;
args.emplace_back(op->GetI32Const((unsigned)DXIL::OpCode::BufferStore));
for (unsigned i = 1; i < 9; ++i) {
args.emplace_back(CI->getArgOperand(i));
}
Builder.CreateCall(newFunction, args);
CI->eraseFromParent();
}
else {
DXASSERT(false, "function can only be used with call instructions.");
}
}
}
void DxilTranslateRawBuffer::ReplaceMinPrecisionRawBufferLoad(Function *F,
Module &M) {
OP *Op = M.GetDxilModule().GetOP();
Type *RetTy = F->getReturnType();
if (StructType *STy = dyn_cast<StructType>(RetTy)) {
Type *EltTy = STy->getElementType(0);
if (EltTy->isHalfTy()) {
ReplaceMinPrecisionRawBufferLoadByType(F, Type::getHalfTy(M.getContext()),
Type::getFloatTy(M.getContext()),
Op, M.getDataLayout());
} else if (EltTy == Type::getInt16Ty(M.getContext())) {
ReplaceMinPrecisionRawBufferLoadByType(
F, Type::getInt16Ty(M.getContext()), Type::getInt32Ty(M.getContext()),
Op, M.getDataLayout());
}
} else {
DXASSERT(false, "RawBufferLoad should return struct type.");
}
}
void DxilTranslateRawBuffer::ReplaceMinPrecisionRawBufferStore(Function *F,
Module &M) {
DXASSERT(F->getReturnType()->isVoidTy(), "rawBufferStore should return a void type.");
Type *ETy = F->getFunctionType()->getParamType(4); // value
Type *NewETy;
if (ETy->isHalfTy()) {
NewETy = Type::getFloatTy(M.getContext());
}
else if (ETy == Type::getInt16Ty(M.getContext())) {
NewETy = Type::getInt32Ty(M.getContext());
}
else {
return; // not a min precision type
}
Function *newFunction = M.GetDxilModule().GetOP()->GetOpFunc(
DXIL::OpCode::RawBufferStore, NewETy);
// for each function
// add argument 4-7 to its upconverted values
// replace function call
for (auto FuncUser = F->user_begin(), FuncEnd = F->user_end(); FuncUser != FuncEnd;) {
CallInst *CI = dyn_cast<CallInst>(*(FuncUser++));
DXASSERT(CI, "function user must be a call instruction.");
IRBuilder<> CIBuilder(CI);
SmallVector<Value *, 9> Args;
for (unsigned i = 0; i < 4; ++i) {
Args.emplace_back(CI->getArgOperand(i));
}
// values to store should be converted to its higher precision types
if (ETy->isHalfTy()) {
for (unsigned i = 4; i < 8; ++i) {
Value *NewV = CIBuilder.CreateFPExt(CI->getArgOperand(i),
Type::getFloatTy(M.getContext()));
Args.emplace_back(NewV);
}
}
else if (ETy == Type::getInt16Ty(M.getContext())) {
// This case only applies to typed buffer since Store operation of byte
// address buffer for min precision is handled by implicit conversion on
// intrinsic call. Since we are extending integer, we have to know if we
// should sign ext or zero ext. We can do this by iterating checking the
// size of the element at struct type and comp type at type annotation
CallInst *handleCI = dyn_cast<CallInst>(CI->getArgOperand(1));
DXASSERT(handleCI, "otherwise handle was not an argument to buffer store.");
ConstantInt *resClass = dyn_cast<ConstantInt>(handleCI->getArgOperand(1));
DXASSERT_LOCALVAR(resClass, resClass && resClass->getSExtValue() ==
(unsigned)DXIL::ResourceClass::UAV,
"otherwise buffer store called on non uav kind.");
ConstantInt *rangeID = dyn_cast<ConstantInt>(handleCI->getArgOperand(2)); // range id or idx?
DXASSERT(rangeID, "wrong createHandle call.");
DxilResource dxilRes = M.GetDxilModule().GetUAV(rangeID->getSExtValue());
StructType *STy = dyn_cast<StructType>(dxilRes.GetRetType());
DxilStructAnnotation *SAnnot = M.GetDxilModule().GetTypeSystem().GetStructAnnotation(STy);
ConstantInt *offsetInt = dyn_cast<ConstantInt>(CI->getArgOperand(3));
unsigned offset = offsetInt->getSExtValue();
unsigned currentOffset = 0;
for (DxilStructTypeIterator iter = begin(STy, SAnnot), ItEnd = end(STy, SAnnot); iter != ItEnd; ++iter) {
std::pair<Type *, DxilFieldAnnotation*> pair = *iter;
currentOffset += M.getDataLayout().getTypeAllocSize(pair.first);
if (currentOffset > offset) {
if (pair.second->GetCompType().IsUIntTy()) {
for (unsigned i = 4; i < 8; ++i) {
Value *NewV = CIBuilder.CreateZExt(CI->getArgOperand(i), Type::getInt32Ty(M.getContext()));
Args.emplace_back(NewV);
}
break;
}
else if (pair.second->GetCompType().IsIntTy()) {
for (unsigned i = 4; i < 8; ++i) {
Value *NewV = CIBuilder.CreateSExt(CI->getArgOperand(i), Type::getInt32Ty(M.getContext()));
Args.emplace_back(NewV);
}
break;
}
else {
DXASSERT(false, "Invalid comp type");
}
}
}
}
// mask
Args.emplace_back(CI->getArgOperand(8));
// alignment
Args.emplace_back(M.GetDxilModule().GetOP()->GetI32Const(
M.getDataLayout().getTypeAllocSize(NewETy)));
CIBuilder.CreateCall(newFunction, Args);
CI->eraseFromParent();
}
}
void DxilTranslateRawBuffer::ReplaceMinPrecisionRawBufferLoadByType(
Function *F, Type *FromTy, Type *ToTy, OP *Op, const DataLayout &DL) {
Function *newFunction = Op->GetOpFunc(DXIL::OpCode::RawBufferLoad, ToTy);
for (auto FUser = F->user_begin(), FEnd = F->user_end(); FUser != FEnd;) {
User *UserCI = *(FUser++);
if (CallInst *CI = dyn_cast<CallInst>(UserCI)) {
IRBuilder<> CIBuilder(CI);
SmallVector<Value *, 5> newFuncArgs;
// opcode, handle, index, elementOffset, mask
// Compiler is generating correct element offset even for min precision types
// So no need to recalculate here
for (unsigned i = 0; i < 5; ++i) {
newFuncArgs.emplace_back(CI->getArgOperand(i));
}
// new alignment for new type
newFuncArgs.emplace_back(Op->GetI32Const(DL.getTypeAllocSize(ToTy)));
CallInst *newCI = CIBuilder.CreateCall(newFunction, newFuncArgs);
for (auto CIUser = CI->user_begin(), CIEnd = CI->user_end();
CIUser != CIEnd;) {
User *UserEV = *(CIUser++);
if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(UserEV)) {
IRBuilder<> EVBuilder(EV);
ArrayRef<unsigned> Indices = EV->getIndices();
DXASSERT(Indices.size() == 1, "Otherwise we have wrong extract value.");
Value *newEV = EVBuilder.CreateExtractValue(newCI, Indices);
Value *newTruncV = nullptr;
if (4 == Indices[0]) { // Don't truncate status
newTruncV = newEV;
}
else if (FromTy->isHalfTy()) {
newTruncV = EVBuilder.CreateFPTrunc(newEV, FromTy);
} else if (FromTy->isIntegerTy()) {
newTruncV = EVBuilder.CreateTrunc(newEV, FromTy);
} else {
DXASSERT(false, "unexpected type conversion");
}
EV->replaceAllUsesWith(newTruncV);
EV->eraseFromParent();
}
}
CI->eraseFromParent();
}
}
F->eraseFromParent();
}
char DxilTranslateRawBuffer::ID = 0;
ModulePass *llvm::createDxilTranslateRawBuffer() {
return new DxilTranslateRawBuffer();
}
INITIALIZE_PASS(DxilTranslateRawBuffer, "hlsl-translate-dxil-raw-buffer",
"Translate raw buffer load", false, false)
| 36.627191 | 128 | 0.646793 | [
"object",
"vector",
"transform"
] |
10592edaf4d92cefa340c57c1cd61ed48d217f87 | 14,444 | cc | C++ | test/time_controller/simulated_time_controller.cc | chensongpoixs/cwebrtc | 3cc02facc428e9ff21650ff6ffb92370c26dd91e | [
"BSD-3-Clause"
] | null | null | null | test/time_controller/simulated_time_controller.cc | chensongpoixs/cwebrtc | 3cc02facc428e9ff21650ff6ffb92370c26dd91e | [
"BSD-3-Clause"
] | null | null | null | test/time_controller/simulated_time_controller.cc | chensongpoixs/cwebrtc | 3cc02facc428e9ff21650ff6ffb92370c26dd91e | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright 2019 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 "test/time_controller/simulated_time_controller.h"
#include <algorithm>
#include <deque>
#include <list>
#include <map>
#include <string>
#include <thread>
#include <vector>
#include "absl/memory/memory.h"
#include "absl/strings/string_view.h"
namespace webrtc {
namespace {
// Helper function to remove from a std container by value.
template <class C>
bool RemoveByValue(C& vec, typename C::value_type val) {
auto it = std::find(vec.begin(), vec.end(), val);
if (it == vec.end())
return false;
vec.erase(it);
return true;
}
} // namespace
namespace sim_time_impl {
class SimulatedSequenceRunner : public ProcessThread, public TaskQueueBase {
public:
SimulatedSequenceRunner(SimulatedTimeControllerImpl* handler,
absl::string_view queue_name)
: handler_(handler), name_(queue_name) {}
~SimulatedSequenceRunner() override { handler_->Unregister(this); }
// Provides next run time.
Timestamp GetNextRunTime() const;
// Iterates through delayed tasks and modules and moves them to the ready set
// if they are supposed to execute by |at time|.
void UpdateReady(Timestamp at_time);
// Runs all ready tasks and modules and updates next run time.
void Run(Timestamp at_time);
// TaskQueueBase interface
void Delete() override;
// Note: PostTask is also in ProcessThread interface.
void PostTask(std::unique_ptr<QueuedTask> task) override;
void PostDelayedTask(std::unique_ptr<QueuedTask> task,
uint32_t milliseconds) override;
// ProcessThread interface
void Start() override;
void Stop() override;
void WakeUp(Module* module) override;
void RegisterModule(Module* module, const rtc::Location& from) override;
void DeRegisterModule(Module* module) override;
// Promoted to public for use in SimulatedTimeControllerImpl::YieldExecution.
using CurrentTaskQueueSetter = TaskQueueBase::CurrentTaskQueueSetter;
private:
Timestamp GetCurrentTime() const { return handler_->CurrentTime(); }
void RunReadyTasks(Timestamp at_time) RTC_LOCKS_EXCLUDED(lock_);
void RunReadyModules(Timestamp at_time) RTC_EXCLUSIVE_LOCKS_REQUIRED(lock_);
void UpdateNextRunTime() RTC_EXCLUSIVE_LOCKS_REQUIRED(lock_);
Timestamp GetNextTime(Module* module, Timestamp at_time);
SimulatedTimeControllerImpl* const handler_;
const std::string name_;
rtc::CriticalSection lock_;
std::deque<std::unique_ptr<QueuedTask>> ready_tasks_ RTC_GUARDED_BY(lock_);
std::map<Timestamp, std::vector<std::unique_ptr<QueuedTask>>> delayed_tasks_
RTC_GUARDED_BY(lock_);
bool process_thread_running_ RTC_GUARDED_BY(lock_) = false;
std::vector<Module*> stopped_modules_ RTC_GUARDED_BY(lock_);
std::vector<Module*> ready_modules_ RTC_GUARDED_BY(lock_);
std::map<Timestamp, std::list<Module*>> delayed_modules_
RTC_GUARDED_BY(lock_);
Timestamp next_run_time_ RTC_GUARDED_BY(lock_) = Timestamp::PlusInfinity();
};
Timestamp SimulatedSequenceRunner::GetNextRunTime() const {
rtc::CritScope lock(&lock_);
return next_run_time_;
}
void SimulatedSequenceRunner::UpdateReady(Timestamp at_time) {
rtc::CritScope lock(&lock_);
for (auto it = delayed_tasks_.begin();
it != delayed_tasks_.end() && it->first <= at_time;
it = delayed_tasks_.erase(it)) {
for (auto& task : it->second) {
ready_tasks_.emplace_back(std::move(task));
}
}
for (auto it = delayed_modules_.begin();
it != delayed_modules_.end() && it->first <= at_time;
it = delayed_modules_.erase(it)) {
for (auto module : it->second) {
ready_modules_.push_back(module);
}
}
}
void SimulatedSequenceRunner::Run(Timestamp at_time) {
RunReadyTasks(at_time);
rtc::CritScope lock(&lock_);
RunReadyModules(at_time);
UpdateNextRunTime();
}
void SimulatedSequenceRunner::Delete() {
{
rtc::CritScope lock(&lock_);
ready_tasks_.clear();
delayed_tasks_.clear();
}
delete this;
}
void SimulatedSequenceRunner::RunReadyTasks(Timestamp at_time) {
std::deque<std::unique_ptr<QueuedTask>> ready_tasks;
{
rtc::CritScope lock(&lock_);
ready_tasks.swap(ready_tasks_);
}
if (!ready_tasks.empty()) {
CurrentTaskQueueSetter set_current(this);
for (auto& ready : ready_tasks) {
bool delete_task = ready->Run();
if (delete_task) {
ready.reset();
} else {
ready.release();
}
}
}
}
void SimulatedSequenceRunner::RunReadyModules(Timestamp at_time) {
if (!ready_modules_.empty()) {
CurrentTaskQueueSetter set_current(this);
for (auto* module : ready_modules_) {
module->Process();
delayed_modules_[GetNextTime(module, at_time)].push_back(module);
}
}
ready_modules_.clear();
}
void SimulatedSequenceRunner::UpdateNextRunTime() {
if (!ready_tasks_.empty() || !ready_modules_.empty()) {
next_run_time_ = Timestamp::MinusInfinity();
} else {
next_run_time_ = Timestamp::PlusInfinity();
if (!delayed_tasks_.empty())
next_run_time_ = std::min(next_run_time_, delayed_tasks_.begin()->first);
if (!delayed_modules_.empty())
next_run_time_ =
std::min(next_run_time_, delayed_modules_.begin()->first);
}
}
void SimulatedSequenceRunner::PostTask(std::unique_ptr<QueuedTask> task) {
rtc::CritScope lock(&lock_);
ready_tasks_.emplace_back(std::move(task));
next_run_time_ = Timestamp::MinusInfinity();
}
void SimulatedSequenceRunner::PostDelayedTask(std::unique_ptr<QueuedTask> task,
uint32_t milliseconds) {
rtc::CritScope lock(&lock_);
Timestamp target_time = GetCurrentTime() + TimeDelta::ms(milliseconds);
delayed_tasks_[target_time].push_back(std::move(task));
next_run_time_ = std::min(next_run_time_, target_time);
}
void SimulatedSequenceRunner::Start() {
std::vector<Module*> starting;
{
rtc::CritScope lock(&lock_);
if (process_thread_running_)
return;
process_thread_running_ = true;
starting.swap(stopped_modules_);
}
for (auto& module : starting)
module->ProcessThreadAttached(this);
Timestamp at_time = GetCurrentTime();
rtc::CritScope lock(&lock_);
for (auto& module : starting)
delayed_modules_[GetNextTime(module, at_time)].push_back(module);
UpdateNextRunTime();
}
void SimulatedSequenceRunner::Stop() {
std::vector<Module*> stopping;
{
rtc::CritScope lock(&lock_);
process_thread_running_ = false;
for (auto* ready : ready_modules_)
stopped_modules_.push_back(ready);
ready_modules_.clear();
for (auto& delayed : delayed_modules_) {
for (auto mod : delayed.second)
stopped_modules_.push_back(mod);
}
delayed_modules_.clear();
stopping = stopped_modules_;
}
for (auto& module : stopping)
module->ProcessThreadAttached(nullptr);
}
void SimulatedSequenceRunner::WakeUp(Module* module) {
rtc::CritScope lock(&lock_);
// If we already are planning to run this module as soon as possible, we don't
// need to do anything.
for (auto mod : ready_modules_)
if (mod == module)
return;
for (auto it = delayed_modules_.begin(); it != delayed_modules_.end(); ++it) {
if (RemoveByValue(it->second, module))
break;
}
Timestamp next_time = GetNextTime(module, GetCurrentTime());
delayed_modules_[next_time].push_back(module);
next_run_time_ = std::min(next_run_time_, next_time);
}
void SimulatedSequenceRunner::RegisterModule(Module* module,
const rtc::Location& from) {
module->ProcessThreadAttached(this);
rtc::CritScope lock(&lock_);
if (!process_thread_running_) {
stopped_modules_.push_back(module);
} else {
Timestamp next_time = GetNextTime(module, GetCurrentTime());
delayed_modules_[next_time].push_back(module);
next_run_time_ = std::min(next_run_time_, next_time);
}
}
void SimulatedSequenceRunner::DeRegisterModule(Module* module) {
bool modules_running;
{
rtc::CritScope lock(&lock_);
if (!process_thread_running_) {
RemoveByValue(stopped_modules_, module);
} else {
bool removed = RemoveByValue(ready_modules_, module);
if (!removed) {
for (auto& pair : delayed_modules_) {
if (RemoveByValue(pair.second, module))
break;
}
}
}
modules_running = process_thread_running_;
}
if (modules_running)
module->ProcessThreadAttached(nullptr);
}
Timestamp SimulatedSequenceRunner::GetNextTime(Module* module,
Timestamp at_time) {
CurrentTaskQueueSetter set_current(this);
return at_time + TimeDelta::ms(module->TimeUntilNextProcess());
}
SimulatedTimeControllerImpl::SimulatedTimeControllerImpl(Timestamp start_time)
: thread_id_(rtc::CurrentThreadId()), current_time_(start_time) {}
SimulatedTimeControllerImpl::~SimulatedTimeControllerImpl() = default;
std::unique_ptr<TaskQueueBase, TaskQueueDeleter>
SimulatedTimeControllerImpl::CreateTaskQueue(
absl::string_view name,
TaskQueueFactory::Priority priority) const {
// TODO(srte): Remove the const cast when the interface is made mutable.
auto mutable_this = const_cast<SimulatedTimeControllerImpl*>(this);
auto task_queue = std::unique_ptr<SimulatedSequenceRunner, TaskQueueDeleter>(
new SimulatedSequenceRunner(mutable_this, name));
rtc::CritScope lock(&mutable_this->lock_);
mutable_this->runners_.push_back(task_queue.get());
return task_queue;
}
std::unique_ptr<ProcessThread> SimulatedTimeControllerImpl::CreateProcessThread(
const char* thread_name) {
rtc::CritScope lock(&lock_);
auto process_thread =
absl::make_unique<SimulatedSequenceRunner>(this, thread_name);
runners_.push_back(process_thread.get());
return process_thread;
}
std::vector<SimulatedSequenceRunner*>
SimulatedTimeControllerImpl::GetNextReadyRunner(Timestamp current_time) {
rtc::CritScope lock(&lock_);
std::vector<SimulatedSequenceRunner*> ready;
for (auto* runner : runners_) {
if (yielded_.find(runner) == yielded_.end() &&
runner->GetNextRunTime() <= current_time) {
ready.push_back(runner);
}
}
return ready;
}
void SimulatedTimeControllerImpl::YieldExecution() {
if (rtc::CurrentThreadId() == thread_id_) {
TaskQueueBase* yielding_from = TaskQueueBase::Current();
// Since we might continue execution on a process thread, we should reset
// the thread local task queue reference. This ensures that thread checkers
// won't think we are executing on the yielding task queue. It also ensure
// that TaskQueueBase::Current() won't return the yielding task queue.
SimulatedSequenceRunner::CurrentTaskQueueSetter reset_queue(nullptr);
RTC_DCHECK_RUN_ON(&thread_checker_);
// When we yield, we don't want to risk executing further tasks on the
// currently executing task queue. If there's a ready task that also yields,
// it's added to this set as well and only tasks on the remaining task
// queues are executed.
auto inserted = yielded_.insert(yielding_from);
RTC_DCHECK(inserted.second);
RunReadyRunners();
yielded_.erase(inserted.first);
}
}
void SimulatedTimeControllerImpl::RunReadyRunners() {
RTC_DCHECK_RUN_ON(&thread_checker_);
RTC_DCHECK_EQ(rtc::CurrentThreadId(), thread_id_);
Timestamp current_time = CurrentTime();
// We repeat until we have no ready left to handle tasks posted by ready
// runners.
while (true) {
auto ready = GetNextReadyRunner(current_time);
if (ready.empty())
break;
for (auto* runner : ready) {
runner->UpdateReady(current_time);
runner->Run(current_time);
}
}
}
Timestamp SimulatedTimeControllerImpl::CurrentTime() const {
rtc::CritScope lock(&time_lock_);
return current_time_;
}
Timestamp SimulatedTimeControllerImpl::NextRunTime() const {
Timestamp current_time = CurrentTime();
Timestamp next_time = Timestamp::PlusInfinity();
rtc::CritScope lock(&lock_);
for (auto* runner : runners_) {
Timestamp next_run_time = runner->GetNextRunTime();
if (next_run_time <= current_time)
return current_time;
next_time = std::min(next_time, next_run_time);
}
return next_time;
}
void SimulatedTimeControllerImpl::AdvanceTime(Timestamp target_time) {
rtc::CritScope time_lock(&time_lock_);
RTC_DCHECK(target_time >= current_time_);
current_time_ = target_time;
}
void SimulatedTimeControllerImpl::Unregister(SimulatedSequenceRunner* runner) {
rtc::CritScope lock(&lock_);
bool removed = RemoveByValue(runners_, runner);
RTC_CHECK(removed);
}
} // namespace sim_time_impl
GlobalSimulatedTimeController::GlobalSimulatedTimeController(
Timestamp start_time)
: sim_clock_(start_time.us()), impl_(start_time) {
global_clock_.SetTimeMicros(start_time.us());
}
GlobalSimulatedTimeController::~GlobalSimulatedTimeController() = default;
Clock* GlobalSimulatedTimeController::GetClock() {
return &sim_clock_;
}
TaskQueueFactory* GlobalSimulatedTimeController::GetTaskQueueFactory() {
return &impl_;
}
std::unique_ptr<ProcessThread>
GlobalSimulatedTimeController::CreateProcessThread(const char* thread_name) {
return impl_.CreateProcessThread(thread_name);
}
void GlobalSimulatedTimeController::Sleep(TimeDelta duration) {
rtc::ScopedYieldPolicy yield_policy(&impl_);
Timestamp current_time = impl_.CurrentTime();
Timestamp target_time = current_time + duration;
RTC_DCHECK_EQ(current_time.us(), rtc::TimeMicros());
while (current_time < target_time) {
impl_.RunReadyRunners();
Timestamp next_time = std::min(impl_.NextRunTime(), target_time);
impl_.AdvanceTime(next_time);
auto delta = next_time - current_time;
current_time = next_time;
sim_clock_.AdvanceTimeMicroseconds(delta.us());
global_clock_.AdvanceTimeMicros(delta.us());
}
}
void GlobalSimulatedTimeController::InvokeWithControlledYield(
std::function<void()> closure) {
rtc::ScopedYieldPolicy yield_policy(&impl_);
closure();
}
// namespace sim_time_impl
} // namespace webrtc
| 32.604966 | 80 | 0.72203 | [
"vector"
] |
105bfbe9f89218d3978e8b6207d02d02b97447c1 | 31,862 | cc | C++ | content/renderer/webcrypto/webcrypto_impl_nss.cc | SlimKatLegacy/android_external_chromium_org | ee480ef5039d7c561fc66ccf52169ead186f1bea | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2015-03-04T02:36:53.000Z | 2016-06-25T11:22:17.000Z | content/renderer/webcrypto/webcrypto_impl_nss.cc | j4ckfrost/android_external_chromium_org | a1a3dad8b08d1fcf6b6b36c267158ed63217c780 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | content/renderer/webcrypto/webcrypto_impl_nss.cc | j4ckfrost/android_external_chromium_org | a1a3dad8b08d1fcf6b6b36c267158ed63217c780 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 4 | 2015-02-09T08:49:30.000Z | 2017-08-26T02:03:34.000Z | // Copyright 2013 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 "content/renderer/webcrypto/webcrypto_impl.h"
#include <cryptohi.h>
#include <pk11pub.h>
#include <sechash.h>
#include <vector>
#include "base/logging.h"
#include "content/renderer/webcrypto/webcrypto_util.h"
#include "crypto/nss_util.h"
#include "crypto/scoped_nss_types.h"
#include "crypto/secure_util.h"
#include "third_party/WebKit/public/platform/WebArrayBuffer.h"
#include "third_party/WebKit/public/platform/WebCryptoAlgorithm.h"
#include "third_party/WebKit/public/platform/WebCryptoAlgorithmParams.h"
namespace content {
namespace {
class SymKeyHandle : public blink::WebCryptoKeyHandle {
public:
explicit SymKeyHandle(crypto::ScopedPK11SymKey key) : key_(key.Pass()) {}
PK11SymKey* key() { return key_.get(); }
private:
crypto::ScopedPK11SymKey key_;
DISALLOW_COPY_AND_ASSIGN(SymKeyHandle);
};
class PublicKeyHandle : public blink::WebCryptoKeyHandle {
public:
explicit PublicKeyHandle(crypto::ScopedSECKEYPublicKey key)
: key_(key.Pass()) {}
SECKEYPublicKey* key() { return key_.get(); }
private:
crypto::ScopedSECKEYPublicKey key_;
DISALLOW_COPY_AND_ASSIGN(PublicKeyHandle);
};
class PrivateKeyHandle : public blink::WebCryptoKeyHandle {
public:
explicit PrivateKeyHandle(crypto::ScopedSECKEYPrivateKey key)
: key_(key.Pass()) {}
SECKEYPrivateKey* key() { return key_.get(); }
private:
crypto::ScopedSECKEYPrivateKey key_;
DISALLOW_COPY_AND_ASSIGN(PrivateKeyHandle);
};
HASH_HashType WebCryptoAlgorithmToNSSHashType(
const blink::WebCryptoAlgorithm& algorithm) {
switch (algorithm.id()) {
case blink::WebCryptoAlgorithmIdSha1:
return HASH_AlgSHA1;
case blink::WebCryptoAlgorithmIdSha224:
return HASH_AlgSHA224;
case blink::WebCryptoAlgorithmIdSha256:
return HASH_AlgSHA256;
case blink::WebCryptoAlgorithmIdSha384:
return HASH_AlgSHA384;
case blink::WebCryptoAlgorithmIdSha512:
return HASH_AlgSHA512;
default:
// Not a digest algorithm.
return HASH_AlgNULL;
}
}
CK_MECHANISM_TYPE WebCryptoAlgorithmToHMACMechanism(
const blink::WebCryptoAlgorithm& algorithm) {
switch (algorithm.id()) {
case blink::WebCryptoAlgorithmIdSha1:
return CKM_SHA_1_HMAC;
case blink::WebCryptoAlgorithmIdSha256:
return CKM_SHA256_HMAC;
default:
// Not a supported algorithm.
return CKM_INVALID_MECHANISM;
}
}
bool AesCbcEncryptDecrypt(
CK_ATTRIBUTE_TYPE operation,
const blink::WebCryptoAlgorithm& algorithm,
const blink::WebCryptoKey& key,
const unsigned char* data,
unsigned data_size,
blink::WebArrayBuffer* buffer) {
DCHECK_EQ(blink::WebCryptoAlgorithmIdAesCbc, algorithm.id());
DCHECK_EQ(algorithm.id(), key.algorithm().id());
DCHECK_EQ(blink::WebCryptoKeyTypeSecret, key.type());
DCHECK(operation == CKA_ENCRYPT || operation == CKA_DECRYPT);
SymKeyHandle* sym_key = reinterpret_cast<SymKeyHandle*>(key.handle());
const blink::WebCryptoAesCbcParams* params = algorithm.aesCbcParams();
if (params->iv().size() != AES_BLOCK_SIZE)
return false;
SECItem iv_item;
iv_item.type = siBuffer;
iv_item.data = const_cast<unsigned char*>(params->iv().data());
iv_item.len = params->iv().size();
crypto::ScopedSECItem param(PK11_ParamFromIV(CKM_AES_CBC_PAD, &iv_item));
if (!param)
return false;
crypto::ScopedPK11Context context(PK11_CreateContextBySymKey(
CKM_AES_CBC_PAD, operation, sym_key->key(), param.get()));
if (!context.get())
return false;
// Oddly PK11_CipherOp takes input and output lengths as "int" rather than
// "unsigned". Do some checks now to avoid integer overflowing.
if (data_size >= INT_MAX - AES_BLOCK_SIZE) {
// TODO(eroman): Handle this by chunking the input fed into NSS. Right now
// it doesn't make much difference since the one-shot API would end up
// blowing out the memory and crashing anyway. However a newer version of
// the spec allows for a sequence<CryptoData> so this will be relevant.
return false;
}
// PK11_CipherOp does an invalid memory access when given empty decryption
// input, or input which is not a multiple of the block size. See also
// https://bugzilla.mozilla.com/show_bug.cgi?id=921687.
if (operation == CKA_DECRYPT &&
(data_size == 0 || (data_size % AES_BLOCK_SIZE != 0))) {
return false;
}
// TODO(eroman): Refine the output buffer size. It can be computed exactly for
// encryption, and can be smaller for decryption.
unsigned output_max_len = data_size + AES_BLOCK_SIZE;
CHECK_GT(output_max_len, data_size);
*buffer = blink::WebArrayBuffer::create(output_max_len, 1);
unsigned char* buffer_data = reinterpret_cast<unsigned char*>(buffer->data());
int output_len;
if (SECSuccess != PK11_CipherOp(context.get(),
buffer_data,
&output_len,
buffer->byteLength(),
data,
data_size)) {
return false;
}
unsigned int final_output_chunk_len;
if (SECSuccess != PK11_DigestFinal(context.get(),
buffer_data + output_len,
&final_output_chunk_len,
output_max_len - output_len)) {
return false;
}
webcrypto::ShrinkBuffer(buffer, final_output_chunk_len + output_len);
return true;
}
CK_MECHANISM_TYPE HmacAlgorithmToGenMechanism(
const blink::WebCryptoAlgorithm& algorithm) {
DCHECK_EQ(algorithm.id(), blink::WebCryptoAlgorithmIdHmac);
const blink::WebCryptoHmacKeyParams* params = algorithm.hmacKeyParams();
DCHECK(params);
switch (params->hash().id()) {
case blink::WebCryptoAlgorithmIdSha1:
return CKM_SHA_1_HMAC;
case blink::WebCryptoAlgorithmIdSha256:
return CKM_SHA256_HMAC;
default:
return CKM_INVALID_MECHANISM;
}
}
CK_MECHANISM_TYPE WebCryptoAlgorithmToGenMechanism(
const blink::WebCryptoAlgorithm& algorithm) {
switch (algorithm.id()) {
case blink::WebCryptoAlgorithmIdAesCbc:
return CKM_AES_KEY_GEN;
case blink::WebCryptoAlgorithmIdHmac:
return HmacAlgorithmToGenMechanism(algorithm);
default:
return CKM_INVALID_MECHANISM;
}
}
unsigned int WebCryptoHmacAlgorithmToBlockSize(
const blink::WebCryptoAlgorithm& algorithm) {
DCHECK_EQ(algorithm.id(), blink::WebCryptoAlgorithmIdHmac);
const blink::WebCryptoHmacKeyParams* params = algorithm.hmacKeyParams();
DCHECK(params);
switch (params->hash().id()) {
case blink::WebCryptoAlgorithmIdSha1:
return 512;
case blink::WebCryptoAlgorithmIdSha256:
return 512;
default:
return 0;
}
}
// Converts a (big-endian) WebCrypto BigInteger, with or without leading zeros,
// to unsigned long.
bool BigIntegerToLong(const uint8* data,
unsigned data_size,
unsigned long* result) {
// TODO(padolph): Is it correct to say that empty data is an error, or does it
// mean value 0? See https://www.w3.org/Bugs/Public/show_bug.cgi?id=23655
if (data_size == 0)
return false;
*result = 0;
for (size_t i = 0; i < data_size; ++i) {
size_t reverse_i = data_size - i - 1;
if (reverse_i >= sizeof(unsigned long) && data[i])
return false; // Too large for a long.
*result |= data[i] << 8 * reverse_i;
}
return true;
}
bool IsAlgorithmRsa(const blink::WebCryptoAlgorithm& algorithm) {
return algorithm.id() == blink::WebCryptoAlgorithmIdRsaEsPkcs1v1_5 ||
algorithm.id() == blink::WebCryptoAlgorithmIdRsaOaep ||
algorithm.id() == blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5;
}
bool ImportKeyInternalRaw(
const unsigned char* key_data,
unsigned key_data_size,
const blink::WebCryptoAlgorithm& algorithm,
bool extractable,
blink::WebCryptoKeyUsageMask usage_mask,
blink::WebCryptoKey* key) {
DCHECK(!algorithm.isNull());
blink::WebCryptoKeyType type;
switch (algorithm.id()) {
case blink::WebCryptoAlgorithmIdHmac:
case blink::WebCryptoAlgorithmIdAesCbc:
type = blink::WebCryptoKeyTypeSecret;
break;
// TODO(bryaneyler): Support more key types.
default:
return false;
}
// TODO(bryaneyler): Need to split handling for symmetric and asymmetric keys.
// Currently only supporting symmetric.
CK_MECHANISM_TYPE mechanism = CKM_INVALID_MECHANISM;
// Flags are verified at the Blink layer; here the flags are set to all
// possible operations for this key type.
CK_FLAGS flags = 0;
switch (algorithm.id()) {
case blink::WebCryptoAlgorithmIdHmac: {
const blink::WebCryptoHmacParams* params = algorithm.hmacParams();
if (!params) {
return false;
}
mechanism = WebCryptoAlgorithmToHMACMechanism(params->hash());
if (mechanism == CKM_INVALID_MECHANISM) {
return false;
}
flags |= CKF_SIGN | CKF_VERIFY;
break;
}
case blink::WebCryptoAlgorithmIdAesCbc: {
mechanism = CKM_AES_CBC;
flags |= CKF_ENCRYPT | CKF_DECRYPT;
break;
}
default:
return false;
}
DCHECK_NE(CKM_INVALID_MECHANISM, mechanism);
DCHECK_NE(0ul, flags);
SECItem key_item = {
siBuffer,
const_cast<unsigned char*>(key_data),
key_data_size
};
crypto::ScopedPK11SymKey pk11_sym_key(
PK11_ImportSymKeyWithFlags(PK11_GetInternalSlot(),
mechanism,
PK11_OriginUnwrap,
CKA_FLAGS_ONLY,
&key_item,
flags,
false,
NULL));
if (!pk11_sym_key.get()) {
return false;
}
*key = blink::WebCryptoKey::create(new SymKeyHandle(pk11_sym_key.Pass()),
type, extractable, algorithm, usage_mask);
return true;
}
bool ExportKeyInternalRaw(
const blink::WebCryptoKey& key,
blink::WebArrayBuffer* buffer) {
DCHECK(key.handle());
DCHECK(buffer);
if (key.type() != blink::WebCryptoKeyTypeSecret || !key.extractable())
return false;
SymKeyHandle* sym_key = reinterpret_cast<SymKeyHandle*>(key.handle());
if (PK11_ExtractKeyValue(sym_key->key()) != SECSuccess)
return false;
const SECItem* key_data = PK11_GetKeyData(sym_key->key());
if (!key_data)
return false;
*buffer = webcrypto::CreateArrayBuffer(key_data->data, key_data->len);
return true;
}
typedef scoped_ptr<CERTSubjectPublicKeyInfo,
crypto::NSSDestroyer<CERTSubjectPublicKeyInfo,
SECKEY_DestroySubjectPublicKeyInfo> >
ScopedCERTSubjectPublicKeyInfo;
// Validates an NSS KeyType against a WebCrypto algorithm. Some NSS KeyTypes
// contain enough information to fabricate a Web Crypto algorithm, which is
// returned if the input algorithm isNull(). This function indicates failure by
// returning a Null algorithm.
blink::WebCryptoAlgorithm ResolveNssKeyTypeWithInputAlgorithm(
KeyType key_type,
const blink::WebCryptoAlgorithm& algorithm_or_null) {
switch (key_type) {
case rsaKey:
// NSS's rsaKey KeyType maps to keys with SEC_OID_PKCS1_RSA_ENCRYPTION and
// according to RFCs 4055/5756 this can be used for both encryption and
// signatures. However, this is not specific enough to build a compatible
// Web Crypto algorithm, since in Web Crypto, RSA encryption and signature
// algorithms are distinct. So if the input algorithm isNull() here, we
// have to fail.
if (!algorithm_or_null.isNull() && IsAlgorithmRsa(algorithm_or_null))
return algorithm_or_null;
break;
case dsaKey:
case ecKey:
case rsaPssKey:
case rsaOaepKey:
// TODO(padolph): Handle other key types.
break;
default:
break;
}
return blink::WebCryptoAlgorithm::createNull();
}
bool ImportKeyInternalSpki(
const unsigned char* key_data,
unsigned key_data_size,
const blink::WebCryptoAlgorithm& algorithm_or_null,
bool extractable,
blink::WebCryptoKeyUsageMask usage_mask,
blink::WebCryptoKey* key) {
DCHECK(key);
if (!key_data_size)
return false;
DCHECK(key_data);
// The binary blob 'key_data' is expected to be a DER-encoded ASN.1 Subject
// Public Key Info. Decode this to a CERTSubjectPublicKeyInfo.
SECItem spki_item = {siBuffer, const_cast<uint8*>(key_data), key_data_size};
const ScopedCERTSubjectPublicKeyInfo spki(
SECKEY_DecodeDERSubjectPublicKeyInfo(&spki_item));
if (!spki)
return false;
crypto::ScopedSECKEYPublicKey sec_public_key(
SECKEY_ExtractPublicKey(spki.get()));
if (!sec_public_key)
return false;
const KeyType sec_key_type = SECKEY_GetPublicKeyType(sec_public_key.get());
blink::WebCryptoAlgorithm algorithm =
ResolveNssKeyTypeWithInputAlgorithm(sec_key_type, algorithm_or_null);
if (algorithm.isNull())
return false;
*key = blink::WebCryptoKey::create(
new PublicKeyHandle(sec_public_key.Pass()),
blink::WebCryptoKeyTypePublic,
extractable,
algorithm,
usage_mask);
return true;
}
bool ExportKeyInternalSpki(
const blink::WebCryptoKey& key,
blink::WebArrayBuffer* buffer) {
DCHECK(key.handle());
DCHECK(buffer);
if (key.type() != blink::WebCryptoKeyTypePublic || !key.extractable())
return false;
PublicKeyHandle* const pub_key =
reinterpret_cast<PublicKeyHandle*>(key.handle());
const crypto::ScopedSECItem spki_der(
SECKEY_EncodeDERSubjectPublicKeyInfo(pub_key->key()));
if (!spki_der)
return false;
DCHECK(spki_der->data);
DCHECK(spki_der->len);
*buffer = webcrypto::CreateArrayBuffer(spki_der->data, spki_der->len);
return true;
}
bool ImportKeyInternalPkcs8(
const unsigned char* key_data,
unsigned key_data_size,
const blink::WebCryptoAlgorithm& algorithm_or_null,
bool extractable,
blink::WebCryptoKeyUsageMask usage_mask,
blink::WebCryptoKey* key) {
DCHECK(key);
if (!key_data_size)
return false;
DCHECK(key_data);
// The binary blob 'key_data' is expected to be a DER-encoded ASN.1 PKCS#8
// private key info object.
SECItem pki_der = {siBuffer, const_cast<uint8*>(key_data), key_data_size};
SECKEYPrivateKey* seckey_private_key = NULL;
if (PK11_ImportDERPrivateKeyInfoAndReturnKey(
PK11_GetInternalSlot(),
&pki_der,
NULL, // nickname
NULL, // publicValue
false, // isPerm
false, // isPrivate
KU_ALL, // usage
&seckey_private_key,
NULL) != SECSuccess) {
return false;
}
DCHECK(seckey_private_key);
crypto::ScopedSECKEYPrivateKey private_key(seckey_private_key);
const KeyType sec_key_type = SECKEY_GetPrivateKeyType(private_key.get());
blink::WebCryptoAlgorithm algorithm =
ResolveNssKeyTypeWithInputAlgorithm(sec_key_type, algorithm_or_null);
if (algorithm.isNull())
return false;
*key = blink::WebCryptoKey::create(
new PrivateKeyHandle(private_key.Pass()),
blink::WebCryptoKeyTypePrivate,
extractable,
algorithm,
usage_mask);
return true;
}
} // namespace
void WebCryptoImpl::Init() {
crypto::EnsureNSSInit();
}
bool WebCryptoImpl::EncryptInternal(
const blink::WebCryptoAlgorithm& algorithm,
const blink::WebCryptoKey& key,
const unsigned char* data,
unsigned data_size,
blink::WebArrayBuffer* buffer) {
DCHECK_EQ(algorithm.id(), key.algorithm().id());
DCHECK(key.handle());
DCHECK(buffer);
if (algorithm.id() == blink::WebCryptoAlgorithmIdAesCbc) {
return AesCbcEncryptDecrypt(
CKA_ENCRYPT, algorithm, key, data, data_size, buffer);
} else if (algorithm.id() == blink::WebCryptoAlgorithmIdRsaEsPkcs1v1_5) {
// RSAES encryption does not support empty input
if (!data_size)
return false;
DCHECK(data);
if (key.type() != blink::WebCryptoKeyTypePublic)
return false;
PublicKeyHandle* const public_key =
reinterpret_cast<PublicKeyHandle*>(key.handle());
const unsigned encrypted_length_bytes =
SECKEY_PublicKeyStrength(public_key->key());
// RSAES can operate on messages up to a length of k - 11, where k is the
// octet length of the RSA modulus.
if (encrypted_length_bytes < 11 || encrypted_length_bytes - 11 < data_size)
return false;
*buffer = blink::WebArrayBuffer::create(encrypted_length_bytes, 1);
unsigned char* const buffer_data =
reinterpret_cast<unsigned char*>(buffer->data());
if (PK11_PubEncryptPKCS1(public_key->key(),
buffer_data,
const_cast<unsigned char*>(data),
data_size,
NULL) != SECSuccess) {
return false;
}
return true;
}
return false;
}
bool WebCryptoImpl::DecryptInternal(
const blink::WebCryptoAlgorithm& algorithm,
const blink::WebCryptoKey& key,
const unsigned char* data,
unsigned data_size,
blink::WebArrayBuffer* buffer) {
DCHECK_EQ(algorithm.id(), key.algorithm().id());
DCHECK(key.handle());
DCHECK(buffer);
if (algorithm.id() == blink::WebCryptoAlgorithmIdAesCbc) {
return AesCbcEncryptDecrypt(
CKA_DECRYPT, algorithm, key, data, data_size, buffer);
} else if (algorithm.id() == blink::WebCryptoAlgorithmIdRsaEsPkcs1v1_5) {
// RSAES decryption does not support empty input
if (!data_size)
return false;
DCHECK(data);
if (key.type() != blink::WebCryptoKeyTypePrivate)
return false;
PrivateKeyHandle* const private_key =
reinterpret_cast<PrivateKeyHandle*>(key.handle());
const int modulus_length_bytes =
PK11_GetPrivateModulusLen(private_key->key());
if (modulus_length_bytes <= 0)
return false;
const unsigned max_output_length_bytes = modulus_length_bytes;
*buffer = blink::WebArrayBuffer::create(max_output_length_bytes, 1);
unsigned char* const buffer_data =
reinterpret_cast<unsigned char*>(buffer->data());
unsigned output_length_bytes = 0;
if (PK11_PrivDecryptPKCS1(private_key->key(),
buffer_data,
&output_length_bytes,
max_output_length_bytes,
const_cast<unsigned char*>(data),
data_size) != SECSuccess) {
return false;
}
DCHECK_LE(output_length_bytes, max_output_length_bytes);
webcrypto::ShrinkBuffer(buffer, output_length_bytes);
return true;
}
return false;
}
bool WebCryptoImpl::DigestInternal(
const blink::WebCryptoAlgorithm& algorithm,
const unsigned char* data,
unsigned data_size,
blink::WebArrayBuffer* buffer) {
HASH_HashType hash_type = WebCryptoAlgorithmToNSSHashType(algorithm);
if (hash_type == HASH_AlgNULL) {
return false;
}
HASHContext* context = HASH_Create(hash_type);
if (!context) {
return false;
}
HASH_Begin(context);
HASH_Update(context, data, data_size);
unsigned hash_result_length = HASH_ResultLenContext(context);
DCHECK_LE(hash_result_length, static_cast<size_t>(HASH_LENGTH_MAX));
*buffer = blink::WebArrayBuffer::create(hash_result_length, 1);
unsigned char* digest = reinterpret_cast<unsigned char*>(buffer->data());
unsigned result_length = 0;
HASH_End(context, digest, &result_length, hash_result_length);
HASH_Destroy(context);
return result_length == hash_result_length;
}
bool WebCryptoImpl::GenerateKeyInternal(
const blink::WebCryptoAlgorithm& algorithm,
bool extractable,
blink::WebCryptoKeyUsageMask usage_mask,
blink::WebCryptoKey* key) {
CK_MECHANISM_TYPE mech = WebCryptoAlgorithmToGenMechanism(algorithm);
unsigned int keylen_bytes = 0;
blink::WebCryptoKeyType key_type = blink::WebCryptoKeyTypeSecret;
if (mech == CKM_INVALID_MECHANISM) {
return false;
}
switch (algorithm.id()) {
case blink::WebCryptoAlgorithmIdAesCbc: {
const blink::WebCryptoAesKeyGenParams* params =
algorithm.aesKeyGenParams();
DCHECK(params);
keylen_bytes = params->length() / 8;
if (params->length() % 8)
return false;
key_type = blink::WebCryptoKeyTypeSecret;
break;
}
case blink::WebCryptoAlgorithmIdHmac: {
const blink::WebCryptoHmacKeyParams* params = algorithm.hmacKeyParams();
DCHECK(params);
if (!params->getLength(keylen_bytes)) {
keylen_bytes = WebCryptoHmacAlgorithmToBlockSize(algorithm) / 8;
}
key_type = blink::WebCryptoKeyTypeSecret;
break;
}
default: {
return false;
}
}
if (keylen_bytes == 0) {
return false;
}
crypto::ScopedPK11Slot slot(PK11_GetInternalKeySlot());
if (!slot) {
return false;
}
crypto::ScopedPK11SymKey pk11_key(
PK11_KeyGen(slot.get(), mech, NULL, keylen_bytes, NULL));
if (!pk11_key) {
return false;
}
*key = blink::WebCryptoKey::create(
new SymKeyHandle(pk11_key.Pass()),
key_type, extractable, algorithm, usage_mask);
return true;
}
bool WebCryptoImpl::GenerateKeyPairInternal(
const blink::WebCryptoAlgorithm& algorithm,
bool extractable,
blink::WebCryptoKeyUsageMask usage_mask,
blink::WebCryptoKey* public_key,
blink::WebCryptoKey* private_key) {
// TODO(padolph): Handle other asymmetric algorithm key generation.
switch (algorithm.id()) {
case blink::WebCryptoAlgorithmIdRsaEsPkcs1v1_5:
case blink::WebCryptoAlgorithmIdRsaOaep:
case blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5: {
const blink::WebCryptoRsaKeyGenParams* const params =
algorithm.rsaKeyGenParams();
DCHECK(params);
crypto::ScopedPK11Slot slot(PK11_GetInternalKeySlot());
unsigned long public_exponent;
if (!slot || !params->modulusLength() ||
!BigIntegerToLong(params->publicExponent().data(),
params->publicExponent().size(),
&public_exponent) ||
!public_exponent) {
return false;
}
PK11RSAGenParams rsa_gen_params;
rsa_gen_params.keySizeInBits = params->modulusLength();
rsa_gen_params.pe = public_exponent;
// Flags are verified at the Blink layer; here the flags are set to all
// possible operations for the given key type.
CK_FLAGS operation_flags;
switch (algorithm.id()) {
case blink::WebCryptoAlgorithmIdRsaEsPkcs1v1_5:
case blink::WebCryptoAlgorithmIdRsaOaep:
operation_flags = CKF_ENCRYPT | CKF_DECRYPT | CKF_WRAP | CKF_UNWRAP;
break;
case blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5:
operation_flags = CKF_SIGN | CKF_VERIFY;
break;
default:
NOTREACHED();
return false;
}
const CK_FLAGS operation_flags_mask = CKF_ENCRYPT | CKF_DECRYPT |
CKF_SIGN | CKF_VERIFY | CKF_WRAP |
CKF_UNWRAP;
const PK11AttrFlags attribute_flags = 0; // Default all PK11_ATTR_ flags.
// Note: NSS does not generate an sec_public_key if the call below fails,
// so there is no danger of a leaked sec_public_key.
SECKEYPublicKey* sec_public_key;
crypto::ScopedSECKEYPrivateKey scoped_sec_private_key(
PK11_GenerateKeyPairWithOpFlags(slot.get(),
CKM_RSA_PKCS_KEY_PAIR_GEN,
&rsa_gen_params,
&sec_public_key,
attribute_flags,
operation_flags,
operation_flags_mask,
NULL));
if (!private_key) {
return false;
}
*public_key = blink::WebCryptoKey::create(
new PublicKeyHandle(crypto::ScopedSECKEYPublicKey(sec_public_key)),
blink::WebCryptoKeyTypePublic,
true,
algorithm,
usage_mask);
*private_key = blink::WebCryptoKey::create(
new PrivateKeyHandle(scoped_sec_private_key.Pass()),
blink::WebCryptoKeyTypePrivate,
extractable,
algorithm,
usage_mask);
return true;
}
default:
return false;
}
}
bool WebCryptoImpl::ImportKeyInternal(
blink::WebCryptoKeyFormat format,
const unsigned char* key_data,
unsigned key_data_size,
const blink::WebCryptoAlgorithm& algorithm_or_null,
bool extractable,
blink::WebCryptoKeyUsageMask usage_mask,
blink::WebCryptoKey* key) {
switch (format) {
case blink::WebCryptoKeyFormatRaw:
// A 'raw'-formatted key import requires an input algorithm.
if (algorithm_or_null.isNull())
return false;
return ImportKeyInternalRaw(key_data,
key_data_size,
algorithm_or_null,
extractable,
usage_mask,
key);
case blink::WebCryptoKeyFormatSpki:
return ImportKeyInternalSpki(key_data,
key_data_size,
algorithm_or_null,
extractable,
usage_mask,
key);
case blink::WebCryptoKeyFormatPkcs8:
return ImportKeyInternalPkcs8(key_data,
key_data_size,
algorithm_or_null,
extractable,
usage_mask,
key);
default:
// NOTE: blink::WebCryptoKeyFormatJwk is handled one level above.
return false;
}
}
bool WebCryptoImpl::ExportKeyInternal(
blink::WebCryptoKeyFormat format,
const blink::WebCryptoKey& key,
blink::WebArrayBuffer* buffer) {
switch (format) {
case blink::WebCryptoKeyFormatRaw:
return ExportKeyInternalRaw(key, buffer);
case blink::WebCryptoKeyFormatSpki:
return ExportKeyInternalSpki(key, buffer);
case blink::WebCryptoKeyFormatPkcs8:
// TODO(padolph): Implement pkcs8 export
return false;
default:
return false;
}
}
bool WebCryptoImpl::SignInternal(
const blink::WebCryptoAlgorithm& algorithm,
const blink::WebCryptoKey& key,
const unsigned char* data,
unsigned data_size,
blink::WebArrayBuffer* buffer) {
blink::WebArrayBuffer result;
switch (algorithm.id()) {
case blink::WebCryptoAlgorithmIdHmac: {
const blink::WebCryptoHmacParams* params = algorithm.hmacParams();
if (!params) {
return false;
}
SymKeyHandle* sym_key = reinterpret_cast<SymKeyHandle*>(key.handle());
DCHECK_EQ(PK11_GetMechanism(sym_key->key()),
WebCryptoAlgorithmToHMACMechanism(params->hash()));
DCHECK_NE(0, key.usages() & blink::WebCryptoKeyUsageSign);
SECItem param_item = { siBuffer, NULL, 0 };
SECItem data_item = {
siBuffer,
const_cast<unsigned char*>(data),
data_size
};
// First call is to figure out the length.
SECItem signature_item = { siBuffer, NULL, 0 };
if (PK11_SignWithSymKey(sym_key->key(),
PK11_GetMechanism(sym_key->key()),
¶m_item,
&signature_item,
&data_item) != SECSuccess) {
NOTREACHED();
return false;
}
DCHECK_NE(0u, signature_item.len);
result = blink::WebArrayBuffer::create(signature_item.len, 1);
signature_item.data = reinterpret_cast<unsigned char*>(result.data());
if (PK11_SignWithSymKey(sym_key->key(),
PK11_GetMechanism(sym_key->key()),
¶m_item,
&signature_item,
&data_item) != SECSuccess) {
NOTREACHED();
return false;
}
DCHECK_EQ(result.byteLength(), signature_item.len);
break;
}
default:
return false;
}
*buffer = result;
return true;
}
bool WebCryptoImpl::VerifySignatureInternal(
const blink::WebCryptoAlgorithm& algorithm,
const blink::WebCryptoKey& key,
const unsigned char* signature,
unsigned signature_size,
const unsigned char* data,
unsigned data_size,
bool* signature_match) {
switch (algorithm.id()) {
case blink::WebCryptoAlgorithmIdHmac: {
blink::WebArrayBuffer result;
if (!SignInternal(algorithm, key, data, data_size, &result)) {
return false;
}
// Handling of truncated signatures is underspecified in the WebCrypto
// spec, so here we fail verification if a truncated signature is being
// verified.
// See https://www.w3.org/Bugs/Public/show_bug.cgi?id=23097
*signature_match =
result.byteLength() == signature_size &&
crypto::SecureMemEqual(result.data(), signature, signature_size);
break;
}
default:
return false;
}
return true;
}
bool WebCryptoImpl::ImportRsaPublicKeyInternal(
const unsigned char* modulus_data,
unsigned modulus_size,
const unsigned char* exponent_data,
unsigned exponent_size,
const blink::WebCryptoAlgorithm& algorithm,
bool extractable,
blink::WebCryptoKeyUsageMask usage_mask,
blink::WebCryptoKey* key) {
if (!modulus_size || !exponent_size)
return false;
DCHECK(modulus_data);
DCHECK(exponent_data);
// NSS does not provide a way to create an RSA public key directly from the
// modulus and exponent values, but it can import an DER-encoded ASN.1 blob
// with these values and create the public key from that. The code below
// follows the recommendation described in
// https://developer.mozilla.org/en-US/docs/NSS/NSS_Tech_Notes/nss_tech_note7
// Pack the input values into a struct compatible with NSS ASN.1 encoding, and
// set up an ASN.1 encoder template for it.
struct RsaPublicKeyData {
SECItem modulus;
SECItem exponent;
};
const RsaPublicKeyData pubkey_in = {
{siUnsignedInteger, const_cast<unsigned char*>(modulus_data),
modulus_size},
{siUnsignedInteger, const_cast<unsigned char*>(exponent_data),
exponent_size}};
const SEC_ASN1Template rsa_public_key_template[] = {
{SEC_ASN1_SEQUENCE, 0, NULL, sizeof(RsaPublicKeyData)},
{SEC_ASN1_INTEGER, offsetof(RsaPublicKeyData, modulus), },
{SEC_ASN1_INTEGER, offsetof(RsaPublicKeyData, exponent), },
{0, }};
// DER-encode the public key.
crypto::ScopedSECItem pubkey_der(SEC_ASN1EncodeItem(
NULL, NULL, &pubkey_in, rsa_public_key_template));
if (!pubkey_der)
return false;
// Import the DER-encoded public key to create an RSA SECKEYPublicKey.
crypto::ScopedSECKEYPublicKey pubkey(
SECKEY_ImportDERPublicKey(pubkey_der.get(), CKK_RSA));
if (!pubkey)
return false;
*key = blink::WebCryptoKey::create(new PublicKeyHandle(pubkey.Pass()),
blink::WebCryptoKeyTypePublic,
extractable,
algorithm,
usage_mask);
return true;
}
} // namespace content
| 31.422091 | 80 | 0.656142 | [
"object",
"vector"
] |
10662cf4e711ed260f9c7b8574f6fd60fef11d37 | 7,877 | cpp | C++ | Luna/lib/resourceManager.cpp | MetroGirl/Src_LUNA | f59befa48bd79ab3a8bf71e3c5b975c8e76e6b79 | [
"Artistic-2.0"
] | 3 | 2015-04-09T10:09:38.000Z | 2018-08-10T13:15:48.000Z | Luna/lib/resourceManager.cpp | MetroGirl/Src_LUNA | f59befa48bd79ab3a8bf71e3c5b975c8e76e6b79 | [
"Artistic-2.0"
] | null | null | null | Luna/lib/resourceManager.cpp | MetroGirl/Src_LUNA | f59befa48bd79ab3a8bf71e3c5b975c8e76e6b79 | [
"Artistic-2.0"
] | null | null | null | #include "stdafx.h"
#include "resourceManager.h"
#include "resourceObject.h"
namespace luna{
LUNA_IMPLEMENT_CONCRETE(luna::ResourceManager);
LUNA_IMPLEMENT_SINGLETON(ResourceManager);
ResourceManager::ResourceManager()
: mResourceTbl()
, mTerminating(false)
, mDirectoryChanged(false)
{
}
ResourceManager::~ResourceManager()
{
}
void ResourceManager::initialize()
{
c16 szTmpBuffer[1024];
GetCurrentDirectory(sizeof(szTmpBuffer) / sizeof(*szTmpBuffer), szTmpBuffer);
mCurrentDir = szTmpBuffer;
buildTypeTbl(ResourceObject::TypeInfo);
#if !LUNA_PUBLISH
DWORD dwThreadId;
mDirectoryWatchThread = CreateThread(nullptr, 0, static_cast<LPTHREAD_START_ROUTINE>(directoryWatchProc), this, 0, &dwThreadId);
#endif
}
void ResourceManager::finalize()
{
mTerminating = true;
// デモの場合はリーク上等なのでチェックしない
//for (auto& resourcePtr : mResourceTbl){
// LUNA_ERRORLINE(L"detected leak of resource[%ls]. refPtr is [%lu].", resourcePtr->getPath().c_str(), resourcePtr->getRef());
//}
#if !LUNA_PUBLISH
WaitForSingleObject(mDirectoryWatchThread, INFINITE);
CloseHandle(mDirectoryWatchThread);
#endif
}
ResourceManager::DetouredResource ResourceManager::load(const c16* filename)
{
if (auto loadedPtr = queryCache(filename)){
return loadedPtr;
}
if (auto retPtr = loadNew(filename)){
enterCache(retPtr);
return retPtr;
}
return nullptr;
}
ResourceObject* ResourceManager::queryCache(const c16* name)
{
for (auto& objectPtr : mResourceTbl){
if (objectPtr->getPath() == name){
if (isReloadRequired(objectPtr)){
reload(objectPtr);
}
objectPtr->addRef();
return static_cast<ResourceObject*>(objectPtr);
}
}
return nullptr;
}
void ResourceManager::enterCache(ResourceObject* objectPtr)
{
mResourceTbl.push_back(objectPtr);
}
ResourceObject* ResourceManager::loadNew(const c16* filename)
{
if (!File::exist(filename)){
LUNA_ERRORLINE(L"file not found [%ls].", filename);
return nullptr;
}
File fIn;
if (!fIn.open(filename, File::OpenMode_Read)){
LUNA_ERRORLINE(L"failed to open file [%ls].", filename);
return nullptr;
}
if (!fIn.getSize()){
LUNA_ERRORLINE(L"[%ls] has no readable area.", filename);
return nullptr;
}
FileStream sIn(&fIn);
return loadNew(sIn);
}
ResourceObject* ResourceManager::loadNew(Stream& sIn)
{
ResourceObject* retPtr = nullptr;
for (auto& tiPtr : mResourceTypeTbl){
if (tiPtr->isAbstract()){
continue;
}
retPtr = static_cast<ResourceObject*>(tiPtr->createInstance());
if (!retPtr){
LUNA_ASSERT(0, L"out of memory.");
continue;
}
retPtr->addRef();
sIn.seek(0, File::SeekMode_Set);
if (retPtr->isLoadable(sIn)){
LUNA_TRACELINE(L"loading : [%24ls][%12hs].", sIn.getPath().c_str(), retPtr->getTypeInfo().getTypeName());
sIn.seek(0, File::SeekMode_Set);
if (!retPtr->doLoad(sIn)){
LUNA_ERRORLINE(L"[%s] load failed, while loading with [%s].", sIn.getPath().c_str(), retPtr->getTypeInfo().getTypeName());
retPtr->release();
retPtr = nullptr;
continue;
}
LUNA_TRACELINE(L"loaded : [%24ls][%12hs].", sIn.getPath().c_str(), retPtr->getTypeInfo().getTypeName());
break;
}
else{
retPtr->release();
retPtr = nullptr;
}
}
if (!retPtr){
LUNA_ERRORLINE(L"There're no loadable class for [%ls].", sIn.getPath().c_str());
}
return retPtr;
}
void ResourceManager::deleteNotification(ResourceObject* objectPtr)
{
LUNA_ASSERT(objectPtr->getRef() == 0, L"");
for (vector<ResourceObject*>::iterator it = mResourceTbl.begin(); it != mResourceTbl.end(); ++it){
if ((*it) == objectPtr){
LUNA_TRACELINE(L"unloaded : [%24ls].", (*it)->getPath().c_str());
mResourceTbl.erase(it);
break;
}
}
}
void ResourceManager::writePackFile(const c16* path)
{
File::writePackFile(path);
}
void ResourceManager::readPackFile(const c16* path, function<void (f32)> cbProgress)
{
if (File::readPackFile(path)){
auto& header = File::getPackHeader();
auto& tocTbl = File::getPackToc();
const f32 incPerFile = 1 / (f32)tocTbl.size();
f32 progress = 0.f;
cbProgress(progress);
for (auto& toc : tocTbl){
load(toc.pathStr);
progress += incPerFile;
cbProgress(progress);
}
cbProgress(1.f);
}
else{
cbProgress(0.f);
cbProgress(1.f);
}
}
bool ResourceManager::isReloadRequired(const luna::TypeInfo &dti)
{
#if !LUNA_PUBLISH
for (vector<ResourceObject*>::iterator it = mResourceTbl.begin(); it != mResourceTbl.end(); ++it){
ResourceObject* objectPtr = (*it);
if (objectPtr->isA(dti) && isReloadRequired(objectPtr)){
return true;
}
}
#endif
return false;
}
bool ResourceManager::isReloadRequired(ResourceObject* objectPtr)
{
#if !LUNA_PUBLISH
vector< pair<FILETIME, wstring> > vecFiles;
vecFiles.push_back(pair<FILETIME, wstring>(objectPtr->getTime(), objectPtr->getPath()));
objectPtr->getSubFiles(vecFiles);
bool isUpdated = false;
for (vector< pair<FILETIME, wstring> >::iterator it = vecFiles.begin(); it != vecFiles.end(); ++it){
FILETIME mem = it->first;
FILETIME file;
HANDLE hFile = CreateFile(it->second.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
if (hFile != INVALID_HANDLE_VALUE){
GetFileTime(hFile, nullptr, nullptr, &file);
CloseHandle(hFile);
}
if (CompareFileTime(&file, &mem) == 1){
isUpdated = true;
break;
}
}
return isUpdated;
#else
return false;
#endif
}
void ResourceManager::reload()
{
reload(ResourceObject::TypeInfo);
}
void ResourceManager::reload(const luna::TypeInfo &dti)
{
#if !LUNA_PUBLISH
vector<ResourceObject*> vecReload;
for (vector<ResourceObject*>::iterator it = mResourceTbl.begin(); it != mResourceTbl.end(); ++it){
ResourceObject* objectPtr = (*it);
if (objectPtr->isA(dti) && isReloadRequired(objectPtr)){
vecReload.push_back(objectPtr);
objectPtr->addRef();
}
}
for (vector<ResourceObject*>::iterator it = vecReload.begin(); it != vecReload.end(); ++it){
ResourceObject* objectPtr = (*it);
reload(objectPtr);
objectPtr->release();
}
#endif
}
void ResourceManager::reload(ResourceObject* objectPtr)
{
objectPtr->doReload();
}
bool ResourceManager::postUpdate()
{
#if !LUNA_PUBLISH
for (vector<ResourceObject*>::iterator it = mResourceTbl.begin(); it != mResourceTbl.end(); ++it){
ResourceObject* objectPtr = (*it);
if (objectPtr->isReloaded()){
objectPtr->setReloaded(false);
}
}
{
ScopedLock lock(mDirectorySync);
if (isDirectoryChanged() || ((GetAsyncKeyState(VK_F5) & 0x8000) == 0x8000)){
reload();
mDirectoryChanged = false;
}
}
#endif
return true;
}
void ResourceManager::buildTypeTbl(const luna::TypeInfo& ti)
{
const luna::TypeInfo* tiPtr = &ti;
while (tiPtr){
if (tiPtr->isA(ResourceObject::TypeInfo)){
mResourceTypeTbl.push_back(tiPtr);
if (tiPtr->getChild()){
buildTypeTbl(*tiPtr->getChild());
}
}
tiPtr = tiPtr->getNext();
}
}
DWORD WINAPI ResourceManager::directoryWatchProc(void* paramPtr)
{
#if !LUNA_PUBLISH
auto* instancePtr = static_cast<ResourceManager*>(paramPtr);
const DWORD filter = FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME | FILE_NOTIFY_CHANGE_ATTRIBUTES | FILE_NOTIFY_CHANGE_SIZE | FILE_NOTIFY_CHANGE_LAST_WRITE;
HANDLE hWatch = FindFirstChangeNotification(L"./data/", TRUE, filter);
if (hWatch == INVALID_HANDLE_VALUE) {
return 1;
}
while (!instancePtr->mTerminating){
const DWORD waitResult = WaitForSingleObject(hWatch, 100);
if (waitResult == WAIT_TIMEOUT) {
continue;
}
{
ScopedLock lock(instancePtr->mDirectorySync);
instancePtr->mDirectoryChanged = true;
}
if (!FindNextChangeNotification(hWatch)){
break;
}
}
#endif
return 0;
}
}
| 24.386997 | 172 | 0.680716 | [
"vector"
] |
106babf7824d2b496c4606f20e3118ff1102cb4e | 6,019 | cc | C++ | src/ui/scenic/lib/gfx/engine/annotation_manager.cc | allansrc/fuchsia | a2c235b33fc4305044d496354a08775f30cdcf37 | [
"BSD-2-Clause"
] | 210 | 2019-02-05T12:45:09.000Z | 2022-03-28T07:59:06.000Z | src/ui/scenic/lib/gfx/engine/annotation_manager.cc | allansrc/fuchsia | a2c235b33fc4305044d496354a08775f30cdcf37 | [
"BSD-2-Clause"
] | 5 | 2019-12-04T15:13:37.000Z | 2020-02-19T08:11:38.000Z | src/ui/scenic/lib/gfx/engine/annotation_manager.cc | allansrc/fuchsia | a2c235b33fc4305044d496354a08775f30cdcf37 | [
"BSD-2-Clause"
] | 73 | 2019-03-06T18:55:23.000Z | 2022-03-26T12:04:51.000Z | // Copyright 2020 The Fuchsia 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 "annotation_manager.h"
#include "src/ui/scenic/lib/gfx/engine/object_linker.h"
#include "src/ui/scenic/lib/gfx/engine/session.h"
#include "src/ui/scenic/lib/gfx/engine/view_tree.h"
#include "src/ui/scenic/lib/gfx/resources/view.h"
#include "src/ui/scenic/lib/gfx/resources/view_holder.h"
#include "src/ui/scenic/lib/utils/helpers.h"
namespace scenic_impl {
namespace gfx {
using fuchsia::ui::views::ViewHolderToken;
using fuchsia::ui::views::ViewRef;
AnnotationManager::AnnotationManager(SceneGraphWeakPtr scene_graph, ViewLinker* view_linker,
std::unique_ptr<Session> session)
: scene_graph_(scene_graph),
view_linker_(view_linker),
session_(std::move(session)),
weak_factory_(this) {
FX_DCHECK(scene_graph_);
FX_DCHECK(view_linker_);
FX_DCHECK(session_);
}
ViewHolderPtr AnnotationManager::NewAnnotationViewHolder(ViewHolderToken view_holder_token,
ViewTreeUpdater& view_tree_updater) {
std::ostringstream annotation_debug_name;
annotation_debug_name << "Annotation ViewHolder: Token " << view_holder_token.value.get();
ViewHolderPtr annotation_view_holder = fxl::MakeRefCounted<ViewHolder>(
session_.get(), session_->id(), /* node_id */ 0U, /* suppress_events */ true,
annotation_debug_name.str(), session_->shared_error_reporter(),
view_tree_updater.GetWeakPtr());
// Set hit test behavior to kSuppress so it will suppress all hit testings.
annotation_view_holder->SetHitTestBehavior(fuchsia::ui::gfx::HitTestBehavior::kSuppress);
// Set up link with annotation View.
ViewLinker::ExportLink link = view_linker_->CreateExport(
annotation_view_holder.get(), std::move(view_holder_token.value), session_->error_reporter());
FX_CHECK(link.valid()) << "Cannot setup link with annotation View!";
annotation_view_holder->Connect(std::move(link));
return annotation_view_holder;
}
bool AnnotationManager::HasHandler(AnnotationHandlerId handler_id) const {
return handlers_state_.find(handler_id) != handlers_state_.end();
}
bool AnnotationManager::RegisterHandler(AnnotationHandlerId handler_id,
fit::function<void(zx_status_t)> on_handler_removed) {
if (HasHandler(handler_id)) {
return false;
}
handlers_state_[handler_id] =
HandlerState{.requests = {}, .on_handler_removed = std::move(on_handler_removed)};
return true;
}
bool AnnotationManager::RemoveHandlerWithEpitaph(AnnotationHandlerId handler_id,
zx_status_t epitaph) {
if (!HasHandler(handler_id)) {
return false;
}
handlers_state_[handler_id].on_handler_removed(epitaph);
handlers_state_.erase(handler_id);
return true;
}
void AnnotationManager::RequestCreate(AnnotationHandlerId handler_id, ViewRef main_view,
ViewHolderToken view_holder_token,
OnAnnotationViewHolderCreatedCallback callback) {
FX_CHECK(HasHandler(handler_id)) << "Handler ID " << handler_id << " invalid!";
handlers_state_[handler_id].requests.push_back(CreationRequest{
.fulfilled = false,
.main_view = std::move(main_view),
.annotation_view_holder = std::move(view_holder_token),
.callback = std::move(callback),
});
}
void AnnotationManager::CleanupInvalidHandlerState(
const std::vector<std::pair<AnnotationHandlerId, zx_status_t>>& invalid_handlers_info) {
std::unordered_set<AnnotationHandlerId> removed_handlers;
// Clean up invalid handlers.
for (const auto& [handler_id, epitaph] : invalid_handlers_info) {
if (removed_handlers.find(handler_id) == removed_handlers.end()) {
auto result = RemoveHandlerWithEpitaph(handler_id, epitaph);
removed_handlers.insert(handler_id);
FX_DCHECK(result) << "Remove annotation handler #" << handler_id
<< " failed: Handler doesn't exist.";
}
}
}
void AnnotationManager::CleanupFulfilledRequests() {
for (auto& kv : handlers_state_) {
HandlerState& state = kv.second;
state.requests.remove_if([](const CreationRequest& request) { return request.fulfilled; });
}
}
void AnnotationManager::FulfillCreateRequests(ViewTreeUpdater& view_tree_updater) {
std::vector<std::pair<AnnotationHandlerId, zx_status_t>> invalid_handlers_info;
for (auto& kv : handlers_state_) {
AnnotationHandlerId handler_id = kv.first;
HandlerState& state = kv.second;
for (auto& request : state.requests) {
// Turn ViewHolderToken into a ViewHolder.
if (std::holds_alternative<fuchsia::ui::views::ViewHolderToken>(
request.annotation_view_holder)) {
request.annotation_view_holder = NewAnnotationViewHolder(
std::move(
std::get<fuchsia::ui::views::ViewHolderToken>(request.annotation_view_holder)),
view_tree_updater);
}
const zx_koid_t main_view_koid = utils::ExtractKoid(request.main_view);
const zx_status_t status = scene_graph_->view_tree().AddAnnotationViewHolder(
main_view_koid, std::get<ViewHolderPtr>(request.annotation_view_holder));
if (status == ZX_OK) {
request.fulfilled = true;
request.callback();
} else if (status == ZX_ERR_PEER_CLOSED) {
// This occurred when Session of |request.main_view| is destroyed
// before AnnotationManager handles the request. In this case we only
// need to remove it from the request list.
request.fulfilled = true;
} else if (status != ZX_ERR_NOT_FOUND) {
invalid_handlers_info.emplace_back(handler_id, status);
break;
}
}
}
CleanupInvalidHandlerState(invalid_handlers_info);
CleanupFulfilledRequests();
}
} // namespace gfx
} // namespace scenic_impl
| 40.668919 | 100 | 0.703439 | [
"vector"
] |
106d81a0406c2e392b0c9feba186eb8be82571c6 | 22,656 | cpp | C++ | Src/Base/AMReX_MultiFabUtil.cpp | wolfram-schmidt/amrex | 88120db4736c325a2d3d2c291adacaffd3bf224b | [
"BSD-3-Clause-LBNL"
] | null | null | null | Src/Base/AMReX_MultiFabUtil.cpp | wolfram-schmidt/amrex | 88120db4736c325a2d3d2c291adacaffd3bf224b | [
"BSD-3-Clause-LBNL"
] | null | null | null | Src/Base/AMReX_MultiFabUtil.cpp | wolfram-schmidt/amrex | 88120db4736c325a2d3d2c291adacaffd3bf224b | [
"BSD-3-Clause-LBNL"
] | null | null | null |
#include <AMReX_MultiFabUtil.H>
#include <AMReX_MultiFabUtil_F.H>
#include <sstream>
#include <iostream>
namespace {
using namespace amrex;
static Box
getIndexBox(const RealBox& real_box, const Geometry& geom) {
IntVect slice_lo, slice_hi;
AMREX_D_TERM(slice_lo[0]=floor((real_box.lo(0) - geom.ProbLo(0))/geom.CellSize(0));,
slice_lo[1]=floor((real_box.lo(1) - geom.ProbLo(1))/geom.CellSize(1));,
slice_lo[2]=floor((real_box.lo(2) - geom.ProbLo(2))/geom.CellSize(2)););
AMREX_D_TERM(slice_hi[0]=floor((real_box.hi(0) - geom.ProbLo(0))/geom.CellSize(0));,
slice_hi[1]=floor((real_box.hi(1) - geom.ProbLo(1))/geom.CellSize(1));,
slice_hi[2]=floor((real_box.hi(2) - geom.ProbLo(2))/geom.CellSize(2)););
return Box(slice_lo, slice_hi) & geom.Domain();
}
static
std::unique_ptr<MultiFab> allocateSlice(int dir, const MultiFab& cell_centered_data,
int ncomp, const Geometry& geom, Real dir_coord,
Vector<int>& slice_to_full_ba_map) {
// Get our slice and convert to index space
RealBox real_slice = geom.ProbDomain();
real_slice.setLo(dir, dir_coord);
real_slice.setHi(dir, dir_coord);
Box slice_box = getIndexBox(real_slice, geom);
// define the multifab that stores slice
BoxArray ba = cell_centered_data.boxArray();
const DistributionMapping& dm = cell_centered_data.DistributionMap();
std::vector< std::pair<int, Box> > isects;
ba.intersections(slice_box, isects, false, 0);
Vector<Box> boxes;
Vector<int> procs;
for (int i = 0; i < isects.size(); ++i) {
procs.push_back(dm[isects[i].first]);
boxes.push_back(isects[i].second);
slice_to_full_ba_map.push_back(isects[i].first);
}
BoxArray slice_ba(&boxes[0], boxes.size());
DistributionMapping slice_dmap(std::move(procs));
std::unique_ptr<MultiFab> slice(new MultiFab(slice_ba, slice_dmap, ncomp, 0,
MFInfo(), cell_centered_data.Factory()));
return slice;
}
}
namespace amrex
{
void average_node_to_cellcenter (MultiFab& cc, int dcomp, const MultiFab& nd, int scomp, int ncomp)
{
#ifdef _OPENMP
#pragma omp parallel
#endif
for (MFIter mfi(cc,true); mfi.isValid(); ++mfi)
{
const Box& bx = mfi.tilebox();
amrex_fort_avg_nd_to_cc(bx.loVect(), bx.hiVect(), &ncomp,
BL_TO_FORTRAN_N(cc[mfi],dcomp),
BL_TO_FORTRAN_N(nd[mfi],scomp));
}
}
void average_edge_to_cellcenter (MultiFab& cc, int dcomp, const Vector<const MultiFab*>& edge)
{
BL_ASSERT(cc.nComp() >= dcomp + AMREX_SPACEDIM);
BL_ASSERT(edge.size() == AMREX_SPACEDIM);
BL_ASSERT(edge[0]->nComp() == 1);
#ifdef _OPENMP
#pragma omp parallel
#endif
for (MFIter mfi(cc,true); mfi.isValid(); ++mfi)
{
const Box& bx = mfi.tilebox();
BL_FORT_PROC_CALL(BL_AVG_EG_TO_CC,bl_avg_eg_to_cc)
(bx.loVect(), bx.hiVect(),
BL_TO_FORTRAN_N(cc[mfi],dcomp),
AMREX_D_DECL(BL_TO_FORTRAN((*edge[0])[mfi]),
BL_TO_FORTRAN((*edge[1])[mfi]),
BL_TO_FORTRAN((*edge[2])[mfi])));
}
}
void average_face_to_cellcenter (MultiFab& cc, int dcomp, const Vector<const MultiFab*>& fc)
{
BL_ASSERT(cc.nComp() >= dcomp + AMREX_SPACEDIM);
BL_ASSERT(fc.size() == AMREX_SPACEDIM);
BL_ASSERT(fc[0]->nComp() == 1);
Real dx[3] = {1.0,1.0,1.0};
Real problo[3] = {0.,0.,0.};
int coord_type = 0;
#ifdef _OPENMP
#pragma omp parallel
#endif
for (MFIter mfi(cc,true); mfi.isValid(); ++mfi)
{
const Box& bx = mfi.tilebox();
BL_FORT_PROC_CALL(BL_AVG_FC_TO_CC,bl_avg_fc_to_cc)
(bx.loVect(), bx.hiVect(),
BL_TO_FORTRAN_N(cc[mfi],dcomp),
AMREX_D_DECL(BL_TO_FORTRAN((*fc[0])[mfi]),
BL_TO_FORTRAN((*fc[1])[mfi]),
BL_TO_FORTRAN((*fc[2])[mfi])),
dx, problo, coord_type);
}
}
void average_face_to_cellcenter (MultiFab& cc, const Vector<const MultiFab*>& fc,
const Geometry& geom)
{
BL_ASSERT(cc.nComp() >= AMREX_SPACEDIM);
BL_ASSERT(fc.size() == AMREX_SPACEDIM);
BL_ASSERT(fc[0]->nComp() == 1); // We only expect fc to have the gradient perpendicular to the face
const Real* dx = geom.CellSize();
const Real* problo = geom.ProbLo();
int coord_type = Geometry::Coord();
#ifdef _OPENMP
#pragma omp parallel
#endif
for (MFIter mfi(cc,true); mfi.isValid(); ++mfi)
{
const Box& bx = mfi.tilebox();
BL_FORT_PROC_CALL(BL_AVG_FC_TO_CC,bl_avg_fc_to_cc)
(bx.loVect(), bx.hiVect(),
BL_TO_FORTRAN(cc[mfi]),
AMREX_D_DECL(BL_TO_FORTRAN((*fc[0])[mfi]),
BL_TO_FORTRAN((*fc[1])[mfi]),
BL_TO_FORTRAN((*fc[2])[mfi])),
dx, problo, coord_type);
}
}
void average_cellcenter_to_face (const Vector<MultiFab*>& fc, const MultiFab& cc,
const Geometry& geom)
{
BL_ASSERT(cc.nComp() == 1);
BL_ASSERT(cc.nGrow() >= 1);
BL_ASSERT(fc.size() == AMREX_SPACEDIM);
BL_ASSERT(fc[0]->nComp() == 1); // We only expect fc to have the gradient perpendicular to the face
const Real* dx = geom.CellSize();
const Real* problo = geom.ProbLo();
int coord_type = Geometry::Coord();
#ifdef _OPENMP
#pragma omp parallel
#endif
for (MFIter mfi(cc,true); mfi.isValid(); ++mfi)
{
const Box& xbx = mfi.nodaltilebox(0);
#if (AMREX_SPACEDIM > 1)
const Box& ybx = mfi.nodaltilebox(1);
#endif
#if (AMREX_SPACEDIM == 3)
const Box& zbx = mfi.nodaltilebox(2);
#endif
BL_FORT_PROC_CALL(BL_AVG_CC_TO_FC,bl_avg_cc_to_fc)
(xbx.loVect(), xbx.hiVect(),
#if (AMREX_SPACEDIM > 1)
ybx.loVect(), ybx.hiVect(),
#endif
#if (AMREX_SPACEDIM == 3)
zbx.loVect(), zbx.hiVect(),
#endif
AMREX_D_DECL(BL_TO_FORTRAN((*fc[0])[mfi]),
BL_TO_FORTRAN((*fc[1])[mfi]),
BL_TO_FORTRAN((*fc[2])[mfi])),
BL_TO_FORTRAN(cc[mfi]),
dx, problo, coord_type);
}
}
// *************************************************************************************************************
// Average fine cell-based MultiFab onto crse cell-centered MultiFab.
// We do NOT assume that the coarse layout is a coarsened version of the fine layout.
// This version DOES use volume-weighting.
void average_down (const MultiFab& S_fine, MultiFab& S_crse,
const Geometry& fgeom, const Geometry& cgeom,
int scomp, int ncomp, int rr)
{
average_down(S_fine,S_crse,fgeom,cgeom,scomp,ncomp,rr*IntVect::TheUnitVector());
}
void average_down (const MultiFab& S_fine, MultiFab& S_crse,
const Geometry& fgeom, const Geometry& cgeom,
int scomp, int ncomp, const IntVect& ratio)
{
if (S_fine.is_nodal() || S_crse.is_nodal())
{
amrex::Error("Can't use amrex::average_down for nodal MultiFab!");
}
#if (AMREX_SPACEDIM == 3)
amrex::average_down(S_fine, S_crse, scomp, ncomp, ratio);
return;
#else
BL_ASSERT(S_crse.nComp() == S_fine.nComp());
//
// Coarsen() the fine stuff on processors owning the fine data.
//
const BoxArray& fine_BA = S_fine.boxArray();
const DistributionMapping& fine_dm = S_fine.DistributionMap();
BoxArray crse_S_fine_BA = fine_BA;
crse_S_fine_BA.coarsen(ratio);
MultiFab crse_S_fine(crse_S_fine_BA,fine_dm,ncomp,0,MFInfo(),FArrayBoxFactory());
MultiFab fvolume;
fgeom.GetVolume(fvolume, fine_BA, fine_dm, 0);
#ifdef _OPENMP
#pragma omp parallel
#endif
for (MFIter mfi(crse_S_fine,true); mfi.isValid(); ++mfi)
{
// NOTE: The tilebox is defined at the coarse level.
const Box& tbx = mfi.tilebox();
// NOTE: We copy from component scomp of the fine fab into component 0 of the crse fab
// because the crse fab is a temporary which was made starting at comp 0, it is
// not part of the actual crse multifab which came in.
BL_FORT_PROC_CALL(BL_AVGDOWN_WITH_VOL,bl_avgdown_with_vol)
(tbx.loVect(), tbx.hiVect(),
BL_TO_FORTRAN_N(S_fine[mfi],scomp),
BL_TO_FORTRAN_N(crse_S_fine[mfi],0),
BL_TO_FORTRAN(fvolume[mfi]),
ratio.getVect(),&ncomp);
}
S_crse.copy(crse_S_fine,0,scomp,ncomp);
#endif
}
// *************************************************************************************************************
// Average fine cell-based MultiFab onto crse cell-centered MultiFab.
// We do NOT assume that the coarse layout is a coarsened version of the fine layout.
// This version does NOT use volume-weighting
void average_down (const MultiFab& S_fine, MultiFab& S_crse, int scomp, int ncomp, int rr)
{
average_down(S_fine,S_crse,scomp,ncomp,rr*IntVect::TheUnitVector());
}
void sum_fine_to_coarse(const MultiFab& S_fine, MultiFab& S_crse,
int scomp, int ncomp, const IntVect& ratio,
const Geometry& cgeom, const Geometry& fgeom)
{
BL_ASSERT(S_crse.nComp() == S_fine.nComp());
BL_ASSERT(ratio == ratio[0]);
BL_ASSERT(S_fine.nGrow() % ratio[0] == 0);
const int nGrow = S_fine.nGrow() / ratio[0];
//
// Coarsen() the fine stuff on processors owning the fine data.
//
BoxArray crse_S_fine_BA = S_fine.boxArray(); crse_S_fine_BA.coarsen(ratio);
MultiFab crse_S_fine(crse_S_fine_BA, S_fine.DistributionMap(), ncomp, nGrow, MFInfo(), FArrayBoxFactory());
#ifdef _OPENMP
#pragma omp parallel
#endif
for (MFIter mfi(crse_S_fine, true); mfi.isValid(); ++mfi)
{
// NOTE: The tilebox is defined at the coarse level.
const Box& tbx = mfi.growntilebox(nGrow);
BL_FORT_PROC_CALL(BL_AVGDOWN, bl_avgdown)
(tbx.loVect(), tbx.hiVect(),
BL_TO_FORTRAN_N(S_fine[mfi] , scomp),
BL_TO_FORTRAN_N(crse_S_fine[mfi], 0),
ratio.getVect(),&ncomp);
}
S_crse.copy(crse_S_fine, 0, scomp, ncomp, nGrow, 0,
cgeom.periodicity(), FabArrayBase::ADD);
}
void average_down (const MultiFab& S_fine, MultiFab& S_crse,
int scomp, int ncomp, const IntVect& ratio)
{
BL_ASSERT(S_crse.nComp() == S_fine.nComp());
BL_ASSERT((S_crse.is_cell_centered() && S_fine.is_cell_centered()) ||
(S_crse.is_nodal() && S_fine.is_nodal()));
bool is_cell_centered = S_crse.is_cell_centered();
//
// Coarsen() the fine stuff on processors owning the fine data.
//
BoxArray crse_S_fine_BA = S_fine.boxArray(); crse_S_fine_BA.coarsen(ratio);
if (crse_S_fine_BA == S_crse.boxArray() and S_fine.DistributionMap() == S_crse.DistributionMap())
{
#ifdef _OPENMP
#pragma omp parallel
#endif
for (MFIter mfi(S_crse,true); mfi.isValid(); ++mfi)
{
// NOTE: The tilebox is defined at the coarse level.
const Box& tbx = mfi.tilebox();
if (is_cell_centered) {
BL_FORT_PROC_CALL(BL_AVGDOWN,bl_avgdown)
(tbx.loVect(), tbx.hiVect(),
BL_TO_FORTRAN_N(S_fine[mfi],scomp),
BL_TO_FORTRAN_N(S_crse[mfi],scomp),
ratio.getVect(),&ncomp);
} else {
BL_FORT_PROC_CALL(BL_AVGDOWN_NODES,bl_avgdown_nodes)
(tbx.loVect(),tbx.hiVect(),
BL_TO_FORTRAN_N(S_fine[mfi],scomp),
BL_TO_FORTRAN_N(S_crse[mfi],scomp),
ratio.getVect(),&ncomp);
}
}
}
else
{
MultiFab crse_S_fine(crse_S_fine_BA, S_fine.DistributionMap(), ncomp, 0, MFInfo(), FArrayBoxFactory());
#ifdef _OPENMP
#pragma omp parallel
#endif
for (MFIter mfi(crse_S_fine,true); mfi.isValid(); ++mfi)
{
// NOTE: The tilebox is defined at the coarse level.
const Box& tbx = mfi.tilebox();
// NOTE: We copy from component scomp of the fine fab into component 0 of the crse fab
// because the crse fab is a temporary which was made starting at comp 0, it is
// not part of the actual crse multifab which came in.
if (is_cell_centered) {
BL_FORT_PROC_CALL(BL_AVGDOWN,bl_avgdown)
(tbx.loVect(), tbx.hiVect(),
BL_TO_FORTRAN_N(S_fine[mfi],scomp),
BL_TO_FORTRAN_N(crse_S_fine[mfi],0),
ratio.getVect(),&ncomp);
} else {
BL_FORT_PROC_CALL(BL_AVGDOWN_NODES,bl_avgdown_nodes)
(tbx.loVect(), tbx.hiVect(),
BL_TO_FORTRAN_N(S_fine[mfi],scomp),
BL_TO_FORTRAN_N(crse_S_fine[mfi],0),
ratio.getVect(),&ncomp);
}
}
S_crse.copy(crse_S_fine,0,scomp,ncomp);
}
}
// *************************************************************************************************************
// Average fine face-based MultiFab onto crse face-based MultiFab.
void average_down_faces (const Vector<const MultiFab*>& fine, const Vector<MultiFab*>& crse,
const IntVect& ratio, int ngcrse)
{
BL_ASSERT(crse.size() == AMREX_SPACEDIM);
BL_ASSERT(fine.size() == AMREX_SPACEDIM);
BL_ASSERT(crse[0]->nComp() == fine[0]->nComp());
int ncomp = crse[0]->nComp();
if (isMFIterSafe(*fine[0], *crse[0]))
{
#ifdef _OPENMP
#pragma omp parallel
#endif
for (int n=0; n<AMREX_SPACEDIM; ++n) {
for (MFIter mfi(*crse[n],true); mfi.isValid(); ++mfi)
{
const Box& tbx = mfi.growntilebox(ngcrse);
BL_FORT_PROC_CALL(BL_AVGDOWN_FACES,bl_avgdown_faces)
(tbx.loVect(),tbx.hiVect(),
BL_TO_FORTRAN((*fine[n])[mfi]),
BL_TO_FORTRAN((*crse[n])[mfi]),
ratio.getVect(),n,ncomp);
}
}
}
else
{
std::array<MultiFab,AMREX_SPACEDIM> ctmp;
Vector<MultiFab*> vctmp(AMREX_SPACEDIM);
for (int idim = 0; idim < AMREX_SPACEDIM; ++idim)
{
BoxArray cba = fine[idim]->boxArray();
cba.coarsen(ratio);
ctmp[idim].define(cba, fine[idim]->DistributionMap(), ncomp, ngcrse, MFInfo(), FArrayBoxFactory());
vctmp[idim] = &ctmp[idim];
}
average_down_faces(fine, vctmp, ratio, ngcrse);
for (int idim = 0; idim < AMREX_SPACEDIM; ++idim)
{
crse[idim]->ParallelCopy(ctmp[idim],0,0,ncomp,ngcrse,ngcrse);
}
}
}
//! Average fine edge-based MultiFab onto crse edge-based MultiFab.
//! This routine assumes that the crse BoxArray is a coarsened version of the fine BoxArray.
void average_down_edges (const Vector<const MultiFab*>& fine, const Vector<MultiFab*>& crse,
const IntVect& ratio, int ngcrse)
{
BL_ASSERT(crse.size() == AMREX_SPACEDIM);
BL_ASSERT(fine.size() == AMREX_SPACEDIM);
BL_ASSERT(crse[0]->nComp() == fine[0]->nComp());
int ncomp = crse[0]->nComp();
#ifdef _OPENMP
#pragma omp parallel
#endif
for (int n=0; n<AMREX_SPACEDIM; ++n) {
for (MFIter mfi(*crse[n],true); mfi.isValid(); ++mfi)
{
const Box& tbx = mfi.growntilebox(ngcrse);
BL_FORT_PROC_CALL(BL_AVGDOWN_EDGES,bl_avgdown_edges)
(tbx.loVect(),tbx.hiVect(),
BL_TO_FORTRAN((*fine[n])[mfi]),
BL_TO_FORTRAN((*crse[n])[mfi]),
ratio.getVect(),n,ncomp);
}
}
}
//! Average fine node-based MultiFab onto crse node-based MultiFab.
//! This routine assumes that the crse BoxArray is a coarsened version of the fine BoxArray.
void average_down_nodal (const MultiFab& fine, MultiFab& crse, const IntVect& ratio, int ngcrse)
{
BL_ASSERT(fine.is_nodal());
BL_ASSERT(crse.is_nodal());
BL_ASSERT(crse.nComp() == fine.nComp());
int ncomp = crse.nComp();
#ifdef _OPENMP
#pragma omp parallel
#endif
for (MFIter mfi(crse,true); mfi.isValid(); ++mfi)
{
const Box& tbx = mfi.growntilebox(ngcrse);
BL_FORT_PROC_CALL(BL_AVGDOWN_NODES,bl_avgdown_nodes)
(tbx.loVect(),tbx.hiVect(),
BL_TO_FORTRAN(fine[mfi]),
BL_TO_FORTRAN(crse[mfi]),
ratio.getVect(),&ncomp);
}
}
// *************************************************************************************************************
void fill_boundary(MultiFab& mf, const Geometry& geom, bool cross)
{
amrex::fill_boundary(mf, 0, mf.nComp(), geom, cross);
}
// *************************************************************************************************************
void fill_boundary(MultiFab& mf, int scomp, int ncomp, const Geometry& geom, bool cross)
{
mf.FillBoundary(scomp,ncomp,geom.periodicity(),cross);
}
void print_state(const MultiFab& mf, const IntVect& cell, const int n)
{
#ifdef _OPENMP
#pragma omp parallel
#endif
for (MFIter mfi(mf); mfi.isValid(); ++mfi)
{
if (mfi.validbox().contains(cell)) {
if (n >= 0) {
amrex::AllPrint().SetPrecision(17) << mf[mfi](cell, n) << std::endl;
} else {
std::ostringstream ss;
ss.precision(17);
const int ncomp = mf.nComp();
for (int i = 0; i < ncomp-1; ++i)
{
ss << mf[mfi](cell,i) << ", ";
}
ss << mf[mfi](cell,ncomp-1);
amrex::AllPrint() << ss.str() << std::endl;
}
}
}
}
void writeFabs (const MultiFab& mf, const std::string& name)
{
writeFabs (mf, 0, mf.nComp(), name);
}
void writeFabs (const MultiFab& mf, int comp, int ncomp, const std::string& name)
{
for (MFIter mfi(mf); mfi.isValid(); ++mfi) {
std::ofstream ofs(name+"-fab-"+std::to_string(mfi.index()));
mf[mfi].writeOn(ofs, comp, ncomp);
}
}
MultiFab ToMultiFab (const iMultiFab& imf)
{
MultiFab mf(imf.boxArray(), imf.DistributionMap(), imf.nComp(), imf.nGrow(),
MFInfo(), FArrayBoxFactory());
const int ncomp = imf.nComp();
#ifdef _OPENMP
#pragma omp parallel
#endif
for (MFIter mfi(mf,true); mfi.isValid(); ++mfi)
{
const Box& tbx = mfi.growntilebox();
amrex_fort_int_to_real(BL_TO_FORTRAN_BOX(tbx), &ncomp,
BL_TO_FORTRAN_ANYD(mf[mfi]),
BL_TO_FORTRAN_ANYD(imf[mfi]));
}
return mf;
}
std::unique_ptr<MultiFab> get_slice_data(int dir, Real coord, const MultiFab& cc, const Geometry& geom, int start_comp, int ncomp, bool interpolate) {
BL_PROFILE("amrex::get_slice_data");
if (interpolate) {
AMREX_ASSERT(cc.nGrow() >= 1);
}
const Real* dx = geom.CellSize();
const Real* plo = geom.ProbLo();
Vector<int> slice_to_full_ba_map;
std::unique_ptr<MultiFab> slice = allocateSlice(dir, cc, ncomp, geom, coord, slice_to_full_ba_map);
int nf = cc.nComp();
#ifdef _OPENMP
#pragma omp parallel
#endif
for (MFIter mfi(*slice, true); mfi.isValid(); ++mfi) {
int slice_gid = mfi.index();
int full_gid = slice_to_full_ba_map[slice_gid];
const Box& tile_box = mfi.tilebox();
if (interpolate)
{
amrex_fill_slice_interp(BL_TO_FORTRAN_BOX(tile_box),
BL_TO_FORTRAN_ANYD(cc[full_gid]),
BL_TO_FORTRAN_ANYD((*slice)[slice_gid]),
&start_comp, &nf, &ncomp, &dir,
&coord, AMREX_ZFILL(plo), AMREX_ZFILL(dx));
}
else
{
amrex_fill_slice(BL_TO_FORTRAN_BOX(tile_box),
BL_TO_FORTRAN_ANYD(cc[full_gid]),
BL_TO_FORTRAN_ANYD((*slice)[slice_gid]),
&start_comp, &nf, &ncomp);
}
}
return slice;
}
iMultiFab makeFineMask (const MultiFab& cmf, const BoxArray& fba, const IntVect& ratio)
{
iMultiFab mask(cmf.boxArray(), cmf.DistributionMap(), 1, 0);
const BoxArray& cfba = amrex::coarsen(fba,ratio);
#ifdef _OPENMP
#pragma omp parallel
#endif
{
std::vector< std::pair<int,Box> > isects;
for (MFIter mfi(mask); mfi.isValid(); ++mfi)
{
IArrayBox& fab = mask[mfi];
const Box& bx = fab.box();
fab.setVal(0);
cfba.intersections(bx, isects);
for (auto const& is : isects)
{
fab.setVal(1, is.second, 0, 1);
}
}
}
return mask;
}
void computeDivergence (MultiFab& divu, const Array<MultiFab const*,AMREX_SPACEDIM>& umac,
const Geometry& geom)
{
const Real* dxinv = geom.InvCellSize();
#ifdef _OPENMP
#pragma omp parallel
#endif
for (MFIter mfi(divu,true); mfi.isValid(); ++mfi)
{
const Box& bx = mfi.tilebox();
amrex_compute_divergence (BL_TO_FORTRAN_BOX(bx),
BL_TO_FORTRAN_ANYD(divu[mfi]),
AMREX_D_DECL(BL_TO_FORTRAN_ANYD((*umac[0])[mfi]),
BL_TO_FORTRAN_ANYD((*umac[1])[mfi]),
BL_TO_FORTRAN_ANYD((*umac[2])[mfi])),
dxinv);
}
}
}
| 35.180124 | 154 | 0.547802 | [
"geometry",
"vector"
] |
106df828dc8cf662cf28a9269403c4fc3c15fe18 | 14,114 | cpp | C++ | src/MainWindow.cpp | frc3512/DriverStationDisplay | c6b5eb263ec1d1701a3d48a915b7b106c982323d | [
"BSD-3-Clause"
] | null | null | null | src/MainWindow.cpp | frc3512/DriverStationDisplay | c6b5eb263ec1d1701a3d48a915b7b106c982323d | [
"BSD-3-Clause"
] | null | null | null | src/MainWindow.cpp | frc3512/DriverStationDisplay | c6b5eb263ec1d1701a3d48a915b7b106c982323d | [
"BSD-3-Clause"
] | 1 | 2017-03-14T02:13:29.000Z | 2017-03-14T02:13:29.000Z | // Copyright (c) 2012-2020 FRC Team 3512. All Rights Reserved.
#include "MainWindow.hpp"
#include <chrono>
#include <cstring>
#include <fstream>
#include <utility>
#include <QHBoxLayout>
#include <QPushButton>
#include <QSpacerItem>
#include <QtWidgets>
#include "MJPEG/MjpegClient.hpp"
#include "MJPEG/VideoStream.hpp"
#include "NetWidgets/ProgressBar.hpp"
#include "NetWidgets/StatusLight.hpp"
#include "NetWidgets/Text.hpp"
#include "Util.hpp"
std::wstring replaceUnicodeChars(std::wstring text) {
size_t uPos = 0;
/* Replace all "\uXXXX" strings with the unicode character corresponding
* to the 32 bit code XXXX
*/
while (uPos < text.length()) {
if (uPos == 0) {
uPos = text.find(L"\\u", uPos);
} else {
uPos = text.find(L"\\u", uPos + 1);
}
if (uPos < text.length() - 5) {
wchar_t num[2];
num[0] = std::stoi(text.substr(uPos + 2, 4), nullptr, 16);
num[1] = '\0';
text = text.replace(uPos, 6, num);
}
}
return text;
}
MainWindow::MainWindow(int width, int height) : m_buffer(0xffff - 28) {
setMinimumSize(width, height);
centralWidget = new QWidget(this);
setCentralWidget(centralWidget);
m_settings = std::make_unique<Settings>("IPSettings.txt");
m_client = new MjpegClient(m_settings->getString("streamHost"),
m_settings->getInt("mjpegPort"),
m_settings->getString("mjpegRequestPath"));
constexpr int32_t videoX = 640;
constexpr int32_t videoY = 480;
m_stream = new VideoStream(
m_client, this, videoX, videoY, &m_streamCallback, [this] {},
[this] { m_button->setText("Stop Stream"); },
[this] { m_button->setText("Start Stream"); });
m_stream->setMaximumSize(videoX, videoY);
m_button = new QPushButton("Start Stream");
connect(m_button, SIGNAL(released()), this, SLOT(toggleButton()));
m_leftWidgetLayout = new QVBoxLayout();
m_centerWidgetLayout = new QVBoxLayout();
m_centerWidgetLayout->addWidget(m_stream, 0,
Qt::AlignHCenter | Qt::AlignTop);
QHBoxLayout* buttonLayout = new QHBoxLayout();
buttonLayout->addWidget(m_button, 0, Qt::AlignTop);
buttonLayout->insertStretch(1);
m_centerWidgetLayout->addLayout(buttonLayout, Qt::AlignHCenter);
auto rightLayout = new QVBoxLayout();
m_rightWidgetLayout = new QVBoxLayout();
m_autoSelect = new QComboBox();
connect(m_autoSelect,
static_cast<void (QComboBox::*)(int)>(&QComboBox::activated),
[this](int index) {
char data[16] = "autonSelect\r\n";
data[13] = index;
m_dataSocket->writeDatagram(data, sizeof(data), m_remoteIP,
m_dataPort);
});
rightLayout->addWidget(m_autoSelect);
rightLayout->addLayout(m_rightWidgetLayout);
QGridLayout* mainLayout = new QGridLayout();
mainLayout->setColumnMinimumWidth(0, (width - videoX / 2) / 3);
mainLayout->setColumnMinimumWidth(1, videoX);
mainLayout->setColumnMinimumWidth(2, (width - videoX / 2) / 3);
mainLayout->addLayout(m_leftWidgetLayout, 0, 0);
mainLayout->setAlignment(m_leftWidgetLayout, Qt::AlignTop);
mainLayout->addLayout(m_centerWidgetLayout, 0, 1);
mainLayout->addLayout(rightLayout, 0, 2);
mainLayout->setAlignment(rightLayout, Qt::AlignTop);
centralWidget->setLayout(mainLayout);
createActions();
createMenus();
setUnifiedTitleAndToolBarOnMac(true);
m_dataSocket = std::make_unique<QUdpSocket>(this);
m_dataSocket->bind(m_settings->getInt("dsDataPort"));
connect(m_dataSocket.get(), SIGNAL(readyRead()), this,
SLOT(handleSocketData()));
m_remoteIP = QHostAddress{
QString::fromUtf8(m_settings->getString("robotIP").c_str())};
m_dataPort = m_settings->getInt("robotDataPort");
m_connectTimer = std::make_unique<QTimer>();
connect(m_connectTimer.get(), &QTimer::timeout, [this] {
if (!m_connectDlgOpen) {
char data[16] = "connect\r\n";
m_dataSocket->writeDatagram(data, sizeof(data), m_remoteIP,
m_dataPort);
}
m_connectTimer->start(2000);
});
m_connectTimer->start(2000);
}
void MainWindow::startMJPEG() { m_client->start(); }
void MainWindow::stopMJPEG() { m_client->stop(); }
void MainWindow::about() {
QMessageBox::about(this, tr("About DriverStationDisplay"),
tr("<br>DriverStationDisplay, Version 2.0<br>"
"Copyright ©2012-2015 FRC Team 3512<br>"
"FRC Team 3512<br>"
"All Rights Reserved"));
}
void MainWindow::toggleButton() {
if (m_client->isStreaming()) {
stopMJPEG();
} else {
startMJPEG();
}
}
void MainWindow::handleSocketData() {
while (m_dataSocket->hasPendingDatagrams()) {
size_t packetPos = 0;
m_buffer.resize(m_dataSocket->pendingDatagramSize());
m_dataSocket->readDatagram(m_buffer.data(), m_buffer.size());
std::string header;
packetToVar(m_buffer, packetPos, header);
/* If this instance has connected to the server before, receiving any
* packet resets the timeout. This check is necessary in case a previous
* instance caused packets to be redirected here.
*/
if (m_connectedBefore) {
m_connectTimer->start(2000);
}
if (header == "display\r\n") {
/* Only allow keep-alive (resetting timer) if we have a valid
* GUI; we need to connect and create the GUI before accepting
* display data
*/
if (m_connectedBefore) {
updateGuiTable(m_buffer, packetPos);
NetWidget::updateElements();
}
} else if (header == "guiCreate\r\n") {
reloadGUI(m_buffer, packetPos);
if (!m_connectedBefore) {
m_connectedBefore = true;
}
} else if (header == "autonList\r\n") {
/* Unpacks the following variables:
*
* Autonomous Modes (contained in rest of packet):
* std::string: autonomous routine name
* <more autonomous routine names>...
*/
std::vector<std::string> autoNames;
std::string autoName;
while (packetPos < m_buffer.size() &&
packetToVar(m_buffer, packetPos, autoName)) {
autoNames.emplace_back(autoName);
}
m_autoSelect->clear();
for (auto& str : autoNames) {
m_autoSelect->addItem(str.c_str());
}
} else if (header == "autonConfirmed\r\n") {
/* If a new autonomous mode was selected from the robot, it
* sends back this packet as confirmation
*/
std::string autoName = "Autonomous mode changed to\n";
std::string tempName;
packetToVar(m_buffer, packetPos, tempName);
autoName += tempName;
int idx = m_autoSelect->findText(QString::fromStdString(tempName));
if (idx != -1) {
m_autoSelect->setCurrentIndex(idx);
}
QMessageBox* connectDlg = new QMessageBox(this);
connectDlg->setAttribute(Qt::WA_DeleteOnClose);
connectDlg->setWindowTitle("Autonomous Change");
connectDlg->setText(autoName.c_str());
connectDlg->open();
}
}
}
void MainWindow::createActions() {
m_startMJPEGAct = new QAction(tr("&Start"), this);
connect(m_startMJPEGAct, SIGNAL(triggered()), this, SLOT(startMJPEG()));
m_stopMJPEGAct = new QAction(tr("&Stop"), this);
connect(m_stopMJPEGAct, SIGNAL(triggered()), this, SLOT(stopMJPEG()));
m_exitAct = new QAction(tr("&Exit"), this);
connect(m_exitAct, SIGNAL(triggered()), this, SLOT(close()));
m_aboutAct = new QAction(tr("&About DriverStationDisplay"), this);
connect(m_aboutAct, SIGNAL(triggered()), this, SLOT(about()));
}
void MainWindow::createMenus() {
m_optionsMenu = menuBar()->addMenu(tr("&Options"));
m_optionsMenu->addAction(m_startMJPEGAct);
m_optionsMenu->addAction(m_stopMJPEGAct);
m_optionsMenu->addSeparator();
m_optionsMenu->addAction(m_exitAct);
m_helpMenu = menuBar()->addMenu(tr("&Help"));
m_helpMenu->addAction(m_aboutAct);
}
void MainWindow::clearGUI() {
clearLayout(m_leftWidgetLayout);
clearLayout(m_rightWidgetLayout);
}
void MainWindow::clearLayout(QLayout* layout) {
QLayoutItem* item;
while ((item = layout->takeAt(0)) != nullptr) {
delete item->widget();
delete item;
}
}
void MainWindow::reloadGUI(std::vector<char>& data, size_t& pos) {
// Remove old elements before creating new ones
clearGUI();
resetAllTemps();
// Read the file into a string
std::string tmpbuf;
packetToVar(data, pos, tmpbuf);
std::vector<std::string> lines = split(tmpbuf, "\n");
for (auto& str : lines) {
parseLine(str);
}
}
void MainWindow::reloadGUI(const std::string& fileName) {
std::ifstream guiSettings(fileName);
// Remove old elements before creating new ones
clearGUI();
if (guiSettings.is_open()) {
resetAllTemps();
while (!guiSettings.eof()) {
std::string temp;
std::getline(guiSettings, temp);
parseLine(std::move(temp));
}
}
}
void MainWindow::updateGuiTable(std::vector<char>& data, size_t& pos) {
NetWidget::updateValues(data, pos);
}
std::vector<std::string> MainWindow::split(const std::string& s,
const std::string& delim) {
std::vector<std::string> elems;
size_t pos = 0;
size_t nextPos = 0;
while (nextPos != std::string::npos) {
nextPos = s.find_first_of(delim, pos);
elems.emplace_back(s.substr(pos, nextPos - pos));
pos = nextPos + delim.length();
}
return elems;
}
void MainWindow::parseLine(std::string line) {
m_tempVarIds.clear();
/* If the line doesn't have any characters in it, don't bother
* parsing it
*/
if (line.length() == 0) {
return;
}
m_start = 0;
// Get five arguments
for (size_t i = 0; i < 5;) {
// First three arguments are delimited by a space
if (i == 0) {
m_delimiter = " ";
} else if (i == 1) {
m_delimiter = ", ";
} else if (i == 3) {
m_delimiter = "\"";
}
if (m_start == std::string::npos) {
return;
}
// If not at the beginning of the string, advance to the next delimiter
if (i > 0) {
m_start = line.find_first_of(m_delimiter + " ", m_start);
}
if (m_start == std::string::npos) {
return;
}
// Find next argument
m_start = line.find_first_not_of(m_delimiter + " ", m_start);
if (m_start == std::string::npos) {
return;
}
// Find end of next argument
m_end = line.find_first_of(m_delimiter, m_start);
// Get current argument
if (i == 0) {
// lastType vars are updated when the column is found
m_currentType = line.substr(m_start, m_end - m_start);
} else if (i == 1) {
/* Add the next variable ID to a storage vector for adding to the
* element later
*/
m_tempVarIds.push_back(line.substr(m_start, m_end - m_start));
} else if (i == 2) {
m_column = line.substr(m_start, m_end - m_start);
} else if (i == 3) {
std::string tempStr = line.substr(m_start, m_end - m_start);
// Convert std::string to std::wstring
m_startText.assign(tempStr.begin(), tempStr.end());
} else if (i == 4) {
std::string tempStr = line.substr(m_start, m_end - m_start);
// Convert std::string to std::wstring
m_updateText.assign(tempStr.begin(), tempStr.end());
}
// Move start past current argument
m_start = m_end;
// If there are more IDs to add, skip incrementing the field counter
if (!(i == 1 && line[m_start] == ',')) {
i++;
}
}
/* Replace all unicode escape characters in the string with their unicode
* equivalents
*/
m_startText = replaceUnicodeChars(m_startText);
m_updateText = replaceUnicodeChars(m_updateText);
NetWidget* netPtr = nullptr;
QWidget* qPtr = nullptr;
// Create element
if (m_currentType == "TEXT") {
auto temp = new Text(true);
temp->setString(m_startText);
netPtr = temp;
qPtr = temp;
} else if (m_currentType == "STATUSLIGHT") {
auto temp = new StatusLight(true);
temp->setString(m_startText);
netPtr = temp;
qPtr = temp;
} else if (m_currentType == "PBAR") {
auto temp = new ProgressBar(true);
temp->setString(m_startText);
netPtr = temp;
qPtr = temp;
}
/* Set update text and add the update variables to track if an element was
* created
*/
if (netPtr != nullptr) {
netPtr->setUpdateText(m_updateText);
netPtr->updateKeys(m_tempVarIds);
}
// Add widget to correct layout if it was created
if (qPtr != nullptr) {
if (m_column == "left") {
m_leftWidgetLayout->addWidget(qPtr);
} else if (m_column == "right") {
m_rightWidgetLayout->addWidget(qPtr);
}
}
}
void MainWindow::resetAllTemps() {
m_substring.clear();
m_start = 0;
m_delimiter.clear();
m_currentType.clear();
m_column.clear();
m_startText.clear();
m_updateText.clear();
m_tempVarIds.clear();
}
| 30.352688 | 80 | 0.585872 | [
"vector"
] |
107366c20f2446c3b2ef20faa23938c1925b6564 | 2,103 | hpp | C++ | modules/core/linalg/include/nt2/toolbox/linalg/functions/leslie.hpp | timblechmann/nt2 | 6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce | [
"BSL-1.0"
] | 2 | 2016-09-14T00:23:53.000Z | 2018-01-14T12:51:18.000Z | modules/core/linalg/include/nt2/toolbox/linalg/functions/leslie.hpp | timblechmann/nt2 | 6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce | [
"BSL-1.0"
] | null | null | null | modules/core/linalg/include/nt2/toolbox/linalg/functions/leslie.hpp | timblechmann/nt2 | 6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce | [
"BSL-1.0"
] | null | null | null | /*******************************************************************************
* Copyright 2003-2012 LASMEA UMR 6602 CNRS/U.B.P
* Copyright 2011-2012 LRI UMR 8623 CNRS/Univ Paris Sud XI
*
* Distributed under the Boost Software License, Version 1.0.
* See accompanying file LICENSE.txt or copy at
* http://www.boost.org/LICENSE_1_0.txt
******************************************************************************/
#ifndef NT2_TOOLBOX_LINALG_FUNCTIONS_LESLIE_HPP_INCLUDED
#define NT2_TOOLBOX_LINALG_FUNCTIONS_LESLIE_HPP_INCLUDED
#include <nt2/include/functor.hpp>
/*!
* \ingroup algebra
* \defgroup algebra_leslie leslie
*
* leslie(a,b) is the n-by-n matrix from the Leslie
* population model with average birth numbers a(_(1, n)) and
* survival rates b(_(1, n-1)). it is zero, apart from on the first row
* (which contains the a(i)) and the first subdiagonal (which contains
* the b(i)). for a valid model, the a(i) are nonnegative and the
* b(i) are positive and bounded by 1.
*
* leslie(n) generates the leslie matrix with a = ones(n,1),
* b = ones(n-1,1).
* References:
* [1] M. R. Cullen, Linear Models in Biology, Ellis Horwood,
* Chichester, UK, 1985.
* [2] H. Anton and C. Rorres, Elementary Linear Algebra: Applications
* Version, eighth edition, Wiley, New York, 2000, Sec. 11.18.
*
*
* \par Header file
*
* \code
* #include <nt2/include/functions/leslie.hpp>
* \endcode
*
**/
//==============================================================================
// leslie actual class forward declaration
//==============================================================================
namespace nt2 { namespace tag
{
/*!
* \brief Define the tag leslie_ of functor leslie
* in namespace nt2::tag for toolbox algebra
**/
struct leslie_ : boost::dispatch::tag::formal_
{
typedef boost::dispatch::tag::formal_ parent;
};
}
BOOST_DISPATCH_FUNCTION_IMPLEMENTATION(tag::leslie_, leslie, 2)
}
#endif
| 33.380952 | 80 | 0.552068 | [
"model"
] |
10763f8d59b7d032bc7fbfb8ab4488b492f30c93 | 5,694 | cpp | C++ | third_party/libigl/include/igl/extract_manifold_patches.cpp | chefmramos85/monster-mash | 239a41f6f178ca83c4be638331e32f23606b0381 | [
"Apache-2.0"
] | 1,125 | 2021-02-01T09:51:56.000Z | 2022-03-31T01:50:40.000Z | third_party/libigl/include/igl/extract_manifold_patches.cpp | ryan-cranfill/monster-mash | c1b906d996885f8a4011bdf7558e62e968e1e914 | [
"Apache-2.0"
] | 19 | 2021-02-01T12:36:30.000Z | 2022-03-19T14:02:50.000Z | third_party/libigl/include/igl/extract_manifold_patches.cpp | ryan-cranfill/monster-mash | c1b906d996885f8a4011bdf7558e62e968e1e914 | [
"Apache-2.0"
] | 148 | 2021-02-13T10:54:31.000Z | 2022-03-28T11:55:20.000Z | // This file is part of libigl, a simple c++ geometry processing library.
//
// Copyright (C) 2016 Alec Jacobson <alecjacobson@gmail.com>
//
// 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/.
#include "extract_manifold_patches.h"
#include "unique_edge_map.h"
#include <cassert>
#include <limits>
#include <queue>
template<
typename DerivedF,
typename DerivedEMAP,
typename uE2EType,
typename DerivedP>
IGL_INLINE size_t igl::extract_manifold_patches(
const Eigen::MatrixBase<DerivedF>& F,
const Eigen::MatrixBase<DerivedEMAP>& EMAP,
const std::vector<std::vector<uE2EType> >& uE2E,
Eigen::PlainObjectBase<DerivedP>& P)
{
assert(F.cols() == 3);
const size_t num_faces = F.rows();
auto edge_index_to_face_index = [&](size_t ei) { return ei % num_faces; };
auto face_and_corner_index_to_edge_index = [&](size_t fi, size_t ci) {
return ci*num_faces + fi;
};
auto is_manifold_edge = [&](size_t fi, size_t ci) -> bool {
const size_t ei = face_and_corner_index_to_edge_index(fi, ci);
return uE2E[EMAP(ei, 0)].size() == 2;
};
auto get_adj_face_index = [&](size_t fi, size_t ci) -> size_t {
const size_t ei = face_and_corner_index_to_edge_index(fi, ci);
const auto& adj_faces = uE2E[EMAP(ei, 0)];
assert(adj_faces.size() == 2);
if (adj_faces[0] == ei) {
return edge_index_to_face_index(adj_faces[1]);
} else {
assert(adj_faces[1] == ei);
return edge_index_to_face_index(adj_faces[0]);
}
};
typedef typename DerivedP::Scalar Scalar;
const Scalar INVALID = std::numeric_limits<Scalar>::max();
P.resize(num_faces,1);
P.setConstant(INVALID);
size_t num_patches = 0;
for (size_t i=0; i<num_faces; i++) {
if (P(i,0) != INVALID) continue;
std::queue<size_t> Q;
Q.push(i);
P(i,0) = num_patches;
while (!Q.empty()) {
const size_t fid = Q.front();
Q.pop();
for (size_t j=0; j<3; j++) {
if (is_manifold_edge(fid, j)) {
const size_t adj_fid = get_adj_face_index(fid, j);
if (P(adj_fid,0) == INVALID) {
Q.push(adj_fid);
P(adj_fid,0) = num_patches;
}
}
}
}
num_patches++;
}
assert((P.array() != INVALID).all());
return num_patches;
}
template <
typename DerivedF,
typename DerivedP>
IGL_INLINE size_t igl::extract_manifold_patches(
const Eigen::MatrixBase<DerivedF> &F,
Eigen::PlainObjectBase<DerivedP> &P)
{
Eigen::MatrixXi E, uE;
Eigen::VectorXi EMAP;
std::vector<std::vector<size_t> > uE2E;
igl::unique_edge_map(F, E, uE, EMAP, uE2E);
return igl::extract_manifold_patches(F, EMAP, uE2E, P);
}
#ifdef IGL_STATIC_LIBRARY
// Explicit template instantiation
// generated by autoexplicit.sh
template size_t igl::extract_manifold_patches<Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, 1, 0, -1, 1> >(Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&);
template size_t igl::extract_manifold_patches<Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, 1, 0, -1, 1>, unsigned long, Eigen::Matrix<int, -1, 1, 0, -1, 1> >(Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> > const&, std::vector<std::vector<unsigned long, std::allocator<unsigned long> >, std::allocator<std::vector<unsigned long, std::allocator<unsigned long> > > > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&);
template size_t igl::extract_manifold_patches<Eigen::Matrix<int, -1, 3, 1, -1, 3>, Eigen::Matrix<int, -1, 1, 0, -1, 1>, unsigned long, Eigen::Matrix<int, -1, 1, 0, -1, 1> >(Eigen::MatrixBase<Eigen::Matrix<int, -1, 3, 1, -1, 3> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> > const&, std::vector<std::vector<unsigned long, std::allocator<unsigned long> >, std::allocator<std::vector<unsigned long, std::allocator<unsigned long> > > > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&);
#ifdef WIN32
template unsigned __int64 igl::extract_manifold_patches<class Eigen::Matrix<int, -1, -1, 0, -1, -1>, class Eigen::Matrix<int, -1, 1, 0, -1, 1>, unsigned __int64, class Eigen::Matrix<int, -1, 1, 0, -1, 1>>(class Eigen::MatrixBase<class Eigen::Matrix<int, -1, -1, 0, -1, -1>> const &, class Eigen::MatrixBase<class Eigen::Matrix<int, -1, 1, 0, -1, 1>> const &, class std::vector<class std::vector<unsigned __int64, class std::allocator<unsigned __int64>>, class std::allocator<class std::vector<unsigned __int64, class std::allocator<unsigned __int64>>>> const &, class Eigen::PlainObjectBase<class Eigen::Matrix<int, -1, 1, 0, -1, 1>> &);
template unsigned __int64 igl::extract_manifold_patches<class Eigen::Matrix<int, -1, 3, 1, -1, 3>, class Eigen::Matrix<int, -1, 1, 0, -1, 1>, unsigned __int64, class Eigen::Matrix<int, -1, 1, 0, -1, 1>>(class Eigen::MatrixBase<class Eigen::Matrix<int, -1, 3, 1, -1, 3>> const &, class Eigen::MatrixBase<class Eigen::Matrix<int, -1, 1, 0, -1, 1>> const &, class std::vector<class std::vector<unsigned __int64, class std::allocator<unsigned __int64>>, class std::allocator<class std::vector<unsigned __int64, class std::allocator<unsigned __int64>>>> const &, class Eigen::PlainObjectBase<class Eigen::Matrix<int, -1, 1, 0, -1, 1>> &);
#endif
#endif
| 54.75 | 637 | 0.640148 | [
"geometry",
"vector"
] |
107706f6795a655d74fbbd7c9b0bb16e597ce64a | 21,379 | cpp | C++ | Tests/DiligentCoreAPITest/src/D3D12/DrawCommandReferenceD3D12.cpp | luzpaz/DiligentCore | 3eaf45aa4785bf566b307613c56b41d67799c5e7 | [
"Apache-2.0"
] | null | null | null | Tests/DiligentCoreAPITest/src/D3D12/DrawCommandReferenceD3D12.cpp | luzpaz/DiligentCore | 3eaf45aa4785bf566b307613c56b41d67799c5e7 | [
"Apache-2.0"
] | null | null | null | Tests/DiligentCoreAPITest/src/D3D12/DrawCommandReferenceD3D12.cpp | luzpaz/DiligentCore | 3eaf45aa4785bf566b307613c56b41d67799c5e7 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2019-2021 Diligent Graphics LLC
* Copyright 2015-2019 Egor Yusov
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* In no event and under no legal theory, whether in tort (including negligence),
* contract, or otherwise, unless required by applicable law (such as deliberate
* and grossly negligent acts) or agreed to in writing, shall any Contributor be
* liable for any damages, including any direct, indirect, special, incidental,
* or consequential damages of any character arising as a result of this License or
* out of the use or inability to use the software (including but not limited to damages
* for loss of goodwill, work stoppage, computer failure or malfunction, or any and
* all other commercial damages or losses), even if such Contributor has been advised
* of the possibility of such damages.
*/
#include "D3D12/TestingEnvironmentD3D12.hpp"
#include "D3D12/TestingSwapChainD3D12.hpp"
#include "../include/DXGITypeConversions.hpp"
#include "../include/d3dx12_win.h"
#include "RenderDeviceD3D12.h"
#include "DeviceContextD3D12.h"
#include "InlineShaders/DrawCommandTestHLSL.h"
namespace Diligent
{
namespace Testing
{
namespace
{
class TriangleRenderer
{
public:
TriangleRenderer(ID3D12Device* pd3d12Device,
const std::string& PSSource,
DXGI_FORMAT RTVFmt,
UINT SampleCount,
const D3D12_ROOT_SIGNATURE_DESC& RootSignatureDesc)
{
CComPtr<ID3DBlob> pVSByteCode, pPSByteCode;
auto hr = CompileD3DShader(HLSL::DrawTest_ProceduralTriangleVS, "main", nullptr, "vs_5_0", &pVSByteCode);
VERIFY_EXPR(SUCCEEDED(hr));
hr = CompileD3DShader(PSSource, "main", nullptr, "ps_5_0", &pPSByteCode);
VERIFY_EXPR(SUCCEEDED(hr));
CComPtr<ID3DBlob> signature;
D3D12SerializeRootSignature(&RootSignatureDesc, D3D_ROOT_SIGNATURE_VERSION_1, &signature, nullptr);
pd3d12Device->CreateRootSignature(0, signature->GetBufferPointer(), signature->GetBufferSize(), __uuidof(m_pd3d12RootSignature), reinterpret_cast<void**>(static_cast<ID3D12RootSignature**>(&m_pd3d12RootSignature)));
D3D12_GRAPHICS_PIPELINE_STATE_DESC PSODesc = {};
PSODesc.pRootSignature = m_pd3d12RootSignature;
PSODesc.VS.pShaderBytecode = pVSByteCode->GetBufferPointer();
PSODesc.VS.BytecodeLength = pVSByteCode->GetBufferSize();
PSODesc.PS.pShaderBytecode = pPSByteCode->GetBufferPointer();
PSODesc.PS.BytecodeLength = pPSByteCode->GetBufferSize();
PSODesc.BlendState = CD3DX12_BLEND_DESC{D3D12_DEFAULT};
PSODesc.RasterizerState = CD3DX12_RASTERIZER_DESC{D3D12_DEFAULT};
PSODesc.DepthStencilState = CD3DX12_DEPTH_STENCIL_DESC{D3D12_DEFAULT};
PSODesc.RasterizerState.CullMode = D3D12_CULL_MODE_NONE;
PSODesc.DepthStencilState.DepthEnable = FALSE;
PSODesc.DepthStencilState.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ZERO;
PSODesc.SampleMask = 0xFFFFFFFF;
PSODesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
PSODesc.NumRenderTargets = 1;
PSODesc.RTVFormats[0] = RTVFmt;
PSODesc.SampleDesc.Count = SampleCount;
PSODesc.SampleDesc.Quality = 0;
PSODesc.NodeMask = 0;
PSODesc.Flags = D3D12_PIPELINE_STATE_FLAG_NONE;
hr = pd3d12Device->CreateGraphicsPipelineState(&PSODesc, __uuidof(m_pd3d12PSO), reinterpret_cast<void**>(static_cast<ID3D12PipelineState**>(&m_pd3d12PSO)));
VERIFY_EXPR(SUCCEEDED(hr));
}
void Draw(ID3D12GraphicsCommandList* pCmdList, Uint32 ViewportWidth, Uint32 ViewportHeight, D3D12_GPU_DESCRIPTOR_HANDLE DescriptorTable = D3D12_GPU_DESCRIPTOR_HANDLE{})
{
D3D12_VIEWPORT d3d12VP = {};
d3d12VP.Width = static_cast<float>(ViewportWidth);
d3d12VP.Height = static_cast<float>(ViewportHeight);
d3d12VP.MaxDepth = 1;
pCmdList->RSSetViewports(1, &d3d12VP);
D3D12_RECT Rect = {0, 0, static_cast<LONG>(ViewportWidth), static_cast<LONG>(ViewportHeight)};
pCmdList->RSSetScissorRects(1, &Rect);
pCmdList->SetPipelineState(m_pd3d12PSO);
pCmdList->SetGraphicsRootSignature(m_pd3d12RootSignature);
if (DescriptorTable.ptr != 0)
pCmdList->SetGraphicsRootDescriptorTable(0, DescriptorTable);
pCmdList->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
pCmdList->DrawInstanced(6, 1, 0, 0);
}
private:
CComPtr<ID3D12RootSignature> m_pd3d12RootSignature;
CComPtr<ID3D12PipelineState> m_pd3d12PSO;
};
} // namespace
void RenderDrawCommandReferenceD3D12(ISwapChain* pSwapChain, const float* pClearColor)
{
auto* pEnv = TestingEnvironmentD3D12::GetInstance();
auto* pContext = pEnv->GetDeviceContext();
auto* pd3d12Device = pEnv->GetD3D12Device();
auto* pTestingSwapChainD3D12 = ValidatedCast<TestingSwapChainD3D12>(pSwapChain);
const auto& SCDesc = pSwapChain->GetDesc();
D3D12_ROOT_SIGNATURE_DESC RootSignatureDesc = {};
RootSignatureDesc.Flags = D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT;
TriangleRenderer TriRenderer{pd3d12Device, HLSL::DrawTest_PS, TexFormatToDXGI_Format(SCDesc.ColorBufferFormat), 1, RootSignatureDesc};
auto pCmdList = pEnv->CreateGraphicsCommandList();
pTestingSwapChainD3D12->TransitionRenderTarget(pCmdList, D3D12_RESOURCE_STATE_RENDER_TARGET);
auto RTVDescriptorHandle = pTestingSwapChainD3D12->GetRTVDescriptorHandle();
pCmdList->OMSetRenderTargets(1, &RTVDescriptorHandle, FALSE, nullptr);
float Zero[] = {0, 0, 0, 0};
pCmdList->ClearRenderTargetView(RTVDescriptorHandle, pClearColor != nullptr ? pClearColor : Zero, 0, nullptr);
TriRenderer.Draw(pCmdList, SCDesc.Width, SCDesc.Height);
pCmdList->Close();
ID3D12CommandList* pCmdLits[] = {pCmdList};
RefCntAutoPtr<IDeviceContextD3D12> pContextD3D12{pContext, IID_DeviceContextD3D12};
auto* pQeueD3D12 = pContextD3D12->LockCommandQueue();
auto* pd3d12Queue = pQeueD3D12->GetD3D12CommandQueue();
pd3d12Queue->ExecuteCommandLists(_countof(pCmdLits), pCmdLits);
pEnv->IdleCommandQueue(pd3d12Queue);
pContextD3D12->UnlockCommandQueue();
}
void RenderPassMSResolveReferenceD3D12(ISwapChain* pSwapChain, const float* pClearColor)
{
auto* pEnv = TestingEnvironmentD3D12::GetInstance();
auto* pContext = pEnv->GetDeviceContext();
auto* pd3d12Device = pEnv->GetD3D12Device();
auto* pTestingSwapChainD3D12 = ValidatedCast<TestingSwapChainD3D12>(pSwapChain);
const auto& SCDesc = pSwapChain->GetDesc();
D3D12_ROOT_SIGNATURE_DESC RootSignatureDesc = {};
RootSignatureDesc.Flags = D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT;
TriangleRenderer TriRenderer{pd3d12Device, HLSL::DrawTest_PS, TexFormatToDXGI_Format(SCDesc.ColorBufferFormat), 4, RootSignatureDesc};
// Create multisample texture
D3D12_HEAP_PROPERTIES HeapProps = {};
HeapProps.Type = D3D12_HEAP_TYPE_DEFAULT;
HeapProps.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
HeapProps.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
HeapProps.CreationNodeMask = 1;
HeapProps.VisibleNodeMask = 1;
D3D12_RESOURCE_DESC TexDesc = {};
TexDesc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
TexDesc.Alignment = 0;
TexDesc.Width = SCDesc.Width;
TexDesc.Height = SCDesc.Height;
TexDesc.DepthOrArraySize = 1;
TexDesc.MipLevels = 1;
TexDesc.Format = TexFormatToDXGI_Format(SCDesc.ColorBufferFormat);
TexDesc.SampleDesc.Count = 4;
TexDesc.SampleDesc.Quality = 0;
TexDesc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;
TexDesc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
float Zero[4] = {};
if (pClearColor == nullptr)
pClearColor = Zero;
D3D12_CLEAR_VALUE ClearColorValue = {};
ClearColorValue.Format = TexDesc.Format;
for (Uint32 i = 0; i < 4; ++i)
ClearColorValue.Color[i] = pClearColor[i];
RefCntAutoPtr<ID3D12Resource> pd3d12MSTex;
auto hr = pd3d12Device->CreateCommittedResource(&HeapProps, D3D12_HEAP_FLAG_NONE, &TexDesc, D3D12_RESOURCE_STATE_RENDER_TARGET, &ClearColorValue,
__uuidof(pd3d12MSTex),
reinterpret_cast<void**>(static_cast<ID3D12Resource**>(&pd3d12MSTex)));
VERIFY(SUCCEEDED(hr), "Failed to create D3D12 MS render target texture");
// Create RTV descriptor heap
CComPtr<ID3D12DescriptorHeap> pd3d12RTVDescriptorHeap;
D3D12_DESCRIPTOR_HEAP_DESC DescriptorHeapDesc = {};
DescriptorHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV;
DescriptorHeapDesc.NumDescriptors = 1;
DescriptorHeapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE;
DescriptorHeapDesc.NodeMask = 0;
hr = pd3d12Device->CreateDescriptorHeap(&DescriptorHeapDesc,
__uuidof(pd3d12RTVDescriptorHeap),
reinterpret_cast<void**>(static_cast<ID3D12DescriptorHeap**>(&pd3d12RTVDescriptorHeap)));
// Init RTV descriptor handle
VERIFY(SUCCEEDED(hr), "Failed to create D3D12 RTV descriptor heap");
auto RTVDescriptorHandle = pd3d12RTVDescriptorHeap->GetCPUDescriptorHandleForHeapStart();
pd3d12Device->CreateRenderTargetView(pd3d12MSTex, nullptr, RTVDescriptorHandle);
auto pCmdList = pEnv->CreateGraphicsCommandList();
pTestingSwapChainD3D12->TransitionRenderTarget(pCmdList, D3D12_RESOURCE_STATE_RESOLVE_DEST);
// Prepare render pass description
D3D12_RENDER_PASS_RENDER_TARGET_DESC RenderPassRT = {};
RenderPassRT.cpuDescriptor = RTVDescriptorHandle;
RenderPassRT.BeginningAccess.Type = D3D12_RENDER_PASS_BEGINNING_ACCESS_TYPE_CLEAR;
RenderPassRT.BeginningAccess.Clear.ClearValue.Format = TexDesc.Format;
for (Uint32 i = 0; i < 4; ++i)
RenderPassRT.BeginningAccess.Clear.ClearValue.Color[i] = pClearColor[i];
RenderPassRT.EndingAccess.Type = D3D12_RENDER_PASS_ENDING_ACCESS_TYPE_RESOLVE;
auto& ResolveParams = RenderPassRT.EndingAccess.Resolve;
ResolveParams.pSrcResource = pd3d12MSTex;
ResolveParams.pDstResource = pTestingSwapChainD3D12->GetD3D12RenderTarget();
ResolveParams.SubresourceCount = 1;
D3D12_RENDER_PASS_ENDING_ACCESS_RESOLVE_SUBRESOURCE_PARAMETERS SubresParams[1];
SubresParams[0].SrcSubresource = 0;
SubresParams[0].DstSubresource = 0;
SubresParams[0].DstX = 0;
SubresParams[0].DstY = 0;
SubresParams[0].SrcRect.left = 0;
SubresParams[0].SrcRect.top = 0;
SubresParams[0].SrcRect.right = static_cast<LONG>(TexDesc.Width);
SubresParams[0].SrcRect.bottom = static_cast<LONG>(TexDesc.Height);
ResolveParams.pSubresourceParameters = SubresParams;
ResolveParams.Format = TexDesc.Format;
ResolveParams.ResolveMode = D3D12_RESOLVE_MODE_AVERAGE;
ResolveParams.PreserveResolveSource = FALSE;
static_cast<ID3D12GraphicsCommandList4*>(pCmdList.p)->BeginRenderPass(1, &RenderPassRT, nullptr, D3D12_RENDER_PASS_FLAG_NONE);
TriRenderer.Draw(pCmdList, SCDesc.Width, SCDesc.Height);
static_cast<ID3D12GraphicsCommandList4*>(pCmdList.p)->EndRenderPass();
pCmdList->Close();
ID3D12CommandList* pCmdLits[] = {pCmdList};
RefCntAutoPtr<IDeviceContextD3D12> pContextD3D12{pContext, IID_DeviceContextD3D12};
auto* pQeueD3D12 = pContextD3D12->LockCommandQueue();
auto* pd3d12Queue = pQeueD3D12->GetD3D12CommandQueue();
pd3d12Queue->ExecuteCommandLists(_countof(pCmdLits), pCmdLits);
pEnv->IdleCommandQueue(pd3d12Queue);
pContextD3D12->UnlockCommandQueue();
}
void RenderPassInputAttachmentReferenceD3D12(ISwapChain* pSwapChain, const float* pClearColor)
{
auto* pEnv = TestingEnvironmentD3D12::GetInstance();
auto* pContext = pEnv->GetDeviceContext();
auto* pd3d12Device = pEnv->GetD3D12Device();
auto* pTestingSwapChainD3D12 = ValidatedCast<TestingSwapChainD3D12>(pSwapChain);
const auto& SCDesc = pSwapChain->GetDesc();
D3D12_ROOT_SIGNATURE_DESC RootSignatureDesc = {};
RootSignatureDesc.Flags = D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT;
TriangleRenderer TriRenderer{pd3d12Device, HLSL::DrawTest_PS, TexFormatToDXGI_Format(SCDesc.ColorBufferFormat), 1, RootSignatureDesc};
// Prepare root signature desc
D3D12_ROOT_PARAMETER RootParams[1] = {};
RootParams[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
D3D12_DESCRIPTOR_RANGE DescriptorRange[1] = {};
DescriptorRange[0].RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV;
DescriptorRange[0].NumDescriptors = 1;
DescriptorRange[0].BaseShaderRegister = 0;
DescriptorRange[0].RegisterSpace = 0;
DescriptorRange[0].OffsetInDescriptorsFromTableStart = 0;
RootParams[0].DescriptorTable.NumDescriptorRanges = _countof(DescriptorRange);
RootParams[0].DescriptorTable.pDescriptorRanges = DescriptorRange;
RootParams[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;
RootSignatureDesc.NumParameters = _countof(RootParams);
RootSignatureDesc.pParameters = RootParams;
TriangleRenderer TriRendererInptAtt{pd3d12Device, HLSL::InputAttachmentTest_PS, TexFormatToDXGI_Format(SCDesc.ColorBufferFormat), 1, RootSignatureDesc};
// Create input attachment texture
D3D12_HEAP_PROPERTIES HeapProps = {};
HeapProps.Type = D3D12_HEAP_TYPE_DEFAULT;
HeapProps.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
HeapProps.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
HeapProps.CreationNodeMask = 1;
HeapProps.VisibleNodeMask = 1;
D3D12_RESOURCE_DESC TexDesc = {};
TexDesc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
TexDesc.Alignment = 0;
TexDesc.Width = SCDesc.Width;
TexDesc.Height = SCDesc.Height;
TexDesc.DepthOrArraySize = 1;
TexDesc.MipLevels = 1;
TexDesc.Format = TexFormatToDXGI_Format(SCDesc.ColorBufferFormat);
TexDesc.SampleDesc.Count = 1;
TexDesc.SampleDesc.Quality = 0;
TexDesc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;
TexDesc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
float Zero[4] = {};
if (pClearColor == nullptr)
pClearColor = Zero;
D3D12_CLEAR_VALUE ClearColorValue = {};
ClearColorValue.Format = TexDesc.Format;
for (Uint32 i = 0; i < 4; ++i)
ClearColorValue.Color[i] = 0;
RefCntAutoPtr<ID3D12Resource> pd3d12Tex;
auto hr = pd3d12Device->CreateCommittedResource(&HeapProps, D3D12_HEAP_FLAG_NONE, &TexDesc, D3D12_RESOURCE_STATE_RENDER_TARGET, &ClearColorValue,
__uuidof(pd3d12Tex),
reinterpret_cast<void**>(static_cast<ID3D12Resource**>(&pd3d12Tex)));
VERIFY(SUCCEEDED(hr), "Failed to create D3D12 MS render target texture");
// Create RTV descriptor heap
CComPtr<ID3D12DescriptorHeap> pd3d12RTVDescriptorHeap;
{
D3D12_DESCRIPTOR_HEAP_DESC DescriptorHeapDesc = {};
DescriptorHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV;
DescriptorHeapDesc.NumDescriptors = 1;
DescriptorHeapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE;
DescriptorHeapDesc.NodeMask = 0;
hr = pd3d12Device->CreateDescriptorHeap(&DescriptorHeapDesc,
__uuidof(pd3d12RTVDescriptorHeap),
reinterpret_cast<void**>(static_cast<ID3D12DescriptorHeap**>(&pd3d12RTVDescriptorHeap)));
}
// Init RTV descriptor handle
VERIFY(SUCCEEDED(hr), "Failed to create D3D12 RTV descriptor heap");
auto RTVDescriptorHandle = pd3d12RTVDescriptorHeap->GetCPUDescriptorHandleForHeapStart();
pd3d12Device->CreateRenderTargetView(pd3d12Tex, nullptr, RTVDescriptorHandle);
// Create SRV descriptor head
CComPtr<ID3D12DescriptorHeap> pd3d12SRVDescriptorHeap;
{
D3D12_DESCRIPTOR_HEAP_DESC DescriptorHeapDesc = {};
DescriptorHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
DescriptorHeapDesc.NumDescriptors = 1;
DescriptorHeapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE;
DescriptorHeapDesc.NodeMask = 0;
hr = pd3d12Device->CreateDescriptorHeap(&DescriptorHeapDesc,
__uuidof(pd3d12SRVDescriptorHeap),
reinterpret_cast<void**>(static_cast<ID3D12DescriptorHeap**>(&pd3d12SRVDescriptorHeap)));
}
auto SrvCpuDescriptorHandle = pd3d12SRVDescriptorHeap->GetCPUDescriptorHandleForHeapStart();
auto SrvGpuDescriptorHandle = pd3d12SRVDescriptorHeap->GetGPUDescriptorHandleForHeapStart();
pd3d12Device->CreateShaderResourceView(pd3d12Tex, nullptr, SrvCpuDescriptorHandle);
auto pCmdList = pEnv->CreateGraphicsCommandList();
auto* pCmdList4 = static_cast<ID3D12GraphicsCommandList4*>(pCmdList.p);
{
// Start the first subpass
D3D12_RENDER_PASS_RENDER_TARGET_DESC RenderPassRT = {};
RenderPassRT.cpuDescriptor = RTVDescriptorHandle;
RenderPassRT.BeginningAccess.Type = D3D12_RENDER_PASS_BEGINNING_ACCESS_TYPE_CLEAR;
RenderPassRT.BeginningAccess.Clear.ClearValue.Format = TexDesc.Format;
for (Uint32 i = 0; i < 4; ++i)
RenderPassRT.BeginningAccess.Clear.ClearValue.Color[i] = 0;
RenderPassRT.EndingAccess.Type = D3D12_RENDER_PASS_ENDING_ACCESS_TYPE_PRESERVE;
pCmdList4->BeginRenderPass(1, &RenderPassRT, nullptr, D3D12_RENDER_PASS_FLAG_NONE);
TriRenderer.Draw(pCmdList, SCDesc.Width, SCDesc.Height);
pCmdList4->EndRenderPass();
}
// Transition input attachment texture from render target to shader resource
{
D3D12_RESOURCE_BARRIER Barrier = {};
Barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
Barrier.Transition.pResource = pd3d12Tex;
Barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_RENDER_TARGET;
Barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE;
Barrier.Transition.Subresource = 0;
pCmdList->ResourceBarrier(1, &Barrier);
}
pTestingSwapChainD3D12->TransitionRenderTarget(pCmdList, D3D12_RESOURCE_STATE_RENDER_TARGET);
{
// Start the second subpass
D3D12_RENDER_PASS_RENDER_TARGET_DESC RenderPassRT = {};
RenderPassRT.cpuDescriptor = pTestingSwapChainD3D12->GetRTVDescriptorHandle();
RenderPassRT.BeginningAccess.Type = D3D12_RENDER_PASS_BEGINNING_ACCESS_TYPE_CLEAR;
RenderPassRT.BeginningAccess.Clear.ClearValue.Format = TexDesc.Format;
for (Uint32 i = 0; i < 4; ++i)
RenderPassRT.BeginningAccess.Clear.ClearValue.Color[i] = pClearColor[i];
RenderPassRT.EndingAccess.Type = D3D12_RENDER_PASS_ENDING_ACCESS_TYPE_PRESERVE;
pCmdList4->BeginRenderPass(1, &RenderPassRT, nullptr, D3D12_RENDER_PASS_FLAG_NONE);
pCmdList4->SetDescriptorHeaps(1, &pd3d12SRVDescriptorHeap.p);
TriRendererInptAtt.Draw(pCmdList, SCDesc.Width, SCDesc.Height, SrvGpuDescriptorHandle);
pCmdList4->EndRenderPass();
}
pCmdList->Close();
ID3D12CommandList* pCmdLits[] = {pCmdList};
RefCntAutoPtr<IDeviceContextD3D12> pContextD3D12{pContext, IID_DeviceContextD3D12};
auto* pQeueD3D12 = pContextD3D12->LockCommandQueue();
auto* pd3d12Queue = pQeueD3D12->GetD3D12CommandQueue();
pd3d12Queue->ExecuteCommandLists(_countof(pCmdLits), pCmdLits);
pEnv->IdleCommandQueue(pd3d12Queue);
pContextD3D12->UnlockCommandQueue();
}
} // namespace Testing
} // namespace Diligent
| 46.476087 | 223 | 0.693157 | [
"render"
] |
107c84b54a31ca7eeaa5d2dbb988b1b17f9682c8 | 451 | cpp | C++ | CodeChef/Easy/E0028.cpp | Mohammed-Shoaib/HackerRank-Problems | ccfb9fc2f0d8dff454439d75ce519cf83bad7c3b | [
"MIT"
] | 54 | 2019-05-13T12:13:09.000Z | 2022-02-27T02:59:00.000Z | CodeChef/Easy/E0028.cpp | Mohammed-Shoaib/HackerRank-Problems | ccfb9fc2f0d8dff454439d75ce519cf83bad7c3b | [
"MIT"
] | 2 | 2020-10-02T07:16:43.000Z | 2020-10-19T04:36:19.000Z | CodeChef/Easy/E0028.cpp | Mohammed-Shoaib/HackerRank-Problems | ccfb9fc2f0d8dff454439d75ce519cf83bad7c3b | [
"MIT"
] | 20 | 2020-05-26T09:48:13.000Z | 2022-03-18T15:18:27.000Z | // Problem Code: AMSGAME1
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int subtractionGame(vector<int> A){
int gcd = A[0];
for(int i=1 ; i<A.size() ; i++)
gcd = __gcd(A[i], gcd);
return gcd;
}
int main(){
int T, N, num;
vector<int> A;
cin >> T;
while(T--){
cin >> N;
for(int i=0 ; i<N ; i++){
cin >> num;
A.push_back(num);
}
cout << subtractionGame(A) << endl;
A.clear();
}
return 0;
} | 15.033333 | 37 | 0.574279 | [
"vector"
] |
107cd0415ed40f21ff43764045913cc0b3cd9171 | 1,643 | cpp | C++ | example/model_size.cpp | JamesYang007/autoppl | e78f8d229d2e399f86f338e473da5ddc7dbed053 | [
"MIT"
] | 37 | 2020-04-12T19:45:12.000Z | 2021-06-28T19:05:38.000Z | example/model_size.cpp | JamesYang007/autoppl | e78f8d229d2e399f86f338e473da5ddc7dbed053 | [
"MIT"
] | 11 | 2020-04-26T14:55:52.000Z | 2020-09-13T19:21:50.000Z | example/model_size.cpp | JamesYang007/autoppl | e78f8d229d2e399f86f338e473da5ddc7dbed053 | [
"MIT"
] | 7 | 2020-04-15T04:45:22.000Z | 2022-03-25T17:28:42.000Z | #include <autoppl/autoppl.hpp>
#include <array>
#include <iostream>
void simple_model()
{
// simple model size
ppl::Data<double> X;
ppl::Param<double> m;
auto model = (
m |= ppl::uniform(-1., 1.),
X |= ppl::normal(m, 1.)
);
std::cout << "Model:\n"
<< "m ~ Uniform(-1, 1)\n"
<< "X ~ Normal(m, 1)\n"
<< std::endl;
std::cout << "Size of model: "
<< sizeof(model) << std::endl;
}
void complex_model()
{
// complicated model size
ppl::Data<double> X;
std::array<ppl::Param<double>, 6> theta;
auto model = (
theta[0] |= ppl::uniform(-1., 1.),
theta[1] |= ppl::uniform(theta[0], theta[0] + 2.),
theta[2] |= ppl::normal(theta[1], theta[0] * theta[0]),
theta[3] |= ppl::normal(-2., 1.),
theta[4] |= ppl::uniform(-0.5, 0.5),
theta[5] |= ppl::normal(theta[2] + theta[3], theta[4]),
X |= ppl::normal(theta[5], 1.)
);
std::cout << "Model:\n"
<< "theta[0] |= ppl::uniform(-1., 1.),\n"
<< "theta[1] |= ppl::uniform(theta[0], theta[0] + 2.),\n"
<< "theta[2] |= ppl::normal(theta[1], theta[0] * theta[0]),\n"
<< "theta[3] |= ppl::normal(-2., 1.),\n"
<< "theta[4] |= ppl::uniform(-0.5, 0.5),\n"
<< "theta[5] |= ppl::normal(theta[2] + theta[3], theta[4]),\n"
<< "X |= ppl::normal(theta[5], 1.)"
<< std::endl;
std::cout << "Size of model: "
<< sizeof(model) << std::endl;
}
int main()
{
simple_model();
complex_model();
return 0;
}
| 27.847458 | 76 | 0.453439 | [
"model"
] |
107e3bd3cae3890860f3c66728eba21ca49424ab | 30,616 | cpp | C++ | examples/connection_tester.cpp | teddywest32/libtorrent | 1dd0e9b280f01750d5e204cca475bd06d30540c4 | [
"BSL-1.0",
"BSD-3-Clause"
] | null | null | null | examples/connection_tester.cpp | teddywest32/libtorrent | 1dd0e9b280f01750d5e204cca475bd06d30540c4 | [
"BSL-1.0",
"BSD-3-Clause"
] | null | null | null | examples/connection_tester.cpp | teddywest32/libtorrent | 1dd0e9b280f01750d5e204cca475bd06d30540c4 | [
"BSL-1.0",
"BSD-3-Clause"
] | null | null | null | /*
Copyright (c) 2008, Arvid Norberg
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 author 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 "libtorrent/peer_id.hpp"
#include "libtorrent/io_service.hpp"
#include "libtorrent/socket.hpp"
#include "libtorrent/address.hpp"
#include "libtorrent/error_code.hpp"
#include "libtorrent/io.hpp"
#include "libtorrent/torrent_info.hpp"
#include "libtorrent/create_torrent.hpp"
#include "libtorrent/hasher.hpp"
#include "libtorrent/socket_io.hpp"
#include "libtorrent/file_pool.hpp"
#include "libtorrent/string_view.hpp"
#include <random>
#include <cstring>
#include <thread>
#include <functional>
#include <iostream>
#include <atomic>
#include <array>
#if BOOST_ASIO_DYN_LINK
#if BOOST_VERSION >= 104500
#include <boost/asio/impl/src.hpp>
#elif BOOST_VERSION >= 104400
#include <boost/asio/impl/src.cpp>
#endif
#endif
using namespace libtorrent;
using namespace libtorrent::detail; // for write_* and read_*
using namespace std::placeholders;
void generate_block(std::uint32_t* buffer, piece_index_t const piece, int start, int length)
{
std::uint32_t fill = (static_cast<int>(piece) << 8) | ((start / 0x4000) & 0xff);
for (int i = 0; i < length / 4; ++i)
{
buffer[i] = fill;
}
}
// in order to circumvent the restricton of only
// one connection per IP that most clients implement
// all sockets created by this tester are bound to
// uniqe local IPs in the range (127.0.0.1 - 127.255.255.255)
// it's only enabled if the target is also on the loopback
int local_if_counter = 0;
bool local_bind = false;
// when set to true, blocks downloaded are verified to match
// the test torrents
bool verify_downloads = false;
// if this is true, one block in 1000 will be sent corrupt.
// this only applies to dual and upload tests
bool test_corruption = false;
// number of seeds we've spawned. The test is terminated
// when this reaches zero, for dual tests
std::atomic<int> num_seeds(0);
// the kind of test to run. Upload sends data to a
// bittorrent client, download requests data from
// a client and dual uploads and downloads from a client
// at the same time (this is presumably the most realistic
// test)
enum test_mode_t{ none, upload_test, download_test, dual_test };
test_mode_t test_mode = none;
// the number of suggest messages received (total across all peers)
std::atomic<int> num_suggest(0);
// the number of requests made from suggested pieces
std::atomic<int> num_suggested_requests(0);
void sleep_ms(int milliseconds)
{
#if defined TORRENT_WINDOWS || defined TORRENT_CYGWIN
Sleep(milliseconds);
#elif defined TORRENT_BEOS
snooze_until(system_time() + std::int64_t(milliseconds) * 1000, B_SYSTEM_TIMEBASE);
#else
usleep(milliseconds * 1000);
#endif
}
std::string leaf_path(std::string f)
{
if (f.empty()) return "";
char const* first = f.c_str();
char const* sep = strrchr(first, '/');
#if defined(TORRENT_WINDOWS) || defined(TORRENT_OS2)
char const* altsep = strrchr(first, '\\');
if (sep == 0 || altsep > sep) sep = altsep;
#endif
if (sep == nullptr) return f;
if (sep - first == int(f.size()) - 1)
{
// if the last character is a / (or \)
// ignore it
int len = 0;
while (sep > first)
{
--sep;
if (*sep == '/'
#if defined(TORRENT_WINDOWS) || defined(TORRENT_OS2)
|| *sep == '\\'
#endif
)
return std::string(sep + 1, len);
++len;
}
return std::string(first, len);
}
return std::string(sep + 1);
}
namespace {
std::random_device dev;
std::mt19937 rng(dev());
}
struct peer_conn
{
peer_conn(io_service& ios, int num_pieces, int blocks_pp, tcp::endpoint const& ep
, char const* ih, bool seed_, int churn_, bool corrupt_)
: s(ios)
, read_pos(0)
, state(handshaking)
, choked(true)
, current_piece(-1)
, current_piece_is_allowed(false)
, block(0)
, blocks_per_piece(blocks_pp)
, info_hash(ih)
, outstanding_requests(0)
, seed(seed_)
, fast_extension(false)
, blocks_received(0)
, blocks_sent(0)
, num_pieces(num_pieces)
, start_time(clock_type::now())
, churn(churn_)
, corrupt(corrupt_)
, endpoint(ep)
, restarting(false)
{
corruption_counter = rand() % 1000;
if (seed) ++num_seeds;
pieces.reserve(num_pieces);
start_conn();
}
void start_conn()
{
if (local_bind)
{
error_code ec;
s.open(endpoint.protocol(), ec);
if (ec)
{
close("ERROR OPEN: %s", ec);
return;
}
tcp::endpoint bind_if(address_v4(
(127 << 24)
+ ((local_if_counter / 255) << 16)
+ ((local_if_counter % 255) + 1)), 0);
++local_if_counter;
s.bind(bind_if, ec);
if (ec)
{
close("ERROR BIND: %s", ec);
return;
}
}
restarting = false;
s.async_connect(endpoint, std::bind(&peer_conn::on_connect, this, _1));
}
tcp::socket s;
char write_buf_proto[100];
std::uint32_t write_buffer[17*1024/4];
std::uint32_t buffer[17*1024/4];
int read_pos;
int corruption_counter;
enum state_t
{
handshaking,
sending_request,
receiving_message
};
int state;
std::vector<piece_index_t> pieces;
std::vector<piece_index_t> suggested_pieces;
std::vector<piece_index_t> allowed_fast;
bool choked;
piece_index_t current_piece; // the piece we're currently requesting blocks from
bool current_piece_is_allowed;
int block;
int blocks_per_piece;
char const* info_hash;
int outstanding_requests;
// if this is true, this connection is a seed
bool seed;
bool fast_extension;
int blocks_received;
int blocks_sent;
int num_pieces;
time_point start_time;
time_point end_time;
int churn;
bool corrupt;
tcp::endpoint endpoint;
bool restarting;
void on_connect(error_code const& ec)
{
if (ec)
{
close("ERROR CONNECT: %s", ec);
return;
}
char handshake[] = "\x13" "BitTorrent protocol\0\0\0\0\0\0\0\x04"
" " // space for info-hash
"aaaaaaaaaaaaaaaaaaaa" // peer-id
"\0\0\0\x01\x02"; // interested
char* h = (char*)malloc(sizeof(handshake));
memcpy(h, handshake, sizeof(handshake));
std::memcpy(h + 28, info_hash, 20);
std::generate(h + 48, h + 68, &rand);
// for seeds, don't send the interested message
boost::asio::async_write(s, boost::asio::buffer(h, (sizeof(handshake) - 1) - (seed ? 5 : 0))
, std::bind(&peer_conn::on_handshake, this, h, _1, _2));
}
void on_handshake(char* h, error_code const& ec, size_t)
{
free(h);
if (ec)
{
close("ERROR SEND HANDSHAKE: %s", ec);
return;
}
// read handshake
boost::asio::async_read(s, boost::asio::buffer((char*)buffer, 68)
, std::bind(&peer_conn::on_handshake2, this, _1, _2));
}
void on_handshake2(error_code const& ec, size_t)
{
if (ec)
{
close("ERROR READ HANDSHAKE: %s", ec);
return;
}
// buffer is the full 68 byte handshake
// look at the extension bits
fast_extension = (((char*)buffer)[27] & 4) != 0;
if (seed)
{
write_have_all();
}
else
{
work_download();
}
}
void write_have_all()
{
if (fast_extension)
{
char* ptr = write_buf_proto;
// have_all
write_uint32(1, ptr);
write_uint8(0xe, ptr);
// unchoke
write_uint32(1, ptr);
write_uint8(1, ptr);
error_code ec;
boost::asio::async_write(s, boost::asio::buffer(write_buf_proto, ptr - write_buf_proto)
, std::bind(&peer_conn::on_have_all_sent, this, _1, _2));
}
else
{
// bitfield
int len = (num_pieces + 7) / 8;
char* ptr = (char*)buffer;
write_uint32(len + 1, ptr);
write_uint8(5, ptr);
memset(ptr, 255, len);
ptr += len;
// unchoke
write_uint32(1, ptr);
write_uint8(1, ptr);
error_code ec;
boost::asio::async_write(s, boost::asio::buffer((char*)buffer, len + 10)
, std::bind(&peer_conn::on_have_all_sent, this, _1, _2));
}
}
void on_have_all_sent(error_code const& ec, size_t)
{
if (ec)
{
close("ERROR SEND HAVE ALL: %s", ec);
return;
}
// read message
boost::asio::async_read(s, boost::asio::buffer((char*)buffer, 4)
, std::bind(&peer_conn::on_msg_length, this, _1, _2));
}
bool write_request()
{
// if we're choked (and there are no allowed-fast pieces left)
if (choked && allowed_fast.empty() && !current_piece_is_allowed) return false;
// if there are no pieces left to request
if (pieces.empty() && suggested_pieces.empty()
&& current_piece == piece_index_t(-1))
{
return false;
}
if (current_piece == piece_index_t(-1))
{
// pick a new piece
if (choked && allowed_fast.size() > 0)
{
current_piece = allowed_fast.front();
allowed_fast.erase(allowed_fast.begin());
current_piece_is_allowed = true;
}
else if (suggested_pieces.size() > 0)
{
current_piece = suggested_pieces.front();
suggested_pieces.erase(suggested_pieces.begin());
++num_suggested_requests;
current_piece_is_allowed = false;
}
else if (pieces.size() > 0)
{
current_piece = pieces.front();
pieces.erase(pieces.begin());
current_piece_is_allowed = false;
}
else
{
TORRENT_ASSERT_FAIL();
}
}
char msg[] = "\0\0\0\xd\x06"
" " // piece
" " // offset
" "; // length
char* m = (char*)malloc(sizeof(msg));
memcpy(m, msg, sizeof(msg));
char* ptr = m + 5;
write_uint32(static_cast<int>(current_piece), ptr);
write_uint32(block * 16 * 1024, ptr);
write_uint32(16 * 1024, ptr);
error_code ec;
boost::asio::async_write(s, boost::asio::buffer(m, sizeof(msg) - 1)
, std::bind(&peer_conn::on_req_sent, this, m, _1, _2));
++outstanding_requests;
++block;
if (block == blocks_per_piece)
{
block = 0;
current_piece = piece_index_t(-1);
current_piece_is_allowed = false;
}
return true;
}
void on_req_sent(char* m, error_code const& ec, size_t)
{
free(m);
if (ec)
{
close("ERROR SEND REQUEST: %s", ec);
return;
}
work_download();
}
void close(char const* fmt, error_code const& ec)
{
end_time = clock_type::now();
char tmp[1024];
std::snprintf(tmp, sizeof(tmp), fmt, ec.message().c_str());
int time = int(total_milliseconds(end_time - start_time));
if (time == 0) time = 1;
float up = (std::int64_t(blocks_sent) * 0x4000) / time / 1000.f;
float down = (std::int64_t(blocks_received) * 0x4000) / time / 1000.f;
error_code e;
char ep_str[200];
address const& addr = s.local_endpoint(e).address();
#if TORRENT_USE_IPV6
if (addr.is_v6())
std::snprintf(ep_str, sizeof(ep_str), "[%s]:%d", addr.to_string(e).c_str()
, s.local_endpoint(e).port());
else
#endif
std::snprintf(ep_str, sizeof(ep_str), "%s:%d", addr.to_string(e).c_str()
, s.local_endpoint(e).port());
std::printf("%s ep: %s sent: %d received: %d duration: %d ms up: %.1fMB/s down: %.1fMB/s\n"
, tmp, ep_str, blocks_sent, blocks_received, time, up, down);
if (seed) --num_seeds;
}
void work_download()
{
if (pieces.empty()
&& suggested_pieces.empty()
&& current_piece == piece_index_t(-1)
&& outstanding_requests == 0
&& blocks_received >= num_pieces * blocks_per_piece)
{
close("COMPLETED DOWNLOAD", error_code());
return;
}
// send requests
if (outstanding_requests < 40)
{
if (write_request()) return;
}
// read message
boost::asio::async_read(s, boost::asio::buffer((char*)buffer, 4)
, std::bind(&peer_conn::on_msg_length, this, _1, _2));
}
void on_msg_length(error_code const& ec, size_t)
{
if ((ec == boost::asio::error::operation_aborted || ec == boost::asio::error::bad_descriptor)
&& restarting)
{
start_conn();
return;
}
if (ec)
{
close("ERROR RECEIVE MESSAGE PREFIX: %s", ec);
return;
}
char* ptr = (char*)buffer;
unsigned int length = read_uint32(ptr);
if (length > sizeof(buffer))
{
std::fprintf(stderr, "len: %d\n", length);
close("ERROR RECEIVE MESSAGE PREFIX: packet too big", error_code());
return;
}
boost::asio::async_read(s, boost::asio::buffer((char*)buffer, length)
, std::bind(&peer_conn::on_message, this, _1, _2));
}
void on_message(error_code const& ec, size_t bytes_transferred)
{
if ((ec == boost::asio::error::operation_aborted || ec == boost::asio::error::bad_descriptor)
&& restarting)
{
start_conn();
return;
}
if (ec)
{
close("ERROR RECEIVE MESSAGE: %s", ec);
return;
}
char* ptr = (char*)buffer;
int msg = read_uint8(ptr);
if (test_mode == dual_test && num_seeds == 0)
{
TORRENT_ASSERT(!seed);
close("NO MORE SEEDS, test done", error_code());
return;
}
//std::printf("msg: %d len: %d\n", msg, int(bytes_transferred));
if (seed)
{
if (msg == 6)
{
if (bytes_transferred != 13)
{
close("REQUEST packet has invalid size", error_code());
return;
}
piece_index_t const piece = piece_index_t(detail::read_int32(ptr));
int const start = detail::read_int32(ptr);
int const length = detail::read_int32(ptr);
write_piece(piece, start, length);
}
else if (msg == 3) // not-interested
{
close("DONE", error_code());
return;
}
else
{
// read another message
boost::asio::async_read(s, boost::asio::buffer(buffer, 4)
, std::bind(&peer_conn::on_msg_length, this, _1, _2));
}
}
else
{
if (msg == 0xe) // have_all
{
// build a list of all pieces and request them all!
pieces.resize(num_pieces);
for (piece_index_t i(0); i < piece_index_t(int(pieces.size())); ++i)
pieces[static_cast<int>(i)] = i;
std::shuffle(pieces.begin(), pieces.end(), rng);
}
else if (msg == 4) // have
{
piece_index_t const piece(detail::read_int32(ptr));
if (pieces.empty()) pieces.push_back(piece);
else pieces.insert(pieces.begin() + (rand() % pieces.size()), piece);
}
else if (msg == 5) // bitfield
{
pieces.reserve(num_pieces);
piece_index_t piece(0);
for (int i = 0; i < int(bytes_transferred); ++i)
{
int mask = 0x80;
for (int k = 0; k < 8; ++k)
{
if (piece > piece_index_t(num_pieces)) break;
if (*ptr & mask) pieces.push_back(piece);
mask >>= 1;
++piece;
}
++ptr;
}
std::shuffle(pieces.begin(), pieces.end(), rng);
}
else if (msg == 7) // piece
{
if (verify_downloads)
{
piece_index_t const piece(read_uint32(ptr));
int start = read_uint32(ptr);
int size = int(bytes_transferred) - 9;
verify_piece(piece, start, ptr, size);
}
++blocks_received;
--outstanding_requests;
piece_index_t const piece = piece_index_t(detail::read_int32(ptr));
int start = detail::read_int32(ptr);
if (churn && (blocks_received % churn) == 0) {
outstanding_requests = 0;
restarting = true;
s.close();
return;
}
if (int((start + bytes_transferred) / 0x4000) == blocks_per_piece)
{
write_have(piece);
return;
}
}
else if (msg == 13) // suggest
{
piece_index_t const piece(detail::read_int32(ptr));
auto i = std::find(pieces.begin(), pieces.end(), piece);
if (i != pieces.end())
{
pieces.erase(i);
suggested_pieces.push_back(piece);
++num_suggest;
}
}
else if (msg == 16) // reject request
{
piece_index_t const piece(detail::read_int32(ptr));
int start = detail::read_int32(ptr);
int length = detail::read_int32(ptr);
// put it back!
if (current_piece != piece)
{
if (pieces.empty() || pieces.back() != piece)
pieces.push_back(piece);
}
else
{
block = (std::min)(start / 0x4000, block);
if (block == 0)
{
pieces.push_back(current_piece);
current_piece = piece_index_t(-1);
current_piece_is_allowed = false;
}
}
--outstanding_requests;
std::fprintf(stderr, "REJECT: [ piece: %d start: %d length: %d ]\n"
, static_cast<int>(piece), start, length);
}
else if (msg == 0) // choke
{
choked = true;
}
else if (msg == 1) // unchoke
{
choked = false;
}
else if (msg == 17) // allowed_fast
{
piece_index_t const piece = piece_index_t(detail::read_int32(ptr));
auto i = std::find(pieces.begin(), pieces.end(), piece);
if (i != pieces.end())
{
pieces.erase(i);
allowed_fast.push_back(piece);
}
}
work_download();
}
}
bool verify_piece(piece_index_t const piece, int start, char const* ptr, int size)
{
std::uint32_t* buf = (std::uint32_t*)ptr;
std::uint32_t const fill = (static_cast<int>(piece) << 8) | ((start / 0x4000) & 0xff);
for (int i = 0; i < size / 4; ++i)
{
if (buf[i] != fill)
{
std::fprintf(stderr, "received invalid block. piece %d block %d\n"
, static_cast<int>(piece), start / 0x4000);
exit(1);
}
}
return true;
}
void write_piece(piece_index_t const piece, int start, int length)
{
generate_block(write_buffer, piece, start, length);
if (corrupt)
{
--corruption_counter;
if (corruption_counter == 0)
{
corruption_counter = 1000;
memset(write_buffer, 0, 10);
}
}
char* ptr = write_buf_proto;
write_uint32(9 + length, ptr);
assert(length == 0x4000);
write_uint8(7, ptr);
write_uint32(static_cast<int>(piece), ptr);
write_uint32(start, ptr);
std::array<boost::asio::const_buffer, 2> vec;
vec[0] = boost::asio::buffer(write_buf_proto, ptr - write_buf_proto);
vec[1] = boost::asio::buffer(write_buffer, length);
boost::asio::async_write(s, vec, std::bind(&peer_conn::on_have_all_sent, this, _1, _2));
++blocks_sent;
if (churn && (blocks_sent % churn) == 0 && seed) {
outstanding_requests = 0;
restarting = true;
s.close();
}
}
void write_have(piece_index_t const piece)
{
char* ptr = write_buf_proto;
write_uint32(5, ptr);
write_uint8(4, ptr);
write_uint32(static_cast<int>(piece), ptr);
boost::asio::async_write(s, boost::asio::buffer(write_buf_proto, 9), std::bind(&peer_conn::on_have_all_sent, this, _1, _2));
}
};
void print_usage()
{
std::fprintf(stderr, "usage: connection_tester command [options]\n\n"
"command is one of:\n"
" gen-torrent generate a test torrent\n"
" options for this command:\n"
" -s <size> the size of the torrent in megabytes\n"
" -n <num-files> the number of files in the test torrent\n"
" -t <file> the file to save the .torrent file to\n"
" -T <name> the name of the torrent (and directory\n"
" its files are saved in)\n\n"
" gen-data generate the data file(s) for the test torrent\n"
" options for this command:\n"
" -t <file> the torrent file that was previously generated\n"
" -P <path> the path to where the data should be stored\n\n"
" gen-test-torrents generate many test torrents (cannot be used for up/down tests)\n"
" options for this command:\n"
" -N <num-torrents> number of torrents to generate\n"
" -n <num-files> number of files in each torrent\n"
" -t <name> base name of torrent files (index is appended)\n\n"
" upload start an uploader test\n"
" download start a downloader test\n"
" dual start a download and upload test\n"
" options for these commands:\n"
" -c <num-conns> the number of connections to make to the target\n"
" -d <dst> the IP address of the target\n"
" -p <dst-port> the port the target listens on\n"
" -t <torrent-file> the torrent file previously generated by gen-torrent\n"
" -C send corrupt pieces sometimes (applies to upload and dual)\n"
" -r <reconnects> churn - number of reconnects per second\n\n"
"examples:\n\n"
"connection_tester gen-torrent -s 1024 -n 4 -t test.torrent\n"
"connection_tester upload -c 200 -d 127.0.0.1 -p 6881 -t test.torrent\n"
"connection_tester download -c 200 -d 127.0.0.1 -p 6881 -t test.torrent\n"
"connection_tester dual -c 200 -d 127.0.0.1 -p 6881 -t test.torrent\n");
exit(1);
}
void hasher_thread(libtorrent::create_torrent* t, piece_index_t const start_piece
, piece_index_t const end_piece, int piece_size, bool print)
{
if (print) std::fprintf(stderr, "\n");
std::uint32_t piece[0x4000 / 4];
for (piece_index_t i = start_piece; i < end_piece; ++i)
{
hasher ph;
for (int j = 0; j < piece_size; j += 0x4000)
{
generate_block(piece, i, j, 0x4000);
ph.update((char*)piece, 0x4000);
}
t->set_hash(i, ph.final());
int const range = static_cast<int>(end_piece) - static_cast<int>(start_piece);
if (print && (static_cast<int>(i) & 1))
{
int const delta_piece = static_cast<int>(i) - static_cast<int>(start_piece);
std::fprintf(stderr, "\r%.1f %% ", float(delta_piece * 100) / float(range));
}
}
if (print) std::fprintf(stderr, "\n");
}
// size is in megabytes
void generate_torrent(std::vector<char>& buf, int size, int num_files
, char const* torrent_name)
{
file_storage fs;
// 1 MiB piece size
const int piece_size = 1024 * 1024;
const int num_pieces = size;
const std::int64_t total_size = std::int64_t(piece_size) * num_pieces;
std::int64_t s = total_size;
int i = 0;
std::int64_t file_size = total_size / num_files;
while (s > 0)
{
char b[100];
std::snprintf(b, sizeof(b), "%s/stress_test%d", torrent_name, i);
++i;
fs.add_file(b, (std::min)(s, std::int64_t(file_size)));
s -= file_size;
file_size += 200;
}
libtorrent::create_torrent t(fs, piece_size);
int const num_threads = std::thread::hardware_concurrency()
? std::thread::hardware_concurrency() : 4;
std::printf("hashing in %d threads\n", num_threads);
std::vector<std::thread> threads;
threads.reserve(num_threads);
for (int i = 0; i < num_threads; ++i)
{
threads.emplace_back(&hasher_thread, &t
, piece_index_t(i * num_pieces / num_threads)
, piece_index_t((i + 1) * num_pieces / num_threads)
, piece_size
, i == 0);
}
for (auto& i : threads)
i.join();
std::back_insert_iterator<std::vector<char>> out(buf);
bencode(out, t.generate());
}
void generate_data(char const* path, torrent_info const& ti)
{
file_storage const& fs = ti.files();
file_pool fp;
storage_params params;
params.files = &const_cast<file_storage&>(fs);
params.mapped_files = nullptr;
params.path = path;
params.pool = &fp;
params.mode = storage_mode_sparse;
std::unique_ptr<storage_interface> st(default_storage_constructor(params));
{
storage_error error;
st->initialize(error);
}
std::uint32_t piece[0x4000 / 4];
for (piece_index_t i(0); i < piece_index_t(ti.num_pieces()); ++i)
{
for (int j = 0; j < ti.piece_size(i); j += 0x4000)
{
generate_block(piece, i, j, 0x4000);
int const left_in_piece = ti.piece_size(i) - j;
iovec_t const b = { piece, size_t(std::min(left_in_piece, 0x4000))};
storage_error error;
st->writev(b, i, j, 0, error);
if (error)
std::fprintf(stderr, "storage error: %s\n", error.ec.message().c_str());
}
if (static_cast<int>(i) & 1)
{
std::fprintf(stderr, "\r%.1f %% ", float(static_cast<int>(i) * 100) / float(ti.num_pieces()));
}
}
}
void io_thread(io_service* ios)
{
error_code ec;
ios->run(ec);
if (ec) std::fprintf(stderr, "ERROR: %s\n", ec.message().c_str());
}
int main(int argc, char* argv[])
{
if (argc <= 1) print_usage();
char const* command = argv[1];
int size = 1000;
int num_files = 10;
int num_torrents = 1;
char const* torrent_file = "benchmark.torrent";
char const* data_path = ".";
int num_connections = 50;
char const* destination_ip = "127.0.0.1";
int destination_port = 6881;
int churn = 0;
argv += 2;
argc -= 2;
while (argc > 0)
{
char const* optname = argv[0];
++argv;
--argc;
if (optname[0] != '-' || strlen(optname) != 2)
{
std::fprintf(stderr, "unknown option: %s\n", optname);
continue;
}
// options with no arguments
switch (optname[1])
{
case 'C': test_corruption = true; continue;
}
if (argc == 0)
{
std::fprintf(stderr, "missing argument for option: %s\n", optname);
break;
}
char const* optarg = argv[0];
++argv;
--argc;
switch (optname[1])
{
case 's': size = atoi(optarg); break;
case 'n': num_files = atoi(optarg); break;
case 'N': num_torrents = atoi(optarg); break;
case 't': torrent_file = optarg; break;
case 'P': data_path = optarg; break;
case 'c': num_connections = atoi(optarg); break;
case 'p': destination_port = atoi(optarg); break;
case 'd': destination_ip = optarg; break;
case 'r': churn = atoi(optarg); break;
default: std::fprintf(stderr, "unknown option: %s\n", optname);
}
}
if (command == "gen-torrent"_sv)
{
std::vector<char> tmp;
std::string name = leaf_path(torrent_file);
name = name.substr(0, name.find_last_of('.'));
std::printf("generating torrent: %s\n", name.c_str());
generate_torrent(tmp, size ? size : 1024, num_files ? num_files : 1
, name.c_str());
FILE* output = stdout;
if ("-"_sv != torrent_file)
{
if( (output = std::fopen(torrent_file, "wb+")) == nullptr)
{
std::fprintf(stderr, "Could not open file '%s' for writing: %s\n"
, torrent_file, std::strerror(errno));
exit(2);
}
}
std::fprintf(stderr, "writing file to: %s\n", torrent_file);
fwrite(&tmp[0], 1, tmp.size(), output);
if (output != stdout)
std::fclose(output);
return 0;
}
else if (command == "gen-data"_sv)
{
error_code ec;
torrent_info ti(torrent_file, ec);
if (ec)
{
std::fprintf(stderr, "ERROR LOADING .TORRENT: %s\n", ec.message().c_str());
return 1;
}
generate_data(data_path, ti);
return 0;
}
else if (command == "gen-test-torrents"_sv)
{
std::vector<char> buf;
for (int i = 0; i < num_torrents; ++i)
{
char torrent_name[100];
std::snprintf(torrent_name, sizeof(torrent_name), "%s-%d.torrent", torrent_file, i);
file_storage fs;
for (int j = 0; j < num_files; ++j)
{
char file_name[100];
std::snprintf(file_name, sizeof(file_name), "%s-%d/file-%d", torrent_file, i, j);
fs.add_file(file_name, std::int64_t(j + i + 1) * 251);
}
// 1 MiB piece size
const int piece_size = 1024 * 1024;
libtorrent::create_torrent t(fs, piece_size);
sha1_hash zero(nullptr);
for (piece_index_t k(0); k < fs.end_piece(); ++k)
t.set_hash(k, zero);
buf.clear();
std::back_insert_iterator<std::vector<char>> out(buf);
bencode(out, t.generate());
FILE* f = std::fopen(torrent_name, "w+");
if (f == nullptr)
{
std::fprintf(stderr, "Could not open file '%s' for writing: %s\n"
, torrent_name, std::strerror(errno));
return 1;
}
size_t ret = fwrite(&buf[0], 1, buf.size(), f);
if (ret != buf.size())
{
std::fprintf(stderr, "write returned: %d (expected %d)\n", int(ret), int(buf.size()));
std::fclose(f);
return 1;
}
std::printf("wrote %s\n", torrent_name);
std::fclose(f);
}
return 0;
}
else if (command == "upload"_sv)
{
test_mode = upload_test;
}
else if (command == "download"_sv)
{
test_mode = download_test;
}
else if (command == "dual"_sv)
{
test_mode = dual_test;
}
else
{
std::fprintf(stderr, "unknown command: %s\n\n", command);
print_usage();
}
error_code ec;
address_v4 addr = address_v4::from_string(destination_ip, ec);
if (ec)
{
std::fprintf(stderr, "ERROR RESOLVING %s: %s\n", destination_ip, ec.message().c_str());
return 1;
}
tcp::endpoint ep(addr, std::uint16_t(destination_port));
#if !defined __APPLE__
// apparently darwin doesn't seems to let you bind to
// loopback on any other IP than 127.0.0.1
std::uint32_t const ip = addr.to_ulong();
if ((ip & 0xff000000) == 0x7f000000)
{
local_bind = true;
}
#endif
torrent_info ti(torrent_file, ec);
if (ec)
{
std::fprintf(stderr, "ERROR LOADING .TORRENT: %s\n", ec.message().c_str());
return 1;
}
std::vector<peer_conn*> conns;
conns.reserve(num_connections);
int const num_threads = 2;
io_service ios[num_threads];
for (int i = 0; i < num_connections; ++i)
{
bool corrupt = test_corruption && (i & 1) == 0;
bool seed = false;
if (test_mode == upload_test) seed = true;
else if (test_mode == dual_test) seed = (i & 1);
conns.push_back(new peer_conn(ios[i % num_threads], ti.num_pieces(), ti.piece_length() / 16 / 1024
, ep, (char const*)&ti.info_hash()[0], seed, churn, corrupt));
sleep_ms(1);
ios[i % num_threads].poll_one(ec);
if (ec)
{
std::fprintf(stderr, "ERROR: %s\n", ec.message().c_str());
break;
}
}
std::thread t1(&io_thread, &ios[0]);
std::thread t2(&io_thread, &ios[1]);
t1.join();
t2.join();
float up = 0.f;
float down = 0.f;
std::uint64_t total_sent = 0;
std::uint64_t total_received = 0;
for (std::vector<peer_conn*>::iterator i = conns.begin()
, end(conns.end()); i != end; ++i)
{
peer_conn* p = *i;
int time = int(total_milliseconds(p->end_time - p->start_time));
if (time == 0) time = 1;
total_sent += p->blocks_sent;
up += (std::int64_t(p->blocks_sent) * 0x4000) / time / 1000.f;
down += (std::int64_t(p->blocks_received) * 0x4000) / time / 1000.f;
delete p;
}
std::printf("=========================\n"
"suggests: %d suggested-requests: %d\n"
"total sent: %.1f %% received: %.1f %%\n"
"rate sent: %.1f MB/s received: %.1f MB/s\n"
, int(num_suggest), int(num_suggested_requests)
, total_sent * 0x4000 * 100.f / float(ti.total_size())
, total_received * 0x4000 * 100.f / float(ti.total_size())
, up, down);
return 0;
}
| 27.022065 | 126 | 0.644696 | [
"vector"
] |
1083f14f342c13bf8bc4fb6965b77c61a62590a4 | 4,294 | cpp | C++ | src/Utils/Network/Messages/PlayerInputMessage.cpp | gameraccoon/tank-game | ec2ca0550269b8051c8742abdfad6ae8adc2a83a | [
"MIT"
] | null | null | null | src/Utils/Network/Messages/PlayerInputMessage.cpp | gameraccoon/tank-game | ec2ca0550269b8051c8742abdfad6ae8adc2a83a | [
"MIT"
] | null | null | null | src/Utils/Network/Messages/PlayerInputMessage.cpp | gameraccoon/tank-game | ec2ca0550269b8051c8742abdfad6ae8adc2a83a | [
"MIT"
] | null | null | null | #include "Base/precomp.h"
#include "Utils/Network/Messages/PlayerInputMessage.h"
#include "Base/Types/Serialization.h"
#include "Base/Types/BasicTypes.h"
#include "GameData/Components/InputHistoryComponent.generated.h"
#include "GameData/Components/NetworkIdComponent.generated.h"
#include "GameData/Components/NetworkIdMappingComponent.generated.h"
#include "GameData/Components/ServerConnectionsComponent.generated.h"
#include "GameData/Network/NetworkMessageIds.h"
#include "GameData/World.h"
#include "Utils/Network/CompressedInput.h"
#include "HAL/Network/ConnectionManager.h"
namespace Network
{
HAL::ConnectionManager::Message CreatePlayerInputMessage(World& world)
{
std::vector<std::byte> inputHistoryMessageData;
InputHistoryComponent* inputHistory = world.getNotRewindableWorldComponents().getOrAddComponent<InputHistoryComponent>();
const size_t inputsSize = inputHistory->getInputs().size();
const size_t inputsToSend = std::min(inputsSize, static_cast<size_t>(10));
inputHistoryMessageData.reserve(4 + 1 + inputsToSend * ((4 + 4) * 2 + (1 + 8) * 1));
Serialization::WriteNumber<u32>(inputHistoryMessageData, inputHistory->getLastInputUpdateIdx());
Serialization::WriteNumber<u8>(inputHistoryMessageData, inputsToSend);
Utils::WriteInputHistory(inputHistoryMessageData, inputHistory->getInputs(), inputsToSend);
return HAL::ConnectionManager::Message{
static_cast<u32>(NetworkMessageId::PlayerInput),
std::move(inputHistoryMessageData)
};
}
static bool hasNewInput(u32 oldFrameIndex, u32 newFrameIndex)
{
constexpr u32 WRAP_ZONE_SIZE = 1024;
constexpr u32 WRAP_MIN = std::numeric_limits<u32>::max() - WRAP_ZONE_SIZE;
constexpr u32 WRAP_MAX = WRAP_ZONE_SIZE;
const bool oldAboutToWrap = (oldFrameIndex > WRAP_MIN);
const bool newAboutToWrap = (newFrameIndex > WRAP_MIN);
const bool oldAfterWrap = (oldFrameIndex < WRAP_MAX);
const bool newAfterWrap = (newFrameIndex < WRAP_MAX);
if ALMOST_NEVER(oldAboutToWrap && newAfterWrap)
{
return true;
}
else if ALMOST_NEVER(newAboutToWrap && oldAfterWrap)
{
return false;
}
else
{
return oldFrameIndex < newFrameIndex;
}
}
void ApplyPlayerInputMessage(World& world, HAL::ConnectionManager::Message&& message, ConnectionId connectionId)
{
ServerConnectionsComponent* serverConnections = world.getNotRewindableWorldComponents().getOrAddComponent<ServerConnectionsComponent>();
size_t streamIndex = 0;
Serialization::ByteStream& data = message.data;
const u32 frameIndex = Serialization::ReadNumber<u32>(data, streamIndex);
const size_t receivedInputsCount = Serialization::ReadNumber<u8>(data, streamIndex);
std::vector<GameplayInput::FrameState> receivedFrameStates = Utils::ReadInputHistory(data, receivedInputsCount, streamIndex);
Input::InputHistory& inputHistory = serverConnections->getInputsRef()[connectionId];
const u32 lastStoredFrameIndex = inputHistory.lastInputUpdateIdx;
if (hasNewInput(lastStoredFrameIndex, frameIndex))
{
const size_t newFramesCount = frameIndex - lastStoredFrameIndex;
const size_t newInputsCount = std::min(newFramesCount, receivedInputsCount);
const size_t resultsOriginalSize = inputHistory.inputs.size();
const size_t resultsNewSize = resultsOriginalSize + newFramesCount;
inputHistory.inputs.resize(resultsNewSize);
// add new elements to the end of the array
const size_t firstIndexToWrite = resultsNewSize - newInputsCount;
const size_t firstIndexToRead = receivedInputsCount - newInputsCount;
for (size_t writeIdx = firstIndexToWrite, readIdx = firstIndexToRead; writeIdx < resultsNewSize; ++writeIdx, ++readIdx)
{
inputHistory.inputs[writeIdx] = receivedFrameStates[readIdx];
}
// if we have a gap in the inputs, fill it with the last input that we had before or the first input after
const size_t firstMissingIndex = resultsNewSize - newFramesCount;
const size_t indexToFillFrom = (resultsOriginalSize > 0) ? (resultsOriginalSize - 1) : firstIndexToWrite;
const GameplayInput::FrameState& inputToFillWith = inputHistory.inputs[indexToFillFrom];
for (size_t idx = firstMissingIndex; idx < firstIndexToWrite; ++idx)
{
inputHistory.inputs[idx] = inputToFillWith;
}
inputHistory.lastInputUpdateIdx = frameIndex;
}
}
}
| 39.036364 | 138 | 0.776898 | [
"vector"
] |
10877518187e964e031ed0acf584cf22448d4ca6 | 1,784 | hpp | C++ | src/xhtml/xhtml_border_info.hpp | gamobink/anura | 410721a174aae98f32a55d71a4e666ad785022fd | [
"CC0-1.0"
] | 6 | 2017-11-16T06:07:37.000Z | 2020-06-26T20:24:01.000Z | src/xhtml/xhtml_border_info.hpp | gamobink/anura | 410721a174aae98f32a55d71a4e666ad785022fd | [
"CC0-1.0"
] | null | null | null | src/xhtml/xhtml_border_info.hpp | gamobink/anura | 410721a174aae98f32a55d71a4e666ad785022fd | [
"CC0-1.0"
] | 3 | 2017-04-11T15:42:54.000Z | 2018-07-07T09:48:56.000Z | /*
Copyright (C) 2003-2013 by Kristina Simpson <sweet.kristas@gmail.com>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
#pragma once
#include "geometry.hpp"
#include "Texture.hpp"
#include "xhtml_style_tree.hpp"
namespace xhtml
{
class BorderInfo
{
public:
explicit BorderInfo(const StyleNodePtr& styles);
void init(const Dimensions& dims);
bool render(const KRE::SceneTreePtr& scene_tree, const Dimensions& dims, const point& offset) const;
void renderNormal(const KRE::SceneTreePtr& scene_tree, const Dimensions& dims, const point& offset) const;
void setWidths(const std::array<float,4>& widths) { widths_ = widths; }
void setOutset(const std::array<float,4>& outset) { outset_ = outset; }
void setSlice(const std::array<float,4>& slice) { slice_ = slice; }
bool isValid(css::Side side) const;
private:
StyleNodePtr styles_;
KRE::TexturePtr image_;
std::array<float,4> slice_;
std::array<float,4> outset_;
std::array<float,4> widths_;
};
}
| 33.660377 | 108 | 0.745516 | [
"geometry",
"render"
] |
10890562cfe3a3556600561743e35313ab12d5f0 | 1,632 | cpp | C++ | boboleetcode/Play-Leetcode-master/0133-Clone-Graph/cpp-0133/main.cpp | yaominzh/CodeLrn2019 | adc727d92904c5c5d445a2621813dfa99474206d | [
"Apache-2.0"
] | 2 | 2021-03-25T05:26:55.000Z | 2021-04-20T03:33:24.000Z | boboleetcode/Play-Leetcode-master/0133-Clone-Graph/cpp-0133/main.cpp | mcuallen/CodeLrn2019 | adc727d92904c5c5d445a2621813dfa99474206d | [
"Apache-2.0"
] | 6 | 2019-12-04T06:08:32.000Z | 2021-05-10T20:22:47.000Z | boboleetcode/Play-Leetcode-master/0133-Clone-Graph/cpp-0133/main.cpp | mcuallen/CodeLrn2019 | adc727d92904c5c5d445a2621813dfa99474206d | [
"Apache-2.0"
] | null | null | null | /// Source : https://leetcode.com/problems/clone-graph/description/
/// Author : liuyubobobo
/// Time : 2018-08-30
#include <iostream>
#include <stack>
#include <vector>
#include <unordered_map>
using namespace std;
/// Definition for undirected graph.
struct UndirectedGraphNode {
int label;
vector<UndirectedGraphNode *> neighbors;
UndirectedGraphNode(int x) : label(x) {};
};
/// Using Two Stacks and HashMap from label to Node
/// Time Complexity: O(V+E)
/// Space Complexity: O(V)
class Solution {
public:
UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
if(node == NULL)
return NULL;
UndirectedGraphNode* ret = new UndirectedGraphNode(node->label);
stack<UndirectedGraphNode*> stack1;
stack1.push(node);
unordered_map<int, UndirectedGraphNode*> visited;
visited[ret->label] = ret;
stack<UndirectedGraphNode*> stack2;
stack2.push(ret);
while(!stack1.empty()){
UndirectedGraphNode* old_cur = stack1.top();
stack1.pop();
UndirectedGraphNode* new_cur = stack2.top();
stack2.pop();
for(UndirectedGraphNode *next: old_cur->neighbors) {
if (visited.find(next->label) == visited.end()) {
visited[next->label] = new UndirectedGraphNode(next->label);
stack1.push(next);
stack2.push(visited[next->label]);
}
new_cur->neighbors.push_back(visited[next->label]);
}
}
return ret;
}
};
int main() {
return 0;
} | 25.904762 | 80 | 0.596814 | [
"vector"
] |
1089d11ee72593ea4aa08b1410fdc8c787855403 | 16,101 | cpp | C++ | remote_openxr/desktop/CubeGraphics.cpp | vimusc/MixedReality-HolographicRemoting-Samples | 315867b8fb8df9539df15900a411bc91da49c04c | [
"Apache-2.0"
] | 1 | 2021-06-15T08:03:54.000Z | 2021-06-15T08:03:54.000Z | remote_openxr/desktop/CubeGraphics.cpp | vimusc/MixedReality-HolographicRemoting-Samples | 315867b8fb8df9539df15900a411bc91da49c04c | [
"Apache-2.0"
] | null | null | null | remote_openxr/desktop/CubeGraphics.cpp | vimusc/MixedReality-HolographicRemoting-Samples | 315867b8fb8df9539df15900a411bc91da49c04c | [
"Apache-2.0"
] | null | null | null | //*********************************************************
// Copyright (c) Microsoft. All rights reserved.
//
// Apache 2.0 License
//
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License.
//
//*********************************************************
#include "pch.h"
#include "OpenXrProgram.h"
#include "DxUtility.h"
namespace {
namespace CubeShader {
struct Vertex {
XrVector3f Position;
XrVector3f Color;
};
constexpr XrVector3f Red{1, 0, 0};
constexpr XrVector3f Green{0, 1, 0};
constexpr XrVector3f Blue{0, 0, 1};
constexpr XrVector3f Yellow{0, 1, 1};
constexpr XrVector3f Purple{1, 0, 1};
constexpr XrVector3f Brown{1, 1, 0};
constexpr XrVector3f Black{0, 0, 0};
constexpr XrVector3f White{1, 1, 1};
// Vertices for a 1x1x1 meter cube. (Left/Right, Top/Bottom, Front/Back)
constexpr XrVector3f LBB{-0.5f, -0.5f, -0.5f};
constexpr XrVector3f LBF{-0.5f, -0.5f, 0.5f};
constexpr XrVector3f LTB{-0.5f, 0.5f, -0.5f};
constexpr XrVector3f LTF{-0.5f, 0.5f, 0.5f};
constexpr XrVector3f RBB{0.5f, -0.5f, -0.5f};
constexpr XrVector3f RBF{0.5f, -0.5f, 0.5f};
constexpr XrVector3f RTB{0.5f, 0.5f, -0.5f};
constexpr XrVector3f RTF{0.5f, 0.5f, 0.5f};
#define CUBE_SIDE(V1, V2, V3, V4, V5, V6, COLOR) {V1, COLOR}, {V2, COLOR}, {V3, COLOR}, {V4, COLOR}, {V5, COLOR}, {V6, COLOR},
constexpr Vertex c_cubeVertices[] = {
{LBB, Black},
{LBF, Blue},
{LTB, Green},
{LTF, Yellow},
{RBB, Red},
{RBF, Purple},
{RTB, Brown},
{RTF, White},
};
constexpr unsigned short c_cubeIndices[] = {
2, 1, 0, // -x
2, 3, 1,
6, 4, 5, // +x
6, 5, 7,
0, 1, 5, // -y
0, 5, 4,
2, 6, 7, // +y
2, 7, 3,
0, 4, 6, // -z
0, 6, 2,
1, 3, 7, // +z
1, 7, 5,
};
struct ModelConstantBuffer {
DirectX::XMFLOAT4X4 Model;
};
struct ViewProjectionConstantBuffer {
DirectX::XMFLOAT4X4 ViewProjection[2];
};
struct ColorFilterConstantBuffer {
DirectX::XMFLOAT4 colorFilter;
};
constexpr uint32_t MaxViewInstance = 2;
// Separate entrypoints for the vertex and pixel shader functions.
constexpr char ShaderHlsl[] = R"_(
struct VSOutput {
float4 Pos : SV_POSITION;
float3 Color : COLOR0;
uint viewId : SV_RenderTargetArrayIndex;
};
struct VSInput {
float3 Pos : POSITION;
float3 Color : COLOR0;
uint instId : SV_InstanceID;
};
cbuffer ModelConstantBuffer : register(b0) {
float4x4 Model;
};
cbuffer ViewProjectionConstantBuffer : register(b1) {
float4x4 ViewProjection[2];
};
cbuffer ColorFilterConstantBuffer: register(b0) {
float4 colorFilter;
};
VSOutput MainVS(VSInput input) {
VSOutput output;
output.Pos = mul(mul(float4(input.Pos, 1), Model), ViewProjection[input.instId]);
output.Color = input.Color;
output.viewId = input.instId;
return output;
}
float4 MainPS(VSOutput input) : SV_TARGET {
return float4(input.Color, 1) * colorFilter;
}
)_";
} // namespace CubeShader
struct CubeGraphics : sample::IGraphicsPluginD3D11 {
ID3D11Device* InitializeDevice(LUID adapterLuid, const std::vector<D3D_FEATURE_LEVEL>& featureLevels) override {
const winrt::com_ptr<IDXGIAdapter1> adapter = sample::dx::GetAdapter(adapterLuid);
sample::dx::CreateD3D11DeviceAndContext(adapter.get(), featureLevels, m_device.put(), m_deviceContext.put());
InitializeD3DResources();
return m_device.get();
}
void InitializeD3DResources() {
const winrt::com_ptr<ID3DBlob> vertexShaderBytes = sample::dx::CompileShader(CubeShader::ShaderHlsl, "MainVS", "vs_5_0");
CHECK_HRCMD(m_device->CreateVertexShader(
vertexShaderBytes->GetBufferPointer(), vertexShaderBytes->GetBufferSize(), nullptr, m_vertexShader.put()));
const winrt::com_ptr<ID3DBlob> pixelShaderBytes = sample::dx::CompileShader(CubeShader::ShaderHlsl, "MainPS", "ps_5_0");
CHECK_HRCMD(m_device->CreatePixelShader(
pixelShaderBytes->GetBufferPointer(), pixelShaderBytes->GetBufferSize(), nullptr, m_pixelShader.put()));
const D3D11_INPUT_ELEMENT_DESC vertexDesc[] = {
{"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0},
{"COLOR", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0},
};
CHECK_HRCMD(m_device->CreateInputLayout(vertexDesc,
(UINT)std::size(vertexDesc),
vertexShaderBytes->GetBufferPointer(),
vertexShaderBytes->GetBufferSize(),
m_inputLayout.put()));
const CD3D11_BUFFER_DESC modelConstantBufferDesc(sizeof(CubeShader::ModelConstantBuffer), D3D11_BIND_CONSTANT_BUFFER);
CHECK_HRCMD(m_device->CreateBuffer(&modelConstantBufferDesc, nullptr, m_modelCBuffer.put()));
const CD3D11_BUFFER_DESC viewProjectionConstantBufferDesc(sizeof(CubeShader::ViewProjectionConstantBuffer),
D3D11_BIND_CONSTANT_BUFFER);
CHECK_HRCMD(m_device->CreateBuffer(&viewProjectionConstantBufferDesc, nullptr, m_viewProjectionCBuffer.put()));
const CD3D11_BUFFER_DESC colorFilterConstantBufferDesc(sizeof(CubeShader::ColorFilterConstantBuffer),
D3D11_BIND_CONSTANT_BUFFER);
CHECK_HRCMD(m_device->CreateBuffer(&colorFilterConstantBufferDesc, nullptr, m_colorFilterCBuffer.put()));
const D3D11_SUBRESOURCE_DATA vertexBufferData{CubeShader::c_cubeVertices};
const CD3D11_BUFFER_DESC vertexBufferDesc(sizeof(CubeShader::c_cubeVertices), D3D11_BIND_VERTEX_BUFFER);
CHECK_HRCMD(m_device->CreateBuffer(&vertexBufferDesc, &vertexBufferData, m_cubeVertexBuffer.put()));
const D3D11_SUBRESOURCE_DATA indexBufferData{CubeShader::c_cubeIndices};
const CD3D11_BUFFER_DESC indexBufferDesc(sizeof(CubeShader::c_cubeIndices), D3D11_BIND_INDEX_BUFFER);
CHECK_HRCMD(m_device->CreateBuffer(&indexBufferDesc, &indexBufferData, m_cubeIndexBuffer.put()));
D3D11_FEATURE_DATA_D3D11_OPTIONS3 options;
m_device->CheckFeatureSupport(D3D11_FEATURE_D3D11_OPTIONS3, &options, sizeof(options));
CHECK_MSG(options.VPAndRTArrayIndexFromAnyShaderFeedingRasterizer,
"This sample requires VPRT support. Adjust sample shaders on GPU without VRPT.");
CD3D11_DEPTH_STENCIL_DESC depthStencilDesc(CD3D11_DEFAULT{});
depthStencilDesc.DepthEnable = true;
depthStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
depthStencilDesc.DepthFunc = D3D11_COMPARISON_GREATER;
CHECK_HRCMD(m_device->CreateDepthStencilState(&depthStencilDesc, m_reversedZDepthNoStencilTest.put()));
}
const std::vector<DXGI_FORMAT>& SupportedColorFormats() const override {
const static std::vector<DXGI_FORMAT> SupportedColorFormats = {
DXGI_FORMAT_R8G8B8A8_UNORM,
DXGI_FORMAT_B8G8R8A8_UNORM,
DXGI_FORMAT_R8G8B8A8_UNORM_SRGB,
DXGI_FORMAT_B8G8R8A8_UNORM_SRGB,
};
return SupportedColorFormats;
}
const std::vector<DXGI_FORMAT>& SupportedDepthFormats() const override {
const static std::vector<DXGI_FORMAT> SupportedDepthFormats = {
DXGI_FORMAT_D32_FLOAT,
DXGI_FORMAT_D16_UNORM,
DXGI_FORMAT_D24_UNORM_S8_UINT,
DXGI_FORMAT_D32_FLOAT_S8X24_UINT,
};
return SupportedDepthFormats;
}
void RenderView(const XrRect2Di& imageRect,
const float renderTargetClearColor[4],
const std::vector<xr::math::ViewProjection>& viewProjections,
DXGI_FORMAT colorSwapchainFormat,
ID3D11Texture2D* colorTexture,
DXGI_FORMAT depthSwapchainFormat,
ID3D11Texture2D* depthTexture,
const std::vector<const sample::Cube*>& cubes) override {
const uint32_t viewInstanceCount = (uint32_t)viewProjections.size();
CHECK_MSG(viewInstanceCount <= CubeShader::MaxViewInstance,
"Sample shader supports 2 or fewer view instances. Adjust shader to accommodate more.")
CD3D11_VIEWPORT viewport(
(float)imageRect.offset.x, (float)imageRect.offset.y, (float)imageRect.extent.width, (float)imageRect.extent.height);
m_deviceContext->RSSetViewports(1, &viewport);
// Create RenderTargetView with the original swapchain format (swapchain image is typeless).
winrt::com_ptr<ID3D11RenderTargetView> renderTargetView;
const CD3D11_RENDER_TARGET_VIEW_DESC renderTargetViewDesc(D3D11_RTV_DIMENSION_TEXTURE2DARRAY, colorSwapchainFormat);
CHECK_HRCMD(m_device->CreateRenderTargetView(colorTexture, &renderTargetViewDesc, renderTargetView.put()));
// Create a DepthStencilView with the original swapchain format (swapchain image is typeless)
winrt::com_ptr<ID3D11DepthStencilView> depthStencilView;
CD3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc(D3D11_DSV_DIMENSION_TEXTURE2DARRAY, depthSwapchainFormat);
CHECK_HRCMD(m_device->CreateDepthStencilView(depthTexture, &depthStencilViewDesc, depthStencilView.put()));
const bool reversedZ = viewProjections[0].NearFar.Near > viewProjections[0].NearFar.Far;
const float depthClearValue = reversedZ ? 0.f : 1.f;
// Clear swapchain and depth buffer. NOTE: This will clear the entire render target view, not just the specified view.
m_deviceContext->ClearRenderTargetView(renderTargetView.get(), renderTargetClearColor);
m_deviceContext->ClearDepthStencilView(depthStencilView.get(), D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, depthClearValue, 0);
m_deviceContext->OMSetDepthStencilState(reversedZ ? m_reversedZDepthNoStencilTest.get() : nullptr, 0);
ID3D11RenderTargetView* renderTargets[] = {renderTargetView.get()};
m_deviceContext->OMSetRenderTargets((UINT)std::size(renderTargets), renderTargets, depthStencilView.get());
ID3D11Buffer* const vsConstantBuffers[] = {m_modelCBuffer.get(), m_viewProjectionCBuffer.get()};
m_deviceContext->VSSetConstantBuffers(0, (UINT)std::size(vsConstantBuffers), vsConstantBuffers);
m_deviceContext->VSSetShader(m_vertexShader.get(), nullptr, 0);
ID3D11Buffer* const psConstantBuffers[] = {m_colorFilterCBuffer.get()};
m_deviceContext->PSSetConstantBuffers(0, (UINT)std::size(psConstantBuffers), psConstantBuffers);
m_deviceContext->PSSetShader(m_pixelShader.get(), nullptr, 0);
CubeShader::ViewProjectionConstantBuffer viewProjectionCBufferData{};
for (uint32_t k = 0; k < viewInstanceCount; k++) {
const DirectX::XMMATRIX spaceToView = xr::math::LoadInvertedXrPose(viewProjections[k].Pose);
const DirectX::XMMATRIX projectionMatrix = ComposeProjectionMatrix(viewProjections[k].Fov, viewProjections[k].NearFar);
// Set view projection matrix for each view, transpose for shader usage.
DirectX::XMStoreFloat4x4(&viewProjectionCBufferData.ViewProjection[k],
DirectX::XMMatrixTranspose(spaceToView * projectionMatrix));
}
m_deviceContext->UpdateSubresource(m_viewProjectionCBuffer.get(), 0, nullptr, &viewProjectionCBufferData, 0, 0);
// Set cube primitive data.
const UINT strides[] = {sizeof(CubeShader::Vertex)};
const UINT offsets[] = {0};
ID3D11Buffer* vertexBuffers[] = {m_cubeVertexBuffer.get()};
m_deviceContext->IASetVertexBuffers(0, (UINT)std::size(vertexBuffers), vertexBuffers, strides, offsets);
m_deviceContext->IASetIndexBuffer(m_cubeIndexBuffer.get(), DXGI_FORMAT_R16_UINT, 0);
m_deviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
m_deviceContext->IASetInputLayout(m_inputLayout.get());
// Render each cube
for (const sample::Cube* cube : cubes) {
// Compute and update the model transform for each cube, transpose for shader usage.
CubeShader::ModelConstantBuffer model;
const DirectX::XMMATRIX scaleMatrix = DirectX::XMMatrixScaling(cube->Scale.x, cube->Scale.y, cube->Scale.z);
DirectX::XMStoreFloat4x4(&model.Model,
DirectX::XMMatrixTranspose(scaleMatrix * xr::math::LoadXrPose(cube->PoseInAppSpace)));
m_deviceContext->UpdateSubresource(m_modelCBuffer.get(), 0, nullptr, &model, 0, 0);
CubeShader::ColorFilterConstantBuffer color;
color.colorFilter = DirectX::XMFLOAT4(cube->colorFilter.x, cube->colorFilter.y, cube->colorFilter.z, 1.0f);
m_deviceContext->UpdateSubresource(m_colorFilterCBuffer.get(), 0, nullptr, &color, 0, 0);
// Draw the cube.
m_deviceContext->DrawIndexedInstanced((UINT)std::size(CubeShader::c_cubeIndices), viewInstanceCount, 0, 0, 0);
}
}
void ClearView(ID3D11Texture2D* colorTexture, const float renderTargetClearColor[4]) override {
winrt::com_ptr<ID3D11RenderTargetView> renderTargetView;
CHECK_HRCMD(m_device->CreateRenderTargetView(colorTexture, nullptr, renderTargetView.put()));
m_deviceContext->ClearRenderTargetView(renderTargetView.get(), renderTargetClearColor);
}
private:
winrt::com_ptr<ID3D11Device> m_device;
winrt::com_ptr<ID3D11DeviceContext> m_deviceContext;
winrt::com_ptr<ID3D11VertexShader> m_vertexShader;
winrt::com_ptr<ID3D11PixelShader> m_pixelShader;
winrt::com_ptr<ID3D11InputLayout> m_inputLayout;
winrt::com_ptr<ID3D11Buffer> m_modelCBuffer;
winrt::com_ptr<ID3D11Buffer> m_viewProjectionCBuffer;
winrt::com_ptr<ID3D11Buffer> m_colorFilterCBuffer;
winrt::com_ptr<ID3D11Buffer> m_cubeVertexBuffer;
winrt::com_ptr<ID3D11Buffer> m_cubeIndexBuffer;
winrt::com_ptr<ID3D11DepthStencilState> m_reversedZDepthNoStencilTest;
};
} // namespace
namespace sample {
std::unique_ptr<sample::IGraphicsPluginD3D11> CreateCubeGraphics() {
return std::make_unique<CubeGraphics>();
}
} // namespace sample
| 49.848297 | 136 | 0.631327 | [
"render",
"vector",
"model",
"transform"
] |
c806be32679e9cf3c95bfebcc87c7d190f7b96ad | 9,776 | cpp | C++ | Source/OpenNI/Win32/XnOSWin32.cpp | Dianpeng-Wang/kinect-1 | 1e9524ffd759841789dadb4ca19fb5d4ac5820e7 | [
"Apache-2.0"
] | 631 | 2015-01-03T18:48:10.000Z | 2022-03-28T06:20:35.000Z | Source/OpenNI/Win32/XnOSWin32.cpp | Dianpeng-Wang/kinect-1 | 1e9524ffd759841789dadb4ca19fb5d4ac5820e7 | [
"Apache-2.0"
] | 41 | 2015-01-03T01:37:56.000Z | 2021-12-22T09:41:25.000Z | Source/OpenNI/Win32/XnOSWin32.cpp | Dianpeng-Wang/kinect-1 | 1e9524ffd759841789dadb4ca19fb5d4ac5820e7 | [
"Apache-2.0"
] | 343 | 2015-01-04T11:10:21.000Z | 2022-03-25T17:11:58.000Z | /*****************************************************************************
* *
* OpenNI 1.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 <XnOS.h>
#include <XnLog.h>
#ifdef __INTEL_COMPILER
#include <ia32intrin.h>
#else
#include <intrin.h>
#endif
//---------------------------------------------------------------------------
// Code
//---------------------------------------------------------------------------
static const XnChar* GetOSName(OSVERSIONINFOEX& osVersionInfo)
{
if (osVersionInfo.dwMajorVersion == 4)
{
// Windows NT
switch (osVersionInfo.wProductType)
{
case VER_NT_WORKSTATION:
return "Windows NT 4.0 Workstation";
case VER_NT_SERVER:
case VER_NT_DOMAIN_CONTROLLER:
return "Windows NT 4.0 Server";
default:
return "Unknown Windows NT 4.0 version";
}
}
else if (osVersionInfo.dwMajorVersion == 5 && osVersionInfo.dwMinorVersion == 0)
{
// Windows 2000
switch (osVersionInfo.wProductType)
{
case VER_NT_WORKSTATION:
return "Windows 2000 Professional";
case VER_NT_SERVER:
case VER_NT_DOMAIN_CONTROLLER:
if ((osVersionInfo.wSuiteMask & VER_SUITE_DATACENTER) == VER_SUITE_DATACENTER)
return "Windows 2000 Datacenter Server";
else if ((osVersionInfo.wSuiteMask & VER_SUITE_ENTERPRISE) == VER_SUITE_ENTERPRISE)
return "Windows 2000 Advanced Server";
else
return "Windows 2000 Server";
default:
return "Unknown Windows 2000 version";
}
}
else if (osVersionInfo.dwMajorVersion == 5 && osVersionInfo.dwMinorVersion == 1)
{
// Windows XP.
if (0 != GetSystemMetrics(SM_TABLETPC))
return "Windows XP Tablet PC Edition";
else if (0 != GetSystemMetrics(SM_STARTER))
return "Windows XP Starter Edition";
else if (0 != GetSystemMetrics(SM_MEDIACENTER))
return "Windows XP Media Center Edition";
else if ((osVersionInfo.wSuiteMask & VER_SUITE_PERSONAL) == VER_SUITE_PERSONAL)
return "Windows XP Home Edition";
else
return "Windows XP Professional";
}
else if (osVersionInfo.dwMajorVersion == 5 && osVersionInfo.dwMinorVersion == 2)
{
// Windows Server 2003
if((osVersionInfo.wSuiteMask & VER_SUITE_DATACENTER) == VER_SUITE_DATACENTER)
return "Windows Server 2003 Datacenter Edition";
else if((osVersionInfo.wSuiteMask & VER_SUITE_ENTERPRISE) == VER_SUITE_ENTERPRISE)
return "Windows Server 2003 Enterprise Edition";
else if((osVersionInfo.wSuiteMask & VER_SUITE_BLADE) == VER_SUITE_BLADE)
return "Windows Server 2003 Web Edition";
else
return "Windows Server 2003 Standard Edition";
}
else if (osVersionInfo.dwMajorVersion == 6 && osVersionInfo.dwMinorVersion == 0)
{
// Windows Vista / Server 2008
switch (osVersionInfo.wProductType)
{
case VER_NT_WORKSTATION:
// Vista
return "Windows Vista";
case VER_NT_SERVER:
case VER_NT_DOMAIN_CONTROLLER:
return "Windows Server 2008";
default:
return "Unknown Windows 6.0 version";
}
}
else if (osVersionInfo.dwMajorVersion == 6 && osVersionInfo.dwMinorVersion == 1)
{
// Windows 7 / Server 2008 R2
if (osVersionInfo.wProductType != VER_NT_WORKSTATION)
{
return ("Windows Server 2008 R2");
}
else
{
return ("Windows 7");
}
}
else if (osVersionInfo.dwMajorVersion == 6 && osVersionInfo.dwMinorVersion == 2)
{
// Windows 8 / Server 2012
if (osVersionInfo.wProductType != VER_NT_WORKSTATION)
{
return ("Windows Server 2012");
}
else
{
return ("Windows 8");
}
}
return "Unknown Windows Version";
}
static void GetCPUName(XnChar* csName)
{
int CPUInfo[4] = {-1};
xnOSMemSet(csName, 0, XN_MAX_OS_NAME_LENGTH);
// calling cpuid with 0x80000000 retrives the number of extended properties
__cpuid(CPUInfo, 0x80000000);
unsigned int nExIds = CPUInfo[0];
if (nExIds >= 0x80000002)
{
__cpuid(CPUInfo, 0x80000002);
xnOSMemCopy(csName, CPUInfo, sizeof(CPUInfo));
}
if (nExIds >= 0x80000003)
{
__cpuid(CPUInfo, 0x80000003);
xnOSMemCopy(csName + 16, CPUInfo, sizeof(CPUInfo));
}
if (nExIds >= 0x80000004)
{
__cpuid(CPUInfo, 0x80000004);
xnOSMemCopy(csName + 32, CPUInfo, sizeof(CPUInfo));
}
if (nExIds > 0x80000002)
return;
// else, we need to build the name ourselves
xnOSMemSet(CPUInfo, 0xFF, sizeof(CPUInfo));
__cpuid(CPUInfo, 0);
int nIds = CPUInfo[0];
*((int*)csName) = CPUInfo[1];
*((int*)(csName+4)) = CPUInfo[3];
*((int*)(csName+8)) = CPUInfo[2];
if (nIds >= 1)
{
__cpuid(CPUInfo, 1);
int nSteppingID = CPUInfo[0] & 0xf;
int nModel = (CPUInfo[0] >> 4) & 0xf;
int nFamily = (CPUInfo[0] >> 8) & 0xf;
//int nProcessorType = (CPUInfo[0] >> 12) & 0x3;
//int nExtendedmodel = (CPUInfo[0] >> 16) & 0xf;
//int nExtendedfamily = (CPUInfo[0] >> 20) & 0xff;
//int nBrandIndex = CPUInfo[1] & 0xff;
sprintf(csName+strlen(csName), " Model: %d Family: %d Stepping: %d", nModel, nFamily, nSteppingID);
}
}
XN_C_API XnStatus xnOSGetInfo(xnOSInfo* pOSInfo)
{
// Validate input/output arguments
XN_VALIDATE_OUTPUT_PTR(pOSInfo);
// Get OS Info
OSVERSIONINFOEX osVersionInfo;
osVersionInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
if (0 == GetVersionEx((LPOSVERSIONINFO)&osVersionInfo))
{
DWORD nErr = GetLastError();
xnLogWarning(XN_MASK_OS, "Failed getting OS version information. Error code: %d", nErr);
return XN_STATUS_ERROR;
}
sprintf(pOSInfo->csOSName, "%s", GetOSName(osVersionInfo));
if (osVersionInfo.szCSDVersion[0] != '\0')
{
strcat(pOSInfo->csOSName, " ");
strcat(pOSInfo->csOSName, osVersionInfo.szCSDVersion);
}
// Get CPU Info
GetCPUName(pOSInfo->csCPUName);
SYSTEM_INFO systemInfo;
GetSystemInfo(&systemInfo);
pOSInfo->nProcessorsCount = systemInfo.dwNumberOfProcessors;
// Get Memory Info
MEMORYSTATUSEX memoryStatus;
memoryStatus.dwLength = sizeof(memoryStatus);
if (0 == GlobalMemoryStatusEx(&memoryStatus))
{
DWORD nErr = GetLastError();
xnLogWarning(XN_MASK_OS, "Failed getting Memory information. Error code: %d", nErr);
return XN_STATUS_ERROR;
}
pOSInfo->nTotalMemory = memoryStatus.ullTotalPhys;
return (XN_STATUS_OK);
}
XnStatus XnWin32CreateKernelObjectName(XnChar* strDest, const XnUInt32 nDestLength, const XnChar* strSource, XnBool bAllowOtherUsers)
{
XnChar* pDest = strDest;
XnChar* pDestEnd = strDest + nDestLength;
if (bAllowOtherUsers)
{
static const XnChar strGlobal[] = "Global\\";
strcpy(strDest, strGlobal);
pDest = strDest + sizeof(strGlobal) - 1;
}
const XnChar* pSource = strSource;
while (pDest < pDestEnd && *pSource != '\0')
{
*pDest = *pSource == '\\' ? '_' : *pSource;
++pDest;
++pSource;
}
if (pDest == pDestEnd)
{
xnLogWarning(XN_MASK_OS, "Event name is too long!");
return XN_STATUS_ERROR;
}
*pDest = '\0';
return (XN_STATUS_OK);
}
XnStatus XnWin32GetSecurityAttributes(XnBool bAllowOtherUsers, SECURITY_ATTRIBUTES** ppSecurityAttributes)
{
*ppSecurityAttributes = NULL;
static SECURITY_DESCRIPTOR securityDesc;
static SECURITY_ATTRIBUTES securityAttributes;
static SECURITY_ATTRIBUTES* pSecurityAttributes = NULL;
if (pSecurityAttributes == NULL)
{
// initialize it now
if (FALSE == InitializeSecurityDescriptor(&securityDesc, SECURITY_DESCRIPTOR_REVISION))
{
xnLogError(XN_MASK_OS, "Failed to initialize security descriptor (%d)", GetLastError());
return XN_STATUS_ERROR;
}
if (FALSE == SetSecurityDescriptorDacl(&securityDesc, TRUE, NULL, FALSE))
{
xnLogError(XN_MASK_OS, "Failed to set security descriptor DACL (%d)", GetLastError());
return XN_STATUS_ERROR;
}
securityAttributes.nLength = sizeof(SECURITY_ATTRIBUTES);
securityAttributes.lpSecurityDescriptor = &securityDesc;
securityAttributes.bInheritHandle = FALSE;
// initialization complete. Store a pointer
pSecurityAttributes = &securityAttributes;
}
*ppSecurityAttributes = bAllowOtherUsers ? pSecurityAttributes : NULL;
return (XN_STATUS_OK);
}
| 31.947712 | 134 | 0.601473 | [
"model"
] |
c808333410049e04e671383758ad57dd91b7f72d | 10,199 | cc | C++ | cvmfs/receiver/commit_processor.cc | egede/cvmfs | 168cdbeeec9dabd1898d4ab7964cb3b9f63cfcd7 | [
"BSD-3-Clause"
] | null | null | null | cvmfs/receiver/commit_processor.cc | egede/cvmfs | 168cdbeeec9dabd1898d4ab7964cb3b9f63cfcd7 | [
"BSD-3-Clause"
] | null | null | null | cvmfs/receiver/commit_processor.cc | egede/cvmfs | 168cdbeeec9dabd1898d4ab7964cb3b9f63cfcd7 | [
"BSD-3-Clause"
] | null | null | null | /**
* This file is part of the CernVM File System.
*/
#include "commit_processor.h"
#include <vector>
#include "catalog_diff_tool.h"
#include "catalog_merge_tool.h"
#include "catalog_mgr_ro.h"
#include "catalog_mgr_rw.h"
#include "compression.h"
#include "download.h"
#include "logging.h"
#include "manifest.h"
#include "manifest_fetch.h"
#include "params.h"
#include "signing_tool.h"
#include "statistics.h"
#include "swissknife.h"
#include "swissknife_history.h"
#include "util/algorithm.h"
#include "util/pointer.h"
#include "util/posix.h"
#include "util/raii_temp_dir.h"
#include "util/string.h"
namespace {
PathString RemoveRepoName(const PathString& lease_path) {
std::string abs_path = lease_path.ToString();
std::string::const_iterator it =
std::find(abs_path.begin(), abs_path.end(), '/');
if (it != abs_path.end()) {
size_t idx = it - abs_path.begin() + 1;
return lease_path.Suffix(idx);
} else {
return lease_path;
}
}
bool CreateNewTag(const RepositoryTag& repo_tag, const std::string& repo_name,
const receiver::Params& params, const std::string& temp_dir,
const std::string& manifest_path,
const std::string& public_key_path) {
swissknife::ArgumentList args;
args['r'].Reset(new std::string(params.spooler_configuration));
args['w'].Reset(new std::string(params.stratum0));
args['t'].Reset(new std::string(temp_dir));
args['m'].Reset(new std::string(manifest_path));
args['p'].Reset(new std::string(public_key_path));
args['f'].Reset(new std::string(repo_name));
args['e'].Reset(new std::string(params.hash_alg_str));
args['a'].Reset(new std::string(repo_tag.name_));
args['c'].Reset(new std::string(repo_tag.channel_));
args['D'].Reset(new std::string(repo_tag.description_));
args['x'].Reset(new std::string());
UniquePtr<swissknife::CommandEditTag> edit_cmd(
new swissknife::CommandEditTag());
const int ret = edit_cmd->Main(args);
if (ret) {
LogCvmfs(kLogReceiver, kLogSyslogErr, "Error %d creating tag: %s", ret,
repo_tag.name_.c_str());
return false;
}
return true;
}
} // namespace
namespace receiver {
CommitProcessor::CommitProcessor() : num_errors_(0) {}
CommitProcessor::~CommitProcessor() {}
/**
* Applies the changes from the new catalog onto the repository.
*
* Let:
* + C_O = the root catalog of the repository (given by old_root_hash) at
* the beginning of the lease, on the release manager machine
* + C_N = the root catalog of the repository (given by new_root_hash), on
* the release manager machine, with the changes introduced during the
* lease
* + C_G = the current root catalog of the repository on the gateway machine.
*
* This method applies all the changes from C_N, with respect to C_O, onto C_G.
* The resulting catalog on the gateway machine (C_GN) is then set as root
* catalog in the repository manifest. The method also signes the updated
* repository manifest.
*/
CommitProcessor::Result CommitProcessor::Process(
const std::string& lease_path, const shash::Any& old_root_hash,
const shash::Any& new_root_hash, const RepositoryTag& tag) {
RepositoryTag final_tag = tag;
// If tag_name is a generic tag, update the time stamp
if (HasPrefix(final_tag.name_, "generic-", false)) {
// timestamp=$(date -u "+%Y-%m-%dT%H:%M:%SZ")
char buf[32];
time_t now = time(NULL);
struct tm timestamp;
gmtime_r(&now, ×tamp);
strftime(buf, sizeof(buf), "%Y-%m-%dT%H:%M:%SZ", ×tamp);
final_tag.name_ = std::string("generic-") + buf;
}
LogCvmfs(kLogReceiver, kLogSyslog,
"CommitProcessor - lease_path: %s, old hash: %s, new hash: %s, "
"tag_name: %s, tag_channel: %s, tag_description: %s",
lease_path.c_str(), old_root_hash.ToString(true).c_str(),
new_root_hash.ToString(true).c_str(), final_tag.name_.c_str(),
final_tag.channel_.c_str(), final_tag.description_.c_str());
const std::vector<std::string> lease_path_tokens =
SplitString(lease_path, '/');
const std::string repo_name = lease_path_tokens.front();
Params params;
if (!GetParamsFromFile(repo_name, ¶ms)) {
LogCvmfs(
kLogReceiver, kLogSyslogErr,
"CommitProcessor - error: Could not get configuration parameters.");
return kError;
}
UniquePtr<ServerTool> server_tool(new ServerTool());
if (!server_tool->InitDownloadManager(true)) {
LogCvmfs(
kLogReceiver, kLogSyslogErr,
"CommitProcessor - error: Could not initialize the download manager");
return kError;
}
const std::string public_key = "/etc/cvmfs/keys/" + repo_name + ".pub";
const std::string trusted_certs =
"/etc/cvmfs/repositories.d/" + repo_name + "/trusted_certs";
if (!server_tool->InitVerifyingSignatureManager(public_key, trusted_certs)) {
LogCvmfs(
kLogReceiver, kLogSyslogErr,
"CommitProcessor - error: Could not initialize the signature manager");
return kError;
}
shash::Any manifest_base_hash;
UniquePtr<manifest::Manifest> manifest(server_tool->FetchRemoteManifest(
params.stratum0, repo_name, manifest_base_hash));
// Current catalog from the gateway machine
if (!manifest.IsValid()) {
LogCvmfs(kLogReceiver, kLogSyslogErr,
"CommitProcessor - error: Could not open repository manifest");
return kError;
}
LogCvmfs(kLogReceiver, kLogSyslog,
"CommitProcessor - lease_path: %s, target root hash: %s",
lease_path.c_str(),
manifest->catalog_hash().ToString(false).c_str());
const std::string spooler_temp_dir =
GetSpoolerTempDir(params.spooler_configuration);
assert(!spooler_temp_dir.empty());
assert(MkdirDeep(spooler_temp_dir + "/receiver", 0666, true));
const std::string temp_dir_root =
spooler_temp_dir + "/receiver/commit_processor";
const PathString relative_lease_path = RemoveRepoName(PathString(lease_path));
LogCvmfs(kLogReceiver, kLogSyslog,
"CommitProcessor - lease_path: %s, merging catalogs",
lease_path.c_str());
CatalogMergeTool<catalog::WritableCatalogManager,
catalog::SimpleCatalogManager>
merge_tool(params.stratum0, old_root_hash, new_root_hash,
relative_lease_path, temp_dir_root,
server_tool->download_manager(), manifest.weak_ref());
if (!merge_tool.Init()) {
LogCvmfs(kLogReceiver, kLogSyslogErr,
"Error: Could not initialize the catalog merge tool");
return kError;
}
std::string new_manifest_path;
if (!merge_tool.Run(params, &new_manifest_path)) {
LogCvmfs(kLogReceiver, kLogSyslogErr,
"CommitProcessor - error: Catalog merge failed");
return kMergeFailure;
}
UniquePtr<RaiiTempDir> raii_temp_dir(RaiiTempDir::Create(temp_dir_root));
const std::string temp_dir = raii_temp_dir->dir();
const std::string certificate = "/etc/cvmfs/keys/" + repo_name + ".crt";
const std::string private_key = "/etc/cvmfs/keys/" + repo_name + ".key";
if (!CreateNewTag(final_tag, repo_name, params, temp_dir, new_manifest_path,
public_key)) {
LogCvmfs(kLogReceiver, kLogSyslogErr, "Error creating tag: %s",
final_tag.name_.c_str());
return kError;
}
// We need to re-initialize the ServerTool component for signing
server_tool.Destroy();
server_tool = new ServerTool();
LogCvmfs(kLogReceiver, kLogSyslog,
"CommitProcessor - lease_path: %s, signing manifest",
lease_path.c_str());
SigningTool signing_tool(server_tool.weak_ref());
SigningTool::Result res = signing_tool.Run(
new_manifest_path, params.stratum0, params.spooler_configuration,
temp_dir, certificate, private_key, repo_name, "", "",
"/var/spool/cvmfs/" + repo_name + "/reflog.chksum",
params.garbage_collection);
switch (res) {
case SigningTool::kReflogChecksumMissing:
LogCvmfs(kLogReceiver, kLogSyslogErr,
"CommitProcessor - error: missing reflog.chksum");
return kMissingReflog;
case SigningTool::kReflogMissing:
LogCvmfs(kLogReceiver, kLogSyslogErr,
"CommitProcessor - error: missing reflog");
return kMissingReflog;
case SigningTool::kError:
case SigningTool::kInitError:
LogCvmfs(kLogReceiver, kLogSyslogErr,
"CommitProcessor - error: signing manifest");
return kError;
case SigningTool::kSuccess:
LogCvmfs(kLogReceiver, kLogSyslog,
"CommitProcessor - lease_path: %s, success.",
lease_path.c_str());
}
{
UniquePtr<ServerTool> server_tool(new ServerTool());
if (!server_tool->InitDownloadManager(true)) {
LogCvmfs(
kLogReceiver, kLogSyslogErr,
"CommitProcessor - error: Could not initialize the download manager");
return kError;
}
const std::string public_key = "/etc/cvmfs/keys/" + repo_name + ".pub";
const std::string trusted_certs =
"/etc/cvmfs/repositories.d/" + repo_name + "/trusted_certs";
if (!server_tool->InitVerifyingSignatureManager(public_key,
trusted_certs)) {
LogCvmfs(kLogReceiver, kLogSyslogErr,
"CommitProcessor - error: Could not initialize the signature "
"manager");
return kError;
}
shash::Any manifest_base_hash;
UniquePtr<manifest::Manifest> manifest(server_tool->FetchRemoteManifest(
params.stratum0, repo_name, manifest_base_hash));
LogCvmfs(kLogReceiver, kLogSyslog,
"CommitProcessor - lease_path: %s, new root hash: %s",
lease_path.c_str(),
manifest->catalog_hash().ToString(false).c_str());
}
// Ensure CVMFS_ROOT_HASH is not set in
// /var/spool/cvmfs/<REPO_NAME>/client.local
const std::string fname = "/var/spool/cvmfs/" + repo_name + "/client.local";
if (truncate(fname.c_str(), 0) < 0) {
LogCvmfs(kLogReceiver, kLogSyslogErr, "Could not truncate %s\n",
fname.c_str());
return kError;
}
return kSuccess;
}
} // namespace receiver
| 35.413194 | 80 | 0.674674 | [
"vector"
] |
c8084f3e69d6e17b564b8587f98c44a2c0dcdcbf | 5,910 | hpp | C++ | setcoveringsolver/solution.hpp | fontanf/setcoveringsolver | e43ca8c2d0244fe489d643525d26674e05301fa6 | [
"MIT"
] | 5 | 2020-12-27T14:11:34.000Z | 2022-02-16T00:43:34.000Z | setcoveringsolver/solution.hpp | fontanf/setcoveringsolver | e43ca8c2d0244fe489d643525d26674e05301fa6 | [
"MIT"
] | 1 | 2021-06-29T04:34:42.000Z | 2021-06-29T07:51:53.000Z | setcoveringsolver/solution.hpp | fontanf/setcoveringsolver | e43ca8c2d0244fe489d643525d26674e05301fa6 | [
"MIT"
] | 1 | 2020-11-16T11:53:35.000Z | 2020-11-16T11:53:35.000Z | #pragma once
#include "setcoveringsolver/instance.hpp"
#include "optimizationtools/indexed_set.hpp"
#include "optimizationtools/indexed_map.hpp"
#include <functional>
namespace setcoveringsolver
{
class Solution
{
public:
/*
* Constructors and destructor.
*/
/** Create an empty solution. */
Solution(const Instance& instance);
/** Create a solution from a certificate file. */
Solution(const Instance& instance, std::string certificate_path);
/** Copy constructor. */
Solution(const Solution& solution);
/** Copy assignment operator. */
Solution& operator=(const Solution& solution);
/** Destructor. */
~Solution() { }
/*
* Getters.
*/
/** Get the instance. */
inline const Instance& instance() const { return instance_; }
/** Get the number of covered elements. */
inline ElementId number_of_elements() const { return elements_.size(); }
/** Get the number of covered elements in component 'c'. */
inline ElementId number_of_elements(ComponentId c) const { return component_number_of_elements_[c]; }
/** Get the number of uncovered elements. */
inline ElementId number_of_uncovered_elements() const { return instance().number_of_elements() - number_of_elements(); }
/** Get the number of sets in the solution. */
inline SetId number_of_sets() const { return sets_.size(); }
/** Get the total cost of the sets of component 'c'. */
inline Cost cost(ComponentId c) const { return component_costs_[c]; }
/** Get the total cost of the solution. */
inline Cost cost() const { return cost_; }
/** Return 'true' iff element 'e' is covered in the solution. */
inline SetId covers(ElementId e) const { return elements_[e]; }
/** Return 'true' iff the solution contains set 's'. */
inline bool contains(SetId s) const { assert(s >= 0); assert(s < instance().number_of_sets()); return sets_.contains(s); }
/** Return 'true' iff the solution is feasible. */
inline bool feasible() const { return number_of_elements() == instance().number_of_elements(); }
/** Return 'true' iff the solution is feasible for component 'c'. */
inline bool feasible(ComponentId c) const { return number_of_elements(c) == instance().number_of_elements(c); }
/** Get the set of elements of the solution. */
const optimizationtools::IndexedMap<SetPos>& elements() const { return elements_; };
/** Get the set of sets of the solution. */
const optimizationtools::IndexedSet& sets() const { return sets_; };
/*
* Setters.
*/
/** Add set 's' to the solution. */
inline void add(SetId s);
/** Remove set 's' from the solution. */
inline void remove(SetId s);
/*
* Export.
*/
/** Write the solution to a file. */
void write(std::string certificate_path);
private:
/*
* Private attributes.
*/
/** Instance. */
const Instance& instance_;
/** Elements. */
optimizationtools::IndexedMap<SetPos> elements_;
/** Sets. */
optimizationtools::IndexedSet sets_;
/** Number of elements in each component. */
std::vector<ElementPos> component_number_of_elements_;
/** Cost of each component. */
std::vector<Cost> component_costs_;
/** Total cost of the solution. */
Cost cost_ = 0;
};
void Solution::add(SetId s)
{
// Checks.
instance().check_set_index(s);
if (contains(s))
throw std::invalid_argument(
"Cannot add set " + std::to_string(s)
+ " which is already in the solution");
ComponentId c = instance().set(s).component;
for (ElementId e: instance().set(s).elements) {
if (covers(e) == 0)
component_number_of_elements_[c]++;
elements_.set(e, elements_[e] + 1);
}
sets_.add(s);
component_costs_[c] += instance().set(s).cost;
cost_ += instance().set(s).cost;
}
void Solution::remove(SetId s)
{
// Checks.
instance().check_set_index(s);
if (!contains(s))
throw std::invalid_argument(
"Cannot remove set " + std::to_string(s)
+ " which is not in the solution");
ComponentId c = instance().set(s).component;
for (ElementId e: instance().set(s).elements) {
elements_.set(e, elements_[e] - 1);
if (covers(e) == 0)
component_number_of_elements_[c]--;
}
sets_.remove(s);
component_costs_[c] -= instance().set(s).cost;
cost_ -= instance().set(s).cost;
}
std::ostream& operator<<(std::ostream& os, const Solution& solution);
/*********************************** Output ***********************************/
struct Output
{
Output(
const Instance& instance,
optimizationtools::Info& info);
Solution solution;
Cost lower_bound = 0;
double time = -1;
bool optimal() const { return solution.feasible() && solution.cost() == lower_bound; }
Cost upper_bound() const { return (solution.feasible())? solution.cost(): solution.instance().total_cost(); }
double gap() const;
void print(
optimizationtools::Info& info,
const std::stringstream& s) const;
void update_solution(
const Solution& solution_new,
const std::stringstream& s,
optimizationtools::Info& info)
{
update_solution(solution_new, -1, s, info);
}
void update_solution(
const Solution& solution_new,
ComponentId c,
const std::stringstream& s,
optimizationtools::Info& info);
void update_lower_bound(
Cost lower_bound_new,
const std::stringstream& s,
optimizationtools::Info& info);
Output& algorithm_end(optimizationtools::Info& info);
};
Cost algorithm_end(
Cost lower_bound,
optimizationtools::Info& info);
}
| 31.105263 | 126 | 0.617259 | [
"vector"
] |
c80a1e6915508af4f9e5f655569dffa0db842508 | 2,252 | hpp | C++ | libff/algebra/fields/field_utils.hpp | p0n1/libff | 501dfd8abd25e400965926274b1c1bb6d20e9bc9 | [
"MIT"
] | null | null | null | libff/algebra/fields/field_utils.hpp | p0n1/libff | 501dfd8abd25e400965926274b1c1bb6d20e9bc9 | [
"MIT"
] | null | null | null | libff/algebra/fields/field_utils.hpp | p0n1/libff | 501dfd8abd25e400965926274b1c1bb6d20e9bc9 | [
"MIT"
] | 1 | 2019-07-10T09:31:25.000Z | 2019-07-10T09:31:25.000Z | /** @file
*****************************************************************************
* @author This file is part of libff, developed by SCIPR Lab
* and contributors (see AUTHORS).
* @copyright MIT license (see LICENSE file)
*****************************************************************************/
#ifndef FIELD_UTILS_HPP_
#define FIELD_UTILS_HPP_
#include <cstdint>
#include <libff/algebra/fields/bigint.hpp>
#include <libff/common/double.hpp>
#include <libff/common/utils.hpp>
namespace libff {
// returns root of unity of order n (for n a power of 2), if one exists
template<typename FieldT>
typename std::enable_if<std::is_same<FieldT, Double>::value, FieldT>::type
get_root_of_unity(const size_t n);
template<typename FieldT>
typename std::enable_if<!std::is_same<FieldT, Double>::value, FieldT>::type
get_root_of_unity(const size_t n);
template<typename FieldT>
typename std::enable_if<std::is_same<FieldT, Double>::value, FieldT>::type
get_root_of_unity2(const size_t n, bool* success);
template<typename FieldT>
typename std::enable_if<!std::is_same<FieldT, Double>::value, FieldT>::type
get_root_of_unity2(const size_t n, bool* success);
template<typename FieldT>
std::vector<FieldT> pack_int_vector_into_field_element_vector(const std::vector<size_t> &v, const size_t w);
template<typename FieldT>
std::vector<FieldT> pack_bit_vector_into_field_element_vector(const bit_vector &v, const size_t chunk_bits);
template<typename FieldT>
std::vector<FieldT> pack_bit_vector_into_field_element_vector(const bit_vector &v);
template<typename FieldT>
std::vector<FieldT> convert_bit_vector_to_field_element_vector(const bit_vector &v);
template<typename FieldT>
bit_vector convert_field_element_vector_to_bit_vector(const std::vector<FieldT> &v);
template<typename FieldT>
bit_vector convert_field_element_to_bit_vector(const FieldT &el);
template<typename FieldT>
bit_vector convert_field_element_to_bit_vector(const FieldT &el, const size_t bitcount);
template<typename FieldT>
FieldT convert_bit_vector_to_field_element(const bit_vector &v);
template<typename FieldT>
void batch_invert(std::vector<FieldT> &vec);
} // libff
#include <libff/algebra/fields/field_utils.tcc>
#endif // FIELD_UTILS_HPP_
| 34.121212 | 108 | 0.738011 | [
"vector"
] |
c80b1eb5bb5586f064a3309d30dce031c0244f8f | 25,658 | cpp | C++ | src/InteractiveMarkerViewer.cpp | personalrobotics/or_interactivemarker | 742d3d0ac5e606e35a1717a1e8b2a5f69e8efb8e | [
"BSD-2-Clause"
] | 6 | 2015-01-15T16:04:30.000Z | 2018-12-24T19:14:09.000Z | src/InteractiveMarkerViewer.cpp | UM-ARM-Lab/or_rviz | 742d3d0ac5e606e35a1717a1e8b2a5f69e8efb8e | [
"BSD-2-Clause"
] | 34 | 2015-01-05T19:41:30.000Z | 2020-08-25T09:49:51.000Z | src/InteractiveMarkerViewer.cpp | personalrobotics/or_interactivemarker | 742d3d0ac5e606e35a1717a1e8b2a5f69e8efb8e | [
"BSD-2-Clause"
] | 7 | 2017-01-16T20:23:02.000Z | 2021-02-19T14:19:19.000Z | /***********************************************************************
Copyright (c) 2015, Carnegie Mellon University
All rights reserved.
Authors: Michael Koval <mkoval@cs.cmu.edu>
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 <boost/format.hpp>
#include <boost/make_shared.hpp>
#include <boost/algorithm/string/trim.hpp>
#include <interactive_markers/interactive_marker_server.h>
#include "util/ScopedConnection.h"
#include "util/ros_conversions.h"
#include "InteractiveMarkerViewer.h"
using boost::format;
using boost::str;
using interactive_markers::InteractiveMarkerServer;
using visualization_msgs::InteractiveMarker;
using visualization_msgs::InteractiveMarkerPtr;
using OpenRAVE::KinBodyPtr;
using OpenRAVE::GraphHandlePtr;
using namespace or_rviz::markers;
using namespace or_rviz::util;
typedef boost::shared_ptr<interactive_markers::InteractiveMarkerServer> InteractiveMarkerServerPtr;
static double const kRefreshRate = 30;
static double const kWidthScaleFactor = 100;
namespace or_rviz {
namespace {
std::string GetRemainingContent(std::istream &stream, bool trim = false)
{
std::istreambuf_iterator<char> eos;
std::string str(std::istreambuf_iterator<char>(stream), eos);
if (trim) {
boost::algorithm::trim(str);
}
return str;
}
}
InteractiveMarkerViewer::InteractiveMarkerViewer(
OpenRAVE::EnvironmentBasePtr env,
std::string const &topic_name)
: OpenRAVE::ViewerBase(env)
, running_(false)
, do_sync_(true)
, topic_name_(topic_name)
, server_(boost::make_shared<InteractiveMarkerServer>(topic_name))
, parent_frame_id_(kDefaultWorldFrameId)
, pixels_to_meters_(0.001)
{
BOOST_ASSERT(env);
RegisterCommand("AddMenuEntry",
boost::bind(&InteractiveMarkerViewer::AddMenuEntryCommand, this, _1, _2),
"Attach a custom menu entry to an object."
);
RegisterCommand("GetMenuSelection",
boost::bind(&InteractiveMarkerViewer::GetMenuSelectionCommand, this, _1, _2),
"Get the name of the last menu selection."
);
set_environment(env);
}
void InteractiveMarkerViewer::set_environment(
OpenRAVE::EnvironmentBasePtr const &env)
{
BOOST_ASSERT(env);
RAVELOG_DEBUG("Switching to environment %d.\n",
OpenRAVE::RaveGetEnvironmentId(env));
// Register a callback to listen for bodies being added and remove.
body_callback_handle_ = env->RegisterBodyCallback(
boost::bind(&InteractiveMarkerViewer::BodyCallback, this, _1, _2)
);
// Manually remove all bodies in the old environment.
if (env_) {
std::vector<OpenRAVE::KinBodyPtr> old_bodies;
env_->GetBodies(old_bodies);
for (OpenRAVE::KinBodyPtr const &body : old_bodies) {
BodyCallback(body, 0);
}
}
// Switch to the new environment.
env_ = env;
// Manually insert all bodies in the new environment.
std::vector<OpenRAVE::KinBodyPtr> new_bodies;
env_->GetBodies(new_bodies);
for (OpenRAVE::KinBodyPtr const &body : new_bodies) {
BodyCallback(body, 1);
}
}
void InteractiveMarkerViewer::set_parent_frame(std::string const &frame_id)
{
if (frame_id != parent_frame_id_) {
RAVELOG_DEBUG("Changed parent frame ID from '%s' to '%s'.\n",
parent_frame_id_.c_str(), frame_id.c_str());
}
parent_frame_id_ = frame_id;
// TODO: Also re-create any visualization markers in the correct frame.
}
int InteractiveMarkerViewer::main(bool bShow)
{
ros::Rate rate(kRefreshRate);
RAVELOG_DEBUG("Starting main loop with a %.0f Hz refresh rate.\n",
kRefreshRate
);
running_ = true;
while (running_) {
if (do_sync_) {
EnvironmentSync();
}
viewer_callbacks_();
rate.sleep();
}
RAVELOG_DEBUG("Exiting main loop.\n");
return 0;
}
void InteractiveMarkerViewer::quitmainloop()
{
RAVELOG_DEBUG("Stopping main loop on the cycle (within %.3f ms).\n",
1.0 / kRefreshRate
);
running_ = false;
}
void InteractiveMarkerViewer::EnvironmentSync()
{
// TODO: Do I need to lock here? Is the environment already locked?
OpenRAVE::EnvironmentMutex::scoped_lock lock(env_->GetMutex(),
boost::try_to_lock);
if (!lock) {
return;
}
std::vector<KinBodyPtr> bodies;
env_->GetBodies(bodies);
for (KinBodyPtr const &body : bodies) {
OpenRAVE::UserDataPtr raw = body->GetUserData("interactive_marker");
auto body_marker = boost::dynamic_pointer_cast<KinBodyMarker>(raw);
// It's possibe to get here without the body's KinBodyMarker being
// fully initialized due to a race condition and/or environment
// cloning, which doesn't call BodyCallback.
if (!body_marker) {
BodyCallback(body, 1);
raw = body->GetUserData("interactive_marker");
body_marker = boost::dynamic_pointer_cast<KinBodyMarker>(raw);
BOOST_ASSERT(body_marker);
}
body_marker->set_parent_frame(parent_frame_id_);
body_marker->EnvironmentSync();
}
// Update any graph handles.
for (util::InteractiveMarkerGraphHandle *const handle : graph_handles_) {
handle->set_parent_frame(parent_frame_id_);
}
server_->applyChanges();
ros::spinOnce();
}
void InteractiveMarkerViewer::SetEnvironmentSync(bool do_update)
{
do_sync_ = do_update;
}
OpenRAVE::UserDataPtr InteractiveMarkerViewer::RegisterItemSelectionCallback(
OpenRAVE::ViewerBase::ItemSelectionCallbackFn const &fncallback)
{
boost::signals2::connection const con = selection_callbacks_.connect(fncallback);
return boost::make_shared<util::ScopedConnection>(con);
return OpenRAVE::UserDataPtr();
}
OpenRAVE::UserDataPtr InteractiveMarkerViewer::RegisterViewerThreadCallback(
OpenRAVE::ViewerBase::ViewerThreadCallbackFn const &fncallback)
{
boost::signals2::connection const con = viewer_callbacks_.connect(fncallback);
return boost::make_shared<util::ScopedConnection>(con);
}
GraphHandlePtr InteractiveMarkerViewer::plot3(
float const *points, int num_points, int stride, float point_size,
OpenRAVE::RaveVector<float> const &color, int draw_style)
{
InteractiveMarkerPtr interactive_marker = CreateMarker();
visualization_msgs::Marker &marker = interactive_marker->controls.front().markers.front();
marker.color = toROSColor<>(color);
if (draw_style == 0) {
marker.type = visualization_msgs::Marker::POINTS;
marker.scale.x = point_size * pixels_to_meters_;
marker.scale.y = point_size * pixels_to_meters_;
} else if (draw_style == 1) {
marker.type = visualization_msgs::Marker::SPHERE_LIST;
marker.scale.x = point_size * pixels_to_meters_;
marker.scale.y = point_size * pixels_to_meters_;
marker.scale.z = point_size * pixels_to_meters_;
} else {
throw OpenRAVE::openrave_exception(str(
format("Unsupported drawstyle %d; expected 0 or 1.")
% draw_style
), OpenRAVE::ORE_InvalidArguments
);
}
ConvertPoints(points, num_points, stride, &marker.points);
return CreateGraphHandle(interactive_marker);
}
OpenRAVE::GraphHandlePtr InteractiveMarkerViewer::plot3(
float const *points, int num_points, int stride, float point_size,
float const *colors, int draw_style, bool has_alpha)
{
InteractiveMarkerPtr interactive_marker = CreateMarker();
visualization_msgs::Marker &marker = interactive_marker->controls.front().markers.front();
if (draw_style == 0) {
marker.type = visualization_msgs::Marker::POINTS;
marker.scale.x = point_size * pixels_to_meters_;
marker.scale.y = point_size * pixels_to_meters_;
} else if (draw_style == 1) {
// TODO: Does this support individual colors?
marker.type = visualization_msgs::Marker::SPHERE_LIST;
marker.scale.x = point_size * pixels_to_meters_;
marker.scale.y = point_size * pixels_to_meters_;
marker.scale.z = point_size * pixels_to_meters_;
} else {
throw OpenRAVE::openrave_exception(str(
format("Unsupported drawstyle %d; expected 0 or 1.")
% draw_style
), OpenRAVE::ORE_InvalidArguments
);
}
ConvertPoints(points, num_points, stride, &marker.points);
ConvertColors(colors, num_points, has_alpha, &marker.colors);
return CreateGraphHandle(interactive_marker);
}
GraphHandlePtr InteractiveMarkerViewer::drawarrow(
OpenRAVE::RaveVector<float> const &p1,
OpenRAVE::RaveVector<float> const &p2,
float fwidth,
OpenRAVE::RaveVector<float> const &color)
{
visualization_msgs::InteractiveMarkerPtr interactive_marker = CreateMarker();
visualization_msgs::Marker &marker = interactive_marker->controls.front().markers.front();
marker.type = visualization_msgs::Marker::ARROW;
marker.color = toROSColor<>(color);
marker.scale.x = fwidth * 1.0f;
marker.scale.y = fwidth * 1.5f;
marker.scale.z = fwidth * 2.0f;
marker.points.push_back(toROSPoint(p1));
marker.points.push_back(toROSPoint(p2));
return CreateGraphHandle(interactive_marker);
}
GraphHandlePtr InteractiveMarkerViewer::drawlinestrip(
float const *points, int num_points, int stride, float width,
OpenRAVE::RaveVector<float> const &color)
{
InteractiveMarkerPtr interactive_marker = CreateMarker();
visualization_msgs::Marker &marker = interactive_marker->controls.front().markers.front();
marker.type = visualization_msgs::Marker::LINE_STRIP;
marker.color = toROSColor<>(color);
marker.scale.x = width * pixels_to_meters_;
ConvertPoints(points, num_points, stride, &marker.points);
return CreateGraphHandle(interactive_marker);
}
GraphHandlePtr InteractiveMarkerViewer::drawlinestrip(
float const *points, int num_points, int stride, float width,
float const *colors)
{
InteractiveMarkerPtr interactive_marker = CreateMarker();
visualization_msgs::Marker &marker = interactive_marker->controls.front().markers.front();
marker.type = visualization_msgs::Marker::LINE_STRIP;
marker.scale.x = width * pixels_to_meters_;
ConvertPoints(points, num_points, stride, &marker.points);
ConvertColors(colors, num_points, false, &marker.colors);
return CreateGraphHandle(interactive_marker);
}
GraphHandlePtr InteractiveMarkerViewer::drawlinelist(
float const *points, int num_points, int stride, float width,
OpenRAVE::RaveVector<float> const &color)
{
InteractiveMarkerPtr interactive_marker = CreateMarker();
visualization_msgs::Marker &marker = interactive_marker->controls.front().markers.front();
marker.type = visualization_msgs::Marker::LINE_LIST;
marker.color = toROSColor<>(color);
marker.scale.x = width / kWidthScaleFactor;
ConvertPoints(points, num_points, stride, &marker.points);
return CreateGraphHandle(interactive_marker);
}
GraphHandlePtr InteractiveMarkerViewer::drawlinelist(
float const *points, int num_points, int stride, float width,
float const *colors)
{
InteractiveMarkerPtr interactive_marker = CreateMarker();
visualization_msgs::Marker &marker = interactive_marker->controls.front().markers.front();
marker.type = visualization_msgs::Marker::LINE_LIST;
marker.scale.x = width / kWidthScaleFactor;
ConvertPoints(points, num_points, stride, &marker.points);
ConvertColors(colors, num_points, false, &marker.colors);
return CreateGraphHandle(interactive_marker);
}
GraphHandlePtr InteractiveMarkerViewer::drawbox(
OpenRAVE::RaveVector<float> const &pos,
OpenRAVE::RaveVector<float> const &extents)
{
InteractiveMarkerPtr interactive_marker = CreateMarker();
visualization_msgs::Marker &marker = interactive_marker->controls.front().markers.front();
marker.type = visualization_msgs::Marker::CUBE;
marker.pose.position = toROSPoint<>(pos);
marker.scale = toROSVector<>(2.0 * extents);
return CreateGraphHandle(interactive_marker);
}
OpenRAVE::GraphHandlePtr InteractiveMarkerViewer::drawplane(
OpenRAVE::RaveTransform<float> const &transform,
OpenRAVE::RaveVector<float> const &extents,
boost::multi_array<float, 3> const &texture)
{
throw OpenRAVE::openrave_exception(
"drawplane is not implemented on InteractiveMarkerViewer",
OpenRAVE::ORE_NotImplemented
);
}
GraphHandlePtr InteractiveMarkerViewer::drawtrimesh(
float const *points, int stride, int const *indices, int num_triangles,
OpenRAVE::RaveVector<float> const &color)
{
InteractiveMarkerPtr interactive_marker = CreateMarker();
visualization_msgs::Marker &marker = interactive_marker->controls.front().markers.front();
marker.type = visualization_msgs::Marker::TRIANGLE_LIST;
marker.color = toROSColor<>(color);
marker.scale.x = 1;
marker.scale.y = 1;
marker.scale.z = 1;
ConvertMesh(points, stride, indices, num_triangles, &marker.points);
return CreateGraphHandle(interactive_marker);
}
GraphHandlePtr InteractiveMarkerViewer::drawtrimesh(
float const *points, int stride, int const *indices, int num_triangles,
boost::multi_array<float, 2> const &colors)
{
InteractiveMarkerPtr interactive_marker = CreateMarker();
visualization_msgs::Marker &marker = interactive_marker->controls.front().markers.front();
marker.type = visualization_msgs::Marker::TRIANGLE_LIST;
marker.scale.x = 1;
marker.scale.y = 1;
marker.scale.z = 1;
ConvertMesh(points, stride, indices, num_triangles, &marker.points);
// TODO: Colors should be per-vertex, not per-face.
size_t const *color_shape = colors.shape();
if (color_shape[0] != num_triangles) {
throw OpenRAVE::openrave_exception(str(
format("Number of colors does not equal number of triangles;"
" expected %d, got %d.")
% color_shape[0] % num_triangles
),
OpenRAVE::ORE_InvalidArguments
);
} else if (color_shape[1] != 3 && color_shape[1] != 4) {
throw OpenRAVE::openrave_exception(str(
format("Invalid number of channels; expected 3 or 4, got %d.")
% color_shape[1]
),
OpenRAVE::ORE_InvalidArguments
);
}
marker.colors.resize(3 * num_triangles);
for (int itri = 0; itri < num_triangles; ++itri) {
std_msgs::ColorRGBA color;
color.r = colors[itri][0];
color.g = colors[itri][1];
color.b = colors[itri][2];
if (color_shape[1] == 4) {
color.a = colors[itri][3];
} else {
color.a = 1.0;
}
for (int ivertex = 0; ivertex < 3; ++ivertex) {
int const index_offset = 3 * itri + ivertex;
int const index = stride * indices[index_offset];
marker.colors[index] = color;
}
}
return CreateGraphHandle(interactive_marker);
}
bool InteractiveMarkerViewer::AddMenuEntryCommand(std::ostream &out,
std::istream &in)
{
std::string type, kinbody_name;
in >> type >> kinbody_name;
// Get the KinBodyMarker associated with the target object.
OpenRAVE::KinBodyPtr const kinbody = env_->GetKinBody(kinbody_name);
if (!kinbody) {
throw OpenRAVE::openrave_exception(
str(format("There is no KinBody named '%s' in the environment.")
% kinbody_name),
OpenRAVE::ORE_Failed
);
}
OpenRAVE::UserDataPtr const marker_raw = kinbody->GetUserData("interactive_marker");
auto const marker = boost::dynamic_pointer_cast<KinBodyMarker>(marker_raw);
if (!marker) {
throw OpenRAVE::openrave_exception(
str(format("KinBody '%s' does not have an associated marker.")
% kinbody_name),
OpenRAVE::ORE_InvalidState
);
}
if (type == "kinbody") {
std::string const name = GetRemainingContent(in, true);
auto const callback = boost::bind(
&InteractiveMarkerViewer::KinBodyMenuCallback,
this, kinbody, name
);
marker->AddMenuEntry(name, callback);
} else if (type == "link") {
std::string link_name;
in >> link_name;
OpenRAVE::KinBody::LinkPtr const link = kinbody->GetLink(link_name);
if (!link) {
throw OpenRAVE::openrave_exception(
str(format("KinBody '%s' has no link '%s'.")
% kinbody_name % link_name),
OpenRAVE::ORE_Failed
);
}
std::string const name = GetRemainingContent(in, true);
auto const callback = boost::bind(
&InteractiveMarkerViewer::LinkMenuCallback,
this, link, name
);
marker->AddMenuEntry(link, name, callback);
} else if (type == "manipulator" || type == "ghost_manipulator") {
std::string manipulator_name;
in >> manipulator_name;
if (!kinbody->IsRobot()) {
throw OpenRAVE::openrave_exception(
str(format("KinBody '%s' is not a robot and does not support"
" manipulator menus.")
% kinbody_name),
OpenRAVE::ORE_Failed
);
}
auto const robot = boost::dynamic_pointer_cast<OpenRAVE::RobotBase>(kinbody);
OpenRAVE::RobotBase::ManipulatorPtr const manipulator = robot->GetManipulator(manipulator_name);
if (!manipulator) {
throw OpenRAVE::openrave_exception(
str(format("Robot '%s' has no manipulator '%s'.")
% kinbody_name % manipulator_name),
OpenRAVE::ORE_Failed
);
}
std::string const name = GetRemainingContent(in, true);
auto const callback = boost::bind(
&InteractiveMarkerViewer::ManipulatorMenuCallback,
this, manipulator, name
);
marker->AddMenuEntry(manipulator, name, callback);
}
return true;
}
void InteractiveMarkerViewer::GraphHandleRemovedCallback(
util::InteractiveMarkerGraphHandle *handle)
{
graph_handles_.erase(handle);
}
bool InteractiveMarkerViewer::GetMenuSelectionCommand(std::ostream &out,
std::istream &in)
{
out << menu_queue_.rdbuf();
}
void InteractiveMarkerViewer::BodyCallback(OpenRAVE::KinBodyPtr body, int flag)
{
RAVELOG_DEBUG("BodyCallback %s -> %d\n", body->GetName().c_str(), flag);
// Added.
if (flag == 1) {
auto const body_marker = boost::make_shared<KinBodyMarker>(server_, body);
body_marker->set_parent_frame(parent_frame_id_);
body->SetUserData("interactive_marker", body_marker);
}
// Removed.
else if (flag == 0) {
body->RemoveUserData("interactive_marker");
}
}
void InteractiveMarkerViewer::KinBodyMenuCallback(OpenRAVE::KinBodyPtr kinbody,
std::string const &name)
{
menu_queue_ << "kinbody " << kinbody->GetName()
<< " " << name << '\n';
selection_callbacks_(OpenRAVE::KinBody::LinkPtr(),
OpenRAVE::RaveVector<float>(),
OpenRAVE::RaveVector<float>());
}
void InteractiveMarkerViewer::LinkMenuCallback(OpenRAVE::KinBody::LinkPtr link,
std::string const &name)
{
menu_queue_ << "link " << link->GetParent()->GetName()
<< " " << link->GetName()
<< " " << name << '\n';
}
void InteractiveMarkerViewer::ManipulatorMenuCallback(
OpenRAVE::RobotBase::ManipulatorPtr manipulator, std::string const &name)
{
menu_queue_ << "manipulator " << manipulator->GetRobot()->GetName()
<< " " << manipulator->GetName()
<< " " << name << '\n';
}
util::InteractiveMarkerGraphHandlePtr InteractiveMarkerViewer::CreateGraphHandle(
visualization_msgs::InteractiveMarkerPtr const &interactive_marker)
{
auto const handle = boost::make_shared<util::InteractiveMarkerGraphHandle>(
server_, interactive_marker,
boost::bind(&InteractiveMarkerViewer::GraphHandleRemovedCallback,
this, _1)
);
graph_handles_.insert(handle.get());
return handle;
}
InteractiveMarkerPtr InteractiveMarkerViewer::CreateMarker() const
{
auto interactive_marker = boost::make_shared<InteractiveMarker>();
interactive_marker->header.frame_id = parent_frame_id_;
interactive_marker->pose = toROSPose(OpenRAVE::Transform());
interactive_marker->name = str(format("GraphHandle[%p]") % interactive_marker.get());
interactive_marker->scale = 1.0;
interactive_marker->controls.resize(1);
visualization_msgs::InteractiveMarkerControl &control = interactive_marker->controls.front();
control.orientation_mode = visualization_msgs::InteractiveMarkerControl::INHERIT;
control.interaction_mode = visualization_msgs::InteractiveMarkerControl::NONE;
control.always_visible = true;
control.markers.resize(1);
visualization_msgs::Marker &marker = control.markers.front();
marker.action = visualization_msgs::Marker::ADD;
marker.pose.orientation.w = 1.0;
marker.scale.x = 1.0;
marker.scale.y = 1.0;
marker.scale.z = 1.0;
return interactive_marker;
}
void InteractiveMarkerViewer::ConvertPoints(
float const *points, int num_points, int stride,
std::vector<geometry_msgs::Point> *out_points) const
{
BOOST_ASSERT(points);
BOOST_ASSERT(num_points >= 0);
BOOST_ASSERT(stride >= 0 && stride % sizeof(float) == 0);
BOOST_ASSERT(out_points);
stride = stride / sizeof(float);
out_points->resize(num_points);
for (size_t ipoint = 0; ipoint < num_points; ++ipoint) {
geometry_msgs::Point &out_point = out_points->at(ipoint);
out_point.x = points[stride * ipoint + 0];
out_point.y = points[stride * ipoint + 1];
out_point.z = points[stride * ipoint + 2];
}
}
void InteractiveMarkerViewer::ConvertColors(
float const *colors, int num_colors, bool has_alpha,
std::vector<std_msgs::ColorRGBA> *out_colors) const
{
BOOST_ASSERT(colors);
BOOST_ASSERT(num_colors >= 0);
BOOST_ASSERT(out_colors);
int stride;
if (has_alpha) {
stride = 4;
} else {
stride = 3;
}
out_colors->resize(num_colors);
for (size_t icolor = 0; icolor < num_colors; ++icolor) {
std_msgs::ColorRGBA &out_color = out_colors->at(icolor);
out_color.r = colors[icolor * stride + 0];
out_color.g = colors[icolor * stride + 1];
out_color.b = colors[icolor * stride + 2];
if (has_alpha) {
out_color.a = colors[icolor * stride + 3];
} else {
out_color.a = 1.0;
}
}
}
void InteractiveMarkerViewer::ConvertMesh(
float const *points, int stride, int const *indices, int num_triangles,
std::vector<geometry_msgs::Point> *out_points) const
{
BOOST_ASSERT(points);
BOOST_ASSERT(stride > 0);
BOOST_ASSERT(indices);
BOOST_ASSERT(num_triangles >= 0);
BOOST_ASSERT(out_points);
auto const points_raw = reinterpret_cast<uint8_t const *>(points);
if (num_triangles == 0) {
out_points->resize(3);
for (int ivertex = 0; ivertex < 3; ++ivertex) {
geometry_msgs::Point &point = (*out_points)[ivertex];
point.x = 0.;
point.y = 0.;
point.z = 0.;
}
} else {
out_points->resize(3 * num_triangles);
for (int iindex = 0; iindex < num_triangles; ++iindex) {
for (int ivertex = 0; ivertex < 3; ++ivertex) {
int const index_offset = 3 * iindex + ivertex;
float const *or_point = reinterpret_cast<float const *>(
points_raw + stride * indices[index_offset]
);
geometry_msgs::Point &out_point = out_points->at(3 * iindex + ivertex);
out_point.x = or_point[0];
out_point.y = or_point[1];
out_point.z = or_point[2];
}
}
}
}
}
| 34.766938 | 104 | 0.663692 | [
"object",
"shape",
"vector",
"transform"
] |
c80b49015815503836b0381bb8fb5f5ae35a272c | 2,781 | cpp | C++ | Eagle/src/Eagle/Camera/CameraController.cpp | IceLuna/Eagle | 3b0d5f014697c97138f160ddd535b1afd6d0c141 | [
"Apache-2.0"
] | 1 | 2021-12-10T19:15:25.000Z | 2021-12-10T19:15:25.000Z | Eagle/src/Eagle/Camera/CameraController.cpp | IceLuna/Eagle | 3b0d5f014697c97138f160ddd535b1afd6d0c141 | [
"Apache-2.0"
] | 41 | 2021-08-18T21:32:14.000Z | 2022-02-20T11:44:06.000Z | Eagle/src/Eagle/Camera/CameraController.cpp | IceLuna/Eagle | 3b0d5f014697c97138f160ddd535b1afd6d0c141 | [
"Apache-2.0"
] | null | null | null | #include "egpch.h"
#include "CameraController.h"
#include "Eagle/Events/MouseEvent.h"
#include "Eagle/Input/Input.h"
#include "Eagle/Components/Components.h"
namespace Eagle
{
void CameraController::OnCreate()
{
if (m_Entity.HasComponent<CameraComponent>())
{
auto& cameraComponent = m_Entity.GetComponent<CameraComponent>();
m_EulerRotation = cameraComponent.GetWorldTransform().Rotation.EulerAngles();
constexpr float rad = glm::radians(180.f);
if (glm::abs(m_EulerRotation.z) == rad)
{
m_EulerRotation.x += -rad;
m_EulerRotation.y -= rad;
m_EulerRotation.y *= -1.f;
m_EulerRotation.z = 0.f;
}
}
}
void CameraController::OnUpdate(Timestep ts)
{
if (m_Entity.HasComponent<CameraComponent>())
{
auto& cameraComponent = m_Entity.GetComponent<CameraComponent>();
if (cameraComponent.Primary)
{
Transform transform = cameraComponent.GetWorldTransform();
if (Input::IsMouseButtonPressed(Mouse::ButtonRight))
{
float offsetX = m_MouseX - Input::GetMouseX();
float offsetY = Input::GetMouseY() - m_MouseY;
if (Input::IsCursorVisible())
{
Input::SetShowCursor(false);
offsetX = offsetY = 0.f;
}
glm::vec3& Location = transform.Location;
glm::vec3& Rotation = m_EulerRotation;
Rotation.x -= glm::radians(offsetY * m_MouseRotationSpeed);
Rotation.y += glm::radians(offsetX * m_MouseRotationSpeed);
constexpr float maxRadians = glm::radians(89.9f);
constexpr float minRadians = glm::radians(-89.9f);
if (Rotation.x >= maxRadians)
Rotation.x = maxRadians;
else if (Rotation.x <= minRadians)
Rotation.x = minRadians;
transform.Rotation = Rotator::FromEulerAngles(Rotation);
glm::vec3 forward = cameraComponent.GetForwardVector();
glm::vec3 right = cameraComponent.GetRightVector();
if (Input::IsKeyPressed(Key::W))
{
Location += (forward * (m_MoveSpeed * ts));
}
if (Input::IsKeyPressed(Key::S))
{
Location -= (forward * (m_MoveSpeed * ts));
}
if (Input::IsKeyPressed(Key::Q))
{
Location.y -= m_MoveSpeed * ts;
}
if (Input::IsKeyPressed(Key::E))
{
Location.y += m_MoveSpeed * ts;
}
if (Input::IsKeyPressed(Key::A))
{
Location -= (right * (m_MoveSpeed * ts));
}
if (Input::IsKeyPressed(Key::D))
{
Location += (right * (m_MoveSpeed * ts));
}
m_MouseX = Input::GetMouseX();
m_MouseY = Input::GetMouseY();
cameraComponent.SetWorldTransform(transform);
}
else
{
if (Input::IsCursorVisible() == false)
{
Input::SetShowCursor(true);
}
}
}
}
}
void CameraController::OnEvent(Event& e)
{
EventDispatcher dispatcher(e);
}
} | 24.610619 | 80 | 0.633585 | [
"transform"
] |
c80bedf2c465a2a56e2818ed7176e5e32b247d13 | 46,520 | cpp | C++ | Source/Urho3D/Graphics/Material.cpp | MatiRg/Urho3D | 900611ceeb05e20cedef707bcb6a2e4ac48fb4e1 | [
"MIT"
] | 1 | 2020-08-18T19:13:00.000Z | 2020-08-18T19:13:00.000Z | Source/Urho3D/Graphics/Material.cpp | MatiRg/Urho3D | 900611ceeb05e20cedef707bcb6a2e4ac48fb4e1 | [
"MIT"
] | null | null | null | Source/Urho3D/Graphics/Material.cpp | MatiRg/Urho3D | 900611ceeb05e20cedef707bcb6a2e4ac48fb4e1 | [
"MIT"
] | 1 | 2017-08-26T06:38:23.000Z | 2017-08-26T06:38:23.000Z | //
// Copyright (c) 2008-2021 the Urho3D project.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#include "../Precompiled.h"
#include "../Core/Context.h"
#include "../Core/CoreEvents.h"
#include "../Core/Profiler.h"
#include "../Graphics/Graphics.h"
#include "../Graphics/Material.h"
#include "../Graphics/Renderer.h"
#include "../Graphics/Technique.h"
#include "../Graphics/Texture2D.h"
#include "../Graphics/Texture2DArray.h"
#include "../Graphics/Texture3D.h"
#include "../Graphics/TextureCube.h"
#include "../IO/FileSystem.h"
#include "../IO/Log.h"
#include "../IO/VectorBuffer.h"
#include "../Resource/ResourceCache.h"
#include "../Resource/XMLFile.h"
#include "../Resource/JSONFile.h"
#include "../Scene/Scene.h"
#include "../Scene/SceneEvents.h"
#include "../Scene/ValueAnimation.h"
#include "../DebugNew.h"
namespace Urho3D
{
extern const char* wrapModeNames[];
static const char* textureUnitNames[] =
{
"diffuse",
"normal",
"specular",
"emissive",
"environment",
#ifdef DESKTOP_GRAPHICS
"volume",
"custom1",
"custom2",
"lightramp",
"lightshape",
"shadowmap",
"faceselect",
"indirection",
"depth",
"light",
"zone",
nullptr
#else
"lightramp",
"lightshape",
"shadowmap",
nullptr
#endif
};
const char* cullModeNames[] =
{
"none",
"ccw",
"cw",
nullptr
};
static const char* fillModeNames[] =
{
"solid",
"wireframe",
"point",
nullptr
};
TextureUnit ParseTextureUnitName(String name)
{
name = name.ToLower().Trimmed();
auto unit = (TextureUnit)GetStringListIndex(name.CString(), textureUnitNames, MAX_TEXTURE_UNITS);
if (unit == MAX_TEXTURE_UNITS)
{
// Check also for shorthand names
if (name == "diff")
unit = TU_DIFFUSE;
else if (name == "albedo")
unit = TU_DIFFUSE;
else if (name == "norm")
unit = TU_NORMAL;
else if (name == "spec")
unit = TU_SPECULAR;
else if (name == "env")
unit = TU_ENVIRONMENT;
// Finally check for specifying the texture unit directly as a number
else if (name.Length() < 3)
unit = (TextureUnit)Clamp(ToInt(name), 0, MAX_TEXTURE_UNITS - 1);
}
if (unit == MAX_TEXTURE_UNITS)
URHO3D_LOGERROR("Unknown texture unit name " + name);
return unit;
}
StringHash ParseTextureTypeName(const String& name)
{
String lowerCaseName = name.ToLower().Trimmed();
if (lowerCaseName == "texture")
return Texture2D::GetTypeStatic();
else if (lowerCaseName == "cubemap")
return TextureCube::GetTypeStatic();
else if (lowerCaseName == "texture3d")
return Texture3D::GetTypeStatic();
else if (lowerCaseName == "texturearray")
return Texture2DArray::GetTypeStatic();
return nullptr;
}
StringHash ParseTextureTypeXml(ResourceCache* cache, const String& filename)
{
StringHash type = nullptr;
if (!cache)
return type;
SharedPtr<File> texXmlFile = cache->GetFile(filename, false);
if (texXmlFile.NotNull())
{
SharedPtr<XMLFile> texXml(new XMLFile(cache->GetContext()));
if (texXml->Load(*texXmlFile))
type = ParseTextureTypeName(texXml->GetRoot().GetName());
}
return type;
}
static TechniqueEntry noEntry;
bool CompareTechniqueEntries(const TechniqueEntry& lhs, const TechniqueEntry& rhs)
{
if (lhs.lodDistance_ != rhs.lodDistance_)
return lhs.lodDistance_ > rhs.lodDistance_;
else
return lhs.qualityLevel_ > rhs.qualityLevel_;
}
TechniqueEntry::TechniqueEntry() noexcept :
qualityLevel_(QUALITY_LOW),
lodDistance_(0.0f)
{
}
TechniqueEntry::TechniqueEntry(Technique* tech, MaterialQuality qualityLevel, float lodDistance) noexcept :
technique_(tech),
original_(tech),
qualityLevel_(qualityLevel),
lodDistance_(lodDistance)
{
}
ShaderParameterAnimationInfo::ShaderParameterAnimationInfo(Material* material, const String& name, ValueAnimation* attributeAnimation,
WrapMode wrapMode, float speed) :
ValueAnimationInfo(material, attributeAnimation, wrapMode, speed),
name_(name)
{
}
ShaderParameterAnimationInfo::ShaderParameterAnimationInfo(const ShaderParameterAnimationInfo& other) = default;
ShaderParameterAnimationInfo::~ShaderParameterAnimationInfo() = default;
void ShaderParameterAnimationInfo::ApplyValue(const Variant& newValue)
{
static_cast<Material*>(target_.Get())->SetShaderParameter(name_, newValue);
}
Material::Material(Context* context) :
Resource(context)
{
ResetToDefaults();
}
Material::~Material() = default;
void Material::RegisterObject(Context* context)
{
context->RegisterFactory<Material>();
}
bool Material::BeginLoad(Deserializer& source)
{
// In headless mode, do not actually load the material, just return success
auto* graphics = GetSubsystem<Graphics>();
if (!graphics)
return true;
String extension = GetExtension(source.GetName());
bool success = false;
if (extension == ".xml")
{
success = BeginLoadXML(source);
if (!success)
success = BeginLoadJSON(source);
if (success)
return true;
}
else // Load JSON file
{
success = BeginLoadJSON(source);
if (!success)
success = BeginLoadXML(source);
if (success)
return true;
}
// All loading failed
ResetToDefaults();
loadJSONFile_.Reset();
return false;
}
bool Material::EndLoad()
{
// In headless mode, do not actually load the material, just return success
auto* graphics = GetSubsystem<Graphics>();
if (!graphics)
return true;
bool success = false;
if (loadXMLFile_)
{
// If async loading, get the techniques / textures which should be ready now
XMLElement rootElem = loadXMLFile_->GetRoot();
success = Load(rootElem);
}
if (loadJSONFile_)
{
JSONValue rootVal = loadJSONFile_->GetRoot();
success = Load(rootVal);
}
loadXMLFile_.Reset();
loadJSONFile_.Reset();
return success;
}
bool Material::BeginLoadXML(Deserializer& source)
{
ResetToDefaults();
loadXMLFile_ = new XMLFile(context_);
if (loadXMLFile_->Load(source))
{
// If async loading, scan the XML content beforehand for technique & texture resources
// and request them to also be loaded. Can not do anything else at this point
if (GetAsyncLoadState() == ASYNC_LOADING)
{
auto* cache = GetSubsystem<ResourceCache>();
XMLElement rootElem = loadXMLFile_->GetRoot();
XMLElement techniqueElem = rootElem.GetChild("technique");
while (techniqueElem)
{
cache->BackgroundLoadResource<Technique>(techniqueElem.GetAttribute("name"), true, this);
techniqueElem = techniqueElem.GetNext("technique");
}
XMLElement textureElem = rootElem.GetChild("texture");
while (textureElem)
{
String name = textureElem.GetAttribute("name");
// Detect cube maps and arrays by file extension: they are defined by an XML file
if (GetExtension(name) == ".xml")
{
#ifdef DESKTOP_GRAPHICS
StringHash type = ParseTextureTypeXml(cache, name);
if (!type && textureElem.HasAttribute("unit"))
{
TextureUnit unit = ParseTextureUnitName(textureElem.GetAttribute("unit"));
if (unit == TU_VOLUMEMAP)
type = Texture3D::GetTypeStatic();
}
if (type == Texture3D::GetTypeStatic())
cache->BackgroundLoadResource<Texture3D>(name, true, this);
else if (type == Texture2DArray::GetTypeStatic())
cache->BackgroundLoadResource<Texture2DArray>(name, true, this);
else
#endif
cache->BackgroundLoadResource<TextureCube>(name, true, this);
}
else
cache->BackgroundLoadResource<Texture2D>(name, true, this);
textureElem = textureElem.GetNext("texture");
}
}
return true;
}
return false;
}
bool Material::BeginLoadJSON(Deserializer& source)
{
// Attempt to load a JSON file
ResetToDefaults();
loadXMLFile_.Reset();
// Attempt to load from JSON file instead
loadJSONFile_ = new JSONFile(context_);
if (loadJSONFile_->Load(source))
{
// If async loading, scan the XML content beforehand for technique & texture resources
// and request them to also be loaded. Can not do anything else at this point
if (GetAsyncLoadState() == ASYNC_LOADING)
{
auto* cache = GetSubsystem<ResourceCache>();
const JSONValue& rootVal = loadJSONFile_->GetRoot();
JSONArray techniqueArray = rootVal.Get("techniques").GetArray();
for (unsigned i = 0; i < techniqueArray.Size(); i++)
{
const JSONValue& techVal = techniqueArray[i];
cache->BackgroundLoadResource<Technique>(techVal.Get("name").GetString(), true, this);
}
JSONObject textureObject = rootVal.Get("textures").GetObject();
for (JSONObject::ConstIterator it = textureObject.Begin(); it != textureObject.End(); it++)
{
String unitString = it->first_;
String name = it->second_.GetString();
// Detect cube maps and arrays by file extension: they are defined by an XML file
if (GetExtension(name) == ".xml")
{
#ifdef DESKTOP_GRAPHICS
StringHash type = ParseTextureTypeXml(cache, name);
if (!type && !unitString.Empty())
{
TextureUnit unit = ParseTextureUnitName(unitString);
if (unit == TU_VOLUMEMAP)
type = Texture3D::GetTypeStatic();
}
if (type == Texture3D::GetTypeStatic())
cache->BackgroundLoadResource<Texture3D>(name, true, this);
else if (type == Texture2DArray::GetTypeStatic())
cache->BackgroundLoadResource<Texture2DArray>(name, true, this);
else
#endif
cache->BackgroundLoadResource<TextureCube>(name, true, this);
}
else
cache->BackgroundLoadResource<Texture2D>(name, true, this);
}
}
// JSON material was successfully loaded
return true;
}
return false;
}
bool Material::Save(Serializer& dest) const
{
SharedPtr<XMLFile> xml(new XMLFile(context_));
XMLElement materialElem = xml->CreateRoot("material");
Save(materialElem);
return xml->Save(dest);
}
bool Material::Load(const XMLElement& source)
{
ResetToDefaults();
if (source.IsNull())
{
URHO3D_LOGERROR("Can not load material from null XML element");
return false;
}
auto* cache = GetSubsystem<ResourceCache>();
XMLElement shaderElem = source.GetChild("shader");
if (shaderElem)
{
vertexShaderDefines_ = shaderElem.GetAttribute("vsdefines");
pixelShaderDefines_ = shaderElem.GetAttribute("psdefines");
}
XMLElement techniqueElem = source.GetChild("technique");
techniques_.Clear();
while (techniqueElem)
{
auto* tech = cache->GetResource<Technique>(techniqueElem.GetAttribute("name"));
if (tech)
{
TechniqueEntry newTechnique;
newTechnique.technique_ = newTechnique.original_ = tech;
if (techniqueElem.HasAttribute("quality"))
newTechnique.qualityLevel_ = (MaterialQuality)techniqueElem.GetInt("quality");
if (techniqueElem.HasAttribute("loddistance"))
newTechnique.lodDistance_ = techniqueElem.GetFloat("loddistance");
techniques_.Push(newTechnique);
}
techniqueElem = techniqueElem.GetNext("technique");
}
SortTechniques();
ApplyShaderDefines();
XMLElement textureElem = source.GetChild("texture");
while (textureElem)
{
TextureUnit unit = TU_DIFFUSE;
if (textureElem.HasAttribute("unit"))
unit = ParseTextureUnitName(textureElem.GetAttribute("unit"));
if (unit < MAX_TEXTURE_UNITS)
{
String name = textureElem.GetAttribute("name");
// Detect cube maps and arrays by file extension: they are defined by an XML file
if (GetExtension(name) == ".xml")
{
#ifdef DESKTOP_GRAPHICS
StringHash type = ParseTextureTypeXml(cache, name);
if (!type && unit == TU_VOLUMEMAP)
type = Texture3D::GetTypeStatic();
if (type == Texture3D::GetTypeStatic())
SetTexture(unit, cache->GetResource<Texture3D>(name));
else if (type == Texture2DArray::GetTypeStatic())
SetTexture(unit, cache->GetResource<Texture2DArray>(name));
else
#endif
SetTexture(unit, cache->GetResource<TextureCube>(name));
}
else
SetTexture(unit, cache->GetResource<Texture2D>(name));
}
textureElem = textureElem.GetNext("texture");
}
batchedParameterUpdate_ = true;
XMLElement parameterElem = source.GetChild("parameter");
while (parameterElem)
{
String name = parameterElem.GetAttribute("name");
if (!parameterElem.HasAttribute("type"))
SetShaderParameter(name, ParseShaderParameterValue(parameterElem.GetAttribute("value")));
else
SetShaderParameter(name, Variant(parameterElem.GetAttribute("type"), parameterElem.GetAttribute("value")));
parameterElem = parameterElem.GetNext("parameter");
}
batchedParameterUpdate_ = false;
XMLElement parameterAnimationElem = source.GetChild("parameteranimation");
while (parameterAnimationElem)
{
String name = parameterAnimationElem.GetAttribute("name");
SharedPtr<ValueAnimation> animation(new ValueAnimation(context_));
if (!animation->LoadXML(parameterAnimationElem))
{
URHO3D_LOGERROR("Could not load parameter animation");
return false;
}
String wrapModeString = parameterAnimationElem.GetAttribute("wrapmode");
WrapMode wrapMode = WM_LOOP;
for (int i = 0; i <= WM_CLAMP; ++i)
{
if (wrapModeString == wrapModeNames[i])
{
wrapMode = (WrapMode)i;
break;
}
}
float speed = parameterAnimationElem.GetFloat("speed");
SetShaderParameterAnimation(name, animation, wrapMode, speed);
parameterAnimationElem = parameterAnimationElem.GetNext("parameteranimation");
}
XMLElement cullElem = source.GetChild("cull");
if (cullElem)
SetCullMode((CullMode)GetStringListIndex(cullElem.GetAttribute("value").CString(), cullModeNames, CULL_CCW));
XMLElement shadowCullElem = source.GetChild("shadowcull");
if (shadowCullElem)
SetShadowCullMode((CullMode)GetStringListIndex(shadowCullElem.GetAttribute("value").CString(), cullModeNames, CULL_CCW));
XMLElement fillElem = source.GetChild("fill");
if (fillElem)
SetFillMode((FillMode)GetStringListIndex(fillElem.GetAttribute("value").CString(), fillModeNames, FILL_SOLID));
XMLElement depthBiasElem = source.GetChild("depthbias");
if (depthBiasElem)
SetDepthBias(BiasParameters(depthBiasElem.GetFloat("constant"), depthBiasElem.GetFloat("slopescaled")));
XMLElement alphaToCoverageElem = source.GetChild("alphatocoverage");
if (alphaToCoverageElem)
SetAlphaToCoverage(alphaToCoverageElem.GetBool("enable"));
XMLElement lineAntiAliasElem = source.GetChild("lineantialias");
if (lineAntiAliasElem)
SetLineAntiAlias(lineAntiAliasElem.GetBool("enable"));
XMLElement renderOrderElem = source.GetChild("renderorder");
if (renderOrderElem)
SetRenderOrder((unsigned char)renderOrderElem.GetUInt("value"));
XMLElement occlusionElem = source.GetChild("occlusion");
if (occlusionElem)
SetOcclusion(occlusionElem.GetBool("enable"));
RefreshShaderParameterHash();
RefreshMemoryUse();
return true;
}
bool Material::Load(const JSONValue& source)
{
ResetToDefaults();
if (source.IsNull())
{
URHO3D_LOGERROR("Can not load material from null JSON element");
return false;
}
auto* cache = GetSubsystem<ResourceCache>();
const JSONValue& shaderVal = source.Get("shader");
if (!shaderVal.IsNull())
{
vertexShaderDefines_ = shaderVal.Get("vsdefines").GetString();
pixelShaderDefines_ = shaderVal.Get("psdefines").GetString();
}
// Load techniques
JSONArray techniquesArray = source.Get("techniques").GetArray();
techniques_.Clear();
techniques_.Reserve(techniquesArray.Size());
for (unsigned i = 0; i < techniquesArray.Size(); i++)
{
const JSONValue& techVal = techniquesArray[i];
auto* tech = cache->GetResource<Technique>(techVal.Get("name").GetString());
if (tech)
{
TechniqueEntry newTechnique;
newTechnique.technique_ = newTechnique.original_ = tech;
JSONValue qualityVal = techVal.Get("quality");
if (!qualityVal.IsNull())
newTechnique.qualityLevel_ = (MaterialQuality)qualityVal.GetInt();
JSONValue lodDistanceVal = techVal.Get("loddistance");
if (!lodDistanceVal.IsNull())
newTechnique.lodDistance_ = lodDistanceVal.GetFloat();
techniques_.Push(newTechnique);
}
}
SortTechniques();
ApplyShaderDefines();
// Load textures
JSONObject textureObject = source.Get("textures").GetObject();
for (JSONObject::ConstIterator it = textureObject.Begin(); it != textureObject.End(); it++)
{
String textureUnit = it->first_;
String textureName = it->second_.GetString();
TextureUnit unit = TU_DIFFUSE;
unit = ParseTextureUnitName(textureUnit);
if (unit < MAX_TEXTURE_UNITS)
{
// Detect cube maps and arrays by file extension: they are defined by an XML file
if (GetExtension(textureName) == ".xml")
{
#ifdef DESKTOP_GRAPHICS
StringHash type = ParseTextureTypeXml(cache, textureName);
if (!type && unit == TU_VOLUMEMAP)
type = Texture3D::GetTypeStatic();
if (type == Texture3D::GetTypeStatic())
SetTexture(unit, cache->GetResource<Texture3D>(textureName));
else if (type == Texture2DArray::GetTypeStatic())
SetTexture(unit, cache->GetResource<Texture2DArray>(textureName));
else
#endif
SetTexture(unit, cache->GetResource<TextureCube>(textureName));
}
else
SetTexture(unit, cache->GetResource<Texture2D>(textureName));
}
}
// Get shader parameters
batchedParameterUpdate_ = true;
JSONObject parameterObject = source.Get("shaderParameters").GetObject();
for (JSONObject::ConstIterator it = parameterObject.Begin(); it != parameterObject.End(); it++)
{
String name = it->first_;
if (it->second_.IsString())
SetShaderParameter(name, ParseShaderParameterValue(it->second_.GetString()));
else if (it->second_.IsObject())
{
JSONObject valueObj = it->second_.GetObject();
SetShaderParameter(name, Variant(valueObj["type"].GetString(), valueObj["value"].GetString()));
}
}
batchedParameterUpdate_ = false;
// Load shader parameter animations
JSONObject paramAnimationsObject = source.Get("shaderParameterAnimations").GetObject();
for (JSONObject::ConstIterator it = paramAnimationsObject.Begin(); it != paramAnimationsObject.End(); it++)
{
String name = it->first_;
JSONValue paramAnimVal = it->second_;
SharedPtr<ValueAnimation> animation(new ValueAnimation(context_));
if (!animation->LoadJSON(paramAnimVal))
{
URHO3D_LOGERROR("Could not load parameter animation");
return false;
}
String wrapModeString = paramAnimVal.Get("wrapmode").GetString();
WrapMode wrapMode = WM_LOOP;
for (int i = 0; i <= WM_CLAMP; ++i)
{
if (wrapModeString == wrapModeNames[i])
{
wrapMode = (WrapMode)i;
break;
}
}
float speed = paramAnimVal.Get("speed").GetFloat();
SetShaderParameterAnimation(name, animation, wrapMode, speed);
}
JSONValue cullVal = source.Get("cull");
if (!cullVal.IsNull())
SetCullMode((CullMode)GetStringListIndex(cullVal.GetString().CString(), cullModeNames, CULL_CCW));
JSONValue shadowCullVal = source.Get("shadowcull");
if (!shadowCullVal.IsNull())
SetShadowCullMode((CullMode)GetStringListIndex(shadowCullVal.GetString().CString(), cullModeNames, CULL_CCW));
JSONValue fillVal = source.Get("fill");
if (!fillVal.IsNull())
SetFillMode((FillMode)GetStringListIndex(fillVal.GetString().CString(), fillModeNames, FILL_SOLID));
JSONValue depthBiasVal = source.Get("depthbias");
if (!depthBiasVal.IsNull())
SetDepthBias(BiasParameters(depthBiasVal.Get("constant").GetFloat(), depthBiasVal.Get("slopescaled").GetFloat()));
JSONValue alphaToCoverageVal = source.Get("alphatocoverage");
if (!alphaToCoverageVal.IsNull())
SetAlphaToCoverage(alphaToCoverageVal.GetBool());
JSONValue lineAntiAliasVal = source.Get("lineantialias");
if (!lineAntiAliasVal.IsNull())
SetLineAntiAlias(lineAntiAliasVal.GetBool());
JSONValue renderOrderVal = source.Get("renderorder");
if (!renderOrderVal.IsNull())
SetRenderOrder((unsigned char)renderOrderVal.GetUInt());
JSONValue occlusionVal = source.Get("occlusion");
if (!occlusionVal.IsNull())
SetOcclusion(occlusionVal.GetBool());
RefreshShaderParameterHash();
RefreshMemoryUse();
return true;
}
bool Material::Save(XMLElement& dest) const
{
if (dest.IsNull())
{
URHO3D_LOGERROR("Can not save material to null XML element");
return false;
}
// Write techniques
for (unsigned i = 0; i < techniques_.Size(); ++i)
{
const TechniqueEntry& entry = techniques_[i];
if (!entry.technique_)
continue;
XMLElement techniqueElem = dest.CreateChild("technique");
techniqueElem.SetString("name", entry.technique_->GetName());
techniqueElem.SetInt("quality", entry.qualityLevel_);
techniqueElem.SetFloat("loddistance", entry.lodDistance_);
}
// Write texture units
for (unsigned j = 0; j < MAX_TEXTURE_UNITS; ++j)
{
Texture* texture = GetTexture((TextureUnit)j);
if (texture)
{
XMLElement textureElem = dest.CreateChild("texture");
textureElem.SetString("unit", textureUnitNames[j]);
textureElem.SetString("name", texture->GetName());
}
}
// Write shader compile defines
if (!vertexShaderDefines_.Empty() || !pixelShaderDefines_.Empty())
{
XMLElement shaderElem = dest.CreateChild("shader");
if (!vertexShaderDefines_.Empty())
shaderElem.SetString("vsdefines", vertexShaderDefines_);
if (!pixelShaderDefines_.Empty())
shaderElem.SetString("psdefines", pixelShaderDefines_);
}
// Write shader parameters
for (HashMap<StringHash, MaterialShaderParameter>::ConstIterator j = shaderParameters_.Begin();
j != shaderParameters_.End(); ++j)
{
XMLElement parameterElem = dest.CreateChild("parameter");
parameterElem.SetString("name", j->second_.name_);
if (j->second_.value_.GetType() != VAR_BUFFER && j->second_.value_.GetType() != VAR_INT && j->second_.value_.GetType() != VAR_BOOL)
parameterElem.SetVectorVariant("value", j->second_.value_);
else
{
parameterElem.SetAttribute("type", j->second_.value_.GetTypeName());
parameterElem.SetAttribute("value", j->second_.value_.ToString());
}
}
// Write shader parameter animations
for (HashMap<StringHash, SharedPtr<ShaderParameterAnimationInfo> >::ConstIterator j = shaderParameterAnimationInfos_.Begin();
j != shaderParameterAnimationInfos_.End(); ++j)
{
ShaderParameterAnimationInfo* info = j->second_;
XMLElement parameterAnimationElem = dest.CreateChild("parameteranimation");
parameterAnimationElem.SetString("name", info->GetName());
if (!info->GetAnimation()->SaveXML(parameterAnimationElem))
return false;
parameterAnimationElem.SetAttribute("wrapmode", wrapModeNames[info->GetWrapMode()]);
parameterAnimationElem.SetFloat("speed", info->GetSpeed());
}
// Write culling modes
XMLElement cullElem = dest.CreateChild("cull");
cullElem.SetString("value", cullModeNames[cullMode_]);
XMLElement shadowCullElem = dest.CreateChild("shadowcull");
shadowCullElem.SetString("value", cullModeNames[shadowCullMode_]);
// Write fill mode
XMLElement fillElem = dest.CreateChild("fill");
fillElem.SetString("value", fillModeNames[fillMode_]);
// Write depth bias
XMLElement depthBiasElem = dest.CreateChild("depthbias");
depthBiasElem.SetFloat("constant", depthBias_.constantBias_);
depthBiasElem.SetFloat("slopescaled", depthBias_.slopeScaledBias_);
// Write alpha-to-coverage
XMLElement alphaToCoverageElem = dest.CreateChild("alphatocoverage");
alphaToCoverageElem.SetBool("enable", alphaToCoverage_);
// Write line anti-alias
XMLElement lineAntiAliasElem = dest.CreateChild("lineantialias");
lineAntiAliasElem.SetBool("enable", lineAntiAlias_);
// Write render order
XMLElement renderOrderElem = dest.CreateChild("renderorder");
renderOrderElem.SetUInt("value", renderOrder_);
// Write occlusion
XMLElement occlusionElem = dest.CreateChild("occlusion");
occlusionElem.SetBool("enable", occlusion_);
return true;
}
bool Material::Save(JSONValue& dest) const
{
// Write techniques
JSONArray techniquesArray;
techniquesArray.Reserve(techniques_.Size());
for (unsigned i = 0; i < techniques_.Size(); ++i)
{
const TechniqueEntry& entry = techniques_[i];
if (!entry.technique_)
continue;
JSONValue techniqueVal;
techniqueVal.Set("name", entry.technique_->GetName());
techniqueVal.Set("quality", (int) entry.qualityLevel_);
techniqueVal.Set("loddistance", entry.lodDistance_);
techniquesArray.Push(techniqueVal);
}
dest.Set("techniques", techniquesArray);
// Write texture units
JSONValue texturesValue;
for (unsigned j = 0; j < MAX_TEXTURE_UNITS; ++j)
{
Texture* texture = GetTexture((TextureUnit)j);
if (texture)
texturesValue.Set(textureUnitNames[j], texture->GetName());
}
dest.Set("textures", texturesValue);
// Write shader compile defines
if (!vertexShaderDefines_.Empty() || !pixelShaderDefines_.Empty())
{
JSONValue shaderVal;
if (!vertexShaderDefines_.Empty())
shaderVal.Set("vsdefines", vertexShaderDefines_);
if (!pixelShaderDefines_.Empty())
shaderVal.Set("psdefines", pixelShaderDefines_);
dest.Set("shader", shaderVal);
}
// Write shader parameters
JSONValue shaderParamsVal;
for (HashMap<StringHash, MaterialShaderParameter>::ConstIterator j = shaderParameters_.Begin();
j != shaderParameters_.End(); ++j)
{
if (j->second_.value_.GetType() != VAR_BUFFER && j->second_.value_.GetType() != VAR_INT && j->second_.value_.GetType() != VAR_BOOL)
shaderParamsVal.Set(j->second_.name_, j->second_.value_.ToString());
else
{
JSONObject valueObj;
valueObj["type"] = j->second_.value_.GetTypeName();
valueObj["value"] = j->second_.value_.ToString();
shaderParamsVal.Set(j->second_.name_, valueObj);
}
}
dest.Set("shaderParameters", shaderParamsVal);
// Write shader parameter animations
JSONValue shaderParamAnimationsVal;
for (HashMap<StringHash, SharedPtr<ShaderParameterAnimationInfo> >::ConstIterator j = shaderParameterAnimationInfos_.Begin();
j != shaderParameterAnimationInfos_.End(); ++j)
{
ShaderParameterAnimationInfo* info = j->second_;
JSONValue paramAnimationVal;
if (!info->GetAnimation()->SaveJSON(paramAnimationVal))
return false;
paramAnimationVal.Set("wrapmode", wrapModeNames[info->GetWrapMode()]);
paramAnimationVal.Set("speed", info->GetSpeed());
shaderParamAnimationsVal.Set(info->GetName(), paramAnimationVal);
}
dest.Set("shaderParameterAnimations", shaderParamAnimationsVal);
// Write culling modes
dest.Set("cull", cullModeNames[cullMode_]);
dest.Set("shadowcull", cullModeNames[shadowCullMode_]);
// Write fill mode
dest.Set("fill", fillModeNames[fillMode_]);
// Write depth bias
JSONValue depthBiasValue;
depthBiasValue.Set("constant", depthBias_.constantBias_);
depthBiasValue.Set("slopescaled", depthBias_.slopeScaledBias_);
dest.Set("depthbias", depthBiasValue);
// Write alpha-to-coverage
dest.Set("alphatocoverage", alphaToCoverage_);
// Write line anti-alias
dest.Set("lineantialias", lineAntiAlias_);
// Write render order
dest.Set("renderorder", (unsigned) renderOrder_);
// Write occlusion
dest.Set("occlusion", occlusion_);
return true;
}
void Material::SetNumTechniques(unsigned num)
{
if (!num)
return;
techniques_.Resize(num);
RefreshMemoryUse();
}
void Material::SetTechnique(unsigned index, Technique* tech, MaterialQuality qualityLevel, float lodDistance)
{
if (index >= techniques_.Size())
return;
techniques_[index] = TechniqueEntry(tech, qualityLevel, lodDistance);
ApplyShaderDefines(index);
}
void Material::SetVertexShaderDefines(const String& defines)
{
if (defines != vertexShaderDefines_)
{
vertexShaderDefines_ = defines;
ApplyShaderDefines();
}
}
void Material::SetPixelShaderDefines(const String& defines)
{
if (defines != pixelShaderDefines_)
{
pixelShaderDefines_ = defines;
ApplyShaderDefines();
}
}
void Material::SetShaderParameter(const String& name, const Variant& value)
{
MaterialShaderParameter newParam;
newParam.name_ = name;
newParam.value_ = value;
StringHash nameHash(name);
shaderParameters_[nameHash] = newParam;
if (nameHash == PSP_MATSPECCOLOR)
{
VariantType type = value.GetType();
if (type == VAR_VECTOR3)
{
const Vector3& vec = value.GetVector3();
specular_ = vec.x_ > 0.0f || vec.y_ > 0.0f || vec.z_ > 0.0f;
}
else if (type == VAR_VECTOR4)
{
const Vector4& vec = value.GetVector4();
specular_ = vec.x_ > 0.0f || vec.y_ > 0.0f || vec.z_ > 0.0f;
}
}
if (!batchedParameterUpdate_)
{
RefreshShaderParameterHash();
RefreshMemoryUse();
}
}
void Material::SetShaderParameterAnimation(const String& name, ValueAnimation* animation, WrapMode wrapMode, float speed)
{
ShaderParameterAnimationInfo* info = GetShaderParameterAnimationInfo(name);
if (animation)
{
if (info && info->GetAnimation() == animation)
{
info->SetWrapMode(wrapMode);
info->SetSpeed(speed);
return;
}
if (shaderParameters_.Find(name) == shaderParameters_.End())
{
URHO3D_LOGERROR(GetName() + " has no shader parameter: " + name);
return;
}
StringHash nameHash(name);
shaderParameterAnimationInfos_[nameHash] = new ShaderParameterAnimationInfo(this, name, animation, wrapMode, speed);
UpdateEventSubscription();
}
else
{
if (info)
{
StringHash nameHash(name);
shaderParameterAnimationInfos_.Erase(nameHash);
UpdateEventSubscription();
}
}
}
void Material::SetShaderParameterAnimationWrapMode(const String& name, WrapMode wrapMode)
{
ShaderParameterAnimationInfo* info = GetShaderParameterAnimationInfo(name);
if (info)
info->SetWrapMode(wrapMode);
}
void Material::SetShaderParameterAnimationSpeed(const String& name, float speed)
{
ShaderParameterAnimationInfo* info = GetShaderParameterAnimationInfo(name);
if (info)
info->SetSpeed(speed);
}
void Material::SetTexture(TextureUnit unit, Texture* texture)
{
if (unit < MAX_TEXTURE_UNITS)
{
if (texture)
textures_[unit] = texture;
else
textures_.Erase(unit);
}
}
void Material::SetUVTransform(const Vector2& offset, float rotation, const Vector2& repeat)
{
Matrix3x4 transform(Matrix3x4::IDENTITY);
transform.m00_ = repeat.x_;
transform.m11_ = repeat.y_;
Matrix3x4 rotationMatrix(Matrix3x4::IDENTITY);
rotationMatrix.m00_ = Cos(rotation);
rotationMatrix.m01_ = Sin(rotation);
rotationMatrix.m10_ = -rotationMatrix.m01_;
rotationMatrix.m11_ = rotationMatrix.m00_;
rotationMatrix.m03_ = 0.5f - 0.5f * (rotationMatrix.m00_ + rotationMatrix.m01_);
rotationMatrix.m13_ = 0.5f - 0.5f * (rotationMatrix.m10_ + rotationMatrix.m11_);
transform = transform * rotationMatrix;
Matrix3x4 offsetMatrix = Matrix3x4::IDENTITY;
offsetMatrix.m03_ = offset.x_;
offsetMatrix.m13_ = offset.y_;
transform = offsetMatrix * transform;
SetShaderParameter("UOffset", Vector4(transform.m00_, transform.m01_, transform.m02_, transform.m03_));
SetShaderParameter("VOffset", Vector4(transform.m10_, transform.m11_, transform.m12_, transform.m13_));
}
void Material::SetUVTransform(const Vector2& offset, float rotation, float repeat)
{
SetUVTransform(offset, rotation, Vector2(repeat, repeat));
}
void Material::SetCullMode(CullMode mode)
{
cullMode_ = mode;
}
void Material::SetShadowCullMode(CullMode mode)
{
shadowCullMode_ = mode;
}
void Material::SetFillMode(FillMode mode)
{
fillMode_ = mode;
}
void Material::SetDepthBias(const BiasParameters& parameters)
{
depthBias_ = parameters;
depthBias_.Validate();
}
void Material::SetAlphaToCoverage(bool enable)
{
alphaToCoverage_ = enable;
}
void Material::SetLineAntiAlias(bool enable)
{
lineAntiAlias_ = enable;
}
void Material::SetRenderOrder(unsigned char order)
{
renderOrder_ = order;
}
void Material::SetOcclusion(bool enable)
{
occlusion_ = enable;
}
void Material::SetScene(Scene* scene)
{
UnsubscribeFromEvent(E_UPDATE);
UnsubscribeFromEvent(E_ATTRIBUTEANIMATIONUPDATE);
subscribed_ = false;
scene_ = scene;
UpdateEventSubscription();
}
void Material::RemoveShaderParameter(const String& name)
{
StringHash nameHash(name);
shaderParameters_.Erase(nameHash);
if (nameHash == PSP_MATSPECCOLOR)
specular_ = false;
RefreshShaderParameterHash();
RefreshMemoryUse();
}
void Material::ReleaseShaders()
{
for (unsigned i = 0; i < techniques_.Size(); ++i)
{
Technique* tech = techniques_[i].technique_;
if (tech)
tech->ReleaseShaders();
}
}
SharedPtr<Material> Material::Clone(const String& cloneName) const
{
SharedPtr<Material> ret(new Material(context_));
ret->SetName(cloneName);
ret->techniques_ = techniques_;
ret->vertexShaderDefines_ = vertexShaderDefines_;
ret->pixelShaderDefines_ = pixelShaderDefines_;
ret->shaderParameters_ = shaderParameters_;
ret->shaderParameterHash_ = shaderParameterHash_;
ret->textures_ = textures_;
ret->depthBias_ = depthBias_;
ret->alphaToCoverage_ = alphaToCoverage_;
ret->lineAntiAlias_ = lineAntiAlias_;
ret->occlusion_ = occlusion_;
ret->specular_ = specular_;
ret->cullMode_ = cullMode_;
ret->shadowCullMode_ = shadowCullMode_;
ret->fillMode_ = fillMode_;
ret->renderOrder_ = renderOrder_;
ret->RefreshMemoryUse();
return ret;
}
void Material::SortTechniques()
{
Sort(techniques_.Begin(), techniques_.End(), CompareTechniqueEntries);
}
void Material::MarkForAuxView(unsigned frameNumber)
{
auxViewFrameNumber_ = frameNumber;
}
const TechniqueEntry& Material::GetTechniqueEntry(unsigned index) const
{
return index < techniques_.Size() ? techniques_[index] : noEntry;
}
Technique* Material::GetTechnique(unsigned index) const
{
return index < techniques_.Size() ? techniques_[index].technique_ : nullptr;
}
Pass* Material::GetPass(unsigned index, const String& passName) const
{
Technique* tech = index < techniques_.Size() ? techniques_[index].technique_ : nullptr;
return tech ? tech->GetPass(passName) : nullptr;
}
Texture* Material::GetTexture(TextureUnit unit) const
{
HashMap<TextureUnit, SharedPtr<Texture> >::ConstIterator i = textures_.Find(unit);
return i != textures_.End() ? i->second_.Get() : nullptr;
}
const Variant& Material::GetShaderParameter(const String& name) const
{
HashMap<StringHash, MaterialShaderParameter>::ConstIterator i = shaderParameters_.Find(name);
return i != shaderParameters_.End() ? i->second_.value_ : Variant::EMPTY;
}
ValueAnimation* Material::GetShaderParameterAnimation(const String& name) const
{
ShaderParameterAnimationInfo* info = GetShaderParameterAnimationInfo(name);
return info == nullptr ? nullptr : info->GetAnimation();
}
WrapMode Material::GetShaderParameterAnimationWrapMode(const String& name) const
{
ShaderParameterAnimationInfo* info = GetShaderParameterAnimationInfo(name);
return info == nullptr ? WM_LOOP : info->GetWrapMode();
}
float Material::GetShaderParameterAnimationSpeed(const String& name) const
{
ShaderParameterAnimationInfo* info = GetShaderParameterAnimationInfo(name);
return info == nullptr ? 0 : info->GetSpeed();
}
Scene* Material::GetScene() const
{
return scene_;
}
String Material::GetTextureUnitName(TextureUnit unit)
{
return textureUnitNames[unit];
}
Variant Material::ParseShaderParameterValue(const String& value)
{
String valueTrimmed = value.Trimmed();
if (valueTrimmed.Length() && IsAlpha((unsigned)valueTrimmed[0]))
return Variant(ToBool(valueTrimmed));
else
return ToVectorVariant(valueTrimmed);
}
void Material::ResetToDefaults()
{
// Needs to be a no-op when async loading, as this does a GetResource() which is not allowed from worker threads
if (!Thread::IsMainThread())
return;
vertexShaderDefines_.Clear();
pixelShaderDefines_.Clear();
SetNumTechniques(1);
auto* renderer = GetSubsystem<Renderer>();
SetTechnique(0, renderer ? renderer->GetDefaultTechnique() :
GetSubsystem<ResourceCache>()->GetResource<Technique>("Techniques/NoTexture.xml"));
textures_.Clear();
batchedParameterUpdate_ = true;
shaderParameters_.Clear();
shaderParameterAnimationInfos_.Clear();
SetShaderParameter("UOffset", Vector4(1.0f, 0.0f, 0.0f, 0.0f));
SetShaderParameter("VOffset", Vector4(0.0f, 1.0f, 0.0f, 0.0f));
SetShaderParameter("MatDiffColor", Vector4::ONE);
SetShaderParameter("MatEmissiveColor", Vector3::ZERO);
SetShaderParameter("MatEnvMapColor", Vector3::ONE);
SetShaderParameter("MatSpecColor", Vector4(0.0f, 0.0f, 0.0f, 1.0f));
SetShaderParameter("Roughness", 0.5f);
SetShaderParameter("Metallic", 0.0f);
batchedParameterUpdate_ = false;
cullMode_ = CULL_CCW;
shadowCullMode_ = CULL_CCW;
fillMode_ = FILL_SOLID;
depthBias_ = BiasParameters(0.0f, 0.0f);
renderOrder_ = DEFAULT_RENDER_ORDER;
occlusion_ = true;
UpdateEventSubscription();
RefreshShaderParameterHash();
RefreshMemoryUse();
}
void Material::RefreshShaderParameterHash()
{
VectorBuffer temp;
for (HashMap<StringHash, MaterialShaderParameter>::ConstIterator i = shaderParameters_.Begin();
i != shaderParameters_.End(); ++i)
{
temp.WriteStringHash(i->first_);
temp.WriteVariant(i->second_.value_);
}
shaderParameterHash_ = 0;
const unsigned char* data = temp.GetData();
unsigned dataSize = temp.GetSize();
for (unsigned i = 0; i < dataSize; ++i)
shaderParameterHash_ = SDBMHash(shaderParameterHash_, data[i]);
}
void Material::RefreshMemoryUse()
{
unsigned memoryUse = sizeof(Material);
memoryUse += techniques_.Size() * sizeof(TechniqueEntry);
memoryUse += MAX_TEXTURE_UNITS * sizeof(SharedPtr<Texture>);
memoryUse += shaderParameters_.Size() * sizeof(MaterialShaderParameter);
SetMemoryUse(memoryUse);
}
ShaderParameterAnimationInfo* Material::GetShaderParameterAnimationInfo(const String& name) const
{
StringHash nameHash(name);
HashMap<StringHash, SharedPtr<ShaderParameterAnimationInfo> >::ConstIterator i = shaderParameterAnimationInfos_.Find(nameHash);
if (i == shaderParameterAnimationInfos_.End())
return nullptr;
return i->second_;
}
void Material::UpdateEventSubscription()
{
if (shaderParameterAnimationInfos_.Size() && !subscribed_)
{
if (scene_)
SubscribeToEvent(scene_, E_ATTRIBUTEANIMATIONUPDATE, URHO3D_HANDLER(Material, HandleAttributeAnimationUpdate));
else
SubscribeToEvent(E_UPDATE, URHO3D_HANDLER(Material, HandleAttributeAnimationUpdate));
subscribed_ = true;
}
else if (subscribed_ && shaderParameterAnimationInfos_.Empty())
{
UnsubscribeFromEvent(E_UPDATE);
UnsubscribeFromEvent(E_ATTRIBUTEANIMATIONUPDATE);
subscribed_ = false;
}
}
void Material::HandleAttributeAnimationUpdate(StringHash eventType, VariantMap& eventData)
{
// Timestep parameter is same no matter what event is being listened to
float timeStep = eventData[Update::P_TIMESTEP].GetFloat();
// Keep weak pointer to self to check for destruction caused by event handling
WeakPtr<Object> self(this);
Vector<String> finishedNames;
for (HashMap<StringHash, SharedPtr<ShaderParameterAnimationInfo> >::ConstIterator i = shaderParameterAnimationInfos_.Begin();
i != shaderParameterAnimationInfos_.End(); ++i)
{
bool finished = i->second_->Update(timeStep);
// If self deleted as a result of an event sent during animation playback, nothing more to do
if (self.Expired())
return;
if (finished)
finishedNames.Push(i->second_->GetName());
}
// Remove finished animations
for (unsigned i = 0; i < finishedNames.Size(); ++i)
SetShaderParameterAnimation(finishedNames[i], nullptr);
}
void Material::ApplyShaderDefines(unsigned index)
{
if (index == M_MAX_UNSIGNED)
{
for (unsigned i = 0; i < techniques_.Size(); ++i)
ApplyShaderDefines(i);
return;
}
if (index >= techniques_.Size() || !techniques_[index].original_)
return;
if (vertexShaderDefines_.Empty() && pixelShaderDefines_.Empty())
techniques_[index].technique_ = techniques_[index].original_;
else
techniques_[index].technique_ = techniques_[index].original_->CloneWithDefines(vertexShaderDefines_, pixelShaderDefines_);
}
}
| 33.540014 | 140 | 0.637769 | [
"render",
"object",
"vector",
"transform",
"solid"
] |
c80da3ac10fd852906ae6b6132384d7134d11f54 | 4,264 | cpp | C++ | core/utilities/FileSystemUtils.cpp | dkesler-execom/WolkSDK-Cpp | fd353d34affa5c252f5a1022c9fc1b6ae9a285a5 | [
"Apache-2.0"
] | null | null | null | core/utilities/FileSystemUtils.cpp | dkesler-execom/WolkSDK-Cpp | fd353d34affa5c252f5a1022c9fc1b6ae9a285a5 | [
"Apache-2.0"
] | null | null | null | core/utilities/FileSystemUtils.cpp | dkesler-execom/WolkSDK-Cpp | fd353d34affa5c252f5a1022c9fc1b6ae9a285a5 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2018 WolkAbout Technology s.r.o.
*
* 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 "utilities/FileSystemUtils.h"
#include <dirent.h>
#include <fstream>
#include <sys/stat.h>
namespace wolkabout
{
const char FileSystemUtils::PATH_DELIMITER = '/';
bool FileSystemUtils::isFilePresent(const std::string& filePath)
{
FILE* configFile = ::fopen(filePath.c_str(), "r");
if (!configFile)
{
return false;
}
fclose(configFile);
return true;
}
bool FileSystemUtils::createFileWithContent(const std::string& filePath, const std::string& content)
{
try
{
std::ofstream ofstream;
ofstream.open(filePath);
if (!ofstream.is_open())
{
return false;
}
ofstream << content;
if (!ofstream)
{
deleteFile(filePath);
return false;
}
return true;
}
catch (...)
{
return false;
}
}
bool FileSystemUtils::createBinaryFileWithContent(const std::string& filePath, const ByteArray& content)
{
try
{
std::ofstream ofstream;
ofstream.open(filePath, std::ofstream::binary);
if (!ofstream.is_open())
{
return false;
}
ofstream.write(reinterpret_cast<const char*>(content.data()), content.size());
if (!ofstream)
{
deleteFile(filePath);
return false;
}
return true;
}
catch (...)
{
return false;
}
}
bool FileSystemUtils::deleteFile(const std::string& filePath)
{
return std::remove(filePath.c_str()) == 0;
}
bool FileSystemUtils::isDirectoryPresent(const std::string& dirPath)
{
struct stat status;
if (stat(dirPath.c_str(), &status) == 0)
{
return (status.st_mode & S_IFDIR) != 0;
}
return false;
}
bool FileSystemUtils::createDirectory(const std::string& dirPath)
{
if (isDirectoryPresent(dirPath))
{
return true;
}
return mkdir(dirPath.c_str(), 0700) == 0;
}
bool FileSystemUtils::readFileContent(const std::string& filePath, std::string& content)
{
std::ifstream ifstream(filePath);
if (!ifstream.is_open())
{
return false;
}
content = std::string((std::istreambuf_iterator<char>(ifstream)), std::istreambuf_iterator<char>());
return true;
}
bool FileSystemUtils::readBinaryFileContent(const std::string& filePath, ByteArray& content)
{
std::ifstream ifstream(filePath, std::ofstream::binary);
if (!ifstream.is_open())
{
return false;
}
content =
ByteUtils::toByteArray(std::string((std::istreambuf_iterator<char>(ifstream)), std::istreambuf_iterator<char>()));
return true;
}
std::vector<std::string> FileSystemUtils::listFiles(const std::string& directoryPath)
{
std::vector<std::string> result;
DIR* dp = nullptr;
struct dirent* dirp = nullptr;
if ((dp = opendir(directoryPath.c_str())) == nullptr)
{
return result;
}
while ((dirp = readdir(dp)) != nullptr)
{
if (dirp->d_type == DT_REG)
{
result.emplace_back(dirp->d_name);
}
}
closedir(dp);
return result;
}
std::string FileSystemUtils::composePath(const std::string& fileName, const std::string& directory)
{
if (directory.empty())
{
return fileName;
}
return directory + PATH_DELIMITER + fileName;
}
std::string FileSystemUtils::absolutePath(const std::string& path)
{
char* reslovedPath = realpath(path.c_str(), NULL);
if (reslovedPath)
{
std::string fullPath(reslovedPath);
free(reslovedPath);
return fullPath;
}
return "";
}
} // namespace wolkabout
| 22.324607 | 120 | 0.624296 | [
"vector"
] |
c8102bbda487f57339cee1e91067bfa1a083fbae | 5,205 | cpp | C++ | tuw_multi_robot_rviz/src/RobotGoalsArrayDisplay.cpp | qzlinqian/tuw_multi_robot | ed42d8535fa7bc34fb40f6067bc3290c13023609 | [
"BSD-3-Clause"
] | null | null | null | tuw_multi_robot_rviz/src/RobotGoalsArrayDisplay.cpp | qzlinqian/tuw_multi_robot | ed42d8535fa7bc34fb40f6067bc3290c13023609 | [
"BSD-3-Clause"
] | null | null | null | tuw_multi_robot_rviz/src/RobotGoalsArrayDisplay.cpp | qzlinqian/tuw_multi_robot | ed42d8535fa7bc34fb40f6067bc3290c13023609 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2012, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <OGRE/OgreSceneNode.h>
#include <OGRE/OgreSceneManager.h>
#include <tf/transform_listener.h>
#include <rviz/visualization_manager.h>
#include <rviz/properties/color_property.h>
#include <rviz/properties/float_property.h>
#include <rviz/frame_manager.h>
#include "tuw_multi_robot_rviz/RobotGoalsArrayDisplay.h"
#include "tuw_multi_robot_rviz/RobotGoalsArrayVisual.h"
namespace tuw_multi_robot_rviz {
// The constructor must have no arguments, so we can't give the
// constructor the parameters it needs to fully initialize.
RobotGoalsArrayDisplay::RobotGoalsArrayDisplay() {
property_scale_pose_ = new rviz::FloatProperty ( "Scale Pose", 0.1,
"Scale of the pose's pose.",
this, SLOT ( updateScalePose() ) );
property_scale_pose_->setMin ( 0 );
property_scale_pose_->setMax ( 1 );
property_color_pose_ = new rviz::ColorProperty ( "Color Pose", QColor ( 204, 51, 0 ),
"Color to draw the pose's pose.",
this, SLOT ( updateColorPose() ) );
}
// After the top-level rviz::Display::initialize() does its own setup,
// it calls the subclass's onInitialize() function. This is where we
// instantiate all the workings of the class. We make sure to also
// call our immediate super-class's onInitialize() function, since it
// does important stuff setting up the message filter.
//
// Note that "MFDClass" is a typedef of
// ``MessageFilterDisplay<message type>``, to save typing that long
// templated class name every time you need to refer to the
// superclass.
void RobotGoalsArrayDisplay::onInitialize() {
MFDClass::onInitialize();
visual_.reset ( new RobotGoalsArrayVisual ( context_->getSceneManager(), scene_node_ ) );
}
RobotGoalsArrayDisplay::~RobotGoalsArrayDisplay() {
}
// Clear the visual by deleting its object.
void RobotGoalsArrayDisplay::reset() {
MFDClass::reset();
}
// Set the current scale for the visual's pose.
void RobotGoalsArrayDisplay::updateScalePose() {
float scale = property_scale_pose_->getFloat();
visual_->setScalePose ( scale );
}
// Set the current color for the visual's pose.
void RobotGoalsArrayDisplay::updateColorPose() {
Ogre::ColourValue color = property_color_pose_->getOgreColor();
visual_->setColorPose ( color );
}
// This is our callback to handle an incoming message.
void RobotGoalsArrayDisplay::processMessage ( const tuw_multi_robot_msgs::RobotGoalsArray::ConstPtr& msg ) {
// Here we call the rviz::FrameManager to get the transform from the
// fixed frame to the frame in the header of this Imu message. If
// it fails, we can't do anything else so we return.
Ogre::Quaternion orientation;
Ogre::Vector3 position;
if ( !context_->getFrameManager()->getTransform ( msg->header.frame_id, msg->header.stamp, position, orientation ) ) {
ROS_DEBUG ( "Error transforming from frame '%s' to frame '%s'",
msg->header.frame_id.c_str(), qPrintable ( fixed_frame_ ) );
return;
}
// Now set or update the contents of the visual.
visual_->setMessage ( msg );
visual_->setFramePosition ( position );
visual_->setFrameOrientation ( orientation );
visual_->setScalePose ( property_scale_pose_->getFloat() );
visual_->setColorPose ( property_color_pose_->getOgreColor() );
}
} // end namespace tuw_geometry_rviz
// Tell pluginlib about this class. It is important to do this in
// global scope, outside our package's namespace.
#include <pluginlib/class_list_macros.h>
PLUGINLIB_EXPORT_CLASS (tuw_multi_robot_rviz::RobotGoalsArrayDisplay,rviz::Display )
| 42.317073 | 122 | 0.733141 | [
"object",
"transform"
] |
c814fe86694edb6ae48a5cfb6eddfd84685a24bf | 14,050 | hpp | C++ | headers/3.4/opencv2/stereo.hpp | christian-boks/opencv-rust | 6b93c859b83c60c8f6b939625780054a69034636 | [
"MIT"
] | 2 | 2020-07-22T09:56:37.000Z | 2021-07-15T03:01:36.000Z | headers/3.4/opencv2/stereo.hpp | christian-boks/opencv-rust | 6b93c859b83c60c8f6b939625780054a69034636 | [
"MIT"
] | null | null | null | headers/3.4/opencv2/stereo.hpp | christian-boks/opencv-rust | 6b93c859b83c60c8f6b939625780054a69034636 | [
"MIT"
] | null | null | null | /*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Copyright (C) 2013, OpenCV Foundation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of the copyright holders may not 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 Intel Corporation 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.
//
//M*/
#ifndef __OPENCV_STEREO_HPP__
#define __OPENCV_STEREO_HPP__
#include "opencv2/core.hpp"
#include "opencv2/stereo/descriptor.hpp"
/**
@defgroup stereo Stereo Correspondance Algorithms
*/
namespace cv
{
namespace stereo
{
//! @addtogroup stereo
//! @{
/** @brief Filters off small noise blobs (speckles) in the disparity map
@param img The input 16-bit signed disparity image
@param newVal The disparity value used to paint-off the speckles
@param maxSpeckleSize The maximum speckle size to consider it a speckle. Larger blobs are not
affected by the algorithm
@param maxDiff Maximum difference between neighbor disparity pixels to put them into the same
blob. Note that since StereoBM, StereoSGBM and may be other algorithms return a fixed-point
disparity map, where disparity values are multiplied by 16, this scale factor should be taken into
account when specifying this parameter value.
@param buf The optional temporary buffer to avoid memory allocation within the function.
*/
/** @brief The base class for stereo correspondence algorithms.
*/
class StereoMatcher : public Algorithm
{
public:
enum { DISP_SHIFT = 4,
DISP_SCALE = (1 << DISP_SHIFT)
};
/** @brief Computes disparity map for the specified stereo pair
@param left Left 8-bit single-channel image.
@param right Right image of the same size and the same type as the left one.
@param disparity Output disparity map. It has the same size as the input images. Some algorithms,
like StereoBM or StereoSGBM compute 16-bit fixed-point disparity map (where each disparity value
has 4 fractional bits), whereas other algorithms output 32-bit floating-point disparity map.
*/
virtual void compute( InputArray left, InputArray right,
OutputArray disparity ) = 0;
virtual int getMinDisparity() const = 0;
virtual void setMinDisparity(int minDisparity) = 0;
virtual int getNumDisparities() const = 0;
virtual void setNumDisparities(int numDisparities) = 0;
virtual int getBlockSize() const = 0;
virtual void setBlockSize(int blockSize) = 0;
virtual int getSpeckleWindowSize() const = 0;
virtual void setSpeckleWindowSize(int speckleWindowSize) = 0;
virtual int getSpeckleRange() const = 0;
virtual void setSpeckleRange(int speckleRange) = 0;
virtual int getDisp12MaxDiff() const = 0;
virtual void setDisp12MaxDiff(int disp12MaxDiff) = 0;
};
//!speckle removal algorithms. These algorithms have the purpose of removing small regions
enum {
CV_SPECKLE_REMOVAL_ALGORITHM, CV_SPECKLE_REMOVAL_AVG_ALGORITHM
};
//!subpixel interpolationm methods for disparities.
enum{
CV_QUADRATIC_INTERPOLATION, CV_SIMETRICV_INTERPOLATION
};
/** @brief Class for computing stereo correspondence using the block matching algorithm, introduced and
contributed to OpenCV by K. Konolige.
*/
class StereoBinaryBM : public StereoMatcher
{
public:
enum { PREFILTER_NORMALIZED_RESPONSE = 0,
PREFILTER_XSOBEL = 1
};
virtual int getPreFilterType() const = 0;
virtual void setPreFilterType(int preFilterType) = 0;
virtual int getPreFilterSize() const = 0;
virtual void setPreFilterSize(int preFilterSize) = 0;
virtual int getPreFilterCap() const = 0;
virtual void setPreFilterCap(int preFilterCap) = 0;
virtual int getTextureThreshold() const = 0;
virtual void setTextureThreshold(int textureThreshold) = 0;
virtual int getUniquenessRatio() const = 0;
virtual void setUniquenessRatio(int uniquenessRatio) = 0;
virtual int getSmallerBlockSize() const = 0;
virtual void setSmallerBlockSize(int blockSize) = 0;
virtual int getScalleFactor() const = 0 ;
virtual void setScalleFactor(int factor) = 0;
virtual int getSpekleRemovalTechnique() const = 0 ;
virtual void setSpekleRemovalTechnique(int factor) = 0;
virtual bool getUsePrefilter() const = 0 ;
virtual void setUsePrefilter(bool factor) = 0;
virtual int getBinaryKernelType() const = 0;
virtual void setBinaryKernelType(int value) = 0;
virtual int getAgregationWindowSize() const = 0;
virtual void setAgregationWindowSize(int value) = 0;
/** @brief Creates StereoBM object
@param numDisparities the disparity search range. For each pixel algorithm will find the best
disparity from 0 (default minimum disparity) to numDisparities. The search range can then be
shifted by changing the minimum disparity.
@param blockSize the linear size of the blocks compared by the algorithm. The size should be odd
(as the block is centered at the current pixel). Larger block size implies smoother, though less
accurate disparity map. Smaller block size gives more detailed disparity map, but there is higher
chance for algorithm to find a wrong correspondence.
The function create StereoBM object. You can then call StereoBM::compute() to compute disparity for
a specific stereo pair.
*/
CV_EXPORTS static Ptr< cv::stereo::StereoBinaryBM > create(int numDisparities = 0, int blockSize = 9);
};
/** @brief The class implements the modified H. Hirschmuller algorithm @cite HH08 that differs from the original
one as follows:
- By default, the algorithm is single-pass, which means that you consider only 5 directions
instead of 8. Set mode=StereoSGBM::MODE_HH in createStereoSGBM to run the full variant of the
algorithm but beware that it may consume a lot of memory.
- The algorithm matches blocks, not individual pixels. Though, setting blockSize=1 reduces the
blocks to single pixels.
- Mutual information cost function is not implemented. Instead, a simpler Birchfield-Tomasi
sub-pixel metric from @cite BT98 is used. Though, the color images are supported as well.
- Some pre- and post- processing steps from K. Konolige algorithm StereoBM are included, for
example: pre-filtering (StereoBM::PREFILTER_XSOBEL type) and post-filtering (uniqueness
check, quadratic interpolation and speckle filtering).
@note
- (Python) An example illustrating the use of the StereoSGBM matching algorithm can be found
at opencv_source_code/samples/python2/stereo_match.py
*/
class StereoBinarySGBM : public StereoMatcher
{
public:
enum
{
MODE_SGBM = 0,
MODE_HH = 1
};
virtual int getPreFilterCap() const = 0;
virtual void setPreFilterCap(int preFilterCap) = 0;
virtual int getUniquenessRatio() const = 0;
virtual void setUniquenessRatio(int uniquenessRatio) = 0;
virtual int getP1() const = 0;
virtual void setP1(int P1) = 0;
virtual int getP2() const = 0;
virtual void setP2(int P2) = 0;
virtual int getMode() const = 0;
virtual void setMode(int mode) = 0;
virtual int getSpekleRemovalTechnique() const = 0 ;
virtual void setSpekleRemovalTechnique(int factor) = 0;
virtual int getBinaryKernelType() const = 0;
virtual void setBinaryKernelType(int value) = 0;
virtual int getSubPixelInterpolationMethod() const = 0;
virtual void setSubPixelInterpolationMethod(int value) = 0;
/** @brief Creates StereoSGBM object
@param minDisparity Minimum possible disparity value. Normally, it is zero but sometimes
rectification algorithms can shift images, so this parameter needs to be adjusted accordingly.
@param numDisparities Maximum disparity minus minimum disparity. The value is always greater than
zero. In the current implementation, this parameter must be divisible by 16.
@param blockSize Matched block size. It must be an odd number \>=1 . Normally, it should be
somewhere in the 3..11 range.
@param P1 The first parameter controlling the disparity smoothness.This parameter is used for the case of slanted surfaces (not fronto parallel).
@param P2 The second parameter controlling the disparity smoothness.This parameter is used for "solving" the depth discontinuities problem.
The larger the values are, the smoother the disparity is. P1 is the penalty on the disparity change by plus or minus 1
between neighbor pixels. P2 is the penalty on the disparity change by more than 1 between neighbor
pixels. The algorithm requires P2 \> P1 . See stereo_match.cpp sample where some reasonably good
P1 and P2 values are shown (like 8\*number_of_image_channels\*SADWindowSize\*SADWindowSize and
32\*number_of_image_channels\*SADWindowSize\*SADWindowSize , respectively).
@param disp12MaxDiff Maximum allowed difference (in integer pixel units) in the left-right
disparity check. Set it to a non-positive value to disable the check.
@param preFilterCap Truncation value for the prefiltered image pixels. The algorithm first
computes x-derivative at each pixel and clips its value by [-preFilterCap, preFilterCap] interval.
The result values are passed to the Birchfield-Tomasi pixel cost function.
@param uniquenessRatio Margin in percentage by which the best (minimum) computed cost function
value should "win" the second best value to consider the found match correct. Normally, a value
within the 5-15 range is good enough.
@param speckleWindowSize Maximum size of smooth disparity regions to consider their noise speckles
and invalidate. Set it to 0 to disable speckle filtering. Otherwise, set it somewhere in the
50-200 range.
@param speckleRange Maximum disparity variation within each connected component. If you do speckle
filtering, set the parameter to a positive value, it will be implicitly multiplied by 16.
Normally, 1 or 2 is good enough.
@param mode Set it to StereoSGBM::MODE_HH to run the full-scale two-pass dynamic programming
algorithm. It will consume O(W\*H\*numDisparities) bytes, which is large for 640x480 stereo and
huge for HD-size pictures. By default, it is set to false .
The first constructor initializes StereoSGBM with all the default parameters. So, you only have to
set StereoSGBM::numDisparities at minimum. The second constructor enables you to set each parameter
to a custom value.
*/
CV_EXPORTS static Ptr<cv::stereo::StereoBinarySGBM> create(int minDisparity, int numDisparities, int blockSize,
int P1 = 100, int P2 = 1000, int disp12MaxDiff = 1,
int preFilterCap = 0, int uniquenessRatio = 5,
int speckleWindowSize = 400, int speckleRange = 200,
int mode = StereoBinarySGBM::MODE_SGBM);
};
//! @}
}//stereo
} // cv
#endif
| 50.905797 | 157 | 0.668399 | [
"object"
] |
c8150230577632fa9cb732b8ac46b2fc080d12f3 | 7,821 | cpp | C++ | test/BaseTestProperty.cpp | stoewer/nix | 7fe4669284b60b6a27228c2da7d3f61a77c943dc | [
"BSD-3-Clause"
] | null | null | null | test/BaseTestProperty.cpp | stoewer/nix | 7fe4669284b60b6a27228c2da7d3f61a77c943dc | [
"BSD-3-Clause"
] | null | null | null | test/BaseTestProperty.cpp | stoewer/nix | 7fe4669284b60b6a27228c2da7d3f61a77c943dc | [
"BSD-3-Clause"
] | null | null | null | // Copyright © 2014 German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.
//
// Author: Christian Kellner <kellner@bio.lmu.de>
#include <ctime>
#include <iostream>
#include <sstream>
#include <iterator>
#include <stdexcept>
#include <limits>
#include <boost/math/constants/constants.hpp>
#include <boost/iterator/zip_iterator.hpp>
#include <nix/util/util.hpp>
#include <nix/valid/validate.hpp>
#include "BaseTestProperty.hpp"
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/CompilerOutputter.h>
#include <cppunit/TestResult.h>
#include <cppunit/TestResultCollector.h>
#include <cppunit/TestRunner.h>
#include <cppunit/BriefTestProgressListener.h>
using namespace nix;
using namespace valid;
void BaseTestProperty::testValidate() {
// values are set but unit is missing: 1 warning
valid::Result result = validate(property);
CPPUNIT_ASSERT(result.getErrors().size() == 0);
CPPUNIT_ASSERT(result.getWarnings().size() == 1);
}
void BaseTestProperty::testId() {
CPPUNIT_ASSERT(property.id().size() == 36);
}
void BaseTestProperty::testName() {
CPPUNIT_ASSERT(property.name() == "prop");
}
void BaseTestProperty::testDefinition() {
std::string def = "some_str";
property.definition(def);
CPPUNIT_ASSERT(*property.definition() == def);
property.definition(nix::none);
CPPUNIT_ASSERT(property.definition() == nix::none);
CPPUNIT_ASSERT_THROW(property.definition(""), EmptyString);
}
void BaseTestProperty::testMapping() {
std::string map = "some_str";
CPPUNIT_ASSERT_THROW(property.mapping(""), EmptyString);
property.mapping(map);
CPPUNIT_ASSERT(*property.mapping() == map);
property.mapping(boost::none);
CPPUNIT_ASSERT(!property.mapping());
}
void BaseTestProperty::testValues()
{
nix::Section section = file.createSection("Area51", "Boolean");
nix::Property p1 = section.createProperty("strProperty", str_dummy);
std::vector<nix::Value> strValues = { nix::Value("Freude"),
nix::Value("schoener"),
nix::Value("Goetterfunken") };
p1.values(strValues);
CPPUNIT_ASSERT_EQUAL(p1.valueCount(), static_cast<ndsize_t>(strValues.size()));
std::vector<nix::Value> ctrlValues = p1.values();
for(size_t i = 0; i < ctrlValues.size(); ++i) {
CPPUNIT_ASSERT_EQUAL(strValues[i], ctrlValues[i]);
}
strValues.emplace_back("Tochter");
strValues.emplace_back("aus");
strValues.emplace_back("Elysium");
strValues.emplace_back("Wir betreten feuertrunken");
p1.values(strValues);
CPPUNIT_ASSERT_EQUAL(p1.valueCount(), static_cast<ndsize_t>(strValues.size()));
strValues.erase(strValues.begin()+6);
p1.values(strValues);
CPPUNIT_ASSERT_EQUAL(p1.valueCount(), static_cast<ndsize_t>(strValues.size()));
nix::Property p2 = section.createProperty("toDelete", str_dummy);
CPPUNIT_ASSERT(p2.valueCount() == 1);
CPPUNIT_ASSERT_EQUAL(p2.values()[0], str_dummy);
strValues.clear();
p2.values(strValues);
CPPUNIT_ASSERT_EQUAL(p2.valueCount(), static_cast<ndsize_t>(strValues.size()));
p2.deleteValues();
CPPUNIT_ASSERT(p2.values().empty() == true);
p2.values(strValues);
p2.values(none);
CPPUNIT_ASSERT(p2.values().empty() == true);
}
void BaseTestProperty::testDataType() {
nix::Section section = file.createSection("Area51", "Boolean");
std::vector<nix::Value> strValues = { nix::Value("Freude"),
nix::Value("schoener"),
nix::Value("Goetterfunken") };
std::vector<nix::Value> doubleValues = { nix::Value(1.0),
nix::Value(2.0),
nix::Value(-99.99) };
std::vector<nix::Value> intValues = {nix::Value(int32_t(1)), nix::Value(int32_t(2)), nix::Value(int32_t(3))};
std::vector<nix::Value> uintValues = {nix::Value(uint32_t(1)), nix::Value(uint32_t(2)), nix::Value(uint32_t(3))};
std::vector<nix::Value> int64Values = {nix::Value(int64_t(1)), nix::Value(int64_t(2)), nix::Value(int64_t(3))};
std::vector<nix::Value> uint64Values = {nix::Value(uint64_t(1)), nix::Value(uint64_t(2)), nix::Value(uint64_t(3))};
std::vector<nix::Value> boolValues = {nix::Value(true), nix::Value(false), nix::Value(true)};
nix::Property p1 = section.createProperty("strProperty", strValues);
nix::Property p2 = section.createProperty("doubleProperty", doubleValues);
nix::Property p3 = section.createProperty("int32Property", intValues);
nix::Property p4 = section.createProperty("uint32Property", uintValues);
nix::Property p5 = section.createProperty("int64Property", int64Values);
nix::Property p6 = section.createProperty("uint64Property", uint64Values);
nix::Property p7 = section.createProperty("boolProperty", boolValues);
CPPUNIT_ASSERT(p1.dataType() == DataType::String);
CPPUNIT_ASSERT(p2.dataType() == DataType::Double);
CPPUNIT_ASSERT(p3.dataType() == DataType::Int32);
CPPUNIT_ASSERT(p4.dataType() == DataType::UInt32);
CPPUNIT_ASSERT(p5.dataType() == DataType::Int64);
CPPUNIT_ASSERT(p6.dataType() == DataType::UInt64);
CPPUNIT_ASSERT(p7.dataType() == DataType::Bool);
file.deleteSection(section.id());
}
void BaseTestProperty::testUnit(){
nix::Section section = file.createSection("testSection", "test");
nix::Value v(22.2);
v.uncertainty = 1.2;
std::vector<Value> values = {v};
nix::Property p1 = section.createProperty("testProperty", int_dummy);
std::string inv_unit = "invalid unit";
std::string valid_unit = "mV*cm^-2";
std::string second_unit = "mV";
CPPUNIT_ASSERT_THROW(property.unit(""), nix::EmptyString);
CPPUNIT_ASSERT_THROW(property.unit(inv_unit), nix::InvalidUnit);
CPPUNIT_ASSERT(!property.unit());
property.unit(valid_unit);
CPPUNIT_ASSERT(property.unit() && *property.unit() == valid_unit);
property.unit(none);
CPPUNIT_ASSERT(!property.unit());
CPPUNIT_ASSERT_NO_THROW(property.unit(second_unit));
CPPUNIT_ASSERT(property.unit() && *property.unit() == second_unit);
}
void BaseTestProperty::testOperators() {
CPPUNIT_ASSERT(property_null == false);
CPPUNIT_ASSERT(property_null == none);
CPPUNIT_ASSERT(property != false);
CPPUNIT_ASSERT(property != none);
CPPUNIT_ASSERT(property == property);
CPPUNIT_ASSERT(property != property_other);
CPPUNIT_ASSERT(property.compare(property_other) != 0);
property_other = property;
CPPUNIT_ASSERT(property == property_other);
CPPUNIT_ASSERT(property.compare(property_other) == 0);
property_other = none;
CPPUNIT_ASSERT(property_other == false);
CPPUNIT_ASSERT(property_other == none);
CPPUNIT_ASSERT(property_null == false);
CPPUNIT_ASSERT(property_null == none);
std::stringstream s;
s << property;
CPPUNIT_ASSERT(s.str() == "Property: {name = " + property.name() + "}");
}
void BaseTestProperty::testCreatedAt() {
CPPUNIT_ASSERT(property.createdAt() >= startup_time);
time_t past_time = time(NULL) - 10000000;
property.forceCreatedAt(past_time);
CPPUNIT_ASSERT(property.createdAt() == past_time);
}
void BaseTestProperty::testUpdatedAt() {
CPPUNIT_ASSERT(property.updatedAt() >= startup_time);
}
void BaseTestProperty::testIsValidEntity() {
Property p = section.createProperty("testProperty", DataType::Double);
CPPUNIT_ASSERT(p.isValidEntity());
section.deleteProperty(p.name());
CPPUNIT_ASSERT(!p.isValidEntity());
}
| 34.76 | 119 | 0.677407 | [
"vector"
] |
c81b0b2a5f60420fc921b949897611acc051d31c | 4,724 | cpp | C++ | cpsapi/core/cpsapiFactory.cpp | copasi/copasi-api | 3e09ad8b33f602981471104b553ebaf14e9ae4b1 | [
"Artistic-2.0"
] | 1 | 2021-04-08T12:39:39.000Z | 2021-04-08T12:39:39.000Z | cpsapi/core/cpsapiFactory.cpp | copasi/copasi-api | 3e09ad8b33f602981471104b553ebaf14e9ae4b1 | [
"Artistic-2.0"
] | 1 | 2021-05-17T15:33:13.000Z | 2021-08-30T21:26:04.000Z | cpsapi/core/cpsapiFactory.cpp | copasi/copasi-api | 3e09ad8b33f602981471104b553ebaf14e9ae4b1 | [
"Artistic-2.0"
] | 1 | 2021-08-13T09:47:49.000Z | 2021-08-13T09:47:49.000Z | #include "cpsapi/core/cpsapiValue.h"
#include "cpsapi/core/cpsapiContainer.h"
#include "cpsapi/core/cpsapiVector.h"
#include "cpsapi/core/cpsapiDataModel.h"
#include "cpsapi/core/cpsapiParameter.h"
#include "cpsapi/core/cpsapiGroup.h"
#include "cpsapi/model/cpsapiModelEntity.h"
#include "cpsapi/model/cpsapiModel.h"
#include <copasi/CopasiDataModel/CDataModel.h>
#include <copasi/core/CDataObjectReference.h>
CPSAPI_NAMESPACE_USE
// static
cpsapiFactory::CopasiMap cpsapiFactory::copasiMap;
// static
void cpsapiFactory::insert(const TypeInfo & typeInfo)
{
copasiMap.insert(std::make_pair(typeInfo.copasiClass, typeInfo));
copasiMap.insert(std::make_pair(typeInfo.cpsapiClass, typeInfo));
}
// static
void cpsapiFactory::init()
{
if (copasiMap.empty())
{
TypeInfo::initProtected< cpsapiObject, CDataObject >();
TypeInfo::initProtected< cpsapiContainer, CDataContainer >();
TypeInfo::initProtected< cpsapiModelEntity, CModelEntity >();
TypeInfo::init< cpsapiVector< cpsapiCompartment >, CDataVectorNS< CCompartment > >();
TypeInfo::init< cpsapiVector< cpsapiSpecies >, CDataVector< CMetab > >();
TypeInfo::init< cpsapiVector< cpsapiSpecies >, CDataVectorNS< CMetab > >();
TypeInfo::init< cpsapiVector< cpsapiGlobalQuantity >, CDataVectorN< CModelValue > >();
TypeInfo::init< cpsapiVector< cpsapiReaction >, CDataVectorNS< CReaction > >();
TypeInfo::init< cpsapiVector< cpsapiDataModel >, CDataVector< CDataModel > >();
TypeInfo::init< cpsapiValue, CDataObjectReference< C_FLOAT64 > >();
TypeInfo::init< cpsapiValue, CDataObjectReference< C_INT32 > >();
TypeInfo::init< cpsapiValue, CDataObjectReference< unsigned C_INT32 > >();
TypeInfo::init< cpsapiValue, CDataObjectReference< size_t > >();
TypeInfo::init< cpsapiValue, CDataObjectReference< std::string > >();
TypeInfo::init< cpsapiValue, CDataObjectReference< CRegisteredCommonName > >();
TypeInfo::init< cpsapiModel, CModel >();
TypeInfo::init< cpsapiCompartment, CCompartment >();
TypeInfo::init< cpsapiSpecies, CMetab >();
TypeInfo::init< cpsapiGlobalQuantity, CModelValue >();
TypeInfo::init< cpsapiReaction, CReaction >();
TypeInfo::init< cpsapiDataModel, CDataModel >();
TypeInfo::init< cpsapiParameter, CCopasiParameter >();
TypeInfo::init< cpsapiGroup, CCopasiParameterGroup >();
}
}
cpsapiFactory::TypeInfo::TypeInfo(const std::type_index & cpsapiClass,
std::shared_ptr< cpsapiFactory::createInterface > cpsapiCreate,
std::shared_ptr< cpsapiFactory::copyInterface > cpsapiCopy,
const std::type_index & copasiClass,
const std::string copasiString)
: cpsapiClass(cpsapiClass)
, cpsapiCreate()
, cpsapiCopy()
, copasiClass(copasiClass)
, copasiString(copasiString)
{
this->cpsapiCreate = cpsapiCreate;
this->cpsapiCopy = cpsapiCopy;
}
cpsapiFactory::TypeInfo & cpsapiFactory::TypeInfo::operator=(const cpsapiFactory::TypeInfo & rhs)
{
if (this != &rhs)
{
cpsapiClass = rhs.cpsapiClass;
cpsapiCreate = rhs.cpsapiCreate;
cpsapiCopy = rhs.cpsapiCopy;
copasiClass = rhs.copasiClass;
copasiString = rhs.copasiString;
}
return *this;
}
// static
const cpsapiFactory::TypeInfo & cpsapiFactory::info(const std::type_index & typeIndex)
{
static const TypeInfo Unknown;
CopasiMap::const_iterator found = copasiMap.find(typeIndex);
if (found != copasiMap.end())
return found->second;
return Unknown;
}
// static
const cpsapiFactory::TypeInfo & cpsapiFactory::info(CDataObject * pFrom)
{
static const TypeInfo Unknown;
if (pFrom != nullptr)
return info(std::type_index(typeid(*pFrom)));
return Unknown;
}
// static
const cpsapiFactory::TypeInfo & cpsapiFactory::info(const cpsapiObject & from)
{
return info(std::type_index(typeid(from)));
}
// static
cpsapiObject * cpsapiFactory::copy(const cpsapiObject & object)
{
const TypeInfo & Info = info(object);
if (Info.cpsapiCopy)
return (*Info.cpsapiCopy)(object);
return nullptr;
}
// static
cpsapiObject * cpsapiFactory::create(CDataObject * pFrom)
{
const TypeInfo & Info = info(pFrom);
if (Info.cpsapiCreate)
return (*Info.cpsapiCreate)(pFrom);
return nullptr;
}
// static
cpsapiObject * cpsapiFactory::make(CDataObject * pDataObject, const TypeInfo * pTypeInfo)
{
cpsapiObject * pObject = nullptr;
const TypeInfo * pInfo = pTypeInfo;
if (pTypeInfo == nullptr)
pInfo = &info(pDataObject);
if (pInfo->cpsapiCreate != nullptr)
pObject = (*pInfo->cpsapiCreate)(pDataObject);
return pObject;
}
| 31.078947 | 97 | 0.697502 | [
"object",
"model"
] |
c81ce4a4accc4e358fc01afd7c5dba3464240eb3 | 4,244 | cpp | C++ | HelperFunctions/getVkDeviceMemoryOverallocationCreateInfoAMD.cpp | dkaip/jvulkan-natives-Linux-x86_64 | ea7932f74e828953c712feea11e0b01751f9dc9b | [
"Apache-2.0"
] | null | null | null | HelperFunctions/getVkDeviceMemoryOverallocationCreateInfoAMD.cpp | dkaip/jvulkan-natives-Linux-x86_64 | ea7932f74e828953c712feea11e0b01751f9dc9b | [
"Apache-2.0"
] | null | null | null | HelperFunctions/getVkDeviceMemoryOverallocationCreateInfoAMD.cpp | dkaip/jvulkan-natives-Linux-x86_64 | ea7932f74e828953c712feea11e0b01751f9dc9b | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2019-2020 Douglas Kaip
*
* 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.
*/
/*
* getVkDeviceMemoryOverallocationCreateInfoAMD.cpp
*
* Created on: May 16, 2019
* Author: Douglas Kaip
*/
#include "JVulkanHelperFunctions.hh"
#include "slf4j.hh"
namespace jvulkan
{
void getVkDeviceMemoryOverallocationCreateInfoAMD(
JNIEnv *env,
jobject jVkDeviceMemoryOverallocationCreateInfoAMDObject,
VkDeviceMemoryOverallocationCreateInfoAMD *vkDeviceMemoryOverallocationCreateInfoAMD,
std::vector<void *> *memoryToFree)
{
jclass theClass = env->GetObjectClass(jVkDeviceMemoryOverallocationCreateInfoAMDObject);
if (env->ExceptionOccurred())
{
LOGERROR(env, "%s", "Could not get class for jVkDeviceMemoryOverallocationCreateInfoAMDObject");
return;
}
////////////////////////////////////////////////////////////////////////
VkStructureType sTypeValue = getSType(env, jVkDeviceMemoryOverallocationCreateInfoAMDObject);
if (env->ExceptionOccurred())
{
LOGERROR(env, "%s", "Call to getSType failed.");
return;
}
////////////////////////////////////////////////////////////////////////
jobject jpNextObject = getpNextObject(env, jVkDeviceMemoryOverallocationCreateInfoAMDObject);
if (env->ExceptionOccurred())
{
LOGERROR(env, "%s", "Call to getpNext failed.");
return;
}
void *pNext = nullptr;
if (jpNextObject != nullptr)
{
getpNextChain(
env,
jpNextObject,
&pNext,
memoryToFree);
if (env->ExceptionOccurred())
{
LOGERROR(env, "%s", "Call to getpNextChain failed.");
return;
}
}
////////////////////////////////////////////////////////////////////////
jmethodID methodId = env->GetMethodID(theClass, "getOverallocationBehavior", "()Lcom/CIMthetics/jvulkan/VulkanExtensions/Enums/VkMemoryOverallocationBehaviorAMD;");
if (env->ExceptionOccurred())
{
LOGERROR(env, "%s", "Could not find method id getOverallocationBehavior.");
return;
}
jobject jVkMemoryOverallocationBehaviorAMDObject = env->CallObjectMethod(jVkDeviceMemoryOverallocationCreateInfoAMDObject, methodId);
if (env->ExceptionOccurred())
{
LOGERROR(env, "%s", "Error calling CallObjectMethod");
return;
}
jclass vkMemoryOverallocationBehaviorAMDClass = env->GetObjectClass(jVkMemoryOverallocationBehaviorAMDObject);
if (env->ExceptionOccurred())
{
LOGERROR(env, "%s", "Could not get class for jVkMemoryOverallocationBehaviorAMDObject");
return;
}
jmethodID valueOfMethodId = env->GetMethodID(vkMemoryOverallocationBehaviorAMDClass, "valueOf", "()I");
if (env->ExceptionOccurred())
{
LOGERROR(env, "%s", "Could not find method id valueOf.");
return;
}
VkMemoryOverallocationBehaviorAMD vkMemoryOverallocationBehaviorAMDEnumValue = (VkMemoryOverallocationBehaviorAMD)env->CallIntMethod(jVkMemoryOverallocationBehaviorAMDObject, valueOfMethodId);
if (env->ExceptionOccurred())
{
LOGERROR(env, "%s", "Error calling CallIntMethod");
return;
}
vkDeviceMemoryOverallocationCreateInfoAMD->sType = sTypeValue;
vkDeviceMemoryOverallocationCreateInfoAMD->pNext = (void *)pNext;
vkDeviceMemoryOverallocationCreateInfoAMD->overallocationBehavior = vkMemoryOverallocationBehaviorAMDEnumValue;
}
}
| 37.22807 | 200 | 0.624882 | [
"vector"
] |
c821233f0fbcc014c0c2931f76569e1a141b64e7 | 5,516 | cpp | C++ | Blue/DBElements/dbcontainers.cpp | AmiditeX/Blue | 6a7a5dfa5e719a97a628bf8c4f2be1e672ed7350 | [
"MIT"
] | 4 | 2018-05-30T16:45:46.000Z | 2020-08-17T06:50:41.000Z | Blue/DBElements/dbcontainers.cpp | AmiditeX/Blue | 6a7a5dfa5e719a97a628bf8c4f2be1e672ed7350 | [
"MIT"
] | 5 | 2018-02-27T19:46:56.000Z | 2018-05-30T16:44:58.000Z | Blue/DBElements/dbcontainers.cpp | AmiditeX/Blue | 6a7a5dfa5e719a97a628bf8c4f2be1e672ed7350 | [
"MIT"
] | null | null | null | #include "dbcontainers.h"
#include <algorithm>
DBContainers::DBContainers()
{
}
DBContainers::DBContainers(const QJsonObject &obj)
{
//Retrieve all items contained in the container in JSON format
QJsonArray allElements = obj.value("DBItems").toArray();
//Instanciate each of them and store pointers in a vector
for(int i = 0; i < allElements.size(); i++)
{
//Current item as a JSON array element
QJsonObject currentItem = allElements[i].toObject();
//Fetch ID of the item to construct the matching object
const QString ID = currentItem.value("ID").toString();
try
{
_itemList.push_back(std::move(createItem(ID, currentItem)));
}
catch (std::exception &e)
{
spdlog::get("LOGGER")->error(e.what());
}
}
//Special tags
_title = obj.value("Name").toString();
_color = obj.value("Color").toString();
_colorText = obj.value("ColorText").toString();
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// PUBLIC //
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Convert whole containers to a JSON Object
QJsonObject DBContainers::toJson() const
{
QJsonArray allElements;
//Retrieve all items contained in this container in JSON format
for(unsigned int i = 0; i < _itemList.size(); i++)
{
//Store them in an array
allElements.append(_itemList[i]->toJson());
}
//Return the object containing all the elements
QJsonObject obj;
obj.insert("DBItems", allElements);
obj.insert("Name", _title);
obj.insert("Color", _color);
obj.insert("ColorText", _colorText);
return obj;
}
std::shared_ptr<AbstractDataBaseItem> DBContainers::addItem(const QString &ID)
{
try
{
std::shared_ptr<AbstractDataBaseItem> newObject = createItem(ID);
_itemList.push_back(newObject);
return newObject;
}
catch (std::exception &e)
{
spdlog::get("LOGGER")->error(e.what());
}
return nullptr;
}
void DBContainers::removeItem(std::shared_ptr<AbstractDataBaseItem> ptr)
{
_itemList.erase(std::remove(_itemList.begin(), _itemList.end(), ptr));
}
std::vector<std::shared_ptr<AbstractDataBaseItem>> DBContainers::returnItemList()
{
return _itemList;
}
QString DBContainers::getTitle()
{
return _title;
}
void DBContainers::setTitle(const QString &title)
{
_title = title;
}
QString DBContainers::getColor()
{
return _color;
}
void DBContainers::setColor(const QString &color)
{
_color = color;
}
QString DBContainers::getTextColor()
{
return _colorText;
}
void DBContainers::setTextColor(const QString &color)
{
_colorText = color;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// PUBLIC //
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// PROTECTED //
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Create an item without settings
std::shared_ptr<AbstractDataBaseItem> DBContainers::createItem(const QString &ID)
{
if(ID == "DBEmailField")
{
return std::make_shared<DBEmailField>();
}
else if(ID == "DBNameField")
{
return std::make_shared<DBNameField>();
}
else if(ID == "DBOtpItem")
{
return std::make_shared<DBOtpItem>();
}
else if(ID == "DBPasswordField")
{
return std::make_shared<DBPasswordField>();
}
else
{
throw std::runtime_error("Invalid type was provided in DBContainers item factory");
}
}
//Create an item given a JSON Object containing its settings
std::shared_ptr<AbstractDataBaseItem> DBContainers::createItem(const QString &ID, const QJsonObject &doc)
{
if(ID == "DBEmailField")
{
return std::make_shared<DBEmailField>(doc);
}
else if(ID == "DBNameField")
{
return std::make_shared<DBNameField>(doc);
}
else if(ID == "DBOtpItem")
{
return std::make_shared<DBOtpItem>(doc);
}
else if(ID == "DBPasswordField")
{
return std::make_shared<DBPasswordField>(doc);
}
else
{
throw std::runtime_error("Invalid type was provided in DBContainers item factory");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// PROTECTED //
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
| 29.978261 | 135 | 0.458122 | [
"object",
"vector"
] |
c8229567a0940f16337547069ac17cd9184bb5ed | 2,474 | cpp | C++ | bindings/python/crocoddyl/multibody/cop-support.cpp | spykspeigel/crocoddyl | 0500e398861564b6986d99206a1e0ccec0d66a33 | [
"BSD-3-Clause"
] | 322 | 2019-06-04T12:04:00.000Z | 2022-03-28T14:37:44.000Z | bindings/python/crocoddyl/multibody/cop-support.cpp | spykspeigel/crocoddyl | 0500e398861564b6986d99206a1e0ccec0d66a33 | [
"BSD-3-Clause"
] | 954 | 2019-09-02T10:07:27.000Z | 2022-03-31T16:14:25.000Z | bindings/python/crocoddyl/multibody/cop-support.cpp | spykspeigel/crocoddyl | 0500e398861564b6986d99206a1e0ccec0d66a33 | [
"BSD-3-Clause"
] | 89 | 2019-08-13T13:37:52.000Z | 2022-03-31T15:55:07.000Z | ///////////////////////////////////////////////////////////////////////////////
// BSD 3-Clause License
//
// Copyright (C) 2021, University of Edinburgh
// Copyright note valid unless otherwise stated in individual files.
// All rights reserved.
///////////////////////////////////////////////////////////////////////////////
#include "crocoddyl/multibody/cop-support.hpp"
#include "python/crocoddyl/multibody/multibody.hpp"
#include "python/crocoddyl/utils/printable.hpp"
namespace crocoddyl {
namespace python {
void exposeCoPSupport() {
bp::register_ptr_to_python<boost::shared_ptr<CoPSupport> >();
#pragma GCC diagnostic push // TODO: Remove once the deprecated update call has been removed in a future release
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
bp::class_<CoPSupport>(
"CoPSupport", "Model of the CoP support as lb <= Af <= ub",
bp::init<Eigen::Matrix3d, Eigen::Vector2d>(bp::args("self", "R", "box"),
"Initialize the CoP support.\n\n"
":param R: rotation matrix that defines the cone orientation\n"
":param box: dimension of the foot surface dim = (length, width)\n"))
.def(bp::init<>(bp::args("self"), "Default initialization of the CoP support."))
.def("update", &CoPSupport::update, bp::args("self"),
"Update the linear inequality (matrix and bounds).\n\n"
"Run this function if you have changed one of the parameters.")
.add_property("A", bp::make_function(&CoPSupport::get_A, bp::return_internal_reference<>()), "inequality matrix")
.add_property("ub", bp::make_function(&CoPSupport::get_ub, bp::return_internal_reference<>()),
"inequality upper bound")
.add_property("lb", bp::make_function(&CoPSupport::get_lb, bp::return_internal_reference<>()),
"inequality lower bound")
.add_property("R", bp::make_function(&CoPSupport::get_R, bp::return_internal_reference<>()),
bp::make_function(&CoPSupport::set_R), "rotation matrix")
.add_property("box", bp::make_function(&CoPSupport::get_box, bp::return_internal_reference<>()),
bp::make_function(&CoPSupport::set_box), "box size used to define the sole")
.def(PrintableVisitor<CoPSupport>());
#pragma GCC diagnostic pop
}
} // namespace python
} // namespace crocoddyl
| 50.489796 | 119 | 0.603072 | [
"model"
] |
c824bf1834d563ddead17ae3a0bbc778264d460e | 2,400 | cpp | C++ | aws-cpp-sdk-robomaker/source/model/SyncDeploymentJobResult.cpp | lintonv/aws-sdk-cpp | 15e19c265ffce19d2046b18aa1b7307fc5377e58 | [
"Apache-2.0"
] | 1 | 2021-12-06T20:36:35.000Z | 2021-12-06T20:36:35.000Z | aws-cpp-sdk-robomaker/source/model/SyncDeploymentJobResult.cpp | lintonv/aws-sdk-cpp | 15e19c265ffce19d2046b18aa1b7307fc5377e58 | [
"Apache-2.0"
] | 1 | 2022-01-03T23:59:37.000Z | 2022-01-03T23:59:37.000Z | aws-cpp-sdk-robomaker/source/model/SyncDeploymentJobResult.cpp | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-12-30T04:25:33.000Z | 2021-12-30T04:25:33.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/robomaker/model/SyncDeploymentJobResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/UnreferencedParam.h>
#include <utility>
using namespace Aws::RoboMaker::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws;
SyncDeploymentJobResult::SyncDeploymentJobResult() :
m_status(DeploymentStatus::NOT_SET),
m_failureCode(DeploymentJobErrorCode::NOT_SET)
{
}
SyncDeploymentJobResult::SyncDeploymentJobResult(const Aws::AmazonWebServiceResult<JsonValue>& result) :
m_status(DeploymentStatus::NOT_SET),
m_failureCode(DeploymentJobErrorCode::NOT_SET)
{
*this = result;
}
SyncDeploymentJobResult& SyncDeploymentJobResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
JsonView jsonValue = result.GetPayload().View();
if(jsonValue.ValueExists("arn"))
{
m_arn = jsonValue.GetString("arn");
}
if(jsonValue.ValueExists("fleet"))
{
m_fleet = jsonValue.GetString("fleet");
}
if(jsonValue.ValueExists("status"))
{
m_status = DeploymentStatusMapper::GetDeploymentStatusForName(jsonValue.GetString("status"));
}
if(jsonValue.ValueExists("deploymentConfig"))
{
m_deploymentConfig = jsonValue.GetObject("deploymentConfig");
}
if(jsonValue.ValueExists("deploymentApplicationConfigs"))
{
Array<JsonView> deploymentApplicationConfigsJsonList = jsonValue.GetArray("deploymentApplicationConfigs");
for(unsigned deploymentApplicationConfigsIndex = 0; deploymentApplicationConfigsIndex < deploymentApplicationConfigsJsonList.GetLength(); ++deploymentApplicationConfigsIndex)
{
m_deploymentApplicationConfigs.push_back(deploymentApplicationConfigsJsonList[deploymentApplicationConfigsIndex].AsObject());
}
}
if(jsonValue.ValueExists("failureReason"))
{
m_failureReason = jsonValue.GetString("failureReason");
}
if(jsonValue.ValueExists("failureCode"))
{
m_failureCode = DeploymentJobErrorCodeMapper::GetDeploymentJobErrorCodeForName(jsonValue.GetString("failureCode"));
}
if(jsonValue.ValueExists("createdAt"))
{
m_createdAt = jsonValue.GetDouble("createdAt");
}
return *this;
}
| 26.666667 | 178 | 0.762083 | [
"model"
] |
c82aeed7e382879187b601715f18231fd2fd4133 | 1,947 | hpp | C++ | source/LibFgBase/src/FgImageIo.hpp | maamountki/FaceGenBaseLibrary | 0c647920e913354028ed09fff3293555e84d2b94 | [
"MIT"
] | null | null | null | source/LibFgBase/src/FgImageIo.hpp | maamountki/FaceGenBaseLibrary | 0c647920e913354028ed09fff3293555e84d2b94 | [
"MIT"
] | null | null | null | source/LibFgBase/src/FgImageIo.hpp | maamountki/FaceGenBaseLibrary | 0c647920e913354028ed09fff3293555e84d2b94 | [
"MIT"
] | null | null | null | //
// Copyright (c) 2015 Singular Inversions Inc. (facegen.com)
// Use, modification and distribution is subject to the MIT License,
// see accompanying file LICENSE.txt or facegen.com/base_library_license.txt
//
// Authors: Andrew Beatty
// Created: May 10, 2005
//
// Functions for reading and writing images to various file formats.
//
#ifndef FGIMAGEIO_HPP
#define FGIMAGEIO_HPP
#include "FgStdLibs.hpp"
#include "FgAlgs.hpp"
#include "FgImage.hpp"
#include "FgMatrixV.hpp"
void
fgLoadImgAnyFormat(const FgString & fname,FgImgRgbaUb & img);
void
fgLoadImgAnyFormat(const FgString & fname,FgImgF & img);
void
fgLoadImgAnyFormat(const FgString & fname,FgImgUC & img);
inline
FgImgRgbaUb
fgLoadImgAnyFormat(const FgString & fname)
{
FgImgRgbaUb ret;
fgLoadImgAnyFormat(fname,ret);
return ret;
}
void
fgSaveImgAnyFormat(const FgString & fname,const FgImgRgbaUb & img);
void
fgSaveImgAnyFormat(const FgString & fname,const FgImgUC & img);
// List of file extensions of the 6 most commonly used formats in LOWER CASE:
std::vector<std::string>
fgImgCommonFormats();
// Command-line options string of the formats above:
std::string
fgImgCommonFormatsDescription();
bool
fgIsImgFilename(const FgString & fname);
// Returns a list of image extensions for which there are readable files 'baseName.ext':
std::vector<std::string>
fgFindImgFiles(const FgString & baseName);
// Look for an image file in any common format starting with 'baseName' and load it if found.
// Return true if found and false otherwise.
bool
fgImgFindLoadAnyFormat(const FgString & baseName,FgImgRgbaUb & img);
// data must be 4 channel RGBA of size wid*hgt*4:
std::vector<uchar>
fgEncodeJpeg(uint wid,uint hgt,const uchar * data,int quality);
// JFIF format (can be dumped to .jpg file):
std::vector<uchar>
fgEncodeJpeg(const FgImgRgbaUb & img,int quality=100);
FgImgRgbaUb
fgDecodeJpeg(const std::vector<uchar> & fileContents);
#endif
| 26.310811 | 93 | 0.758603 | [
"vector"
] |
c82cb4e944410ebdb81c83e432409bc94b74f5fe | 6,597 | cpp | C++ | src/openms/source/COMPARISON/CLUSTERING/CompleteLinkage.cpp | vmusch/OpenMS | 3c4a078ad4687677393c138d4acb91bb444a7c7b | [
"BSL-1.0",
"Zlib",
"Apache-2.0"
] | 348 | 2015-01-17T16:50:12.000Z | 2022-03-30T22:55:39.000Z | src/openms/source/COMPARISON/CLUSTERING/CompleteLinkage.cpp | vmusch/OpenMS | 3c4a078ad4687677393c138d4acb91bb444a7c7b | [
"BSL-1.0",
"Zlib",
"Apache-2.0"
] | 4,259 | 2015-01-01T14:07:54.000Z | 2022-03-31T16:49:14.000Z | src/openms/source/COMPARISON/CLUSTERING/CompleteLinkage.cpp | vmusch/OpenMS | 3c4a078ad4687677393c138d4acb91bb444a7c7b | [
"BSL-1.0",
"Zlib",
"Apache-2.0"
] | 266 | 2015-01-24T14:56:14.000Z | 2022-03-30T12:32:35.000Z | // --------------------------------------------------------------------------
// OpenMS -- Open-Source Mass Spectrometry
// --------------------------------------------------------------------------
// Copyright The OpenMS Team -- Eberhard Karls University Tuebingen,
// ETH Zurich, and Freie Universitaet Berlin 2002-2021.
//
// This software is released under a three-clause BSD license:
// * 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 any author or any participating institution
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
// For a full list of authors, refer to the file AUTHORS.
// --------------------------------------------------------------------------
// 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 ANY OF THE AUTHORS OR THE CONTRIBUTING
// INSTITUTIONS 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.
//
// --------------------------------------------------------------------------
// $Maintainer: Mathias Walzer $
// $Authors: $
// --------------------------------------------------------------------------
//
#include <OpenMS/COMPARISON/CLUSTERING/CompleteLinkage.h>
#include <OpenMS/DATASTRUCTURES/String.h>
namespace OpenMS
{
ClusterFunctor * CompleteLinkage::create()
{
return new CompleteLinkage();
}
const String CompleteLinkage::getProductName()
{
return "CompleteLinkage";
}
CompleteLinkage::CompleteLinkage() :
ClusterFunctor(), ProgressLogger()
{
}
CompleteLinkage::CompleteLinkage(const CompleteLinkage & source) :
ClusterFunctor(source), ProgressLogger()
{
}
CompleteLinkage::~CompleteLinkage()
{
}
CompleteLinkage & CompleteLinkage::operator=(const CompleteLinkage & source)
{
if (this != &source)
{
ClusterFunctor::operator=(source);
ProgressLogger::operator=(source);
}
return *this;
}
void CompleteLinkage::operator()(DistanceMatrix<float> & original_distance, std::vector<BinaryTreeNode> & cluster_tree, const float threshold /*=1*/) const
{
// attention: clustering process is done by clustering the indices
// pointing to elements in input vector and distances in input matrix
// input MUST have >= 2 elements!
if (original_distance.dimensionsize() < 2)
{
throw ClusterFunctor::InsufficientInput(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Distance matrix to start from only contains one element");
}
std::vector<std::set<Size> > clusters(original_distance.dimensionsize());
for (Size i = 0; i < original_distance.dimensionsize(); ++i)
{
clusters[i].insert(i);
}
cluster_tree.clear();
cluster_tree.reserve(original_distance.dimensionsize() - 1);
// Initial minimum-distance pair
original_distance.updateMinElement();
std::pair<Size, Size> min = original_distance.getMinElementCoordinates();
Size overall_cluster_steps(original_distance.dimensionsize());
startProgress(0, original_distance.dimensionsize(), "clustering data");
while (original_distance(min.first, min.second) < threshold)
{
//grow the tree
cluster_tree.emplace_back(*(clusters[min.second].begin()), *(clusters[min.first].begin()), original_distance(min.first, min.second));
if (cluster_tree.back().left_child > cluster_tree.back().right_child)
{
std::swap(cluster_tree.back().left_child, cluster_tree.back().right_child);
}
if (original_distance.dimensionsize() > 2)
{
//pick minimum-distance pair i,j and merge them
//pushback elements of second to first (and then erase second)
clusters[min.second].insert(clusters[min.first].begin(), clusters[min.first].end());
// erase first one
clusters.erase(clusters.begin() + min.first);
//update original_distance matrix
//complete linkage: new distance between clusters is the minimum distance between elements of each cluster
//lance-williams update for d((i,j),k): 0.5* d(i,k) + 0.5* d(j,k) + 0.5* |d(i,k)-d(j,k)|
for (Size k = 0; k < min.second; ++k)
{
float dik = original_distance.getValue(min.first, k);
float djk = original_distance.getValue(min.second, k);
original_distance.setValueQuick(min.second, k, (0.5f * dik + 0.5f * djk + 0.5f * std::fabs(dik - djk)));
}
for (Size k = min.second + 1; k < original_distance.dimensionsize(); ++k)
{
float dik = original_distance.getValue(min.first, k);
float djk = original_distance.getValue(min.second, k);
original_distance.setValueQuick(k, min.second, (0.5f * dik + 0.5f * djk + 0.5f * std::fabs(dik - djk)));
}
//reduce
original_distance.reduce(min.first);
//update minimum-distance pair
original_distance.updateMinElement();
//get new min-pair
min = original_distance.getMinElementCoordinates();
}
else
{
break;
}
setProgress(overall_cluster_steps - original_distance.dimensionsize());
//repeat until only two cluster remains or threshold exceeded, last step skips matrix operations
}
//fill tree with dummy nodes
Size sad(*clusters.front().begin());
for (Size i = 1; i < clusters.size() && (cluster_tree.size() < cluster_tree.capacity()); ++i)
{
cluster_tree.emplace_back(sad, *clusters[i].begin(), -1.0);
}
//~ while(cluster_tree.size() < cluster_tree.capacity())
//~ {
//~ cluster_tree.push_back(BinaryTreeNode(0,1,-1.0));
//~ }
endProgress();
}
}
| 39.035503 | 157 | 0.643626 | [
"vector"
] |
c82ce782895eb3873b1ea6815a0f93366c98cb40 | 5,226 | cpp | C++ | src/color_bicubic_interpolation.cpp | jsanchezperez/estadeo | 37bbfeeaa41ee36058256b3a392d42e9bc0de540 | [
"BSD-2-Clause"
] | 2 | 2018-10-26T11:35:02.000Z | 2021-05-11T04:40:48.000Z | src/color_bicubic_interpolation.cpp | jsanchezperez/estadeo | 37bbfeeaa41ee36058256b3a392d42e9bc0de540 | [
"BSD-2-Clause"
] | null | null | null | src/color_bicubic_interpolation.cpp | jsanchezperez/estadeo | 37bbfeeaa41ee36058256b3a392d42e9bc0de540 | [
"BSD-2-Clause"
] | null | null | null | // This program is free software: you can use, modify and/or redistribute it
// under the terms of the simplified BSD License. You should have received a
// copy of this license along this program. If not, see
// <http://www.opensource.org/licenses/bsd-license.html>.
//
// Copyright (C) 2015-2018, Javier Sánchez Pérez <jsanchez@ulpgc.es>
// Copyright (C) 2014, Nelson Monzón López <nmonzon@ctim.es>
// All rights reserved.
#include "color_bicubic_interpolation.h"
#include "bicubic_interpolation.h"
#include "transformation.h"
/**
*
* Neumann boundary condition test
*
**/
int neumann_bc (int x, int nx)
{
if (x<0) x=0;
else if (x >= nx)
x = nx - 1;
return x;
}
/**
*
* Compute the bicubic interpolation of a point in an image.
* It detects if the point goes beyond the image domain
*
**/
float bicubic_interpolation(
float *input, //image to be interpolated
float uu, //x component of the vector field
float vv, //y component of the vector field
int nx, //width of the image
int ny, //height of the image
int nz, //number of channels of the image
int k //actual channel
)
{
if(uu>nx || uu<-1 || vv>ny || vv<-1)
return 0;
else
{
int sx = (uu < 0) ? -1 : 1;
int sy = (vv < 0) ? -1 : 1;
int x, y, mx, my, dx, dy, ddx, ddy;
x = neumann_bc ((int) uu, nx);
y = neumann_bc ((int) vv, ny);
mx = neumann_bc ((int) uu - sx, nx);
my = neumann_bc ((int) vv - sy, ny);
dx = neumann_bc ((int) uu + sx, nx);
dy = neumann_bc ((int) vv + sy, ny);
ddx = neumann_bc ((int) uu + 2 * sx, nx);
ddy = neumann_bc ((int) vv + 2 * sy, ny);
//obtain the interpolation points of the image
float p11 = input[(mx + nx * my) * nz + k];
float p12 = input[(x + nx * my) * nz + k];
float p13 = input[(dx + nx * my) * nz + k];
float p14 = input[(ddx + nx * my) * nz + k];
float p21 = input[(mx + nx * y) * nz + k];
float p22 = input[(x + nx * y) * nz + k];
float p23 = input[(dx + nx * y) * nz + k];
float p24 = input[(ddx + nx * y) * nz + k];
float p31 = input[(mx + nx * dy) * nz + k];
float p32 = input[(x + nx * dy) * nz + k];
float p33 = input[(dx + nx * dy) * nz + k];
float p34 = input[(ddx + nx * dy) * nz + k];
float p41 = input[(mx + nx * ddy) * nz + k];
float p42 = input[(x + nx * ddy) * nz + k];
float p43 = input[(dx + nx * ddy) * nz + k];
float p44 = input[(ddx + nx * ddy) * nz + k];
//create array
float pol[4][4] = {
{p11, p21, p31, p41}, {p12, p22, p32, p42},
{p13, p23, p33, p43}, {p14, p24, p34, p44}
};
//return interpolation
return bicubic_interpolation(pol, (float) uu-x, (float) vv-y);
}
}
/**
*
* Compute the bicubic interpolation of an image from a parametric trasform
*
**/
void bicubic_interpolation(
float *input, //image to be warped
float *output, //warped output image with bicubic interpolation
float *params, //x component of the vector field
int nparams, //number of parameters of the transform
int nx, //width of the image
int ny, //height of the image
int nz //number of channels of the image
)
{
#pragma omp parallel for
for (int i=0; i<ny; i++)
for (int j=0; j<nx; j++)
{
int p=i*nx+j;
float x, y;
//transform coordinates using the parametric model
project(j, i, params, x, y, nparams);
//obtain the bicubic interpolation at position (uu, vv)
for(int k=0; k<nz; k++)
output[p*nz+k]=bicubic_interpolation(
input, x, y, nx, ny, nz, k
);
}
}
/**
*
* Function to warp the image using bilinear interpolation
*
**/
void bilinear_interpolation(
float *input, //image to be warped
float *output, //warped output image with bicubic interpolation
float *params, //x component of the vector field
int nparams, //number of parameters of the transform
int nx, //width of the image
int ny, //height of the image
int nz //number of channels of the image
)
{
#pragma omp parallel for
for(int i = 0; i < ny; i++)
for(int j = 0; j < nx; j++)
{
float uu, vv;
//transform coordinates using the parametric model
project(j, i, params, uu, vv, nparams);
if(uu<1 || uu>nx-2 || vv<1 || vv>ny-2)
for(int k=0; k<nz; k++)
output[(j+nx*i)*nz+k]=0;
else {
int sx=(uu<0)? -1: 1;
int sy=(vv<0)? -1: 1;
int x, y, dx, dy;
x =(int) uu;
y =(int) vv;
dx=(int) uu+sx;
dy=(int) vv+sy;
for(int k=0; k<nz; k++){
float p1=input[(x +nx*y)*nz+k];
float p2=input[(dx+nx*y)*nz+k];
float p3=input[(x +nx*dy)*nz+k];
float p4=input[(dx+nx*dy)*nz+k];
float e1=((float) sx*(uu-x));
float E1=((float) 1.0-e1);
float e2=((float) sy*(vv-y));
float E2=((float) 1.0-e2);
float w1=E1*p1+e1*p2;
float w2=E1*p3+e1*p4;
output[(j+nx*i)*nz+k]=E2*w1+e2*w2;
}
}
}
}
| 27.505263 | 76 | 0.538653 | [
"vector",
"model",
"transform"
] |
c82d974305ea826e32abf796c4c60361a54597c0 | 7,037 | cpp | C++ | src/third_party/mozjs/extract/js/src/jit/EffectiveAddressAnalysis.cpp | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | src/third_party/mozjs/extract/js/src/jit/EffectiveAddressAnalysis.cpp | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | src/third_party/mozjs/extract/js/src/jit/EffectiveAddressAnalysis.cpp | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
* vim: set ts=8 sts=2 et sw=2 tw=80:
* 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/. */
#include "jit/EffectiveAddressAnalysis.h"
#include "jit/IonAnalysis.h"
#include "jit/MIR.h"
#include "jit/MIRGenerator.h"
#include "jit/MIRGraph.h"
#include "util/CheckedArithmetic.h"
using namespace js;
using namespace jit;
static void AnalyzeLsh(TempAllocator& alloc, MLsh* lsh) {
if (lsh->type() != MIRType::Int32) {
return;
}
if (lsh->isRecoveredOnBailout()) {
return;
}
MDefinition* index = lsh->lhs();
MOZ_ASSERT(index->type() == MIRType::Int32);
MConstant* shiftValue = lsh->rhs()->maybeConstantValue();
if (!shiftValue) {
return;
}
if (shiftValue->type() != MIRType::Int32 ||
!IsShiftInScaleRange(shiftValue->toInt32())) {
return;
}
Scale scale = ShiftToScale(shiftValue->toInt32());
int32_t displacement = 0;
MInstruction* last = lsh;
MDefinition* base = nullptr;
while (true) {
if (!last->hasOneUse()) {
break;
}
MUseIterator use = last->usesBegin();
if (!use->consumer()->isDefinition() ||
!use->consumer()->toDefinition()->isAdd()) {
break;
}
MAdd* add = use->consumer()->toDefinition()->toAdd();
if (add->type() != MIRType::Int32 || !add->isTruncated()) {
break;
}
MDefinition* other = add->getOperand(1 - add->indexOf(*use));
if (MConstant* otherConst = other->maybeConstantValue()) {
displacement += otherConst->toInt32();
} else {
if (base) {
break;
}
base = other;
}
last = add;
if (last->isRecoveredOnBailout()) {
return;
}
}
if (!base) {
uint32_t elemSize = 1 << ScaleToShift(scale);
if (displacement % elemSize != 0) {
return;
}
if (!last->hasOneUse()) {
return;
}
MUseIterator use = last->usesBegin();
if (!use->consumer()->isDefinition() ||
!use->consumer()->toDefinition()->isBitAnd()) {
return;
}
MBitAnd* bitAnd = use->consumer()->toDefinition()->toBitAnd();
if (bitAnd->isRecoveredOnBailout()) {
return;
}
MDefinition* other = bitAnd->getOperand(1 - bitAnd->indexOf(*use));
MConstant* otherConst = other->maybeConstantValue();
if (!otherConst || otherConst->type() != MIRType::Int32) {
return;
}
uint32_t bitsClearedByShift = elemSize - 1;
uint32_t bitsClearedByMask = ~uint32_t(otherConst->toInt32());
if ((bitsClearedByShift & bitsClearedByMask) != bitsClearedByMask) {
return;
}
bitAnd->replaceAllUsesWith(last);
return;
}
if (base->isRecoveredOnBailout()) {
return;
}
MEffectiveAddress* eaddr =
MEffectiveAddress::New(alloc, base, index, scale, displacement);
last->replaceAllUsesWith(eaddr);
last->block()->insertAfter(last, eaddr);
}
// Transform:
//
// [AddI]
// addl $9, %esi
// [LoadUnboxedScalar]
// movsd 0x0(%rbx,%rsi,8), %xmm4
//
// into:
//
// [LoadUnboxedScalar]
// movsd 0x48(%rbx,%rsi,8), %xmm4
//
// This is possible when the AddI is only used by the LoadUnboxedScalar opcode.
static void AnalyzeLoadUnboxedScalar(MLoadUnboxedScalar* load) {
if (load->isRecoveredOnBailout()) {
return;
}
if (!load->getOperand(1)->isAdd()) {
return;
}
JitSpew(JitSpew_EAA, "analyze: %s%u", load->opName(), load->id());
MAdd* add = load->getOperand(1)->toAdd();
if (add->type() != MIRType::Int32 || !add->hasUses() ||
add->truncateKind() != TruncateKind::Truncate) {
return;
}
MDefinition* lhs = add->lhs();
MDefinition* rhs = add->rhs();
MDefinition* constant = nullptr;
MDefinition* node = nullptr;
if (lhs->isConstant()) {
constant = lhs;
node = rhs;
} else if (rhs->isConstant()) {
constant = rhs;
node = lhs;
} else
return;
MOZ_ASSERT(constant->type() == MIRType::Int32);
size_t storageSize = Scalar::byteSize(load->storageType());
int32_t c1 = load->offsetAdjustment();
int32_t c2 = 0;
if (!SafeMul(constant->maybeConstantValue()->toInt32(), storageSize, &c2)) {
return;
}
int32_t offset = 0;
if (!SafeAdd(c1, c2, &offset)) {
return;
}
JitSpew(JitSpew_EAA, "set offset: %d + %d = %d on: %s%u", c1, c2, offset,
load->opName(), load->id());
load->setOffsetAdjustment(offset);
load->replaceOperand(1, node);
if (!add->hasLiveDefUses() && DeadIfUnused(add) &&
add->canRecoverOnBailout()) {
JitSpew(JitSpew_EAA, "mark as recovered on bailout: %s%u", add->opName(),
add->id());
add->setRecoveredOnBailoutUnchecked();
}
}
template <typename AsmJSMemoryAccess>
void EffectiveAddressAnalysis::analyzeAsmJSHeapAccess(AsmJSMemoryAccess* ins) {
MDefinition* base = ins->base();
if (base->isConstant()) {
// If the index is within the minimum heap length, we can optimize
// away the bounds check.
int32_t imm = base->toConstant()->toInt32();
if (imm >= 0) {
int32_t end = (uint32_t)imm + ins->byteSize();
if (end >= imm && (uint32_t)end <= mir_->minWasmHeapLength()) {
ins->removeBoundsCheck();
}
}
}
}
// This analysis converts patterns of the form:
// truncate(x + (y << {0,1,2,3}))
// truncate(x + (y << {0,1,2,3}) + imm32)
// into a single lea instruction, and patterns of the form:
// asmload(x + imm32)
// asmload(x << {0,1,2,3})
// asmload((x << {0,1,2,3}) + imm32)
// asmload((x << {0,1,2,3}) & mask) (where mask is redundant
// with shift)
// asmload(((x << {0,1,2,3}) + imm32) & mask) (where mask is redundant
// with shift + imm32)
// into a single asmload instruction (and for asmstore too).
//
// Additionally, we should consider the general forms:
// truncate(x + y + imm32)
// truncate((y << {0,1,2,3}) + imm32)
bool EffectiveAddressAnalysis::analyze() {
JitSpew(JitSpew_EAA, "Begin");
for (ReversePostorderIterator block(graph_.rpoBegin());
block != graph_.rpoEnd(); block++) {
for (MInstructionIterator i = block->begin(); i != block->end(); i++) {
if (!graph_.alloc().ensureBallast()) {
return false;
}
// Note that we don't check for MWasmCompareExchangeHeap
// or MWasmAtomicBinopHeap, because the backend and the OOB
// mechanism don't support non-zero offsets for them yet
// (TODO bug 1254935).
if (i->isLsh()) {
AnalyzeLsh(graph_.alloc(), i->toLsh());
} else if (i->isLoadUnboxedScalar()) {
AnalyzeLoadUnboxedScalar(i->toLoadUnboxedScalar());
} else if (i->isAsmJSLoadHeap()) {
analyzeAsmJSHeapAccess(i->toAsmJSLoadHeap());
} else if (i->isAsmJSStoreHeap()) {
analyzeAsmJSHeapAccess(i->toAsmJSStoreHeap());
}
}
}
return true;
}
| 27.488281 | 79 | 0.604519 | [
"transform"
] |
c82dfc5c2a4ffdf0e0d7a95f075fe191071b10dc | 1,223 | hpp | C++ | src/include/duckdb/parser/query_node/recursive_cte_node.hpp | shenyunlong/duckdb | ecb90f22b36a50b051fdd8e0d681bade3365c430 | [
"MIT"
] | null | null | null | src/include/duckdb/parser/query_node/recursive_cte_node.hpp | shenyunlong/duckdb | ecb90f22b36a50b051fdd8e0d681bade3365c430 | [
"MIT"
] | 7 | 2020-08-25T22:24:16.000Z | 2020-09-06T00:16:49.000Z | src/include/duckdb/parser/query_node/recursive_cte_node.hpp | shenyunlong/duckdb | ecb90f22b36a50b051fdd8e0d681bade3365c430 | [
"MIT"
] | null | null | null | //===----------------------------------------------------------------------===//
// DuckDB
//
// duckdb/parser/query_node/recursive_cte_node.hpp
//
//
//===----------------------------------------------------------------------===//
#pragma once
#include "duckdb/parser/parsed_expression.hpp"
#include "duckdb/parser/query_node.hpp"
#include "duckdb/parser/sql_statement.hpp"
namespace duckdb {
class RecursiveCTENode : public QueryNode {
public:
RecursiveCTENode() : QueryNode(QueryNodeType::RECURSIVE_CTE_NODE) {
}
string ctename;
bool union_all;
//! The left side of the set operation
unique_ptr<QueryNode> left;
//! The right side of the set operation
unique_ptr<QueryNode> right;
const vector<unique_ptr<ParsedExpression>> &GetSelectList() const override {
return left->GetSelectList();
}
public:
bool Equals(const QueryNode *other) const override;
//! Create a copy of this SelectNode
unique_ptr<QueryNode> Copy() override;
//! Serializes a SelectNode to a stand-alone binary blob
void Serialize(Serializer &serializer) override;
//! Deserializes a blob back into a SelectNode
static unique_ptr<QueryNode> Deserialize(Deserializer &source);
};
} // namespace duckdb
| 27.177778 | 80 | 0.645953 | [
"vector"
] |
c82e85d3fdc556f6e98392e2824c26005ace6403 | 6,623 | cpp | C++ | src/Vector.cpp | KPO-2020-2021/zad3-delipl-1 | a4ca6747a2e8b7127765548aff687a4a1d2f7dae | [
"Unlicense"
] | null | null | null | src/Vector.cpp | KPO-2020-2021/zad3-delipl-1 | a4ca6747a2e8b7127765548aff687a4a1d2f7dae | [
"Unlicense"
] | null | null | null | src/Vector.cpp | KPO-2020-2021/zad3-delipl-1 | a4ca6747a2e8b7127765548aff687a4a1d2f7dae | [
"Unlicense"
] | null | null | null | #include <cmath>
#include <limits>
#include "Vector.h"
#ifndef MIN_DIFF
#define MIN_DIFF 0.0000001
#endif
/* -------------------------------------------------------------------------- */
/* CONSTRUCTORS */
/* -------------------------------------------------------------------------- */
template <typename Tf>
Vector<Tf>::Vector() {
this->value = nullptr;
this->dim = 0;
}
template <typename Tf>
Vector<Tf>::Vector(const Vector &v) {
this->dim = v.Dim();
this->value = new Tf[v.Dim()];
for (std::size_t i = 0; i < this->dim; i++) {
this->value[i] = v[i];
}
}
template <typename Tf>
template <typename... T>
Vector<Tf>::Vector(const Tf &first, const T... args) {
this->dim = sizeof...(args) + 1;
this->value = new Tf[this->dim];
this->value[0] = first;
Tf tempTab[] = {args...};
for (std::size_t i = 1; i < this->dim; i++)
this->value[i] = tempTab[i - 1];
}
template <typename Tf>
Vector<Tf>::Vector(const Tf &first){
this->dim = 1;
this->value = new Tf[this->dim];
this->value[0] = first;
}
template <typename Tf>
Vector<Tf>::~Vector() {
if (this->value != nullptr)
delete [] this->value;
}
/* -------------------------------------------------------------------------- */
/* METHODS */
/* -------------------------------------------------------------------------- */
template <typename Tf>
std::size_t Vector<Tf>::Dim() const {
return this->dim;
}
template <typename Tf>
Tf Vector<Tf>::Length() const {
Tf x = Tf();
for (std::size_t i = 0; i < this->dim; i++)
x += this->value[i] * this->value[i];
return sqrt(x);
}
template <typename Tf>
void Vector<Tf>::Put(const Tf &value) {
Tf *ptr = this->value;
this->dim++;
this->value = new Tf[this->dim];
for (std::size_t i = 0; i < this->dim - 1; i++)
this->value[i] = Tf(ptr[i]);
this->value[this->dim - 1] = Tf(value);
}
template <typename Tf>
Tf Vector<Tf>::Pop() {
Tf *ptr = this->value;
this->dim--;
this->value = new Tf[this->dim];
for (std::size_t i = 0; i < this->dim; i++)
{
this->value[i] = Tf(ptr[i]);
}
Tf x = ptr[this->dim];
delete (ptr);
return x;
}
template <typename Tf>
Tf Vector<Tf>::Remove(const std::size_t index){
if(index >= this->dim)
throw std::out_of_range("Try to remove on index out of range");
Tf *ptr = this->value;
this->dim--;
Tf x(ptr[index]);
this->value = new Tf[this->dim];
for (std::size_t i = 0; i < this->dim; i++)
{
if (i >= index){
this->value[i] = Tf(ptr[i+1]);
}
else{
this->value[i] = Tf(ptr[i]);
}
}
return x;
}
/* -------------------------------------------------------------------------- */
/* OPERATORS */
/* -------------------------------------------------------------------------- */
template <typename Tf>
Tf Vector<Tf>::operator[](const std::size_t &i) const {
if (i >= this->dim)
throw std::out_of_range("Vector out of range");
return value[i];
}
template <typename Tf>
Tf &Vector<Tf>::operator[](const std::size_t &i){
if (i >= this->dim)
throw std::out_of_range("Vector out of range");
return value[i];
}
template <typename Tf>
bool Vector<Tf>::operator==(const Vector &v) const {
for (std::size_t i = 0; i < this->dim; i++)
if (this->value[i] != v[i])
return false;
return true;
}
template <typename Tf>
bool Vector<Tf>::operator!=(const Vector &v) const {
for (std::size_t i = 0; i < this->dim; i++)
if (this->value[i] != v[i])
return true;
return false;
}
template <typename Tf>
bool Vector<Tf>::operator!() const {
return this->value == nullptr || this->dim == 0;
}
template <typename Tf>
Vector<Tf> &Vector<Tf>::operator=(const Vector &v) {
this->dim = v.Dim();
if(this->value != nullptr)
delete (this->value);
this->value = new Tf[v.Dim()];
for (std::size_t i = 0; i < this->dim; i++)
this->value[i] = Tf(v[i]);
return *this;
}
template <typename Tf>
Vector<Tf> &Vector<Tf>::operator=(const Tf &x) {
for (std::size_t i = 0; i < this->dim; i++)
this->value[i] = x;
return *this;
}
template <typename Tf>
Vector<Tf> Vector<Tf>::operator+(const Vector &v) const {
Vector u(v);
for (std::size_t i = 0; i < this->dim; i++)
u[i] = u[i] + this->value[i];
return u;
}
template <typename Tf>
Vector<Tf> Vector<Tf>::operator-(const Vector &v) const {
Vector u(v);
for (std::size_t i = 0; i < this->dim; i++)
u.value[i] = this->value[i] - u[i];
return u;
}
template <typename Tf>
Vector<Tf> Vector<Tf>::operator*(const Tf &k) {
Vector u(*this);
for (std::size_t i = 0; i < this->dim; i++){
u.value[i] = k * this->value[i];
}
return u;
}
template <typename Tf>
Vector<Tf> Vector<Tf>::operator/(const Tf &k) {
Vector u(*this);
for (std::size_t i = 0; i < this->dim; i++)
u.value[i] = this->value[i] / k;
return u;
}
template <typename Tf>
Tf Vector<Tf>::operator*(const Vector &v) {
Tf x = Tf();
for (std::size_t i = 0; i < this->dim; i++)
x += this->value[i] * v[i];
return x;
}
template <>
double Vector<double>::operator*(const Vector &v) {
double x = double();
for (std::size_t i = 0; i < this->dim; i++)
x += this->value[i] * v[i];
double re = (std::size_t)(x * pow(MIN_DIFF, -1));
re = x * pow(MIN_DIFF, -1);
re = round(re);
re = re * MIN_DIFF;
return re;
}
template <typename Tf>
std::ostream &operator<<(std::ostream &cout, const Vector<Tf> &v) {
if (v.Dim() == 0) {
return cout << "[null]";
}
cout << "[";
if(v.Dim() > 1){
cout << v[0] << ", ";
for (std::size_t i = 1; i < v.Dim() - 1; i++) {
cout << v[i] << ", ";
}
cout << v[v.Dim() - 1];
}
else{
cout << v[0];
}
cout << "]";
return cout;
}
template <typename Tf>
std::istream &operator>>(std::istream &cin, Vector<Tf> &v) {
char c;
std::size_t i = 0;
while(i < v.Dim()){
cin >> c;
if (!cin)
return cin;
if(c == '\n' || c == EOF)
return cin;
cin.putback(c);
Tf x;
cin >> x;
if (!cin)
throw std::logic_error("Vector input error");
v[i] = x;
++i;
}
return cin;
} | 25.972549 | 80 | 0.473652 | [
"vector"
] |
c8302062516fd30ee4c9ae349f35e7dc2316b969 | 9,287 | hpp | C++ | include/linalg/polynomial.hpp | YuanL12/BATS | 35a32facc87e17649b7fc32225c8ffaf0301bbfa | [
"MIT"
] | null | null | null | include/linalg/polynomial.hpp | YuanL12/BATS | 35a32facc87e17649b7fc32225c8ffaf0301bbfa | [
"MIT"
] | null | null | null | include/linalg/polynomial.hpp | YuanL12/BATS | 35a32facc87e17649b7fc32225c8ffaf0301bbfa | [
"MIT"
] | null | null | null | #pragma once
/*
Header file for univariate polynomial class with coefficients in T
*/
#include <vector>
#include <initializer_list>
#include <iostream>
#include <stdexcept>
#include <type_traits>
#include "col_matrix.hpp"
#include "sparse_vector.hpp"
template <typename T>
class UnivariatePolynomial
{
private:
std::vector<T> c; // vector of coefficients
// remove zero coeffients from back
void clear_zeros() {
while (!c.empty() && c.back() == 0) {
c.pop_back();
}
}
public:
// constructor from vector of coefficients
UnivariatePolynomial(const std::vector<T>& c) : c(c) {clear_zeros();}
// constructor from initializer list
UnivariatePolynomial(std::initializer_list<T> l) : c(l) {clear_zeros();}
// constructor of constant polynomial
UnivariatePolynomial(const T& c0) : c{c0} {clear_zeros();}
// empty constructor
UnivariatePolynomial() {}
// multipliciative identity
static UnivariatePolynomial identity() {
return UnivariatePolynomial(T(1));
}
// additive identity
static UnivariatePolynomial zero() {
return UnivariatePolynomial();
}
bool is_zero() const {
return c.empty();
}
// monomial with degree d, scaled by scale
static UnivariatePolynomial monomial(size_t d, T scale=T(1)) {
std::vector<T> coeff(d + 1, T(0));
coeff[d] = scale;
return UnivariatePolynomial(coeff);
}
// access coefficients
template <typename TI>
inline const T operator[] (const TI i) const { return c[i]; }
// update coefficient
template <typename TI>
inline T& operator[] (const TI i) { return c[i]; }
// dimension of polynomial
inline size_t dim() const { return c.size() - 1; }
inline size_t degree() const { return dim(); }
// size - useful for iteration
inline size_t size() const { return c.size(); }
// leading coefficient
inline T leading_coeff() const {
return c.back();
}
// apply polynomial
T operator()(const T& v) const {
if (is_zero()) {return T(0);}
T sum = c[0];
T vk = T(1);
for (size_t k = 1; k < size(); k++) {
vk = vk * v; // v^k
sum += c[k] * vk;
}
return sum;
}
// apply polynomial of matrix to vector
// p(A) * v
template <typename TC>
TC operator()(const ColumnMatrix<TC>& A, const TC& v) const {
if (is_zero()){ return TC(); }
TC sum; sum.axpy(c[0], v); // c[0]*v
TC Akv(v); // A^k * v
for (size_t k = 1; k < size(); k++) {
Akv = A * Akv; // A^k * v
sum.axpy(c[k], Akv);
}
return sum;
}
// negation
UnivariatePolynomial operator-() const {
std::vector<T> newc(c.size());
for (size_t i = 0; i < c.size(); i++) {
newc[i] = -c[i];
}
return UnivariatePolynomial(newc);
}
// addition
UnivariatePolynomial operator+(const UnivariatePolynomial &other) const {
std::vector<T> newc;
newc.reserve(size());
auto it1 = c.begin();
auto it2 = other.c.begin();
while (it1 != c.end() && it2 != other.c.end()) {
newc.emplace_back(*it1++ + *it2++);
}
while (it1 != c.end()) {
newc.emplace_back(*it1++);
}
while (it2 != other.c.end()) {
newc.emplace_back(*it2++);
}
return UnivariatePolynomial(newc);
}
// addition
UnivariatePolynomial& operator+=(const UnivariatePolynomial &other) {
auto it1 = c.begin();
auto it2 = other.c.begin();
while (it1 != c.end() && it2 != other.c.end()) {
*it1++ += *it2++;
}
while (it2 != other.c.end()) {
c.emplace_back(*it2++);
}
clear_zeros();
return *this;
}
// addition
UnivariatePolynomial& operator-=(const UnivariatePolynomial &other) {
auto it1 = c.begin();
auto it2 = other.c.begin();
while (it1 != c.end() && it2 != other.c.end()) {
*it1++ -= *it2++;
}
while (it2 != other.c.end()) {
c.emplace_back(-(*it2++));
}
clear_zeros();
return *this;
}
// subtraction
UnivariatePolynomial operator-(const UnivariatePolynomial &other) const {
std::vector<T> newc;
newc.reserve(size());
auto it1 = c.begin();
auto it2 = other.c.begin();
while (it1 != c.end() && it2 != other.c.end()) {
newc.emplace_back(*it1++ - *it2++);
}
while (it1 != c.end()) {
newc.emplace_back(*it1++);
}
while (it2 != other.c.end()) {
newc.emplace_back(-(*it2++));
}
return UnivariatePolynomial(newc);
}
// multiplication
UnivariatePolynomial operator*(const UnivariatePolynomial &other) const {
if (is_zero() || other.is_zero()) { return zero(); }
std::vector<T> newc(size() + other.size() - 1, T(0));
for (size_t i = 0; i < size(); i++) {
for (size_t j = 0; j < other.size(); j++) {
newc[i+j] += c[i] * other[j];
}
}
return UnivariatePolynomial(newc);
}
// division + remainder
std::tuple<UnivariatePolynomial, UnivariatePolynomial> divrem(const UnivariatePolynomial& other) const {
UnivariatePolynomial quotient(0);
UnivariatePolynomial remainder(*this);
while (remainder.size() >= other.size()) {
T coeff = remainder.leading_coeff() / other.leading_coeff();
UnivariatePolynomial m = monomial(remainder.dim() - other.dim(), coeff);
quotient += m;
remainder -= (m * other);
}
return std::tie(quotient, remainder);
}
// division
UnivariatePolynomial operator/(const UnivariatePolynomial& other) const {
auto [q, r] = divrem(other);
return q;
}
// remainder
UnivariatePolynomial remainder(const UnivariatePolynomial& other) const {
auto [q, r] = divrem(other);
return r;
}
template <typename T2>
bool operator==(const T2& other) const {
return other == 0 ? is_zero() : (size() == 1 && c[0] == other);
}
bool operator==(const UnivariatePolynomial &other) const {
if (size() != other.size()) return false;
for (size_t i = 0; i < size(); i++) {
if (c[i] != other[i]) return false;
}
return true;
}
template <typename T2>
bool operator!=(const T2& other) const {
return other == 0 ? !is_zero() : !(size() == 1 && c[0] == other);
}
inline bool operator!=(const UnivariatePolynomial &other) const {
return !(*this == other);
}
// gcd using Euclidean algorithm
UnivariatePolynomial gcd(const UnivariatePolynomial& other) const {
UnivariatePolynomial a(*this), b(other), t;
while (!b.is_zero()) {
t = b;
b = a.remainder(b);
a = t;
}
return a;
}
inline bool is_monic() const {
return leading_coeff() == T(1);
}
// companion matrix
ColumnMatrix<SparseVector<T>> companion_matrix() const {
if (!is_monic()) {throw std::runtime_error("Companion matrix requires monic polynomial!");}
size_t n = dim(); // size of companion matrix
std::vector<SparseVector<T>> cols(n);
for (size_t j = 0; j < n-1; j++) {
cols[j] = SparseVector<T>({j+1}, {T(1)});
}
std::vector<size_t> ind(n);
std::vector<T> val(n);
for (size_t i = 0; i < n; i++) {
ind[i] = i;
val[i] = -c[i];
}
cols[n-1] = SparseVector<T>(ind, val);
return ColumnMatrix(n,n,cols);
}
// call as function to evaluate
// input should be templated. e.g. should be able to evaluate on matrix or field elt.
// pretty printing
friend std::ostream& operator<<( std::ostream& os, const UnivariatePolynomial &p) {
for (size_t i = 0; i < p.c.size(); i++) {
if (p.c[i] != 0) {
os << p.c[i] << " x^" << i;
if (i != p.c.size() - 1) os << " + ";
}
}
return os;
}
void print() {
std::cout << *this << std::endl;
}
}; // end UnivariatePolynomial
// type trait
template <typename T>
struct is_UnivariatePolynomial : std::false_type {};
template <typename T>
struct is_UnivariatePolynomial<UnivariatePolynomial<T>> : std::true_type {};
// characteristic matrix
// xI - A
template <typename T>
auto characteristic_matrix(
const ColumnMatrix<SparseVector<T>>& A
) {
using PT = UnivariatePolynomial<T>;
auto n = A.ncol();
auto m = A.nrow();
if (m != n) {throw std::runtime_error("Characteristic matrix must be square!");}
std::vector<SparseVector<PT>> cols(n);
std::vector<size_t> ind;
std::vector<PT> val;
for (size_t j = 0; j < n; j++) {
ind.clear();
val.clear();
auto p = A[j].nzbegin();
bool found_diagonal = false;
while (p != A[j].nzend()) {
if (p->ind == j) {
ind.emplace_back(p->ind);
val.emplace_back(PT({-p->val, T(1)}));
found_diagonal=true;
p++;
break;
} else if (p->ind < j) {
ind.emplace_back(p->ind);
val.emplace_back(PT(-p->val));
} else {
break;
}
p++;
}
if (!found_diagonal) {
ind.emplace_back(j);
val.emplace_back(PT({T(0), T(1)}));
}
// new loop without branch conditions
// only loops over indices > j
while (p != A[j].nzend()) {
ind.emplace_back(p->ind);
val.emplace_back(PT(-p->val));
p++;
}
cols[j] = SparseVector<PT>(ind, val);
}
return ColumnMatrix<SparseVector<PT>>(n, n, cols);
}
| 24.831551 | 108 | 0.576289 | [
"vector"
] |
c833507319b9cbb93f13122355404d30901429dc | 15,321 | hpp | C++ | IGC/Compiler/CISACodeGen/WIAnalysis.hpp | lfelipe/intel-graphics-compiler | da6c84a62d5d499544b2ae5f70ae7d1cb4d78fbd | [
"MIT"
] | null | null | null | IGC/Compiler/CISACodeGen/WIAnalysis.hpp | lfelipe/intel-graphics-compiler | da6c84a62d5d499544b2ae5f70ae7d1cb4d78fbd | [
"MIT"
] | null | null | null | IGC/Compiler/CISACodeGen/WIAnalysis.hpp | lfelipe/intel-graphics-compiler | da6c84a62d5d499544b2ae5f70ae7d1cb4d78fbd | [
"MIT"
] | null | null | null | /*===================== begin_copyright_notice ==================================
Copyright (c) 2017 Intel Corporation
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
======================= end_copyright_notice ==================================*/
#pragma once
#include "Compiler/MetaDataUtilsWrapper.h"
#include "Compiler/CodeGenContextWrapper.hpp"
#include "Compiler/CISACodeGen/TranslationTable.hpp"
#include "common/LLVMWarningsPush.hpp"
#include <llvmWrapper/IR/InstrTypes.h>
#include <llvm/Pass.h>
#include <llvm/IR/Function.h>
#include <llvm/IR/Instructions.h>
#include <llvm/Support/raw_ostream.h>
#include <llvm/ADT/Statistic.h>
#include <llvm/ADT/DenseMap.h>
#include <llvm/ADT/DenseSet.h>
#include <llvm/ADT/SmallSet.h>
#include <llvm/IR/Module.h>
#include <llvm/IR/Value.h>
#include <llvm/IR/InstIterator.h>
#include <llvm/IR/Dominators.h>
#include <llvm/Analysis/PostDominators.h>
#include "common/LLVMWarningsPop.hpp"
#ifdef OCL_SPECIFIC
#include "RuntimeServices.h"
#include "SoaAllocaAnalysis.h"
#include "Logger.h"
#endif
#include <vector>
namespace IGC
{
class BranchInfo;
class WIAnalysis;
//This is a trick, since we cannot forward-declare enums embedded in class definitions.
// The better solution is to completely hoist-out the WIDependency enum into a separate enum class
// (c++ 11) and have it separate from WIAnalysis pass class. Nevertheless, that would require
// updating many places in the current CodeGen code...
// thus: WIAnalysis::WIDependancy ~ WIBaseClass::WIDependancy, the types are equal and do not require
// conversion
class WIBaseClass
{
public:
/// @brief describes the type of dependency on the work item
enum WIDependancy {
UNIFORM_GLOBAL = 0, /// Same for all work-items within a shader.
UNIFORM_WORKGROUP = 1, /// Same for all work-items within a work group (compute).
UNIFORM_THREAD = 2, /// Same for all work-items within a HW thread.
CONSECUTIVE = 3, /// Elements are consecutive
PTR_CONSECUTIVE = 4, /// Elements are pointers which are consecutive
STRIDED = 5, /// Elements are in strides
RANDOM = 6, /// Unknown or non consecutive order
NumDeps = 7, /// Overall amount of dependencies
INVALID = 8
};
};
// Provide FastValueMapAttributeInfo for WIDependancy.
template<> struct FastValueMapAttributeInfo<WIBaseClass::WIDependancy> {
static inline WIBaseClass::WIDependancy getEmptyAttribute() { return WIBaseClass::INVALID; }
};
class WIAnalysisRunner
{
public:
void init(
llvm::Function* F,
llvm::DominatorTree* DT,
llvm::PostDominatorTree* PDT,
IGCMD::MetaDataUtils* MDUtils,
CodeGenContext* CGCtx,
ModuleMetaData* ModMD,
TranslationTable* TransTable);
WIAnalysisRunner(
llvm::Function* F,
llvm::DominatorTree* DT,
llvm::PostDominatorTree* PDT,
IGCMD::MetaDataUtils* MDUtils,
CodeGenContext* CGCtx,
ModuleMetaData* ModMD,
TranslationTable* TransTable)
{
init(F, DT, PDT, MDUtils, CGCtx, ModMD, TransTable);
}
WIAnalysisRunner() {}
~WIAnalysisRunner() {}
bool run();
/// @brief Returns the type of dependency the instruction has on
/// the work-item
/// @param val llvm::Value to test
/// @return Dependency kind
WIBaseClass::WIDependancy whichDepend(const llvm::Value* val) const;
/// @brief Returns True if 'val' is uniform
/// @param val llvm::Value to test
bool isUniform(const llvm::Value* val) const;
bool isWorkGroupOrGlobalUniform(const llvm::Value* val);
bool isGlobalUniform(const llvm::Value* val);
/// incremental update of the dep-map on individual value
/// without propagation. Exposed for later pass.
void incUpdateDepend(const llvm::Value* val, WIBaseClass::WIDependancy dep)
{
m_depMap.SetAttribute(val, dep);
}
/// check if a value is defined inside divergent control-flow
bool insideDivergentCF(const llvm::Value* val)
{
return(llvm::isa<llvm::Instruction>(val) &&
m_ctrlBranches.find(llvm::cast<llvm::Instruction>(val)->getParent()) != m_ctrlBranches.end());
}
void releaseMemory()
{
m_ctrlBranches.clear();
m_changed1.clear();
m_changed2.clear();
m_allocaDepMap.clear();
m_storeDepMap.clear();
m_depMap.clear();
}
/// print - print m_deps in human readable form
void print(llvm::raw_ostream& OS, const llvm::Module* = 0) const;
/// dump - Dump the m_deps to a file.
void dump() const;
// helper for dumping WI info into files with lock
void lock_print();
private:
struct AllocaDep
{
std::vector<const llvm::StoreInst*> stores;
bool assume_uniform;
};
/// @brief Update dependency relations between all values
void updateDeps();
/// @brief backward update dependency based upon use
void genSpecificBackwardUpdate();
/// @brief mark the arguments dependency based on the metadata set
void updateArgsDependency(llvm::Function* pF);
/*! \name Dependency Calculation Functions
* \{ */
/// @brief Calculate the dependency type for the instruction
/// @param inst Instruction to inspect
/// @return Type of dependency.
void calculate_dep(const llvm::Value* val);
WIBaseClass::WIDependancy calculate_dep(const llvm::BinaryOperator* inst);
WIBaseClass::WIDependancy calculate_dep(const llvm::CallInst* inst);
WIBaseClass::WIDependancy calculate_dep(const llvm::GetElementPtrInst* inst);
WIBaseClass::WIDependancy calculate_dep(const llvm::PHINode* inst);
WIBaseClass::WIDependancy calculate_dep(const llvm::SelectInst* inst);
WIBaseClass::WIDependancy calculate_dep(const llvm::AllocaInst* inst);
WIBaseClass::WIDependancy calculate_dep(const llvm::CastInst* inst);
WIBaseClass::WIDependancy calculate_dep(const llvm::VAArgInst* inst);
WIBaseClass::WIDependancy calculate_dep(const llvm::LoadInst* inst);
WIBaseClass::WIDependancy calculate_dep_terminator(const IGCLLVM::TerminatorInst* inst);
/*! \} */
/// @brief do the trivial checking WI-dep
/// @param I instruction to check
/// @return Dependency type. Returns Uniform if all operands are
/// Uniform, Random otherwise
WIBaseClass::WIDependancy calculate_dep_simple(const llvm::Instruction* I);
/// @brief update the WI-dep from a divergent branch,
/// affected instructions are added to m_pChangedNew
/// @param the divergent branch
void update_cf_dep(const IGCLLVM::TerminatorInst* TI);
/// @brief update the WI-dep for a sequence of insert-elements forming a vector
/// affected instructions are added to m_pChangedNew
/// @param the insert-element instruction
void updateInsertElements(const llvm::InsertElementInst* inst);
/// @check phi divergence at a join-blk due to a divergent branch
void updatePHIDepAtJoin(llvm::BasicBlock* blk, BranchInfo* brInfo);
void updateDepMap(const llvm::Instruction* inst, WIBaseClass::WIDependancy dep);
/// @brief Provide known dependency type for requested value
/// @param val llvm::Value to examine
/// @return Dependency type. Returns Uniform for unknown type
WIBaseClass::WIDependancy getDependency(const llvm::Value* val);
/// @brief return true if there is calculated dependency type for requested value
/// @param val llvm::Value to examine
/// @return true if value has dependency type, false otherwise.
bool hasDependency(const llvm::Value* val) const;
/// @brief return true if all uses of this value are marked RANDOM
bool allUsesRandom(const llvm::Value* val);
/// @brief return true if any of the use require the value to be uniform
bool needToBeUniform(const llvm::Value* val);
/// @brief return true is the instruction is simple and making it random is cheap
bool isInstructionSimple(const llvm::Instruction* inst);
/// @brief return true if all the source operands are defined outside the region
bool isRegionInvariant(const llvm::Instruction* inst, BranchInfo* brInfo, unsigned level);
/// @brief update dependency structure for Alloca
bool TrackAllocaDep(const llvm::Value* I, AllocaDep& dep);
void checkLocalIdUniform(
llvm::Function* F,
bool& IsLxUniform,
bool& IsLyUniform,
bool& IsLzUniform);
private:
#ifdef OCL_SPECIFIC
// @brief pointer to Soa alloca analysis performed for this function
SoaAllocaAnalysis* m_soaAllocaAnalysis;
/// Runtime services pointer
RuntimeServices* m_rtServices;
#endif
/// The WIAnalysis follows pointer arithmetic
/// and Index arithmetic when calculating dependency
/// properties. If a part of the index is lost due to
/// a transformation, it is acceptable.
/// This constant decides how many bits need to be
/// preserved before we give up on the analysis.
static const unsigned int MinIndexBitwidthToPreserve;
/// Stores an updated list of all dependencies
/// for each block, store the list of diverging branches that affect it
llvm::DenseMap<const llvm::BasicBlock*, llvm::SmallPtrSet<const llvm::Instruction*, 4>> m_ctrlBranches;
/// Iteratively one set holds the changed from the previous iteration and
/// the other holds the new changed values from the current iteration.
std::vector<const llvm::Value*> m_changed1;
std::vector<const llvm::Value*> m_changed2;
/// ptr to m_changed1, m_changed2
std::vector<const llvm::Value*>* m_pChangedOld;
std::vector<const llvm::Value*>* m_pChangedNew;
llvm::Function* m_func;
llvm::DominatorTree* DT;
llvm::PostDominatorTree* PDT;
IGC::IGCMD::MetaDataUtils* m_pMdUtils;
IGC::CodeGenContext* m_CGCtx;
IGC::ModuleMetaData* m_ModMD;
IGC::TranslationTable* m_TT;
// Allow access to all the store into an alloca if we were able to track it
llvm::DenseMap<const llvm::AllocaInst*, AllocaDep> m_allocaDepMap;
// reverse map to allow to know what alloca to update when store changes
llvm::DenseMap<const llvm::StoreInst*, const llvm::AllocaInst*> m_storeDepMap;
IGC::FastValueMap<WIBaseClass::WIDependancy, FastValueMapAttributeInfo<WIBaseClass::WIDependancy>> m_depMap;
// For dumpping WIA info per each invocation
static llvm::DenseMap<const llvm::Function*, int> m_funcInvocationId;
};
/// @brief Work Item Analysis class used to provide information on
/// individual instructions. The analysis class detects values which
/// depend in work-item and describe their dependency.
/// The algorithm used is recursive and new instructions are updated
/// according to their operands (which are already calculated).
/// original code for OCL vectorizer
///
class WIAnalysis : public llvm::FunctionPass, public WIBaseClass
{
public:
static char ID; // Pass identification, replacement for typeid
WIAnalysis();
~WIAnalysis() {}
/// @brief Provides name of pass
llvm::StringRef getPassName() const override
{
return "WIAnalysis";
}
void getAnalysisUsage(llvm::AnalysisUsage& AU) const override
{
// Analysis pass preserve all
AU.setPreservesAll();
#ifdef OCL_SPECIFIC
AU.addRequired<SoaAllocaAnalysis>();
#endif
AU.addRequired<llvm::DominatorTreeWrapperPass>();
AU.addRequired<llvm::PostDominatorTreeWrapperPass>();
AU.addRequired<MetaDataUtilsWrapper>();
AU.addRequired<CodeGenContextWrapper>();
AU.addRequired<TranslationTable>();
}
/// @brief LLVM llvm::Function pass entry
/// @param F llvm::Function to transform
/// @return True if changed
bool runOnFunction(llvm::Function& F) override;
/// print - print m_deps in human readable form
void print(llvm::raw_ostream& OS, const llvm::Module* = 0) const override;
/// dump - Dump the m_deps to dbgs().
void dump() const;
public:
/// @brief Returns the type of dependency the instruction has on
/// the work-item
/// @param val llvm::Value to test
/// @return Dependency kind
WIDependancy whichDepend(const llvm::Value* val);
/// @brief Returns True if 'val' is uniform
/// @param val llvm::Value to test
bool isUniform(const llvm::Value* val) const; // Return true for any uniform
bool isWorkGroupOrGlobalUniform(const llvm::Value* val);
bool isGlobalUniform(const llvm::Value* val);
/// incremental update of the dep-map on individual value
/// without propagation. Exposed for later pass.
void incUpdateDepend(const llvm::Value* val, WIDependancy dep);
/// check if a value is defined inside divergent control-flow
bool insideDivergentCF(const llvm::Value* val);
void releaseMemory() override
{
Runner.releaseMemory();
}
/// Return true if Dep is any of uniform dependancy.
static bool isDepUniform(WIDependancy Dep) {
return Dep == WIDependancy::UNIFORM_GLOBAL ||
Dep == WIDependancy::UNIFORM_WORKGROUP ||
Dep == WIDependancy::UNIFORM_THREAD;
}
private:
WIAnalysisRunner Runner;
};
} // namespace IGC
| 40.10733 | 116 | 0.651655 | [
"vector",
"transform"
] |
c835495d07a22bb30d1f8168b390189d104b19ef | 2,499 | cpp | C++ | src/InkDocument.cpp | sunjinbo/ink | fc3d7366dd8646cb2243f65a7785e80d86bc381c | [
"MIT"
] | null | null | null | src/InkDocument.cpp | sunjinbo/ink | fc3d7366dd8646cb2243f65a7785e80d86bc381c | [
"MIT"
] | null | null | null | src/InkDocument.cpp | sunjinbo/ink | fc3d7366dd8646cb2243f65a7785e80d86bc381c | [
"MIT"
] | null | null | null | /* ====================================================================
* File: InkDocument.cpp
* Created: 03/03/10
* Author: Sun Jinbo
* Copyright (c): Tieto, All rights reserved
* ==================================================================== */
// INCLUDS
#include "InkAppUi.h"
#include "InkDocument.h"
// CONSTANS
// ======== MEMBER FUNCTIONS ========
// ----------------------------------------------------------------------------
// CInkDocument::NewL
// Standard Symbian OS construction sequence
// ----------------------------------------------------------------------------
//
CInkDocument* CInkDocument::NewL(CEikApplication& aApp)
{
CInkDocument* self = NewLC(aApp);
CleanupStack::Pop(self);
return self;
}
// ----------------------------------------------------------------------------
// CInkDocument::NewLC
// Standard Symbian OS construction sequence
// ----------------------------------------------------------------------------
//
CInkDocument* CInkDocument::NewLC(CEikApplication& aApp)
{
CInkDocument* self = new (ELeave) CInkDocument(aApp);
CleanupStack::PushL(self);
self->ConstructL();
return self;
}
// ----------------------------------------------------------------------------
// CInkDocument::ConstructL
// ----------------------------------------------------------------------------
//
void CInkDocument::ConstructL()
{
// no implementation required
}
// ----------------------------------------------------------------------------
// CInkDocument::CInkDocument
// ----------------------------------------------------------------------------
//
CInkDocument::CInkDocument(CEikApplication& aApp)
: CAknDocument(aApp)
{
// no implementation required
}
// ----------------------------------------------------------------------------
// CInkDocument::~CInkDocument
// ----------------------------------------------------------------------------
//
CInkDocument::~CInkDocument()
{
// no implementation required
}
// ----------------------------------------------------------------------------
// CInkDocument::CreateAppUiL
// ----------------------------------------------------------------------------
//
CEikAppUi* CInkDocument::CreateAppUiL()
{
// Create the application user interface, and return a pointer to it,
// the framework takes ownership of this object
CEikAppUi* appUi = new (ELeave) CInkAppUi;
return appUi;
}
// End of File
| 30.47561 | 79 | 0.37455 | [
"object"
] |
c83ac52d7f8b092f1ab973f2cca96b9669406e0f | 14,246 | cpp | C++ | tools/pnnx/src/pass_level2.cpp | CeasarLee/ncnn | 178825d14a16c4059820d9f054a8d857df671027 | [
"BSD-3-Clause"
] | null | null | null | tools/pnnx/src/pass_level2.cpp | CeasarLee/ncnn | 178825d14a16c4059820d9f054a8d857df671027 | [
"BSD-3-Clause"
] | null | null | null | tools/pnnx/src/pass_level2.cpp | CeasarLee/ncnn | 178825d14a16c4059820d9f054a8d857df671027 | [
"BSD-3-Clause"
] | null | null | null | // Tencent is pleased to support the open source community by making ncnn available.
//
// Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// https://opensource.org/licenses/BSD-3-Clause
//
// 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 "pass_level2.h"
#include <algorithm>
#include <map>
#include <unordered_map>
namespace pnnx {
GraphRewriterPass::~GraphRewriterPass()
{
}
const char* GraphRewriterPass::name_str() const
{
return type_str();
}
bool GraphRewriterPass::match(const std::map<std::string, Parameter>& /*captured_params*/) const
{
return true;
}
bool GraphRewriterPass::match(const std::map<std::string, Parameter>& captured_params, const std::map<std::string, Attribute>& /*captured_attrs*/) const
{
return match(captured_params);
}
void GraphRewriterPass::write(Operator* op, const std::map<std::string, Parameter>& captured_params) const
{
for (auto x : captured_params)
{
op->params[x.first] = x.second;
}
}
void GraphRewriterPass::write(Operator* op, const std::map<std::string, Parameter>& captured_params, const std::map<std::string, Attribute>& /*captured_attrs*/) const
{
write(op, captured_params);
}
static std::map<int, std::vector<const GraphRewriterPass*> > g_global_pnnx_graph_rewriter_passes;
GraphRewriterPassRegister::GraphRewriterPassRegister(const GraphRewriterPass* _pass, int priority)
: pass(_pass)
{
if (g_global_pnnx_graph_rewriter_passes.find(priority) == g_global_pnnx_graph_rewriter_passes.end())
{
g_global_pnnx_graph_rewriter_passes[priority] = std::vector<const GraphRewriterPass*>();
}
g_global_pnnx_graph_rewriter_passes[priority].push_back(pass);
}
GraphRewriterPassRegister::~GraphRewriterPassRegister()
{
delete pass;
}
static bool match_parameter(const Parameter& a, const Parameter& b, std::map<std::string, Parameter>& captured_params)
{
if (b.type == 4 && b.s[0] == '%')
{
// captured parameter
captured_params[b.s.substr(1)] = a;
return true;
}
if (b.type == 4 && b.s == "*")
{
// ignored parameter
return true;
}
if (a.type != b.type)
return false;
const int type = a.type;
if (type == 0)
{
return true;
}
if (type == 1)
{
return a.b == b.b;
}
if (type == 2)
{
return a.i == b.i;
}
if (type == 3)
{
return a.f == b.f;
}
if (type == 4)
{
return a.s == b.s;
}
if (type == 5)
{
if (a.ai.size() != b.ai.size())
return false;
for (size_t i = 0; i < a.ai.size(); i++)
{
if (a.ai[i] != b.ai[i])
return false;
}
return true;
}
if (type == 6)
{
if (a.af.size() != b.af.size())
return false;
for (size_t i = 0; i < a.af.size(); i++)
{
if (a.af[i] != b.af[i])
return false;
}
return true;
}
if (type == 7)
{
if (a.as.size() != b.as.size())
return false;
for (size_t i = 0; i < a.as.size(); i++)
{
if (a.as[i] != b.as[i])
return false;
}
return true;
}
// unknown
return false;
}
static bool match_operator(const Operator* a, const Operator* b, std::map<std::string, Parameter>& captured_params, std::map<std::string, Attribute>& captured_attrs)
{
if (a->type != b->type)
return false;
if (a->inputs.size() != b->inputs.size())
return false;
if (a->outputs.size() != b->outputs.size())
return false;
// match params
if (b->params.size() == 1 && b->params.find("%*") != b->params.end() && b->params.at("%*").type == 4 && b->params.at("%*").s == "%*")
{
for (const auto& p : a->params)
{
const std::string& pkey = p.first;
const Parameter& pp = p.second;
// capture all parameters
captured_params[b->name + '.' + pkey] = pp;
}
}
else
{
if (a->params.size() != b->params.size())
return false;
for (const auto& p : a->params)
{
const std::string& akey = p.first;
const Parameter& ap = p.second;
if (b->params.find(akey) == b->params.end())
return false;
if (!match_parameter(ap, b->params.at(akey), captured_params))
return false;
}
}
for (const auto& p : a->attrs)
{
const std::string& akey = p.first;
const Attribute& aa = p.second;
// capture all attributes
captured_attrs[b->name + '.' + akey] = aa;
}
return true;
}
static bool match(const Operator* anchor, const Operator* pattern, std::unordered_map<std::string, const Operator*>& matched_operators, std::unordered_map<std::string, const Operand*>& matched_inputs, std::map<std::string, Parameter>& captured_params, std::map<std::string, Attribute>& captured_attrs)
{
if (!match_operator(anchor, pattern, captured_params, captured_attrs))
return false;
for (size_t i = 0; i < pattern->outputs.size(); i++)
{
if (pattern->outputs[i]->consumers.size() == 1 && pattern->outputs[i]->consumers[0]->type == "pnnx.Output")
continue;
if (anchor->outputs[i]->consumers.size() != pattern->outputs[i]->consumers.size())
return false;
}
matched_operators[pattern->name] = anchor;
// lets match
for (size_t i = 0; i < pattern->inputs.size(); i++)
{
const Operator* anchor2 = anchor->inputs[i]->producer;
const Operator* pattern2 = pattern->inputs[i]->producer;
if (pattern2->type == "pnnx.Input")
{
if (matched_inputs.find(pattern->inputs[i]->name) == matched_inputs.end())
{
matched_inputs[pattern->inputs[i]->name] = anchor->inputs[i];
}
continue;
}
if (!match(anchor2, pattern2, matched_operators, matched_inputs, captured_params, captured_attrs))
return false;
}
return true;
}
void pnnx_graph_rewrite(Graph& graph, const GraphRewriterPass* pass, int& opindex)
{
Graph pattern_graph;
pattern_graph.parse(pass->match_pattern_graph());
// collect pattern inputs and outputs order
std::vector<std::string> pattern_graph_inputs;
std::vector<std::string> pattern_graph_outputs;
std::vector<const Operator*> pattern_graph_output_operators;
for (const auto& x : pattern_graph.ops)
{
if (x->type == "pnnx.Input")
{
for (const auto& y : x->outputs)
pattern_graph_inputs.push_back(y->name);
}
if (x->type == "pnnx.Output")
{
pattern_graph_output_operators.push_back(x);
for (const auto& y : x->inputs)
pattern_graph_outputs.push_back(y->name);
}
}
std::vector<Operator*> new_ops;
while (1)
{
const int graph_op_count = (int)graph.ops.size();
bool matched = true;
// lets match from output
std::unordered_map<std::string, const Operator*> matched_operators;
std::unordered_map<std::string, const Operand*> matched_inputs;
std::unordered_map<std::string, const Operand*> matched_outputs;
std::map<std::string, Parameter> captured_params;
std::map<std::string, Attribute> captured_attrs;
// pattern match from end to beginning
int q = graph_op_count - 1;
for (; q >= 1; q--)
{
for (const Operator* pattern : pattern_graph_output_operators)
{
for (size_t i = 0; i < pattern->inputs.size(); i++)
{
const Operator* pattern2 = pattern->inputs[i]->producer;
int j = q;
for (; j >= 0; j--)
{
const Operator* anchor = graph.ops[j];
std::unordered_map<std::string, const Operator*> matched_operators2;
std::unordered_map<std::string, const Operand*> matched_inputs2;
std::map<std::string, Parameter> captured_params2;
std::map<std::string, Attribute> captured_attrs2;
if (!match(anchor, pattern2, matched_operators2, matched_inputs2, captured_params2, captured_attrs2))
continue;
bool submatch_matched = true;
for (auto x : matched_operators2)
{
// check these matched operators are same with previous matched ones
if (matched_operators.find(x.first) != matched_operators.end())
{
if (matched_operators[x.first] != x.second)
{
// unmatched two sub-matches
submatch_matched = false;
break;
}
}
else
{
matched_operators[x.first] = x.second;
}
}
if (!submatch_matched)
continue;
for (auto x : matched_inputs2)
{
if (matched_inputs.find(x.first) == matched_inputs.end())
{
matched_inputs[x.first] = x.second;
}
}
for (auto x : captured_params2)
{
captured_params[x.first] = x.second;
}
for (auto x : captured_attrs2)
{
captured_attrs[x.first] = x.second;
}
// match !
matched_outputs[pattern->inputs[i]->name] = anchor->outputs[i];
break;
}
if (j == -1)
{
matched = false;
break;
}
}
if (!matched)
break;
}
if (matched && !pass->match(captured_params, captured_attrs))
{
matched_operators.clear();
matched_inputs.clear();
matched_outputs.clear();
captured_params.clear();
captured_attrs.clear();
continue;
}
break;
}
if (!matched)
break;
// fprintf(stderr, "matched !\n");
// lets replace
// remove all matched_operators
for (auto& _x : matched_operators)
{
// fprintf(stderr, "remove %s\n", _x.second->name.c_str());
Operator* x = (Operator*)_x.second;
for (auto& r : x->inputs)
{
r->remove_consumer(x);
}
x->inputs.clear();
for (auto& r : x->outputs)
{
r->producer = 0;
}
x->outputs.clear();
graph.ops.erase(std::find(graph.ops.begin(), graph.ops.end(), x));
delete _x.second;
}
// insert new operator before all output consumers
const Operator* cur = 0;
{
int cur_index = graph.ops.size() - 1;
for (auto& o : matched_outputs)
{
for (auto& c : o.second->consumers)
{
int c_index = std::find(graph.ops.begin(), graph.ops.end(), c) - graph.ops.begin();
cur_index = std::min(cur_index, c_index);
}
}
cur = graph.ops[cur_index];
}
Operator* op = graph.new_operator_before(pass->type_str(), std::string(pass->name_str()), cur);
for (const auto& k : pattern_graph_inputs)
{
Operand* r = (Operand*)matched_inputs.at(k);
r->consumers.push_back(op);
op->inputs.push_back(r);
op->inputnames.push_back(k);
}
for (const auto& k : pattern_graph_outputs)
{
Operand* r = (Operand*)matched_outputs.at(k);
r->producer = op;
op->outputs.push_back(r);
}
pass->write(op, captured_params, captured_attrs);
new_ops.push_back(op);
}
// assign new op name number
for (int i = (int)new_ops.size() - 1; i >= 0; i--)
{
new_ops[i]->name = new_ops[i]->name + "_" + std::to_string(opindex++);
}
}
void pass_level2(Graph& g)
{
int opindex = 0;
for (auto x : g_global_pnnx_graph_rewriter_passes)
{
for (auto rewriter : x.second)
{
pnnx_graph_rewrite(g, rewriter, opindex);
}
}
}
} // namespace pnnx
| 30.505353 | 302 | 0.496209 | [
"vector"
] |
c83fe37c6a0b715b26b4d2e36eaa1c4c6a282159 | 13,003 | cpp | C++ | svo_img_align/src/sparse_img_align_gpu.cpp | jsz0913/rpg_dvs_evo_open | 93edc7a2d215ed097e3f6a9abbefd0b572958b74 | [
"BSD-2-Clause-Patent"
] | 97 | 2021-06-24T09:34:08.000Z | 2022-02-28T01:58:09.000Z | svo_img_align/src/sparse_img_align_gpu.cpp | jsz0913/rpg_dvs_evo_open | 93edc7a2d215ed097e3f6a9abbefd0b572958b74 | [
"BSD-2-Clause-Patent"
] | 14 | 2021-06-14T13:01:27.000Z | 2022-03-30T01:49:57.000Z | svo_img_align/src/sparse_img_align_gpu.cpp | jsz0913/rpg_dvs_evo_open | 93edc7a2d215ed097e3f6a9abbefd0b572958b74 | [
"BSD-2-Clause-Patent"
] | 32 | 2021-06-24T09:34:12.000Z | 2022-03-01T15:23:29.000Z | // This file is part of SVO - Semi-direct Visual Odometry.
//
// Copyright (C) 2014 Christian Forster <forster at ifi dot uzh dot ch>
// (Robotics and Perception Group, University of Zurich, Switzerland).
//
// This file is subject to the terms and conditions defined in the file
// 'LICENSE', which is part of this source code package.
#include <svo/img_align/sparse_img_align_gpu.h>
#include <algorithm>
#include <opencv2/highgui/highgui.hpp>
#include <vikit/vision.h>
#include <vikit/math_utils.h>
#include <aslam/cameras/camera-pinhole.h>
#include <imp/cu_core/cu_image_gpu.cuh>
#include <imp/cu_core/cu_matrix.cuh>
#include <imp/cu_core/cu_pinhole_camera.cuh>
#include <imp/bridge/opencv/image_cv.hpp>
//TODO: remove
#include <imp/bridge/opencv/cu_cv_bridge.hpp>
#include <svo/common/logging.h>
#include <svo/common/point.h>
#include <svo/direct/depth_filter.h>
#include <svo/img_align/sparse_img_align_device_utils.cuh>
#include <svo/img_align/frame_gpu.h>
namespace svo {
SparseImgAlignGpu::SparseImgAlignGpu(
SolverOptions optimization_options,
SparseImgAlignOptions options)
: SparseImgAlignBase(optimization_options,options)
{
setPatchSize<SparseImgAlignGpu>(4);
}
size_t SparseImgAlignGpu::run(
const FrameBundle::Ptr& ref_frames,
const FrameBundle::Ptr& cur_frames)
{
CHECK(!ref_frames->empty());
CHECK_EQ(ref_frames->size(),cur_frames->size());
// Set member variables
ref_frames_ = ref_frames;
cur_frames_ = cur_frames;
T_iref_world_ = ref_frames->at(0)->T_imu_world();
// Transform to GPU datatypes. TODO: This should be done only ones for transformation/camera data
int nbr_cameras = static_cast<int>(ref_frames->frames_.size());
cu_ref_imgs_pyramid_copy_.resize(nbr_cameras);
cu_cur_imgs_pyramid_copy_.resize(nbr_cameras);
cu_T_imu_cam_bundle_.resize(nbr_cameras);
cu_T_cam_imu_bundle_.resize(nbr_cameras);
cu_camera_bundle_.resize(nbr_cameras);
// check if Gpu frame and if gpu frame data is initialized
// TOTO (mg): modify sparse image align gpu function to take frame bundels.
if(dynamic_cast<FrameGpu*>(ref_frames->at(0).get()) == nullptr || !dynamic_cast<FrameGpu*>(ref_frames->at(0).get())->cu_camera_)
{
SVO_WARN_STREAM("Sparse image align: Input frame is not a GPU. Creating GPU data structures now.");
// Input is not a GPU frame bundle. GPU datastructures need to be instantiated.
for(int i = 0; i < nbr_cameras; ++i)
{
cu_ref_imgs_pyramid_copy_.at(i).resize(options_.max_level + 1);
cu_cur_imgs_pyramid_copy_.at(i).resize(options_.max_level + 1);
for(int j = 0; j < static_cast<int>(cu_ref_imgs_pyramid_copy_.at(i).size()); ++j)
{
cu_ref_imgs_pyramid_copy_.at(i).at(j) = std::make_shared<imp::cu::ImageGpu8uC1>(
imp::cu::ImageGpu8uC1(imp::ImageCv8uC1(ref_frames_->frames_.at(i)->img_pyr_.at(j))));
cu_cur_imgs_pyramid_copy_.at(i).at(j) = std::make_shared<imp::cu::ImageGpu8uC1>(
imp::cu::ImageGpu8uC1(imp::ImageCv8uC1(cur_frames_->frames_.at(i)->img_pyr_.at(j))));
}
cu_T_imu_cam_bundle_.at(i) = std::make_shared<imp::cu::Matrix<FloatTypeGpu,3,4> >(
imp::cu::Matrix<FloatTypeGpu,3,4>(
ref_frames->frames_.at(i)->T_imu_cam().getTransformationMatrix().block<3,4>(0,0).cast<FloatTypeGpu>()));
cu_T_cam_imu_bundle_.at(i) = std::make_shared<imp::cu::Matrix<FloatTypeGpu,3,4> >(
imp::cu::Matrix<FloatTypeGpu,3,4>(
ref_frames->frames_.at(i)->T_cam_imu().getTransformationMatrix().block<3,4>(0,0).cast<FloatTypeGpu>()));
aslam::PinholeCamera* pinhole = dynamic_cast<aslam::PinholeCamera*>(ref_frames->frames_.at(i)->cam().get());
if((pinhole != nullptr) && (pinhole->getDistortion().getType() == aslam::Distortion::Type::kNoDistortion))
{
cu_camera_bundle_.at(i) = std::make_shared<imp::cu::PinholeCamera>(
imp::cu::PinholeCamera(pinhole->fu(),pinhole->fv(),pinhole->cu(),pinhole->cv()));
}
else
{
SVO_ERROR_STREAM("Camera model not supported yet for GPU version");
return 0;
}
}
}
else
{
// Input is a GPU frame bundle. Simply copy the pointers to the GPU data.
for(int i = 0; i < nbr_cameras; ++i)
{
cu_ref_imgs_pyramid_copy_.at(i).resize(options_.max_level + 1);
cu_cur_imgs_pyramid_copy_.at(i).resize(options_.max_level + 1);
for(int j = 0; j < static_cast<int>(cu_ref_imgs_pyramid_copy_.at(i).size()); ++j)
{
cu_ref_imgs_pyramid_copy_.at(i).at(j) = std::static_pointer_cast<FrameGpu>(ref_frames_->at(i))->cu_img_pyramid_copy_.at(j);
cu_cur_imgs_pyramid_copy_.at(i).at(j) = std::static_pointer_cast<FrameGpu>(cur_frames_->at(i))->cu_img_pyramid_copy_.at(j);
}
cu_T_imu_cam_bundle_.at(i) = std::static_pointer_cast<FrameGpu>(ref_frames_->at(i))->cu_T_imu_cam_;
cu_T_cam_imu_bundle_.at(i) = std::static_pointer_cast<FrameGpu>(ref_frames_->at(i))->cu_T_cam_imu_;
cu_camera_bundle_.at(i) = std::static_pointer_cast<FrameGpu>(ref_frames_->at(i))->cu_camera_;
}
}
// Clear caches on host. Capacity remains unchanged.
host_cache_.clear();
// Select all visible features and subsample if required.
size_t nbr_fts_to_track = 0;
size_t nbr_extracted = 0;
for(auto frame : ref_frames->frames_)
{
host_cache_.first_ftr_index.push_back(nbr_fts_to_track);
sparse_img_align_host_utils::extractFeaturesSubset(*frame,
options_.max_level,
patch_size_with_border_,
nbr_extracted,
host_cache_);
nbr_fts_to_track += nbr_extracted;
host_cache_.nbr_of_ftrs.push_back(nbr_extracted);
}
host_cache_.total_nbr_of_ftrs = nbr_fts_to_track;
// The variable to be optimized is the imu-pose of the current frame.
Transformation T_icur_iref =
cur_frames_->at(0)->T_imu_world() * T_iref_world_.inverse();
SparseImgAlignState state;
state.T_icur_iref = T_icur_iref;
state.alpha = alpha_init_;
state.beta = beta_init_;
// Precompute values common to all pyramid levels.
sparse_img_align_device_utils::precomputeBaseCaches(host_cache_.uv_cache,
host_cache_.xyz_ref_cache,
host_cache_.first_ftr_index,
host_cache_.nbr_of_ftrs,
cu_T_imu_cam_bundle_,
cu_T_cam_imu_bundle_,
cu_camera_bundle_,
host_cache_.total_nbr_of_ftrs,
gpu_cache_);
// To reserve sufficient memory for the reduction step we need to compute the number of blocks and threads
// for the reduction step.
sparse_img_align_device_utils::computeNumBlocksAndThreadsReduction(host_cache_.total_nbr_of_ftrs,
patch_area_,
gpu_props_,
num_blocks_reduce_, num_threads_reduce_);
gpu_cache_.reserveReductionCacheCapacity(static_cast<size_t>(num_blocks_reduce_));
for(level_=options_.max_level; level_>=options_.min_level; --level_)
{
mu_ = 0.1;
have_cache_ = false; // at every level, recompute the jacobians
if(solver_options_.verbose)
printf("\nPYRAMID LEVEL %i\n---------------\n", level_);
optimize(state);
}
/// Uncomment if you need the median disparity
// median_disparity_ = sparse_img_align_device_utils::computeDisparity(
// cu_cur_imgs_pyramid_copy_,
// cu_T_cur_ref_bundle_,
// cu_camera_bundle_,
// host_cache_.first_ftr_index,
// host_cache_.nbr_of_ftrs,
// host_cache_.total_nbr_of_ftrs,
// gpu_cache_);
// Finished, we save the pose in the frame.
for(auto f : cur_frames->frames_)
{
f->T_f_w_ = f->T_cam_imu()*state.T_icur_iref*T_iref_world_;
}
// Reset initial values of illumination estimation TODO: make reset function
alpha_init_ = 0.0;
beta_init_ = 0.0;
return host_cache_.total_nbr_of_ftrs;
}
double SparseImgAlignGpu::evaluateError(
const SparseImgAlignState& state,
HessianMatrix* H,
GradientVector* g)
{
if(!have_cache_) // is reset at every new level.
{
//TODO check why gpu image pyramid does not work
// sparse_img_align_device_utils::precomputeJacobiansAndRefPatches(
// cu_ref_pyramids_device_,
// level_,
// kPatchSize_,
// options_.estimate_illumination_gain,
// options_.estimate_illumination_offset,
// host_cache_.first_ftr_index,
// host_cache_.nbr_of_ftrs,
// gpu_cache_);
sparse_img_align_device_utils::precomputeJacobiansAndRefPatches(
cu_ref_imgs_pyramid_copy_,
level_,
patch_size_,
options_.estimate_illumination_gain,
options_.estimate_illumination_offset,
host_cache_.first_ftr_index,
host_cache_.nbr_of_ftrs,
gpu_cache_);
have_cache_ = true;
}
// Store T_cur_ref in GPU compatible format.
cu_T_cur_ref_bundle_.resize(cu_T_cam_imu_bundle_.size());
for(size_t i = 0; i < cu_T_cam_imu_bundle_.size();++i)
{
const Transformation T_cur_ref =
cur_frames_->at(i)->T_cam_imu() * state.T_icur_iref
* ref_frames_->at(i)->T_imu_cam();
cu_T_cur_ref_bundle_.at(i) =
imp::cu::Matrix<FloatTypeGpu,3,4>(
T_cur_ref.getTransformationMatrix().block<3,4>(0,0).cast<FloatTypeGpu>());
}
//TODO: Bring camera control back
sparse_img_align_device_utils::computeResidualsOfFrame(
cu_cur_imgs_pyramid_copy_, cu_T_cur_ref_bundle_,
cu_camera_bundle_,
host_cache_.first_ftr_index,
host_cache_.nbr_of_ftrs,
level_, patch_size_,
state.alpha, state.beta,
gpu_cache_);
FloatTypeGpu chi2 = sparse_img_align_device_utils::computeHessianAndGradient(
H, g,
host_cache_.total_nbr_of_ftrs*patch_area_,
patch_area_,
gpu_cache_,
num_blocks_reduce_,
num_threads_reduce_);
return chi2;
}
namespace sparse_img_align_host_utils
{
void extractFeaturesSubset(const Frame& ref_frame,
const int max_level,
const int patch_size_wb, // patch_size + border (usually 2 for gradient),
size_t& nr_fts_extracted,
HostCacheHandler& host_cache)
{
const FloatTypeGpu scale = 1.0f/(1<<max_level);
const Vector3ft ref_pos = ref_frame.pos();
const cv::Mat& ref_img = ref_frame.img_pyr_.at(max_level);
const int rows_minus_one = ref_img.rows - 1;
const int cols_minus_one = ref_img.cols - 1;
const FloatTypeGpu patch_center_wb = (patch_size_wb - 1)/2.0f;
nr_fts_extracted = 0;
for(size_t i = 0; i < ref_frame.num_features_; ++i)
{
if(ref_frame.landmark_vec_[i] == nullptr &&
ref_frame.seed_ref_vec_[i].keyframe == nullptr)
{
continue;
}
const FloatTypeGpu u_tl = ref_frame.px_vec_(0,i)*scale - patch_center_wb;
const FloatTypeGpu v_tl = ref_frame.px_vec_(1,i)*scale - patch_center_wb;
const int u_tl_i = std::floor(u_tl);
const int v_tl_i = std::floor(v_tl);
if(!(u_tl_i < 0 || v_tl_i < 0
|| u_tl_i + patch_size_wb >= cols_minus_one || v_tl_i + patch_size_wb >= rows_minus_one))
{
host_cache.push_uv(static_cast<FloatTypeGpu>(ref_frame.px_vec_(0,i)),
static_cast<FloatTypeGpu>(ref_frame.px_vec_(1,i)));
// evaluate jacobian. cannot just take the 3d points coordinate because of
// the reprojection errors in the reference image!!!
FloatTypeGpu depth = 0;
if(ref_frame.landmark_vec_[i])
{
depth = ((ref_frame.landmark_vec_[i]->pos_ - ref_pos).norm());
}
else if(ref_frame.seed_ref_vec_[i].keyframe)
{
const SeedRef& seed_ref = ref_frame.seed_ref_vec_[i];
const Position pos = seed_ref.keyframe->T_world_cam()
* (seed_ref.keyframe->f_vec_.col(seed_ref.seed_id)
* 1.0/seed_ref.keyframe->invmu_sigma2_a_b_vec_(0, seed_ref.seed_id));
depth = (pos - ref_pos).norm();
}
const Vector3ftGpu xyz_ref(ref_frame.f_vec_.col(i).cast<FloatTypeGpu>()*depth);
host_cache.push_xyz(xyz_ref(0),xyz_ref(1),xyz_ref(2));
nr_fts_extracted++;
}
}
SVO_DEBUG_STREAM("Img Align: Maximum Number of Features = " << ref_frame.num_features_);
}
} // namespace sparse_img_align_host_utils
} // namespace svo
| 39.40303 | 131 | 0.649004 | [
"model",
"transform",
"3d"
] |
c84064f9d58a20254ee5ec6f35530fc92b545669 | 2,387 | cpp | C++ | PopcornTime_Desktop-src/Import/QtAV/tools/templates/vo.cpp | officialrafsan/POPCORNtime | b5bc452b10d7b46c2f4978e37d7fd2e9c0f75782 | [
"MIT"
] | null | null | null | PopcornTime_Desktop-src/Import/QtAV/tools/templates/vo.cpp | officialrafsan/POPCORNtime | b5bc452b10d7b46c2f4978e37d7fd2e9c0f75782 | [
"MIT"
] | null | null | null | PopcornTime_Desktop-src/Import/QtAV/tools/templates/vo.cpp | officialrafsan/POPCORNtime | b5bc452b10d7b46c2f4978e37d7fd2e9c0f75782 | [
"MIT"
] | null | null | null |
#include "QtAV/%CLASS%.h"
#include "private/VideoRenderer_p.h"
#include <QResizeEvent>
namespace QtAV {
class %CLASS%Private : public VideoRendererPrivate
{
public:
DPTR_DECLARE_PUBLIC(%CLASS%)
%CLASS%Private()
{
}
~%CLASS%Private() {
}
virtual void setupQuality() {}
};
%CLASS%::%CLASS%(QWidget *parent, Qt::WindowFlags f):
QWidget(parent, f)
, VideoRenderer(*new %CLASS%Private())
{
DPTR_INIT_PRIVATE(%CLASS%);
setAcceptDrops(true);
setFocusPolicy(Qt::StrongFocus);
//setAttribute(Qt::WA_OpaquePaintEvent);
//setAttribute(Qt::WA_NoSystemBackground);
setAutoFillBackground(false);
setAttribute(Qt::WA_PaintOnScreen, true);
}
%CLASS%::~%CLASS%()
{
}
QPaintEngine* %CLASS%::paintEngine() const
{
return 0; //use native engine
}
void %CLASS%::convertData(const QByteArray &data)
{
DPTR_D(%CLASS%);
//TODO: if date is deep copied, mutex can be avoided
QMutexLocker locker(&d.img_mutex);
Q_UNUSED(locker);
}
ool %CLASS%::needUpdateBackground() const
{
return VideoRenderer::needUpdateBackground();
}
void %CLASS%::drawBackground()
{
}
bool %CLASS%::needDrawFrame() const
{
return VideoRenderer::needDrawFrame();
}
void %CLASS%::drawFrame()
{
//assume that the image data is already scaled to out_size(NOT renderer size!)
if (d.src_width == d.out_rect.width() && d.src_height == d.out_rect.height()) {
//you may copy data to video buffer directly
} else {
//paint with scale
}
}
void %CLASS%::paintEvent(QPaintEvent *)
{
//DPTR_D(%CLASS%);
//d.painter->begin(this); //Widget painting can only begin as a result of a paintEvent
handlePaintEvent();
//end paint. how about QPainter::endNativePainting()?
//d.painter->end();
}
void %CLASS%::resizeEvent(QResizeEvent *e)
{
DPTR_D(%CLASS%);
d.update_background = true;
resizeRenderer(e->size());
update();
}
void %CLASS%::showEvent(QShowEvent *event)
{
Q_UNUSED(event);
DPTR_D(%CLASS%);
d.update_background = true;
/*
* Do something that depends on widget below! e.g. recreate render target for direct2d.
* When Qt::WindowStaysOnTopHint changed, window will hide first then show. If you
* don't do anything here, the widget content will never be updated.
*/
}
bool %CLASS%::write()
{
update();
return true;
}
} //namespace QtAV
| 21.3125 | 91 | 0.661919 | [
"render"
] |
c8410b3e6be6e6cbc669c4ff16f3aecb1eaeb112 | 807 | cpp | C++ | graph-source-code/505-B/9706422.cpp | AmrARaouf/algorithm-detection | 59f3028d2298804870b32729415d71eec6116557 | [
"MIT"
] | null | null | null | graph-source-code/505-B/9706422.cpp | AmrARaouf/algorithm-detection | 59f3028d2298804870b32729415d71eec6116557 | [
"MIT"
] | null | null | null | graph-source-code/505-B/9706422.cpp | AmrARaouf/algorithm-detection | 59f3028d2298804870b32729415d71eec6116557 | [
"MIT"
] | null | null | null | //Language: GNU C++
#include<iostream>
#include<stdio.h>
#include<vector>
#include<algorithm>
#include<string>
#include<stdio.h>
#include<map>
#include<bitset>
using namespace std;
vector<int> graph[105][105];
void DFS(vector<int> grap[],int u,bool vis[],int v){
vis[u]=1;
for(int i=0;i<grap[u].size();i++){
if(vis[grap[u][i]]==0){
DFS(grap,grap[u][i],vis,v) ;
}
}
}
int main(){
//freopen("input.txt","r",stdin);
int n,m;cin>>n>>m;
for(int i=1;i<=m;i++){
int c,u,v;cin>>u>>v>>c;
graph[c-1][u-1].push_back(v-1);
graph[c-1][v-1].push_back(u-1);
}
int q;cin>>q;
while(q--){
int u,v;cin>>u>>v;
int count=0;
for(int i=0;i<m;i++){
bool vis[105]={0};
DFS(graph[i],u-1,vis,v) ;
if(vis[v-1]) count++;
}
cout<<count<<endl;
}
return 0;
}
| 14.944444 | 53 | 0.552664 | [
"vector"
] |
c841cf2fbb0a43a9b6a0e6f25ec039068ff29b94 | 31,414 | cpp | C++ | GameLib/ShipRenderContext.cpp | pac0master/Floating-Sandbox | d53ba0ce42a0ea45d56a987097396f202f793572 | [
"CC-BY-4.0"
] | null | null | null | GameLib/ShipRenderContext.cpp | pac0master/Floating-Sandbox | d53ba0ce42a0ea45d56a987097396f202f793572 | [
"CC-BY-4.0"
] | null | null | null | GameLib/ShipRenderContext.cpp | pac0master/Floating-Sandbox | d53ba0ce42a0ea45d56a987097396f202f793572 | [
"CC-BY-4.0"
] | null | null | null | /***************************************************************************************
* Original Author: Gabriele Giuseppini
* Created: 2018-03-22
* Copyright: Gabriele Giuseppini (https://github.com/GabrieleGiuseppini)
***************************************************************************************/
#include "ShipRenderContext.h"
#include "GameException.h"
#include "GameMath.h"
#include "GameParameters.h"
namespace Render {
ShipRenderContext::ShipRenderContext(
size_t pointCount,
std::optional<ImageData> texture,
ShaderManager<ShaderManagerTraits> & shaderManager,
GameOpenGLTexture & textureAtlasOpenGLHandle,
TextureAtlasMetadata const & textureAtlasMetadata,
float const(&orthoMatrix)[4][4],
float visibleWorldHeight,
float visibleWorldWidth,
float canvasToVisibleWorldHeightRatio,
float ambientLightIntensity,
float waterLevelOfDetail,
ShipRenderMode shipRenderMode,
VectorFieldRenderMode vectorFieldRenderMode,
bool showStressedSprings,
bool wireframeMode)
: mShaderManager(shaderManager)
// Parameters - all set at the end of the constructor
, mCanvasToVisibleWorldHeightRatio(0)
, mAmbientLightIntensity(0.0f)
, mWaterLevelThreshold(0.0f)
, mShipRenderMode(ShipRenderMode::Structure)
, mVectorFieldRenderMode(VectorFieldRenderMode::None)
, mShowStressedSprings(false)
, mWireframeMode(false)
// Textures
, mElementShipTexture()
, mElementStressedSpringTexture()
// Points
, mPointCount(pointCount)
, mPointPositionVBO()
, mPointLightVBO()
, mPointWaterVBO()
, mPointColorVBO()
, mPointElementTextureCoordinatesVBO()
// Generic Textures
, mTextureAtlasOpenGLHandle(textureAtlasOpenGLHandle)
, mTextureAtlasMetadata(textureAtlasMetadata)
, mGenericTextureConnectedComponents()
, mGenericTextureMaxVertexBufferSize(0)
, mGenericTextureAllocatedVertexBufferSize(0)
, mGenericTextureRenderPolygonVertexVBO()
// Connected components
, mConnectedComponentsMaxSizes()
, mConnectedComponents()
// Vectors
, mVectorArrowPointPositionBuffer()
, mVectorArrowPointPositionVBO()
, mVectorArrowColor()
{
GLuint tmpGLuint;
// Clear errors
glGetError();
//
// Create and initialize point VBOs
//
GLuint pointVBOs[5];
glGenBuffers(5, pointVBOs);
mPointPositionVBO = pointVBOs[0];
glBindBuffer(GL_ARRAY_BUFFER, *mPointPositionVBO);
glBufferData(GL_ARRAY_BUFFER, pointCount * sizeof(vec2f), nullptr, GL_DYNAMIC_DRAW);
glVertexAttribPointer(static_cast<GLuint>(VertexAttributeType::ShipPointPosition), 2, GL_FLOAT, GL_FALSE, sizeof(vec2f), (void*)(0));
CheckOpenGLError();
mPointLightVBO = pointVBOs[1];
glBindBuffer(GL_ARRAY_BUFFER, *mPointLightVBO);
glBufferData(GL_ARRAY_BUFFER, pointCount * sizeof(float), nullptr, GL_DYNAMIC_DRAW);
glVertexAttribPointer(static_cast<GLuint>(VertexAttributeType::ShipPointLight), 1, GL_FLOAT, GL_FALSE, sizeof(float), (void*)(0));
CheckOpenGLError();
mPointWaterVBO = pointVBOs[2];
glBindBuffer(GL_ARRAY_BUFFER, *mPointWaterVBO);
glBufferData(GL_ARRAY_BUFFER, pointCount * sizeof(float), nullptr, GL_DYNAMIC_DRAW);
glVertexAttribPointer(static_cast<GLuint>(VertexAttributeType::ShipPointWater), 1, GL_FLOAT, GL_FALSE, sizeof(float), (void*)(0));
CheckOpenGLError();
mPointColorVBO = pointVBOs[3];
glBindBuffer(GL_ARRAY_BUFFER, *mPointColorVBO);
glBufferData(GL_ARRAY_BUFFER, mPointCount * sizeof(vec3f), nullptr, GL_STATIC_DRAW);
glVertexAttribPointer(static_cast<GLuint>(VertexAttributeType::ShipPointColor), 3, GL_FLOAT, GL_FALSE, sizeof(vec3f), (void*)(0));
CheckOpenGLError();
mPointElementTextureCoordinatesVBO = pointVBOs[4];
glBindBuffer(GL_ARRAY_BUFFER, *mPointElementTextureCoordinatesVBO);
glBufferData(GL_ARRAY_BUFFER, mPointCount * sizeof(vec2f), nullptr, GL_STATIC_DRAW);
glVertexAttribPointer(static_cast<GLuint>(VertexAttributeType::ShipPointTextureCoordinates), 2, GL_FLOAT, GL_FALSE, sizeof(vec2f), (void*)(0));
CheckOpenGLError();
glBindBuffer(GL_ARRAY_BUFFER, 0);
//
// Create and upload ship texture, if present
//
if (!!texture)
{
glGenTextures(1, &tmpGLuint);
mElementShipTexture = tmpGLuint;
// Bind texture
glBindTexture(GL_TEXTURE_2D, *mElementShipTexture);
CheckOpenGLError();
// Upload texture
GameOpenGL::UploadMipmappedTexture(std::move(*texture));
//
// Configure texture
//
// Set repeat mode
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
CheckOpenGLError();
// Set filtering
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
CheckOpenGLError();
// Unbind texture
glBindTexture(GL_TEXTURE_2D, 0);
}
//
// Create stressed spring texture
//
// Create texture name
glGenTextures(1, &tmpGLuint);
mElementStressedSpringTexture = tmpGLuint;
// Bind texture
glBindTexture(GL_TEXTURE_2D, *mElementStressedSpringTexture);
CheckOpenGLError();
// Set repeat mode
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
CheckOpenGLError();
// Set filtering
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
CheckOpenGLError();
// Make texture data
unsigned char buf[] = {
239, 16, 39, 255, 255, 253, 181, 255, 239, 16, 39, 255,
255, 253, 181, 255, 239, 16, 39, 255, 255, 253, 181, 255,
239, 16, 39, 255, 255, 253, 181, 255, 239, 16, 39, 255
};
// Upload texture data
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 3, 3, 0, GL_RGBA, GL_UNSIGNED_BYTE, buf);
CheckOpenGLError();
// Unbind texture
glBindTexture(GL_TEXTURE_2D, 0);
//
// Initialize generic textures
//
// Create VBO
glGenBuffers(1, &tmpGLuint);
mGenericTextureRenderPolygonVertexVBO = tmpGLuint;
// Bind VBO
glBindBuffer(GL_ARRAY_BUFFER, *mGenericTextureRenderPolygonVertexVBO);
CheckOpenGLError();
// Describe vertex buffer
glVertexAttribPointer(static_cast<GLuint>(VertexAttributeType::GenericTexturePackedData1), 4, GL_FLOAT, GL_FALSE, sizeof(TextureRenderPolygonVertex), (void*)0);
glVertexAttribPointer(static_cast<GLuint>(VertexAttributeType::GenericTextureTextureCoordinates), 2, GL_FLOAT, GL_FALSE, sizeof(TextureRenderPolygonVertex), (void*)((2 + 2) * sizeof(float)));
glVertexAttribPointer(static_cast<GLuint>(VertexAttributeType::GenericTexturePackedData2), 4, GL_FLOAT, GL_FALSE, sizeof(TextureRenderPolygonVertex), (void*)((2 + 2 + 2) * sizeof(float)));
CheckOpenGLError();
//
// Initialize vector field
//
// Create VBO
glGenBuffers(1, &tmpGLuint);
mVectorArrowPointPositionVBO = tmpGLuint;
//
// Set parameters to initial values
//
UpdateOrthoMatrix(orthoMatrix);
UpdateVisibleWorldCoordinates(
visibleWorldHeight,
visibleWorldWidth,
canvasToVisibleWorldHeightRatio);
UpdateAmbientLightIntensity(ambientLightIntensity);
UpdateWaterLevelThreshold(waterLevelOfDetail);
UpdateShipRenderMode(shipRenderMode);
UpdateVectorFieldRenderMode(vectorFieldRenderMode);
UpdateShowStressedSprings(showStressedSprings);
UpdateWireframeMode(wireframeMode);
}
ShipRenderContext::~ShipRenderContext()
{
}
void ShipRenderContext::UpdateOrthoMatrix(float const(&orthoMatrix)[4][4])
{
//
// Set parameter in all programs
//
mShaderManager.ActivateProgram<ProgramType::ShipTrianglesColor>();
mShaderManager.SetProgramParameter<ProgramType::ShipTrianglesColor, ProgramParameterType::OrthoMatrix>(
orthoMatrix);
mShaderManager.ActivateProgram<ProgramType::ShipTrianglesTexture>();
mShaderManager.SetProgramParameter<ProgramType::ShipTrianglesTexture, ProgramParameterType::OrthoMatrix>(
orthoMatrix);
mShaderManager.ActivateProgram<ProgramType::ShipRopes>();
mShaderManager.SetProgramParameter<ProgramType::ShipRopes, ProgramParameterType::OrthoMatrix>(
orthoMatrix);
mShaderManager.ActivateProgram<ProgramType::ShipStressedSprings>();
mShaderManager.SetProgramParameter<ProgramType::ShipStressedSprings, ProgramParameterType::OrthoMatrix>(
orthoMatrix);
mShaderManager.ActivateProgram<ProgramType::GenericTextures>();
mShaderManager.SetProgramParameter<ProgramType::GenericTextures, ProgramParameterType::OrthoMatrix>(
orthoMatrix);
}
void ShipRenderContext::UpdateVisibleWorldCoordinates(
float /*visibleWorldHeight*/,
float /*visibleWorldWidth*/,
float canvasToVisibleWorldHeightRatio)
{
mCanvasToVisibleWorldHeightRatio = canvasToVisibleWorldHeightRatio;
}
void ShipRenderContext::UpdateAmbientLightIntensity(float ambientLightIntensity)
{
mAmbientLightIntensity = ambientLightIntensity;
//
// Set parameter in all programs
//
mShaderManager.ActivateProgram<ProgramType::ShipTrianglesColor>();
mShaderManager.SetProgramParameter<ProgramType::ShipTrianglesColor, ProgramParameterType::AmbientLightIntensity>(
ambientLightIntensity);
mShaderManager.ActivateProgram<ProgramType::ShipTrianglesTexture>();
mShaderManager.SetProgramParameter<ProgramType::ShipTrianglesTexture, ProgramParameterType::AmbientLightIntensity>(
ambientLightIntensity);
mShaderManager.ActivateProgram<ProgramType::ShipRopes>();
mShaderManager.SetProgramParameter<ProgramType::ShipRopes, ProgramParameterType::AmbientLightIntensity>(
ambientLightIntensity);
mShaderManager.ActivateProgram<ProgramType::GenericTextures>();
mShaderManager.SetProgramParameter<ProgramType::GenericTextures, ProgramParameterType::AmbientLightIntensity>(
ambientLightIntensity);
}
void ShipRenderContext::UpdateWaterLevelThreshold(float waterLevelOfDetail)
{
// Transform: 0->1 == 2.0->0.01
mWaterLevelThreshold = 2.0f + waterLevelOfDetail * (-2.0f + 0.01f);
//
// Set parameter in all programs
//
mShaderManager.ActivateProgram<ProgramType::ShipTrianglesColor>();
mShaderManager.SetProgramParameter<ProgramType::ShipTrianglesColor, ProgramParameterType::WaterLevelThreshold>(
mWaterLevelThreshold);
mShaderManager.ActivateProgram<ProgramType::ShipTrianglesTexture>();
mShaderManager.SetProgramParameter<ProgramType::ShipTrianglesTexture, ProgramParameterType::WaterLevelThreshold>(
mWaterLevelThreshold);
mShaderManager.ActivateProgram<ProgramType::ShipRopes>();
mShaderManager.SetProgramParameter<ProgramType::ShipRopes, ProgramParameterType::WaterLevelThreshold>(
mWaterLevelThreshold);
}
void ShipRenderContext::UpdateShipRenderMode(ShipRenderMode shipRenderMode)
{
mShipRenderMode = shipRenderMode;
}
void ShipRenderContext::UpdateVectorFieldRenderMode(VectorFieldRenderMode vectorFieldRenderMode)
{
mVectorFieldRenderMode = vectorFieldRenderMode;
}
void ShipRenderContext::UpdateShowStressedSprings(bool showStressedSprings)
{
mShowStressedSprings = showStressedSprings;
}
void ShipRenderContext::UpdateWireframeMode(bool wireframeMode)
{
mWireframeMode = wireframeMode;
}
//////////////////////////////////////////////////////////////////////////////////
void ShipRenderContext::RenderStart(std::vector<std::size_t> const & connectedComponentsMaxSizes)
{
// Store connected component max sizes
mConnectedComponentsMaxSizes = connectedComponentsMaxSizes;
//
// Reset generic textures
//
mGenericTextureConnectedComponents.clear();
mGenericTextureConnectedComponents.resize(connectedComponentsMaxSizes.size());
mGenericTextureMaxVertexBufferSize = 0;
}
void ShipRenderContext::UploadPointImmutableGraphicalAttributes(
vec3f const * restrict color,
vec2f const * restrict textureCoordinates)
{
// Upload colors
glBindBuffer(GL_ARRAY_BUFFER, *mPointColorVBO);
glBufferSubData(GL_ARRAY_BUFFER, 0, mPointCount * sizeof(vec3f), color);
CheckOpenGLError();
if (!!mElementShipTexture)
{
// Upload texture coordinates
glBindBuffer(GL_ARRAY_BUFFER, *mPointElementTextureCoordinatesVBO);
glBufferSubData(GL_ARRAY_BUFFER, 0, mPointCount * sizeof(vec2f), textureCoordinates);
CheckOpenGLError();
}
}
void ShipRenderContext::UploadPoints(
vec2f const * restrict position,
float const * restrict light,
float const * restrict water)
{
// Upload positions
glBindBuffer(GL_ARRAY_BUFFER, *mPointPositionVBO);
glBufferSubData(GL_ARRAY_BUFFER, 0, mPointCount * sizeof(vec2f), position);
CheckOpenGLError();
// Upload light
glBindBuffer(GL_ARRAY_BUFFER, *mPointLightVBO);
glBufferSubData(GL_ARRAY_BUFFER, 0, mPointCount * sizeof(float), light);
CheckOpenGLError();
// Upload water
glBindBuffer(GL_ARRAY_BUFFER, *mPointWaterVBO);
glBufferSubData(GL_ARRAY_BUFFER, 0, mPointCount * sizeof(float), water);
CheckOpenGLError();
}
void ShipRenderContext::UploadElementsStart()
{
GLuint elementVBO;
if (mConnectedComponentsMaxSizes.size() != mConnectedComponents.size())
{
// A change in the number of connected components, nuke everything
mConnectedComponents.clear();
mConnectedComponents.resize(mConnectedComponentsMaxSizes.size());
}
for (size_t c = 0; c < mConnectedComponentsMaxSizes.size(); ++c)
{
//
// Prepare point elements
//
// Max # of points = number of points
size_t maxConnectedComponentPoints = mConnectedComponentsMaxSizes[c];
if (mConnectedComponents[c].pointElementMaxCount != maxConnectedComponentPoints)
{
// A change in the max size of this connected component
mConnectedComponents[c].pointElementBuffer.reset();
mConnectedComponents[c].pointElementBuffer.reset(new PointElement[maxConnectedComponentPoints]);
mConnectedComponents[c].pointElementMaxCount = maxConnectedComponentPoints;
}
mConnectedComponents[c].pointElementCount = 0;
if (!mConnectedComponents[c].pointElementVBO)
{
glGenBuffers(1, &elementVBO);
mConnectedComponents[c].pointElementVBO = elementVBO;
}
//
// Prepare spring elements
//
size_t maxConnectedComponentSprings = mConnectedComponentsMaxSizes[c] * GameParameters::MaxSpringsPerPoint;
if (mConnectedComponents[c].springElementMaxCount != maxConnectedComponentSprings)
{
// A change in the max size of this connected component
mConnectedComponents[c].springElementBuffer.reset();
mConnectedComponents[c].springElementBuffer.reset(new SpringElement[maxConnectedComponentSprings]);
mConnectedComponents[c].springElementMaxCount = maxConnectedComponentSprings;
}
mConnectedComponents[c].springElementCount = 0;
if (!mConnectedComponents[c].springElementVBO)
{
glGenBuffers(1, &elementVBO);
mConnectedComponents[c].springElementVBO = elementVBO;
}
//
// Prepare rope elements
//
// Max # of ropes = max number of springs
size_t maxConnectedComponentRopes = maxConnectedComponentSprings;
if (mConnectedComponents[c].ropeElementMaxCount != maxConnectedComponentRopes)
{
// A change in the max size of this connected component
mConnectedComponents[c].ropeElementBuffer.reset();
mConnectedComponents[c].ropeElementBuffer.reset(new RopeElement[maxConnectedComponentRopes]);
mConnectedComponents[c].ropeElementMaxCount = maxConnectedComponentRopes;
}
mConnectedComponents[c].ropeElementCount = 0;
if (!mConnectedComponents[c].ropeElementVBO)
{
glGenBuffers(1, &elementVBO);
mConnectedComponents[c].ropeElementVBO = elementVBO;
}
//
// Prepare triangle elements
//
size_t maxConnectedComponentTriangles = mConnectedComponentsMaxSizes[c] * GameParameters::MaxTrianglesPerPoint;
if (mConnectedComponents[c].triangleElementMaxCount != maxConnectedComponentTriangles)
{
// A change in the max size of this connected component
mConnectedComponents[c].triangleElementBuffer.reset();
mConnectedComponents[c].triangleElementBuffer.reset(new TriangleElement[maxConnectedComponentTriangles]);
mConnectedComponents[c].triangleElementMaxCount = maxConnectedComponentTriangles;
}
mConnectedComponents[c].triangleElementCount = 0;
if (!mConnectedComponents[c].triangleElementVBO)
{
glGenBuffers(1, &elementVBO);
mConnectedComponents[c].triangleElementVBO = elementVBO;
}
//
// Prepare stressed spring elements
//
// Max # of stressed springs = max number of springs
size_t maxConnectedComponentStressedSprings = maxConnectedComponentSprings;
if (mConnectedComponents[c].stressedSpringElementMaxCount != maxConnectedComponentStressedSprings)
{
// A change in the max size of this connected component
mConnectedComponents[c].stressedSpringElementBuffer.reset();
mConnectedComponents[c].stressedSpringElementBuffer.reset(new StressedSpringElement[maxConnectedComponentStressedSprings]);
mConnectedComponents[c].stressedSpringElementMaxCount = maxConnectedComponentStressedSprings;
}
mConnectedComponents[c].stressedSpringElementCount = 0;
if (!mConnectedComponents[c].stressedSpringElementVBO)
{
glGenBuffers(1, &elementVBO);
mConnectedComponents[c].stressedSpringElementVBO = elementVBO;
}
}
}
void ShipRenderContext::UploadElementsEnd()
{
//
// Upload all elements, except for stressed springs
//
for (size_t c = 0; c < mConnectedComponents.size(); ++c)
{
// Points
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, *mConnectedComponents[c].pointElementVBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, mConnectedComponents[c].pointElementCount * sizeof(PointElement), mConnectedComponents[c].pointElementBuffer.get(), GL_STATIC_DRAW);
CheckOpenGLError();
// Springs
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, *mConnectedComponents[c].springElementVBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, mConnectedComponents[c].springElementCount * sizeof(SpringElement), mConnectedComponents[c].springElementBuffer.get(), GL_STATIC_DRAW);
CheckOpenGLError();
// Ropes
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, *mConnectedComponents[c].ropeElementVBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, mConnectedComponents[c].ropeElementCount * sizeof(RopeElement), mConnectedComponents[c].ropeElementBuffer.get(), GL_STATIC_DRAW);
CheckOpenGLError();
// Triangles
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, *mConnectedComponents[c].triangleElementVBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, mConnectedComponents[c].triangleElementCount * sizeof(TriangleElement), mConnectedComponents[c].triangleElementBuffer.get(), GL_STATIC_DRAW);
CheckOpenGLError();
}
}
void ShipRenderContext::UploadElementStressedSpringsStart()
{
for (size_t c = 0; c < mConnectedComponents.size(); ++c)
{
// Zero-out count of stressed springs
mConnectedComponents[c].stressedSpringElementCount = 0;
}
}
void ShipRenderContext::UploadElementStressedSpringsEnd()
{
//
// Upload stressed spring elements
//
for (size_t c = 0; c < mConnectedComponents.size(); ++c)
{
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, *mConnectedComponents[c].stressedSpringElementVBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, mConnectedComponents[c].stressedSpringElementCount * sizeof(StressedSpringElement), mConnectedComponents[c].stressedSpringElementBuffer.get(), GL_DYNAMIC_DRAW);
CheckOpenGLError();
}
}
void ShipRenderContext::UploadVectors(
size_t count,
vec2f const * restrict position,
vec2f const * restrict vector,
float lengthAdjustment,
vec4f const & color)
{
static float const CosAlphaLeftRight = cos(-2.f * Pi<float> / 8.f);
static float const SinAlphaLeft = sin(-2.f * Pi<float> / 8.f);
static float const SinAlphaRight = -SinAlphaLeft;
static vec2f const XMatrixLeft = vec2f(CosAlphaLeftRight, SinAlphaLeft);
static vec2f const YMatrixLeft = vec2f(-SinAlphaLeft, CosAlphaLeftRight);
static vec2f const XMatrixRight = vec2f(CosAlphaLeftRight, SinAlphaRight);
static vec2f const YMatrixRight = vec2f(-SinAlphaRight, CosAlphaLeftRight);
//
// Create buffer with endpoint positions of each segment of each arrow
//
mVectorArrowPointPositionBuffer.clear();
mVectorArrowPointPositionBuffer.reserve(count * 3 * 2);
for (size_t i = 0; i < count; ++i)
{
// Stem
vec2f stemEndpoint = position[i] + vector[i] * lengthAdjustment;
mVectorArrowPointPositionBuffer.push_back(position[i]);
mVectorArrowPointPositionBuffer.push_back(stemEndpoint);
// Left
vec2f leftDir = vec2f(-vector[i].dot(XMatrixLeft), -vector[i].dot(YMatrixLeft)).normalise();
mVectorArrowPointPositionBuffer.push_back(stemEndpoint);
mVectorArrowPointPositionBuffer.push_back(stemEndpoint + leftDir * 0.2f);
// Right
vec2f rightDir = vec2f(-vector[i].dot(XMatrixRight), -vector[i].dot(YMatrixRight)).normalise();
mVectorArrowPointPositionBuffer.push_back(stemEndpoint);
mVectorArrowPointPositionBuffer.push_back(stemEndpoint + rightDir * 0.2f);
}
//
// Upload buffer
//
glBindBuffer(GL_ARRAY_BUFFER, *mVectorArrowPointPositionVBO);
glBufferData(GL_ARRAY_BUFFER, mVectorArrowPointPositionBuffer.size() * sizeof(vec2f), mVectorArrowPointPositionBuffer.data(), GL_DYNAMIC_DRAW);
CheckOpenGLError();
//
// Store color
//
mVectorArrowColor = color;
}
void ShipRenderContext::RenderEnd()
{
//
// Disable vertex attribute 0, as we won't use it in here (it's all dedicated)
//
glDisableVertexAttribArray(0);
//
// Process all connected components, from first to last, and draw all elements
//
for (size_t c = 0; c < mConnectedComponents.size(); ++c)
{
//
// Draw points
//
if (mShipRenderMode == ShipRenderMode::Points
&& !mWireframeMode)
{
RenderPointElements(mConnectedComponents[c]);
}
//
// Draw springs
//
// We draw springs when:
// - RenderMode is springs ("X-Ray Mode"), in which case we use colors - so to show structural springs -, or
// - RenderMode is structure (so to draw 1D chains), in which case we use colors, or
// - RenderMode is texture (so to draw 1D chains), in which case we use texture iff it is present
// - AND: it's not wireframe mode
//
if ((mShipRenderMode == ShipRenderMode::Springs
|| mShipRenderMode == ShipRenderMode::Structure
|| mShipRenderMode == ShipRenderMode::Texture)
&& !mWireframeMode)
{
RenderSpringElements(
mConnectedComponents[c],
mShipRenderMode == ShipRenderMode::Texture);
}
//
// Draw ropes now if RenderMode is:
// - Springs
// - Texture (so rope endpoints are hidden behind texture, looks better)
//
if (mShipRenderMode == ShipRenderMode::Springs
|| mShipRenderMode == ShipRenderMode::Texture)
{
RenderRopeElements(mConnectedComponents[c]);
}
//
// Draw triangles
//
if (mShipRenderMode == ShipRenderMode::Structure
|| mShipRenderMode == ShipRenderMode::Texture)
{
RenderTriangleElements(
mConnectedComponents[c],
mShipRenderMode == ShipRenderMode::Texture);
}
//
// Draw ropes now if RenderMode is Structure (so rope endpoints on the structure are visible)
//
if (mShipRenderMode == ShipRenderMode::Structure)
{
RenderRopeElements(mConnectedComponents[c]);
}
//
// Draw stressed springs
//
if (mShowStressedSprings)
{
RenderStressedSpringElements(mConnectedComponents[c]);
}
//
// Draw Generic textures
//
RenderGenericTextures(mGenericTextureConnectedComponents[c]);
}
//
// Render vectors, if we're asked to
//
if (mVectorFieldRenderMode != VectorFieldRenderMode::None)
{
RenderVectors();
}
}
/////////////////////////////////////////////////////////////////////////////////////////////
void ShipRenderContext::RenderPointElements(ConnectedComponentData const & connectedComponent)
{
// Use color program
mShaderManager.ActivateProgram<ProgramType::ShipTrianglesColor>();
// Set point size
glPointSize(0.2f * 2.0f * mCanvasToVisibleWorldHeightRatio);
// Bind VBO
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, *connectedComponent.pointElementVBO);
CheckOpenGLError();
// Draw
glDrawElements(GL_POINTS, static_cast<GLsizei>(1 * connectedComponent.pointElementCount), GL_UNSIGNED_INT, 0);
}
void ShipRenderContext::RenderSpringElements(
ConnectedComponentData const & connectedComponent,
bool withTexture)
{
if (withTexture && !!mElementShipTexture)
{
// Use texture program
mShaderManager.ActivateProgram<ProgramType::ShipTrianglesTexture>();
// Bind texture
glBindTexture(GL_TEXTURE_2D, *mElementShipTexture);
CheckOpenGLError();
}
else
{
// Use color program
mShaderManager.ActivateProgram<ProgramType::ShipTrianglesColor>();
}
// Set line size
glLineWidth(0.1f * 2.0f * mCanvasToVisibleWorldHeightRatio);
// Bind VBO
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, *connectedComponent.springElementVBO);
CheckOpenGLError();
// Draw
glDrawElements(GL_LINES, static_cast<GLsizei>(2 * connectedComponent.springElementCount), GL_UNSIGNED_INT, 0);
}
void ShipRenderContext::RenderRopeElements(ConnectedComponentData const & connectedComponent)
{
if (connectedComponent.ropeElementCount > 0)
{
// Use rope program
mShaderManager.ActivateProgram<ProgramType::ShipRopes>();
// Set line size
glLineWidth(0.1f * 2.0f * mCanvasToVisibleWorldHeightRatio);
// Bind VBO
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, *connectedComponent.ropeElementVBO);
CheckOpenGLError();
// Draw
glDrawElements(GL_LINES, static_cast<GLsizei>(2 * connectedComponent.ropeElementCount), GL_UNSIGNED_INT, 0);
}
}
void ShipRenderContext::RenderTriangleElements(
ConnectedComponentData const & connectedComponent,
bool withTexture)
{
if (withTexture && !!mElementShipTexture)
{
// Use texture program
mShaderManager.ActivateProgram<ProgramType::ShipTrianglesTexture>();
// Bind texture
glBindTexture(GL_TEXTURE_2D, *mElementShipTexture);
}
else
{
// Use color program
mShaderManager.ActivateProgram<ProgramType::ShipTrianglesColor>();
}
if (mWireframeMode)
glLineWidth(0.1f);
// Bind VBO
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, *connectedComponent.triangleElementVBO);
CheckOpenGLError();
// Draw
glDrawElements(GL_TRIANGLES, static_cast<GLsizei>(3 * connectedComponent.triangleElementCount), GL_UNSIGNED_INT, 0);
}
void ShipRenderContext::RenderStressedSpringElements(ConnectedComponentData const & connectedComponent)
{
if (connectedComponent.stressedSpringElementCount > 0)
{
// Use program
mShaderManager.ActivateProgram<ProgramType::ShipStressedSprings>();
// Set line size
glLineWidth(0.1f * 2.0f * mCanvasToVisibleWorldHeightRatio);
// Bind texture
glBindTexture(GL_TEXTURE_2D, *mElementStressedSpringTexture);
CheckOpenGLError();
// Bind VBO
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, *connectedComponent.stressedSpringElementVBO);
CheckOpenGLError();
// Draw
glDrawElements(GL_LINES, static_cast<GLsizei>(2 * connectedComponent.stressedSpringElementCount), GL_UNSIGNED_INT, 0);
}
}
void ShipRenderContext::RenderGenericTextures(GenericTextureConnectedComponentData const & connectedComponent)
{
if (!connectedComponent.VertexBuffer.empty())
{
//
// Upload vertex buffer
//
glBindBuffer(GL_ARRAY_BUFFER, *mGenericTextureRenderPolygonVertexVBO);
// Allocate vertex buffer, if needed
if (mGenericTextureAllocatedVertexBufferSize != mGenericTextureMaxVertexBufferSize)
{
glBufferData(GL_ARRAY_BUFFER, mGenericTextureMaxVertexBufferSize * sizeof(TextureRenderPolygonVertex), nullptr, GL_DYNAMIC_DRAW);
CheckOpenGLError();
mGenericTextureAllocatedVertexBufferSize = mGenericTextureMaxVertexBufferSize;
}
glBufferSubData(GL_ARRAY_BUFFER, 0, connectedComponent.VertexBuffer.size() * sizeof(TextureRenderPolygonVertex), connectedComponent.VertexBuffer.data());
CheckOpenGLError();
//
// Render
//
// Use program
mShaderManager.ActivateProgram<ProgramType::GenericTextures>();
if (mWireframeMode)
glLineWidth(0.1f);
// Bind atlas
glBindTexture(GL_TEXTURE_2D, *mTextureAtlasOpenGLHandle);
CheckOpenGLError();
// Draw polygons
glDrawArrays(GL_TRIANGLES, 0, static_cast<GLsizei>(connectedComponent.VertexBuffer.size()));
}
}
void ShipRenderContext::RenderVectors()
{
// Use matte program
mShaderManager.ActivateProgram<ProgramType::Matte>();
// Set line size
glLineWidth(0.5f);
// Set vector color
mShaderManager.SetProgramParameter<ProgramType::Matte, ProgramParameterType::MatteColor>(
mVectorArrowColor.x,
mVectorArrowColor.y,
mVectorArrowColor.z,
mVectorArrowColor.w);
// Bind VBO
glBindBuffer(GL_ARRAY_BUFFER, *mVectorArrowPointPositionVBO);
CheckOpenGLError();
// Describe buffer
glVertexAttribPointer(static_cast<GLuint>(VertexAttributeType::SharedAttribute0), 2, GL_FLOAT, GL_FALSE, sizeof(vec2f), (void*)(0));
CheckOpenGLError();
// Enable vertex attribute 0
glEnableVertexAttribArray(0);
CheckOpenGLError();
// Draw
glDrawArrays(GL_LINES, 0, static_cast<GLsizei>(mVectorArrowPointPositionBuffer.size()));
}
} | 33.814855 | 206 | 0.696314 | [
"render",
"vector",
"transform"
] |
c8440d6730c630ce253495564522ac5df180d879 | 3,895 | cpp | C++ | src/plugins/intel_gpu/src/graph/activation.cpp | ryanloney/openvino-1 | 4e0a740eb3ee31062ba0df88fcf438564f67edb7 | [
"Apache-2.0"
] | 1 | 2022-02-26T17:33:44.000Z | 2022-02-26T17:33:44.000Z | src/plugins/intel_gpu/src/graph/activation.cpp | ryanloney/openvino-1 | 4e0a740eb3ee31062ba0df88fcf438564f67edb7 | [
"Apache-2.0"
] | 18 | 2022-01-21T08:42:58.000Z | 2022-03-28T13:21:31.000Z | src/plugins/intel_gpu/src/graph/activation.cpp | ryanloney/openvino-1 | 4e0a740eb3ee31062ba0df88fcf438564f67edb7 | [
"Apache-2.0"
] | 1 | 2020-12-13T22:16:54.000Z | 2020-12-13T22:16:54.000Z | // Copyright (C) 2018-2022 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include "activation_inst.h"
#include "primitive_type_base.h"
#include "intel_gpu/runtime/error_handler.hpp"
#include "json_object.h"
#include <string>
#include <vector>
namespace cldnn {
primitive_type_id activation::type_id() {
static primitive_type_base<activation> instance;
return &instance;
}
layout activation_inst::calc_output_layout(activation_node const& node) {
assert(static_cast<bool>(node.get_primitive()->output_data_type) == false &&
"Output data type forcing is not supported for activation_node!");
auto input_node_layout = node.input().get_non_padded_output_layout();
auto func = node.get_primitive()->activation_function;
std::vector<activation_func> activations_int8 = {
activation_func::none,
activation_func::negative,
activation_func::negation,
activation_func::relu,
activation_func::floor,
activation_func::clamp };
if (input_node_layout.data_type == data_types::i8 || input_node_layout.data_type == data_types::i32) {
if (std::find(activations_int8.begin(), activations_int8.end(), func) == activations_int8.end())
CLDNN_ERROR_MESSAGE(node.id(), "Requested activation is not supported for integer type.");
}
if (node.has_fused_primitives()) {
input_node_layout.data_type = node.get_fused_output_layout().data_type;
}
return input_node_layout;
}
std::string activation_inst::to_string(activation_node const& node) {
auto node_info = node.desc_to_json();
auto desc = node.get_primitive();
std::stringstream primitive_description;
json_composite activation_info;
activation_info.add("activation_func", static_cast<int>(desc->activation_function));
activation_info.add("additional_params.a", desc->additional_params.a);
activation_info.add("additional_params.b", desc->additional_params.b);
activation_info.add("additional_params input", desc->additional_params_input);
node_info->add("activation info", activation_info);
node_info->dump(primitive_description);
return primitive_description.str();
}
activation_inst::typed_primitive_inst(network& network, activation_node const& node) : parent(network, node) {
auto input_arg = node.input().get_output_layout();
auto output_arg = node.get_output_layout();
CLDNN_ERROR_NOT_EQUAL(node.id(),
"ReLU input number",
input_arg.size.raw.size(),
"ReLU output number",
output_arg.size.raw.size(),
"Relu input/output num dismatch");
if (is_parameterized()) {
/// Slope input x dimension should be equal to input feature size (one slope per channel).
auto slope_layout = node.slope_input().get_output_layout();
auto slope_input_size = slope_layout.size;
auto input_feature_size = slope_layout.size.feature[0];
CLDNN_ERROR_LESS_THAN(node.id(),
"Slope x size",
slope_input_size.feature[0],
"input feature size",
input_feature_size,
"Dimensions mismatch between input and slope input in Activation layer(slope x size "
"should be equal to input feature size)!");
// All other dimensions should be 1
CLDNN_ERROR_NOT_EQUAL(node.id(),
"Slope input size count",
slope_input_size.count(),
"Slope input size x",
slope_input_size.feature[0],
"Dimensions mismatch of slope input in Activation layer!");
}
}
} // namespace cldnn
| 39.744898 | 115 | 0.643646 | [
"vector"
] |
c849281a659e011082973e06f31ebbeccff920b0 | 656 | hpp | C++ | willow/include/popart/transforms/transform.hpp | gglin001/popart | 3225214343f6d98550b6620e809a3544e8bcbfc6 | [
"MIT"
] | 61 | 2020-07-06T17:11:46.000Z | 2022-03-12T14:42:51.000Z | willow/include/popart/transforms/transform.hpp | gglin001/popart | 3225214343f6d98550b6620e809a3544e8bcbfc6 | [
"MIT"
] | 1 | 2021-02-25T01:30:29.000Z | 2021-11-09T11:13:14.000Z | willow/include/popart/transforms/transform.hpp | gglin001/popart | 3225214343f6d98550b6620e809a3544e8bcbfc6 | [
"MIT"
] | 6 | 2020-07-15T12:33:13.000Z | 2021-11-07T06:55:00.000Z | // Copyright (c) 2018 Graphcore Ltd. All rights reserved.
#ifndef GUARD_NEURALNET_TRANSFORM_HPP
#define GUARD_NEURALNET_TRANSFORM_HPP
#include <string>
#include <typeinfo>
namespace popart {
class Graph;
class Transform {
public:
Transform() {}
virtual ~Transform() {}
virtual bool apply(Graph &graph) const = 0;
virtual std::size_t getId() const = 0;
virtual std::string getName() const = 0;
// apply a transformation to the given Ir
static void applyTransform(std::size_t transformId, Graph &);
// add a transform to the list of transforms
static bool registerTransform(Transform *transform);
};
} // namespace popart
#endif
| 19.878788 | 63 | 0.730183 | [
"transform"
] |
c849cde42231d3483124f834270208424ed95ed7 | 63,466 | cpp | C++ | Source/RendererDX11.cpp | zgpxgame/hieroglyph3 | bb1c59d82a69062bb76431b691fbcb381930768a | [
"MIT"
] | 25 | 2017-08-05T07:29:00.000Z | 2022-02-02T06:28:27.000Z | Source/RendererDX11.cpp | zgpxgame/hieroglyph3 | bb1c59d82a69062bb76431b691fbcb381930768a | [
"MIT"
] | null | null | null | Source/RendererDX11.cpp | zgpxgame/hieroglyph3 | bb1c59d82a69062bb76431b691fbcb381930768a | [
"MIT"
] | 9 | 2018-07-14T08:40:29.000Z | 2021-03-19T08:51:30.000Z | //--------------------------------------------------------------------------------
// This file is a portion of the Hieroglyph 3 Rendering Engine. It is distributed
// under the MIT License, available in the root of this distribution and
// at the following URL:
//
// http://www.opensource.org/licenses/mit-license.php
//
// Copyright (c) Jason Zink
//--------------------------------------------------------------------------------
//--------------------------------------------------------------------------------
#include "PCH.h"
#include "RendererDX11.h"
#include "Log.h"
#include "VertexBufferDX11.h"
#include "IndexBufferDX11.h"
#include "ConstantBufferDX11.h"
#include "StructuredBufferDX11.h"
#include "ByteAddressBufferDX11.h"
#include "IndirectArgsBufferDX11.h"
#include "Texture1dDX11.h"
#include "Texture2dDX11.h"
#include "Texture3dDX11.h"
#include "ResourceDX11.h"
#include "SwapChainDX11.h"
#include "ViewPortDX11.h"
#include "BufferConfigDX11.h"
#include "Texture1dConfigDX11.h"
#include "Texture2dConfigDX11.h"
#include "Texture3dConfigDX11.h"
#include "SwapChainConfigDX11.h"
#include "ShaderResourceViewDX11.h"
#include "RenderTargetViewDX11.h"
#include "DepthStencilViewDX11.h"
#include "UnorderedAccessViewDX11.h"
#include "BlendStateConfigDX11.h"
#include "DepthStencilStateConfigDX11.h"
#include "RasterizerStateConfigDX11.h"
#include "VertexShaderDX11.h"
#include "HullShaderDX11.h"
#include "DomainShaderDX11.h"
#include "GeometryShaderDX11.h"
#include "PixelShaderDX11.h"
#include "ComputeShaderDX11.h"
#include "ShaderFactoryDX11.h"
#include "ShaderReflectionDX11.h"
#include "ShaderReflectionFactoryDX11.h"
#include "VectorParameterDX11.h"
#include "MatrixParameterDX11.h"
#include "MatrixArrayParameterDX11.h"
#include "ShaderResourceParameterDX11.h"
#include "UnorderedAccessParameterDX11.h"
#include "ConstantBufferParameterDX11.h"
#include "SamplerParameterDX11.h"
#include "RenderEffectDX11.h"
#include "GeometryDX11.h"
#include "CommandListDX11.h"
#include "DXGIAdapter.h"
#include "DXGIOutput.h"
#include "ParameterManagerDX11.h"
#include "PipelineManagerDX11.h"
#include "Task.h"
#include "EventManager.h"
#include "EvtErrorMessage.h"
#include "FileSystem.h"
#include "Process.h"
#include "D3DEnumConversion.h"
#include "WICTextureLoader.h"
#include "DDSTextureLoader.h"
// Library imports
#pragma comment( lib, "d3d11.lib" )
#pragma comment( lib, "DXGI.lib" )
using Microsoft::WRL::ComPtr;
//--------------------------------------------------------------------------------
using namespace Glyph3;
//--------------------------------------------------------------------------------
RendererDX11* RendererDX11::m_spRenderer = 0;
//--------------------------------------------------------------------------------
RendererDX11::RendererDX11()
{
if ( m_spRenderer == 0 )
m_spRenderer = this;
// m_pDevice = 0;
// m_pDebugger = 0;
m_driverType = D3D_DRIVER_TYPE_NULL;
m_pParamMgr = 0;
pImmPipeline = 0;
// Initialize this to always use MT!
MultiThreadingConfig.SetConfiguration( true );
MultiThreadingConfig.ApplyConfiguration();
m_FeatureLevel = D3D_FEATURE_LEVEL_9_1; // Initialize this to only support 9.1...
}
//--------------------------------------------------------------------------------
RendererDX11::~RendererDX11()
{
}
//--------------------------------------------------------------------------------
RendererDX11* RendererDX11::Get()
{
return( m_spRenderer );
}
//--------------------------------------------------------------------------------
D3D_FEATURE_LEVEL RendererDX11::GetAvailableFeatureLevel( D3D_DRIVER_TYPE DriverType )
{
D3D_FEATURE_LEVEL FeatureLevel;
HRESULT hr;
// If the device has already been created, simply return the feature level.
// Otherwise perform a test with null inputs to get the returned feature level
// without creating the device. The application can then do whatever it needs
// to for a given feature level.
if ( m_pDevice ) {
FeatureLevel = m_pDevice->GetFeatureLevel();
} else {
hr = D3D11CreateDevice(
nullptr,
DriverType,
nullptr,
0,
nullptr,
0,
D3D11_SDK_VERSION,
nullptr,
&FeatureLevel,
nullptr );
if ( FAILED( hr ) ) {
Log::Get().Write( L"Failed to determine the available hardware feature level!" );
}
}
return( FeatureLevel );
}
//--------------------------------------------------------------------------------
D3D_FEATURE_LEVEL RendererDX11::GetCurrentFeatureLevel()
{
return( m_FeatureLevel );
}
//--------------------------------------------------------------------------------
UINT64 RendererDX11::GetAvailableVideoMemory()
{
// Acquire the DXGI device, then the adapter.
// TODO: This method needs to be capable of checking on multiple adapters!
ComPtr<IDXGIDevice> pDXGIDevice;
ComPtr<IDXGIAdapter> pDXGIAdapter;
HRESULT hr = m_pDevice.CopyTo( pDXGIDevice.GetAddressOf() );
pDXGIDevice->GetAdapter( pDXGIAdapter.GetAddressOf() );
// Use the adapter interface to get its description. Then grab the available
// video memory based on if there is dedicated or shared memory for the GPU.
DXGI_ADAPTER_DESC AdapterDesc;
pDXGIAdapter->GetDesc( &AdapterDesc );
UINT64 availableVideoMem = 0;
if ( AdapterDesc.DedicatedVideoMemory )
availableVideoMem = AdapterDesc.DedicatedVideoMemory;
else
availableVideoMem = AdapterDesc.SharedSystemMemory;
return( availableVideoMem );
}
//--------------------------------------------------------------------------------
bool RendererDX11::Initialize( D3D_DRIVER_TYPE DriverType, D3D_FEATURE_LEVEL FeatureLevel )
{
HRESULT hr = S_OK;
// Create a factory to enumerate all of the hardware in the system.
ComPtr<IDXGIFactory1> pFactory;
hr = CreateDXGIFactory1( __uuidof(IDXGIFactory), reinterpret_cast<void**>( pFactory.GetAddressOf() ) );
// Enumerate all of the adapters in the current system. This includes all
// adapters, even the ones that don't support the ID3D11Device interface.
ComPtr<IDXGIAdapter1> pCurrentAdapter;
std::vector<DXGIAdapter> vAdapters;
while( pFactory->EnumAdapters1( static_cast<UINT>(vAdapters.size()), pCurrentAdapter.ReleaseAndGetAddressOf() ) != DXGI_ERROR_NOT_FOUND )
{
vAdapters.push_back( pCurrentAdapter );
DXGI_ADAPTER_DESC1 desc;
pCurrentAdapter->GetDesc1( &desc );
Log::Get().Write( desc.Description );
}
// Specify debug
UINT CreateDeviceFlags = 0;
#ifdef _DEBUG
CreateDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG;
#endif
DeviceContextComPtr pContext;
D3D_FEATURE_LEVEL level[] = { FeatureLevel };
D3D_FEATURE_LEVEL CreatedLevel;
// If we are trying to get a hardware device, then loop through all available
// adapters until we successfully create it. This is useful for multi-adapter
// systems, where the built in GPU may or may not be capable of the most recent
// feature levels.
//
// If it isn't a hardware device, then we simply use nullptr for the adapter with
// the appropriate driver type. See the following page for more details on device
// creation: http://msdn.microsoft.com/en-us/library/windows/desktop/ff476082%28v=vs.85%29.aspx
if ( DriverType == D3D_DRIVER_TYPE_HARDWARE )
{
for ( auto pAdapter : vAdapters )
{
hr = D3D11CreateDevice(
pAdapter.m_pAdapter.Get(),
D3D_DRIVER_TYPE_UNKNOWN,
nullptr,
CreateDeviceFlags,
level,
1,
D3D11_SDK_VERSION,
m_pDevice.GetAddressOf(),
&CreatedLevel,
pContext.GetAddressOf() );
if (hr == S_OK)
break;
}
}
else
{
hr = D3D11CreateDevice(
nullptr,
DriverType,
nullptr,
CreateDeviceFlags,
level,
1,
D3D11_SDK_VERSION,
m_pDevice.GetAddressOf(),
&CreatedLevel,
pContext.GetAddressOf() );
}
if( FAILED( hr ) )
return false;
// Get the debugger interface from the device.
hr = m_pDevice.CopyTo( m_pDebugger.GetAddressOf() );
if ( FAILED( hr ) )
{
Log::Get().Write( L"Unable to acquire the ID3D11Debug interface from the device!" );
}
// Grab a copy of the feature level for use by the rest of the rendering system.
m_FeatureLevel = m_pDevice->GetFeatureLevel();
// Create the renderer components here, including the parameter manager,
// pipeline manager, and resource manager.
m_pParamMgr = new ParameterManagerDX11( 0 );
pImmPipeline = new PipelineManagerDX11();
pImmPipeline->SetDeviceContext( pContext, m_FeatureLevel );
// Rasterizer State (RS) - the first state will be index zero, so no need
// to keep a copy of it here.
RasterizerStateConfigDX11 RasterizerState;
pImmPipeline->RasterizerStage.DesiredState.RasterizerState.SetState( CreateRasterizerState( &RasterizerState ) );
// Depth Stencil State (DS) - the first state will be index zero, so no need
// to keep a copy of it here.
DepthStencilStateConfigDX11 DepthStencilState;
pImmPipeline->OutputMergerStage.DesiredState.DepthStencilState.SetState( CreateDepthStencilState( &DepthStencilState ) );
// Output Merger State (OM) - the first state will be index zero, so no need
// to keep a copy of it here.
BlendStateConfigDX11 BlendState;
pImmPipeline->OutputMergerStage.DesiredState.BlendState.SetState( CreateBlendState( &BlendState ) );
// Create the default resource views for each category. This has the effect
// of allowing the '0' index to be the default state.
m_vShaderResourceViews.emplace_back( ShaderResourceViewComPtr() );
m_vUnorderedAccessViews.emplace_back( UnorderedAccessViewComPtr() );
m_vRenderTargetViews.emplace_back( RenderTargetViewComPtr() );
m_vDepthStencilViews.emplace_back( DepthStencilViewComPtr() );
// Create a query object to be used to gather statistics on the pipeline.
D3D11_QUERY_DESC queryDesc;
queryDesc.Query = D3D11_QUERY_PIPELINE_STATISTICS;
queryDesc.MiscFlags = 0;
for( int i = 0; i < PipelineManagerDX11::NumQueries; ++i)
{
hr = m_pDevice->CreateQuery( &queryDesc, &pImmPipeline->m_Queries[i] );
if ( FAILED( hr ) )
{
Log::Get().Write( L"Unable to create a query object!" );
Shutdown();
return( false );
}
}
D3D11_FEATURE_DATA_D3D10_X_HARDWARE_OPTIONS Options;
m_pDevice->CheckFeatureSupport(D3D11_FEATURE_D3D10_X_HARDWARE_OPTIONS, &Options, sizeof(Options));
if ( Options.ComputeShaders_Plus_RawAndStructuredBuffers_Via_Shader_4_x )
Log::Get().Write( L"Device supports compute shaders plus raw and structured buffers via shader 4.x" );
D3D11_FEATURE_DATA_THREADING ThreadingOptions;
m_pDevice->CheckFeatureSupport( D3D11_FEATURE_THREADING, &ThreadingOptions, sizeof( ThreadingOptions ) );
// TODO: Enumerate all of the formats and quality levels available for the given format.
// It may be beneficial to allow this query from the user instead of enumerating
// all possible formats...
UINT NumQuality;
HRESULT hr1 = m_pDevice->CheckMultisampleQualityLevels( DXGI_FORMAT_R8G8B8A8_UNORM, 4, &NumQuality );
// Initialize the multithreading portion of the renderer. This includes
// creating the threads themselves, initializing the thread payloads as well.
for ( int i = 0; i < NUM_THREADS; i++ )
{
// Mark each payload so that the thread knows which synchronization primitives to use.
g_aPayload[i].id = i;
// Create a deferred context for each thread's pipeline.
DeviceContextComPtr pDeferred;
m_pDevice->CreateDeferredContext( 0, pDeferred.GetAddressOf() );
// Create the pipeline and set the context.
g_aPayload[i].pPipeline = new PipelineManagerDX11();
g_aPayload[i].pPipeline->SetDeviceContext( pDeferred, m_FeatureLevel );
g_aPayload[i].pPipeline->RasterizerStage.DesiredState.RasterizerState.SetState( 0 );
g_aPayload[i].pPipeline->OutputMergerStage.DesiredState.DepthStencilState.SetState( 0 );
g_aPayload[i].pPipeline->OutputMergerStage.DesiredState.BlendState.SetState( 0 );
// Create the command list.
g_aPayload[i].pList = new CommandListDX11();
// Generate a new parameter manager for each thread.
g_aPayload[i].pParamManager = new ParameterManagerDX11( i+1 );
g_aPayload[i].pParamManager->AttachParent( m_pParamMgr );
// Initialize the payload data variables.
g_aPayload[i].bComplete = true;
g_aPayload[i].pTask = nullptr;
// Create the threads in a suspended state.
g_aThreadHandles[i] = 0;
g_aThreadHandles[i] = (HANDLE)_beginthreadex( 0, 0xfffff, _TaskThreadProc, &g_aPayload[i], CREATE_SUSPENDED, 0 );
// Create the synchronization events.
g_aBeginEventHandle[i] = CreateEvent( 0, FALSE, FALSE, 0 );
g_aEndEventHandle[i] = CreateEvent( 0, FALSE, FALSE, 0 );
// Start the thread up now that it has a synch object to use.
ResumeThread( g_aThreadHandles[i] );
}
return( true );
}
//--------------------------------------------------------------------------------
void RendererDX11::Shutdown()
{
// Print some details about the renderer's status at shutdown.
LogObjectPtrVector<ShaderDX11*>( m_vShaders );
// Shutdown all of the threads
for ( int i = 0; i < NUM_THREADS; i++ )
{
g_aPayload[i].bComplete = true;
g_aPayload[i].pTask = nullptr;
SAFE_DELETE( g_aPayload[i].pParamManager );
SAFE_DELETE( g_aPayload[i].pPipeline );
SAFE_DELETE( g_aPayload[i].pList );
CloseHandle( g_aThreadHandles[i] );
CloseHandle( g_aBeginEventHandle[i] );
CloseHandle( g_aEndEventHandle[i] );
}
SAFE_DELETE( m_pParamMgr );
SAFE_DELETE( pImmPipeline );
// Since these are all managed with smart pointers, we just empty the
// container and the objects will automatically be deleted.
m_BlendStates.clear();
m_DepthStencilStates.clear();
m_RasterizerStates.clear();
m_vSamplerStates.clear();
m_vInputLayouts.clear();
m_vViewPorts.clear();
for ( auto pShader : m_vShaders )
delete pShader;
m_vShaderResourceViews.clear();
m_vRenderTargetViews.clear();
m_vDepthStencilViews.clear();
m_vUnorderedAccessViews.clear();
for ( auto pResource : m_vResources )
delete pResource;
for ( auto pSwapChain : m_vSwapChains ) {
if ( pSwapChain->m_pSwapChain != nullptr ) {
pSwapChain->m_pSwapChain->SetFullscreenState( false, NULL );
}
delete pSwapChain;
}
// Clear the context and the device
//SAFE_RELEASE( m_pDevice );
//SAFE_RELEASE( m_pDebugger );
}
//--------------------------------------------------------------------------------
void RendererDX11::Present(HWND hWnd, int SwapChain, UINT SyncInterval, UINT PresentFlags )
{
// Present to the window
unsigned int index = static_cast<unsigned int>( SwapChain );
if ( index < m_vSwapChains.size() ) {
SwapChainDX11* pSwapChain = m_vSwapChains[SwapChain];
HRESULT hr = pSwapChain->m_pSwapChain->Present( SyncInterval, PresentFlags );
}
else {
Log::Get().Write( L"Tried to present an invalid swap chain index!" );
}
}
//--------------------------------------------------------------------------------
int RendererDX11::CreateSwapChain( SwapChainConfigDX11* pConfig )
{
// Attempt to create the DXGI Factory.
ComPtr<IDXGIDevice> pDXGIDevice;
HRESULT hr = m_pDevice.CopyTo( pDXGIDevice.GetAddressOf() );
ComPtr<IDXGIAdapter> pDXGIAdapter;
hr = pDXGIDevice->GetParent(__uuidof(IDXGIAdapter), reinterpret_cast<void **>( pDXGIAdapter.GetAddressOf() ) );
ComPtr<IDXGIFactory> pFactory;
pDXGIAdapter->GetParent(__uuidof(IDXGIFactory), reinterpret_cast<void **>( pFactory.GetAddressOf() ) );
// Attempt to create the swap chain.
ComPtr<IDXGISwapChain> pSwapChain;
hr = pFactory->CreateSwapChain( m_pDevice.Get(), &pConfig->m_State, pSwapChain.GetAddressOf() );
// Release the factory regardless of pass or fail.
if ( FAILED( hr ) )
{
Log::Get().Write( L"Failed to create swap chain!" );
return( -1 );
}
// Acquire the texture interface from the swap chain.
Texture2DComPtr pSwapChainBuffer;
hr = pSwapChain->GetBuffer( 0, __uuidof( ID3D11Texture2D ), reinterpret_cast< void** >( pSwapChainBuffer.GetAddressOf() ) );
if ( FAILED( hr ) )
{
Log::Get().Write( L"Failed to get swap chain texture resource!" );
return( -1 );
}
// Add the swap chain's back buffer texture and render target views to the internal data
// structures to allow setting them later on.
int ResourceID = StoreNewResource( new Texture2dDX11( pSwapChainBuffer ) );
// If we get here, then we succeeded in creating our swap chain and it's constituent parts.
// Now we create the wrapper object and store the result in our container.
Texture2dConfigDX11 TextureConfig;
pSwapChainBuffer->GetDesc( &TextureConfig.m_State );
ResourcePtr Proxy( new ResourceProxyDX11( ResourceID, &TextureConfig, this ) );
// With the resource proxy created, create the swap chain wrapper and store it.
// The resource proxy can then be used later on by the application to get the
// RTV or texture ID if needed.
m_vSwapChains.push_back( new SwapChainDX11( pSwapChain, Proxy ) );
return( m_vSwapChains.size() - 1 );
}
//--------------------------------------------------------------------------------
ResourcePtr RendererDX11::CreateVertexBuffer( BufferConfigDX11* pConfig, D3D11_SUBRESOURCE_DATA* pData )
{
// Create the buffer with the specified configuration.
BufferComPtr pBuffer;
HRESULT hr = m_pDevice->CreateBuffer( &pConfig->m_State, pData, pBuffer.GetAddressOf() );
if ( pBuffer )
{
VertexBufferDX11* pVertexBuffer = new VertexBufferDX11( pBuffer );
pVertexBuffer->SetDesiredDescription( pConfig->m_State );
// Return an index with the lower 16 bits of index, and the upper
// 16 bits to identify the resource type.
int ResourceID = StoreNewResource( pVertexBuffer );
ResourcePtr Proxy( new ResourceProxyDX11( ResourceID, pConfig, this ) );
return( Proxy );
}
return( ResourcePtr( new ResourceProxyDX11() ) );
}
//--------------------------------------------------------------------------------
ResourcePtr RendererDX11::CreateIndexBuffer( BufferConfigDX11* pConfig, D3D11_SUBRESOURCE_DATA* pData )
{
// Create the buffer with the specified configuration.
BufferComPtr pBuffer;
HRESULT hr = m_pDevice->CreateBuffer( &pConfig->m_State, pData, pBuffer.GetAddressOf() );
if ( pBuffer )
{
IndexBufferDX11* pIndexBuffer = new IndexBufferDX11( pBuffer );
pIndexBuffer->SetDesiredDescription( pConfig->m_State );
// Return an index with the lower 16 bits of index, and the upper
// 16 bits to identify the resource type.
int ResourceID = StoreNewResource( pIndexBuffer );
ResourcePtr Proxy( new ResourceProxyDX11( ResourceID, pConfig, this ) );
return( Proxy );
}
return( ResourcePtr( new ResourceProxyDX11() ) );
}
//--------------------------------------------------------------------------------
ResourcePtr RendererDX11::CreateStructuredBuffer( BufferConfigDX11* pConfig, D3D11_SUBRESOURCE_DATA* pData )
{
// Create the buffer with the specified configuration.
BufferComPtr pBuffer;
HRESULT hr = m_pDevice->CreateBuffer( &pConfig->m_State, pData, pBuffer.GetAddressOf() );
if ( pBuffer )
{
StructuredBufferDX11* pStructuredBuffer = new StructuredBufferDX11( pBuffer );
pStructuredBuffer->SetDesiredDescription( pConfig->m_State );
// Return an index with the lower 16 bits of index, and the upper
// 16 bits to identify the resource type.
int ResourceID = StoreNewResource( pStructuredBuffer );
ResourcePtr Proxy( new ResourceProxyDX11( ResourceID, pConfig, this ) );
return( Proxy );
}
return( ResourcePtr( new ResourceProxyDX11() ) );
}
//--------------------------------------------------------------------------------
ResourcePtr RendererDX11::CreateByteAddressBuffer( BufferConfigDX11* pConfig, D3D11_SUBRESOURCE_DATA* pData )
{
// Create the buffer with the specified configuration.
BufferComPtr pBuffer;
HRESULT hr = m_pDevice->CreateBuffer( &pConfig->m_State, pData, pBuffer.GetAddressOf() );
if ( pBuffer )
{
ByteAddressBufferDX11* pByteAddressBuffer = new ByteAddressBufferDX11( pBuffer );
pByteAddressBuffer->SetDesiredDescription( pConfig->m_State );
// Return an index with the lower 16 bits of index, and the upper
// 16 bits to identify the resource type.
int ResourceID = StoreNewResource( pByteAddressBuffer );
ResourcePtr Proxy( new ResourceProxyDX11( ResourceID, pConfig, this ) );
return( Proxy );
}
return( ResourcePtr( new ResourceProxyDX11() ) );
}
//--------------------------------------------------------------------------------
ResourcePtr RendererDX11::CreateIndirectArgsBuffer( BufferConfigDX11* pConfig, D3D11_SUBRESOURCE_DATA* pData )
{
// Create the buffer with the specified configuration.
BufferComPtr pBuffer;
HRESULT hr = m_pDevice->CreateBuffer( &pConfig->m_State, pData, pBuffer.GetAddressOf() );
if ( pBuffer )
{
IndirectArgsBufferDX11* pIndirectArgsBuffer = new IndirectArgsBufferDX11( pBuffer );
pIndirectArgsBuffer->SetDesiredDescription( pConfig->m_State );
// Return an index with the lower 16 bits of index, and the upper
// 16 bits to identify the resource type.
int ResourceID = StoreNewResource( pIndirectArgsBuffer );
ResourcePtr Proxy( new ResourceProxyDX11( ResourceID, pConfig, this ) );
return( Proxy );
}
return( ResourcePtr( new ResourceProxyDX11() ) );
}
//--------------------------------------------------------------------------------
ResourcePtr RendererDX11::CreateConstantBuffer( BufferConfigDX11* pConfig, D3D11_SUBRESOURCE_DATA* pData, bool bAutoUpdate )
{
// Set the constant buffer flag in addition to any other flags that
// the user has set.
BufferComPtr pBuffer;
HRESULT hr = m_pDevice->CreateBuffer( &pConfig->m_State, pData, pBuffer.GetAddressOf() );
if ( pBuffer )
{
ConstantBufferDX11* pConstantBuffer = new ConstantBufferDX11( pBuffer );
pConstantBuffer->SetDesiredDescription( pConfig->m_State );
pConstantBuffer->SetAutoUpdate( bAutoUpdate );
// Return an index with the lower 16 bits of index, and the upper
// 16 bits to identify the resource type.
int ResourceID = StoreNewResource( pConstantBuffer );
ResourcePtr Proxy( new ResourceProxyDX11( ResourceID, pConfig, this ) );
return( Proxy );
}
return( ResourcePtr( new ResourceProxyDX11() ) );
}
//--------------------------------------------------------------------------------
ResourcePtr RendererDX11::CreateTexture1D( Texture1dConfigDX11* pConfig, D3D11_SUBRESOURCE_DATA* pData,
ShaderResourceViewConfigDX11* pSRVConfig,
RenderTargetViewConfigDX11* pRTVConfig,
UnorderedAccessViewConfigDX11* pUAVConfig )
{
Texture1DComPtr pTexture;
HRESULT hr = m_pDevice->CreateTexture1D( &pConfig->m_State, pData, pTexture.GetAddressOf() );
if ( pTexture )
{
Texture1dDX11* pTex = new Texture1dDX11( pTexture );
pTex->SetDesiredDescription( pConfig->GetTextureDesc() );
// Return an index with the lower 16 bits of index, and the upper
// 16 bits to identify the resource type.
int ResourceID = StoreNewResource( pTex );
ResourcePtr Proxy( new ResourceProxyDX11( ResourceID, pConfig, this, pSRVConfig, pRTVConfig, pUAVConfig ) );
return( Proxy );
}
return( ResourcePtr( new ResourceProxyDX11() ) );
}
//--------------------------------------------------------------------------------
ResourcePtr RendererDX11::CreateTexture2D( Texture2dConfigDX11* pConfig, D3D11_SUBRESOURCE_DATA* pData,
ShaderResourceViewConfigDX11* pSRVConfig,
RenderTargetViewConfigDX11* pRTVConfig,
UnorderedAccessViewConfigDX11* pUAVConfig,
DepthStencilViewConfigDX11* pDSVConfig )
{
Texture2DComPtr pTexture;
HRESULT hr = m_pDevice->CreateTexture2D( &pConfig->m_State, pData, pTexture.GetAddressOf() );
if ( pTexture )
{
Texture2dDX11* pTex = new Texture2dDX11( pTexture );
pTex->SetDesiredDescription( pConfig->GetTextureDesc() );
// Return an index with the lower 16 bits of index, and the upper
// 16 bits to identify the resource type.
int ResourceID = StoreNewResource( pTex );
ResourcePtr Proxy( new ResourceProxyDX11( ResourceID, pConfig, this, pSRVConfig, pRTVConfig, pUAVConfig, pDSVConfig ) );
return( Proxy );
}
return( ResourcePtr( new ResourceProxyDX11() ) );
}
//--------------------------------------------------------------------------------
ResourcePtr RendererDX11::CreateTexture3D( Texture3dConfigDX11* pConfig, D3D11_SUBRESOURCE_DATA* pData,
ShaderResourceViewConfigDX11* pSRVConfig,
RenderTargetViewConfigDX11* pRTVConfig,
UnorderedAccessViewConfigDX11* pUAVConfig )
{
Texture3DComPtr pTexture;
HRESULT hr = m_pDevice->CreateTexture3D( &pConfig->m_State, pData, pTexture.GetAddressOf() );
if ( pTexture )
{
Texture3dDX11* pTex = new Texture3dDX11( pTexture );
pTex->SetDesiredDescription( pConfig->GetTextureDesc() );
// Return an index with the lower 16 bits of index, and the upper
// 16 bits to identify the resource type.
int ResourceID = StoreNewResource( pTex );
ResourcePtr Proxy( new ResourceProxyDX11( ResourceID, pConfig, this, pSRVConfig, pRTVConfig, pUAVConfig ) );
return( Proxy );
}
return( ResourcePtr( new ResourceProxyDX11() ) );
}
//--------------------------------------------------------------------------------
int RendererDX11::CreateShaderResourceView( int ResourceID, D3D11_SHADER_RESOURCE_VIEW_DESC* pDesc )
{
ID3D11Resource* pRawResource = 0;
ResourceDX11* pResource = GetResourceByIndex( ResourceID );
if ( pResource ) {
pRawResource = pResource->GetResource();
if ( pRawResource ) {
ShaderResourceViewComPtr pView;
HRESULT hr = m_pDevice->CreateShaderResourceView( pRawResource, pDesc, pView.GetAddressOf() );
if ( pView ) {
m_vShaderResourceViews.push_back( pView );
return( m_vShaderResourceViews.size() - 1 );
}
}
}
return( -1 );
}
//--------------------------------------------------------------------------------
int RendererDX11::CreateRenderTargetView( int ResourceID, D3D11_RENDER_TARGET_VIEW_DESC* pDesc )
{
ID3D11Resource* pRawResource = 0;
ResourceDX11* pResource = GetResourceByIndex( ResourceID );
if ( pResource ) {
pRawResource = pResource->GetResource();
if ( pRawResource ) {
RenderTargetViewComPtr pView;
HRESULT hr = m_pDevice->CreateRenderTargetView( pRawResource, pDesc, pView.GetAddressOf() );
if ( pView ) {
m_vRenderTargetViews.push_back( pView );
return( m_vRenderTargetViews.size() - 1 );
}
}
}
return( -1 );
}
//--------------------------------------------------------------------------------
int RendererDX11::CreateDepthStencilView( int ResourceID, D3D11_DEPTH_STENCIL_VIEW_DESC* pDesc )
{
ID3D11Resource* pRawResource = 0;
ResourceDX11* pResource = GetResourceByIndex( ResourceID );
if ( pResource ) {
pRawResource = pResource->GetResource();
if ( pRawResource ) {
DepthStencilViewComPtr pView;
HRESULT hr = m_pDevice->CreateDepthStencilView( pRawResource, pDesc, pView.GetAddressOf() );
if ( pView ) {
m_vDepthStencilViews.push_back( pView );
return( m_vDepthStencilViews.size() - 1 );
}
}
}
return( -1 );
}
//--------------------------------------------------------------------------------
int RendererDX11::CreateUnorderedAccessView( int ResourceID, D3D11_UNORDERED_ACCESS_VIEW_DESC* pDesc )
{
ID3D11Resource* pRawResource = 0;
ResourceDX11* pResource = GetResourceByIndex( ResourceID );
if ( pResource ) {
pRawResource = pResource->GetResource();
if ( pRawResource ) {
UnorderedAccessViewComPtr pView;
HRESULT hr = m_pDevice->CreateUnorderedAccessView( pRawResource, pDesc, pView.GetAddressOf() );
if ( pView ) {
m_vUnorderedAccessViews.push_back( pView );
return( m_vUnorderedAccessViews.size() - 1 );
}
}
}
return( -1 );
}
//--------------------------------------------------------------------------------
void RendererDX11::ResizeTexture( ResourcePtr texture, UINT width, UINT height )
{
// For the texture, and then for each associated resource view create the new
// sized versions. Afterwards, release the old versions and replace them with
// the new ones.
int rid = texture->m_iResource;
// Grab the old texture description and update it for the new size.
Texture2dDX11* pTexture = GetTexture2DByIndex( rid );
D3D11_TEXTURE2D_DESC TexDesc = pTexture->GetActualDescription();
TexDesc.Width = width;
TexDesc.Height = height;
// Release the old texture, and replace it with the new one.
if ( FAILED( m_pDevice->CreateTexture2D( &TexDesc, 0, pTexture->m_pTexture.ReleaseAndGetAddressOf() ) ) ) {
Log::Get().Write( L"Error trying to resize texture..." );
}
// Update the description of the texture for future reference.
pTexture->m_ActualDesc = TexDesc;
pTexture->m_DesiredDesc = TexDesc;
texture->m_pTexture2dConfig->m_State = TexDesc;
// Resize each of the resource views, if required.
ResizeTextureSRV( rid, texture->m_iResourceSRV, width, height );
ResizeTextureRTV( rid, texture->m_iResourceRTV, width, height );
ResizeTextureDSV( rid, texture->m_iResourceDSV, width, height );
ResizeTextureUAV( rid, texture->m_iResourceUAV, width, height );
}
//--------------------------------------------------------------------------------
void RendererDX11::ResizeTextureSRV( int RID, int SRVID, UINT width, UINT height )
{
// Check to make sure we are supposed to do anything...
if ( SRVID == 0 ) {
return;
}
ResourceDX11* pResource = GetResourceByIndex( RID );
// Check that the input resources / views are legit.
unsigned int index = static_cast<unsigned int>( SRVID );
if ( !pResource || !( index < m_vShaderResourceViews.size() ) || (pResource->GetType() != RT_TEXTURE2D ) ) {
Log::Get().Write( L"Error trying to resize a SRV!!!!" );
return;
}
// Get the existing UAV.
ShaderResourceViewDX11& SRV = m_vShaderResourceViews[index];
// Get its description.
D3D11_SHADER_RESOURCE_VIEW_DESC SRVDesc;
SRV.m_pShaderResourceView->GetDesc( &SRVDesc );
// Create the new one.
if ( FAILED( m_pDevice->CreateShaderResourceView(
pResource->GetResource(),
&SRVDesc,
SRV.m_pShaderResourceView.ReleaseAndGetAddressOf() ) ) )
{
Log::Get().Write( L"Error trying to resize a SRV!!!!" );
}
}
//--------------------------------------------------------------------------------
void RendererDX11::ResizeTextureRTV( int RID, int RTVID, UINT width, UINT height )
{
// Check to make sure we are supposed to do anything...
if ( RTVID == 0 ) {
return;
}
ResourceDX11* pResource = GetResourceByIndex( RID );
// Check that the input resources / views are legit.
unsigned int index = static_cast<unsigned int>( RTVID );
if ( !pResource || !( index < m_vRenderTargetViews.size() ) || (pResource->GetType() != RT_TEXTURE2D ) ) {
Log::Get().Write( L"Error trying to resize a RTV!!!!" );
return;
}
// Get the existing UAV.
RenderTargetViewDX11& RTV = m_vRenderTargetViews[index];
// Get its description.
D3D11_RENDER_TARGET_VIEW_DESC RTVDesc;
RTV.m_pRenderTargetView->GetDesc( &RTVDesc );
// Create the new one.
if ( FAILED( m_pDevice->CreateRenderTargetView(
pResource->GetResource(),
&RTVDesc,
RTV.m_pRenderTargetView.ReleaseAndGetAddressOf() ) ) )
{
Log::Get().Write( L"Error trying to resize a RTV!!!!" );
}
}
//--------------------------------------------------------------------------------
void RendererDX11::ResizeTextureDSV( int RID, int DSVID, UINT width, UINT height )
{
// Check to make sure we are supposed to do anything...
if ( DSVID == 0 ) {
return;
}
ResourceDX11* pResource = GetResourceByIndex( RID );
// Check that the input resources / views are legit.
unsigned int index = static_cast<unsigned int>( DSVID );
if ( !pResource || !( index < m_vDepthStencilViews.size() ) || (pResource->GetType() != RT_TEXTURE2D ) ) {
Log::Get().Write( L"Error trying to resize a DSV!!!!" );
return;
}
// Get the existing UAV.
DepthStencilViewDX11& DSV = m_vDepthStencilViews[index];
// Get its description.
D3D11_DEPTH_STENCIL_VIEW_DESC DSVDesc;
DSV.m_pDepthStencilView->GetDesc( &DSVDesc );
// Create the new one.
if ( FAILED( m_pDevice->CreateDepthStencilView(
pResource->GetResource(),
&DSVDesc,
DSV.m_pDepthStencilView.ReleaseAndGetAddressOf() ) ) )
{
Log::Get().Write( L"Error trying to resize a DSV!!!!" );
}
}
//--------------------------------------------------------------------------------
void RendererDX11::ResizeTextureUAV( int RID, int UAVID, UINT width, UINT height )
{
// Check to make sure we are supposed to do anything...
if ( UAVID == 0 ) {
return;
}
ResourceDX11* pResource = GetResourceByIndex( RID );
// Check that the input resources / views are legit.
unsigned int index = static_cast<unsigned int>( UAVID );
if ( !pResource || !( index < m_vUnorderedAccessViews.size() ) || (pResource->GetType() != RT_TEXTURE2D ) ) {
Log::Get().Write( L"Error trying to resize a UAV!!!!" );
return;
}
// Get the existing UAV.
UnorderedAccessViewDX11& UAV = m_vUnorderedAccessViews[index];
// Get its description.
D3D11_UNORDERED_ACCESS_VIEW_DESC UAVDesc;
UAV.m_pUnorderedAccessView->GetDesc( &UAVDesc );
// Create the new one.
if ( FAILED( m_pDevice->CreateUnorderedAccessView(
pResource->GetResource(),
&UAVDesc,
UAV.m_pUnorderedAccessView.ReleaseAndGetAddressOf() ) ) )
{
Log::Get().Write( L"Error trying to resize a UAV!!!!" );
}
}
//--------------------------------------------------------------------------------
void RendererDX11::ResizeSwapChain( int SID, UINT width, UINT height )
{
unsigned int index = static_cast<unsigned int>( SID );
if ( !( index < m_vSwapChains.size() ) ) {
Log::Get().Write( L"Error trying to resize swap chain!" );
return;
}
// In order to resize a swap chain, you first have to release all outstanding
// references to it. In our case, this means to release the texture and
// render target view that we maintain in the renderer.
SwapChainDX11* pSwapChain = m_vSwapChains[index];
Texture2dDX11* pBackBuffer = GetTexture2DByIndex( pSwapChain->m_Resource->m_iResource );
pBackBuffer->m_pTexture.Reset();
RenderTargetViewDX11& RTV = m_vRenderTargetViews[pSwapChain->m_Resource->m_iResourceRTV];
// Get its description.
DXGI_SWAP_CHAIN_DESC SwapDesc;
pSwapChain->GetSwapChain()->GetDesc( &SwapDesc );
D3D11_RENDER_TARGET_VIEW_DESC RTVDesc;
RTV.m_pRenderTargetView->GetDesc( &RTVDesc );
RTV.m_pRenderTargetView.Reset();
this->pImmPipeline->ClearPipelineState();
for ( int i = 0; i < NUM_THREADS; i++ ) {
g_aPayload[i].pPipeline->ClearPipelineState();
}
// Resize the buffers.
HRESULT hr = pSwapChain->m_pSwapChain->ResizeBuffers( 2, width, height, SwapDesc.BufferDesc.Format, SwapDesc.Flags );
if ( FAILED(hr) ) {
Log::Get().Write( L"Failed to resize buffers!" );
}
// Re-acquire the back buffer reference.
hr = pSwapChain->m_pSwapChain->GetBuffer( 0, __uuidof( ID3D11Texture2D ),
reinterpret_cast< void** >( pBackBuffer->m_pTexture.GetAddressOf() ) );
// Create the new one.
hr = m_pDevice->CreateRenderTargetView( pBackBuffer->m_pTexture.Get(), &RTVDesc, RTV.m_pRenderTargetView.GetAddressOf() );
}
//--------------------------------------------------------------------------------
void RendererDX11::ResizeViewport( int ID, UINT width, UINT height )
{
unsigned int index = static_cast<unsigned int>( ID );
if ( !( index < m_vViewPorts.size() ) ) {
Log::Get().Write( L"Error trying to resize viewport!" );
}
ViewPortDX11& pViewport = m_vViewPorts[index];
pViewport.m_ViewPort.Width = static_cast<float>( width );
pViewport.m_ViewPort.Height = static_cast<float>( height );
}
//--------------------------------------------------------------------------------
int RendererDX11::LoadShader( ShaderType type, std::wstring& filename, std::wstring& function,
std::wstring& model, bool enablelogging )
{
return LoadShader( type, filename, function, model, NULL, enablelogging );
}
//--------------------------------------------------------------------------------
int RendererDX11::LoadShader( ShaderType type, std::wstring& filename, std::wstring& function,
std::wstring& model, const D3D_SHADER_MACRO* pDefines, bool enablelogging )
{
// Check the existing list of shader files to see if there are any matches
// before trying to load it up again. This will reduce the load times,
// and should speed up rendering in many cases since the shader object won't
// have to be bound again.
//
// In the case that there are any defines passed in, we skip returning the
// cached shader - we assume that something is different about the shader due
// to the defines, so we can't just reuse a previously loaded one.
for ( unsigned int i = 0; i < m_vShaders.size(); i++ )
{
ShaderDX11* pShader = m_vShaders[i];
if ( pShader->FileName.compare( filename ) == 0
&& pShader->Function.compare( function ) == 0
&& pShader->ShaderModel.compare( model ) == 0
&& pDefines == nullptr )
{
return( i );
}
}
HRESULT hr = S_OK;
ID3DBlob* pCompiledShader = NULL;
pCompiledShader = ShaderFactoryDX11::GenerateShader( type, filename, function, model, pDefines, enablelogging );
//pCompiledShader = ShaderFactoryDX11::GeneratePrecompiledShader( filename, function, model );
if ( pCompiledShader == nullptr ) {
return( -1 );
}
// Create the shader wrapper to house all of the information about its interface.
ShaderDX11* pShaderWrapper = 0;
switch( type )
{
case VERTEX_SHADER:
{
ID3D11VertexShader* pShader = 0;
hr = m_pDevice->CreateVertexShader(
pCompiledShader->GetBufferPointer(),
pCompiledShader->GetBufferSize(),
0, &pShader );
pShaderWrapper = new VertexShaderDX11( pShader );
break;
}
case HULL_SHADER:
{
ID3D11HullShader* pShader = 0;
hr = m_pDevice->CreateHullShader(
pCompiledShader->GetBufferPointer(),
pCompiledShader->GetBufferSize(),
0, &pShader );
pShaderWrapper = new HullShaderDX11( pShader );
break;
}
case DOMAIN_SHADER:
{
ID3D11DomainShader* pShader = 0;
hr = m_pDevice->CreateDomainShader(
pCompiledShader->GetBufferPointer(),
pCompiledShader->GetBufferSize(),
0, &pShader );
pShaderWrapper = new DomainShaderDX11( pShader );
break;
}
case GEOMETRY_SHADER:
{
ID3D11GeometryShader* pShader = 0;
hr = m_pDevice->CreateGeometryShader(
pCompiledShader->GetBufferPointer(),
pCompiledShader->GetBufferSize(),
0, &pShader );
pShaderWrapper = new GeometryShaderDX11( pShader );
break;
}
case PIXEL_SHADER:
{
ID3D11PixelShader* pShader = 0;
hr = m_pDevice->CreatePixelShader(
pCompiledShader->GetBufferPointer(),
pCompiledShader->GetBufferSize(),
0, &pShader );
pShaderWrapper = new PixelShaderDX11( pShader );
break;
}
case COMPUTE_SHADER:
{
ID3D11ComputeShader* pShader = 0;
hr = m_pDevice->CreateComputeShader(
pCompiledShader->GetBufferPointer(),
pCompiledShader->GetBufferSize(),
0, &pShader );
pShaderWrapper = new ComputeShaderDX11( pShader );
break;
}
}
if ( FAILED( hr ) )
{
Log::Get().Write( L"Failed to create shader!" );
pCompiledShader->Release();
delete pShaderWrapper;
return( -1 );
}
pShaderWrapper->FileName = filename;
pShaderWrapper->Function = function;
pShaderWrapper->ShaderModel = model;
m_vShaders.push_back( pShaderWrapper );
// Store the compiled shader in the shader wrapper for use later on in creating
// and checking input and output signatures.
pShaderWrapper->m_pCompiledShader = pCompiledShader;
ShaderReflectionDX11* pReflection = ShaderReflectionFactoryDX11::GenerateReflection( *pShaderWrapper );
// Initialize the constant buffers of this shader, so that they aren't
// lazy created later on...
pReflection->InitializeConstantBuffers( m_pParamMgr );
pShaderWrapper->SetReflection( pReflection );
//pReflection->PrintShaderDetails();
// Return the index for future referencing.
return( m_vShaders.size() - 1 );
}
//--------------------------------------------------------------------------------
int RendererDX11::CreateInputLayout( std::vector<D3D11_INPUT_ELEMENT_DESC>& elements, int ShaderID )
{
// Create array of elements here for the API call.
D3D11_INPUT_ELEMENT_DESC* pElements = new D3D11_INPUT_ELEMENT_DESC[elements.size()];
for ( unsigned int i = 0; i < elements.size(); i++ )
pElements[i] = elements[i];
// Attempt to create the input layout from the input information.
ID3DBlob* pCompiledShader = m_vShaders[ShaderID]->m_pCompiledShader;
InputLayoutComPtr pLayout;
HRESULT hr = m_pDevice->CreateInputLayout( pElements, elements.size(),
pCompiledShader->GetBufferPointer(), pCompiledShader->GetBufferSize(), pLayout.GetAddressOf() );
// Release the input elements array.
delete[] pElements;
// On failure, log the error and return an invalid index.
if ( FAILED( hr ) )
{
Log::Get().Write( L"Failed to create input layout!" );
return( -1 );
}
m_vInputLayouts.push_back( pLayout );
// Return the index for referencing later on.
return( m_vInputLayouts.size() - 1 );
}
//--------------------------------------------------------------------------------
ResourcePtr RendererDX11::LoadTexture( std::wstring filename, bool sRGB )
{
ComPtr<ID3D11Resource> pResource;
FileSystem fs;
filename = fs.GetTextureFolder() + filename;
// Test whether this is a DDS file or not.
std::wstring extension = filename.substr( filename.size()-3, 3 );
std::transform( extension.begin(), extension.end(), extension.begin(), ::tolower );
HRESULT hr = S_OK;
if ( extension == L"dds" )
{
hr = DirectX::CreateDDSTextureFromFile(
m_pDevice.Get(),
filename.c_str(),
//0,
//D3D11_USAGE_DEFAULT,
//D3D11_BIND_SHADER_RESOURCE,
//0,
//0,
//sRGB,
pResource.GetAddressOf(),
nullptr );
}
else
{
hr = DirectX::CreateWICTextureFromFileEx(
m_pDevice.Get(),
pImmPipeline->m_pContext.Get(),
filename.c_str(),
0,
D3D11_USAGE_DEFAULT,
D3D11_BIND_SHADER_RESOURCE,
0,
0,
sRGB,
pResource.GetAddressOf(),
0 );
}
if ( FAILED( hr ) )
{
Log::Get().Write( L"Failed to load texture from file: " + filename );
return( ResourcePtr( new ResourceProxyDX11() ) );
}
ComPtr<ID3D11Texture2D> pTexture;
pResource.CopyTo( pTexture.GetAddressOf() );
int ResourceID = StoreNewResource( new Texture2dDX11( pTexture ) );
Texture2dConfigDX11 TextureConfig;
pTexture->GetDesc( &TextureConfig.m_State );
return( ResourcePtr( new ResourceProxyDX11( ResourceID, &TextureConfig, this ) ) );
}
//--------------------------------------------------------------------------------
ResourcePtr RendererDX11::LoadTexture( void* pData, SIZE_T sizeInBytes/*, D3DX11_IMAGE_LOAD_INFO* pLoadInfo*/ )
{
ComPtr<ID3D11Resource> pResource;
HRESULT hr = DirectX::CreateWICTextureFromMemory(
m_pDevice.Get(),
pImmPipeline->m_pContext.Get(),
static_cast<uint8_t*>(pData),
sizeInBytes,
pResource.GetAddressOf(),
0 );
if ( FAILED( hr ) )
{
Log::Get().Write( L"Failed to load texture from memory!" );
return( ResourcePtr( new ResourceProxyDX11() ) );
}
ComPtr<ID3D11Texture2D> pTexture;
pResource.CopyTo( pTexture.GetAddressOf() );
int ResourceID = StoreNewResource( new Texture2dDX11( pTexture ) );
Texture2dConfigDX11 TextureConfig;
pTexture->GetDesc( &TextureConfig.m_State );
return( ResourcePtr( new ResourceProxyDX11( ResourceID, &TextureConfig, this ) ) );
}
//--------------------------------------------------------------------------------
ResourcePtr RendererDX11::LoadTexture( ID3D11Texture2D* pTexture )
{
// Add a reference to the texture to ensure it doesn't get destroyed while we
// are using it.
// TODO: This method has to be double checked to ensure that the reference
// counting functions properly with the externally created texture!
ComPtr<ID3D11Texture2D> pTexturePtr( pTexture );
int ResourceID = StoreNewResource( new Texture2dDX11( pTexture ) );
Texture2dConfigDX11 TextureConfig;
pTexture->GetDesc( &TextureConfig.m_State );
return( ResourcePtr( new ResourceProxyDX11( ResourceID, &TextureConfig, this ) ) );
}
//--------------------------------------------------------------------------------
int RendererDX11::CreateBlendState( BlendStateConfigDX11* pConfig )
{
// If this state has already been created before, just return the index.
auto entry = m_BlendStateLookup.find( *pConfig );
if ( entry != m_BlendStateLookup.end() ) {
return entry->second;
}
// If it hasn't been created before, create it, then store it, and return it.
BlendStateComPtr pState;
HRESULT hr = m_pDevice->CreateBlendState( dynamic_cast<D3D11_BLEND_DESC*>( pConfig ), pState.GetAddressOf() );
if ( FAILED( hr ) )
{
Log::Get().Write( L"Failed to create blend state!" );
return( -1 );
}
m_BlendStates.push_back( pState );
int id = m_BlendStates.size() - 1;
m_BlendStateLookup[*pConfig] = id;
return id;
}
//--------------------------------------------------------------------------------
int RendererDX11::CreateDepthStencilState( DepthStencilStateConfigDX11* pConfig )
{
// If this state has already been created before, just return the index.
auto entry = m_DepthStencilStateLookup.find( *pConfig );
if ( entry != m_DepthStencilStateLookup.end() ) {
return entry->second;
}
// If it hasn't been created before, create it, then store it, and return it.
DepthStencilStateComPtr pState;
HRESULT hr = m_pDevice->CreateDepthStencilState( dynamic_cast<D3D11_DEPTH_STENCIL_DESC*>( pConfig ), pState.GetAddressOf() );
if ( FAILED( hr ) )
{
Log::Get().Write( L"Failed to create depth stencil state!" );
return( -1 );
}
m_DepthStencilStates.push_back( pState );
int id = m_DepthStencilStates.size() - 1;
m_DepthStencilStateLookup[*pConfig] = id;
return id;
}
//--------------------------------------------------------------------------------
int RendererDX11::CreateRasterizerState( RasterizerStateConfigDX11* pConfig )
{
// If this state has already been created before, just return the index.
auto entry = m_RasterizerStateLookup.find( *pConfig );
if ( entry != m_RasterizerStateLookup.end() ) {
return entry->second;
}
// If it hasn't been created before, create it, then store it, and return it.
RasterizerStateComPtr pState;
HRESULT hr = m_pDevice->CreateRasterizerState( dynamic_cast<D3D11_RASTERIZER_DESC*>( pConfig ), pState.GetAddressOf() );
if ( FAILED( hr ) )
{
Log::Get().Write( L"Failed to create rasterizer state!" );
return( -1 );
}
m_RasterizerStates.push_back( pState );
int id = m_RasterizerStates.size() - 1;
m_RasterizerStateLookup[*pConfig] = id;
return id;
}
//--------------------------------------------------------------------------------
int RendererDX11::CreateSamplerState( D3D11_SAMPLER_DESC* pDesc )
{
SamplerStateComPtr pState;
HRESULT hr = m_pDevice->CreateSamplerState( pDesc, pState.GetAddressOf() );
if ( FAILED( hr ) )
{
Log::Get().Write( L"Failed to create sampler state!" );
return( -1 );
}
m_vSamplerStates.push_back( pState );
return( m_vSamplerStates.size() - 1 );
}
//--------------------------------------------------------------------------------
int RendererDX11::CreateViewPort( D3D11_VIEWPORT viewport )
{
m_vViewPorts.emplace_back( viewport );
return( m_vViewPorts.size() - 1 );
}
//--------------------------------------------------------------------------------
ResourcePtr RendererDX11::GetSwapChainResource( int ID )
{
unsigned int index = static_cast<unsigned int>( ID );
if ( index < m_vSwapChains.size() )
return( m_vSwapChains[index]->m_Resource );
Log::Get().Write( L"Tried to get an invalid swap buffer index texture ID!" );
return( ResourcePtr( new ResourceProxyDX11() ) );
}
//--------------------------------------------------------------------------------
Vector2f RendererDX11::GetDesktopResolution()
{
// Acquire the DXGI device, then the adapter, then the output...
ComPtr<IDXGIDevice> pDXGIDevice;
HRESULT hr = m_pDevice.CopyTo( pDXGIDevice.GetAddressOf() );
ComPtr<IDXGIAdapter> pDXGIAdapter;
hr = pDXGIDevice->GetParent(__uuidof(IDXGIAdapter), reinterpret_cast<void **>( pDXGIAdapter.GetAddressOf() ) );
// Take the first output in the adapter.
ComPtr<IDXGIOutput> pDXGIOutput;
pDXGIAdapter->EnumOutputs( 0, pDXGIOutput.GetAddressOf() );
// Use the output interface to get the output description.
DXGI_OUTPUT_DESC desc;
pDXGIOutput->GetDesc( &desc );
// Return the current output's resolution from the description.
return( Vector2f( static_cast<float>( desc.DesktopCoordinates.right - desc.DesktopCoordinates.left ),
static_cast<float>( desc.DesktopCoordinates.bottom - desc.DesktopCoordinates.top ) ) );
}
//--------------------------------------------------------------------------------
BlendStateComPtr RendererDX11::GetBlendState( int index )
{
// TODO: There should be a default blend state that can be returned which will
// put the blend state into the default D3D11 state...
if ( index >= 0 )
return( m_BlendStates[index] );
else
return( m_BlendStates[0] );
}
//--------------------------------------------------------------------------------
DepthStencilStateComPtr RendererDX11::GetDepthState( int index )
{
// TODO: There should be a default blend state that can be returned which will
// put the blend state into the default D3D11 state...
if ( index >= 0 )
return( m_DepthStencilStates[index] );
else
return( m_DepthStencilStates[0] );
}
//--------------------------------------------------------------------------------
RasterizerStateComPtr RendererDX11::GetRasterizerState( int index )
{
// TODO: There should be a default blend state that can be returned which will
// put the blend state into the default D3D11 state...
if ( index >= 0 )
return( m_RasterizerStates[index] );
else
return( m_RasterizerStates[0] );
}
//--------------------------------------------------------------------------------
const ViewPortDX11& RendererDX11::GetViewPort( int ID )
{
unsigned int index = static_cast<unsigned int>( ID );
assert( index < m_vViewPorts.size() );
return( m_vViewPorts[index] );
}
//--------------------------------------------------------------------------------
ResourceDX11* RendererDX11::GetResourceByIndex( int ID )
{
ResourceDX11* pResource = 0;
unsigned int index = ID & 0xffff;
int innerID = ( ID & 0xffff0000 ) >> 16;
if ( index < m_vResources.size() ) {
pResource = m_vResources[index];
if ( pResource->GetInnerID() != innerID ) {
Log::Get().Write( L"Inner ID doesn't match resource index!!!" );
}
}
return( pResource );
}
//--------------------------------------------------------------------------------
InputLayoutComPtr RendererDX11::GetInputLayout( int index )
{
return( m_vInputLayouts[index] );
}
//--------------------------------------------------------------------------------
SamplerStateComPtr RendererDX11::GetSamplerState( int index )
{
return( m_vSamplerStates[index] );
}
//--------------------------------------------------------------------------------
ShaderDX11* RendererDX11::GetShader( int ID )
{
unsigned int index = static_cast<unsigned int>( ID );
if ( index < m_vShaders.size() )
return( m_vShaders[index] );
else
return( nullptr );
}
//--------------------------------------------------------------------------------
void RendererDX11::QueueTask( Task* pTask )
{
m_vQueuedTasks.push_back( pTask );
}
//--------------------------------------------------------------------------------
void RendererDX11::ProcessTaskQueue( )
{
MultiThreadingConfig.ApplyConfiguration();
if ( MultiThreadingConfig.GetConfiguration() == false )
{
// Single-threaded processing of the render view queue
for ( int i = m_vQueuedTasks.size()-1; i >= 0; i-=NUM_THREADS )
{
for ( int j = 0; j < NUM_THREADS; j++ )
{
if ( (i-j) >= 0 )
{
//
pImmPipeline->BeginEvent( std::wstring( L"View Draw: ") + m_vQueuedTasks[i-j]->GetName() );
m_vQueuedTasks[i-j]->ExecuteTask( pImmPipeline, g_aPayload[j].pParamManager );
pImmPipeline->EndEvent();
//PIXEndEvent();
}
}
}
m_vQueuedTasks.clear();
}
else
{
// Multi-threaded processing of the render view queue
for ( int i = m_vQueuedTasks.size()-1; i >= 0; i-=NUM_THREADS )
{
DWORD count = 0;
for ( int j = 0; j < NUM_THREADS; j++ )
{
if ( (i-j) >= 0 )
{
count++;
g_aPayload[j].pTask = m_vQueuedTasks[i-j];
SetEvent( g_aBeginEventHandle[j] );
}
}
WaitForMultipleObjects( count, g_aEndEventHandle, true, INFINITE );
for ( int j = 0; count > 0; count-- )
{
pImmPipeline->ExecuteCommandList( g_aPayload[j].pList );
g_aPayload[j].pList->ReleaseList();
j++;
}
}
m_vQueuedTasks.clear();
}
}
//--------------------------------------------------------------------------------
//--------------------------------------------------------------------------------
// Here is the render view process for each thread. The intention here is to
// have a thread perform a single render view's rendering commands to generate
// a command list. This list is later used by the immediate context to execute
// the list.
//--------------------------------------------------------------------------------
HANDLE g_aThreadHandles[NUM_THREADS];
Glyph3::ThreadPayLoad g_aPayload[NUM_THREADS];
HANDLE g_aBeginEventHandle[NUM_THREADS];
HANDLE g_aEndEventHandle[NUM_THREADS];
unsigned int WINAPI _TaskThreadProc( void* lpParameter )
{
ThreadPayLoad* pPayload = (ThreadPayLoad*) lpParameter;
int id = pPayload->id;
for ( ; ; )
{
// Wait for the main thread to signal that there is a payload available.
WaitForSingleObject( g_aBeginEventHandle[id], INFINITE );
pPayload->pPipeline->m_pContext->ClearState();
// Execute the render view with the provided pipeline and parameter managers.
pPayload->pTask->ExecuteTask( pPayload->pPipeline, pPayload->pParamManager );
// Generate the command list.
pPayload->pPipeline->GenerateCommandList( pPayload->pList );
// Signal to the main thread that the view has been collected into a command list.
SetEvent( g_aEndEventHandle[id] );
}
return( 0 );
}
//--------------------------------------------------------------------------------
Texture1dDX11* RendererDX11::GetTexture1DByIndex( int rid )
{
Texture1dDX11* pResult = 0;
ResourceDX11* pResource = GetResourceByIndex(rid);
if ( pResource != NULL ) {
if ( pResource->GetType() != RT_TEXTURE1D ) {
Log::Get().Write( L"Trying to access a non-texture1D resource!!!!" );
} else {
pResult = reinterpret_cast<Texture1dDX11*>( pResource );
}
}
return( pResult );
}
//--------------------------------------------------------------------------------
Texture2dDX11* RendererDX11::GetTexture2DByIndex( int rid )
{
Texture2dDX11* pResult = 0;
ResourceDX11* pResource = GetResourceByIndex(rid);
if ( pResource != NULL ) {
if ( pResource->GetType() != RT_TEXTURE2D ) {
Log::Get().Write( L"Trying to access a non-texture2D resource!!!!" );
} else {
pResult = reinterpret_cast<Texture2dDX11*>( pResource );
}
}
return( pResult );
}
//--------------------------------------------------------------------------------
Texture3dDX11* RendererDX11::GetTexture3DByIndex( int rid )
{
Texture3dDX11* pResult = 0;
ResourceDX11* pResource = GetResourceByIndex(rid);
if ( pResource != NULL ) {
if ( pResource->GetType() != RT_TEXTURE3D ) {
Log::Get().Write( L"Trying to access a non-texture3D resource!!!!" );
} else {
pResult = reinterpret_cast<Texture3dDX11*>( pResource );
}
}
return( pResult );
}
//--------------------------------------------------------------------------------
SwapChainDX11* RendererDX11::GetSwapChainByIndex( int sid )
{
return( m_vSwapChains[sid] );
}
//--------------------------------------------------------------------------------
BufferDX11* RendererDX11::GetGenericBufferByIndex( int rid )
{
// This method returns a BufferDX11 pointer, which is useful for methods that
// can operate on more than one type of buffer. As long as the underlying
// resource is not a texture, then the pointer is returned, otherwise null
// is returned.
BufferDX11* pResult = 0;
ResourceDX11* pResource = GetResourceByIndex(rid);
if ( pResource != NULL ) {
if ( pResource->GetType() == RT_TEXTURE1D || pResource->GetType() == RT_TEXTURE2D || pResource->GetType() == RT_TEXTURE3D ) {
Log::Get().Write( L"Trying to access a non-buffer resource!!!!" );
} else {
pResult = reinterpret_cast<BufferDX11*>( pResource );
}
}
return( pResult );
}
//--------------------------------------------------------------------------------
ConstantBufferDX11* RendererDX11::GetConstantBufferByIndex( int rid )
{
ConstantBufferDX11* pResult = 0;
ResourceDX11* pResource = GetResourceByIndex(rid);
if ( pResource != NULL ) {
if ( pResource->GetType() != RT_CONSTANTBUFFER ) {
Log::Get().Write( L"Trying to access a non-vertex buffer resource!!!!" );
} else {
pResult = reinterpret_cast<ConstantBufferDX11*>( pResource );
}
}
return( pResult );
}
//--------------------------------------------------------------------------------
VertexBufferDX11* RendererDX11::GetVertexBufferByIndex( int rid )
{
VertexBufferDX11* pResult = 0;
ResourceDX11* pResource = GetResourceByIndex(rid);
if ( pResource != NULL ) {
if ( pResource->GetType() != RT_VERTEXBUFFER ) {
Log::Get().Write( L"Trying to access a non-vertex buffer resource!!!!" );
} else {
pResult = reinterpret_cast<VertexBufferDX11*>( pResource );
}
}
return( pResult );
}
//--------------------------------------------------------------------------------
IndexBufferDX11* RendererDX11::GetIndexBufferByIndex( int rid )
{
IndexBufferDX11* pResult = 0;
ResourceDX11* pResource = GetResourceByIndex(rid);
if ( pResource != NULL ) {
if ( pResource->GetType() != RT_INDEXBUFFER ) {
Log::Get().Write( L"Trying to access a non-index buffer resource!!!!" );
} else {
pResult = reinterpret_cast<IndexBufferDX11*>( pResource );
}
}
return( pResult );
}
//--------------------------------------------------------------------------------
ByteAddressBufferDX11* RendererDX11::GetByteAddressBufferByIndex( int rid )
{
ByteAddressBufferDX11* pResult = 0;
ResourceDX11* pResource = GetResourceByIndex(rid);
if ( pResource != NULL ) {
if ( pResource->GetType() != RT_BYTEADDRESSBUFFER ) {
Log::Get().Write( L"Trying to access a non-byte address buffer resource!!!!" );
} else {
pResult = reinterpret_cast<ByteAddressBufferDX11*>( pResource );
}
}
return( pResult );
}
//--------------------------------------------------------------------------------
IndirectArgsBufferDX11* RendererDX11::GetIndirectArgsBufferByIndex( int rid )
{
IndirectArgsBufferDX11* pResult = 0;
ResourceDX11* pResource = GetResourceByIndex(rid);
if ( pResource != NULL ) {
if ( pResource->GetType() != RT_INDIRECTARGSBUFFER ) {
Log::Get().Write( L"Trying to access a non-indirect args buffer resource!!!!" );
} else {
pResult = reinterpret_cast<IndirectArgsBufferDX11*>( pResource );
}
}
return( pResult );
}
//--------------------------------------------------------------------------------
StructuredBufferDX11* RendererDX11::GetStructuredBufferByIndex( int rid )
{
StructuredBufferDX11* pResult = 0;
ResourceDX11* pResource = GetResourceByIndex(rid);
if ( pResource != NULL ) {
if ( pResource->GetType() != RT_STRUCTUREDBUFFER ) {
Log::Get().Write( L"Trying to access a non-structured buffer resource!!!!" );
} else {
pResult = reinterpret_cast<StructuredBufferDX11*>( pResource );
}
}
return( pResult );
}
//--------------------------------------------------------------------------------
RenderTargetViewDX11& RendererDX11::GetRenderTargetViewByIndex( int rid )
{
assert( rid >= 0 );
assert( rid < m_vRenderTargetViews.size() );
return( m_vRenderTargetViews[rid] );
}
//--------------------------------------------------------------------------------
DepthStencilViewDX11& RendererDX11::GetDepthStencilViewByIndex( int rid )
{
assert( rid >= 0 );
assert( rid < m_vDepthStencilViews.size() );
return( m_vDepthStencilViews[rid] );
}
//--------------------------------------------------------------------------------
ShaderResourceViewDX11& RendererDX11::GetShaderResourceViewByIndex( int rid )
{
assert( rid >= 0 );
assert( rid < m_vShaderResourceViews.size() );
return( m_vShaderResourceViews[rid] );
}
//--------------------------------------------------------------------------------
UnorderedAccessViewDX11& RendererDX11::GetUnorderedAccessViewByIndex( int rid )
{
assert( rid >= 0 );
assert( rid < m_vUnorderedAccessViews.size() );
return( m_vUnorderedAccessViews[rid] );
}
//--------------------------------------------------------------------------------
int RendererDX11::GetUnusedResourceIndex()
{
// Initialize return index to -1.
int index = -1;
// Search for a NULL index location.
for ( unsigned int i = 0; i < m_vResources.size(); i++ ) {
if ( m_vResources[i] == NULL ) {
index = i;
break;
}
}
// Return either an empty location, or -1 if none exist.
return( index );
}
//--------------------------------------------------------------------------------
int RendererDX11::StoreNewResource( ResourceDX11* pResource )
{
// This method either finds an empty spot in the list, or just appends the
// resource to the end of it if none are available.
int index = GetUnusedResourceIndex();
if ( index == -1 ) {
m_vResources.push_back( pResource );
index = m_vResources.size() - 1;
} else {
m_vResources[index] = pResource;
}
// Shift the inner ID to the upper 16 bits.
int innerID = (int)pResource->GetInnerID() << 16;
index = index + innerID;
return( index );
}
//--------------------------------------------------------------------------------
void RendererDX11::DeleteResource( ResourcePtr ptr )
{
// This is a convenience method that just passes the resource index to
// the delete function.
DeleteResource( ptr->m_iResource );
}
//--------------------------------------------------------------------------------
void RendererDX11::DeleteResource( int index )
{
// Here the resource is looked up, then deleted if it was found. After
// being deleted, it is
ResourceDX11* pResource = GetResourceByIndex( index );
if ( pResource != nullptr ) {
delete pResource;
m_vResources[index & 0xffff] = nullptr;
}
}
//--------------------------------------------------------------------------------
ID3D11Device* RendererDX11::GetDevice()
{
return( m_pDevice.Get() );
}
//--------------------------------------------------------------------------------
template <class T>
void LogObjectVector( std::vector<T> objects )
{
for ( auto object : objects )
Log::Get().Write( object.ToString() );
}
//--------------------------------------------------------------------------------
template <class T>
void LogObjectPtrVector( std::vector<T> objects )
{
for ( auto object : objects )
Log::Get().Write( object->ToString() );
}
//--------------------------------------------------------------------------------
| 31.638086 | 138 | 0.63727 | [
"render",
"object",
"vector",
"model",
"transform"
] |
c84add71bc0fc2bd7c4bb6bcdd4fdbfef5eb95af | 11,517 | cpp | C++ | itemwisesales.cpp | bizjust/bizjust-erp | d3291e212bf89ab6e753194127b3951afcd02548 | [
"MIT"
] | 1 | 2022-02-16T13:02:43.000Z | 2022-02-16T13:02:43.000Z | itemwisesales.cpp | bizjust/bizjust-erp | d3291e212bf89ab6e753194127b3951afcd02548 | [
"MIT"
] | null | null | null | itemwisesales.cpp | bizjust/bizjust-erp | d3291e212bf89ab6e753194127b3951afcd02548 | [
"MIT"
] | null | null | null | #include "itemwisesales.h"
#include "ui_itemwisesales.h"
ItemWiseSales::ItemWiseSales(QWidget *parent) :
QWidget(parent),
ui(new Ui::ItemWiseSales)
{
ui->setupUi(this);
timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(loadParams()) );
timer->start(5);
}
ItemWiseSales::~ItemWiseSales()
{
delete ui;
}
void ItemWiseSales::autocompleter(QString sql, QLineEdit *name_txt, QLineEdit *id_txt)
{
sch.name_txt = name_txt;
sch.id_txt = id_txt;
QMap<int, QString> data = sch.data;
QSqlQuery qry;
qry.prepare(sql);
if(qry.exec())
{
while(qry.next())
{
data[qry.value(0).toInt()] = qry.value(1).toString();
}
}
QCompleter *completer = new QCompleter(this);
QStandardItemModel *model = new QStandardItemModel(completer);
QMapIterator<int, QString> it(data);
while (it.hasNext())
{
it.next();
int code = it.key();
QString name = it.value();
QStandardItem *item = new QStandardItem;
item->setText(name);
item->setData(code, Qt::UserRole);
model->appendRow(item);
}
completer->setModel(model);
completer->setCaseSensitivity(Qt::CaseInsensitive);
completer->setCurrentRow(0);
completer->setFilterMode(Qt::MatchContains);
name_txt->setCompleter(completer);
connect(completer, SIGNAL(highlighted(QModelIndex)),this,SLOT(onItemHighlighted(QModelIndex)),Qt::QueuedConnection);
connect(name_txt,SIGNAL(editingFinished()),this,SLOT(editingFinished() ));
}
void ItemWiseSales::onItemHighlighted(const QModelIndex &index)
{
QString code = index.data(Qt::UserRole).toString();
QString sname = index.data(0).toString();
sch.searchname = sname;
sch.searchid = code;
sch.id_txt->setText(code);
}
void ItemWiseSales::editingFinished()
{
QString sname = sch.name_txt->text();
QString sid = sch.id_txt->text();
if(sname!=sch.searchname || sid != sch.searchid)
{
sch.name_txt->setText("");
sch.id_txt->setText("");
}
}
void ItemWiseSales::loadParams()
{
timer->stop();
ui->begindate->setDate( erp.reportBeginDate() );
ui->enddate->setDate( QDate::currentDate() );
}
void ItemWiseSales::on_itemname_textEdited(const QString &arg1)
{
autocompleter(sch.items(arg1),ui->itemname,ui->itemid);
}
void ItemWiseSales::on_btn_next_clicked()
{
this->setCursor(Qt::WaitCursor);
printer=new QPrinter();
printer->setOutputFormat(QPrinter::PdfFormat);
printer->setPaperSize(QPrinter::A4);
printer->setPageMargins(QMarginsF(10,10,10,10));
printDlg=new QPrintDialog(printer);
pageDlg=new QPageSetupDialog(printer);
pd = new QPrintPreviewDialog(printer);
connect(pd,SIGNAL(paintRequested(QPrinter*)),this,SLOT(printPreview(QPrinter*)));
pd->setWindowTitle("Item Wise Sales");
pd->setWindowFlags(Qt::Window);
pd->resize(900,600);
pd->show();
}
void ItemWiseSales::printPreview(QPrinter *p)
{
QString begindate = ui->begindate->date().toString("yyyy-MM-dd");
QString enddate = ui->enddate->date().toString("yyyy-MM-dd");
QString itemid = ui->itemid->text();
/******************************************report detail***********************************************/
html = "";
html += "<table width='100%' border='1' cellspacing='0' cellpadding='3'>"
"<thead><tr bgcolor='#f2f2f2'>"
"<th colspan='8'>From: "+ erp.DDMMYYDateFromSQL(begindate) +" To: "+ erp.DDMMYYDateFromSQL(enddate) +"</th>"
"</tr>";
html +="<tr bgcolor='#f2f2f2'>"
"<th width='10%'>Item Code</th>"
"<th width='30%'>Item Name</th>"
"<th width='10%'>Qty Sold</th>"
"<th width='10%'>Sales (Value)</th>"
"<th width='10%'>Qty Returned</th>"
"<th width='10%'>Sales Return (Value)</th>"
"<th width='10%'>Net Sales</th>"
"<th width='10%'>Avg Price</th>"
"</tr></thead>";
int totalqty=0;
float totalprc=0;
int totalretqty=0;
float totalrettot=0;
float Grandtot=0;
QString query_2="select i.description, i.itemid, i.itemcode, it.ITDate, t.ItemPriceEach, t.Qty as iqty, "
" sum(pcs) as tot_pcs, (t.Qty*t.ItemPriceEach) AS total_ from tblitemtransdet t, tblitems i, "
" tblitemtrans it, tblitemcategory s WHERE i.categoryid=s.id and t.itranstype='si' and "
" t.itransid=it.itransid and t.itranstype=it.itranstype and i.itemid = t.itemid ";
if(itemid!="")
{
query_2 += " and i.itemid='"+itemid+"' ";
}
query_2 += " group by i.itemid order by i.description asc ";
//qDebug()<<query_2<<endl;
QSqlQuery info_2(query_2);
while(info_2.next())
{
QString iid = info_2.value("itemid").toString();
QString iname = info_2.value("description").toString();
QString icode = info_2.value("itemcode").toString();
//QString qtys_packing = erp.checkQty(iid,"si",true,"",begindate,enddate);
int qtys_units = erp.checkQty(iid,"si",false,"",begindate,enddate).toInt();
float amt = erp.checkQtyAmount(iid,"si","",begindate,enddate);
//QString Returnqtys_packing = erp.checkQty(iid,"sr",true,"",begindate,enddate);
int Returnqtys_units = erp.checkQty(iid,"sr",false,"",begindate,enddate).toInt();
float Returnamt = erp.checkQtyAmount(iid,"sr","",begindate,enddate);
int net_sale_units = qtys_units - Returnqtys_units;
float net_sale_amount = amt - Returnamt;
if(amt!=0)
{
float avg = net_sale_amount/net_sale_units;
html+="<tr>"
"<td>"+ icode +"</td>"
"<td>"+ iname +"</td>"
"<td align='center'>"+erp.intString(qtys_units)+"</td>"
"<td align='right'>"+erp.amountString(amt)+"</td>"
"<td align='center'>"+erp.intString(Returnqtys_units)+"</td>"
"<td align='right'>"+erp.amountString(Returnamt)+"</td>"
"<td align='right'>"+erp.amountString(net_sale_amount)+"</td>"
"<td align='right'>"+erp.amountString(avg)+"</td>"
"</tr>";
totalqty = totalqty + qtys_units;
totalprc = totalprc + amt;
totalretqty = totalretqty + Returnqtys_units;
totalrettot = totalrettot + Returnamt;
Grandtot = Grandtot + net_sale_amount;
}
}
html+="<tr>"
"<th align='right' colspan='2'>Totals:</th>"
"<th align='center'>"+erp.amountString(totalqty)+"</th>"
"<th align='right'>"+erp.amountString(totalprc)+"</th>"
"<th align='center'>"+erp.amountString(totalretqty)+"</th>"
"<th align='right'>"+erp.amountString(totalrettot)+"</th>"
"<th align='right'>"+erp.amountString(Grandtot)+"</th>"
"<th></th>"
"</tr>";
html +="</table>";
/******************************************* Header****************************************************/
QString header_html = "<table width='100%'>"
"<tr>"
"<td rowspan='2' width='20%' valign='bottom'>Print Date: "+QDate::currentDate().toString("dd/MM/yyyy")+"</td>"
"<td width='60%' align='center' style='font-size:22px;text-transform:uppercase;'><b>"+erp.companyname()+"</b></td>"
"<td rowspan='2' width='20%' align='right' valign='bottom'></td>"
"</tr>"
"<tr>"
"<th style='font-size:16px;'>Item Wise Sale</th>"
"</tr>"
"<!--<tr><td colspan='3'><hr/></td></tr>-->" "" ""
"</table>";
/******************************************* Settings ****************************************************/
QRect printer_rect(p->pageRect());
//Setting up the header and calculating the header size
QTextDocument *document_header = new QTextDocument(this);
document_header->setPageSize(printer_rect.size());
//int pagenum = document_header->pageCount();
document_header->setHtml(header_html);
QSizeF header_size = document_header->size();
//Setting up the footer and calculating the footer size
QTextDocument *document_footer = new QTextDocument(this);
document_footer->setPageSize(printer_rect.size());
//document_footer->setHtml("");
//QSizeF footer_size = document_footer->size();
//Calculating the main document size for one page
QSizeF center_size(printer_rect.width(), (p->pageRect().height() - header_size.toSize().height() ));//- footer_size.toSize().height()
//Setting up the center page
QTextDocument *main_doc = new QTextDocument(this);
main_doc->setHtml(html);
main_doc->setPageSize(center_size);
//Setting up the rectangles for each section.
QRect pageNo = QRect(700, 40, 100, 50);
QRect headerRect = QRect(QPoint(0,0), document_header->size().toSize());
QRect footerRect = QRect(QPoint(0,0), document_footer->size().toSize());
QRect contentRect = QRect(QPoint(0,0), main_doc->size().toSize()); // Main content rectangle.
QRect currentRect = QRect(QPoint(0,0), center_size.toSize()); // Current main content rectangle.
QPainter painter(p);
pagenum=1;
while (currentRect.intersects(contentRect))
{//Loop if the current content rectangle intersects with the main content rectangle.
//Resetting the painter matrix co ordinate system.
painter.resetMatrix();
//Applying negative translation of painter co-ordinate system by current main content rectangle top y coordinate.
painter.translate(0, -currentRect.y());
//Applying positive translation of painter co-ordinate system by header hight.
painter.translate(0, headerRect.height());
//Drawing the center content for current page.
main_doc->drawContents(&painter, currentRect);
//Resetting the painter matrix co ordinate system.
painter.resetMatrix();
//Drawing the header on the top of the page
document_header->drawContents(&painter, headerRect);
painter.drawText(pageNo,"Page. "+erp.intString(pagenum));
//Applying positive translation of painter co-ordinate system to draw the footer
painter.translate(0, headerRect.height());
painter.translate(0, center_size.height());
document_footer->drawContents(&painter, footerRect);
//Translating the current rectangle to the area to be printed for the next page
currentRect.translate(0, currentRect.height());
//Inserting a new page if there is till area left to be printed
if (currentRect.intersects(contentRect))
{
p->newPage();
pagenum++;
}
}
this->setCursor(Qt::ArrowCursor);
}
| 40.985765 | 265 | 0.566988 | [
"model",
"transform"
] |
c84aeda6d96ca4d84bbc3c4cca79ff94a2914089 | 1,792 | cc | C++ | lib/base/MCategoryHeader.cc | rlalik/mapt2-framework | 8c63c643e38c215ea0e02b6396b229e2391e46c2 | [
"MIT"
] | null | null | null | lib/base/MCategoryHeader.cc | rlalik/mapt2-framework | 8c63c643e38c215ea0e02b6396b229e2391e46c2 | [
"MIT"
] | null | null | null | lib/base/MCategoryHeader.cc | rlalik/mapt2-framework | 8c63c643e38c215ea0e02b6396b229e2391e46c2 | [
"MIT"
] | 1 | 2020-02-20T12:37:41.000Z | 2020-02-20T12:37:41.000Z | // @(#)lib/base:$Id$
// Author: Rafal Lalik 18/11/2017
/*************************************************************************
* Copyright (C) 2017-2018, Rafał Lalik. *
* All rights reserved. *
* *
* For the licensing terms see $MAPTSYS/LICENSE. *
* For the list of contributors see $MAPTSYS/README/CREDITS. *
*************************************************************************/
#include <iostream>
#include <TBuffer.h>
#include <TClass.h>
#include <TClonesArray.h>
#include "MCategoryHeader.h"
void MCategoryHeader::clear()
{
name.Clear();
simulation = kFALSE;
dim = 0;
dim_sizes.Set(0);
dim_offsets.Set(0);
data_size = 0;
writable = kFALSE;
}
void MCategoryHeader::Streamer(TBuffer &R__b)
{
// Stream an object of class HLinearCategory.
Char_t clase[200];
if (R__b.IsReading())
{
TObject::Streamer(R__b);
R__b >> name;
R__b >> simulation;
R__b >> dim;
Int_t a, b;
dim_sizes.Set(dim);
dim_offsets.Set(dim);
for (int i = 0; i < dim; ++i)
{
R__b >> a >> b;
dim_sizes[i] = a;
dim_offsets[i] = b;
}
R__b >> data_size;
R__b >> writable;
} else {
TObject::Streamer(R__b);
R__b << name;
R__b << simulation;
R__b << dim;
Int_t a, b;
for (int i = 0; i < dim; ++i)
{
a = dim_sizes[i];
b = dim_offsets[i];
R__b << a << b;
}
R__b << data_size;
R__b << writable;
}
}
ClassImp(MCategoryHeader);
| 25.6 | 75 | 0.425223 | [
"object"
] |
c84e667fe47097be9264a1a8dddf3c3894587b62 | 11,903 | cpp | C++ | src/Samples/src/samples/materials/shadermaterial/shader_material_pbr_test_scene.cpp | sacceus/BabylonCpp | 94669cf7cbe3214ec6e905cbf249fa0c9daf6222 | [
"Apache-2.0"
] | 277 | 2017-05-18T08:27:10.000Z | 2022-03-26T01:31:37.000Z | src/Samples/src/samples/materials/shadermaterial/shader_material_pbr_test_scene.cpp | sacceus/BabylonCpp | 94669cf7cbe3214ec6e905cbf249fa0c9daf6222 | [
"Apache-2.0"
] | 77 | 2017-09-03T15:35:02.000Z | 2022-03-28T18:47:20.000Z | src/Samples/src/samples/materials/shadermaterial/shader_material_pbr_test_scene.cpp | sacceus/BabylonCpp | 94669cf7cbe3214ec6e905cbf249fa0c9daf6222 | [
"Apache-2.0"
] | 37 | 2017-03-30T03:36:24.000Z | 2022-01-28T08:28:36.000Z | #include <babylon/cameras/free_camera.h>
#include <babylon/engines/engine.h>
#include <babylon/engines/scene.h>
#include <babylon/interfaces/irenderable_scene.h>
#include <babylon/lights/hemispheric_light.h>
#include <babylon/materials/effect.h>
#include <babylon/materials/effect_shaders_store.h>
#include <babylon/materials/shader_material.h>
#include <babylon/meshes/builders/mesh_builder_options.h>
#include <babylon/meshes/mesh.h>
#include <babylon/meshes/mesh_builder.h>
#include <babylon/samples/babylon_register_sample.h>
namespace BABYLON {
namespace Samples {
class ShaderMaterialPbrTestScene : public IRenderableScene {
public:
/** Vertex Shader **/
static constexpr const char* customVertexShader
= R"ShaderCode(
#ifdef GL_ES
precision highp float;
#endif
// Attributes
attribute vec3 position;
attribute vec2 uv;
// Uniforms
uniform mat4 worldViewProjection;
// Varying
varying vec2 vUV;
void main(void) {
gl_Position = worldViewProjection * vec4(position, 1.0);
vUV = uv;
}
)ShaderCode";
/** Pixel (Fragment) Shader **/
// PBR_Test ( https://www.shadertoy.com/view/MlB3DV )
static constexpr const char* customFragmentShader
= R"ShaderCode(
#ifdef GL_ES
precision highp float;
#endif
// Varying
varying vec3 vPosition;
varying vec3 vNormal;
varying vec2 vUV;
// Uniforms
uniform mat4 worldViewProjection;
uniform float iTime;
uniform float iAspectRatio;
uniform vec2 iResolution;
/*
* References :
*
*
http://renderwonk.com/publications/s2010-shading-course/hoffman/
s2010_physically_based_shading_hoffman_b_notes.pdf
*
*
http://www.frostbite.com/wp-content/uploads/2014/11/
course_notes_moving_frostbite_to_pbr.pdf
*
* http://graphicrants.blogspot.fr/2013/08/specular-brdf-reference.html
*
*
http://www.filmicworlds.com/2014/04/21/
optimizing-ggx-shaders-with-dotlh/
*
*
http://blog.selfshadow.com/publications/s2013-shading-course/
#course_content
*
* Ray marching code from iq
*/
#define NB_LIGHTS 3
// Metals values in linear space
#define GOLD vec3(1.0, 0.71, 0.29)
#define COPPER vec3(0.95, 0.64, 0.54)
#define IRON vec3(0.56, 0.57, 0.58)
#define ALUMINIUM vec3(0.91, 0.92, 0.92)
#define SILVER vec3(0.95, 0.93, 0.88)
float fPlane(vec3 p, vec4 n) {
// n must be normalized
return dot(p, n.xyz) + n.w;
}
float fSphere(vec3 p, float s) { return length(p) - s; }
float opS(float d1, float d2) { return max(-d2, d1); }
vec2 opU(vec2 d1, vec2 d2) { return (d1.x < d2.x) ? d1 : d2; }
vec3 opRep(vec3 p, vec3 c) { return mod(p, c) - 0.5 * c; }
// ---- Scene definition
vec2 fScene(vec3 p) {
vec3 pSphere = p /*opRep(p, vec3( 2.0, 0.0, 2.0))*/;
vec2 sphere0 = vec2(fSphere(p, 1.0), 0.5);
vec2 sphere1 = vec2(fSphere(p + vec3(2.1, 0.0, 2.0), 1.0), 2.5);
vec2 sphere2 = vec2(fSphere(p + vec3(-2.1, 0.0, 2.0), 1.0), 3.5);
vec2 sphere3 = vec2(fSphere(p + vec3(2.1, 0.0, -2.0), 1.0), 4.5);
vec2 sphere4 = vec2(fSphere(p + vec3(-2.1, 0.0, -2.0), 1.0), 5.5);
vec2 plane = vec2(fPlane(p, vec4(0, 1, 0, 1.0)), 1.5);
return opU(opU(opU(opU(opU(plane, sphere0), sphere1), sphere2),
sphere3), sphere4);
}
// -----
vec2 castRay(in vec3 ro, in vec3 rd) {
float tmin = 1.0;
float tmax = 100.0;
float precis = 0.00001;
float t = tmin;
float m = -1.0;
for (int i = 0; i < 50; i++) {
vec2 res = fScene(ro + rd * t);
if (res.x < precis || t > tmax)
break;
t += res.x;
m = res.y;
}
if (t > tmax)
m = -1.0;
return vec2(t, m);
}
float softshadow(in vec3 ro, in vec3 rd,
in float mint, in float tmax) {
float res = 1.0;
float t = mint;
for (int i = 0; i < 16; i++) {
float h = fScene(ro + rd * t).x;
res = min(res, 8.0 * h / t);
t += clamp(h, 0.02, 0.10);
if (h < 0.001 || t > tmax)
break;
}
return clamp(res, 0.0, 1.0);
}
vec3 calcNormal(in vec3 pos) {
vec3 eps = vec3(0.001, 0.0, 0.0);
vec3 nor = vec3(fScene(pos + eps.xyy).x - fScene(pos - eps.xyy).x,
fScene(pos + eps.yxy).x - fScene(pos - eps.yxy).x,
fScene(pos + eps.yyx).x - fScene(pos - eps.yyx).x);
return normalize(nor);
}
struct Light {
vec3 pos;
vec3 color;
};
Light lights[NB_LIGHTS];
float G1V(float dotNV, float k) {
return 1.0 / (dotNV * (1.0 - k) + k);
}
vec3 computePBRLighting(in Light light, in vec3 position,
in vec3 N, in vec3 V,
in vec3 albedo, in float roughness,
in vec3 F0) {
float alpha = roughness * roughness;
vec3 L = normalize(light.pos.xyz - position);
vec3 H = normalize(V + L);
float dotNL = clamp(dot(N, L), 0.0, 1.0);
float dotNV = clamp(dot(N, V), 0.0, 1.0);
float dotNH = clamp(dot(N, H), 0.0, 1.0);
float dotLH = clamp(dot(L, H), 0.0, 1.0);
float D, vis;
vec3 F;
// NDF : GGX
float alphaSqr = alpha * alpha;
float pi = 3.1415926535;
float denom = dotNH * dotNH * (alphaSqr - 1.0) + 1.0;
D = alphaSqr / (pi * denom * denom);
// Fresnel (Schlick)
float dotLH5 = pow(1.0 - dotLH, 5.0);
F = F0 + (1.0 - F0) * (dotLH5);
// Visibility term (G) : Smith with Schlick's approximation
float k = alpha / 2.0;
vis = G1V(dotNL, k) * G1V(dotNV, k);
vec3 specular = /*dotNL **/ D * F * vis;
vec3 ambient = vec3(.01);
float invPi = 0.31830988618;
vec3 diffuse = (albedo * invPi);
return ambient + (diffuse + specular) * light.color.xyz * dotNL;
}
vec3 addPBR(in vec3 position, in vec3 N, in vec3 V, in vec3 baseColor,
in float metalMask, in float smoothness,
in float reflectance) {
vec3 color = vec3(0.0);
float roughness = 1.0 - smoothness * smoothness;
vec3 F0 = 0.16 * reflectance * reflectance * (1.0 - metalMask) +
baseColor * metalMask;
vec3 albedo = baseColor;
float s = 0.0;
for (int i = 0; i < NB_LIGHTS; ++i) {
vec3 col =
computePBRLighting(lights[i], position, N, V,
albedo, roughness, F0);
color += col;
s += softshadow(position, normalize(lights[i].pos.xyz - position),
0.02, 2.5);
}
return color * s;
}
vec3 render(in vec3 ro, in vec3 rd) {
vec3 col = vec3(0.8, 0.9, 1.0) * 8.0; // Sky color
vec2 res = castRay(ro, rd);
float t = res.x;
float m = res.y;
vec3 p = ro + t * rd;
if (m > -0.5) { // Intersection found
if (m < 1.0) {
// float f = mod( floor( 5.0*p.z ) + floor( 5.0*p.x ), 2.0 );
vec3 sur = vec3(1.0, 1.0, 1.0) *
smoothstep(-1.0, -0.6, sin(16.0 * p.x));
col = addPBR(p, calcNormal(p), -rd, GOLD * sur, sur.x,
0.3 + 0.6 * sur.x, 0.5);
} else if (m < 2.0) {
float f = mod(floor(5.0 * p.z) + floor(5.0 * p.x), 2.0);
col = addPBR(p, calcNormal(p), -rd, vec3(0.5),
0.0, 0.3 + 0.6 * f, 0.5);
} else if (m < 3.0) {
vec3 sur = vec3(1.0, 1.0, 1.0) * smoothstep(-1.0, -0.4,
sin(18.0 * p.x));
col = addPBR(p, calcNormal(p), -rd, COPPER * sur, sur.x,
0.3 + 0.6 * sur.x, 0.5);
} else if (m < 4.0) {
vec3 sur = vec3(1.0, 1.0, 1.0) *
smoothstep(-1.0, -0.0995, sin(106.0 * p.x)) *
smoothstep(-1.0, -0.9, sin(47.0 * p.z));
col = addPBR(p, calcNormal(p), -rd, vec3(0.2), 1.0 - sur.x,
0.9 * sur.x, 0.5);
} else if (m < 5.0) {
vec3 sur = vec3(1.0) * smoothstep(-1.0, -0.765,
sin(24.0 * p.x)) *
smoothstep(-1.0, -0.4, sin(70.9 * p.z));
col = addPBR(p, calcNormal(p), -rd, GOLD * (1.0 - sur), sur.x,
0.3 + 0.6 * sur.x, 0.5);
} else if (m < 6.0) {
vec3 sur = vec3(1.0, 1.0, 1.0) * smoothstep(-1.0, -0.4,
sin(18.0 * p.x));
col = addPBR(p, calcNormal(p), -rd, ALUMINIUM * sur, sur.x,
0.3 + 0.6 * sur.x, 0.5);
}
}
return col;
}
mat3 setCamera(in vec3 ro, in vec3 ta, float cr) {
vec3 cw = normalize(ta - ro);
vec3 cp = vec3(sin(cr), cos(cr), 0.0);
vec3 cu = normalize(cross(cw, cp));
vec3 cv = normalize(cross(cu, cw));
return mat3(cu, cv, cw);
}
vec4 hejlToneMapping(in vec4 color) {
vec4 x = max(vec4(0.0), color - vec4(0.004));
return (x * ((6.2 * x) + vec4(0.5))) /
max(x * ((6.2 * x) + vec4(1.7)) + vec4(0.06), vec4(1e-8));
}
void main(void) {
float time = 0.25 * iTime;
lights[0] = Light(vec3(0.0, 5.0, .0), vec3(1.0));
lights[1] = Light(vec3(12.0 * sin(iTime), 8.0, 12.0 * cos(iTime)),
vec3(1.0));
lights[2] =
Light(vec3(-12.0 * cos(-iTime), 8.0, 12.0 * sin(-iTime)),
vec3(.05));
vec2 q = vUV.xy;
vec2 p = -1.0 + 2.0 * q;
p.x *= iResolution.x / iResolution.y;
// camera
vec3 ro = vec3(7.0 * sin(time), 7.0, -7.0 * cos(time));
vec3 ta = vec3(0.0);
// camera-to-world transformation
mat3 ca = setCamera(ro, ta, 0.0);
// ray direction
vec3 rd = ca * normalize(vec3(p.xy, 2.5));
// render
vec3 col = render(ro, rd);
#if 0
col = pow( col, vec3(0.4545) );
fragColor=vec4( col, 1.0 );
#else
float exposure = 0.032 + 0.023 * sin(time - 3.14);
gl_FragColor = hejlToneMapping(vec4(col, 1.0) * exposure);
#endif
}
)ShaderCode";
public:
ShaderMaterialPbrTestScene(ICanvas* iCanvas)
: IRenderableScene(iCanvas), _time{0.f}, _shaderMaterial{nullptr}
{
// Vertex shader
Effect::ShadersStore()["customVertexShader"] = customVertexShader;
// Fragment shader
Effect::ShadersStore()["customFragmentShader"] = customFragmentShader;
}
~ShaderMaterialPbrTestScene() override = default;
const char* getName() override
{
return "Shader Material PBR Test Scene";
}
void initializeScene(ICanvas* canvas, Scene* scene) override
{
// Create a FreeCamera, and set its position to (x:0, y:0, z:-8)
auto camera = FreeCamera::New("camera1", Vector3(0.f, 0.f, -8.f), scene);
// Target the camera to scene origin
camera->setTarget(Vector3::Zero());
// Attach the camera to the canvas
camera->attachControl(canvas, true);
// Create a basic light, aiming 0,1,0 - meaning, to the sky
HemisphericLight::New("light1", Vector3(0.f, 1.f, 0.f), scene);
// Create a built-in "box" shape
const float ratio = static_cast<float>(getEngine()->getRenderWidth())
/ static_cast<float>(getEngine()->getRenderHeight());
BoxOptions options;
options.size = 5.f;
options.sideOrientation = Mesh::DEFAULTSIDE;
options.updatable = false;
options.width = *options.size * ratio;
auto skybox = MeshBuilder::CreateBox("skybox", options, scene);
// Create shader material
IShaderMaterialOptions shaderMaterialOptions;
shaderMaterialOptions.attributes = {"position", "uv"};
shaderMaterialOptions.uniforms
= {"iTime", "worldViewProjection", "iAspectRatio", "iResolution"};
_shaderMaterial = ShaderMaterial::New("boxShader", scene, "custom", shaderMaterialOptions);
// box + sky = skybox !
skybox->material = _shaderMaterial;
// Animation
scene->onAfterCameraRenderObservable.add([this](Camera*, EventState&) {
const Vector2 resolution{static_cast<float>(_engine->getRenderWidth()),
static_cast<float>(_engine->getRenderHeight())};
const float aspectRatio = resolution.x / resolution.y;
_shaderMaterial->setFloat("iTime", _time);
_shaderMaterial->setFloat("iAspectRatio", aspectRatio);
_shaderMaterial->setVector2("iResolution", resolution);
_time += 0.01f * getScene()->getAnimationRatio();
});
}
private:
float _time;
ShaderMaterialPtr _shaderMaterial;
}; // end of class ShaderMaterialPBRTestScene
BABYLON_REGISTER_SAMPLE("Shader Material", ShaderMaterialPbrTestScene)
} // end of namespace Samples
} // end of namespace BABYLON | 28.820823 | 95 | 0.594472 | [
"mesh",
"render",
"shape"
] |
c850b9da4ac217edbf7ff090933b635b57d532e3 | 740 | cpp | C++ | segmentedSieve.cpp | akshay31057/Competitive-Programming-Repository | bb4e61df348803795d0bf24c11000b2e02ab8cda | [
"MIT"
] | 1 | 2020-10-09T15:07:36.000Z | 2020-10-09T15:07:36.000Z | segmentedSieve.cpp | akshay31057/Competitive-Programming-Repository | bb4e61df348803795d0bf24c11000b2e02ab8cda | [
"MIT"
] | null | null | null | segmentedSieve.cpp | akshay31057/Competitive-Programming-Repository | bb4e61df348803795d0bf24c11000b2e02ab8cda | [
"MIT"
] | 1 | 2018-10-25T15:07:12.000Z | 2018-10-25T15:07:12.000Z | /**
* Description: Get primes in range [ll, ul].
* Usage: getPrimes. O(NlgN) where N = ul-ll+1
* Source: https://github.com/dragonslayerx
*/
void getPrimes(int ll, int ul, set<int> &largePrimes) {
vector<bool> isprm;
isprm.resize(ul - ll + 1);
for(int i = 0; i < ul - ll + 1; i++) {
isprm[i] = 1;
}
for (int i = 2; i * i <= ul; i++) {
if (isprime[i]) {
int j;
j = ll / i;
for(; i * j <= ul; j++) {
if (i * j >= ll && j > 1) {
isprm[i * j - ll] = 0;
}
}
}
}
for (int i = ll; i <= ul; i++) {
if (isprm[i - ll] && i > 1) {
largePrimes.insert(i);
}
}
} | 25.517241 | 55 | 0.387838 | [
"vector"
] |
c851647e6b48e23c28074ce08d6946115194f4d1 | 1,003 | cpp | C++ | 12015.cpp | felikjunvianto/kfile-uvaoj-submissions | 5bd8b3b413ca8523abe412b0a0545f766f70ce63 | [
"MIT"
] | null | null | null | 12015.cpp | felikjunvianto/kfile-uvaoj-submissions | 5bd8b3b413ca8523abe412b0a0545f766f70ce63 | [
"MIT"
] | null | null | null | 12015.cpp | felikjunvianto/kfile-uvaoj-submissions | 5bd8b3b413ca8523abe412b0a0545f766f70ce63 | [
"MIT"
] | null | null | null | #include <cstdio>
#include <cmath>
#include <iostream>
#include <string>
#include <cstring>
#include <algorithm>
#include <vector>
#include <utility>
#include <stack>
#include <queue>
#include <map>
#define fi first
#define se second
#define pb push_back
#define mp make_pair
#define pi 2*acos(0.0)
#define eps 1e-9
#define PII pair<int,int>
#define PDD pair<double,double>
#define LL long long
#define INF 1000000000
using namespace std;
typedef struct
{
int nilai,urut;
string nama;
} cell;
cell web[20];
int T,x,y,i;
char msk[111];
bool cf(cell i,cell j)
{
if(i.nilai!=j.nilai) return(i.nilai>j.nilai);
return(i.urut<j.urut);
}
int main()
{
scanf("%d",&T);
for(i=1;i<=T;i++)
{
for(x=0;x<10;x++)
{
scanf("%s %d",msk,&y);
web[x]=(cell){y,x,msk};
}
sort(web,web+10,cf);
y=web[0].nilai;
printf("Case #%d:\n",i);
for(x=0;x<10;x++) if(web[x].nilai==y)
printf("%s\n",web[x].nama.c_str());
}
return 0;
}
| 16.177419 | 47 | 0.596211 | [
"vector"
] |
c8570dae48fa196ca8a6c9667ab73d4dc4c18bb7 | 21,200 | cpp | C++ | UtinniCore/swg/scene/world_snapshot.cpp | ModTheGalaxy/Utinni | 6fc118d7d80667a6e12864fc5fffe5782eaacd58 | [
"MIT"
] | 2 | 2021-03-29T20:25:05.000Z | 2021-03-29T20:25:54.000Z | UtinniCore/swg/scene/world_snapshot.cpp | ModTheGalaxy/Utinni | 6fc118d7d80667a6e12864fc5fffe5782eaacd58 | [
"MIT"
] | null | null | null | UtinniCore/swg/scene/world_snapshot.cpp | ModTheGalaxy/Utinni | 6fc118d7d80667a6e12864fc5fffe5782eaacd58 | [
"MIT"
] | null | null | null | /**
* MIT License
*
* Copyright (c) 2020 Philip Klatt
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
**/
#include "world_snapshot.h"
#include <filesystem>
#include "ground_scene.h"
#include "swg/appearance/appearance.h"
#include "swg/misc/network.h"
#include "swg/object/object.h"
#include "swg/object/client_object.h"
#include "swg/game/game.h"
#include "swg/appearance/portal.h"
#include "utility/string_utility.h"
namespace swg::worldSnapshotReaderWriter
{
using pOpenFile = bool(__thiscall*)(utinni::WorldSnapshotReaderWriter* pThis, const char* filename);
using pSaveFile = bool(__thiscall*)(utinni::WorldSnapshotReaderWriter* pThis, const char* filename);
using pClear = void(__thiscall*)(utinni::WorldSnapshotReaderWriter* pThis);
using pGetObjectTemplateName = const char* (__thiscall*)(utinni::WorldSnapshotReaderWriter* pThis, int objectTemplateNameIndex);
using pNodeCount = int(__thiscall*)(utinni::WorldSnapshotReaderWriter* pThis);
using pNodeCountTotal = int(__thiscall*)(utinni::WorldSnapshotReaderWriter* pThis);
using pGetNodeByNetworkId = utinni::WorldSnapshotReaderWriter::Node* (__thiscall*)(utinni::WorldSnapshotReaderWriter* pThis, swgptr networkId);
using pGetNodeByIndex = utinni::WorldSnapshotReaderWriter::Node* (__thiscall*)(utinni::WorldSnapshotReaderWriter* pThis, int nodeId);
using pAddNode = swgptr(__thiscall*)(utinni::WorldSnapshotReaderWriter* pThis, int nodeId, int parentNodeId, const utinni::CrcString& objectFilenameCrcString, int cellId, const swg::math::Transform& transform, float radius, unsigned int pobCrc);
using pRemoveNode = void(__thiscall*)(utinni::WorldSnapshotReaderWriter* pThis, int nodeId);
pOpenFile openFile = (pOpenFile)0x00B97D90;
pSaveFile saveFile = (pSaveFile)0x00B98120;
pClear clear = (pClear)0x00B98290;
pGetObjectTemplateName getObjectTemplateName = (pGetObjectTemplateName)0x00B98720;
pNodeCount nodeCount = (pNodeCount)0x00B986A0;
pNodeCountTotal nodeCountTotal = (pNodeCountTotal)0x00B986D0;
pGetNodeByNetworkId getNodeByNetworkId = (pGetNodeByNetworkId)0x00B98740;
pGetNodeByIndex getNodeByIndex = (pGetNodeByIndex)0x00B986B0;
pAddNode addNode = (pAddNode)0x00B98410;
pRemoveNode removeNode = (pRemoveNode)0x00B98780;
namespace node
{
using pGetNodeNetworkId = int(__thiscall*)(utinni::WorldSnapshotReaderWriter::Node* pThis);
using pGetNodeSpatialSubdivisionHandle = swgptr(__thiscall*)(utinni::WorldSnapshotReaderWriter::Node* pThis);
using pSetNodeSpatialSubdivisionHandle = void(__thiscall*)(utinni::WorldSnapshotReaderWriter::Node* pThis, swgptr handle);
using pRemoveFromWorld = void(__thiscall*)(utinni::WorldSnapshotReaderWriter::Node* pThis);
pGetNodeNetworkId getNodeNetworkId = (pGetNodeNetworkId)0x00B971D0;
pGetNodeSpatialSubdivisionHandle getNodeSpatialSubdivisionHandle = (pGetNodeSpatialSubdivisionHandle)0x00B97390;
pSetNodeSpatialSubdivisionHandle setNodeSpatialSubdivisionHandle = (pSetNodeSpatialSubdivisionHandle)0x00B973A0;
pRemoveFromWorld removeFromWorld = (pRemoveFromWorld)0x00B97440;
}
}
namespace swg::worldsnapshot
{
using pLoad = void(__cdecl*)(const char* name);
using pUnload = void(__cdecl*)();
using pClearPreloadList = char(__cdecl*)(swgptr, swgptr, swgptr);
using pCreateObject = swgptr(__cdecl*)(utinni::WorldSnapshotReaderWriter* reader, utinni::WorldSnapshotReaderWriter::Node* node, swgptr result);
using pAddObject = void(__cdecl*)(swgptr object, swgptr node);
using pDetailLevelChanged = void(__cdecl*)();
pLoad load = (pLoad)0x0059C380;
pUnload unload = (pUnload)0x0059C1D0;
pClearPreloadList clearPreloadList = (pClearPreloadList)0x00404D50;
pCreateObject createObject = (pCreateObject)0x0059BBA0;
pAddObject addObject = (pAddObject)0x0059BF20;
pDetailLevelChanged detailLevelChanged = (pDetailLevelChanged)0x0059DC30;
}
namespace utinni
{
WorldSnapshotReaderWriter* WorldSnapshotReaderWriter::get() { return (WorldSnapshotReaderWriter*) 0x1913E94; } // Static WorldSnapshotReaderWriter ptr
void WorldSnapshotReaderWriter::clear()
{
swg::worldSnapshotReaderWriter::clear(this);
}
const char* WorldSnapshotReaderWriter::getObjectTemplateName(int objectTemplateNameIndex)
{
return swg::worldSnapshotReaderWriter::getObjectTemplateName(this, objectTemplateNameIndex);
}
int WorldSnapshotReaderWriter::getNodeCount()
{
return swg::worldSnapshotReaderWriter::nodeCount(this);
}
int WorldSnapshotReaderWriter::getNodeCountTotal()
{
return swg::worldSnapshotReaderWriter::nodeCountTotal(this);
}
WorldSnapshotReaderWriter::Node* WorldSnapshotReaderWriter::getNodeById(int id)
{
Node* result = nullptr;
for (int i = 0; i < nodeList->size(); ++i)
{
Node* node = nodeList->at(i);
if (node->id == id)
{
result = node;
break;
}
}
return result;
}
WorldSnapshotReaderWriter::Node* WorldSnapshotReaderWriter::getNodeById(int id, Object* parentObject)
{
if (parentObject == nullptr)
{
return getNodeById(id);
}
else
{
return getNodeByIdWithParent(parentObject, id);
}
}
WorldSnapshotReaderWriter::Node* WorldSnapshotReaderWriter::findChildNode(Node* parentNode, int id)
{
Node* result = nullptr;
for (int i = 0; i < parentNode->children->size(); ++i)
{
Node* child = parentNode->children->at(i);
if (child->id == id)
{
result = child;
break;
}
}
if (result == nullptr)
{
for (int i = 0; i < parentNode->children->size(); ++i)
{
Node* child = parentNode->children->at(i);
if (child->children != nullptr && !child->children->empty())
{
Node* childResult = findChildNode(child, id);
if (childResult != nullptr && childResult->id == id)
{
result = childResult;
break;
}
}
}
}
return result;
}
WorldSnapshotReaderWriter::Node* WorldSnapshotReaderWriter::getNodeByIdWithParent(Object* parentObject, int id)
{
Node* result = nullptr;
Object* topParent = parentObject;
while (true)
{
if (topParent->parentObject == nullptr)
{
break;
}
topParent = topParent->parentObject;
}
Node* parentNode = getNodeById(topParent->networkId);
result = findChildNode(parentNode, id);
return result;
}
WorldSnapshotReaderWriter::Node* WorldSnapshotReaderWriter::getNodeByNetworkId(int networkId)
{
return swg::worldSnapshotReaderWriter::getNodeByNetworkId(this, networkId);
}
WorldSnapshotReaderWriter::Node* WorldSnapshotReaderWriter::getNodeAt(int index)
{
return swg::worldSnapshotReaderWriter::getNodeByIndex(this, index);
}
WorldSnapshotReaderWriter::Node* WorldSnapshotReaderWriter::getLastNode()
{
return nodeList->back();
}
WorldSnapshotReaderWriter::Node* WorldSnapshotReaderWriter::addNode(int nodeId, int parentNodeId, const char* objectFilename, int cellId, const swg::math::Transform& transform, float radius, unsigned int pobCrc)
{
// For some reason, the ptr is wrong if parentNodeId is 0 and it's actually 'result - 4' to get the accurate pointer
swgptr node;
if (parentNodeId == 0)
{
node = swg::worldSnapshotReaderWriter::addNode(this, nodeId, parentNodeId, *ConstCharCrcString::ctor(objectFilename), cellId, transform, radius, pobCrc) - 4; // That's why we subtract 4 here
}
else
{
node = swg::worldSnapshotReaderWriter::addNode(this, nodeId, parentNodeId, *ConstCharCrcString::ctor(objectFilename), cellId, transform, radius, pobCrc); // If it's added to a parentNode, it seems fine
}
// Upon further testing, the ptr returned isn't reliable, unsure why
// return memory::read<Node*>(node);
return nullptr;
}
void WorldSnapshotReaderWriter::Node::removeNode()
{
if (!Game::isSafeToUse())
{
return;
}
if (parentId == 0)
{
removeNodeFull();
const auto reader = get();
for (int i = 0; i < get()->getNodeCount(); ++i)
{
if (reader->nodeList->at(i)->id == id)
{
reader->nodeList->erase(reader->nodeList->begin() + i);
break;
}
}
}
else
{
// ToDo check if removeNodeFull can replace the below remove obj
for (int i = 0; i < parentNode->children->size(); ++i)
{
if (parentNode->children->at(i)->id == id)
{
parentNode->children->erase(parentNode->children->begin() + i);
break;
}
}
}
Object* nodeObject = Network::getObjectById(id);
// Need to nullptr check because only loaded objects are non null, ie in range or previously 'seen'
// and the loop goes through all nodes in the entire .WS
if (nodeObject != nullptr)
{
nodeObject->remove();
}
swg::worldSnapshotReaderWriter::removeNode(WorldSnapshotReaderWriter::get(), id);
}
void WorldSnapshotReaderWriter::Node::removeNodeFull() // WIP - Messy IDA pseudo code
{
if (!Game::isSafeToUse())
{
return;
}
using Void1 = int(__thiscall*)(swgptr, int);
using Void2 = int(__thiscall*)(swgptr);
using Void3 = void(__cdecl*)();
Void1 void1 = (Void1)0x005A25A0;
Void1 void2 = (Void1)0x005A08D0;
Void3 void5 = (Void3)0x005A09C0;
Void2 call1 = (Void2)0x005A2D90;
if (getNodeSpatialSubdivisionHandle())
{
swgptr nodeSpatialSubdivisionHandle1 = getNodeSpatialSubdivisionHandle();
swgptr nodeSpatialSubdivisionHandle2 = nodeSpatialSubdivisionHandle1;
if (nodeSpatialSubdivisionHandle1)
{
swgptr nodeSpatialSubdivisionHandle3 = *(swgptr*)(nodeSpatialSubdivisionHandle1 + 4);
if (nodeSpatialSubdivisionHandle3)
{
void1(nodeSpatialSubdivisionHandle3, nodeSpatialSubdivisionHandle1);
swgptr nodeSpatialSubdivisionHandle4 = nodeSpatialSubdivisionHandle2;
if (!(*(byte*)(0x19BB7DC) & 1))
{
*(byte*)(0x19BB7DC) |= 1u;
call1(memory::read<swgptr>(0x19BB7E0));
void5();
}
void2(memory::read<swgptr>(0x19BB7E0), (int)&nodeSpatialSubdivisionHandle4);
}
}
setNodeSpatialSubdivisionHandle(0);
}
Object* nodeObject = Network::getObjectById(id);
// Need to nullptr check because only loaded objects are non null, ie in range or previously 'seen'
// and the loop goes through all nodes in the entire .WS
if (nodeObject != nullptr)
{
nodeObject->remove();
}
swg::worldSnapshotReaderWriter::node::removeFromWorld(this);
}
int64_t WorldSnapshotReaderWriter::Node::getNodeNetworkId()
{
return Network::cast(id);
}
swgptr WorldSnapshotReaderWriter::Node::getNodeSpatialSubdivisionHandle()
{
return swg::worldSnapshotReaderWriter::node::getNodeSpatialSubdivisionHandle(this);
}
void WorldSnapshotReaderWriter::Node::setNodeSpatialSubdivisionHandle(swgptr handle)
{
swg::worldSnapshotReaderWriter::node::setNodeSpatialSubdivisionHandle(this, handle);
}
const char* WorldSnapshotReaderWriter::Node::getObjectTemplateName() const
{
return WorldSnapshotReaderWriter::get()->getObjectTemplateName(objectTemplateNameIndex);
}
int WorldSnapshotReaderWriter::Node::getChildCount() const
{
return children->size();
}
WorldSnapshotReaderWriter::Node* WorldSnapshotReaderWriter::Node::getChildById(int id)
{
Node* result = nullptr;
for (int i = 0; i < children->size(); ++i)
{
Node* node = children->at(i);
if (node->id == id)
{
result = node;
break;
}
}
return result;
}
WorldSnapshotReaderWriter::Node* WorldSnapshotReaderWriter::Node::getChildAt(int index)
{
return children->at(index);
}
WorldSnapshotReaderWriter::Node* WorldSnapshotReaderWriter::Node::getLastChild()
{
return children->back();
}
void WorldSnapshot::load(const std::string& name)
{
if (name.empty())
{
return;
}
memory::nopAddress(0x0059C3F3, 6); // Removes the grabbing of current .trn name to allow the loading of any .ws
swg::worldsnapshot::load(name.c_str());
}
void WorldSnapshot::unload()
{
if (!Game::isSafeToUse())
{
return;
}
auto readerWriter = WorldSnapshotReaderWriter::get();
for (int i = 0; i < readerWriter->getNodeCount(); ++i)
{
readerWriter->getNodeAt(i)->removeNodeFull();
}
swg::worldsnapshot::unload();
}
void WorldSnapshot::reload()
{
unload();
load(GroundScene::get()->getName());
}
void WorldSnapshotReaderWriter::clearPreloadList(swgptr unk1, swgptr unk2, swgptr unk3)
{
swg::worldsnapshot::clearPreloadList(unk1, unk2, unk3);
}
void WorldSnapshotReaderWriter::saveFile(const char* snapshotName)
{
CreateDirectory((utility::getWorkingDirectory() + "/snapshot/").c_str(), nullptr);
if (constCharUtility::isEmpty(snapshotName))
{
swg::worldSnapshotReaderWriter::saveFile(this, ("snapshot/" + GroundScene::get()->getName() + ".ws").c_str());
}
else
{
swg::worldSnapshotReaderWriter::saveFile(this, ("snapshot/" + std::string(snapshotName) + ".ws").c_str());
}
}
bool WorldSnapshot::getPreloadSnapshot()
{
return memory::read<bool>(0x191113C);
}
void WorldSnapshot::setPreloadSnapshot(bool preloadSnapshot)
{
memory::write<bool>(0x191113C, preloadSnapshot);
}
void WorldSnapshot::detailLevelChanged()
{
swg::worldsnapshot::detailLevelChanged();
}
static int highestId = 0;
int getHighestIdFromNode(int currentHighestId, const WorldSnapshotReaderWriter::Node* node)
{
int result = max(currentHighestId, node->id);
if (node->children && !node->children->empty())
{
for (const WorldSnapshotReaderWriter::Node* childNode : *node->children)
{
result = getHighestIdFromNode(result, childNode);
}
}
return result;
}
int WorldSnapshot::generateHighestId()
{
int newId = 0;
auto snapshotFilenames = Game::getRepository()->getDirectoryFilenames("snapshot");
for (const auto& filename : snapshotFilenames)
{
swg::worldSnapshotReaderWriter::openFile(WorldSnapshotReaderWriter::get(), std::filesystem::path(filename).filename().replace_extension("").string().c_str());
const auto reader = WorldSnapshotReaderWriter::get();
for (int i = 0; i < reader->getNodeCount(); ++i)
{
newId = getHighestIdFromNode(newId, reader->nodeList->at(i));
}
}
highestId = newId;
return newId;
}
Object* createObject(WorldSnapshotReaderWriter::Node* node)
{
DWORD errorCode = 0;
return (Object*)swg::worldsnapshot::createObject(WorldSnapshotReaderWriter::get(), node, errorCode);
}
bool WorldSnapshot::isValidObject(const char* objectFilename)
{
if (strstr(objectFilename, "/base/"))
{
return false;
}
ClientObject* cobj = ObjectTemplate::createObject(objectFilename)->getClientObject();
if (cobj == 0 || cobj->getCreatureObject() != 0 || cobj->getShipObject() != 0 || (cobj != 0 && cobj->getTangibleObject() == 0 && cobj->getStaticObject() == 0))
{
return false;
}
cobj->remove();
cobj = nullptr; // ToDo does this need to be dealloc instead?
return true;
}
// ToDo move duplicated code in the following functions to shared function
WorldSnapshotReaderWriter::Node* WorldSnapshot::createAddNode(const char* objectFilename, swg::math::Transform& transform)
{
/* if (!isValidObject(objectFilename))
{
return nullptr;
}*/
const auto reader = WorldSnapshotReaderWriter::get();
WorldSnapshotReaderWriter::Node* parentNode = nullptr;
// Temporary check to get parent, make this better
int parentNodeId = 0;
Camera* camera = GroundScene::get()->getCurrentCamera(); // If camera is outside of the POB and the new node to be created is inside, it crashes as parentObject is nullptr
if (camera->parentObject != nullptr)
{
parentNode = reader->getNodeById(camera->parentObject->networkId, camera->parentObject->parentObject);
if (parentNode == nullptr)
{
return nullptr;
}
parentNodeId = parentNode->id;
}
if (camera->parentObject != nullptr && parentNode == nullptr)
{
return nullptr;
}
auto objectTemplate = ObjectTemplateList::getObjectTemplateByFilename(objectFilename);
const char* pobFilename = ObjectTemplateList::getObjectTemplateByFilename(objectFilename)->getPortalLayoutFilename();
if (!objectTemplate->getAppearanceFilename() && !objectTemplate->getClientDataFilename() && !pobFilename)
{
return nullptr;
}
// Check if the object contains cells
int pobCrc = 0;
int pobCellCount = 0;
if (pobFilename != nullptr && pobFilename[0] != '\0')
{
PortalPropertyTemplate* pPob = PortalPropertyTemplateList::getPobByCrcString(PersistentCrcString::ctor(pobFilename));
pobCrc = pPob->getCrc();
pobCellCount = pPob->getCellCount() - 1;
}
highestId++;
const int id = highestId;
reader->addNode(id, parentNodeId, objectFilename, 0, transform, 512, pobCrc); // ToDo Make radius a customizable variable
// If the object contains cells, create them
for (int i = 0; i < pobCellCount; ++i)
{
highestId = id + i + 1;
reader->addNode(highestId, id, "object/cell/shared_cell.iff", i + 1, swg::math::Transform::getIdentity(), 0, 0);
}
// Workaround to the unreliable ptr return of reader->addNode
WorldSnapshotReaderWriter::Node* node;
if (parentNode == nullptr)
{
node = reader->nodeList->back();
}
else
{
node = parentNode->children->back();
}
Object* obj = createObject(node);
if (obj)
{
obj->addToWorld();
}
return node;
}
WorldSnapshotReaderWriter::Node* WorldSnapshot::createNodeCopy(WorldSnapshotReaderWriter::Node* originalNode, swg::math::Transform& transform)
{
const auto reader = WorldSnapshotReaderWriter::get();
highestId++;
const int id = highestId;
reader->addNode(id, originalNode->parentId, originalNode->getObjectTemplateName(), originalNode->cellIndex, transform, originalNode->radius, originalNode->pobCRC);
if (originalNode->children != nullptr)
{
for (int i = 0; i < originalNode->children->size(); ++i)
{
highestId = id + i + 1;
const auto childNode = originalNode->children->at(i);
reader->addNode(highestId, id, childNode->getObjectTemplateName(), childNode->cellIndex, swg::math::Transform(childNode->transform), childNode->radius, childNode->pobCRC);
}
}
// Workaround to the unreliable ptr return of reader->addNode
WorldSnapshotReaderWriter::Node* node;
if (originalNode->parentNode == nullptr)
{
node = reader->nodeList->back();
}
else
{
node = originalNode->parentNode->children->back();
}
Object* obj = createObject(node);
if (obj)
{
obj->addToWorld();
}
return node;
}
Object* WorldSnapshot::addNode(WorldSnapshotReaderWriter::Node* node)
{
const auto reader = WorldSnapshotReaderWriter::get();
reader->addNode(node->id, node->parentId, node->getObjectTemplateName(), node->cellIndex, node->transform, node->radius, node->pobCRC);
if (node->children != nullptr)
{
for (int i = 0; i < node->children->size(); ++i)
{
const auto childNode = node->children->at(i);
reader->addNode(childNode->id, childNode->parentId, childNode->getObjectTemplateName(), childNode->cellIndex, childNode->transform, childNode->radius, childNode->pobCRC);
}
}
Object* obj = createObject(node);
if (obj)
{
obj->addToWorld();
}
return obj;
}
void WorldSnapshot::removeNode(WorldSnapshotReaderWriter::Node* node)
{
node->removeNode();
detailLevelChanged(); // Hack to update the .WS
}
}
| 30.994152 | 245 | 0.683113 | [
"object",
"transform"
] |
c85b13a5c8b324220b3204eaa2c23b58a20e0d60 | 35,525 | cc | C++ | dcmtk-3.6.6/dcmsr/libcmr/tid1411.cc | happymanx/Weather_FFI | a7f9bf8f1bda2b50c9d9a875c08fccf58379ad9f | [
"MIT"
] | null | null | null | dcmtk-3.6.6/dcmsr/libcmr/tid1411.cc | happymanx/Weather_FFI | a7f9bf8f1bda2b50c9d9a875c08fccf58379ad9f | [
"MIT"
] | null | null | null | dcmtk-3.6.6/dcmsr/libcmr/tid1411.cc | happymanx/Weather_FFI | a7f9bf8f1bda2b50c9d9a875c08fccf58379ad9f | [
"MIT"
] | null | null | null | /*
*
* Copyright (C) 2016-2019, J. Riesmeier, Oldenburg, Germany
* All rights reserved. See COPYRIGHT file for details.
*
* Source file for class TID1411_VolumetricROIMeasurements
*
* Author: Joerg Riesmeier
*
*/
#include "dcmtk/config/osconfig.h" /* make sure OS specific configuration is included first */
#include "dcmtk/dcmsr/cmr/tid1411.h"
#include "dcmtk/dcmsr/cmr/tid15def.h"
#include "dcmtk/dcmsr/cmr/logger.h"
#include "dcmtk/dcmsr/codes/dcm.h"
#include "dcmtk/dcmsr/codes/ncit.h"
#include "dcmtk/dcmsr/codes/sct.h"
#include "dcmtk/dcmsr/codes/umls.h"
#include "dcmtk/dcmsr/dsrtpltn.h"
#include "dcmtk/dcmdata/dcdeftag.h"
#include "dcmtk/dcmdata/dcuid.h"
// helper macros for checking the return value of API calls
#define CHECK_RESULT(call) if (result.good()) result = call
#define STORE_RESULT(call) result = call
#define GOOD_RESULT(call) if (result.good()) call
#define BAD_RESULT(call) if (result.bad()) call
// index positions in node list (makes source code more readable)
#define MEASUREMENT_GROUP 0
#define ACTIVITY_SESSION 1
#define TRACKING_IDENTIFIER 2
#define TRACKING_UNIQUE_IDENTIFIER 3
#define FINDING 4
#define TIME_POINT 5
#define REFERENCED_SEGMENT 6
#define SOURCE_SERIES_FOR_SEGMENTATION 7
#define REAL_WORLD_VALUE_MAP 8
#define MEASUREMENT_METHOD 9
#define LAST_FINDING_SITE 10
#define LAST_MEASUREMENT 11
#define LAST_QUALITATIVE_EVALUATION 12
#define NUMBER_OF_LIST_ENTRIES 13
// general information on TID 1411 (Volumetric ROI Measurements)
#define TEMPLATE_NUMBER "1411"
#define MAPPING_RESOURCE "DCMR"
#define MAPPING_RESOURCE_UID UID_DICOMContentMappingResource
#define TEMPLATE_TYPE OFTrue /* extensible */
#define TEMPLATE_ORDER OFFalse /* non-significant */
template<typename T1, typename T2, typename T3, typename T4>
TID1411_VolumetricROIMeasurements<T1, T2, T3, T4>::TID1411_VolumetricROIMeasurements(const OFBool createGroup)
: DSRSubTemplate(TEMPLATE_NUMBER, MAPPING_RESOURCE, MAPPING_RESOURCE_UID),
Measurement(new TID1419_Measurement())
{
setExtensible(TEMPLATE_TYPE);
setOrderSignificant(TEMPLATE_ORDER);
/* need to store position of various content items */
reserveEntriesInNodeList(NUMBER_OF_LIST_ENTRIES, OFTrue /*initialize*/);
/* TID 1411 (Volumetric ROI Measurements) Row 1 */
if (createGroup)
createMeasurementGroup();
}
template<typename T1, typename T2, typename T3, typename T4>
void TID1411_VolumetricROIMeasurements<T1, T2, T3, T4>::clear()
{
DSRSubTemplate::clear();
Measurement->clear();
}
template<typename T1, typename T2, typename T3, typename T4>
OFBool TID1411_VolumetricROIMeasurements<T1, T2, T3, T4>::isValid() const
{
/* check whether base class is valid and all required content items are present */
return DSRSubTemplate::isValid() &&
hasMeasurementGroup() && hasTrackingIdentifier() && hasTrackingUniqueIdentifier() &&
hasReferencedSegment() && hasSourceSeriesForSegmentation() && hasMeasurements(OFTrue /*checkChildren*/);
}
template<typename T1, typename T2, typename T3, typename T4>
OFBool TID1411_VolumetricROIMeasurements<T1, T2, T3, T4>::hasMeasurementGroup(const OFBool checkChildren) const
{
OFBool result = OFFalse;
/* need to check for child nodes? */
if (checkChildren)
{
DSRDocumentTreeNodeCursor cursor(getRoot());
/* go to content item at TID 1411 (Volumetric ROI Measurements) Row 1 */
if (gotoEntryFromNodeList(cursor, MEASUREMENT_GROUP) > 0)
result = cursor.hasChildNodes();
} else {
/* check for content item at TID 1411 (Volumetric ROI Measurements) Row 1 */
result = (getEntryFromNodeList(MEASUREMENT_GROUP) > 0);
}
return result;
}
template<typename T1, typename T2, typename T3, typename T4>
OFBool TID1411_VolumetricROIMeasurements<T1, T2, T3, T4>::hasTrackingIdentifier() const
{
/* check for content item at TID 1411 (Volumetric ROI Measurements) Row 2 */
return (getEntryFromNodeList(TRACKING_IDENTIFIER) > 0);
}
template<typename T1, typename T2, typename T3, typename T4>
OFBool TID1411_VolumetricROIMeasurements<T1, T2, T3, T4>::hasTrackingUniqueIdentifier() const
{
/* check for content item at TID 1411 (Volumetric ROI Measurements) Row 3 */
return (getEntryFromNodeList(TRACKING_UNIQUE_IDENTIFIER) > 0);
}
template<typename T1, typename T2, typename T3, typename T4>
OFBool TID1411_VolumetricROIMeasurements<T1, T2, T3, T4>::hasReferencedSegment() const
{
/* check for content item at TID 1411 (Volumetric ROI Measurements) Row 7 */
return (getEntryFromNodeList(REFERENCED_SEGMENT) > 0);
}
template<typename T1, typename T2, typename T3, typename T4>
OFBool TID1411_VolumetricROIMeasurements<T1, T2, T3, T4>::hasSourceSeriesForSegmentation() const
{
/* check for content item at TID 1411 (Volumetric ROI Measurements) Row 12 */
return (getEntryFromNodeList(SOURCE_SERIES_FOR_SEGMENTATION) > 0);
}
template<typename T1, typename T2, typename T3, typename T4>
OFBool TID1411_VolumetricROIMeasurements<T1, T2, T3, T4>::hasMeasurements(const OFBool checkChildren) const
{
OFBool result = OFFalse;
/* need to check for child nodes? */
if (checkChildren)
{
DSRDocumentTreeNodeCursor cursor(getRoot());
/* go to content item at TID 1411 (Volumetric ROI Measurements) Row 13 */
if (gotoEntryFromNodeList(cursor, LAST_MEASUREMENT) > 0)
{
/* check whether any of the "included TID 1419 templates" is non-empty */
while (cursor.isValid() && (cursor.getNode()->getValueType() == VT_includedTemplate))
{
const DSRSubTemplate *subTempl = OFstatic_cast(const DSRIncludedTemplateTreeNode *, cursor.getNode())->getValue().get();
if (subTempl != NULL)
{
if (subTempl->compareTemplateIdentication("1419", "DCMR"))
{
result = !subTempl->isEmpty();
if (result) break;
} else {
/* exit loop */
break;
}
}
if (cursor.gotoPrevious() == 0)
{
/* invalidate cursor */
cursor.clear();
}
}
}
} else {
/* check for content item at TID 1411 (Volumetric ROI Measurements) Row 13 */
result = (getEntryFromNodeList(LAST_MEASUREMENT) > 0);
}
return result;
}
template<typename T1, typename T2, typename T3, typename T4>
OFCondition TID1411_VolumetricROIMeasurements<T1, T2, T3, T4>::setActivitySession(const OFString &session,
const OFBool check)
{
OFCondition result = EC_Normal;
/* basic check of parameter */
if (!session.empty())
{
/* check whether measurement group already exists */
if (!hasMeasurementGroup())
result = createMeasurementGroup();
/* TID 1411 (Volumetric ROI Measurements) Row 1b */
CHECK_RESULT(addOrReplaceContentItem(ACTIVITY_SESSION, RT_hasObsContext, VT_Text, CODE_NCIt_ActivitySession, "TID 1411 - Row 1b", check));
CHECK_RESULT(getCurrentContentItem().setStringValue(session, check));
} else
result = EC_IllegalParameter;
return result;
}
template<typename T1, typename T2, typename T3, typename T4>
OFCondition TID1411_VolumetricROIMeasurements<T1, T2, T3, T4>::setTrackingIdentifier(const OFString &trackingID,
const OFBool check)
{
OFCondition result = EC_Normal;
/* basic check of parameter */
if (!trackingID.empty())
{
/* check whether measurement group already exists */
if (!hasMeasurementGroup())
result = createMeasurementGroup();
/* TID 1411 (Volumetric ROI Measurements) Row 2 */
CHECK_RESULT(addOrReplaceContentItem(TRACKING_IDENTIFIER, RT_hasObsContext, VT_Text, CODE_DCM_TrackingIdentifier, "TID 1411 - Row 2", check));
CHECK_RESULT(getCurrentContentItem().setStringValue(trackingID, check));
} else
result = EC_IllegalParameter;
return result;
}
template<typename T1, typename T2, typename T3, typename T4>
OFCondition TID1411_VolumetricROIMeasurements<T1, T2, T3, T4>::setTrackingUniqueIdentifier(const OFString &trackingUID,
const OFBool check)
{
OFCondition result = EC_Normal;
/* basic check of parameter */
if (!trackingUID.empty())
{
/* check whether measurement group already exists */
if (!hasMeasurementGroup())
result = createMeasurementGroup();
/* TID 1411 (Volumetric ROI Measurements) Row 3 */
CHECK_RESULT(addOrReplaceContentItem(TRACKING_UNIQUE_IDENTIFIER, RT_hasObsContext, VT_UIDRef, CODE_DCM_TrackingUniqueIdentifier, "TID 1411 - Row 3", check));
CHECK_RESULT(getCurrentContentItem().setStringValue(trackingUID, check));
} else
result = EC_IllegalParameter;
return result;
}
template<typename T1, typename T2, typename T3, typename T4>
OFCondition TID1411_VolumetricROIMeasurements<T1, T2, T3, T4>::setFinding(const DSRCodedEntryValue &finding,
const OFBool check)
{
OFCondition result = EC_Normal;
/* basic check of parameter */
if (finding.isComplete())
{
/* check whether measurement group already exists */
if (!hasMeasurementGroup())
result = createMeasurementGroup();
/* TID 1411 (Volumetric ROI Measurements) Row 3b */
CHECK_RESULT(addOrReplaceContentItem(FINDING, RT_contains, VT_Code, CODE_DCM_Finding, "TID 1411 - Row 3b", check));
CHECK_RESULT(getCurrentContentItem().setCodeValue(finding, check));
} else
result = EC_IllegalParameter;
return result;
}
template<typename T1, typename T2, typename T3, typename T4>
OFCondition TID1411_VolumetricROIMeasurements<T1, T2, T3, T4>::setTimePoint(const OFString &timePoint,
const OFBool check)
{
OFCondition result = EC_Normal;
/* basic check of parameter */
if (!timePoint.empty())
{
/* check whether measurement group already exists */
if (!hasMeasurementGroup())
result = createMeasurementGroup();
/* TID 1502 (Time Point Context) Row 3 */
CHECK_RESULT(addOrReplaceContentItem(TIME_POINT, RT_hasObsContext, VT_Text, CODE_UMLS_TimePoint, "TID 1502 - Row 3", check));
CHECK_RESULT(getCurrentContentItem().setStringValue(timePoint, check));
} else
result = EC_IllegalParameter;
return result;
}
template<typename T1, typename T2, typename T3, typename T4>
OFCondition TID1411_VolumetricROIMeasurements<T1, T2, T3, T4>::setReferencedSegment(const DSRImageReferenceValue &segment,
const OFBool check)
{
OFCondition result = EC_Normal;
/* basic check of parameter */
if (segment.isComplete())
{
const char *annotationText = "TID 1411 - Row 7";
const DSRBasicCodedEntry conceptName(CODE_DCM_ReferencedSegment);
/* check for supported segmentation SOP classes */
if ((segment.getSOPClassUID() != UID_SegmentationStorage) && (segment.getSOPClassUID() != UID_SurfaceSegmentationStorage))
{
DCMSR_CMR_WARN("Cannot set value of '" << conceptName.CodeMeaning << "' content item (" << annotationText << ") ... wrong SOP Class");
DCMSR_CMR_DEBUG("SOP Class UID \"" << segment.getSOPClassUID() << "\" does not match one of the known Segmentation objects");
result = CMR_EC_InvalidSegmentationObject;
}
/* ... and number of referenced segments */
else if ((segment.getSegmentList().getNumberOfItems() != 1))
{
DCMSR_CMR_WARN("Cannot set value of '" << conceptName.CodeMeaning << "' content item (" << annotationText << ") ... wrong number of segments");
result = CMR_EC_InvalidSegmentationObject;
} else {
/* check whether measurement group already exists */
if (!hasMeasurementGroup())
result = createMeasurementGroup();
/* TID 1411 (Volumetric ROI Measurements) Row 7 */
CHECK_RESULT(addOrReplaceContentItem(REFERENCED_SEGMENT, RT_contains, VT_Image, conceptName, annotationText, check));
CHECK_RESULT(getCurrentContentItem().setImageReference(segment, check));
}
} else
result = EC_IllegalParameter;
return result;
}
template<typename T1, typename T2, typename T3, typename T4>
OFCondition TID1411_VolumetricROIMeasurements<T1, T2, T3, T4>::setReferencedSegment(DcmItem &dataset,
const Uint16 segmentNumber,
const OFBool copyTracking,
const OFBool check)
{
DSRImageReferenceValue segment;
/* first, create the referenced image/segment object */
OFCondition result = segment.setReference(dataset, check);
segment.getSegmentList().addItem(segmentNumber);
/* then, add/set the corresponding content item */
CHECK_RESULT(setReferencedSegment(segment, check));
/* need to copy tracking information? (introduced with CP-1496) */
if (copyTracking && result.good())
{
DcmSequenceOfItems *dseq = NULL;
/* get SegmentSequence (should always be present) */
result = dataset.findAndGetSequence(DCM_SegmentSequence, dseq);
checkElementValue(dseq, DCM_SegmentSequence, "1-n", "1", result, "SegmentDescriptionMacro");
if (result.good())
{
DcmObject *dobj = NULL;
OFBool segmentFound = OFFalse;
/* iterate over all items in this sequence */
while (((dobj = dseq->nextInContainer(dobj)) != NULL) && !segmentFound)
{
Uint16 number = 0;
DcmItem *ditem = OFstatic_cast(DcmItem *, dobj);
/* search for given segment number */
if (ditem->findAndGetUint16(DCM_SegmentNumber, number).good())
{
if (segmentNumber == number)
{
OFString trackingID, trackingUID;
/* get tracking ID and UID from current item (if present) and add/set content item */
getAndCheckStringValueFromDataset(*ditem, DCM_TrackingID, trackingID, "1", "1C", "SegmentSequence");
getAndCheckStringValueFromDataset(*ditem, DCM_TrackingUID, trackingUID, "1", "1C", "SegmentSequence");
if (!trackingID.empty() && !trackingUID.empty())
{
CHECK_RESULT(setTrackingIdentifier(trackingID, check));
CHECK_RESULT(setTrackingUniqueIdentifier(trackingUID, check));
}
else if (trackingID.empty() != trackingUID.empty())
{
/* report a violation of the type 1C conditions */
DCMSR_CMR_WARN("Either Tracking ID or Tracking UID is absent/empty in referenced segmentation object");
}
/* given segment number found */
segmentFound = OFTrue;
}
}
}
/* report a warning if referenced segment could not be found */
if (!segmentFound)
{
DCMSR_CMR_WARN("Cannot copy tracking information for '" << CODE_DCM_ReferencedSegment.CodeMeaning << "' content item (TID 1411 - Row 7) ... segment not found");
DCMSR_CMR_DEBUG("Cannot find given Segment Number (" << segmentNumber << ") in Segment Sequence of referenced segmentation object");
}
} else {
/* report a warning if referenced segment could not be found */
DCMSR_CMR_WARN("Cannot copy tracking information for '" << CODE_DCM_ReferencedSegment.CodeMeaning << "' content item (TID 1411 - Row 7) ... segment not found");
}
/* tbc: return with an error in case the tracking information could not be copied? */
}
return result;
}
template<typename T1, typename T2, typename T3, typename T4>
OFCondition TID1411_VolumetricROIMeasurements<T1, T2, T3, T4>::setSourceSeriesForSegmentation(const OFString &seriesUID,
const OFBool check)
{
OFCondition result = EC_Normal;
/* basic check of parameter */
if (!seriesUID.empty())
{
/* check whether measurement group already exists */
if (!hasMeasurementGroup())
result = createMeasurementGroup();
/* TID 1411 (Volumetric ROI Measurements) Row 12 */
CHECK_RESULT(addOrReplaceContentItem(SOURCE_SERIES_FOR_SEGMENTATION, RT_contains, VT_UIDRef, CODE_DCM_SourceSeriesForSegmentation, "TID 1411 - Row 12", check));
CHECK_RESULT(getCurrentContentItem().setStringValue(seriesUID, check));
} else
result = EC_IllegalParameter;
return result;
}
template<typename T1, typename T2, typename T3, typename T4>
OFCondition TID1411_VolumetricROIMeasurements<T1, T2, T3, T4>::setRealWorldValueMap(const DSRCompositeReferenceValue &valueMap,
const OFBool check)
{
OFCondition result = EC_Normal;
/* basic check of parameter */
if (valueMap.isComplete())
{
const char *annotationText = "TID 1411 - Row 14";
const DSRBasicCodedEntry conceptName(CODE_DCM_RealWorldValueMapUsedForMeasurement);
/* check for real world value mapping SOP classes */
if (valueMap.getSOPClassUID() != UID_RealWorldValueMappingStorage)
{
DCMSR_CMR_WARN("Cannot set value of '" << conceptName.CodeMeaning << "' content item (" << annotationText << ") ... wrong SOP Class");
DCMSR_CMR_DEBUG("SOP Class UID \"" << valueMap.getSOPClassUID() << "\" does not match the one of the Real World Value Mapping object");
result = CMR_EC_InvalidRealWorldValueMappingObject;
} else {
/* check whether measurement group already exists */
if (!hasMeasurementGroup())
result = createMeasurementGroup();
/* TID 1411 (Volumetric ROI Measurements) Row 14 */
CHECK_RESULT(addOrReplaceContentItem(REAL_WORLD_VALUE_MAP, RT_contains, VT_Composite, conceptName, annotationText, check));
CHECK_RESULT(getCurrentContentItem().setCompositeReference(valueMap, check));
}
} else
result = EC_IllegalParameter;
return result;
}
template<typename T1, typename T2, typename T3, typename T4>
OFCondition TID1411_VolumetricROIMeasurements<T1, T2, T3, T4>::setRealWorldValueMap(DcmItem &dataset,
const OFBool check)
{
DSRCompositeReferenceValue valueMap;
/* first, create the referenced composite object */
OFCondition result = valueMap.setReference(dataset, check);
/* then, add/set the corresponding content item */
CHECK_RESULT(setRealWorldValueMap(valueMap, check));
return result;
}
template<typename T1, typename T2, typename T_Method, typename T4>
OFCondition TID1411_VolumetricROIMeasurements<T1, T2, T_Method, T4>::setMeasurementMethod(const T_Method &method,
const OFBool check)
{
OFCondition result = EC_Normal;
/* basic check of parameter */
if (method.hasSelectedValue())
{
/* check whether measurement group already exists */
if (!hasMeasurementGroup())
result = createMeasurementGroup();
/* TID 1419 (ROI Measurements) Row 1 */
CHECK_RESULT(addOrReplaceContentItem(MEASUREMENT_METHOD, RT_hasConceptMod, VT_Code, CODE_SCT_MeasurementMethod, "TID 1419 - Row 1", check));
CHECK_RESULT(getCurrentContentItem().setCodeValue(method, check));
} else
result = EC_IllegalParameter;
return result;
}
template<typename T1, typename T2, typename T3, typename T4>
OFCondition TID1411_VolumetricROIMeasurements<T1, T2, T3, T4>::addFindingSite(const DSRCodedEntryValue &site,
const CID244e_Laterality &laterality,
const DSRCodedEntryValue &siteModifier,
const OFBool check)
{
OFCondition result = EC_Normal;
/* basic check of mandatory parameter */
if (site.isComplete())
{
/* check whether measurement group already exists */
if (!hasMeasurementGroup())
result = createMeasurementGroup();
if (result.good())
{
/* create a new subtree in order to "rollback" in case of error */
DSRDocumentSubTree *subTree = new DSRDocumentSubTree;
if (subTree != NULL)
{
/* TID 1419 (ROI Measurements) Row 2 */
CHECK_RESULT(subTree->addContentItem(RT_hasConceptMod, VT_Code, CODE_SCT_FindingSite, check));
CHECK_RESULT(subTree->getCurrentContentItem().setCodeValue(site, check));
CHECK_RESULT(subTree->getCurrentContentItem().setAnnotationText("TID 1419 - Row 2"));
const size_t lastNode = subTree->getNodeID();
/* TID 1419 (ROI Measurements) Row 3 - optional */
if (laterality.hasSelectedValue())
{
CHECK_RESULT(subTree->addChildContentItem(RT_hasConceptMod, VT_Code, CODE_SCT_Laterality, check));
CHECK_RESULT(subTree->getCurrentContentItem().setCodeValue(laterality, check));
CHECK_RESULT(subTree->getCurrentContentItem().setAnnotationText("TID 1419 - Row 3"));
GOOD_RESULT(subTree->gotoParent());
}
/* TID 1419 (ROI Measurements) Row 4 - optional */
if (siteModifier.isComplete())
{
CHECK_RESULT(subTree->addChildContentItem(RT_hasConceptMod, VT_Code, CODE_SCT_TopographicalModifier, check));
CHECK_RESULT(subTree->getCurrentContentItem().setCodeValue(siteModifier, check));
CHECK_RESULT(subTree->getCurrentContentItem().setAnnotationText("TID 1419 - Row 4"));
GOOD_RESULT(subTree->gotoParent());
}
/* if everything was OK, insert new subtree into the template */
if (result.good() && !subTree->isEmpty())
{
/* go to last measurement (if any) */
if (gotoLastEntryFromNodeList(this, LAST_FINDING_SITE) == getEntryFromNodeList(MEASUREMENT_GROUP))
{
/* insert subtree below root */
STORE_RESULT(insertSubTree(subTree, AM_belowCurrent));
} else {
/* insert subtree after current position */
STORE_RESULT(insertSubTree(subTree, AM_afterCurrent));
}
/* store ID of recently added node for later use */
GOOD_RESULT(storeEntryInNodeList(LAST_FINDING_SITE, lastNode));
/* in case of error, make sure that memory is freed */
BAD_RESULT(delete subTree);
} else {
/* delete the new subtree since it has not been inserted */
delete subTree;
}
} else
result = EC_MemoryExhausted;
} else
result = CMR_EC_NoMeasurement;
} else
result = EC_IllegalParameter;
return result;
}
template<typename T_Measurement, typename T_Units, typename T_Method, typename T_Derivation>
OFCondition TID1411_VolumetricROIMeasurements<T_Measurement, T_Units, T_Method, T_Derivation>::addMeasurement(const T_Measurement &conceptName,
const MeasurementValue &numericValue,
const OFBool checkEmpty,
const OFBool checkValue)
{
OFCondition result = EC_Normal;
/* basic check of mandatory parameters */
if (conceptName.hasSelectedValue() && numericValue.isComplete())
{
/* check whether measurement group already exists */
if (!hasMeasurementGroup())
result = createMeasurementGroup();
if (result.good())
{
/* go to content item at TID 1411 (Volumetric ROI Measurements) Row 15 */
if (gotoEntryFromNodeList(this, LAST_MEASUREMENT) > 0)
{
/* check whether the current instance of TID 1419 is non-empty (if needed) */
if (checkEmpty && Measurement->isEmpty())
result = getMeasurement().createNewMeasurement(conceptName, numericValue, checkValue);
else {
/* create new instance of TID 1419 (ROI Measurements) */
TID1419_Measurement *subTempl = new TID1419_Measurement(conceptName, numericValue, checkValue);
if (subTempl != NULL)
{
/* store (shared) reference to new instance */
Measurement.reset(subTempl);
/* and add it to the current template (TID 1411 - Row 15) */
STORE_RESULT(includeTemplate(Measurement, AM_afterCurrent, RT_contains));
CHECK_RESULT(getCurrentContentItem().setAnnotationText("TID 1411 - Row 15"));
GOOD_RESULT(storeEntryInNodeList(LAST_MEASUREMENT, getNodeID()));
/* tbc: what if the call of includeTemplate() fails? */
} else
result = EC_MemoryExhausted;
}
} else
result = CMR_EC_NoMeasurementGroup;
}
} else
result = EC_IllegalParameter;
return result;
}
template<typename T1, typename T2, typename T3, typename T4>
OFCondition TID1411_VolumetricROIMeasurements<T1, T2, T3, T4>::addQualitativeEvaluation(const DSRCodedEntryValue &conceptName,
const DSRCodedEntryValue &codeValue,
const OFBool check)
{
OFCondition result = EC_Normal;
/* make sure that the parameters are non-empty */
if (conceptName.isComplete() && codeValue.isComplete())
{
/* check whether measurement group already exists */
if (!hasMeasurementGroup())
result = createMeasurementGroup();
if (result.good())
{
/* go to last qualitative evaluation (if any) */
if (gotoLastEntryFromNodeList(this, LAST_QUALITATIVE_EVALUATION) == getEntryFromNodeList(MEASUREMENT_GROUP))
{
/* insert TID 1411 (Volumetric ROI Measurements) Row 16 below root */
STORE_RESULT(addChildContentItem(RT_contains, VT_Code, conceptName, check));
} else {
/* insert TID 1411 (Volumetric ROI Measurements) Row 16 after current position */
STORE_RESULT(addContentItem(RT_contains, VT_Code, conceptName, check));
}
CHECK_RESULT(getCurrentContentItem().setCodeValue(codeValue, check));
CHECK_RESULT(getCurrentContentItem().setAnnotationText("TID 1411 - Row 16"));
/* store ID of recently added node for later use */
GOOD_RESULT(storeEntryInNodeList(LAST_QUALITATIVE_EVALUATION, getNodeID()));
}
} else
result = EC_IllegalParameter;
return result;
}
template<typename T1, typename T2, typename T3, typename T4>
OFCondition TID1411_VolumetricROIMeasurements<T1, T2, T3, T4>::addQualitativeEvaluation(const DSRCodedEntryValue &conceptName,
const OFString &stringValue,
const OFBool check)
{
OFCondition result = EC_Normal;
/* make sure that the parameters are non-empty */
if (conceptName.isComplete() && !stringValue.empty())
{
/* check whether measurement group already exists */
if (!hasMeasurementGroup())
result = createMeasurementGroup();
if (result.good())
{
/* go to last qualitative evaluation (if any) */
if (gotoLastEntryFromNodeList(this, LAST_QUALITATIVE_EVALUATION) == getEntryFromNodeList(MEASUREMENT_GROUP))
{
/* insert TID 1411 (Volumetric ROI Measurements) Row 17 below root */
STORE_RESULT(addChildContentItem(RT_contains, VT_Text, conceptName, check));
} else {
/* insert TID 1411 (Volumetric ROI Measurements) Row 17 after current position */
STORE_RESULT(addContentItem(RT_contains, VT_Text, conceptName, check));
}
CHECK_RESULT(getCurrentContentItem().setStringValue(stringValue, check));
CHECK_RESULT(getCurrentContentItem().setAnnotationText("TID 1411 - Row 17"));
/* store ID of recently added node for later use */
GOOD_RESULT(storeEntryInNodeList(LAST_QUALITATIVE_EVALUATION, getNodeID()));
}
} else
result = EC_IllegalParameter;
return result;
}
// protected methods
template<typename T1, typename T2, typename T3, typename T4>
OFCondition TID1411_VolumetricROIMeasurements<T1, T2, T3, T4>::createMeasurementGroup()
{
OFCondition result = SR_EC_InvalidTemplateStructure;
if (isEmpty())
{
/* TID 1411 (Volumetric ROI Measurements) Row 1 */
STORE_RESULT(addContentItem(RT_unknown, VT_Container, CODE_DCM_MeasurementGroup));
CHECK_RESULT(getCurrentContentItem().setAnnotationText("TID 1411 - Row 1"));
GOOD_RESULT(storeEntryInNodeList(MEASUREMENT_GROUP, getNodeID()));
/* TID 1411 (Volumetric ROI Measurements) Row 15 */
CHECK_RESULT(includeTemplate(Measurement, AM_belowCurrent, RT_contains));
CHECK_RESULT(getCurrentContentItem().setAnnotationText("TID 1411 - Row 15"));
GOOD_RESULT(storeEntryInNodeList(LAST_MEASUREMENT, getNodeID()));
/* if anything went wrong, clear the report */
BAD_RESULT(clear());
}
return result;
}
template<typename T1, typename T2, typename T3, typename T4>
OFCondition TID1411_VolumetricROIMeasurements<T1, T2, T3, T4>::addOrReplaceContentItem(const size_t nodePos,
const E_RelationshipType relationshipType,
const E_ValueType valueType,
const DSRCodedEntryValue &conceptName,
const OFString &annotationText,
const OFBool check)
{
OFCondition result = EC_Normal;
/* check concept name and coded entry value */
if (conceptName.isComplete())
{
/* check whether content item already exists */
if (getEntryFromNodeList(nodePos) == 0)
{
/* if not, create the content item (at correct position) */
if (gotoLastEntryFromNodeList(this, nodePos) == getEntryFromNodeList(MEASUREMENT_GROUP))
{
/* need to add the new content item as the first child */
if (addContentItem(relationshipType, valueType, AM_belowCurrentBeforeFirstChild) > 0)
{
if (getCurrentContentItem().setConceptName(conceptName, check).bad())
result = SR_EC_InvalidConceptName;
} else
result = SR_EC_CannotAddContentItem;
} else {
/* add new content item as a sibling (after the current one) */
STORE_RESULT(addContentItem(relationshipType, valueType, conceptName));
}
/* store ID of added node for later use */
GOOD_RESULT(storeEntryInNodeList(nodePos, getNodeID()));
}
else if (gotoEntryFromNodeList(this, nodePos) > 0)
{
/* make sure that the value type of the existing content item is correct */
if (getCurrentContentItem().getValueType() != valueType)
{
DCMSR_CMR_WARN("Cannot replace value of '" << conceptName.getCodeMeaning()
<< "' content item (" << annotationText << ") ... wrong value type");
result = SR_EC_InvalidContentItem;
}
else if (getCurrentContentItem().getConceptName() != conceptName)
{
DCMSR_CMR_WARN("Cannot replace value of '" << conceptName.getCodeMeaning()
<< "' content item (" << annotationText << ") ... wrong concept name");
result = SR_EC_InvalidConceptName;
} else {
DCMSR_CMR_DEBUG("Replacing value of '" << conceptName.getCodeMeaning()
<< "' content item (" << annotationText << ")");
/* the actual replacing of the value is done by the caller of this method */
}
} else
result = SR_EC_InvalidTemplateStructure;
/* finally, set annotation */
CHECK_RESULT(getCurrentContentItem().setAnnotationText(annotationText));
} else
result = SR_EC_InvalidConceptName;
return result;
}
// explicit template instantiation (needed for use in TID 1500)
template class TID1411_VolumetricROIMeasurements<CID7469_GenericIntensityAndSizeMeasurements,
CID7181_AbstractMultiDimensionalImageModelComponentUnits,
CID6147_ResponseCriteria,
CID7464_GeneralRegionOfInterestMeasurementModifiers>;
| 47.812921 | 176 | 0.602505 | [
"object"
] |
c85b566edb2e42b90cb2edb7eafcdc6b3c0c6aab | 4,705 | cpp | C++ | clang/EnumerateIncludeDirectivesResult.cpp | djp952/tools-llvm | 01503ab630354dc7196a8dfe15f4525bf9a0e1ec | [
"MIT"
] | 1 | 2016-09-11T11:32:08.000Z | 2016-09-11T11:32:08.000Z | clang/EnumerateIncludeDirectivesResult.cpp | djp952/tools-llvm | 01503ab630354dc7196a8dfe15f4525bf9a0e1ec | [
"MIT"
] | 3 | 2016-06-04T03:55:58.000Z | 2016-06-09T03:13:15.000Z | clang/EnumerateIncludeDirectivesResult.cpp | djp952/tools-llvm | 01503ab630354dc7196a8dfe15f4525bf9a0e1ec | [
"MIT"
] | null | null | null | //---------------------------------------------------------------------------
// Copyright (c) 2016 Michael G. Brehm
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//---------------------------------------------------------------------------
#include "stdafx.h"
#include "EnumerateIncludeDirectivesResult.h"
#pragma warning(push, 4) // Enable maximum compiler warnings
namespace zuki::tools::llvm::clang {
//---------------------------------------------------------------------------
// EnumerateIncludeDirectivesResult Constructor (internal)
//
// Arguments:
//
// result - CXVisitorResult to represent with this class
EnumerateIncludeDirectivesResult::EnumerateIncludeDirectivesResult(CXVisitorResult result) : m_result(result)
{
}
//---------------------------------------------------------------------------
// EnumerateIncludeDirectivesResult::operator == (static)
bool EnumerateIncludeDirectivesResult::operator==(EnumerateIncludeDirectivesResult lhs, EnumerateIncludeDirectivesResult rhs)
{
return lhs.m_result == rhs.m_result;
}
//---------------------------------------------------------------------------
// EnumerateIncludeDirectivesResult::operator != (static)
bool EnumerateIncludeDirectivesResult::operator!=(EnumerateIncludeDirectivesResult lhs, EnumerateIncludeDirectivesResult rhs)
{
return lhs.m_result != rhs.m_result;
}
//---------------------------------------------------------------------------
// EnumerateIncludeDirectivesResult::operator CXVisitorResult (static)
EnumerateIncludeDirectivesResult::operator CXVisitorResult(EnumerateIncludeDirectivesResult rhs)
{
return rhs.m_result;
}
//---------------------------------------------------------------------------
// EnumerateIncludeDirectivesResult::Equals
//
// Compares this FindCursorResult to another FindCursorResult
//
// Arguments:
//
// rhs - Right-hand EnumerateIncludeDirectivesResult to compare against
bool EnumerateIncludeDirectivesResult::Equals(EnumerateIncludeDirectivesResult rhs)
{
return (*this == rhs);
}
//---------------------------------------------------------------------------
// EnumerateIncludeDirectivesResult::Equals
//
// Overrides Object::Equals()
//
// Arguments:
//
// rhs - Right-hand object instance to compare against
bool EnumerateIncludeDirectivesResult::Equals(Object^ rhs)
{
if(Object::ReferenceEquals(rhs, nullptr)) return false;
// Convert the provided object into a EnumerateIncludeDirectivesResult instance
EnumerateIncludeDirectivesResult^ rhsref = dynamic_cast<EnumerateIncludeDirectivesResult^>(rhs);
if(rhsref == nullptr) return false;
return (*this == *rhsref);
}
//---------------------------------------------------------------------------
// EnumerateIncludeDirectivesResult::GetHashCode
//
// Overrides Object::GetHashCode()
//
// Arguments:
//
// NONE
int EnumerateIncludeDirectivesResult::GetHashCode(void)
{
return static_cast<int>(m_result).GetHashCode();
}
//---------------------------------------------------------------------------
// EnumerateIncludeDirectivesResult::ToString
//
// Overrides Object::ToString()
//
// Arguments:
//
// NONE
String^ EnumerateIncludeDirectivesResult::ToString(void)
{
switch(m_result) {
case CXVisitorResult::CXVisit_Break: return gcnew String("Break");
case CXVisitorResult::CXVisit_Continue: return gcnew String("Continue");
}
return String::Format("{0}", static_cast<int>(m_result));
}
//---------------------------------------------------------------------------
} // zuki::tools::llvm::clang
#pragma warning(pop)
| 34.094203 | 126 | 0.612115 | [
"object"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.