hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13 values | lang stringclasses 1 value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 109 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 48.5k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
cd01d8ee25017283708d0f56c5cbef66b5d03e83 | 430 | cpp | C++ | Programming Basics with C++ - September 2018/02. Lesson/Birthday/Birthday.cpp | Kazalev/SoftUni-ProgrammingBasics-CPlusPlus | 115f2618a370443be533b9958121aecca54f4649 | [
"MIT"
] | 3 | 2019-07-17T10:11:31.000Z | 2020-01-09T18:04:47.000Z | Programming Basics with C++ - September 2018/02. Lesson/Birthday/Birthday.cpp | Kazalev/SoftUni-ProgrammingBasics-CPlusPlus | 115f2618a370443be533b9958121aecca54f4649 | [
"MIT"
] | null | null | null | Programming Basics with C++ - September 2018/02. Lesson/Birthday/Birthday.cpp | Kazalev/SoftUni-ProgrammingBasics-CPlusPlus | 115f2618a370443be533b9958121aecca54f4649 | [
"MIT"
] | null | null | null | #include <iostream>
#include <cmath>
using namespace std;
int main() {
int length, width, height;
double percent;
cin >> length >> width >> height >> percent;
int volume = length * width * height;
double liters = volume * 0.001;
percent = percent * 0.01;
double realLeaters = liters * (1-percent);
cout.setf(ios::fixed);
cout.precision(3);
cout << realLeaters << endl;
return 0;
}
| 19.545455 | 48 | 0.611628 | Kazalev |
cd0309415258a6c4b4b89ac6406766474c5c26e2 | 2,594 | cpp | C++ | tests/objects_door.cpp | jd28/libnw | 15bcb23cf3ef221296b026ad8ce2909044282f2b | [
"MIT"
] | null | null | null | tests/objects_door.cpp | jd28/libnw | 15bcb23cf3ef221296b026ad8ce2909044282f2b | [
"MIT"
] | null | null | null | tests/objects_door.cpp | jd28/libnw | 15bcb23cf3ef221296b026ad8ce2909044282f2b | [
"MIT"
] | null | null | null | #include <catch2/catch.hpp>
#include <nlohmann/json.hpp>
#include <nw/kernel/Kernel.hpp>
#include <nw/objects/Door.hpp>
#include <nw/serialization/Archives.hpp>
#include <filesystem>
#include <fstream>
namespace fs = std::filesystem;
TEST_CASE("door: from_gff", "[objects]")
{
auto door = nw::kernel::objects().load(fs::path("test_data/user/development/door_ttr_002.utd"));
auto d = door.get<nw::Door>();
auto common = door.get<nw::Common>();
auto lock = door.get<nw::Lock>();
REQUIRE(common->resref == "door_ttr_002");
REQUIRE(d->appearance == 0);
REQUIRE(!d->plot);
REQUIRE(!lock->locked);
door.destruct();
}
TEST_CASE("door: to_json", "[objects]")
{
auto door = nw::kernel::objects().load(fs::path("test_data/user/development/door_ttr_002.utd"));
nlohmann::json j;
nw::kernel::objects().serialize(door, j, nw::SerializationProfile::blueprint);
auto door2 = nw::kernel::objects().deserialize(nw::ObjectType::door, j,
nw::SerializationProfile::blueprint);
REQUIRE(door2.is_alive());
nlohmann::json j2;
nw::kernel::objects().serialize(door, j2, nw::SerializationProfile::blueprint);
REQUIRE(j == j2);
std::ofstream f{"tmp/door_ttr_002.utd.json"};
f << std::setw(4) << j;
}
TEST_CASE("door: gff round trip", "[ojbects]")
{
nw::GffInputArchive g("test_data/user/development/door_ttr_002.utd");
REQUIRE(g.valid());
auto door = nw::kernel::objects().load(fs::path("test_data/user/development/door_ttr_002.utd"));
nw::GffOutputArchive oa = nw::kernel::objects().serialize(door, nw::SerializationProfile::blueprint);
oa.write_to("tmp/door_ttr_002.utd");
nw::GffInputArchive g2("tmp/door_ttr_002.utd");
REQUIRE(g2.valid());
REQUIRE(nw::gff_to_gffjson(g) == nw::gff_to_gffjson(g2));
REQUIRE(oa.header.struct_offset == g.head_->struct_offset);
REQUIRE(oa.header.struct_count == g.head_->struct_count);
REQUIRE(oa.header.field_offset == g.head_->field_offset);
REQUIRE(oa.header.field_count == g.head_->field_count);
REQUIRE(oa.header.label_offset == g.head_->label_offset);
REQUIRE(oa.header.label_count == g.head_->label_count);
REQUIRE(oa.header.field_data_offset == g.head_->field_data_offset);
REQUIRE(oa.header.field_data_count == g.head_->field_data_count);
REQUIRE(oa.header.field_idx_offset == g.head_->field_idx_offset);
REQUIRE(oa.header.field_idx_count == g.head_->field_idx_count);
REQUIRE(oa.header.list_idx_offset == g.head_->list_idx_offset);
REQUIRE(oa.header.list_idx_count == g.head_->list_idx_count);
}
| 34.586667 | 105 | 0.690439 | jd28 |
cd08ac7c2192da17a509a33caa837d1693ac8926 | 1,533 | hpp | C++ | includecpp/network.hpp | willst/libcaer | ff0e741fcfc0b59a41f87679d59620e3cc3b3a7e | [
"BSD-2-Clause"
] | 1 | 2018-12-05T16:42:26.000Z | 2018-12-05T16:42:26.000Z | includecpp/network.hpp | willst/libcaer | ff0e741fcfc0b59a41f87679d59620e3cc3b3a7e | [
"BSD-2-Clause"
] | null | null | null | includecpp/network.hpp | willst/libcaer | ff0e741fcfc0b59a41f87679d59620e3cc3b3a7e | [
"BSD-2-Clause"
] | null | null | null | #ifndef LIBCAER_NETWORK_HPP_
#define LIBCAER_NETWORK_HPP_
#include "libcaer.hpp"
#include <libcaer/network.h>
namespace libcaer {
namespace network {
class AEDAT3NetworkHeader : private aedat3_network_header {
public:
AEDAT3NetworkHeader() {
magicNumber = AEDAT3_NETWORK_MAGIC_NUMBER;
sequenceNumber = 0;
versionNumber = AEDAT3_NETWORK_VERSION;
formatNumber = 0;
sourceID = 0;
}
AEDAT3NetworkHeader(const uint8_t *h) {
struct aedat3_network_header header = caerParseNetworkHeader(h);
magicNumber = header.magicNumber;
sequenceNumber = header.sequenceNumber;
versionNumber = header.versionNumber;
formatNumber = header.formatNumber;
sourceID = header.sourceID;
}
int64_t getMagicNumber() const noexcept {
return (magicNumber);
}
bool checkMagicNumber() const noexcept {
return (magicNumber == AEDAT3_NETWORK_MAGIC_NUMBER);
}
int64_t getSequenceNumber() const noexcept {
return (sequenceNumber);
}
void incrementSequenceNumber() noexcept {
sequenceNumber++;
}
int8_t getVersionNumber() const noexcept {
return (versionNumber);
}
bool checkVersionNumber() const noexcept {
return (versionNumber == AEDAT3_NETWORK_VERSION);
}
int8_t getFormatNumber() const noexcept {
return (formatNumber);
}
void setFormatNumber(int8_t format) noexcept {
formatNumber = format;
}
int16_t getSourceID() const noexcept {
return (sourceID);
}
void setSourceID(int16_t source) noexcept {
sourceID = source;
}
};
}
}
#endif /* LIBCAER_NETWORK_HPP_ */
| 20.716216 | 66 | 0.741683 | willst |
cd08d9dda3d2b4a463ae745a2ec9ff6d3b42c633 | 18,190 | cpp | C++ | src/certificate/Certificate.cpp | LabSEC/libcryptosec | e53030ec32b52b6abeaa973a9f0bfba0eb2c2440 | [
"BSD-3-Clause"
] | 22 | 2015-08-26T16:40:59.000Z | 2022-02-22T19:52:55.000Z | src/certificate/Certificate.cpp | LabSEC/Libcryptosec | e53030ec32b52b6abeaa973a9f0bfba0eb2c2440 | [
"BSD-3-Clause"
] | 14 | 2015-09-01T00:39:22.000Z | 2018-12-17T16:24:28.000Z | src/certificate/Certificate.cpp | LabSEC/Libcryptosec | e53030ec32b52b6abeaa973a9f0bfba0eb2c2440 | [
"BSD-3-Clause"
] | 22 | 2015-08-31T19:17:37.000Z | 2021-01-04T13:38:35.000Z | #include <libcryptosec/certificate/Certificate.h>
Certificate::Certificate(X509 *cert)
{
this->cert = cert;
}
Certificate::Certificate(std::string pemEncoded)
throw (EncodeException)
{
BIO *buffer;
buffer = BIO_new(BIO_s_mem());
if (buffer == NULL)
{
throw EncodeException(EncodeException::BUFFER_CREATING, "Certificate::Certificate");
}
if ((unsigned int)(BIO_write(buffer, pemEncoded.c_str(), pemEncoded.size())) != pemEncoded.size())
{
BIO_free(buffer);
throw EncodeException(EncodeException::BUFFER_WRITING, "Certificate::Certificate");
}
this->cert = PEM_read_bio_X509(buffer, NULL, NULL, NULL);
if (this->cert == NULL)
{
BIO_free(buffer);
throw EncodeException(EncodeException::PEM_DECODE, "Certificate::Certificate");
}
BIO_free(buffer);
}
Certificate::Certificate(ByteArray &derEncoded)
throw (EncodeException)
{
BIO *buffer;
buffer = BIO_new(BIO_s_mem());
if (buffer == NULL)
{
throw EncodeException(EncodeException::BUFFER_CREATING, "Certificate::Certificate");
}
if ((unsigned int)(BIO_write(buffer, derEncoded.getDataPointer(), derEncoded.size())) != derEncoded.size())
{
BIO_free(buffer);
throw EncodeException(EncodeException::BUFFER_WRITING, "Certificate::Certificate");
}
this->cert = d2i_X509_bio(buffer, NULL); /* TODO: will the second parameter work fine ? */
if (this->cert == NULL)
{
BIO_free(buffer);
throw EncodeException(EncodeException::DER_DECODE, "Certificate::Certificate");
}
BIO_free(buffer);
}
Certificate::Certificate(const Certificate& cert)
{
this->cert = X509_dup(cert.getX509());
}
Certificate::~Certificate()
{
X509_free(this->cert);
this->cert = NULL;
}
std::string Certificate::getXmlEncoded()
{
return this->getXmlEncoded("");
}
std::string Certificate::getXmlEncoded(std::string tab)
{
std::string ret, string;
ByteArray data;
char temp[15];
long value;
std::vector<Extension *> extensions;
unsigned int i;
ret = "<?xml version=\"1.0\"?>\n";
ret += "<certificate>\n";
ret += "\t<tbsCertificate>\n";
try /* version */
{
value = this->getVersion();
sprintf(temp, "%d", (int)value);
string = temp;
ret += "\t\t<version>" + string + "</version>\n";
}
catch (...)
{
}
try /* Serial Number */
{
value = this->getSerialNumber();
sprintf(temp, "%d", (int)value);
string = temp;
ret += "\t\t<serialNumber>" + string + "</serialNumber>\n";
}
catch (...)
{
}
string = OBJ_nid2ln(OBJ_obj2nid(this->cert->sig_alg->algorithm));
ret += "\t\t<signature>" + string + "</signature>\n";
ret += "\t\t<issuer>\n";
try
{
ret += (this->getIssuer()).getXmlEncoded("\t\t\t");
}
catch (...)
{
}
ret += "\t\t</issuer>\n";
ret += "\t\t<validity>\n";
try
{
ret += "\t\t\t<notBefore>" + ((this->getNotBefore()).getXmlEncoded()) + "</notBefore>\n";
}
catch (...)
{
}
try
{
ret += "\t\t\t<notAfter>" + ((this->getNotAfter()).getXmlEncoded()) + "</notAfter>\n";
}
catch (...)
{
}
ret += "\t\t</validity>\n";
ret += "\t\t<subject>\n";
try
{
ret += (this->getSubject()).getXmlEncoded("\t\t\t");
}
catch (...)
{
}
ret += "\t\t</subject>\n";
ret += "\t\t<subjectPublicKeyInfo>\n";
string = OBJ_nid2ln(OBJ_obj2nid(this->cert->cert_info->key->algor->algorithm));
ret += "\t\t\t<algorithm>" + string + "</algorithm>\n";
data = ByteArray(this->cert->cert_info->key->public_key->data, this->cert->cert_info->key->public_key->length);
string = Base64::encode(data);
ret += "\t\t\t<subjectPublicKey>" + string + "</subjectPublicKey>\n";
ret += "\t\t</subjectPublicKeyInfo>\n";
if (this->cert->cert_info->issuerUID)
{
data = ByteArray(this->cert->cert_info->issuerUID->data, this->cert->cert_info->issuerUID->length);
string = Base64::encode(data);
ret += "\t\t<issuerUniqueID>" + string + "</issuerUniqueID>\n";
}
if (this->cert->cert_info->subjectUID)
{
data = ByteArray(this->cert->cert_info->subjectUID->data, this->cert->cert_info->subjectUID->length);
string = Base64::encode(data);
ret += "\t\t<subjectUniqueID>" + string + "</subjectUniqueID>\n";
}
ret += "\t\t<extensions>\n";
extensions = this->getExtensions();
for (i=0;i<extensions.size();i++)
{
ret += extensions.at(i)->getXmlEncoded("\t\t\t");
delete extensions.at(i);
}
ret += "\t\t</extensions>\n";
ret += "\t</tbsCertificate>\n";
ret += "\t<signatureAlgorithm>\n";
string = OBJ_nid2ln(OBJ_obj2nid(this->cert->sig_alg->algorithm));
ret += "\t\t<algorithm>" + string + "</algorithm>\n";
ret += "\t</signatureAlgorithm>\n";
data = ByteArray(this->cert->signature->data, this->cert->signature->length);
string = Base64::encode(data);
ret += "\t<signatureValue>" + string + "</signatureValue>\n";
ret += "</certificate>\n";
return ret;
}
std::string Certificate::toXml(std::string tab)
{
std::string ret, string;
ByteArray data;
char temp[15];
long value;
std::vector<Extension *> extensions;
unsigned int i;
ret = "<?xml version=\"1.0\"?>\n";
ret += "<certificate>\n";
ret += "\t<tbsCertificate>\n";
try /* version */
{
value = this->getVersion();
sprintf(temp, "%d", (int)value);
string = temp;
ret += "\t\t<version>" + string + "</version>\n";
}
catch (...)
{
}
try /* Serial Number */
{
ret += "\t\t<serialNumber>" + this->getSerialNumberBigInt().toDec() + "</serialNumber>\n";
}
catch (...)
{
}
string = OBJ_nid2ln(OBJ_obj2nid(this->cert->sig_alg->algorithm));
ret += "\t\t<signature>" + string + "</signature>\n";
ret += "\t\t<issuer>\n";
try
{
ret += (this->getIssuer()).getXmlEncoded("\t\t\t");
}
catch (...)
{
}
ret += "\t\t</issuer>\n";
ret += "\t\t<validity>\n";
try
{
ret += "\t\t\t<notBefore>" + ((this->getNotBefore()).getXmlEncoded()) + "</notBefore>\n";
}
catch (...)
{
}
try
{
ret += "\t\t\t<notAfter>" + ((this->getNotAfter()).getXmlEncoded()) + "</notAfter>\n";
}
catch (...)
{
}
ret += "\t\t</validity>\n";
ret += "\t\t<subject>\n";
try
{
ret += (this->getSubject()).getXmlEncoded("\t\t\t");
}
catch (...)
{
}
ret += "\t\t</subject>\n";
ret += "\t\t<subjectPublicKeyInfo>\n";
string = OBJ_nid2ln(OBJ_obj2nid(this->cert->cert_info->key->algor->algorithm));
ret += "\t\t\t<algorithm>" + string + "</algorithm>\n";
data = ByteArray(this->cert->cert_info->key->public_key->data, this->cert->cert_info->key->public_key->length);
string = Base64::encode(data);
ret += "\t\t\t<subjectPublicKey>" + string + "</subjectPublicKey>\n";
ret += "\t\t</subjectPublicKeyInfo>\n";
if (this->cert->cert_info->issuerUID)
{
data = ByteArray(this->cert->cert_info->issuerUID->data, this->cert->cert_info->issuerUID->length);
string = Base64::encode(data);
ret += "\t\t<issuerUniqueID>" + string + "</issuerUniqueID>\n";
}
if (this->cert->cert_info->subjectUID)
{
data = ByteArray(this->cert->cert_info->subjectUID->data, this->cert->cert_info->subjectUID->length);
string = Base64::encode(data);
ret += "\t\t<subjectUniqueID>" + string + "</subjectUniqueID>\n";
}
ret += "\t\t<extensions>\n";
extensions = this->getExtensions();
for (i=0;i<extensions.size();i++)
{
ret += extensions.at(i)->toXml("\t\t\t");
delete extensions.at(i);
}
ret += "\t\t</extensions>\n";
ret += "\t</tbsCertificate>\n";
ret += "\t<signatureAlgorithm>\n";
string = OBJ_nid2ln(OBJ_obj2nid(this->cert->sig_alg->algorithm));
ret += "\t\t<algorithm>" + string + "</algorithm>\n";
ret += "\t</signatureAlgorithm>\n";
data = ByteArray(this->cert->signature->data, this->cert->signature->length);
string = Base64::encode(data);
ret += "\t<signatureValue>" + string + "</signatureValue>\n";
ret += "</certificate>\n";
return ret;
}
std::string Certificate::getPemEncoded() const
throw (EncodeException)
{
BIO *buffer;
int ndata, wrote;
std::string ret;
ByteArray *retTemp;
unsigned char *data;
buffer = BIO_new(BIO_s_mem());
if (buffer == NULL)
{
throw EncodeException(EncodeException::BUFFER_CREATING, "Certificate::getPemEncoded");
}
wrote = PEM_write_bio_X509(buffer, this->cert);
if (!wrote)
{
BIO_free(buffer);
throw EncodeException(EncodeException::PEM_ENCODE, "Certificate::getPemEncoded");
}
ndata = BIO_get_mem_data(buffer, &data);
if (ndata <= 0)
{
BIO_free(buffer);
throw EncodeException(EncodeException::BUFFER_READING, "Certificate::getPemEncoded");
}
retTemp = new ByteArray(data, ndata);
ret = retTemp->toString();
delete retTemp;
BIO_free(buffer);
return ret;
}
ByteArray Certificate::getDerEncoded() const
throw (EncodeException)
{
BIO *buffer;
int ndata, wrote;
ByteArray ret;
unsigned char *data;
buffer = BIO_new(BIO_s_mem());
if (buffer == NULL)
{
throw EncodeException(EncodeException::BUFFER_CREATING, "Certificate::getDerEncoded");
}
wrote = i2d_X509_bio(buffer, this->cert);
if (!wrote)
{
BIO_free(buffer);
throw EncodeException(EncodeException::DER_ENCODE, "Certificate::getDerEncoded");
}
ndata = BIO_get_mem_data(buffer, &data);
if (ndata <= 0)
{
BIO_free(buffer);
throw EncodeException(EncodeException::BUFFER_READING, "Certificate::getDerEncoded");
}
ret = ByteArray(data, ndata);
BIO_free(buffer);
return ret;
}
long int Certificate::getSerialNumber() throw (CertificationException)
{
ASN1_INTEGER *asn1Int;
long ret;
if (this->cert == NULL)
{
throw CertificationException(CertificationException::INVALID_CERTIFICATE, "Certificate::getSerialNumber");
}
/* Here, we have a problem!!! the return value -1 can be error and a valid value. */
asn1Int = X509_get_serialNumber(this->cert);
if (asn1Int == NULL)
{
throw CertificationException(CertificationException::SET_NO_VALUE, "Certificate::getSerialNumber");
}
if (asn1Int->data == NULL)
{
throw CertificationException(CertificationException::INTERNAL_ERROR, "Certificate::getSerialNumber");
}
ret = ASN1_INTEGER_get(asn1Int);
if (ret < 0L)
{
throw CertificationException(CertificationException::INTERNAL_ERROR, "Certificate::getSerialNumber");
}
return ret;
}
BigInteger Certificate::getSerialNumberBigInt() throw (CertificationException)
{
ASN1_INTEGER *asn1Int;
BigInteger ret;
if (this->cert == NULL)
{
throw CertificationException(CertificationException::INVALID_CERTIFICATE, "Certificate::getSerialNumberBytes");
}
/* Here, we have a problem!!! the return value -1 can be error and a valid value. */
asn1Int = X509_get_serialNumber(this->cert);
if (asn1Int == NULL)
{
throw CertificationException(CertificationException::SET_NO_VALUE, "Certificate::getSerialNumberBytes");
}
if (asn1Int->data == NULL)
{
throw CertificationException(CertificationException::INTERNAL_ERROR, "Certificate::getSerialNumberBytes");
}
ret = BigInteger(asn1Int);
return ret;
}
MessageDigest::Algorithm Certificate::getMessageDigestAlgorithm()
throw (MessageDigestException)
{
MessageDigest::Algorithm ret;
ret = MessageDigest::getMessageDigest(OBJ_obj2nid(this->cert->sig_alg->algorithm));
return ret;
}
PublicKey* Certificate::getPublicKey() throw (CertificationException, AsymmetricKeyException)
{
EVP_PKEY *key;
PublicKey *ret;
if (this->cert == NULL)
{
throw CertificationException(CertificationException::INVALID_CERTIFICATE, "Certificate::getPublicKey");
}
key = X509_get_pubkey(this->cert);
if (key == NULL)
{
throw CertificationException(CertificationException::SET_NO_VALUE, "Certificate::getPublicKey");
}
try
{
ret = new PublicKey(key);
}
catch (...)
{
EVP_PKEY_free(key);
throw;
}
return ret;
}
ByteArray Certificate::getPublicKeyInfo()
throw (CertificationException)
{
ByteArray ret;
unsigned int size;
ASN1_BIT_STRING *temp;
if (!this->cert->cert_info->key)
{
throw CertificationException(CertificationException::SET_NO_VALUE, "Certificate::getPublicKeyInfo");
}
temp = this->cert->cert_info->key->public_key;
ret = ByteArray(EVP_MAX_MD_SIZE);
EVP_Digest(temp->data, temp->length, ret.getDataPointer(), &size, EVP_sha1(), NULL);
ret = ByteArray(ret.getDataPointer(), size);
return ret;
}
long Certificate::getVersion() throw (CertificationException)
{
long ret;
/* Here, we have a problem!!! the return value 0 can be error and a valid value. */
if (this->cert == NULL)
{
throw CertificationException(CertificationException::INVALID_CERTIFICATE, "Certificate::getVersion");
}
ret = X509_get_version(this->cert);
if (ret < 0 || ret > 2)
{
throw CertificationException(CertificationException::SET_NO_VALUE, "Certificate::getVersion");
}
return ret;
}
DateTime Certificate::getNotBefore()
{
ASN1_TIME *asn1Time;
asn1Time = X509_get_notBefore(this->cert);
return DateTime(asn1Time);
}
DateTime Certificate::getNotAfter()
{
ASN1_TIME *asn1Time;
asn1Time = X509_get_notAfter(this->cert);
return DateTime(asn1Time);
}
RDNSequence Certificate::getIssuer()
{
RDNSequence name;
if (this->cert)
{
name = RDNSequence(X509_get_issuer_name(this->cert));
}
return name;
}
RDNSequence Certificate::getSubject()
{
RDNSequence name;
if (this->cert)
{
name = RDNSequence(X509_get_subject_name(this->cert));
}
return name;
}
std::vector<Extension*> Certificate::getExtension(Extension::Name extensionName)
{
int next, i;
X509_EXTENSION *ext;
std::vector<Extension *> ret;
Extension *oneExt;
next = X509_get_ext_count(this->cert);
for (i=0;i<next;i++)
{
ext = X509_get_ext(this->cert, i);
if (Extension::getName(ext) == extensionName)
{
switch (Extension::getName(ext))
{
case Extension::KEY_USAGE:
oneExt = new KeyUsageExtension(ext);
break;
case Extension::EXTENDED_KEY_USAGE:
oneExt = new ExtendedKeyUsageExtension(ext);
break;
case Extension::AUTHORITY_KEY_IDENTIFIER:
oneExt = new AuthorityKeyIdentifierExtension(ext);
break;
case Extension::CRL_DISTRIBUTION_POINTS:
oneExt = new CRLDistributionPointsExtension(ext);
break;
case Extension::AUTHORITY_INFORMATION_ACCESS:
oneExt = new AuthorityInformationAccessExtension(ext);
break;
case Extension::BASIC_CONSTRAINTS:
oneExt = new BasicConstraintsExtension(ext);
break;
case Extension::CERTIFICATE_POLICIES:
oneExt = new CertificatePoliciesExtension(ext);
break;
case Extension::ISSUER_ALTERNATIVE_NAME:
oneExt = new IssuerAlternativeNameExtension(ext);
break;
case Extension::SUBJECT_ALTERNATIVE_NAME:
oneExt = new SubjectAlternativeNameExtension(ext);
break;
case Extension::SUBJECT_INFORMATION_ACCESS:
oneExt = new SubjectInformationAccessExtension(ext);
break;
case Extension::SUBJECT_KEY_IDENTIFIER:
oneExt = new SubjectKeyIdentifierExtension(ext);
break;
default:
oneExt = new Extension(ext);
break;
}
ret.push_back(oneExt);
}
}
return ret;
}
std::vector<Extension*> Certificate::getExtensions()
{
int next, i;
X509_EXTENSION *ext;
std::vector<Extension *> ret;
Extension *oneExt;
next = X509_get_ext_count(this->cert);
for (i=0;i<next;i++)
{
ext = X509_get_ext(this->cert, i);
switch (Extension::getName(ext))
{
case Extension::KEY_USAGE:
oneExt = new KeyUsageExtension(ext);
break;
case Extension::EXTENDED_KEY_USAGE:
oneExt = new ExtendedKeyUsageExtension(ext);
break;
case Extension::AUTHORITY_KEY_IDENTIFIER:
oneExt = new AuthorityKeyIdentifierExtension(ext);
break;
case Extension::CRL_DISTRIBUTION_POINTS:
oneExt = new CRLDistributionPointsExtension(ext);
break;
case Extension::AUTHORITY_INFORMATION_ACCESS:
oneExt = new AuthorityInformationAccessExtension(ext);
break;
case Extension::BASIC_CONSTRAINTS:
oneExt = new BasicConstraintsExtension(ext);
break;
case Extension::CERTIFICATE_POLICIES:
oneExt = new CertificatePoliciesExtension(ext);
break;
case Extension::ISSUER_ALTERNATIVE_NAME:
oneExt = new IssuerAlternativeNameExtension(ext);
break;
case Extension::SUBJECT_ALTERNATIVE_NAME:
oneExt = new SubjectAlternativeNameExtension(ext);
break;
case Extension::SUBJECT_INFORMATION_ACCESS:
oneExt = new SubjectInformationAccessExtension(ext);
break;
case Extension::SUBJECT_KEY_IDENTIFIER:
oneExt = new SubjectKeyIdentifierExtension(ext);
break;
default:
oneExt = new Extension(ext);
break;
}
ret.push_back(oneExt);
}
return ret;
}
std::vector<Extension *> Certificate::getUnknownExtensions()
{
int next, i;
X509_EXTENSION *ext;
std::vector<Extension *> ret;
Extension *oneExt;
next = X509_get_ext_count(this->cert);
for (i=0;i<next;i++)
{
ext = X509_get_ext(this->cert, i);
switch (Extension::getName(ext))
{
case Extension::UNKNOWN:
oneExt = new Extension(ext);
ret.push_back(oneExt);
default:
break;
}
}
return ret;
}
ByteArray Certificate::getFingerPrint(MessageDigest::Algorithm algorithm) const
throw (CertificationException, EncodeException, MessageDigestException)
{
ByteArray ret, derEncoded;
MessageDigest messageDigest;
derEncoded = this->getDerEncoded();
messageDigest.init(algorithm);
ret = messageDigest.doFinal(derEncoded);
return ret;
}
bool Certificate::verify(PublicKey &publicKey)
{
int ok;
ok = X509_verify(this->cert, publicKey.getEvpPkey());
return (ok == 1);
}
X509* Certificate::getX509() const
{
return this->cert;
}
CertificateRequest Certificate::getNewCertificateRequest(PrivateKey &privateKey, MessageDigest::Algorithm algorithm)
throw (CertificationException)
{
X509_REQ* req = NULL;
req = X509_to_X509_REQ(this->cert, privateKey.getEvpPkey(), MessageDigest::getMessageDigest(algorithm));
if (!req)
{
throw CertificationException(CertificationException::INTERNAL_ERROR, "Certificate::getNewCertificateRequest");
}
return CertificateRequest(req);
}
Certificate& Certificate::operator =(const Certificate& value)
{
if (this->cert)
{
X509_free(this->cert);
}
this->cert = X509_dup(value.getX509());
return (*this);
}
bool Certificate::operator ==(const Certificate& value)
{
return X509_cmp(this->cert, value.getX509()) == 0;
}
bool Certificate::operator !=(const Certificate& value)
{
return !this->operator==(value);
}
| 26.060172 | 116 | 0.682298 | LabSEC |
cd0b536e305307c3d3c26556015131863c3b4d2f | 2,156 | cpp | C++ | leetcode/problems/medium/918-maximum-sum-circular-subarray.cpp | wingkwong/competitive-programming | e8bf7aa32e87b3a020b63acac20e740728764649 | [
"MIT"
] | 18 | 2020-08-27T05:27:50.000Z | 2022-03-08T02:56:48.000Z | leetcode/problems/medium/918-maximum-sum-circular-subarray.cpp | wingkwong/competitive-programming | e8bf7aa32e87b3a020b63acac20e740728764649 | [
"MIT"
] | null | null | null | leetcode/problems/medium/918-maximum-sum-circular-subarray.cpp | wingkwong/competitive-programming | e8bf7aa32e87b3a020b63acac20e740728764649 | [
"MIT"
] | 1 | 2020-10-13T05:23:58.000Z | 2020-10-13T05:23:58.000Z | /*
Maximum Sum Circular Subarray
Given a circular array C of integers represented by A, find the maximum possible sum of a non-empty subarray of C.
Here, a circular array means the end of the array connects to the beginning of the array. (Formally, C[i] = A[i] when 0 <= i < A.length, and C[i+A.length] = C[i] when i >= 0.)
Also, a subarray may only include each element of the fixed buffer A at most once. (Formally, for a subarray C[i], C[i+1], ..., C[j], there does not exist i <= k1, k2 <= j with k1 % A.length = k2 % A.length.)
Example 1:
Input: [1,-2,3,-2]
Output: 3
Explanation: Subarray [3] has maximum sum 3
Example 2:
Input: [5,-3,5]
Output: 10
Explanation: Subarray [5,5] has maximum sum 5 + 5 = 10
Example 3:
Input: [3,-1,2,-1]
Output: 4
Explanation: Subarray [2,-1,3] has maximum sum 2 + (-1) + 3 = 4
Example 4:
Input: [3,-2,2,-3]
Output: 3
Explanation: Subarray [3] and [3,-2,2] both have maximum sum 3
Example 5:
Input: [-2,-3,-1]
Output: -1
Explanation: Subarray [-1] has maximum sum -1
Note:
-30000 <= A[i] <= 30000
1 <= A.length <= 30000
*/
class Solution {
public:
int maxSubarraySumCircular(vector<int>& A) {
int total_sum = 0, global_max = INT_MIN, global_min = INT_MAX,
local_min = 0, local_max = 0;
// kadane's algorithm
for (int a : A) {
local_max = max(a, local_max + a);
global_max = max(global_max, local_max);
local_min = min(a, local_min + a);
global_min = min(global_min, local_min);
total_sum += a;
}
// case 1: max subarray is not circular
// ______________________________
// | | Max subarray| |
// 0 --------------------------- N-1
// case 2: max subarray is circular
// _____________________________
// | | Max su|barray| |
// 0 -----------|N-1------------ 2N-1
// which is equal to
// ______________________________
// | max | Min subarray| subarray|
// 0 --------------------------- N-1
// max(the max subarray sum, the total sum - the min subarray sum)
return global_max > 0 ? max(global_max, total_sum - global_min)
: global_max;
}
}; | 28.746667 | 209 | 0.600186 | wingkwong |
cd0c3a8cc403b314828878a87f5691eb2244b298 | 27,488 | cpp | C++ | src/align.cpp | ezracb/librealsense | c595bc426e1b258c7af1625cabb8e9ccb9335a8b | [
"BSD-2-Clause",
"Apache-2.0"
] | null | null | null | src/align.cpp | ezracb/librealsense | c595bc426e1b258c7af1625cabb8e9ccb9335a8b | [
"BSD-2-Clause",
"Apache-2.0"
] | null | null | null | src/align.cpp | ezracb/librealsense | c595bc426e1b258c7af1625cabb8e9ccb9335a8b | [
"BSD-2-Clause",
"Apache-2.0"
] | null | null | null | // License: Apache 2.0. See LICENSE file in root directory.
// Copyright(c) 2015 Intel Corporation. All Rights Reserved.
#include "../include/librealsense2/rs.hpp"
#include "../include/librealsense2/rsutil.h"
#include "core/video.h"
#include "align.h"
#include "archive.h"
#include "context.h"
#include "environment.h"
namespace librealsense
{
template<class MAP_DEPTH> void deproject_depth(float * points, const rs2_intrinsics & intrin, const uint16_t * depth, MAP_DEPTH map_depth)
{
for (int y = 0; y<intrin.height; ++y)
{
for (int x = 0; x<intrin.width; ++x)
{
const float pixel[] = { (float)x, (float)y };
rs2_deproject_pixel_to_point(points, &intrin, pixel, map_depth(*depth++));
points += 3;
}
}
}
const float3 * depth_to_points(uint8_t* image, const rs2_intrinsics &depth_intrinsics, const uint16_t * depth_image, float depth_scale)
{
deproject_depth(reinterpret_cast<float *>(image), depth_intrinsics, depth_image, [depth_scale](uint16_t z) { return depth_scale * z; });
return reinterpret_cast<float3 *>(image);
}
float3 transform(const rs2_extrinsics *extrin, const float3 &point) { float3 p = {}; rs2_transform_point_to_point(&p.x, extrin, &point.x); return p; }
float2 project(const rs2_intrinsics *intrin, const float3 & point) { float2 pixel = {}; rs2_project_point_to_pixel(&pixel.x, intrin, &point.x); return pixel; }
float2 pixel_to_texcoord(const rs2_intrinsics *intrin, const float2 & pixel) { return{ (pixel.x + 0.5f) / intrin->width, (pixel.y + 0.5f) / intrin->height }; }
float2 project_to_texcoord(const rs2_intrinsics *intrin, const float3 & point) { return pixel_to_texcoord(intrin, project(intrin, point)); }
void processing_block::set_processing_callback(frame_processor_callback_ptr callback)
{
std::lock_guard<std::mutex> lock(_mutex);
_callback = callback;
}
void processing_block::set_output_callback(frame_callback_ptr callback)
{
_source.set_callback(callback);
}
processing_block::processing_block()
: _source_wrapper(_source)
{
_source.init(std::make_shared<metadata_parser_map>());
}
void processing_block::invoke(frame_holder f)
{
auto callback = _source.begin_callback();
try
{
if (_callback)
{
frame_interface* ptr = nullptr;
std::swap(f.frame, ptr);
_callback->on_frame((rs2_frame*)ptr, _source_wrapper.get_c_wrapper());
}
}
catch(...)
{
LOG_ERROR("Exception was thrown during user processing callback!");
}
}
void synthetic_source::frame_ready(frame_holder result)
{
_actual_source.invoke_callback(std::move(result));
}
frame_interface* synthetic_source::allocate_points(std::shared_ptr<stream_profile_interface> stream, frame_interface* original)
{
auto vid_stream = dynamic_cast<video_stream_profile_interface*>(stream.get());
if (vid_stream)
{
frame_additional_data data{};
data.frame_number = original->get_frame_number();
data.timestamp = original->get_frame_timestamp();
data.timestamp_domain = original->get_frame_timestamp_domain();
data.metadata_size = 0;
data.system_time = _actual_source.get_time();
auto res = _actual_source.alloc_frame(RS2_EXTENSION_POINTS, vid_stream->get_width() * vid_stream->get_height() * sizeof(float) * 5, data, true);
if (!res) throw wrong_api_call_sequence_exception("Out of frame resources!");
res->set_sensor(original->get_sensor());
res->set_stream(stream);
return res;
}
return nullptr;
}
frame_interface* synthetic_source::allocate_video_frame(std::shared_ptr<stream_profile_interface> stream,
frame_interface* original,
int new_bpp,
int new_width,
int new_height,
int new_stride,
rs2_extension frame_type)
{
video_frame* vf = nullptr;
if (new_bpp == 0 || (new_width == 0 && new_stride == 0) || new_height == 0)
{
// If the user wants to delegate width, height and etc to original frame, it must be a video frame
if (!rs2_is_frame_extendable_to((rs2_frame*)original, RS2_EXTENSION_VIDEO_FRAME, nullptr))
{
throw std::runtime_error("If original frame is not video frame, you must specify new bpp, width/stide and height!");
}
vf = static_cast<video_frame*>(original);
}
frame_additional_data data{};
data.frame_number = original->get_frame_number();
data.timestamp = original->get_frame_timestamp();
data.timestamp_domain = original->get_frame_timestamp_domain();
data.metadata_size = 0;
data.system_time = _actual_source.get_time();
auto width = new_width;
auto height = new_height;
auto bpp = new_bpp * 8;
auto stride = new_stride;
if (bpp == 0)
{
bpp = vf->get_bpp();
}
if (width == 0 && stride == 0)
{
width = vf->get_width();
stride = width * bpp / 8;
}
else if (width == 0)
{
width = stride * 8 / bpp;
}
else if (stride == 0)
{
stride = width * bpp / 8;
}
if (height == 0)
{
height = vf->get_height();
}
auto res = _actual_source.alloc_frame(frame_type, stride * height, data, true);
if (!res) throw wrong_api_call_sequence_exception("Out of frame resources!");
vf = static_cast<video_frame*>(res);
vf->assign(width, height, stride, bpp);
vf->set_sensor(original->get_sensor());
res->set_stream(stream);
if (frame_type == RS2_EXTENSION_DEPTH_FRAME)
{
original->acquire();
(dynamic_cast<depth_frame*>(res))->set_original(original);
}
return res;
}
int get_embeded_frames_size(frame_interface* f)
{
if (f == nullptr) return 0;
if (auto c = dynamic_cast<composite_frame*>(f))
return static_cast<int>(c->get_embedded_frames_count());
return 1;
}
void copy_frames(frame_holder from, frame_interface**& target)
{
if (auto comp = dynamic_cast<composite_frame*>(from.frame))
{
auto frame_buff = comp->get_frames();
for (size_t i = 0; i < comp->get_embedded_frames_count(); i++)
{
std::swap(*target, frame_buff[i]);
target++;
}
from.frame->disable_continuation();
}
else
{
*target = nullptr; // "move" the frame ref into target
std::swap(*target, from.frame);
target++;
}
}
frame_interface* synthetic_source::allocate_composite_frame(std::vector<frame_holder> holders)
{
frame_additional_data d {};
auto req_size = 0;
for (auto&& f : holders)
req_size += get_embeded_frames_size(f.frame);
auto res = _actual_source.alloc_frame(RS2_EXTENSION_COMPOSITE_FRAME, req_size * sizeof(rs2_frame*), d, true);
if (!res) return nullptr;
auto cf = static_cast<composite_frame*>(res);
auto frames = cf->get_frames();
for (auto&& f : holders)
copy_frames(std::move(f), frames);
frames -= req_size;
auto releaser = [frames, req_size]()
{
for (auto i = 0; i < req_size; i++)
{
frames[i]->release();
frames[i] = nullptr;
}
};
frame_continuation release_frames(releaser, nullptr);
cf->attach_continuation(std::move(release_frames));
cf->set_stream(cf->first()->get_stream());
return res;
}
pointcloud::pointcloud()
:_depth_intrinsics_ptr(nullptr),
_depth_units_ptr(nullptr),
_mapped_intrinsics_ptr(nullptr),
_extrinsics_ptr(nullptr),
_mapped(nullptr),
_depth_stream_uid(0)
{
auto on_frame = [this](rs2::frame f, const rs2::frame_source& source)
{
auto inspect_depth_frame = [this](const rs2::frame& depth)
{
auto depth_frame = (frame_interface*)depth.get();
std::lock_guard<std::mutex> lock(_mutex);
if (!_stream.get() || _depth_stream_uid != depth_frame->get_stream()->get_unique_id())
{
_stream = depth_frame->get_stream()->clone();
_depth_stream_uid = depth_frame->get_stream()->get_unique_id();
environment::get_instance().get_extrinsics_graph().register_same_extrinsics(*_stream, *depth_frame->get_stream());
_depth_intrinsics_ptr = nullptr;
_depth_units_ptr = nullptr;
}
bool found_depth_intrinsics = false;
bool found_depth_units = false;
if (!_depth_intrinsics_ptr)
{
auto stream_profile = depth_frame->get_stream();
if (auto video = dynamic_cast<video_stream_profile_interface*>(stream_profile.get()))
{
_depth_intrinsics = video->get_intrinsics();
_depth_intrinsics_ptr = &_depth_intrinsics;
found_depth_intrinsics = true;
}
}
if (!_depth_units_ptr)
{
auto sensor = depth_frame->get_sensor();
_depth_units = sensor->get_option(RS2_OPTION_DEPTH_UNITS).query();
_depth_units_ptr = &_depth_units;
found_depth_units = true;
}
if (found_depth_units != found_depth_intrinsics)
{
throw wrong_api_call_sequence_exception("Received depth frame that doesn't provide either intrinsics or depth units!");
}
};
auto inspect_other_frame = [this](const rs2::frame& other)
{
auto other_frame = (frame_interface*)other.get();
std::lock_guard<std::mutex> lock(_mutex);
if (_mapped.get() != other_frame->get_stream().get())
{
_mapped = other_frame->get_stream();
_mapped_intrinsics_ptr = nullptr;
_extrinsics_ptr = nullptr;
}
if (!_mapped_intrinsics_ptr)
{
if (auto video = dynamic_cast<video_stream_profile_interface*>(_mapped.get()))
{
_mapped_intrinsics = video->get_intrinsics();
_mapped_intrinsics_ptr = &_mapped_intrinsics;
}
}
if (_stream && !_extrinsics_ptr)
{
if ( environment::get_instance().get_extrinsics_graph().try_fetch_extrinsics(
*_stream, *other_frame->get_stream(), &_extrinsics
))
{
_extrinsics_ptr = &_extrinsics;
}
}
};
auto process_depth_frame = [this](const rs2::depth_frame& depth)
{
frame_holder res = get_source().allocate_points(_stream, (frame_interface*)depth.get());
auto pframe = (points*)(res.frame);
auto depth_data = (const uint16_t*)depth.get_data();
//auto original_depth = ((depth_frame*)depth.get())->get_original_depth();
//if (original_depth) depth_data = (const uint16_t*)original_depth->get_frame_data();
auto points = depth_to_points((uint8_t*)pframe->get_vertices(), *_depth_intrinsics_ptr, depth_data, *_depth_units_ptr);
auto vid_frame = depth.as<rs2::video_frame>();
float2* tex_ptr = pframe->get_texture_coordinates();
rs2_intrinsics mapped_intr;
rs2_extrinsics extr;
bool map_texture = false;
{
std::lock_guard<std::mutex> lock(_mutex);
if (_extrinsics_ptr && _mapped_intrinsics_ptr)
{
mapped_intr = *_mapped_intrinsics_ptr;
extr = *_extrinsics_ptr;
map_texture = true;
}
}
if (map_texture)
{
for (int y = 0; y < vid_frame.get_height(); ++y)
{
for (int x = 0; x < vid_frame.get_width(); ++x)
{
if (points->z)
{
auto trans = transform(&extr, *points);
auto tex_xy = project_to_texcoord(&mapped_intr, trans);
*tex_ptr = tex_xy;
}
else
{
*tex_ptr = { 0.f, 0.f };
}
++points;
++tex_ptr;
}
}
}
get_source().frame_ready(std::move(res));
};
if (auto composite = f.as<rs2::frameset>())
{
auto depth = composite.first_or_default(RS2_STREAM_DEPTH);
if (depth)
{
inspect_depth_frame(depth);
process_depth_frame(depth);
}
else
{
composite.foreach(inspect_other_frame);
}
}
else
{
if (f.get_profile().stream_type() == RS2_STREAM_DEPTH)
{
inspect_depth_frame(f);
process_depth_frame(f);
}
else
{
inspect_other_frame(f);
}
}
};
auto callback = new rs2::frame_processor_callback<decltype(on_frame)>(on_frame);
processing_block::set_processing_callback(std::shared_ptr<rs2_frame_processor_callback>(callback));
}
//void colorize::set_color_map(rs2_color_map cm)
//{
// std::lock_guard<std::mutex> lock(_mutex);
// switch(cm)
// {
// case RS2_COLOR_MAP_CLASSIC:
// _cm = &classic;
// break;
// case RS2_COLOR_MAP_JET:
// _cm = &jet;
// break;
// case RS2_COLOR_MAP_HSV:
// _cm = &hsv;
// break;
// default:
// _cm = &classic;
// }
//}
//void colorize::histogram_equalization(bool enable)
//{
// std::lock_guard<std::mutex> lock(_mutex);
// _equalize = enable;
//}
//colorize::colorize(std::shared_ptr<uvc::time_service> ts)
// : processing_block(RS2_EXTENSION_VIDEO_FRAME, ts), _cm(&classic), _equalize(true)
//{
// auto on_frame = [this](std::vector<rs2::frame> frames, const rs2::frame_source& source)
// {
// std::lock_guard<std::mutex> lock(_mutex);
// for (auto&& f : frames)
// {
// if (f.get_stream_type() == RS2_STREAM_DEPTH)
// {
// const auto max_depth = 0x10000;
// static uint32_t histogram[max_depth];
// memset(histogram, 0, sizeof(histogram));
// auto vf = f.as<video_frame>();
// auto width = vf.get_width();
// auto height = vf.get_height();
// auto depth_image = vf.get_frame_data();
// for (auto i = 0; i < width*height; ++i) ++histogram[depth_image[i]];
// for (auto i = 2; i < max_depth; ++i) histogram[i] += histogram[i - 1]; // Build a cumulative histogram for the indices in [1,0xFFFF]
// for (auto i = 0; i < width*height; ++i)
// {
// auto d = depth_image[i];
// //if (d)
// //{
// // auto f = histogram[d] / (float)histogram[0xFFFF]; // 0-255 based on histogram location
// // auto c = map.get(f);
// // rgb_image[i * 3 + 0] = c.x;
// // rgb_image[i * 3 + 1] = c.y;
// // rgb_image[i * 3 + 2] = c.z;
// //}
// //else
// //{
// // rgb_image[i * 3 + 0] = 0;
// // rgb_image[i * 3 + 1] = 0;
// // rgb_image[i * 3 + 2] = 0;
// //}
// }
// }
// }
// };
// auto callback = new rs2::frame_processor_callback<decltype(on_frame)>(on_frame);
// set_processing_callback(std::shared_ptr<rs2_frame_processor_callback>(callback));
//}
template<class GET_DEPTH, class TRANSFER_PIXEL>
void align_images(const rs2_intrinsics & depth_intrin, const rs2_extrinsics & depth_to_other,
const rs2_intrinsics & other_intrin, GET_DEPTH get_depth, TRANSFER_PIXEL transfer_pixel)
{
// Iterate over the pixels of the depth image
#pragma omp parallel for schedule(dynamic)
for (int depth_y = 0; depth_y < depth_intrin.height; ++depth_y)
{
int depth_pixel_index = depth_y * depth_intrin.width;
for (int depth_x = 0; depth_x < depth_intrin.width; ++depth_x, ++depth_pixel_index)
{
// Skip over depth pixels with the value of zero, we have no depth data so we will not write anything into our aligned images
if (float depth = get_depth(depth_pixel_index))
{
// Map the top-left corner of the depth pixel onto the other image
float depth_pixel[2] = { depth_x - 0.5f, depth_y - 0.5f }, depth_point[3], other_point[3], other_pixel[2];
rs2_deproject_pixel_to_point(depth_point, &depth_intrin, depth_pixel, depth);
rs2_transform_point_to_point(other_point, &depth_to_other, depth_point);
rs2_project_point_to_pixel(other_pixel, &other_intrin, other_point);
const int other_x0 = static_cast<int>(other_pixel[0] + 0.5f);
const int other_y0 = static_cast<int>(other_pixel[1] + 0.5f);
// Map the bottom-right corner of the depth pixel onto the other image
depth_pixel[0] = depth_x + 0.5f; depth_pixel[1] = depth_y + 0.5f;
rs2_deproject_pixel_to_point(depth_point, &depth_intrin, depth_pixel, depth);
rs2_transform_point_to_point(other_point, &depth_to_other, depth_point);
rs2_project_point_to_pixel(other_pixel, &other_intrin, other_point);
const int other_x1 = static_cast<int>(other_pixel[0] + 0.5f);
const int other_y1 = static_cast<int>(other_pixel[1] + 0.5f);
if (other_x0 < 0 || other_y0 < 0 || other_x1 >= other_intrin.width || other_y1 >= other_intrin.height)
continue;
// Transfer between the depth pixels and the pixels inside the rectangle on the other image
for (int y = other_y0; y <= other_y1; ++y)
{
for (int x = other_x0; x <= other_x1; ++x)
{
transfer_pixel(depth_pixel_index, y * other_intrin.width + x);
}
}
}
}
}
}
align::align(rs2_stream to_stream)
: _depth_intrinsics_ptr(nullptr),
_depth_units_ptr(nullptr),
_other_intrinsics_ptr(nullptr),
_depth_to_other_extrinsics_ptr(nullptr),
_other_bytes_per_pixel_ptr(nullptr),
_other_stream_type(to_stream)
{
auto on_frame = [this](rs2::frame f, const rs2::frame_source& source)
{
auto inspect_depth_frame = [this, &source](const rs2::frame& depth, const rs2::frame& other)
{
auto depth_frame = (frame_interface*)depth.get();
std::lock_guard<std::mutex> lock(_mutex);
bool found_depth_intrinsics = false;
bool found_depth_units = false;
if (!_depth_intrinsics_ptr)
{
auto stream_profile = depth_frame->get_stream();
if (auto video = dynamic_cast<video_stream_profile_interface*>(stream_profile.get()))
{
_depth_intrinsics = video->get_intrinsics();
_depth_intrinsics_ptr = &_depth_intrinsics;
found_depth_intrinsics = true;
}
}
if (!_depth_units_ptr)
{
auto sensor = depth_frame->get_sensor();
_depth_units = sensor->get_option(RS2_OPTION_DEPTH_UNITS).query();
_depth_units_ptr = &_depth_units;
found_depth_units = true;
}
if (found_depth_units != found_depth_intrinsics)
{
throw wrong_api_call_sequence_exception("Received depth frame that doesn't provide either intrinsics or depth units!");
}
if (!_depth_stream_profile.get())
{
_depth_stream_profile = depth_frame->get_stream();
environment::get_instance().get_extrinsics_graph().register_same_extrinsics(*_depth_stream_profile, *depth_frame->get_stream());
auto vid_frame = depth.as<rs2::video_frame>();
_width = vid_frame.get_width();
_height = vid_frame.get_height();
}
if (!_depth_to_other_extrinsics_ptr && _depth_stream_profile && _other_stream_profile)
{
environment::get_instance().get_extrinsics_graph().try_fetch_extrinsics(*_depth_stream_profile, *_other_stream_profile, &_depth_to_other_extrinsics);
_depth_to_other_extrinsics_ptr = &_depth_to_other_extrinsics;
}
if (_depth_intrinsics_ptr && _depth_units_ptr && _depth_stream_profile && _other_bytes_per_pixel_ptr &&
_depth_to_other_extrinsics_ptr && _other_intrinsics_ptr && _other_stream_profile && other)
{
std::vector<frame_holder> frames(2);
auto other_frame = (frame_interface*)other.get();
other_frame->acquire();
frames[0] = frame_holder{ other_frame };
frame_holder out_frame = get_source().allocate_video_frame(_depth_stream_profile, depth_frame,
_other_bytes_per_pixel / 8, _other_intrinsics.width, _other_intrinsics.height, 0, RS2_EXTENSION_DEPTH_FRAME);
auto p_out_frame = reinterpret_cast<uint16_t*>(((frame*)(out_frame.frame))->data.data());
memset(p_out_frame, _depth_stream_profile->get_format() == RS2_FORMAT_DISPARITY16 ? 0xFF : 0x00, _other_intrinsics.height * _other_intrinsics.width * sizeof(uint16_t));
auto p_depth_frame = reinterpret_cast<const uint16_t*>(((frame*)(depth_frame))->get_frame_data());
align_images(*_depth_intrinsics_ptr, *_depth_to_other_extrinsics_ptr, *_other_intrinsics_ptr,
[p_depth_frame, this](int z_pixel_index)
{
return _depth_units * p_depth_frame[z_pixel_index];
},
[p_out_frame, p_depth_frame/*, p_out_other_frame, other_bytes_per_pixel*/](int z_pixel_index, int other_pixel_index)
{
p_out_frame[other_pixel_index] = p_out_frame[other_pixel_index] ?
std::min( (int)(p_out_frame[other_pixel_index]), (int)(p_depth_frame[z_pixel_index]) )
: p_depth_frame[z_pixel_index];
});
frames[1] = std::move(out_frame);
auto composite = get_source().allocate_composite_frame(std::move(frames));
get_source().frame_ready(std::move(composite));
}
};
auto inspect_other_frame = [this, &source](const rs2::frame& other)
{
auto other_frame = (frame_interface*)other.get();
std::lock_guard<std::mutex> lock(_mutex);
if (_other_stream_type != other_frame->get_stream()->get_stream_type())
return;
if (!_other_stream_profile.get())
{
_other_stream_profile = other_frame->get_stream();
}
if (!_other_bytes_per_pixel_ptr)
{
auto vid_frame = other.as<rs2::video_frame>();
_other_bytes_per_pixel = vid_frame.get_bytes_per_pixel();
_other_bytes_per_pixel_ptr = &_other_bytes_per_pixel;
}
if (!_other_intrinsics_ptr)
{
if (auto video = dynamic_cast<video_stream_profile_interface*>(_other_stream_profile.get()))
{
_other_intrinsics = video->get_intrinsics();
_other_intrinsics_ptr = &_other_intrinsics;
}
}
//source.frame_ready(other);
};
if (auto composite = f.as<rs2::frameset>())
{
auto depth = composite.first_or_default(RS2_STREAM_DEPTH);
auto other = composite.first_or_default(_other_stream_type);
if (other)
{
inspect_other_frame(other);
}
if (depth)
{
inspect_depth_frame(depth, other);
}
}
};
auto callback = new rs2::frame_processor_callback<decltype(on_frame)>(on_frame);
processing_block::set_processing_callback(std::shared_ptr<rs2_frame_processor_callback>(callback));
}
}
| 41.46003 | 188 | 0.524993 | ezracb |
cd0dfb65ec82c65ba4e4af4650cae6ed709900a3 | 34 | cpp | C++ | libwx/src/Maps/MapControlBaseTpl.cpp | EnjoMitch/EnjoLib | 321167146657cba1497a9d3b4ffd71430f9b24b3 | [
"BSD-3-Clause"
] | 3 | 2021-06-14T15:36:46.000Z | 2022-02-28T15:16:08.000Z | libwx/src/Maps/MapControlBaseTpl.cpp | EnjoMitch/EnjoLib | 321167146657cba1497a9d3b4ffd71430f9b24b3 | [
"BSD-3-Clause"
] | 1 | 2021-07-17T07:52:15.000Z | 2021-07-17T07:52:15.000Z | libwx/src/Maps/MapControlBaseTpl.cpp | EnjoMitch/EnjoLib | 321167146657cba1497a9d3b4ffd71430f9b24b3 | [
"BSD-3-Clause"
] | 3 | 2021-07-12T14:52:38.000Z | 2021-11-28T17:10:33.000Z | #include "MapControlBaseTpl.hpp"
| 11.333333 | 32 | 0.794118 | EnjoMitch |
cd110ba1a1a3db65d78b2c090a63cd54c1bd7781 | 1,158 | cpp | C++ | BZOJ/1193/std.cpp | sjj118/OI-Code | 964ea6e799d14010f305c7e4aee269d860a781f7 | [
"MIT"
] | null | null | null | BZOJ/1193/std.cpp | sjj118/OI-Code | 964ea6e799d14010f305c7e4aee269d860a781f7 | [
"MIT"
] | null | null | null | BZOJ/1193/std.cpp | sjj118/OI-Code | 964ea6e799d14010f305c7e4aee269d860a781f7 | [
"MIT"
] | null | null | null | #include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <queue>
using namespace std;
int x,y,fx[10][3],dis[105][105];
struct Point
{
int x,y;
};
void bfs()
{
memset(dis,-1,sizeof(dis));
dis[x][y]=0;
fx[1][1]=fx[2][1]=1,fx[3][1]=fx[4][1]=-1,fx[5][1]=fx[6][1]=2,fx[7][1]=fx[8][1]=-2;
fx[1][2]=fx[3][2]=2,fx[2][2]=fx[4][2]=-2,fx[5][2]=fx[7][2]=1,fx[6][2]=fx[8][2]=-1;
queue<Point> q;
Point p;
p.x=x,p.y=y;
q.push(p);
while (!q.empty())
{
Point x;
x=q.front();
q.pop();
for (int i=1;i<=8;i++)
{
int nowx=x.x+fx[i][1],nowy=x.y+fx[i][2];
if (nowx<0||nowy<0||nowx>100||nowy>100) continue;
if (dis[nowx][nowy]!=-1) continue;
dis[nowx][nowy]=dis[x.x][x.y]+1;
Point X;
X.x=nowx,X.y=nowy;
q.push(X);
if (nowx==50&&nowy==50) return;
}
}
}
int main()
{
freopen("code.in","r",stdin);freopen("std.out","w",stdout);
int xp,yp,xs,ys;
scanf("%d%d%d%d",&xp,&yp,&xs,&ys);
x=abs(xs-xp),y=abs(ys-yp);
int ans=0;
while (x+y>=50)
{
if (x<y) swap(x,y);
if (x-4>=y*2) x-=4;
else x-=4,y-=2;
ans+=2;
}
x+=50,y+=50;
bfs();
printf("%d\n",ans+dis[50][50]);
return 0;
}
| 18.983607 | 83 | 0.535406 | sjj118 |
99832a30287b84907193b5279b1fbf5a94ab9c12 | 3,138 | hh | C++ | src/c++/include/xml/XmlWriter.hh | Illumina/Isaac4 | 0924fba8b467868da92e1c48323b15d7cbca17dd | [
"BSD-3-Clause"
] | 13 | 2018-02-09T22:59:39.000Z | 2021-11-29T06:33:22.000Z | src/c++/include/xml/XmlWriter.hh | Illumina/Isaac4 | 0924fba8b467868da92e1c48323b15d7cbca17dd | [
"BSD-3-Clause"
] | 17 | 2018-01-26T11:36:07.000Z | 2022-02-03T18:48:43.000Z | src/c++/include/xml/XmlWriter.hh | Illumina/Isaac4 | 0924fba8b467868da92e1c48323b15d7cbca17dd | [
"BSD-3-Clause"
] | 4 | 2018-10-19T20:00:00.000Z | 2020-10-29T14:44:06.000Z | /**
** Isaac Genome Alignment Software
** Copyright (c) 2010-2017 Illumina, Inc.
** All rights reserved.
**
** This software is provided under the terms and conditions of the
** GNU GENERAL PUBLIC LICENSE Version 3
**
** You should have received a copy of the GNU GENERAL PUBLIC LICENSE Version 3
** along with this program. If not, see
** <https://github.com/illumina/licenses/>.
**
** \file XmlWriter.hh
**
** Helper classes for composing xml
**
** \author Roman Petrovski
**/
#ifndef iSAAC_XML_XML_WRITER_HH
#define iSAAC_XML_XML_WRITER_HH
#include <libxml/xmlwriter.h>
#include <iostream>
#include <boost/noncopyable.hpp>
#include "common/Debug.hh"
#include "common/Exceptions.hh"
namespace isaac
{
namespace xml
{
class XmlWriterException : public common::IsaacException
{
public:
XmlWriterException(const std::string &message) : common::IsaacException(message)
{
}
};
class XmlWriter: boost::noncopyable
{
std::ostream &os_;
xmlTextWriterPtr xmlWriter_;
static int xmlOutputWriteCallback(void * context, const char * buffer, int len);
public:
explicit XmlWriter(std::ostream &os);
~XmlWriter();
void close();
XmlWriter &startElement(const char *name);
XmlWriter &startElement(const std::string &name) {return startElement(name.c_str());}
XmlWriter &endElement();
XmlWriter &writeText(const char *text);
template <typename T> XmlWriter &writeElement(const char *name, const T& value)
{
return (startElement(name) << value).endElement();
}
template <typename T> XmlWriter &writeElement(const std::string &name, const T& value)
{
return writeElement(name.c_str(), value);
}
template <typename T> XmlWriter &writeAttribute(const char *name, const T& value)
{
const std::string strValue = boost::lexical_cast<std::string>(value);
const int written = xmlTextWriterWriteAttribute(xmlWriter_, BAD_CAST name, BAD_CAST strValue.c_str());
if (-1 == written)
{
BOOST_THROW_EXCEPTION(XmlWriterException(
std::string("xmlTextWriterWriteAttribute returned -1 for attribute name: ") + name + " value: " + strValue));
}
return *this;
}
template <typename T> XmlWriter &operator <<(const T&t)
{
return writeText(boost::lexical_cast<std::string>(t).c_str());
}
struct BlockMacroSupport
{
bool set_;
BlockMacroSupport() : set_(true){}
void reset () {set_ = false;};
operator bool() const {return set_;}
};
// This is to allow macro ISAAC_XML_WRITER_ELEMENT_BLOCK to work
operator BlockMacroSupport() const {return BlockMacroSupport();}
};
/**
* \brief Macro for controling xml element scope. Automatically closes the element at the end of the block
*/
#define ISAAC_XML_WRITER_ELEMENT_BLOCK(writer, name) for(xml::XmlWriter::BlockMacroSupport iSaacElementBlockVariable = writer.startElement(name); iSaacElementBlockVariable; iSaacElementBlockVariable.reset(), writer.endElement())
} // namespace xml
} // namespace isaac
#endif // #ifndef iSAAC_XML_XML_WRITER_HH
| 29.055556 | 228 | 0.689611 | Illumina |
9983945023649b0aa66452dfe0bf3f3805212be4 | 1,753 | cpp | C++ | app/plugins/widgets/PaintField.cpp | adius/FeetJ | aca8ffc72911440eb8341a953ad833f3c7115554 | [
"MIT"
] | 1 | 2021-12-20T16:50:25.000Z | 2021-12-20T16:50:25.000Z | app/plugins/widgets/PaintField.cpp | adius/FeetJ | aca8ffc72911440eb8341a953ad833f3c7115554 | [
"MIT"
] | null | null | null | app/plugins/widgets/PaintField.cpp | adius/FeetJ | aca8ffc72911440eb8341a953ad833f3c7115554 | [
"MIT"
] | null | null | null | #include "PaintField.h"
#include <QPainter>
//We need to register this Type in MTQ
MTQ_QML_REGISTER_PLUGIN(PaintField)
//Constructor
PaintField::PaintField(QQuickItem *)
{
setHeight(600);
setWidth(600);
setStrokeHue(0);
setBackgroundBrightness(255);
}
void PaintField::paint(QPainter *painter)
{
painter->setRenderHint(QPainter::Antialiasing);
QRect rect(4, 4, width() - 8, height() - 8);
painter->fillRect(rect, m_bgColor);
for (int strokeI = 0; strokeI < m_strokes.size(); strokeI++)
{
painter->setPen(QPen(QBrush(m_strokeColors.at(strokeI)),4));
if (m_strokes.at(strokeI).size() == 1)
painter->drawPoint(m_strokes.at(strokeI).at(0));
else if (m_strokes.at(strokeI).size() > 1) {
for (int i = 0; i < m_strokes.at(strokeI).size() - 1; i++) {
painter->drawLine(m_strokes.at(strokeI).at(i),
m_strokes.at(strokeI).at(i+1));
}
}
}
}
qreal PaintField::strokeHue() const
{
return m_strokeHue;
}
void PaintField::setStrokeHue(const qreal hue)
{
m_strokeHue = hue;
}
int PaintField::backgroundBrightness() const
{
return m_backgroundBrightness;
}
void PaintField::setBackgroundBrightness(const int brightness)
{
m_backgroundBrightness = brightness;
m_bgColor = QColor().fromHsv(1, 0, brightness);
update();
}
void PaintField::processContactDown(mtq::ContactEvent *event)
{
m_strokes.push_back(QVector<QPointF>());
m_strokeColors.push_back(QColor().fromHsvF(m_strokeHue, 1, 1));
QPointF center = event->mappedCenter();
m_strokes.last().push_back(center);
update();
}
void PaintField::processContactMove(mtq::ContactEvent *event)
{
QPointF center = event->mappedCenter();
m_strokes.last().push_back(center);
update();
}
void PaintField::processContactUp(mtq::ContactEvent *event)
{
update();
}
| 22.189873 | 64 | 0.716486 | adius |
9986cefe6251c6c099a5a6d74636638750c6475b | 1,101 | cc | C++ | EvtGenBase/EvtPropBreitWigner.cc | brownd1978/FastSim | 05f590d72d8e7f71856fd833114a38b84fc7fd48 | [
"Apache-2.0"
] | null | null | null | EvtGenBase/EvtPropBreitWigner.cc | brownd1978/FastSim | 05f590d72d8e7f71856fd833114a38b84fc7fd48 | [
"Apache-2.0"
] | null | null | null | EvtGenBase/EvtPropBreitWigner.cc | brownd1978/FastSim | 05f590d72d8e7f71856fd833114a38b84fc7fd48 | [
"Apache-2.0"
] | null | null | null | #include "Experiment/Experiment.hh"
/*******************************************************************************
* Project: BaBar detector at the SLAC PEP-II B-factory
* Package: EvtGenBase
* File: $Id: EvtPropBreitWigner.cc 427 2010-01-14 13:25:53Z stroili $
* Author: Alexei Dvoretskii, dvoretsk@slac.stanford.edu, 2001-2002
*
* Copyright (C) 2002 Caltech
*******************************************************************************/
#include <math.h>
#include "EvtGenBase/EvtConst.hh"
#include "EvtGenBase/EvtPropBreitWigner.hh"
EvtPropBreitWigner::EvtPropBreitWigner(double m0, double g0)
: EvtPropagator(m0,g0)
{}
EvtPropBreitWigner::EvtPropBreitWigner(const EvtPropBreitWigner& other)
: EvtPropagator(other)
{}
EvtPropBreitWigner::~EvtPropBreitWigner()
{}
EvtAmplitude<EvtPoint1D>* EvtPropBreitWigner::clone() const
{
return new EvtPropBreitWigner(*this);
}
EvtComplex EvtPropBreitWigner::amplitude(const EvtPoint1D& x) const
{
double m = x.value();
EvtComplex value = sqrt(_g0/EvtConst::twoPi)/(m-_m0-EvtComplex(0.0,_g0/2.));
return value;
}
| 26.214286 | 81 | 0.630336 | brownd1978 |
9987109a9171472654a7e6be81e326619c361621 | 439 | cpp | C++ | src/search-a-2d-matrix.cpp | Liuchang0812/leetcode | d71f87b0035e661d0009f4382b39c4787c355f89 | [
"MIT"
] | 9 | 2015-09-09T20:28:31.000Z | 2019-05-15T09:13:07.000Z | src/search-a-2d-matrix.cpp | liuchang0812/leetcode | d71f87b0035e661d0009f4382b39c4787c355f89 | [
"MIT"
] | 1 | 2015-02-25T13:10:09.000Z | 2015-02-25T13:10:09.000Z | src/search-a-2d-matrix.cpp | liuchang0812/leetcode | d71f87b0035e661d0009f4382b39c4787c355f89 | [
"MIT"
] | 1 | 2016-08-31T19:14:52.000Z | 2016-08-31T19:14:52.000Z | class Solution {
public:
bool searchMatrix(vector<vector<int> > &matrix, int target) {
int posx = 0, posy = 0;
int n = matrix.size();
int m = matrix[0].size();
do {
if (matrix[posx][posy] == target) return true;
if (posx + 1 < n && matrix[posx+1][posy] <= target) posx ++;
else posy++;
} while (posx < n && posy < m);
return false;
}
};
| 27.4375 | 72 | 0.473804 | Liuchang0812 |
99872690557531ff5706528de551053c5cf13fd3 | 32,319 | hpp | C++ | api/vpl/preview/video_param.hpp | alexelizarov/oneVPL | cdf7444dc971544d148c51e0d93a2df1bb55dda7 | [
"MIT"
] | null | null | null | api/vpl/preview/video_param.hpp | alexelizarov/oneVPL | cdf7444dc971544d148c51e0d93a2df1bb55dda7 | [
"MIT"
] | null | null | null | api/vpl/preview/video_param.hpp | alexelizarov/oneVPL | cdf7444dc971544d148c51e0d93a2df1bb55dda7 | [
"MIT"
] | 1 | 2021-06-17T07:38:18.000Z | 2021-06-17T07:38:18.000Z | /*############################################################################
# Copyright Intel Corporation
#
# SPDX-License-Identifier: MIT
############################################################################*/
#pragma once
#include <algorithm>
#include <iostream>
#include <utility>
#include <tuple>
#include "vpl/preview/detail/string_helpers.hpp"
namespace oneapi {
namespace vpl {
#define DECLARE_MEMBER_ACCESS(father, type, name) \
/*! @brief Returns name value. */ \
/*! @return name value. */ \
type get_##name() const { \
return param_.name; \
} \
/*! @brief Sets name value. */ \
/*! @param[in] name Value. */ \
/*! @return Reference to the instance. */ \
father &set_##name(type name) { \
param_.name = name; \
return *this; \
}
#define DECLARE_INNER_MEMBER_ACCESS(father, type, parent, name) \
/*! @brief Returns name value. */ \
/*! @return name value. */ \
type get_##name() const { \
return param_.parent.name; \
} \
/*! @brief Sets name value. */ \
/*! @param[in] name Value. */ \
/*! @return Reference to the instance. */ \
father &set_##name(type name) { \
param_.parent.name = name; \
return *this; \
}
#define DECLARE_INNER_MEMBER_ARRAY_ACCESS(father, type, size, parent, name) \
/*! @brief Returns name value. */ \
/*! @return name value. */ \
auto get_##name() const { \
return param_.parent.name; \
} \
/*! @brief Sets name value. */ \
/*! @param[in] name Value. */ \
/*! @return Reference to the instance. */ \
father &set_##name(type name[size]) { \
std::copy(name, name + size, param_.parent.name); \
return *this; \
}
/// @brief Holds general video params applicable for all kind of sessions.
class video_param {
public:
/// @brief Constructs params and initialize them with default values.
video_param() : param_() {}
video_param(const video_param ¶m) : param_(param.param_) {
clear_extension_buffers();
}
video_param& operator=(const video_param& other){
param_ = other.param_;
clear_extension_buffers();
return *this;
}
/// @brief Dtor
virtual ~video_param() {
param_ = {};
}
public:
/// @brief Returns pointer to raw data
/// @return Pointer to raw data
mfxVideoParam *getMfx() {
return ¶m_;
}
public:
DECLARE_MEMBER_ACCESS(video_param, uint32_t, AllocId)
DECLARE_MEMBER_ACCESS(video_param, uint16_t, AsyncDepth)
DECLARE_MEMBER_ACCESS(video_param, uint16_t, Protected)
/// @brief Returns i/o memory pattern value.
/// @return i/o memory pattern value.
io_pattern get_IOPattern() const {
return (io_pattern)param_.IOPattern;
}
/// @brief Sets i/o memory pattern value.
/// @param[in] IOPattern i/o memory pattern.
/// @return Reference to this object
video_param &set_IOPattern(io_pattern IOPattern) {
param_.IOPattern = (uint32_t)IOPattern;
return *this;
}
/// @brief Attaches extension buffers to the video params
/// @param[in] buffer Array of extension buffers
/// @param[in] num Number of extension buffers
/// @return Reference to this object
video_param &set_extension_buffers(mfxExtBuffer **buffer, uint16_t num) {
param_.ExtParam = buffer;
param_.NumExtParam = num;
return *this;
}
/// @brief Clear extension buffers from the video params
/// @param[in] buffer Array of extension buffers
/// @param[in] num Number of extension buffers
/// @return Reference to this object
video_param &clear_extension_buffers() {
param_.ExtParam = nullptr;
param_.NumExtParam = 0;
return *this;
}
/// @brief Friend operator to print out state of the class in human readable form.
/// @param[inout] out Reference to the stream to write.
/// @param[in] p Referebce to the video_param instance to dump the state.
/// @return Reference to the stream.
friend std::ostream &operator<<(std::ostream &out, const video_param &p);
protected:
/// @brief Raw data
mfxVideoParam param_;
};
inline std::ostream &operator<<(std::ostream &out, const video_param &p) {
out << "Base:" << std::endl;
out << detail::space(detail::INTENT, out, "AllocId = ") << p.param_.AllocId << std::endl;
out << detail::space(detail::INTENT, out, "AsyncDepth = ")
<< detail::NotSpecifyed0(p.param_.AsyncDepth) << std::endl;
out << detail::space(detail::INTENT, out, "Protected = ") << p.param_.Protected << std::endl;
out << detail::space(detail::INTENT, out, "IOPattern = ")
<< detail::IOPattern2String(p.param_.IOPattern) << std::endl;
return out;
}
class codec_video_param;
class vpp_video_param;
/// @brief Holds general frame related params.
class frame_info {
public:
/// @brief Default ctor.
frame_info() : param_() {}
/// @brief Copy ctor.
/// @param[in] other another object to use as data source
frame_info(const frame_info &other) {
param_ = other.param_;
}
/// @brief Constructs object from the raw data.
/// @param[in] other another object to use as data source
explicit frame_info(const mfxFrameInfo &other) {
param_ = other;
}
/// @brief Copy operator.
/// @param[in] other another object to use as data source
/// @returns Reference to this object
frame_info &operator=(const frame_info &other) {
param_ = other.param_;
return *this;
}
DECLARE_MEMBER_ACCESS(frame_info, uint16_t, BitDepthLuma)
DECLARE_MEMBER_ACCESS(frame_info, uint16_t, BitDepthChroma)
DECLARE_MEMBER_ACCESS(frame_info, uint16_t, Shift)
DECLARE_MEMBER_ACCESS(frame_info, mfxFrameId, FrameId)
/// @brief Returns color format fourCC value.
/// @return color format fourCC value.
color_format_fourcc get_FourCC() const {
return (color_format_fourcc)param_.FourCC;
}
/// @brief Sets color format fourCC value.
/// @param[in] FourCC color format fourCC.
/// @return Reference to this object
frame_info &set_FourCC(color_format_fourcc FourCC) {
param_.FourCC = (uint32_t)FourCC;
return *this;
}
/// @todo below group valid for formats != P8
/// @brief Returns frame size.
/// @return Pair of width and height.
auto get_frame_size() const {
return std::pair(param_.Width, param_.Height);
}
/// @brief Sets frame size value.
/// @param[in] size pair of width and height.
/// @return Reference to this object
frame_info &set_frame_size(std::pair<uint32_t, uint32_t> size) {
param_.Width = std::get<0>(size);
param_.Height = std::get<1>(size);
return *this;
}
/// @brief Returns ROI.
/// @return Two pairs: pair of left corner and pair of size.
auto get_ROI() const {
return std::pair(std::pair(param_.CropX, param_.CropY),
std::pair(param_.CropW, param_.CropH));
}
/// @brief Sets ROI.
/// @param[in] roi Two pairs: pair of left corner and pair of size.
/// @return Reference to this object
frame_info &set_ROI(
std::pair<std::pair<uint16_t, uint16_t>, std::pair<uint16_t, uint16_t>> roi) {
param_.CropX = std::get<0>(std::get<0>(roi));
param_.CropY = std::get<1>(std::get<0>(roi));
param_.CropW = std::get<0>(std::get<1>(roi));
param_.CropH = std::get<1>(std::get<1>(roi));
return *this;
}
/// @todo below method is valid for P8 format only
DECLARE_MEMBER_ACCESS(frame_info, uint64_t, BufferSize)
/// @brief Returns frame rate value.
/// @return Pair of numerator and denominator.
auto get_frame_rate() const {
return std::pair(param_.FrameRateExtN, param_.FrameRateExtD);
}
/// @brief Sets frame rate value.
/// @param[in] rate pair of numerator and denominator.
/// @return Reference to this object
frame_info &set_frame_rate(std::pair<uint32_t, uint32_t> rate) {
param_.FrameRateExtN = std::get<0>(rate);
param_.FrameRateExtD = std::get<1>(rate);
return *this;
}
/// @brief Returns aspect ratio.
/// @return Pair of width and height of aspect ratio.
auto get_aspect_ratio() const {
return std::pair(param_.AspectRatioW, param_.AspectRatioH);
}
/// @brief Sets aspect ratio.
/// @param[in] ratio pair of width and height of aspect ratio.
/// @return Reference to this object
frame_info &set_aspect_ratio(std::pair<uint32_t, uint32_t> ratio) {
param_.AspectRatioW = std::get<0>(ratio);
param_.AspectRatioH = std::get<1>(ratio);
return *this;
}
/// @brief Returns picture structure value.
/// @return picture structure value.
pic_struct get_PicStruct() const {
return (pic_struct)param_.PicStruct;
}
/// @brief Sets picture structure value.
/// @param[in] PicStruct picture structure.
/// @return Reference to this object
frame_info &set_PicStruct(pic_struct PicStruct) {
param_.PicStruct = (uint16_t)PicStruct;
return *this;
}
/// @brief Returns chroma format value.
/// @return chroma format value.
chroma_format_idc get_ChromaFormat() const {
return (chroma_format_idc)param_.ChromaFormat;
}
/// @brief Sets chroma format value.
/// @param[in] ChromaFormat chroma format.
/// @return Reference to this object
frame_info &set_ChromaFormat(chroma_format_idc ChromaFormat) {
param_.ChromaFormat = (uint32_t)ChromaFormat;
return *this;
}
/// @brief Friend class
friend class codec_video_param;
/// @brief Friend class
friend class vpp_video_param;
/// @brief Friend operator to print out state of the class in human readable form.
/// @param[inout] out Reference to the stream to write.
/// @param[in] p Reference to the codec_video_param instance to dump the state.
/// @return Reference to the stream.
friend std::ostream &operator<<(std::ostream &out, const codec_video_param &p);
/// @brief Friend operator to print out state of the class in human readable form.
/// @param[inout] out Reference to the stream to write.
/// @param[in] v Reference to the vpp_video_param instance to dump the state.
/// @return Reference to the stream.
friend std::ostream &operator<<(std::ostream &out, const vpp_video_param &v);
/// @brief Friend operator to print out state of the class in human readable form.
/// @param[inout] out Reference to the stream to write.
/// @param[in] f Reference to the frame_info instance to dump the state.
/// @return Reference to the stream.
friend std::ostream &operator<<(std::ostream &out, const frame_info &f);
/// @brief Provides raw data.
/// @return Raw data.
mfxFrameInfo operator()() const {
return param_;
}
protected:
/// @brief Raw data
mfxFrameInfo param_;
};
inline std::ostream &operator<<(std::ostream &out, const frame_info &f) {
out << detail::space(detail::INTENT, out, "BitDepthLuma = ") << f.param_.BitDepthLuma
<< std::endl;
out << detail::space(detail::INTENT, out, "BitDepthChroma = ") << f.param_.BitDepthChroma
<< std::endl;
out << detail::space(detail::INTENT, out, "Shift = ")
<< detail::NotSpecifyed0(f.param_.Shift) << std::endl;
out << detail::space(detail::INTENT, out, "Color Format = ")
<< detail::FourCC2String(f.param_.FourCC) << std::endl;
if (f.param_.FourCC == MFX_FOURCC_P8) {
out << detail::space(detail::INTENT, out, "BufferSize = ") << f.param_.BufferSize
<< std::endl;
}
else {
out << detail::space(detail::INTENT, out, "Size [W,H] = [") << f.param_.Width << ","
<< f.param_.Height << "]" << std::endl;
out << detail::space(detail::INTENT, out, "ROI [X,Y,W,H] = [") << f.param_.CropX << ","
<< f.param_.CropY << "," << f.param_.CropW << "," << f.param_.CropH << "]" << std::endl;
}
out << detail::space(detail::INTENT, out, "FrameRate [N:D]= ")
<< detail::NotSpecifyed0(f.param_.FrameRateExtN) << ":"
<< detail::NotSpecifyed0(f.param_.FrameRateExtD) << std::endl;
if (0 == f.param_.AspectRatioW && 0 == f.param_.AspectRatioH) {
out << detail::space(detail::INTENT, out, "AspecRato [W,H]= [") << "Unset"
<< "]" << std::endl;
}
else {
out << detail::space(detail::INTENT, out, "AspecRato [W,H]= [") << f.param_.AspectRatioW
<< "," << f.param_.AspectRatioH << "]" << std::endl;
}
out << detail::space(detail::INTENT, out, "PicStruct = ")
<< detail::PicStruct2String(f.param_.PicStruct) << std::endl;
out << detail::space(detail::INTENT, out, "ChromaFormat = ")
<< detail::ChromaFormat2String(f.param_.ChromaFormat) << std::endl;
return out;
}
/// @brief Holds general frame related params.
class frame_data {
public:
/// @brief Default ctor.
frame_data() : param_() {}
/// @brief Copy ctor.
/// @param[in] other another object to use as data source
frame_data(const frame_data &other) {
param_ = other.param_;
}
/// @brief Constructs object from the raw data.
/// @param[in] other another object to use as data source
explicit frame_data(const mfxFrameData &other) {
param_ = other;
}
/// @brief Copy operator.
/// @param[in] other another object to use as data source
/// @return Reference to this object
frame_data &operator=(const frame_data &other) {
param_ = other.param_;
return *this;
}
DECLARE_MEMBER_ACCESS(frame_data, uint16_t, MemType)
/// @brief Returns pitch value.
/// @return Pitch value.
uint32_t get_pitch() const {
return ((uint32_t)param_.PitchHigh << 16) | (uint32_t)(uint32_t)param_.PitchLow;
}
/// @brief Sets pitch value.
/// @param[in] pitch Pitch.
void set_pitch(uint32_t pitch) {
param_.PitchHigh = (uint16_t)(pitch >> 16);
param_.PitchLow = (uint16_t)(pitch & 0xFFFF);
}
DECLARE_MEMBER_ACCESS(frame_data, uint64_t, TimeStamp)
DECLARE_MEMBER_ACCESS(frame_data, uint32_t, FrameOrder)
DECLARE_MEMBER_ACCESS(frame_data, uint16_t, Locked)
DECLARE_MEMBER_ACCESS(frame_data, uint16_t, Corrupted)
DECLARE_MEMBER_ACCESS(frame_data, uint16_t, DataFlag)
/// @brief Gets pointer for formats with 1 plane.
/// @return Pointer for formats with 1 plane.
auto get_plane_ptrs_1() const {
return param_.R;
}
/// @brief Gets pointer for formats with 1 plane (BGRA).
/// @return Pointer for formats with 1 plane (BGRA).
auto get_plane_ptrs_1_BGRA() const {
return param_.B;
}
/// @brief Gets pointer for formats with 2 planes.
/// @return Pointers for formats with 2 planes. Pointers for planes layout is: Y, UV.
auto get_plane_ptrs_2() const {
return std::pair(param_.R, param_.G);
}
/// @brief Gets pointer for formats with 3 planes.
/// @return Pointers for formats with 3 planes. Pointers for planes layout is: R, G, B or Y, U, V.
auto get_plane_ptrs_3() const {
return std::make_tuple(param_.R, param_.G, param_.B);
}
/// @brief Gets pointer for formats with 4 planes.
/// @return Pointers for formats with 4 planes. Pointers for planes layout is: R, G, B, A.
auto get_plane_ptrs_4() const {
return std::make_tuple(param_.R, param_.G, param_.B, param_.A);
}
/// @brief Friend operator to print out state of the class in human readable form.
/// @param[inout] out Reference to the stream to write.
/// @param[in] f Reference to the frame_data instance to dump the state.
/// @return Reference to the stream.
friend std::ostream &operator<<(std::ostream &out, const frame_data &f);
protected:
/// @brief Raw data
mfxFrameData param_;
};
inline std::ostream &operator<<(std::ostream &out, const frame_data &f) {
out << detail::space(detail::INTENT, out, "MemType = ")
<< detail::MemType2String(f.param_.MemType) << std::endl;
out << detail::space(detail::INTENT, out, "PitchHigh = ") << f.param_.PitchHigh << std::endl;
out << detail::space(detail::INTENT, out, "PitchLow = ") << f.param_.PitchLow << std::endl;
out << detail::space(detail::INTENT, out, "TimeStamp = ")
<< detail::TimeStamp2String(static_cast<uint64_t>(f.param_.TimeStamp)) << std::endl;
out << detail::space(detail::INTENT, out, "FrameOrder = ") << f.param_.FrameOrder << std::endl;
out << detail::space(detail::INTENT, out, "Locked = ") << f.param_.Locked << std::endl;
out << detail::space(detail::INTENT, out, "Corrupted = ")
<< detail::Corruption2String(f.param_.Corrupted) << std::endl;
out << detail::space(detail::INTENT, out, "DataFlag = ")
<< detail::TimeStamp2String(f.param_.DataFlag) << std::endl;
return out;
}
/// @brief Holds general codec-specific params applicable for any decoder and encoder.
class codec_video_param : public video_param {
protected:
/// @brief Constructs params and initialize them with default values.
codec_video_param() : video_param() {}
codec_video_param(const codec_video_param ¶m) : video_param(param) {}
codec_video_param& operator=(const codec_video_param ¶m){
video_param::operator=(param);
return *this;
}
public:
DECLARE_INNER_MEMBER_ACCESS(codec_video_param, uint16_t, mfx, LowPower);
DECLARE_INNER_MEMBER_ACCESS(codec_video_param, uint16_t, mfx, BRCParamMultiplier);
/// @brief Returns codec fourCC value.
/// @return codec fourCC value.
codec_format_fourcc get_CodecId() const {
return (codec_format_fourcc)param_.mfx.CodecId;
}
/// @brief Sets codec fourCC value.
/// @param[in] CodecID codec fourCC.
/// @return Reference to this object
codec_video_param &set_CodecId(codec_format_fourcc CodecID) {
param_.mfx.CodecId = (uint32_t)CodecID;
return *this;
}
DECLARE_INNER_MEMBER_ACCESS(codec_video_param, uint16_t, mfx, CodecProfile);
DECLARE_INNER_MEMBER_ACCESS(codec_video_param, uint16_t, mfx, CodecLevel);
DECLARE_INNER_MEMBER_ACCESS(codec_video_param, uint16_t, mfx, NumThread);
/// @brief Returns frame_info value.
/// @return frame info value.
frame_info get_frame_info() const {
return frame_info(param_.mfx.FrameInfo);
}
/// @brief Sets name value.
/// @param[in] name Value.
/// @return Reference to this object
codec_video_param &set_frame_info(frame_info name) {
param_.mfx.FrameInfo = name();
return *this;
}
/// Friend operator to print out state of the class in human readable form.
friend std::ostream &operator<<(std::ostream &out, const codec_video_param &p);
};
inline std::ostream &operator<<(std::ostream &out, const codec_video_param &p) {
const video_param &v = dynamic_cast<const video_param &>(p);
out << v;
out << "Codec:" << std::endl;
out << detail::space(detail::INTENT, out, "LowPower = ")
<< detail::TriState2String(p.param_.mfx.LowPower) << std::endl;
out << detail::space(detail::INTENT, out, "BRCParamMultiplier = ")
<< p.param_.mfx.BRCParamMultiplier << std::endl;
out << detail::space(detail::INTENT, out, "CodecId = ")
<< detail::FourCC2String(p.param_.mfx.CodecId) << std::endl;
out << detail::space(detail::INTENT, out, "CodecProfile = ") << p.param_.mfx.CodecProfile
<< std::endl;
out << detail::space(detail::INTENT, out, "CodecLevel = ") << p.param_.mfx.CodecLevel
<< std::endl;
out << detail::space(detail::INTENT, out, "NumThread = ") << p.param_.mfx.NumThread
<< std::endl;
out << "FrameInfo:" << std::endl;
out << frame_info(p.param_.mfx.FrameInfo) << std::endl;
return out;
}
/// @brief Holds encoder specific params.
class encoder_video_param : public codec_video_param {
public:
/// @brief Constructs params and initialize them with default values.
encoder_video_param() : codec_video_param() {}
/// @brief Returns TargetUsage value.
/// @return TargetUsage Target Usage value.
target_usage get_TargetUsage() const {
return (target_usage)param_.mfx.TargetUsage;
}
/// @brief Sets Target Usage value.
/// @param[in] TargetUsage Target Usage.
/// @return Reference to this object
encoder_video_param &set_TargetUsage(target_usage TargetUsage) {
param_.mfx.CodecId = (uint32_t)TargetUsage;
return *this;
}
DECLARE_INNER_MEMBER_ACCESS(encoder_video_param, uint16_t, mfx, GopPicSize);
DECLARE_INNER_MEMBER_ACCESS(encoder_video_param, uint32_t, mfx, GopRefDist);
DECLARE_INNER_MEMBER_ACCESS(encoder_video_param, uint16_t, mfx, GopOptFlag);
DECLARE_INNER_MEMBER_ACCESS(encoder_video_param, uint16_t, mfx, IdrInterval);
/// @brief Returns rate control method value.
/// @return rate control method value.
rate_control_method get_RateControlMethod() const {
return (rate_control_method)param_.mfx.RateControlMethod;
}
/// @brief Sets rate control method value.
/// @param[in] RateControlMethod rate control method.
/// @return Reference to this object
encoder_video_param &set_RateControlMethod(rate_control_method RateControlMethod) {
param_.mfx.RateControlMethod = (uint32_t)RateControlMethod;
return *this;
}
DECLARE_INNER_MEMBER_ACCESS(encoder_video_param, uint16_t, mfx, InitialDelayInKB);
DECLARE_INNER_MEMBER_ACCESS(encoder_video_param, uint16_t, mfx, QPI);
DECLARE_INNER_MEMBER_ACCESS(encoder_video_param, uint16_t, mfx, Accuracy);
DECLARE_INNER_MEMBER_ACCESS(encoder_video_param, uint16_t, mfx, BufferSizeInKB);
DECLARE_INNER_MEMBER_ACCESS(encoder_video_param, uint16_t, mfx, TargetKbps);
DECLARE_INNER_MEMBER_ACCESS(encoder_video_param, uint16_t, mfx, QPP);
DECLARE_INNER_MEMBER_ACCESS(encoder_video_param, uint16_t, mfx, ICQQuality);
DECLARE_INNER_MEMBER_ACCESS(encoder_video_param, uint16_t, mfx, MaxKbps);
DECLARE_INNER_MEMBER_ACCESS(encoder_video_param, uint16_t, mfx, QPB);
DECLARE_INNER_MEMBER_ACCESS(encoder_video_param, uint16_t, mfx, Convergence);
DECLARE_INNER_MEMBER_ACCESS(encoder_video_param, uint16_t, mfx, NumSlice);
DECLARE_INNER_MEMBER_ACCESS(encoder_video_param, uint16_t, mfx, NumRefFrame);
DECLARE_INNER_MEMBER_ACCESS(encoder_video_param, uint16_t, mfx, EncodedOrder);
/// @brief Friend operator to print out state of the class in human readable form.
/// @param[inout] out Reference to the stream to write.
/// @param[in] e Reference to the encoder_video_param instance to dump the state.
/// @return Reference to the stream.
friend std::ostream &operator<<(std::ostream &out, const encoder_video_param &e);
};
inline std::ostream &operator<<(std::ostream &out, const encoder_video_param &e) {
const codec_video_param &c = dynamic_cast<const codec_video_param &>(e);
out << c;
out << "Encoder:" << std::endl;
out << detail::space(detail::INTENT, out, "TargetUsage = ")
<< detail::NotSpecifyed0(e.param_.mfx.TargetUsage) << std::endl;
out << detail::space(detail::INTENT, out, "GopPicSize = ")
<< detail::NotSpecifyed0(e.param_.mfx.GopPicSize) << std::endl;
out << detail::space(detail::INTENT, out, "GopRefDist = ")
<< detail::NotSpecifyed0(e.param_.mfx.GopRefDist) << std::endl;
out << detail::space(detail::INTENT, out, "GopOptFlag = ")
<< detail::GopOptFlag2String(e.param_.mfx.GopOptFlag) << std::endl;
out << detail::space(detail::INTENT, out, "IdrInterval = ") << e.param_.mfx.IdrInterval
<< std::endl;
out << detail::space(detail::INTENT, out, "RateControlMethod = ")
<< detail::RateControlMethod2String(e.param_.mfx.RateControlMethod) << std::endl;
out << detail::space(detail::INTENT, out, "InitialDelayInKB = ")
<< e.param_.mfx.InitialDelayInKB << std::endl;
out << detail::space(detail::INTENT, out, "QPI = ") << e.param_.mfx.QPI
<< std::endl;
out << detail::space(detail::INTENT, out, "Accuracy = ") << e.param_.mfx.Accuracy
<< std::endl;
out << detail::space(detail::INTENT, out, "BufferSizeInKB = ") << e.param_.mfx.BufferSizeInKB
<< std::endl;
out << detail::space(detail::INTENT, out, "TargetKbps = ") << e.param_.mfx.TargetKbps
<< std::endl;
out << detail::space(detail::INTENT, out, "QPP = ") << e.param_.mfx.QPP
<< std::endl;
out << detail::space(detail::INTENT, out, "ICQQuality = ") << e.param_.mfx.ICQQuality
<< std::endl;
out << detail::space(detail::INTENT, out, "MaxKbps = ") << e.param_.mfx.MaxKbps
<< std::endl;
out << detail::space(detail::INTENT, out, "QPB = ") << e.param_.mfx.QPB
<< std::endl;
out << detail::space(detail::INTENT, out, "Convergence = ") << e.param_.mfx.Convergence
<< std::endl;
out << detail::space(detail::INTENT, out, "NumSlice = ")
<< detail::NotSpecifyed0(e.param_.mfx.NumSlice) << std::endl;
out << detail::space(detail::INTENT, out, "NumRefFrame = ")
<< detail::NotSpecifyed0(e.param_.mfx.NumRefFrame) << std::endl;
out << detail::space(detail::INTENT, out, "EncodedOrder = ")
<< detail::Boolean2String(e.param_.mfx.EncodedOrder) << std::endl;
return out;
}
/// @brief Holds decoder specific params.
class decoder_video_param : public codec_video_param {
public:
/// @brief Constructs params and initialize them with default values.
decoder_video_param() : codec_video_param() {}
explicit decoder_video_param(const codec_video_param &other) : codec_video_param(other) {}
DECLARE_INNER_MEMBER_ACCESS(decoder_video_param, uint16_t, mfx, DecodedOrder);
DECLARE_INNER_MEMBER_ACCESS(decoder_video_param, uint16_t, mfx, ExtendedPicStruct);
DECLARE_INNER_MEMBER_ACCESS(decoder_video_param, uint32_t, mfx, TimeStampCalc);
DECLARE_INNER_MEMBER_ACCESS(decoder_video_param, uint16_t, mfx, SliceGroupsPresent);
DECLARE_INNER_MEMBER_ACCESS(decoder_video_param, uint16_t, mfx, MaxDecFrameBuffering);
DECLARE_INNER_MEMBER_ACCESS(decoder_video_param, uint16_t, mfx, EnableReallocRequest);
/// @brief Friend operator to print out state of the class in human readable form.
/// @param[inout] out Reference to the stream to write.
/// @param[in] d Reference to the decoder_video_param instance to dump the state.
/// @return Reference to the stream.
friend std::ostream &operator<<(std::ostream &out, const decoder_video_param &d);
};
inline std::ostream &operator<<(std::ostream &out, const decoder_video_param &d) {
const codec_video_param &c = dynamic_cast<const codec_video_param &>(d);
out << c;
out << "Decoder:" << std::endl;
out << detail::space(detail::INTENT, out, "DecodedOrder = ")
<< detail::Boolean2String(d.param_.mfx.DecodedOrder) << std::endl;
out << detail::space(detail::INTENT, out, "ExtendedPicStruct = ")
<< detail::PicStruct2String(d.param_.mfx.ExtendedPicStruct) << std::endl;
out << detail::space(detail::INTENT, out, "TimeStampCalc = ")
<< detail::TimeStampCalc2String(d.param_.mfx.TimeStampCalc) << std::endl;
out << detail::space(detail::INTENT, out, "SliceGroupsPresent = ")
<< detail::Boolean2String(d.param_.mfx.SliceGroupsPresent) << std::endl;
out << detail::space(detail::INTENT, out, "MaxDecFrameBuffering = ")
<< detail::NotSpecifyed0(d.param_.mfx.MaxDecFrameBuffering) << std::endl;
out << detail::space(detail::INTENT, out, "EnableReallocRequest = ")
<< detail::TriState2String(d.param_.mfx.EnableReallocRequest) << std::endl;
return out;
}
/// @brief Holds JPEG decoder specific params.
class jpeg_decoder_video_param : public codec_video_param {
public:
/// @brief Constructs params and initialize them with default values.
jpeg_decoder_video_param() : codec_video_param() {}
DECLARE_INNER_MEMBER_ACCESS(jpeg_decoder_video_param, uint16_t, mfx, JPEGChromaFormat);
DECLARE_INNER_MEMBER_ACCESS(jpeg_decoder_video_param, uint16_t, mfx, Rotation);
DECLARE_INNER_MEMBER_ACCESS(jpeg_decoder_video_param, uint32_t, mfx, JPEGColorFormat);
DECLARE_INNER_MEMBER_ACCESS(jpeg_decoder_video_param, uint16_t, mfx, InterleavedDec);
DECLARE_INNER_MEMBER_ARRAY_ACCESS(jpeg_decoder_video_param, uint8_t, 4, mfx, SamplingFactorH);
DECLARE_INNER_MEMBER_ARRAY_ACCESS(jpeg_decoder_video_param, uint8_t, 4, mfx, SamplingFactorV);
};
/// @brief Holds JPEG encoder specific params.
class jpeg_encoder_video_param : public codec_video_param {
public:
/// @brief Constructs params and initialize them with default values.
jpeg_encoder_video_param() : codec_video_param() {}
DECLARE_INNER_MEMBER_ACCESS(jpeg_encoder_video_param, uint16_t, mfx, Interleaved);
DECLARE_INNER_MEMBER_ACCESS(jpeg_encoder_video_param, uint16_t, mfx, Quality);
DECLARE_INNER_MEMBER_ACCESS(jpeg_encoder_video_param, uint32_t, mfx, RestartInterval);
};
/// @brief Holds VPP specific params.
class vpp_video_param : public video_param {
public:
/// @brief Constructs params and initialize them with default values.
vpp_video_param() : video_param() {}
public:
/// @brief Returns frame_info in value.
/// @return frame info in value.
frame_info get_in_frame_info() const {
return frame_info(param_.vpp.In);
}
/// @brief Sets name value.
/// @param[in] name Value.
/// @return Reference to this object
vpp_video_param &set_in_frame_info(frame_info name) {
param_.vpp.In = name();
return *this;
}
/// @brief Returns frame_info out value.
/// @return frame info out value.
frame_info get_out_frame_info() const {
return frame_info(param_.vpp.Out);
}
/// @brief Sets name value.
/// @param[in] name Value.
/// @return Reference to this object
vpp_video_param &set_out_frame_info(frame_info name) {
param_.vpp.Out = name();
return *this;
}
/// @brief Friend operator to print out state of the class in human readable form.
/// @param[inout] out Reference to the stream to write.
/// @param[in] v Reference to the vpp_video_param instance to dump the state.
/// @return Reference to the stream.
friend std::ostream &operator<<(std::ostream &out, const vpp_video_param &v);
};
inline std::ostream &operator<<(std::ostream &out, const vpp_video_param &vpp) {
const video_param &v = dynamic_cast<const video_param &>(vpp);
out << v;
out << "Input FrameInfo:" << std::endl;
out << frame_info(vpp.param_.vpp.In) << std::endl;
out << "Output FrameInfo:" << std::endl;
out << frame_info(vpp.param_.vpp.Out) << std::endl;
return out;
}
} // namespace vpl
} // namespace oneapi
| 41.328645 | 102 | 0.632569 | alexelizarov |
998e041b4883ee11c6ee796bd4f582a31b7c617e | 278 | hpp | C++ | src/core/game-states/cinematic-state.hpp | guillaume-haerinck/imac-tower-defense | 365a32642ea0d3ad8b2b7d63347d585c44d9f670 | [
"MIT"
] | 44 | 2019-06-06T21:33:30.000Z | 2022-03-26T06:18:23.000Z | src/core/game-states/cinematic-state.hpp | guillaume-haerinck/imac-tower-defense | 365a32642ea0d3ad8b2b7d63347d585c44d9f670 | [
"MIT"
] | 1 | 2019-09-27T12:04:52.000Z | 2019-09-29T13:30:42.000Z | src/core/game-states/cinematic-state.hpp | guillaume-haerinck/imac-tower-defense | 365a32642ea0d3ad8b2b7d63347d585c44d9f670 | [
"MIT"
] | 8 | 2019-07-26T16:44:26.000Z | 2020-11-24T17:56:18.000Z | #pragma once
#include "i-game-state.hpp"
class Game; // Forward declaration
class CinematicState : public IGameState {
public:
CinematicState(Game& game);
virtual ~CinematicState();
void enter() override;
void update(float deltatime) override;
void exit() override;
};
| 17.375 | 42 | 0.741007 | guillaume-haerinck |
998ef2272096e1f01bcdf770cbf9fbc0511898f0 | 15,127 | cpp | C++ | GameEngine/CoreEngine/CoreEngine/src/ShadingOperation.cpp | mettaursp/SuddenlyGames | e2ff1c2771d4ca54824650e4f1a33a527536ca61 | [
"Apache-2.0"
] | 1 | 2021-01-17T13:05:20.000Z | 2021-01-17T13:05:20.000Z | GameEngine/CoreEngine/CoreEngine/src/ShadingOperation.cpp | suddenly-games/SuddenlyGames | e2ff1c2771d4ca54824650e4f1a33a527536ca61 | [
"Apache-2.0"
] | null | null | null | GameEngine/CoreEngine/CoreEngine/src/ShadingOperation.cpp | suddenly-games/SuddenlyGames | e2ff1c2771d4ca54824650e4f1a33a527536ca61 | [
"Apache-2.0"
] | null | null | null | #include "ShadingOperation.h"
extern "C" {
#include <math.h>
}
#include "Graphics.h"
#include "Textures.h"
#include "Light.h"
#include "FrameBuffer.h"
namespace GraphicsEngine
{
void ShadingOperation::Initialize()
{
auto shadowCamera = Engine::Create<Camera>();
auto shadowScene = Engine::Create<Scene>();
shadowCamera->SetParent(This.lock());
shadowScene->SetParent(This.lock());
ShadowCamera = shadowCamera;
ShadowScene = shadowScene;
shadowScene->CurrentCamera = ShadowCamera;
int width = 2048;
int height = 2048;
auto rightMap = FrameBuffer::Create(width, height, Textures::Create(width, height, GL_LINEAR, GL_CLAMP_TO_EDGE, GL_FLOAT, GL_R32F, GL_RED));
auto leftMap = FrameBuffer::Create(width, height, Textures::Create(width, height, GL_LINEAR, GL_CLAMP_TO_EDGE, GL_FLOAT, GL_R32F, GL_RED));
auto topMap = FrameBuffer::Create(width, height, Textures::Create(width, height, GL_LINEAR, GL_CLAMP_TO_EDGE, GL_FLOAT, GL_R32F, GL_RED));
auto bottomMap = FrameBuffer::Create(width, height, Textures::Create(width, height, GL_LINEAR, GL_CLAMP_TO_EDGE, GL_FLOAT, GL_R32F, GL_RED));
auto frontMap = FrameBuffer::Create(width, height, Textures::Create(width, height, GL_LINEAR, GL_CLAMP_TO_EDGE, GL_FLOAT, GL_R32F, GL_RED));
auto backMap = FrameBuffer::Create(width, height, Textures::Create(width, height, GL_LINEAR, GL_CLAMP_TO_EDGE, GL_FLOAT, GL_R32F, GL_RED));
auto parent = This.lock();
rightMap->SetParent(parent);
leftMap->SetParent(parent);
topMap->SetParent(parent);
bottomMap->SetParent(parent);
frontMap->SetParent(parent);
backMap->SetParent(parent);
RightMap = rightMap;
LeftMap = leftMap;
TopMap = topMap;
BottomMap = bottomMap;
FrontMap = frontMap;
BackMap = backMap;
}
void ShadingOperation::Update(float)
{
if (CurrentScene.expired())
return;
CurrentScene.lock()->RefreshWatches();
}
void ShadingOperation::Render()
{
if (CurrentCamera.expired() || CurrentScene.expired())
return;
glEnable(GL_BLEND); CheckGLErrors();
glEnable(GL_DEPTH_TEST); CheckGLErrors();
glDepthMask(GL_FALSE); CheckGLErrors();
glBlendFunc(GL_SRC_ALPHA, GL_ONE); CheckGLErrors();
Programs::PhongOutput->Use();
Programs::PhongOutput->SetInputBuffer(SceneBuffer.lock());
Programs::PhongOutput->resolution.Set(Resolution);
Programs::PhongOutput->shadowsEnabled.Set(false);
Programs::PhongOutput->shadowLeft.Set(LeftMap.lock()->GetTexture(), 8);
Programs::PhongOutput->shadowRight.Set(RightMap.lock()->GetTexture(), 9);
Programs::PhongOutput->shadowFront.Set(FrontMap.lock()->GetTexture(), 10);
Programs::PhongOutput->shadowBack.Set(BackMap.lock()->GetTexture(), 11);
Programs::PhongOutput->shadowTop.Set(TopMap.lock()->GetTexture(), 12);
Programs::PhongOutput->shadowBottom.Set(BottomMap.lock()->GetTexture(), 13);
auto currentCamera = CurrentCamera.lock();
if (GlobalLight.expired())
{
Programs::PhongOutput->lightBrightness.Set(1);
Programs::PhongOutput->attenuation.Set(1, 0, 0);
Programs::PhongOutput->lightPosition.Set(0, 0, 0);
Programs::PhongOutput->lightDirection.Set(-currentCamera->GetTransformationInverse().UpVector());
Programs::PhongOutput->lightDiffuse.Set(0.5f, 0.5f, 0.5f);
Programs::PhongOutput->lightSpecular.Set(1, 1, 1);
Programs::PhongOutput->lightAmbient.Set(0.5f, 0.5f, 0.5f);
Programs::PhongOutput->spotlightAngles.Set(0, 0);
Programs::PhongOutput->spotlightFalloff.Set(0);
Programs::PhongOutput->lightType.Set(0);
}
else
{
auto globalLight = GlobalLight.lock();
Programs::PhongOutput->lightBrightness.Set(globalLight->Brightness);
Programs::PhongOutput->attenuation.Set(globalLight->Attenuation);
Programs::PhongOutput->lightPosition.Set(globalLight->Position);
Programs::PhongOutput->lightDirection.Set(currentCamera->GetTransformationInverse() * -globalLight->Direction);
Programs::PhongOutput->lightDiffuse.Set(globalLight->Diffuse);
Programs::PhongOutput->lightSpecular.Set(globalLight->Specular);
Programs::PhongOutput->lightAmbient.Set(globalLight->Ambient);
Programs::PhongOutput->spotlightAngles.Set(globalLight->InnerRadius, globalLight->OuterRadius);
Programs::PhongOutput->spotlightFalloff.Set(globalLight->SpotlightFalloff);
Programs::PhongOutput->lightType.Set(globalLight->Type);
}
Programs::PhongOutput->transform.Set(Matrix3().Scale(1, 1, 1));
Programs::PhongOutput->CoreMeshes.Square->Draw();
glEnable(GL_STENCIL_TEST); CheckGLErrors();
glDepthFunc(GL_GEQUAL); CheckGLErrors();
auto currentScene = CurrentScene.lock();
for (int i = 0; i < currentScene->GetLights(); ++i)
{
std::shared_ptr<Light> light = currentScene->GetLight(i);
if (!light->Enabled || light->AreShadowsEnabled())
continue;
if (currentCamera->GetFrustum().Intersects(light->GetBoundingBox()) == Enum::IntersectionType::Outside)
continue;
Draw(light);
}
glBlendFunc(GL_SRC_ALPHA, GL_ONE); CheckGLErrors();
for (int i = 0; i < currentScene->GetLights(); ++i)
{
std::shared_ptr<Light> light = currentScene->GetLight(i);
if (!light->Enabled || !light->AreShadowsEnabled())
continue;
if (currentCamera->GetFrustum().Intersects(light->GetBoundingBox()) == Enum::IntersectionType::Outside)
continue;
glDisable(GL_BLEND); CheckGLErrors();
glDepthMask(GL_TRUE); CheckGLErrors();
glDisable(GL_STENCIL_TEST); CheckGLErrors();
glEnable(GL_DEPTH_TEST); CheckGLErrors();
glDepthFunc(GL_LEQUAL); CheckGLErrors();
glCullFace(GL_FRONT); CheckGLErrors();
Programs::DepthTrace->Use();
DrawShadows(light, i);
glCullFace(GL_BACK); CheckGLErrors();
glEnable(GL_BLEND); CheckGLErrors();
glEnable(GL_DEPTH_TEST); CheckGLErrors();
glDepthMask(GL_FALSE); CheckGLErrors();
glEnable(GL_STENCIL_TEST); CheckGLErrors();
glDepthFunc(GL_GEQUAL); CheckGLErrors();
Programs::PhongOutput->Use();
LightBuffer.lock()->DrawTo();
Draw(light);
}
glDepthMask(GL_TRUE); CheckGLErrors();
glDisable(GL_STENCIL_TEST); CheckGLErrors();
//glEnable(GL_DEPTH_TEST); CheckGLErrors();
glDepthFunc(GL_LEQUAL); CheckGLErrors();
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); CheckGLErrors();
}
void ShadingOperation::Draw(const std::shared_ptr<Light>& light)
{
auto currentCamera = CurrentCamera.lock();
Programs::PhongOutput->lightBrightness.Set(light->Brightness);
Programs::PhongOutput->cameraTransform.Set(light->GetShadowMapInverseTransformation() * currentCamera->GetTransformation());
Programs::PhongOutput->attenuation.Set(light->Attenuation);
Programs::PhongOutput->lightPosition.Set(currentCamera->GetTransformationInverse() * light->Position);
Programs::PhongOutput->lightDirection.Set(currentCamera->GetTransformationInverse() * -light->Direction);
Programs::PhongOutput->lightDiffuse.Set(light->Diffuse);
Programs::PhongOutput->lightSpecular.Set(light->Specular);
Programs::PhongOutput->lightAmbient.Set(light->Ambient);
Programs::PhongOutput->spotlightAngles.Set(cosf(light->InnerRadius), cosf(light->OuterRadius));
Programs::PhongOutput->spotlightFalloff.Set(light->SpotlightFalloff);
Programs::PhongOutput->lightType.Set(light->Type);
const Mesh* mesh = nullptr;
const Mesh* stencilMesh = nullptr;
float lightRadius = 0;
Matrix3 transform;
if (light->Type == Enum::LightType::Directional)
{
transform = Matrix3().Scale(1, 1, 1);
Programs::PhongOutput->shadowsEnabled.Set(false);
Programs::PhongOutput->transform.Set(transform);
mesh = Programs::PhongOutput->CoreMeshes.Square;
stencilMesh = Programs::PhongOutputStencil->CoreMeshes.Square;
}
else
{
Dimensions shadowMapSize = light->GetShadowMapSize();
Programs::PhongOutput->shadowsEnabled.Set(light->AreShadowsEnabled());
Programs::PhongOutput->shadowDebugView.Set(light->ShadowDebugView);
if (light->AreShadowsEnabled())
Programs::PhongOutput->shadowScale.Set(float(shadowMapSize.Width) / 2048, float(shadowMapSize.Height) / 2048);
lightRadius = light->GetRadius();
Programs::PhongOutput->maxRadius.Set(lightRadius);
lightRadius *= 1.1f;
if (light->Type == Enum::LightType::Spot && light->OuterRadius <= PI / 2 + 0.001f)
{
Matrix3 rotation;
float direction = 1;
if (light->Direction == Vector3(0, -1, 0))
rotation = Matrix3().RotatePitch(PI);//direction = -1;
else if (light->Direction != Vector3(0, 1, 0))
rotation = Matrix3().RotateYaw(atan2f(light->Direction.X, -light->Direction.Z)) * Matrix3().RotatePitch(-acosf(light->Direction.Y));
transform = currentCamera->GetProjection() * Matrix3().Translate(light->Position) * Matrix3().Scale(-lightRadius, lightRadius, lightRadius) * rotation;
Programs::PhongOutput->transform.Set(transform);
if (light->OuterRadius <= PI / 4 + 0.001f)
{
mesh = Programs::PhongOutput->CoreMeshes.Cone;
stencilMesh = Programs::PhongOutputStencil->CoreMeshes.Cone;
}
else
{
mesh = Programs::PhongOutput->CoreMeshes.HalfBoundingVolume;
stencilMesh = Programs::PhongOutputStencil->CoreMeshes.HalfBoundingVolume;
}
}
else
{
transform = currentCamera->GetProjectionMatrix() * Matrix3().Translate(
currentCamera->GetTransformationInverse() * light->Position
) * Matrix3().Scale(-lightRadius, lightRadius, lightRadius);
Programs::PhongOutput->transform.Set(transform);
mesh = Programs::PhongOutput->CoreMeshes.BoundingVolume;
stencilMesh = Programs::PhongOutputStencil->CoreMeshes.BoundingVolume;
}
}
glStencilMask(0xFF); CheckGLErrors();
glStencilFunc(GL_ALWAYS, 1, 0xFF); CheckGLErrors();
glStencilOp(GL_ZERO, GL_ZERO, GL_REPLACE); CheckGLErrors();
Programs::PhongOutputStencil->Use();
Programs::PhongOutputStencil->transform.Set(transform);
glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); CheckGLErrors();
stencilMesh->Draw();
glStencilFunc(GL_EQUAL, 1, 0xFF); CheckGLErrors();
glStencilOp(GL_ZERO, GL_ZERO, GL_REPLACE); CheckGLErrors();
Programs::PhongOutputStencil->transform.Set(transform * Matrix3().Scale(-1, 1, 1));
glDepthFunc(GL_LEQUAL); CheckGLErrors();
stencilMesh->Draw();
Programs::PhongOutput->Use();
glStencilMask(0x00); CheckGLErrors();
glStencilFunc(GL_EQUAL, 1, 0xFF); CheckGLErrors();
glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP); CheckGLErrors();
glDepthFunc(GL_GEQUAL); CheckGLErrors();
glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); CheckGLErrors();
mesh->Draw();
}
void ShadingOperation::DrawShadows(const std::shared_ptr<Light>& light, int index)
{
float lightRadius = light->GetRadius() * 1.1f;
Matrix3 backPanelTransform = Matrix3(0, 0, -lightRadius + 0.01f) * Matrix3().Scale(lightRadius, lightRadius, 0);
//Matrix3 base = Matrix3().ExtractRotation(CurrentCamera->GetTransformation(), light->Position);
Dimensions bufferSize = light->GetShadowMapSize();
const AabbTree& watch = CurrentScene.lock()->GetWatched(index);
auto shadowCamera = ShadowCamera.lock();
shadowCamera->SetProperties(0.5f * PI, 1, 1e-1f, lightRadius);
if (light->Type != Enum::LightType::Spot || light->OuterRadius > PI / 4 + 0.001f)
{
RightMap.lock()->DrawTo(0, 0, bufferSize.Width, bufferSize.Height);
Graphics::ClearScreen(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
shadowCamera->SetTransformation(light->GetShadowMapTransformation() * Matrix3(Vector3(), Vector3(0, 0, 1), Vector3(0, 1, 0), Vector3(-1, 0, 0)));
Scene::Draw(watch, false, shadowCamera);
Programs::DepthTrace->transform.Set(shadowCamera->GetProjectionMatrix() * backPanelTransform);
Programs::DepthTrace->objectTransform.Set(shadowCamera->GetTransformation() * backPanelTransform);
Programs::DepthTrace->CoreMeshes.Cube->Draw();
}
if (light->Type != Enum::LightType::Spot || light->OuterRadius > PI / 4 + 0.001f)
{
LeftMap.lock()->DrawTo(0, 0, bufferSize.Width, bufferSize.Height);
Graphics::ClearScreen(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
shadowCamera->SetTransformation(light->GetShadowMapTransformation() * Matrix3(Vector3(), Vector3(0, 0, -1), Vector3(0, 1, 0), Vector3(1, 0, 0)));
Scene::Draw(watch, false, shadowCamera);
Programs::DepthTrace->transform.Set(shadowCamera->GetProjectionMatrix() * backPanelTransform);
Programs::DepthTrace->objectTransform.Set(shadowCamera->GetTransformation() * backPanelTransform);
Programs::DepthTrace->CoreMeshes.Cube->Draw();
}
if (light->Type != Enum::LightType::Spot || light->OuterRadius > PI / 4 + 0.001f)
{
FrontMap.lock()->DrawTo(0, 0, bufferSize.Width, bufferSize.Height);
Graphics::ClearScreen(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
shadowCamera->SetTransformation(light->GetShadowMapTransformation() * Matrix3(Vector3(), Vector3(1, 0, 0), Vector3(0, 1, 0), Vector3(0, 0, 1)));
Scene::Draw(watch, false, shadowCamera);
Programs::DepthTrace->transform.Set(shadowCamera->GetProjectionMatrix() * backPanelTransform);
Programs::DepthTrace->objectTransform.Set(shadowCamera->GetTransformation() * backPanelTransform);
Programs::DepthTrace->CoreMeshes.Cube->Draw();
}
if (light->Type != Enum::LightType::Spot || light->OuterRadius > PI / 4 + 0.001f)
{
BackMap.lock()->DrawTo(0, 0, bufferSize.Width, bufferSize.Height);
Graphics::ClearScreen(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
shadowCamera->SetTransformation(light->GetShadowMapTransformation() * Matrix3(Vector3(), Vector3(-1, 0, 0), Vector3(0, 1, 0), Vector3(0, 0, -1)));
Scene::Draw(watch, false, shadowCamera);
Programs::DepthTrace->transform.Set(shadowCamera->GetProjectionMatrix() * backPanelTransform);
Programs::DepthTrace->objectTransform.Set(shadowCamera->GetTransformation() * backPanelTransform);
Programs::DepthTrace->CoreMeshes.Cube->Draw();
}
//if (light->Type != Enum::LightType::Spot || light->OuterRadius <= PI / 4 + 0.001f)
{
TopMap.lock()->DrawTo(0, 0, bufferSize.Width, bufferSize.Height);
Graphics::ClearScreen(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
shadowCamera->SetTransformation(light->GetShadowMapTransformation() * Matrix3(Vector3(), Vector3(1, 0, 0), Vector3(0, 0, 1), Vector3(0, -1, 0)));
Scene::Draw(watch, false, shadowCamera);
Programs::DepthTrace->transform.Set(shadowCamera->GetProjectionMatrix() * backPanelTransform);
Programs::DepthTrace->objectTransform.Set(shadowCamera->GetTransformation() * backPanelTransform);
Programs::DepthTrace->CoreMeshes.Cube->Draw();
}
if (light->Type != Enum::LightType::Spot || light->OuterRadius > 3 * PI / 4 + 0.001f)
{
BottomMap.lock()->DrawTo(0, 0, bufferSize.Width, bufferSize.Height);
Graphics::ClearScreen(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
shadowCamera->SetTransformation(light->GetShadowMapTransformation() * Matrix3(Vector3(), Vector3(1, 0, 0), Vector3(0, 0, -1), Vector3(0, 1, 0)));
Scene::Draw(watch, false, shadowCamera);
Programs::DepthTrace->transform.Set(shadowCamera->GetProjectionMatrix() * backPanelTransform);
Programs::DepthTrace->objectTransform.Set(shadowCamera->GetTransformation() * backPanelTransform);
Programs::DepthTrace->CoreMeshes.Cube->Draw();
}
}
}
| 36.627119 | 155 | 0.728763 | mettaursp |
998f59d8ff627006e43f0c806056bc361bbe6e56 | 33,660 | hpp | C++ | Tests/wrappers.hpp | adam-morrison/Comparing_Filters | 8287cae15a64cffd5e5885516dc547f7b01621a7 | [
"Apache-2.0"
] | null | null | null | Tests/wrappers.hpp | adam-morrison/Comparing_Filters | 8287cae15a64cffd5e5885516dc547f7b01621a7 | [
"Apache-2.0"
] | null | null | null | Tests/wrappers.hpp | adam-morrison/Comparing_Filters | 8287cae15a64cffd5e5885516dc547f7b01621a7 | [
"Apache-2.0"
] | null | null | null | /* Taken from
* https://github.com/FastFilter/fastfilter_cpp
* */
#ifndef FILTERS_WRAPPERS_HPP
#define FILTERS_WRAPPERS_HPP
#include <climits>
#include <iomanip>
#include <iostream>
#include <map>
#include <random>
#include <set>
#include <stdexcept>
#include <stdio.h>
#include <vector>
#include "../Bloom_Filter/bloom.hpp"
#include "../PD_Filter/dict.hpp"
#include "TPD_Filter/T_dict.hpp"
//#include "../TPD_Filter/pd512_wrapper.hpp"
//#include "dict512.hpp"
#include "TPD_Filter/dict512.hpp"
#include "d512/att_d512.hpp"
#include "d512/twoChoicer.hpp"
// #include "../cuckoo/cuckoofilter.h"
#include "../cuckoofilter/src/cuckoofilter.h"
//#include "../morton/compressed_cuckoo_filter.h"
#include "../Bloom_Filter/simd-block-fixed-fpp.h"
#include "../Bloom_Filter/simd-block.h"
#include "../morton/morton_sample_configs.h"
//#include "xorfilter.h"
//#include "../xorfilter/xorfilter_2.h"
//#include "../xorfilter/xorfilter_2n.h"
//#include "../xorfilter/xorfilter_10bit.h"
//#include "../xorfilter/xorfilter_10_666bit.h"
//#include "../xorfilter/xorfilter_13bit.h"
//#include "../xorfilter/xorfilter_plus.h"
//#include "../xorfilter/xorfilter_singleheader.h"
//#include "../xorfilter/xor_fuse_filter.h"
#define CONTAIN_ATTRIBUTES __attribute__((noinline))
enum filter_id
{
BF,
CF,
CF_ss,
MF,
SIMD,
pd_id,
tpd_id,
d512,
att_d512_id,
twoChoicer_id
};
template <typename Table>
struct FilterAPI
{
};
template <typename ItemType, size_t bits_per_item, template <size_t> class TableType, typename HashFamily>
struct FilterAPI<cuckoofilter::CuckooFilter<ItemType, bits_per_item, TableType, HashFamily>>
{
using Table = cuckoofilter::CuckooFilter<ItemType, bits_per_item, TableType, HashFamily>;
static Table ConstructFromAddCount(size_t add_count)
{
return Table(add_count);
}
static void Add(uint64_t key, Table *table)
{
if (table->Add(key) != cuckoofilter::Ok)
{
std::cerr << "Cuckoo filter is too full. Inertion of the element (" << key << ") failed.\n";
get_info(table);
throw logic_error("The filter is too small to hold all of the elements");
}
}
static void AddAll(const vector<ItemType> keys, const size_t start, const size_t end, Table *table)
{
for (int i = start; i < end; ++i)
{
if (table->Add(keys[i]) != cuckoofilter::Ok)
{
std::cerr << "Cuckoo filter is too full. Inertion of the element (" << keys[i] << ") failed.\n";
get_info(table);
throw logic_error("The filter is too small to hold all of the elements");
}
}
}
static void AddAll(const std::vector<ItemType> keys, Table *table)
{
for (int i = 0; i < keys.size(); ++i)
{
if (table->Add(keys[i]) != cuckoofilter::Ok) {
std::cerr << "Cuckoo filter is too full. Inertion of the element (" << keys[i] << ") failed.\n";
// std::cerr << "Load before insertion is: " << ;
get_info(table);
throw logic_error("The filter is too small to hold all of the elements");
}
}
// table->AddAll(keys, 0, keys.size());
}
static void Remove(uint64_t key, Table *table)
{
table->Delete(key);
}
CONTAIN_ATTRIBUTES static bool Contain(uint64_t key, const Table *table)
{
return (0 == table->Contain(key));
}
static string get_name(Table *table)
{
auto ss = table->Info();
std::string temp = "PackedHashtable";
if (ss.find(temp)!= std::string::npos){
return "CF-ss";
}
return "Cuckoo";
}
static auto get_info(const Table *table) ->std::stringstream
{
std::string state = table->Info();
std::stringstream ss;
ss << state;
return ss;
// std::cout << state << std::endl;
}
static auto get_ID(Table *table) -> filter_id
{
return CF;
}
};
template <
class TableType, typename spareItemType,
typename itemType>
struct FilterAPI<att_d512<TableType, spareItemType, itemType>>
{
using Table = att_d512<TableType, spareItemType, itemType, 8, 51, 50>;
// using Table = dict512<TableType, spareItemType, itemType>;
static Table ConstructFromAddCount(size_t add_count)
{
return Table(add_count, .955, .5);
}
static void Add(itemType key, Table *table)
{
// assert(table->case_validate());
table->insert(key);
// assert(table->case_validate());
}
static void AddAll(const std::vector<itemType> keys, const size_t start, const size_t end, Table *table)
{
for (int i = start; i < end; ++i)
{
table->insert(keys[i]);
}
}
static void AddAll(const std::vector<itemType> keys, Table *table)
{
for (int i = 0; i < keys.size(); ++i)
{
table->insert(keys[i]);
}
}
static void Remove(itemType key, Table *table)
{
// std::cout << "Remove in Wrapper!" << std::endl;
table->remove(key);
}
CONTAIN_ATTRIBUTES static bool Contain(itemType key, const Table *table)
{
return table->lookup(key);
}
static string get_name(Table *table)
{
return table->get_name();
}
static auto get_info(Table *table) ->std::stringstream
{
return table->get_extended_info();
}
static auto get_ID(Table *table) -> filter_id
{
return att_d512_id;
}
};
template <typename itemType>
struct FilterAPI<twoChoicer<itemType>>
{
using Table = twoChoicer<itemType, 8, 51, 50>;
// using Table = dict512<TableType, spareItemType, itemType>;
static Table ConstructFromAddCount(size_t add_count)
{
return Table(add_count, .9, .5);
}
static void Add(itemType key, Table *table)
{
// assert(table->case_validate());
table->insert(key);
// assert(table->case_validate());
}
static void AddAll(const std::vector<itemType> keys, const size_t start, const size_t end, Table *table)
{
for (int i = start; i < end; ++i)
{
table->insert(keys[i]);
}
}
static void AddAll(const std::vector<itemType> keys, Table *table)
{
for (int i = 0; i < keys.size(); ++i)
{
table->insert(keys[i]);
}
}
static void Remove(itemType key, Table *table)
{
table->remove(key);
}
CONTAIN_ATTRIBUTES static bool Contain(itemType key, const Table *table)
{
return table->lookup(key);
}
static string get_name(Table *table)
{
return table->get_name();
}
static auto get_info(Table *table) ->std::stringstream
{
return table->get_extended_info();
}
static auto get_ID(Table *table) -> filter_id
{
return twoChoicer_id;
}
};
////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////
template <typename ItemType, size_t bits_per_item, bool branchless, typename HashFamily>
struct FilterAPI<bloomfilter::bloom<ItemType, bits_per_item, branchless, HashFamily>>
{
using Table = bloomfilter::bloom<ItemType, bits_per_item, branchless, HashFamily>;
static Table ConstructFromAddCount(size_t add_count) {
return Table(add_count);
}
static void Add(uint64_t key, Table *table)
{
table->Add(key);
}
static void AddAll(const std::vector<ItemType> keys, const size_t start, const size_t end, Table *table)
{
table->AddAll(keys, start, end);
}
static void AddAll(const std::vector<ItemType> keys, Table *table)
{
table->AddAll(keys, 0, keys.size());
}
static void Remove(uint64_t key, Table *table)
{
throw std::runtime_error("Unsupported");
}
static string get_name(Table *table)
{
return "Bloom";
}
static auto get_info(Table *table) ->std::stringstream
{
assert(false);
std::stringstream ss;
return ss;
}
CONTAIN_ATTRIBUTES static bool Contain(uint64_t key, const Table *table)
{
return (0 == table->Contain(key));
}
static auto get_ID(Table *table) -> filter_id
{
return BF;
}
};
template <>
struct FilterAPI<SimdBlockFilter<>>
{
using Table = SimdBlockFilter<>;
static Table ConstructFromAddCount(size_t add_count)
{
Table ans(ceil(log2(add_count * 8.0 / CHAR_BIT)));
return ans;
}
static void Add(uint64_t key, Table *table)
{
table->Add(key);
}
static void AddAll(const vector<uint64_t> keys, const size_t start, const size_t end, Table *table)
{
for (int i = start; i < end; ++i)
{
table->Add(keys[i]);
}
}
static void AddAll(const std::vector<uint64_t> keys, Table *table)
{
AddAll(keys, 0, keys.size(), table);
/* for (int i = 0; i < keys.size(); ++i) {
table->Add(keys[i]);
}*/
}
static bool Contain(uint64_t key, const Table *table)
{
return table->Find(key);
}
static void Remove(uint64_t key, Table *table)
{
throw std::runtime_error("Unsupported");
}
static string get_name(Table *table)
{
return "SimdBlockFilter";
}
static auto get_info(Table *table) ->std::stringstream
{
assert(false);
std::stringstream ss;
return ss;
}
static auto get_ID(Table *table) -> filter_id
{
return SIMD;
}
};
class MortonFilter
{
using mf7_6 = CompressedCuckoo::Morton7_6;
mf7_6 *filter;
size_t size;
public:
MortonFilter(const size_t size)
{
// filter = new CompressedCuckoo::Morton3_8((size_t) (size / 0.95) + 64);
// filter = new CompressedCuckoo::Morton3_8((size_t) (2.1 * size) + 64);
filter = new mf7_6((size_t)(size / 0.95) + 64);
this->size = size;
}
~MortonFilter()
{
delete filter;
}
void Add(uint64_t key)
{
filter->insert(key);
}
void AddAll(const vector<uint64_t> keys, const size_t start, const size_t end)
{
size_t size = end - start;
::std::vector<uint64_t> k(size);
::std::vector<bool> status(size);
for (size_t i = start; i < end; i++)
{
k[i - start] = keys[i];
}
// TODO return value and status is ignored currently
filter->insert_many(k, status, size);
}
void AddAll(const std::vector<uint64_t> keys)
{
AddAll(keys, 0, keys.size());
}
inline bool Contain(uint64_t &item)
{
return filter->likely_contains(item);
};
size_t SizeInBytes() const
{
// according to morton_sample_configs.h:
// Morton3_8 - 3-slot buckets with 8-bit fingerprints: 11.7 bits/item
// (load factor = 0.95)
// so in theory we could just hardcode the size here,
// and don't measure it
// return (size_t)((size * 11.7) / 8);
return filter->SizeInBytes();
}
};
template <>
struct FilterAPI<MortonFilter>
{
using Table = MortonFilter;
static Table ConstructFromAddCount(size_t add_count)
{
return Table(add_count);
}
static void Add(uint64_t key, Table *table)
{
table->Add(key);
}
static void AddAll(const vector<uint64_t> keys, const size_t start, const size_t end, Table *table)
{
for (int i = start; i < end; ++i)
{
table->Add(keys[i]);
}
// table->AddAll(keys, start, end);
}
static void AddAll(const std::vector<uint64_t> keys, Table *table)
{
for (unsigned long key : keys)
{
table->Add(key);
}
}
static void Remove(uint64_t key, Table *table)
{
throw std::runtime_error("Unsupported");
}
CONTAIN_ATTRIBUTES static bool Contain(uint64_t key, Table *table)
{
return table->Contain(key);
}
static string get_name(Table *table)
{
return "Morton";
}
static auto get_info(Table *table) ->std::stringstream
{
assert(false);
std::stringstream ss;
return ss;
}
static auto get_ID(Table *table) -> filter_id
{
return MF;
}
};
//template<typename itemType, size_t bits_per_item,brancless, Hashfam>
//template<typename itemType, size_t bits_per_item, bool branchless, typename HashFamily>
//template<typename itemType, template<typename> class TableType>
//template<template<typename> class TableType, typename itemType, size_t bits_per_item>
//struct FilterAPI<dict<PD, TableType, itemType, bits_per_item>> {
template <template <typename> class TableType, typename itemType, typename spareItemType>
struct FilterAPI<dict<PD, TableType, itemType, spareItemType>>
{
// using Table = dict<PD, hash_table<uint32_t>, itemType, bits_per_item, branchless, HashFamily>;
using Table = dict<PD, TableType, itemType, spareItemType>;
static Table ConstructFromAddCount(size_t add_count, size_t bits_per_item)
{
return Table(add_count, bits_per_item, .95, .5);
}
static void Add(itemType key, Table *table)
{
table->insert(key);
}
static void AddAll(const std::vector<itemType> keys, const size_t start, const size_t end, Table *table)
{
for (int i = start; i < end; ++i)
{
table->insert(keys[i]);
}
}
static void AddAll(const std::vector<itemType> keys, Table *table)
{
for (int i = 0; i < keys.size(); ++i)
{
table->insert(keys[i]);
}
}
static void Remove(itemType key, Table *table)
{
table->remove(key);
}
CONTAIN_ATTRIBUTES static bool Contain(itemType key, const Table *table)
{
return table->lookup(key);
}
static string get_name(Table *table)
{
return "PD";
}
static auto get_info(Table *table) ->std::stringstream
{
assert(false);
std::stringstream ss;
return ss;
}
static auto get_ID(Table *table) -> filter_id
{
return pd_id;
}
};
/*
template<class temp_PD, template<typename> class TableType, typename itemType, typename spareItemType>
struct FilterAPI<dict<temp_PD, TableType, itemType, spareItemType>> {
using Table = dict<temp_PD, TableType, itemType, spareItemType>;
static Table ConstructFromAddCount(size_t add_count, size_t bits_per_item) {
return Table(add_count, bits_per_item, .95, .5);
}
static void Add(itemType key, Table *table) {
table->insert(key);
}
static void AddAll(const std::vector<itemType> keys, const size_t start, const size_t end, Table *table) {
for (int i = start; i < end; ++i) {
table->insert(keys[i]);
}
}
static void AddAll(const std::vector<itemType> keys, Table *table) {
for (int i = 0; i < keys.size(); ++i) {
table->insert(keys[i]);
}
}
static void Remove(itemType key, Table *table) {
table->remove(key);
}
CONTAIN_ATTRIBUTES static bool Contain(itemType key, const Table *table) {
return table->lookup(key);
}
static string get_name() {
// string res = "TPD";
// res += sizeof()
return "TPD";
}
};
*/
/*
template<template<typename, size_t, size_t> class temp_PD, typename slot_type, size_t bits_per_item, size_t max_capacity,
typename itemType,
template<typename> class TableType, typename spareItemType>
struct FilterAPI<dict<temp_PD<slot_type, bits_per_item, max_capacity>, TableType, itemType, spareItemType>> {
// using Table = dict<PD, hash_table<uint32_t>, itemType, bits_per_item, branchless, HashFamily>;
using Table = dict<TPD_name::TPD<slot_type, bits_per_item, max_capacity>, TableType, itemType, spareItemType>;
static Table ConstructFromAddCount(size_t add_count) {
return Table(add_count, bits_per_item, .95, .5, max_capacity);
}
static void Add(itemType key, Table *table) {
table->insert(key);
}
static void AddAll(const std::vector<itemType> keys, const size_t start, const size_t end, Table *table) {
for (int i = start; i < end; ++i) {
table->insert(keys[i]);
}
}
static void AddAll(const std::vector<itemType> keys, Table *table) {
for (int i = 0; i < keys.size(); ++i) {
table->insert(keys[i]);
}
}
static void Remove(itemType key, Table *table) {
table->remove(key);
}
CONTAIN_ATTRIBUTES static bool Contain(itemType key, const Table *table) {
return table->lookup(key);
}
static string get_name() {
// string res = "TPD";
// res += sizeof()
return "TPD";
}
};
*/
//<slot_type, bits_per_item, max_capacity>
template <
class temp_PD,
typename slot_type, size_t bits_per_item, size_t max_capacity,
typename itemType,
class TableType, typename spareItemType>
struct FilterAPI<
T_dict<temp_PD,
slot_type, bits_per_item, max_capacity,
TableType, spareItemType,
itemType>>
{
// using Table = T_dict<TPD_name::TPD<slot_type,bits_per_item, max_capacity>, slot_type, bits_per_item, max_capacity, TableType, spareItemType, itemType>;
using Table = T_dict<temp_PD, slot_type, bits_per_item, max_capacity, TableType, spareItemType, itemType>;
static Table ConstructFromAddCount(size_t add_count)
{
return Table(add_count, .95, .5);
}
static void Add(itemType key, Table *table)
{
table->insert(key);
}
static void AddAll(const std::vector<itemType> keys, const size_t start, const size_t end, Table *table)
{
for (int i = start; i < end; ++i)
{
table->insert(keys[i]);
}
}
static void AddAll(const std::vector<itemType> keys, Table *table)
{
for (int i = 0; i < keys.size(); ++i)
{
table->insert(keys[i]);
}
}
static void Remove(itemType key, Table *table)
{
table->remove(key);
}
CONTAIN_ATTRIBUTES static bool Contain(itemType key, const Table *table)
{
return table->lookup(key);
}
static string get_name(Table *table)
{
return table->get_name();
}
static auto get_info(Table *table) ->std::stringstream
{
table->get_dynamic_info();
std::stringstream ss;
return ss;
}
static auto get_ID(Table *table) -> filter_id
{
return tpd_id;
}
};
template <
class TableType, typename spareItemType,
typename itemType>
struct FilterAPI<
dict512<TableType, spareItemType,
itemType>>
{
using Table = dict512<TableType, spareItemType, itemType, 8, 51, 50>;
// using Table = dict512<TableType, spareItemType, itemType>;
static Table ConstructFromAddCount(size_t add_count)
{
return Table(add_count, 1, .5);
}
static void Add(itemType key, Table *table)
{
table->insert(key);
}
static void AddAll(const std::vector<itemType> keys, const size_t start, const size_t end, Table *table)
{
for (int i = start; i < end; ++i)
{
table->insert(keys[i]);
}
}
static void AddAll(const std::vector<itemType> keys, Table *table)
{
for (int i = 0; i < keys.size(); ++i)
{
table->insert(keys[i]);
}
}
static void Remove(itemType key, Table *table)
{
table->remove(key);
}
CONTAIN_ATTRIBUTES static bool Contain(itemType key, const Table *table)
{
return table->lookup(key);
}
static string get_name(Table *table)
{
return table->get_name();
}
static auto get_info(Table *table) ->std::stringstream
{
table->get_dynamic_info();
std::stringstream ss;
return ss;
}
static auto get_ID(Table *table) -> filter_id
{
return d512;
}
};
/**Before changing first argument in T_dict template argument*/
/*
template<
template<typename, size_t, size_t> class temp_PD,
typename slot_type, size_t bits_per_item, size_t max_capacity,
typename itemType,
template<typename> class TableType, typename spareItemType
>
struct FilterAPI<
T_dict<temp_PD,
slot_type, bits_per_item, max_capacity,
TableType, spareItemType,
itemType>
> {
using Table = T_dict<TPD_name::TPD, slot_type, bits_per_item, max_capacity, TableType, spareItemType, itemType>;
static Table ConstructFromAddCount(size_t add_count) {
return Table(add_count, .95, .5);
}
static void Add(itemType key, Table *table) {
table->insert(key);
}
static void AddAll(const std::vector<itemType> keys, const size_t start, const size_t end, Table *table) {
for (int i = start; i < end; ++i) {
table->insert(keys[i]);
}
}
static void AddAll(const std::vector<itemType> keys, Table *table) {
for (int i = 0; i < keys.size(); ++i) {
table->insert(keys[i]);
}
}
static void Remove(itemType key, Table *table) {
table->remove(key);
}
CONTAIN_ATTRIBUTES static bool Contain(itemType key, const Table *table) {
return table->lookup(key);
}
static string get_name() {
// string res = "TPD";
// res += sizeof()
return "T_dict";
}
};
*/
/*
#ifdef __AVX2__
template<typename HashFamily>
struct FilterAPI<SimdBlockFilter<HashFamily>> {
using Table = SimdBlockFilter<HashFamily>;
static Table ConstructFromAddCount(size_t add_count) {
Table ans(ceil(log2(add_count * 8.0 / CHAR_BIT)));
return ans;
}
static void Add(uint64_t key, Table *table) {
table->Add(key);
}
static void AddAll(const vector<uint64_t> keys, const size_t start, const size_t end, Table *table) {
throw std::runtime_error("Unsupported");
}
static void AddAll(const vector<uint64_t> keys, Table *table) {
throw std::runtime_error("Unsupported");
}
static void Remove(uint64_t key, Table *table) {
throw std::runtime_error("Unsupported");
}
CONTAIN_ATTRIBUTES static bool Contain(uint64_t key, const Table *table) {
return table->Find(key);
}
static string get_name() {
return "SimdBlockFilter";
}
};
template<typename HashFamily>
struct FilterAPI<SimdBlockFilterFixed64<HashFamily>> {
using Table = SimdBlockFilterFixed64<HashFamily>;
static Table ConstructFromAddCount(size_t add_count) {
Table ans(ceil(add_count * 8.0 / CHAR_BIT));
return ans;
}
static void Add(uint64_t key, Table *table) {
table->Add(key);
}
static void AddAll(const vector<uint64_t> keys, const size_t start, const size_t end, Table *table) {
throw std::runtime_error("Unsupported");
}
static void AddAll(const vector<uint64_t> keys, Table *table) {
throw std::runtime_error("Unsupported");
}
static void Remove(uint64_t key, Table *table) {
throw std::runtime_error("Unsupported");
}
CONTAIN_ATTRIBUTES static bool Contain(uint64_t key, const Table *table) {
return table->Find(key);
}
static string get_name() {
return "SimdBlockFilterFixed64";
}
};
*/
/*
template <typename HashFamily>
struct FilterAPI<SimdBlockFilterFixed16<HashFamily>> {
using Table = SimdBlockFilterFixed16<HashFamily>;
static Table ConstructFromAddCount(size_t add_count) {
Table ans(ceil(add_count * 8.0 / CHAR_BIT));
return ans;
}
static void Add(uint64_t key, Table* table) {
table->Add(key);
}
static void AddAll(const vector<uint64_t> keys, const size_t start, const size_t end, Table* table) {
throw std::runtime_error("Unsupported");
}
static void Remove(uint64_t key, Table * table) {
throw std::runtime_error("Unsupported");
}
CONTAIN_ATTRIBUTES static bool Contain(uint64_t key, const Table * table) {
return table->Find(key);
}
};
*/
/*
template<typename HashFamily>
struct FilterAPI<SimdBlockFilterFixed<HashFamily>> {
using Table = SimdBlockFilterFixed<HashFamily>;
static Table ConstructFromAddCount(size_t add_count) {
Table ans(ceil(add_count * 8.0 / CHAR_BIT));
return ans;
}
static void Add(uint64_t key, Table *table) {
table->Add(key);
}
static void AddAll(const vector<uint64_t> keys, const size_t start, const size_t end, Table *table) {
table->AddAll(keys, start, end);
}
static void AddAll(const vector<uint64_t> keys, Table *table) {
table->AddAll(keys, 0, keys.size());
}
static void Remove(uint64_t key, Table *table) {
throw std::runtime_error("Unsupported");
}
CONTAIN_ATTRIBUTES static bool Contain(uint64_t key, const Table *table) {
return table->Find(key);
}
static string get_name() {
return "SimdBlockFilterFixed";
}
};
#endif
*/
/*
template<typename itemType>
struct FilterAPI<set<itemType>> {
// using Table = dict<PD, hash_table<uint32_t>, itemType, bits_per_item, branchless, HashFamily>;
// using Table = set<itemType>;
static set<itemType> ConstructFromAddCount(size_t add_count) { return set<itemType>(); }
static void Add(itemType key, set<itemType> *table) {
table->insert(key);
}
static void AddAll(const std::vector<itemType> keys, const size_t start, const size_t end, set<itemType> *table) {
table->insert(keys);
// for (int i = start; i < end; ++i) {
// table->insert(keys[i]);
// }
}
static void AddAll(const std::vector<itemType> keys, Table *table) {
table->insert(keys);
// for (int i = 0; i < keys.size(); ++i) {
// table->insert(keys[i]);
// }
}
static void Remove(itemType key, Table *table) {
table->remove(key);
}
CONTAIN_ATTRIBUTES static bool Contain(itemType key, const Table *table) {
return table->lookup(key);
}
static string get_name() {
return "std::set";
}
};
*/
//typedef struct FilterAPI<bloomfilter::bloom<uint64_t, 8, false, HashUtil>> filter_api_bloom;
/*
template<typename itemType, typename FingerprintType, typename HashFamily>
struct FilterAPI<xorfilter::XorFilter<itemType, FingerprintType, HashFamily>> {
using Table = xorfilter::XorFilter<itemType, FingerprintType, HashFamily>;
static Table ConstructFromAddCount(size_t add_count) { return Table(add_count); }
static void Add(uint64_t key, Table *table) {
throw std::runtime_error("Unsupported");
}
static void AddAll(const vector<itemType> keys, const size_t start, const size_t end, Table *table) {
table->AddAll(keys, start, end);
}
static void AddAll(const std::vector<itemType> keys, Table *table) {
table->AddAll(keys, 0, keys.size());
}
static void Remove(uint64_t key, Table *table) {
throw std::runtime_error("Unsupported");
}
CONTAIN_ATTRIBUTES static bool Contain(uint64_t key, const Table *table) {
return (0 == table->Contain(key));
}
};
template<typename itemType, typename FingerprintType, typename FingerprintStorageType, typename HashFamily>
struct FilterAPI<xorfilter2::XorFilter2<itemType, FingerprintType, FingerprintStorageType, HashFamily>> {
using Table = xorfilter2::XorFilter2<itemType, FingerprintType, FingerprintStorageType, HashFamily>;
static Table ConstructFromAddCount(size_t add_count) { return Table(add_count); }
static void Add(uint64_t key, Table *table) {
throw std::runtime_error("Unsupported");
}
static void AddAll(const vector<itemType> keys, const size_t start, const size_t end, Table *table) {
table->AddAll(keys, start, end);
}
static void AddAll(const std::vector<itemType> keys, Table *table) {
table->AddAll(keys, 0, keys.size());
}
static void Remove(uint64_t key, Table *table) {
throw std::runtime_error("Unsupported");
}
CONTAIN_ATTRIBUTES static bool Contain(uint64_t key, const Table *table) {
return (0 == table->Contain(key));
}
};
template<typename itemType, typename HashFamily>
struct FilterAPI<xorfilter::XorFilter10<itemType, HashFamily>> {
using Table = xorfilter::XorFilter10<itemType, HashFamily>;
static Table ConstructFromAddCount(size_t add_count) { return Table(add_count); }
static void Add(uint64_t key, Table *table) {
throw std::runtime_error("Unsupported");
}
static void AddAll(const vector<itemType> keys, const size_t start, const size_t end, Table *table) {
table->AddAll(keys, start, end);
}
static void AddAll(const std::vector<itemType> keys, Table *table) {
table->AddAll(keys, 0, keys.size());
}
static void Remove(uint64_t key, Table *table) {
throw std::runtime_error("Unsupported");
}
CONTAIN_ATTRIBUTES static bool Contain(uint64_t key, const Table *table) {
return (0 == table->Contain(key));
}
};
template<typename itemType, typename HashFamily>
struct FilterAPI<xorfilter::XorFilter13<itemType, HashFamily>> {
using Table = xorfilter::XorFilter13<itemType, HashFamily>;
static Table ConstructFromAddCount(size_t add_count) { return Table(add_count); }
static void Add(uint64_t key, Table *table) {
throw std::runtime_error("Unsupported");
}
static void AddAll(const vector<itemType> keys, const size_t start, const size_t end, Table *table) {
table->AddAll(keys, start, end);
}
static void AddAll(const std::vector<itemType> keys, Table *table) {
table->AddAll(keys, 0, keys.size());
}
static void Remove(uint64_t key, Table *table) {
throw std::runtime_error("Unsupported");
}
CONTAIN_ATTRIBUTES static bool Contain(uint64_t key, const Table *table) {
return (0 == table->Contain(key));
}
};
template<typename itemType, typename HashFamily>
struct FilterAPI<xorfilter::XorFilter10_666<itemType, HashFamily>> {
using Table = xorfilter::XorFilter10_666<itemType, HashFamily>;
static Table ConstructFromAddCount(size_t add_count) { return Table(add_count); }
static void Add(uint64_t key, Table *table) {
throw std::runtime_error("Unsupported");
}
static void AddAll(const vector<itemType> keys, const size_t start, const size_t end, Table *table) {
table->AddAll(keys, start, end);
}
static void AddAll(const std::vector<itemType> keys, Table *table) {
table->AddAll(keys, 0, keys.size());
}
static void Remove(uint64_t key, Table *table) {
throw std::runtime_error("Unsupported");
}
CONTAIN_ATTRIBUTES static bool Contain(uint64_t key, const Table *table) {
return (0 == table->Contain(key));
}
};
template<typename itemType, typename FingerprintType, typename FingerprintStorageType, typename HashFamily>
struct FilterAPI<xorfilter2n::XorFilter2n<itemType, FingerprintType, FingerprintStorageType, HashFamily>> {
using Table = xorfilter2n::XorFilter2n<itemType, FingerprintType, FingerprintStorageType, HashFamily>;
static Table ConstructFromAddCount(size_t add_count) { return Table(add_count); }
static void Add(uint64_t key, Table *table) {
throw std::runtime_error("Unsupported");
}
static void AddAll(const vector<itemType> keys, const size_t start, const size_t end, Table *table) {
table->AddAll(keys, start, end);
}
static void AddAll(const std::vector<itemType> keys, Table *table) {
table->AddAll(keys, 0, keys.size());
}
static void Remove(uint64_t key, Table *table) {
throw std::runtime_error("Unsupported");
}
CONTAIN_ATTRIBUTES static bool Contain(uint64_t key, const Table *table) {
return (0 == table->Contain(key));
}
};
template<typename itemType, typename FingerprintType, typename HashFamily>
struct FilterAPI<xorfilter_plus::XorFilterPlus<itemType, FingerprintType, HashFamily>> {
using Table = xorfilter_plus::XorFilterPlus<itemType, FingerprintType, HashFamily>;
static Table ConstructFromAddCount(size_t add_count) { return Table(add_count); }
static void Add(uint64_t key, Table *table) {
throw std::runtime_error("Unsupported");
}
static void AddAll(const vector<itemType> keys, const size_t start, const size_t end, Table *table) {
table->AddAll(keys, start, end);
}
static void AddAll(const std::vector<itemType> keys, Table *table) {
table->AddAll(keys, 0, keys.size());
}
static void Remove(uint64_t key, Table *table) {
throw std::runtime_error("Unsupported");
}
CONTAIN_ATTRIBUTES static bool Contain(uint64_t key, const Table *table) {
return (0 == table->Contain(key));
}
};
*/
#endif //FILTERS_WRAPPERS_HPP
| 27.29927 | 161 | 0.618865 | adam-morrison |
9991b56b62a55e134f4e51bad4c8017ebe807f11 | 764 | hpp | C++ | src/debug/TextMesh.hpp | bferan/lucent | b19163df12739ffc513110d927e92f98c0b54321 | [
"MIT"
] | 1 | 2021-11-12T08:42:43.000Z | 2021-11-12T08:42:43.000Z | src/debug/TextMesh.hpp | bferan/lucent | b19163df12739ffc513110d927e92f98c0b54321 | [
"MIT"
] | null | null | null | src/debug/TextMesh.hpp | bferan/lucent | b19163df12739ffc513110d927e92f98c0b54321 | [
"MIT"
] | null | null | null | #pragma once
#include "device/Device.hpp"
#include "debug/Font.hpp"
#include "rendering/Mesh.hpp"
namespace lucent
{
class TextMesh
{
public:
TextMesh(Device* device, const Font& font);
void SetScreenSize(uint32 width, uint32 height);
float Draw(const std::string& str, float x, float y, Color color = Color::White());
float Draw(char c, float screenX, float screenY, Color color = Color::White());
void Clear();
void Upload();
void Render(Context& context);
private:
const Font& m_Font;
bool m_Dirty;
std::vector<Mesh::Vertex> m_Vertices;
std::vector<uint32> m_Indices;
Device* m_Device;
Buffer* m_VertexBuffer;
Buffer* m_IndexBuffer;
uint32 m_ScreenWidth;
uint32 m_ScreenHeight;
};
}
| 17.767442 | 87 | 0.67801 | bferan |
999555c38ab2089f6515280071f0e9c1d48743f1 | 3,139 | cpp | C++ | src/test/test_disparities.cpp | ShnitzelKiller/Reverse-Engineering-Carpentry | 585b5ff053c7e3bf286b663a584bc83687691bd6 | [
"MIT"
] | 3 | 2021-09-08T07:28:13.000Z | 2022-03-02T21:12:40.000Z | src/test/test_disparities.cpp | ShnitzelKiller/Reverse-Engineering-Carpentry | 585b5ff053c7e3bf286b663a584bc83687691bd6 | [
"MIT"
] | 1 | 2021-09-21T14:40:55.000Z | 2021-09-26T01:19:38.000Z | src/test/test_disparities.cpp | ShnitzelKiller/Reverse-Engineering-Carpentry | 585b5ff053c7e3bf286b663a584bc83687691bd6 | [
"MIT"
] | null | null | null | //
// Created by James Noeckel on 10/13/20.
//
#include "reconstruction/ReconstructionData.h"
#include <opencv2/opencv.hpp>
using namespace Eigen;
void saveEpipolarLines(ReconstructionData &reconstruction) {
for (auto &pair : reconstruction.images) {
Vector3d origin1 = pair.second.origin();
double minL2 = std::numeric_limits<double>::max();
int matchImgInd = -1;
for (const auto &pair2 : reconstruction.images) {
if (pair.first != pair2.first) {
Vector3d origin2 = pair2.second.origin();
double L2 = (origin1 - origin2).squaredNorm();
if (L2 < minL2) {
minL2 = L2;
matchImgInd = pair2.first;
}
}
}
Vector3d center(0, 0, 0);
Vector2d midpoint1 = reconstruction.project(center.transpose(), pair.first).transpose();
Vector2d midpoint2 = reconstruction.project(center.transpose(), matchImgInd).transpose();
// Vector2d midpoint1 = reconstruction.resolution(pair.first) * 0.5;
// Vector2d midpoint2 = reconstruction.resolution(matchImgInd) * 0.5;
Vector2d epipolarLine1 = reconstruction.epipolar_line(midpoint1.y(), midpoint1.x(),
pair.first, matchImgInd);
Vector2d epipolarLine2 = reconstruction.epipolar_line(midpoint2.y(), midpoint2.x(),
matchImgInd, pair.first);
Vector2d startpoint1 = midpoint1 - epipolarLine1 * midpoint1.x();
Vector2d otherpoint1 = midpoint1 + epipolarLine1 * midpoint1.x();
Vector2d startpoint2 = midpoint2 - epipolarLine2 * midpoint2.x();
Vector2d otherpoint2 = midpoint2 + epipolarLine2 * midpoint2.x();
cv::Mat img1 = pair.second.getImage().clone();
cv::line(img1, cv::Point(startpoint1.x(), startpoint1.y()), cv::Point(otherpoint1.x(), otherpoint1.y()), cv::Scalar(255, 100, 255), 2);
cv::circle(img1, cv::Point(midpoint1.x(), midpoint1.y()), 2, cv::Scalar(0, 0, 255), CV_FILLED);
cv::imwrite("image_" + std::to_string(pair.first) + "_" + std::to_string(matchImgInd) + "_" + std::to_string(pair.first) + ".png", img1);
cv::Mat img2 = reconstruction.images[matchImgInd].getImage().clone();
cv::line(img2, cv::Point(startpoint2.x(), startpoint2.y()), cv::Point(otherpoint2.x(), otherpoint2.y()), cv::Scalar(255, 100, 255), 2);
cv::circle(img2, cv::Point(midpoint2.x(), midpoint2.y()), 2, cv::Scalar(0, 0, 255), CV_FILLED);
cv::imwrite("image_" + std::to_string(pair.first) + "_" + std::to_string(matchImgInd) + "_" + std::to_string(matchImgInd) + ".png", img2);
}
}
int main(int argc, char **argv) {
ReconstructionData reconstruction;
if (!reconstruction.load_bundler_file("../data/bench/alignment_complete3/complete3.out")) {
std::cout << "failed to load reconstruction" << std::endl;
return 1;
}
//saveEpipolarLines(reconstruction);
reconstruction.setImageScale(0.25);
saveEpipolarLines(reconstruction);
return 0;
} | 53.20339 | 146 | 0.61389 | ShnitzelKiller |
9995e36c1017e036a5b84650d2593e276195d63f | 19,392 | cpp | C++ | src-plugins/v3dView/v3dViewFiberInteractor.cpp | gpasquie/medInria-public | 1efa82292698695f6ee69fe00114aabce5431246 | [
"BSD-4-Clause"
] | null | null | null | src-plugins/v3dView/v3dViewFiberInteractor.cpp | gpasquie/medInria-public | 1efa82292698695f6ee69fe00114aabce5431246 | [
"BSD-4-Clause"
] | null | null | null | src-plugins/v3dView/v3dViewFiberInteractor.cpp | gpasquie/medInria-public | 1efa82292698695f6ee69fe00114aabce5431246 | [
"BSD-4-Clause"
] | null | null | null | /*=========================================================================
medInria
Copyright (c) INRIA 2013. All rights reserved.
See LICENSE.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.
=========================================================================*/
#include "v3dViewFiberInteractor.h"
#include <dtkCore/dtkAbstractData.h>
#include <dtkCore/dtkAbstractDataFactory.h>
#include <dtkCore/dtkAbstractView.h>
#include <dtkCore/dtkAbstractViewFactory.h>
#include <medMessageController.h>
#include <vtkSmartPointer.h>
#include <vtkPolyData.h>
#include <vtkFiberDataSetManager.h>
#include <vtkImageView.h>
#include <vtkImageView2D.h>
#include <vtkImageView3D.h>
#include <vtkLimitFibersToVOI.h>
#include <vtkPointData.h>
#include <vtkLookupTableManager.h>
#include <vtkFiberDataSet.h>
#include <vtkMatrix4x4.h>
#include <vtkLimitFibersToROI.h>
#include <vtkIsosurfaceManager.h>
#include <itkImage.h>
#include <itkImageToVTKImageFilter.h>
#include <itkFiberBundleStatisticsCalculator.h>
#include "v3dView.h"
#include "medVtkView.h"
#include <QInputDialog>
#include <QColorDialog>
class v3dViewFiberInteractorPrivate
{
public:
dtkAbstractData *data;
v3dView *view;
dtkAbstractData *projectionData;
vtkFiberDataSetManager *manager;
vtkIsosurfaceManager *roiManager;
vtkSmartPointer<vtkFiberDataSet> dataset;
QMap<QString, double> meanFAList;
QMap<QString, double> minFAList;
QMap<QString, double> maxFAList;
QMap<QString, double> varFAList;
QMap<QString, double> meanADCList;
QMap<QString, double> minADCList;
QMap<QString, double> maxADCList;
QMap<QString, double> varADCList;
QMap<QString, double> meanLengthList;
QMap<QString, double> minLengthList;
QMap<QString, double> maxLengthList;
QMap<QString, double> varLengthList;
};
v3dViewFiberInteractor::v3dViewFiberInteractor(): medAbstractVtkViewInteractor(), d(new v3dViewFiberInteractorPrivate)
{
d->data = 0;
d->dataset = 0;
d->view = 0;
d->manager = vtkFiberDataSetManager::New();
d->manager->SetHelpMessageVisibility(0);
d->roiManager = vtkIsosurfaceManager::New();
// d->manager->SetBoxWidget (0);
vtkLookupTable* lut = vtkLookupTableManager::GetSpectrumLookupTable();
d->manager->SetLookupTable(lut);
lut->Delete();
}
v3dViewFiberInteractor::~v3dViewFiberInteractor()
{
this->disable();
d->manager->Delete();
d->roiManager->Delete();
delete d;
d = 0;
}
QString v3dViewFiberInteractor::description() const
{
return tr("Interactor to help visualising Fibers");
}
QString v3dViewFiberInteractor::identifier() const
{
return "v3dViewFiberInteractor";
}
QStringList v3dViewFiberInteractor::handled() const
{
return QStringList () << v3dView::s_identifier() << medVtkView::s_identifier();
}
bool v3dViewFiberInteractor::isDataTypeHandled(QString dataType) const
{
if (dataType == "v3dDataFibers")
return true;
return false;
}
bool v3dViewFiberInteractor::registered()
{
return dtkAbstractViewFactory::instance()->registerViewInteractorType("v3dViewFiberInteractor",
QStringList () << v3dView::s_identifier() << medVtkView::s_identifier(),
createV3dViewFiberInteractor);
}
void v3dViewFiberInteractor::setData(dtkAbstractData *data)
{
if (!data)
return;
if (data->identifier()=="v3dDataFibers") {
if (vtkFiberDataSet *dataset = static_cast<vtkFiberDataSet *>(data->data())) {
d->dataset = dataset;
d->manager->SetInput (d->dataset);
if (!data->hasMetaData("BundleList"))
data->addMetaData("BundleList", QStringList());
if (!data->hasMetaData("BundleColorList"))
data->addMetaData("BundleColorList", QStringList());
// add bundles to 2d
vtkFiberDataSet::vtkFiberBundleListType bundles = d->dataset->GetBundleList();
vtkFiberDataSet::vtkFiberBundleListType::iterator it = bundles.begin();
while (it!=bundles.end())
{
if (d->view)
d->view->renderer2d()->AddActor(
d->manager->GetBundleActor ((*it).first ));
++it;
}
this->clearStatistics();
d->data = data;
}
}
}
dtkAbstractData *v3dViewFiberInteractor::data()
{
return d->data;
}
void v3dViewFiberInteractor::setView(dtkAbstractView *view)
{
if (v3dView *v3dview = qobject_cast<v3dView*>(view) ) {
d->view = v3dview;
d->manager->SetRenderer( d->view->renderer3d() );
d->manager->SetRenderWindowInteractor( d->view->interactor() );
d->view->renderer2d()->AddActor( d->manager->GetOutput() );
d->roiManager->SetRenderWindowInteractor( d->view->interactor() );
}
}
dtkAbstractView *v3dViewFiberInteractor::view()
{
return d->view;
}
void v3dViewFiberInteractor::enable()
{
if (this->enabled())
return;
if (d->view) {
d->manager->Enable();
d->roiManager->Enable();
if (d->dataset) {
vtkFiberDataSet::vtkFiberBundleListType bundles = d->dataset->GetBundleList();
vtkFiberDataSet::vtkFiberBundleListType::iterator it = bundles.begin();
while (it!=bundles.end())
{
if (d->view)
d->view->renderer2d()->AddActor(
d->manager->GetBundleActor ((*it).first ));
++it;
}
}
}
dtkAbstractViewInteractor::enable();
}
void v3dViewFiberInteractor::disable()
{
if (!this->enabled())
return;
if (d->view) {
d->manager->Disable();
d->roiManager->Disable();
if (d->dataset) {
vtkFiberDataSet::vtkFiberBundleListType bundles = d->dataset->GetBundleList();
vtkFiberDataSet::vtkFiberBundleListType::iterator it = bundles.begin();
while (it!=bundles.end())
{
if (d->view)
d->view->renderer2d()->RemoveActor(
d->manager->GetBundleActor ((*it).first ));
++it;
}
}
}
dtkAbstractViewInteractor::disable();
}
void v3dViewFiberInteractor::setVisibility(bool visible)
{
d->manager->SetVisibility(visible);
}
void v3dViewFiberInteractor::setBoxVisibility(bool visible)
{
if (d->view && d->view->property("Orientation") != "3D") {
medMessageController::instance()->showError("View must be in 3D mode to activate the bundling box",
3000);
d->manager->SetBoxWidget(false);
return;
}
d->manager->SetBoxWidget(visible);
d->view->update();
}
void v3dViewFiberInteractor::setRenderingMode(RenderingMode mode)
{
switch(mode)
{
case v3dViewFiberInteractor::Lines:
d->manager->SetRenderingModeToPolyLines();
break;
case v3dViewFiberInteractor::Ribbons:
d->manager->SetRenderingModeToRibbons();
break;
case v3dViewFiberInteractor::Tubes:
d->manager->SetRenderingModeToTubes();
break;
default:
qDebug() << "v3dViewFiberInteractor: unknown rendering mode";
}
d->view->update();
}
void v3dViewFiberInteractor::activateGPU(bool activate)
{
if (activate) {
vtkFibersManager::UseHardwareShadersOn();
d->manager->ChangeMapperToUseHardwareShaders();
} else {
vtkFibersManager::UseHardwareShadersOff();
d->manager->ChangeMapperToDefault();
}
d->view->update();
}
void v3dViewFiberInteractor::setColorMode(ColorMode mode)
{
switch(mode)
{
case v3dViewFiberInteractor::Local:
d->manager->SetColorModeToLocalFiberOrientation();
break;
case v3dViewFiberInteractor::Global:
d->manager->SetColorModelToGlobalFiberOrientation();
break;
case v3dViewFiberInteractor::FA:
d->manager->SetColorModeToLocalFiberOrientation();
for (int i=0; i<d->manager->GetNumberOfPointArrays(); i++) {
if (d->manager->GetPointArrayName (i)) {
if (strcmp ( d->manager->GetPointArrayName (i), "FA")==0)
{
d->manager->SetColorModeToPointArray (i);
break;
}
}
}
break;
default:
qDebug() << "v3dViewFiberInteractor: unknown color mode";
}
d->view->update();
}
void v3dViewFiberInteractor::setBoxBooleanOperation(BooleanOperation op)
{
switch(op)
{
case v3dViewFiberInteractor::Plus:
d->manager->GetVOILimiter()->SetBooleanOperationToAND();
break;
case v3dViewFiberInteractor::Minus:
d->manager->GetVOILimiter()->SetBooleanOperationToNOT();
break;
default:
qDebug() << "v3dViewFiberInteractor: Unknown boolean operations";
}
d->manager->GetVOILimiter()->Modified();
d->view->update();
}
void v3dViewFiberInteractor::tagSelection()
{
d->manager->SwapInputOutput();
d->view->update();
}
void v3dViewFiberInteractor::resetSelection()
{
d->manager->Reset();
d->view->update();
}
void v3dViewFiberInteractor::validateSelection(const QString &name, const QColor &color)
{
if (!d->data)
return;
double color_d[3] = {(double)color.red()/255.0, (double)color.green()/255.0, (double)color.blue()/255.0};
d->manager->Validate (name.toAscii().constData(), color_d);
d->view->renderer2d()->AddActor (d->manager->GetBundleActor(name.toAscii().constData()));
d->data->addMetaData("BundleList", name);
d->data->addMetaData("BundleColorList", color.name());
// reset to initial navigation state
d->manager->Reset();
d->view->update();
}
void v3dViewFiberInteractor::computeBundleFAStatistics (const QString &name,
double &mean,
double &min,
double &max,
double &var)
{
itk::FiberBundleStatisticsCalculator::Pointer statCalculator = itk::FiberBundleStatisticsCalculator::New();
statCalculator->SetInput (d->dataset->GetBundle (name.toAscii().constData()).Bundle);
try
{
statCalculator->Compute();
}
catch(itk::ExceptionObject &e)
{
qDebug() << e.GetDescription();
mean = 0.0;
min = 0.0;
max = 0.0;
var = 0.0;
return;
}
statCalculator->GetFAStatistics(mean, min, max, var);
}
void v3dViewFiberInteractor::bundleFAStatistics(const QString &name,
double &mean,
double &min,
double &max,
double &var)
{
if (!d->meanFAList.contains(name)) {
this->computeBundleFAStatistics(name, mean, min, max, var);
d->meanFAList[name] = mean;
d->minFAList[name] = min;
d->maxFAList[name] = max;
d->varFAList[name] = var;
}
else {
mean = d->meanFAList[name];
min = d->minFAList[name];
max = d->maxFAList[name];
var = d->varFAList[name];
}
}
void v3dViewFiberInteractor::computeBundleADCStatistics (const QString &name,
double &mean,
double &min,
double &max,
double &var)
{
itk::FiberBundleStatisticsCalculator::Pointer statCalculator = itk::FiberBundleStatisticsCalculator::New();
statCalculator->SetInput (d->dataset->GetBundle (name.toAscii().constData()).Bundle);
try
{
statCalculator->Compute();
}
catch(itk::ExceptionObject &e)
{
qDebug() << e.GetDescription();
mean = 0.0;
min = 0.0;
max = 0.0;
var = 0.0;
return;
}
statCalculator->GetADCStatistics(mean, min, max, var);
}
void v3dViewFiberInteractor::bundleADCStatistics(const QString &name,
double &mean,
double &min,
double &max,
double &var)
{
if (!d->meanADCList.contains(name)) {
this->computeBundleADCStatistics(name, mean, min, max, var);
d->meanADCList[name] = mean;
d->minADCList[name] = min;
d->maxADCList[name] = max;
d->varADCList[name] = var;
}
else {
mean = d->meanADCList[name];
min = d->minADCList[name];
max = d->maxADCList[name];
var = d->varADCList[name];
}
}
void v3dViewFiberInteractor::computeBundleLengthStatistics (const QString &name,
double &mean,
double &min,
double &max,
double &var)
{
itk::FiberBundleStatisticsCalculator::Pointer statCalculator = itk::FiberBundleStatisticsCalculator::New();
statCalculator->SetInput (d->dataset->GetBundle (name.toAscii().constData()).Bundle);
try
{
statCalculator->Compute();
}
catch(itk::ExceptionObject &e)
{
qDebug() << e.GetDescription();
mean = 0.0;
min = 0.0;
max = 0.0;
var = 0.0;
return;
}
statCalculator->GetLengthStatistics(mean, min, max, var);
}
void v3dViewFiberInteractor::bundleLengthStatistics(const QString &name,
double &mean,
double &min,
double &max,
double &var)
{
if (!d->meanLengthList.contains(name)) {
this->computeBundleLengthStatistics(name, mean, min, max, var);
d->meanLengthList[name] = mean;
d->minLengthList[name] = min;
d->maxLengthList[name] = max;
d->varLengthList[name] = var;
}
else {
mean = d->meanLengthList[name];
min = d->minLengthList[name];
max = d->maxLengthList[name];
var = d->varLengthList[name];
}
}
void v3dViewFiberInteractor::clearStatistics(void)
{
d->meanFAList.clear();
d->minFAList.clear();
d->maxFAList.clear();
d->varFAList.clear();
d->meanADCList.clear();
d->minADCList.clear();
d->maxADCList.clear();
d->varADCList.clear();
d->meanLengthList.clear();
d->minLengthList.clear();
d->maxLengthList.clear();
d->varLengthList.clear();
}
void v3dViewFiberInteractor::setProjection(const QString& value)
{
if (!d->view)
return;
if (value=="true") {
d->view->view2d()->AddDataSet( d->manager->GetCallbackOutput() );
}
}
void v3dViewFiberInteractor::setRadius (int value)
{
d->manager->SetRadius (value);
if (d->view)
d->view->update();
}
void v3dViewFiberInteractor::setROI(dtkAbstractData *data)
{
if (!data)
return;
if (data->identifier()!="itkDataImageUChar3")
return;
typedef itk::Image<unsigned char, 3> ROIType;
ROIType::Pointer roiImage = static_cast<ROIType*>(data->data());
if (!roiImage.IsNull()) {
itk::ImageToVTKImageFilter<ROIType>::Pointer converter = itk::ImageToVTKImageFilter<ROIType>::New();
converter->SetReferenceCount(2);
converter->SetInput(roiImage);
converter->Update();
ROIType::DirectionType directions = roiImage->GetDirection();
vtkMatrix4x4 *matrix = vtkMatrix4x4::New();
matrix->Identity();
for (int i=0; i<3; i++)
for (int j=0; j<3; j++)
matrix->SetElement (i, j, directions (i,j));
d->manager->Reset();
d->manager->GetROILimiter()->SetMaskImage (converter->GetOutput());
d->manager->GetROILimiter()->SetDirectionMatrix (matrix);
ROIType::PointType origin = roiImage->GetOrigin();
vtkMatrix4x4 *matrix2 = vtkMatrix4x4::New();
matrix2->Identity();
for (int i=0; i<3; i++)
for (int j=0; j<3; j++)
matrix2->SetElement (i, j, directions (i,j));
double v_origin[4], v_origin2[4];
for (int i=0; i<3; i++)
v_origin[i] = origin[i];
v_origin[3] = 1.0;
matrix->MultiplyPoint (v_origin, v_origin2);
for (int i=0; i<3; i++)
matrix2->SetElement (i, 3, v_origin[i]-v_origin2[i]);
d->roiManager->SetInput (converter->GetOutput());
d->roiManager->SetDirectionMatrix (matrix2);
// d->manager->GetROILimiter()->Update();
d->roiManager->GenerateData();
matrix->Delete();
matrix2->Delete();
}
else {
d->manager->GetROILimiter()->SetMaskImage (0);
d->manager->GetROILimiter()->SetDirectionMatrix (0);
d->roiManager->ResetData();
}
d->view->update();
}
void v3dViewFiberInteractor::setRoiBoolean(int roi, int meaning)
{
d->manager->GetROILimiter()->SetBooleanOperation (roi, meaning);
d->view->update();
}
int v3dViewFiberInteractor::roiBoolean(int roi)
{
return d->manager->GetROILimiter()->GetBooleanOperationVector()[roi+1];
}
void v3dViewFiberInteractor::setBundleVisibility(const QString &name, bool visibility)
{
d->manager->SetBundleVisibility(name.toAscii().constData(), (int)visibility);
d->view->update();
}
bool v3dViewFiberInteractor::bundleVisibility(const QString &name) const
{
return d->manager->GetBundleVisibility(name.toAscii().constData());
}
void v3dViewFiberInteractor::setAllBundlesVisibility(bool visibility)
{
if (visibility)
d->manager->ShowAllBundles();
else
d->manager->HideAllBundles();
d->view->update();
}
void v3dViewFiberInteractor::setOpacity(dtkAbstractData * /*data*/, double /*opacity*/)
{
}
double v3dViewFiberInteractor::opacity(dtkAbstractData * /*data*/) const
{
//TODO
return 100;
}
void v3dViewFiberInteractor::setVisible(dtkAbstractData * /*data*/, bool /*visible*/)
{
//TODO
}
bool v3dViewFiberInteractor::isVisible(dtkAbstractData * /*data*/) const
{
//TODO
return true;
}
// /////////////////////////////////////////////////////////////////
// Type instantiation
// /////////////////////////////////////////////////////////////////
dtkAbstractViewInteractor *createV3dViewFiberInteractor()
{
return new v3dViewFiberInteractor;
}
| 29.248869 | 146 | 0.569565 | gpasquie |
9995eeacaf1d87cdb211400fd56c8653626272fd | 28,059 | cpp | C++ | cpp-projects/base/files/assimp_loader.cpp | FlorianLance/toolbox | 87882a14ec86852d90527c81475b451b9f6e12cf | [
"MIT"
] | null | null | null | cpp-projects/base/files/assimp_loader.cpp | FlorianLance/toolbox | 87882a14ec86852d90527c81475b451b9f6e12cf | [
"MIT"
] | null | null | null | cpp-projects/base/files/assimp_loader.cpp | FlorianLance/toolbox | 87882a14ec86852d90527c81475b451b9f6e12cf | [
"MIT"
] | 1 | 2021-07-06T14:47:41.000Z | 2021-07-06T14:47:41.000Z |
/*******************************************************************************
** Toolbox-base **
** MIT License **
** Copyright (c) [2018] [Florian Lance] **
** **
** 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 "assimp_loader.hpp"
// std
#include <filesystem>
#include <algorithm>
// assimp
#include <assimp/Importer.hpp>
#include <assimp/postprocess.h>
using namespace tool::geo;
using namespace tool::files;
//Texture2D *AiLoader::read_texture(Model *model, aiMaterial *mat, aiTextureType type, unsigned int index){
// // ai data
// aiString path; // receives the path to the texture. If the texture is embedded, receives a '*' followed by the id of the texture
// // (for the textures stored in the corresponding scene) which can be converted to an int using a function like atoi. NULL is a valid value
// aiTextureMapping mapping; // texture mapping, NULL is allowed as value
// unsigned int uvIndex; // uv index of the texture (NULL is valid value)
// ai_real blend; // blend factor for the texture
// aiTextureOp operation; // texture operation to be performed between this texture and the previous texture
// aiTextureMapMode mapMode[3];// mapping modes to be used for the texture, the parameter may be NULL but if it is a valid pointer it MUST
// // point to an array of 3 aiTextureMapMode's (one for each axis: UVW order (=XYZ)).
// mat->GetTexture(type, index, &path, &mapping, &uvIndex, &blend, &operation, &mapMode[0]);
// // auto wrapping = read_texture_property<int>(MatP::text_mapping, aiMat, texturesPerType.first, ii).value();
// // auto uvwSource = read_texture_property<int>(MatP::text_uvw_source, aiMat, texturesPerType.first, ii).value();
// // auto mappingModeU = read_texture_property<int>(MatP::text_mapping_mode_u, aiMat, texturesPerType.first, ii).value();
// // auto mappingModeV = read_texture_property<int>(MatP::text_mapping_mode_v, aiMat, texturesPerType.first, ii).value();
// // auto flags = read_texture_property<int>(MatP::text_flags, aiMat, texturesPerType.first, ii).value();
// // auto texmapAxis = read_texture_property<aiVector3D>(MatP::text_texmap_axis, aiMat, texturesPerType.first, ii).value();
// // auto blend = read_texture_property<float>(MatP::text_blend, aiMat, texturesPerType.first, ii).value();
// // find texture
// namespace fs = std::filesystem;
// const std::string aiPath = path.C_Str();
// if(aiPath.length() > 0){
// if(aiPath[0] == '*'){
// std::cout << "[ASSIMP_LOADER] Embedded texture detected, not managed yet\n";
// return nullptr;
// }
// }
// fs::path texturePath = aiPath;
// if(!fs::exists(texturePath)){ // check if full path exist
// fs::path dirPath = model->directory;
// std_v1<fs::path> pathsToTest;
// pathsToTest.emplace_back(dirPath / texturePath.filename());
// pathsToTest.emplace_back(dirPath / "texture" / texturePath.filename());
// pathsToTest.emplace_back(dirPath / "textures" / texturePath.filename());
// pathsToTest.emplace_back(dirPath / ".." / "texture" / texturePath.filename());
// pathsToTest.emplace_back(dirPath / ".." / "textures" / texturePath.filename());
// bool found = false;
// for(const auto &pathToTest : pathsToTest){
// if(fs::exists(pathToTest)){
// found = true;
// texturePath = pathToTest;
// break;
// }
// }
// if(!found){
// std::cerr << "[ASSIMP_LOADER] Cannot find texture " << texturePath.filename() << "\n";
// return nullptr;
// }
// }
// std::string foundPath = texturePath.u8string();
// auto textures = &model->m_textures;
// if(textures->count(foundPath) == 0){
// // load texture
// Texture2D texture(foundPath);
// // type
// texture.type = get_texture_type(type);
// // mapping
// texture.mapping = get_texture_mapping(mapping);
// // operation
// texture.operation = get_texture_operation(operation);
// // mapMode
// texture.mapMode = Pt3<TexMapMode>{get_texture_map_mode(mapMode[0]),get_texture_map_mode(mapMode[1]),get_texture_map_mode(mapMode[2])};
// // add texture to model
// (*textures)[foundPath] = std::move(texture);
// }
// return &(*textures)[foundPath];
//}
std::shared_ptr<Model> AiLoader::load_model(std::string path, bool verbose){
if(verbose){
std::cout << "[ASSIMP_LOADER] Load model with path: " << path << "\n";
}
namespace fs = std::filesystem;
fs::path pathModel = path;
if(!fs::exists(pathModel)){
// throw std::runtime_error("[ASSIMP_LOADER] Path " + path + " doesn't exists, cannot load model.\n");
std::cerr << "[ASSIMP_LOADER] Path " << path << " doesn't exists, cannot load model.\n";
return nullptr;
}
// read from assimp
Assimp::Importer import;
const aiScene *scene = import.ReadFile(path, aiProcess_Triangulate); // aiProcess_EmbedTextures / aiProcess_FlipUVs
if(!scene || scene->mFlags & AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode){
std::cerr << "[ASSIMP_LOADER] " << import.GetErrorString() << "\n";
return nullptr;
}
// create model
auto model = std::make_shared<Model>();
model->directory = pathModel.parent_path().string();
model->name = scene->mRootNode->mName.C_Str();
if(verbose){
std::cout << "[ASSIMP_LOADER] Model name: " << model->name << "\n";
}
// retrieve global inverse transform
model->globalInverseTr = scene->mRootNode->mTransformation;
model->globalInverseTr.Inverse();
auto m = scene->mRootNode->mTransformation;
m.Inverse();
model->globalInverseTr2 = geo::Mat4f{
m.a1,m.a2,m.a3,m.a4,
m.b1,m.b2,m.b3,m.b4,
m.c1,m.c2,m.c3,m.c4,
m.d1,m.d2,m.d3,m.d4,
};
// aiVector3t<float> aiTr,aiRot,aiSc;
// m_GlobalInverseTransform.Decompose(aiSc,aiRot,aiTr);
// auto r = geo::Pt3f{aiRot.x,aiRot.y,aiRot.z};
// model->globalInverseTr = geo::Mat4f::transform(
// geo::Pt3f{aiSc.x,aiSc.y,aiSc.z},
// geo::Pt3f{rad_2_deg(r.x()),rad_2_deg(r.y()),rad_2_deg(r.z())},
// geo::Pt3f{aiTr.x,aiTr.y,aiTr.z}
// );
// std::cout << "GLOBAL INVERSE:\n " <<geo::Pt3f{aiSc.x,aiSc.y,aiSc.z} << " " << geo::Pt3f{rad_2_deg(r.x()),rad_2_deg(r.y()),rad_2_deg(r.z())} << " "<< geo::Pt3f{aiTr.x,aiTr.y,aiTr.z} << "\n";
// // read embedded textures // EMBEDDED
// if(scene->HasTextures()){
// for(size_t ii = 0; ii < scene->mNumTextures; ++ii){
// auto aiTexture = scene->mTextures[ii];
// std::string file = aiTexture->mFilename.C_Str();
// std::cout << "embedded texture " << ii << " " << file << " " << aiTexture->mWidth << " " << aiTexture->mHeight << "\n";
// for(size_t jj = 0; jj < aiTexture->mWidth * aiTexture->mHeight; ++jj){
// aiTexture->pcData->r;
// aiTexture->pcData->g;
// aiTexture->pcData->b;
// aiTexture->pcData->a;
// }
// }
// }
// retrieve materials
if(scene->HasMaterials()){
if(verbose){
std::cout << "[ASSIMP_LOADER] Load materials: " << scene->mNumMaterials << "\n";
}
for(size_t ii = 0; ii < scene->mNumMaterials; ++ii){
read_material(model.get(), scene->mMaterials[ii]);
}
}
// retrieve meshes
if(scene->HasMeshes()){
if(verbose){
std::cout << "[ASSIMP_LOADER] Load meshes: " << scene->mNumMeshes << "\n";
}
for(size_t ii = 0; ii < scene->mNumMeshes; ++ii){
if(verbose){
std::cout << "[ASSIMP_LOADER] Mesh: " << scene->mMeshes[ii]->mName.C_Str() << "\n";
}
read_mesh(model.get(), scene->mMeshes[ii]);
}
}
// retrieve animations
if(scene->HasAnimations()){
if(verbose){
std::cout << "[ASSIMP_LOADER] Load animations: " << scene->mNumAnimations << "\n";
}
for(size_t ii = 0; ii < scene->mNumAnimations; ++ii){
if(verbose){
std::cout << "[ASSIMP_LOADER] Animation: " << scene->mAnimations[ii]->mName.C_Str() << "\n";
}
auto assimpAnimation = scene->mAnimations[ii];
graphics::Animation animation;
animation.duration = assimpAnimation->mDuration;
animation.ticksPerSecond = assimpAnimation->mTicksPerSecond;
animation.name = assimpAnimation->mName.C_Str();
for(size_t jj = 0; jj < assimpAnimation->mNumChannels; ++jj){
auto assimpChannel = assimpAnimation->mChannels[jj];
const std::string affectedNodeName = assimpChannel->mNodeName.C_Str();
tool::graphics::AnimationKeys keys;
keys.positionTimes.resize(assimpChannel->mNumPositionKeys);
keys.positionKeys.resize(assimpChannel->mNumPositionKeys);
for(size_t kk = 0; kk < keys.positionTimes.size(); ++kk){
auto &key = assimpChannel->mPositionKeys[kk];
keys.positionTimes[kk] = key.mTime;
keys.positionKeys[kk] = {key.mValue.x,key.mValue.y,key.mValue.z};
}
keys.rotationTimes.resize(assimpChannel->mNumRotationKeys);
keys.rotationKeys.resize(assimpChannel->mNumRotationKeys);
for(size_t kk = 0; kk < keys.rotationTimes.size(); ++kk){
auto &key = assimpChannel->mRotationKeys[kk];
keys.rotationTimes[kk] = key.mTime;
keys.rotationKeys[kk] = {key.mValue.x,key.mValue.y,key.mValue.z, key.mValue.w};
}
keys.scalingTimes.resize(assimpChannel->mNumScalingKeys);
keys.scalingKeys.resize(assimpChannel->mNumScalingKeys);
for(size_t kk = 0; kk < keys.scalingTimes.size(); ++kk){
auto &key = assimpChannel->mScalingKeys[kk];
keys.scalingTimes[kk] = key.mTime;
keys.scalingKeys[kk] = {key.mValue.x,key.mValue.y,key.mValue.z};
}
model->animationsKeys[animation.name][affectedNodeName] = std::move(keys);
}
model->animations.emplace_back(std::move(animation));
}
}
// bones
read_bones_hierarchy(&model->bonesHierachy, scene->mRootNode);
return model;
}
void AiLoader::read_mesh(Model *model, aiMesh *aiMesh){
bool verbose = false;
auto gmesh = std::make_shared<GMesh>();
gmesh->name = aiMesh->mName.C_Str();
gmesh->material = &model->m_materials[aiMesh->mMaterialIndex];
Mesh *mesh = &gmesh->mesh;
bool hasPoints = aiMesh->mPrimitiveTypes & aiPrimitiveType::aiPrimitiveType_POINT;
bool hasLines = aiMesh->mPrimitiveTypes & aiPrimitiveType::aiPrimitiveType_LINE;
bool hasTriangles = aiMesh->mPrimitiveTypes & aiPrimitiveType::aiPrimitiveType_TRIANGLE;
bool hasPolygons = aiMesh->mPrimitiveTypes & aiPrimitiveType::aiPrimitiveType_POLYGON;
// process vertex positions, normals and texture coordinates
mesh->vertices.reserve(aiMesh->mNumVertices);
if(aiMesh->HasNormals()){
mesh->normals.reserve(aiMesh->mNumVertices);
}
if(aiMesh->HasTextureCoords(0)){
mesh->tCoords.reserve(aiMesh->mNumVertices);
}else{
mesh->tCoords.resize(aiMesh->mNumVertices);
std::fill(std::begin(mesh->tCoords), std::end(mesh->tCoords), Pt2f{0.f,0.f});
}
if(aiMesh->HasTangentsAndBitangents()){
mesh->tangents.resize(aiMesh->mNumVertices);
}
if(aiMesh->HasVertexColors(0)){
mesh->colors.reserve(aiMesh->mNumVertices);
}
if(aiMesh->HasBones()){
mesh->bones.resize(aiMesh->mNumVertices);
}
for(unsigned int ii = 0; ii < aiMesh->mNumVertices; ii++){
// position
mesh->vertices.emplace_back(Pt3f{aiMesh->mVertices[ii].x, aiMesh->mVertices[ii].y, aiMesh->mVertices[ii].z});
// normal
if(aiMesh->HasNormals()){
mesh->normals.emplace_back(Vec3f{aiMesh->mNormals[ii].x, aiMesh->mNormals[ii].y, aiMesh->mNormals[ii].z});
}
// uv
// aiMesh->GetNumUVChannels()
if(aiMesh->HasTextureCoords(0)){
mesh->tCoords.emplace_back(Pt2f{aiMesh->mTextureCoords[0][ii].x, aiMesh->mTextureCoords[0][ii].y});
}
// tangents
if(aiMesh->HasTangentsAndBitangents()){
mesh->tangents.emplace_back(Pt4f{aiMesh->mTangents->x,aiMesh->mTangents->y,aiMesh->mTangents->z,1.f});
}
// colors
// aiMesh->GetNumColorChannels()
if(aiMesh->HasVertexColors(0)){
mesh->colors.emplace_back(Pt4f{
aiMesh->mColors[0][ii].r,
aiMesh->mColors[0][ii].g,
aiMesh->mColors[0][ii].b,
aiMesh->mColors[0][ii].a
});
}
// aiMesh->mBitangents
// aiMesh->mMethod
// aiMesh->mAnimMeshes
}
// process indices
if(hasTriangles && !hasPoints && !hasLines && !hasPolygons){
mesh->triIds.reserve(aiMesh->mNumFaces);
for(unsigned int ii = 0; ii < aiMesh->mNumFaces; ii++){
aiFace face = aiMesh->mFaces[ii];
mesh->triIds.emplace_back(TriIds{face.mIndices[0], face.mIndices[1], face.mIndices[2]});
}
}else{
std::cerr << "[ASSIMP_LOADER] Face format not managed.\n";
}
// compute normals if necessary
if(!aiMesh->HasNormals()){
mesh->generate_normals();
}
// generate tangents if necessary
if(!aiMesh->HasTangentsAndBitangents() && (mesh->normals.size() > 0) && aiMesh->HasTextureCoords(0)){
mesh->generate_tangents();
}
// if(mesh->tangents.size() != mesh->vertices.size()){
// std::cout << "[ASSIMP_LOADER] Invalid tangents. Recomputing.\n";
// mesh->generate_tangents();
// }
// bones
if(aiMesh->HasBones()){
// for (uint i = 0 ; i < pMesh->mNumBones ; i++) {
// uint BoneIndex = 0;
// string BoneName(pMesh->mBones[i]->mName.data);
// if (m_BoneMapping.find(BoneName) == m_BoneMapping.end()) {
// BoneIndex = m_NumBones;
// m_NumBones++;
// BoneInfo bi;
// m_BoneInfo.push_back(bi);
// }
// else {
// BoneIndex = m_BoneMapping[BoneName];
// }
// m_BoneMapping[BoneName] = BoneIndex;
// m_BoneInfo[BoneIndex].BoneOffset = pMesh->mBones[i]->mOffsetMatrix;
// for (uint j = 0 ; j < pMesh->mBones[i]->mNumWeights ; j++) {
// uint VertexID = m_Entries[MeshIndex].BaseVertex + pMesh->mBones[i]->mWeights[j].mVertexId;
// float Weight = pMesh->mBones[i]->mWeights[j].mWeight;
// Bones[VertexID].AddBoneData(BoneIndex, Weight);
// }
// }
if(verbose){
std::cout << "Num bones: " << aiMesh->mNumBones << "\n";
}
for(size_t ii = 0; ii < aiMesh->mNumBones; ++ii){
unsigned int boneIndex = 0;
auto bone = aiMesh->mBones[ii];
std::string boneName(bone->mName.C_Str());
if(verbose){
std::cout << "Bone: " << boneName << "\n";
}
if(model->bonesMapping.count(boneName) == 0){
boneIndex = static_cast<unsigned int>(model->bonesMapping.size());
model->bonesInfo.emplace_back(graphics::BoneInfo{});
// model->bonesMapping[boneName] = boneIndex;
if(verbose){
std::cout << "Add bone in mapping, current index: " << boneIndex << " " << model->bonesMapping.size() << "\n";
}
}else{
boneIndex = model->bonesMapping[boneName];
if(verbose){
std::cout << "Bone already in mapping at index: " << boneIndex << "\n";
}
}
model->bonesMapping[boneName] = boneIndex;
model->bonesInfo[boneIndex].offset = bone->mOffsetMatrix;
// model->bonesInfo[boneIndex].offset = geo::Mat4f
// {
// m.a1,m.a2,m.a3,m.a4,
// m.b1,m.b2,m.b3,m.b4,
// m.c1,m.c2,m.c3,m.c4,
// m.d1,m.d2,m.d3,m.d4,
// };
// // bone offset
// // # decompose
// aiVector3t<float> aiTr,aiRot,aiSc;
// bone->mOffsetMatrix.Decompose(aiSc,aiRot,aiTr);
// // # create offset transform
// auto r = geo::Pt3f{aiRot.x,aiRot.y,aiRot.z};
// model->bonesInfo[boneIndex].offset = geo::Mat4f::transform(
// geo::Pt3f{aiSc.x,aiSc.y,aiSc.z},
// geo::Pt3f{rad_2_deg(r.x()),rad_2_deg(r.y()),rad_2_deg(r.z())},
//// geo::Pt3f{(r.x()),(r.y()),(r.z())},
// geo::Pt3f{aiTr.x,aiTr.y,aiTr.z}
// );
if(verbose){
std::cout << "Num weights: " << bone->mNumWeights << "\n";
}
for (size_t jj = 0 ; jj < bone->mNumWeights; jj++) {
unsigned int VertexId = bone->mWeights[jj].mVertexId;
float Weight = bone->mWeights[jj].mWeight;
mesh->bones[VertexId].add_bone_data(boneIndex, Weight);
}
}
}
model->gmeshes.emplace_back(std::move(gmesh));
}
void AiLoader::read_material(Model *model, aiMaterial *aiMat){
using MatP = Material::Property;
// read properties
Material material;
// # str
material.name = to_string(read_property<aiString>(MatP::name, aiMat));
// # int
material.backfaceCulling = read_property<int>(MatP::twosided, aiMat).value() != 0;
material.wireframe = read_property<int>(MatP::enable_wireframe, aiMat).value() != 0;
// # float
material.opacity = read_property<float>(MatP::opacity, aiMat).value();
material.shininess = read_property<float>(MatP::shininess, aiMat).value();
material.shininessStrength = read_property<float>(MatP::shininess_strength, aiMat).value();
material.refraction = read_property<float>(MatP::refacti, aiMat).value();
material.reflectivity = read_property<float>(MatP::reflectivity, aiMat).value();
// # point3f
material.ambiantColor = to_color(read_property<aiColor3D>(MatP::color_ambient, aiMat));
material.diffuseColor = to_color(read_property<aiColor3D>(MatP::color_diffuse, aiMat));
material.specularColor = to_color(read_property<aiColor3D>(MatP::color_specular, aiMat));
material.emissiveColor = to_color(read_property<aiColor3D>(MatP::color_emissive, aiMat));
material.transparentColor = to_color(read_property<aiColor3D>(MatP::color_transparent, aiMat));
material.reflectiveColor = to_color(read_property<aiColor3D>(MatP::color_reflective, aiMat));
// mat.mNumAllocated;
// mat.mNumProperties;
// read textures
for(const auto &type : textureTypes.data){
for(unsigned int ii = 0; ii < aiMat->GetTextureCount(std::get<1>(type)); ++ii){
// ai data
aiString path; // receives the path to the texture. If the texture is embedded, receives a '*' followed by the id of the texture
// (for the textures stored in the corresponding scene) which can be converted to an int using a function like atoi. NULL is a valid value
aiTextureMapping mapping = aiTextureMapping_UV; // texture mapping, NULL is allowed as value
unsigned int uvIndex; // uv index of the texture (NULL is valid value)
ai_real blend; // blend factor for the texture
aiTextureOp operation = aiTextureOp_Multiply;// texture operation to be performed between this texture and the previous texture
aiTextureMapMode mapMode[3];// mapping modes to be used for the texture, the parameter may be NULL but if it is a valid pointer it MUST
aiMat->GetTexture(std::get<1>(type), ii, &path, &mapping, &uvIndex, &blend, &operation, &mapMode[0]);
if(auto pathTexture = retrieve_texture_path(model, path); pathTexture.has_value()){
Texture2D *texture = nullptr;
if(model->m_textures.count(pathTexture.value()) == 0){ // add texture
model->m_textures[pathTexture.value()] = Texture2D(pathTexture.value());
}
texture = &model->m_textures[pathTexture.value()];
TextureInfo textureInfo;
textureInfo.texture = texture;
textureInfo.options.type = std::get<0>(type);
textureInfo.options.mapping = get_texture_mapping(mapping);
textureInfo.options.operation = get_texture_operation(operation);
textureInfo.options.mapMode = Pt3<TextureMapMode>{
get_texture_map_mode(mapMode[0]),
get_texture_map_mode(mapMode[1]),
get_texture_map_mode(mapMode[2])
};
// others textures info
auto wrapping = read_texture_property<int>(MatP::text_mapping, aiMat, textureInfo.options.type, ii).value();
auto uvwSource = read_texture_property<int>(MatP::text_uvw_source, aiMat, textureInfo.options.type, ii).value();
auto mappingModeU = read_texture_property<int>(MatP::text_mapping_mode_u, aiMat, textureInfo.options.type, ii).value();
auto mappingModeV = read_texture_property<int>(MatP::text_mapping_mode_v, aiMat, textureInfo.options.type, ii).value();
auto flags = read_texture_property<int>(MatP::text_flags, aiMat, textureInfo.options.type, ii).value();
auto texmapAxis = read_texture_property<aiVector3D>(MatP::text_texmap_axis, aiMat, textureInfo.options.type, ii).value();
auto blend = read_texture_property<float>(MatP::text_blend, aiMat, textureInfo.options.type, ii).value();
static_cast<void>(wrapping);
static_cast<void>(uvwSource);
static_cast<void>(mappingModeU);
static_cast<void>(mappingModeV);
static_cast<void>(flags);
static_cast<void>(texmapAxis);
static_cast<void>(blend);
// name,twosided,shading_model,enable_wireframe,blend_func,opacity, bumpscaling, shininess, reflectivity,
// shininess_strength, refacti, color_diffuse, color_ambient, color_specular, color_emissive, color_transparent,
// color_reflective, global_background_image,
// text_blend, text_mapping, text_operation, text_uvw_source,
// text_mapping_mode_u, text_mapping_mode_v,
// text_texmap_axis, text_flags,
// add infos
material.texturesInfo[textureInfo.options.type].emplace_back(std::move(textureInfo));
}
}
}
model->m_materials.emplace_back(std::move(material));
}
std::optional<std::string> AiLoader::retrieve_texture_path(Model *model, const aiString &aiPath){
const std::string path = aiPath.C_Str();
if(path.length() > 0){
if(path[0] == '*'){
std::cout << "[ASSIMP_LOADER] Embedded texture detected, not managed yet\n";
return {};
}
}
namespace fs = std::filesystem;
fs::path texturePath = path;
std::error_code code;
if(!fs::exists(texturePath,code)){ // check if full path exist
fs::path dirPath = model->directory;
std_v1<fs::path> pathsToTest;
pathsToTest.emplace_back(dirPath / texturePath.filename());
pathsToTest.emplace_back(dirPath / "texture" / texturePath.filename());
pathsToTest.emplace_back(dirPath / "textures" / texturePath.filename());
pathsToTest.emplace_back(dirPath / ".." / "texture" / texturePath.filename());
pathsToTest.emplace_back(dirPath / ".." / "textures" / texturePath.filename());
bool found = false;
for(const auto &pathToTest : pathsToTest){
if(fs::exists(pathToTest)){
found = true;
texturePath = pathToTest;
break;
}
}
if(!found){
std::cerr << "[ASSIMP_LOADER] Cannot find texture " << texturePath.filename() << "\n";
return {};
}
}
// found path
return texturePath.string();
}
void AiLoader::read_bones_hierarchy(tool::graphics::BonesHierarchy *bones, aiNode *node){
bones->boneName = node->mName.C_Str();
// set transform
// const auto &m = node->mTransformation;
// aiVector3t<float> aiTr,aiRot,aiSc;
// node->mTransformation.Decompose(aiSc,aiRot,aiTr);
// auto r = geo::Pt3f{aiRot.x,aiRot.y,aiRot.z};
// bones->tr = geo::Mat4f::transform(
// geo::Pt3f{aiSc.x,aiSc.y,aiSc.z},
// geo::Pt3f{rad_2_deg(r.x()),rad_2_deg(r.y()),rad_2_deg(r.z())},
//// geo::Pt3f{(r.x()),(r.y()),(r.z())},
// geo::Pt3f{aiTr.x,aiTr.y,aiTr.z}
// );
bones->tr = node->mTransformation;
// const auto &m = node->mTransformation;//.Transpose();
// bones->tr = geo::Mat4f
// {
// m.a1,m.a2,m.a3,m.a4,
// m.b1,m.b2,m.b3,m.b4,
// m.c1,m.c2,m.c3,m.c4,
// m.d1,m.d2,m.d3,m.d4,
// };
// std::cout << "TR: " << geo::Pt3f{aiSc.x,aiSc.y,aiSc.z} << " " << geo::Pt3f{rad_2_deg(r.x()),rad_2_deg(r.y()),rad_2_deg(r.z())} << " " << geo::Pt3f{aiTr.x,aiTr.y,aiTr.z} << "\n";
for(size_t ii = 0; ii < node->mNumChildren; ++ii){
graphics::BonesHierarchy bh;
read_bones_hierarchy(&bh, node->mChildren[ii]);
bones->children.emplace_back(std::move(bh));
}
}
| 41.202643 | 197 | 0.572544 | FlorianLance |
999825db590c44fa8bd30f1ba9d1112b526bc9e3 | 4,292 | cpp | C++ | tools/ecrecover.cpp | beerriot/concord | b03ccf01963bd072915020bb954a7afdb3074d79 | [
"Apache-2.0"
] | null | null | null | tools/ecrecover.cpp | beerriot/concord | b03ccf01963bd072915020bb954a7afdb3074d79 | [
"Apache-2.0"
] | null | null | null | tools/ecrecover.cpp | beerriot/concord | b03ccf01963bd072915020bb954a7afdb3074d79 | [
"Apache-2.0"
] | null | null | null | // Copyright (c) 2018-2019 VMware, Inc. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
#include "utils/concord_eth_hash.hpp"
#include "utils/concord_eth_sign.hpp"
#include "utils/concord_utils.hpp"
#include "utils/rlp.hpp"
using namespace std;
using concord::utils::dehex;
using concord::utils::EthSign;
using concord::utils::RLPBuilder;
using concord::utils::RLPParser;
std::vector<uint8_t> next_part(RLPParser &parser, const char *label) {
if (parser.at_end()) {
cerr << "Transaction too short: missing " << label << endl;
exit(-1);
}
return parser.next();
}
std::string addr_to_string(evm_address a) {
static const char hexes[] = "0123456789abcdef";
std::string out;
for (size_t i = 0; i < sizeof(evm_address); i++) {
out.append(hexes + (a.bytes[i] >> 4), 1)
.append(hexes + (a.bytes[i] & 0x0f), 1);
}
return out;
}
uint64_t uint_from_vector(std::vector<uint8_t> v, const char *label) {
if (v.size() > 8) {
cerr << label << " > uint64_t\n" << endl;
exit(-1);
}
uint64_t u = 0;
for (size_t i = 0; i < v.size(); i++) {
u = u << 8;
u += v[i];
}
return u;
}
int main(int argc, char **argv) {
if (argc != 2) {
cerr << "Usage: ecrecover <signed transaction hex>" << endl;
return -1;
}
string tx_s(argv[1]);
vector<uint8_t> tx = dehex(tx_s);
// Decode RLP
RLPParser tx_envelope_p = RLPParser(tx);
std::vector<uint8_t> tx_envelope = tx_envelope_p.next();
if (!tx_envelope_p.at_end()) {
cerr << "Warning: There are more bytes here than one transaction\n";
}
RLPParser tx_parts_p = RLPParser(tx_envelope);
std::vector<uint8_t> nonce_v = next_part(tx_parts_p, "nonce");
std::vector<uint8_t> gasPrice_v = next_part(tx_parts_p, "gas price");
std::vector<uint8_t> gas_v = next_part(tx_parts_p, "start gas");
std::vector<uint8_t> to = next_part(tx_parts_p, "to address");
std::vector<uint8_t> value_v = next_part(tx_parts_p, "value");
std::vector<uint8_t> data = next_part(tx_parts_p, "data");
std::vector<uint8_t> v = next_part(tx_parts_p, "signature V");
std::vector<uint8_t> r_v = next_part(tx_parts_p, "signature R");
std::vector<uint8_t> s_v = next_part(tx_parts_p, "signature S");
uint64_t nonce = uint_from_vector(nonce_v, "nonce");
uint64_t gasPrice = uint_from_vector(gasPrice_v, "gas price");
uint64_t gas = uint_from_vector(gas_v, "start gas");
uint64_t value = uint_from_vector(value_v, "value");
if (r_v.size() != sizeof(evm_uint256be)) {
cout << "Signature R is too short (" << r_v.size() << ")" << endl;
return -1;
}
evm_uint256be r;
std::copy(r_v.begin(), r_v.end(), r.bytes);
if (s_v.size() != sizeof(evm_uint256be)) {
cout << "Signature S is too short (" << s_v.size() << ")" << endl;
return -1;
}
evm_uint256be s;
std::copy(s_v.begin(), s_v.end(), s.bytes);
// Figure out non-signed V
if (v.size() < 1) {
cerr << "Signature V is empty\n" << endl;
return -1;
}
uint64_t chainID = uint_from_vector(v, "chain ID");
uint8_t actualV;
if (chainID < 37) {
cerr << "Non-EIP-155 signature V value" << endl;
return -1;
}
if (chainID % 2) {
actualV = 0;
chainID = (chainID - 35) / 2;
} else {
actualV = 1;
chainID = (chainID - 36) / 2;
}
// Re-encode RLP
RLPBuilder unsignedTX_b;
unsignedTX_b.start_list();
std::vector<uint8_t> empty;
unsignedTX_b.add(empty); // S
unsignedTX_b.add(empty); // R
unsignedTX_b.add(chainID); // V
unsignedTX_b.add(data);
if (value == 0) {
// signing hash expects 0x80 here, not 0x00
unsignedTX_b.add(empty);
} else {
unsignedTX_b.add(value);
}
unsignedTX_b.add(to);
if (gas == 0) {
unsignedTX_b.add(empty);
} else {
unsignedTX_b.add(gas);
}
if (gasPrice == 0) {
unsignedTX_b.add(empty);
} else {
unsignedTX_b.add(gasPrice);
}
if (nonce == 0) {
unsignedTX_b.add(empty);
} else {
unsignedTX_b.add(nonce);
}
std::vector<uint8_t> unsignedTX = unsignedTX_b.build();
// Recover Address
evm_uint256be unsignedTX_h =
concord::utils::eth_hash::keccak_hash(unsignedTX);
EthSign verifier;
evm_address from = verifier.ecrecover(unsignedTX_h, actualV, r, s);
cout << "Recovered: " << addr_to_string(from) << endl;
return 0;
}
| 26.012121 | 72 | 0.637931 | beerriot |
99a2e0a90e4dd2ff7f515862951c93847489be92 | 2,323 | hpp | C++ | include/expressions/diff_expr.hpp | miceks/gem | 08321fd35f8e3338f70bf9364448c8e77735ed2d | [
"MIT"
] | null | null | null | include/expressions/diff_expr.hpp | miceks/gem | 08321fd35f8e3338f70bf9364448c8e77735ed2d | [
"MIT"
] | null | null | null | include/expressions/diff_expr.hpp | miceks/gem | 08321fd35f8e3338f70bf9364448c8e77735ed2d | [
"MIT"
] | null | null | null | #pragma once
namespace gem::expr
{
// Expression produced by the - operator
template <typename LHS, typename RHS>
class diff_expr
{
LHS const& m_lhs_expr;
RHS const& m_rhs_expr;
public:
using result_type
= gem::meta::sum<typename LHS::result_type,
typename RHS::result_type>::type;
constexpr diff_expr(LHS const& lhs, RHS const& rhs)
: m_lhs_expr(lhs), m_rhs_expr(rhs)
{
}
template <std::size_t I>
auto constexpr subscript() const
{
// Find which indices in sub expressions map to index I
using index_mapping
= gem::meta::sum_sub_indices<I, result_type,
typename LHS::result_type,
typename RHS::result_type>;
// Only rhs contributes a term.
if constexpr(index_mapping::I1 == LHS::result_type::size)
{
return -m_rhs_expr. template subscript<index_mapping::I2>();
}
// Only lhs contributes a term.
else if constexpr(index_mapping::I2 == RHS::result_type::size)
{
return m_lhs_expr. template subscript<index_mapping::I1>();
}
// Both rhs and lhs contribute a term each.
else
{
return m_lhs_expr. template subscript<index_mapping::I1>()
- m_rhs_expr. template subscript<index_mapping::I2>();
}
}
};
} // namespace gem::expr
namespace gem
{
// Difference of two expressions
template <expression LHS, expression RHS>
auto constexpr operator - (LHS const& lhs, RHS const& rhs)
{
return expr::diff_expr<LHS, RHS>(lhs, rhs);
}
// Difference of scalar and expression
template <expression RHS>
auto constexpr operator - (mvec<blade<0,0,0>> const& lhs, RHS const& rhs)
{
return expr::diff_expr(lhs, rhs);
}
// Difference of expression and scalar
template <expression LHS>
auto constexpr operator - (LHS const& lhs, mvec<blade<0,0,0>> const& rhs)
{
return expr::diff_expr(lhs, rhs);
}
} // namespace gem | 29.782051 | 77 | 0.541972 | miceks |
99a4913fa33c824bec8d78bb7283b51536954b6c | 5,738 | hpp | C++ | L7/Common/Headers/GpProtoHeaders.hpp | ITBear/GpNetwork | 65b28ee8ed16e47efd8f8991cd8942c8a517c45e | [
"Apache-2.0"
] | null | null | null | L7/Common/Headers/GpProtoHeaders.hpp | ITBear/GpNetwork | 65b28ee8ed16e47efd8f8991cd8942c8a517c45e | [
"Apache-2.0"
] | null | null | null | L7/Common/Headers/GpProtoHeaders.hpp | ITBear/GpNetwork | 65b28ee8ed16e47efd8f8991cd8942c8a517c45e | [
"Apache-2.0"
] | null | null | null | #pragma once
#include "GpProtoHeaderValue.hpp"
#include "../Enums/GpEnums.hpp"
namespace GPlatform {
class GPNETWORK_API GpProtoHeaders: public GpTypeStructBase
{
public:
CLASS_DECLARE_DEFAULTS(GpProtoHeaders)
TYPE_STRUCT_DECLARE("88a01e4e-9105-4cd5-9990-4578ebb14b51"_sv)
public:
explicit GpProtoHeaders (void) noexcept;
GpProtoHeaders (const GpProtoHeaders& aHeaders);
GpProtoHeaders (GpProtoHeaders&& aHeaders) noexcept;
virtual ~GpProtoHeaders (void) noexcept override;
void Set (const GpProtoHeaders& aHeaders);
void Set (GpProtoHeaders&& aHeaders) noexcept;
void Clear (void);
GpProtoHeaderValue::C::MapStr::SP& Headers (void) noexcept {return headers;}
const GpProtoHeaderValue::C::MapStr::SP&
Headers (void) const noexcept {return headers;}
GpProtoHeaders& Replace (std::string aName,
std::string_view aValue);
GpProtoHeaders& Replace (std::string aName,
std::string&& aValue);
GpProtoHeaders& Replace (std::string aName,
const u_int_64 aValue);
GpProtoHeaders& Add (std::string aName,
std::string_view aValue);
GpProtoHeaders& Add (std::string aName,
std::string&& aValue);
GpProtoHeaders& Add (std::string aName,
const u_int_64 aValue);
protected:
template<typename T, typename V>
GpProtoHeaders& Replace (const typename T::EnumT aType,
std::string_view aValue);
template<typename T, typename V>
GpProtoHeaders& Replace (const typename T::EnumT aType,
std::string&& aValue);
template<typename T, typename V>
GpProtoHeaders& Replace (const typename T::EnumT aType,
const u_int_64 aValue);
template<typename T, typename V>
GpProtoHeaders& Add (const typename T::EnumT aType,
std::string_view aValue);
template<typename T, typename V>
GpProtoHeaders& Add (const typename T::EnumT aType,
std::string&& aValue);
template<typename T, typename V>
GpProtoHeaders& Add (const typename T::EnumT aType,
const u_int_64 aValue);
private:
GpProtoHeaderValue::C::MapStr::SP headers;
public:
static const GpArray<std::string, GpContentType::SCount().As<size_t>()> sContentType;
static const GpArray<std::string, GpCharset::SCount().As<size_t>()> sCharset;
};
template<typename T, typename V>
GpProtoHeaders& GpProtoHeaders::Replace
(
const typename T::EnumT aType,
std::string_view aValue
)
{
return Replace<T, V>(aType, std::string(aValue));
}
template<typename T, typename V>
GpProtoHeaders& GpProtoHeaders::Replace
(
const typename T::EnumT aType,
std::string&& aValue
)
{
const std::string& headerName = V::sHeadersNames.at(size_t(aType));
headers[headerName] = MakeSP<GpProtoHeaderValue>(std::move(aValue));
return *this;
}
template<typename T, typename V>
GpProtoHeaders& GpProtoHeaders::Replace
(
const typename T::EnumT aType,
const u_int_64 aValue)
{
return Replace<T, V>(aType, StrOps::SFromUI64(aValue));
}
template<typename T, typename V>
GpProtoHeaders& GpProtoHeaders::Add
(
const typename T::EnumT aType,
std::string_view aValue
)
{
return Add<T, V>(aType, std::string(aValue));
}
template<typename T, typename V>
GpProtoHeaders& GpProtoHeaders::Add
(
const typename T::EnumT aType,
std::string&& aValue
)
{
const std::string& headerName = V::sHeadersNames.at(size_t(aType));
auto iter = headers.find(headerName);
if (iter == headers.end())
{
return Replace<T, V>(aType, std::move(aValue));
} else
{
iter->second->elements.emplace_back(std::move(aValue));
}
return *this;
}
template<typename T, typename V>
GpProtoHeaders& GpProtoHeaders::Add
(
const typename T::EnumT aType,
const u_int_64 aValue
)
{
return Add<T, V>(aType, StrOps::SFromUI64(aValue));
}
}//namespace GPlatform
| 40.125874 | 104 | 0.467585 | ITBear |
99a5be3d0bb725a723cd52bc36fbae911f0f21f9 | 3,991 | cpp | C++ | Advanced C++ Course/Benjamin Rutan HW 1 Submission/1.5/1.5/Line.cpp | BRutan/Cpp | 8acbc6c341f49d6d83168ccd5ba49bd6824214f9 | [
"MIT"
] | null | null | null | Advanced C++ Course/Benjamin Rutan HW 1 Submission/1.5/1.5/Line.cpp | BRutan/Cpp | 8acbc6c341f49d6d83168ccd5ba49bd6824214f9 | [
"MIT"
] | null | null | null | Advanced C++ Course/Benjamin Rutan HW 1 Submission/1.5/1.5/Line.cpp | BRutan/Cpp | 8acbc6c341f49d6d83168ccd5ba49bd6824214f9 | [
"MIT"
] | null | null | null | /* Line.cpp (exercise 1.5.5)
Description:
* Declare Line class that represents a line in 2-D Euclidean space.
State Variables/Objects:
*Point p1, p2: Points in 2-D Euclidean space.
Member Functions:
*Line(): Default constructor (allocates memory for both state Point objects, sets their states to (0,0)).
*Line(const Point&, const Point&): Overloaded constructor (allocates memory for both state Point objects, sets their states to (0,0)).
*Line(const Line&): Copy constructor (allocates memory for both state Point objects, sets their states to passed Line's point's states).
*~Line(): Destructor (frees memory previously allocated by constructor).
// Accessors:
*Point P1() const: Return copy of P1 Point Object.
*Point P2() const: Return copy of P2 Point Object.
// Mutators:
*void P1(const Point&): Change P1's state to state of passed Point object.
*void P2(const Point&): Change P2's state to state of passed Point object.
// Misc. Methods:
*double Length() const: Return length of line.
*void Draw() const: Draw calling Line object.
*string ToString() const: Return string description of Length object's state ("Line((P1_X(), P1_Y()), (P2_X(), P2_Y()))").
*/
#include <iostream>
#include <string>
#include <sstream>
#include "IODevice.hpp"
#include "Line.hpp"
#include "Shape.hpp"
////////////////////////////////
// Constructors/Destructor:
////////////////////////////////
Line::Line() noexcept : p1(), p2(), Shape() /* Default constructor. */
{
}
Line::Line(const Point &p1_in, const Point &p2_in) noexcept : p1(p1_in), p2(p2_in), Shape() /* Overloaded constructor (parameters reference existing point objects). */
{
}
Line::Line(const Line &line_in) noexcept : p1(line_in.p1), p2(line_in.p2), Shape(line_in) /* Copy constructor. */
{
}
Line::~Line() noexcept /* Destructor. */
{
}
////////////////////////////////
// Accessors:
////////////////////////////////
Point Line::P1() const noexcept /* Return P1. */
{
return p1;
}
Point Line::P2() const noexcept /* Return P2. */
{
return p2;
}
////////////////////////////////
// Mutators:
////////////////////////////////
void Line::P1(const Point &point_in) noexcept /* Set state of P1 by using assignment operator with point_in. */
{
p1 = point_in;
}
void Line::P2(const Point &point_in) noexcept /* Set state of P2 by using assignment operator with point_in. */
{
p2 = point_in;
}
////////////////////////////////
// Misc. methods:
////////////////////////////////
double Line::Length() const noexcept /* Return euclidean distance between P1 and P2. */
{
return (p1.Distance(p2));
}
void Line::Draw() const noexcept /* Draw current Line object. */
{
std::cout << "Line has been drawn. " << std::endl;
}
void Line::display(const IODevice &in) const noexcept /* Display Circle object on passed input-output device. */
{
in << *this;
}
std::string Line::ToString() const noexcept /* Return description of Line object's state ("Line((P1_X(), P1_Y()), (P2_X(), P2_Y()))") */
{
std::stringstream ss;
// Append the base Shape object description to Line object description:
std::string s = Shape::ToString();
ss << "Line({" << p1.X() << ", " << p1.Y() << "},{" << p2.X() << ", " << p2.Y() << "}) " << s;
return ss.str();
}
//////////////////////////////////////
// Overloaded Operators:
//////////////////////////////////////
// Member operators:
Line& Line::operator=(const Line& line_in) noexcept /* Assignment operator. */
{
// Preclude self-assignment (check if passed line has the same memory address):
if (this != &line_in)
{
p1 = line_in.p1;
p2 = line_in.p2;
// Copy passed Line object's base state:
Shape::operator=(line_in);
}
return *this;
}
// Global operators:
std::ostream& operator<<(std::ostream& os, const Line& line_in) noexcept /* Overloaded ostream operator. */
{
os << "Line((" << line_in.p1.X() << ", " << line_in.p1.Y() << "),(" << line_in.p2.X() << ", " << line_in.p2.Y() << "))";
return os;
}
| 34.111111 | 168 | 0.604861 | BRutan |
99a9fe05108b7f6744f3b903c9983d67caf2f920 | 157 | hpp | C++ | BBB_GPIO/utils.hpp | felipegarcia99/beagleboneblack-gpio-cpp-api | e6169957fe8da0dfb87381ee4c1a12941c1f02be | [
"MIT"
] | 1 | 2021-09-09T10:10:43.000Z | 2021-09-09T10:10:43.000Z | BBB_GPIO/utils.hpp | felipegarcia99/beagleboneblack-gpio-cpp-api | e6169957fe8da0dfb87381ee4c1a12941c1f02be | [
"MIT"
] | null | null | null | BBB_GPIO/utils.hpp | felipegarcia99/beagleboneblack-gpio-cpp-api | e6169957fe8da0dfb87381ee4c1a12941c1f02be | [
"MIT"
] | null | null | null | #include <signal.h> // our new library
extern volatile sig_atomic_t flag;
void delay(float time);
void defining_sigaction();
void my_handler(int signal); | 22.428571 | 40 | 0.764331 | felipegarcia99 |
99aadc94c20aa96fec0056556828f140150c470b | 294 | hpp | C++ | jet-sdk-csgo/src/i_client_leaf_system.hpp | bruhmoment21/csgo-imgui-sdk | f299375d4786b029b800800cde9a3404aa66e0e5 | [
"MIT"
] | 57 | 2020-07-04T16:32:12.000Z | 2022-03-03T20:18:33.000Z | jet-sdk-csgo/src/i_client_leaf_system.hpp | bruhmoment21/csgo-imgui-sdk | f299375d4786b029b800800cde9a3404aa66e0e5 | [
"MIT"
] | 9 | 2021-03-15T08:48:17.000Z | 2021-12-18T15:34:12.000Z | jet-sdk-csgo/src/i_client_leaf_system.hpp | bruhmoment21/csgo-imgui-sdk | f299375d4786b029b800800cde9a3404aa66e0e5 | [
"MIT"
] | 21 | 2020-07-21T15:33:05.000Z | 2022-03-04T23:19:11.000Z | #pragma once
#include "utilities.hpp"
class i_client_leaf_system
{
public:
void create_renderable_handle(void* obj)
{
return utilities::call_virtual< void, 0, std::uintptr_t, bool, int, int, std::uint32_t >(this, reinterpret_cast<std::uintptr_t>(obj) + 4, false, 0, -1, 0xFFFFFFFF);
}
}; | 24.5 | 166 | 0.72449 | bruhmoment21 |
99ab0539d47cd5450c5ce19ab5dc1409fc7e40fb | 1,597 | cpp | C++ | source/init_coreload_postparse.cpp | cloudy-astrophysics/cloudy_lfs | aed1d6d78042b93f17ea497a37b35a524f3d3e2e | [
"Zlib"
] | null | null | null | source/init_coreload_postparse.cpp | cloudy-astrophysics/cloudy_lfs | aed1d6d78042b93f17ea497a37b35a524f3d3e2e | [
"Zlib"
] | null | null | null | source/init_coreload_postparse.cpp | cloudy-astrophysics/cloudy_lfs | aed1d6d78042b93f17ea497a37b35a524f3d3e2e | [
"Zlib"
] | null | null | null | /* This file is part of Cloudy and is copyright (C)1978-2019 by Gary J. Ferland and
* others. For conditions of distribution and use see copyright notice in license.txt */
/*InitCoreloadPostparse initialization at start, called from cloudy
* after parser one time per core load */
#include "cddefines.h"
#include "init.h"
#include "dense.h"
#include "iso.h"
#include "species.h"
/*InitCoreloadPostparse initialization at start, called from cloudy
* after parser, one time per core load */
void InitCoreloadPostparse( void )
{
static int nCalled = 0;
DEBUG_ENTRY( "InitCoreloadPostparse()" );
/* only do this once per coreload */
if( nCalled > 0 )
{
return;
}
/* this is first call, increment the nCalled counter so we never do this again */
++nCalled;
for( long ipISO=ipH_LIKE; ipISO<NISO; ++ipISO )
{
for( long nelem=ipISO; nelem<LIMELM; ++nelem)
{
/* only grab core for elements that are turned on */
if( nelem < 2 || dense.lgElmtOn[nelem] )
{
iso_update_num_levels( ipISO, nelem );
ASSERT( iso_sp[ipISO][nelem].numLevels_max > 0 );
iso_ctrl.nLyman_alloc[ipISO] = iso_ctrl.nLyman[ipISO];
iso_ctrl.nLyman_max[ipISO] = iso_ctrl.nLyman[ipISO];
// resolved and collapsed levels
long numLevels = iso_sp[ipISO][nelem].numLevels_max;
// "extra" Lyman lines
numLevels += iso_ctrl.nLyman_alloc[ipISO] - 2;
// satellite lines (one for doubly-excited continuum)
if( iso_ctrl.lgDielRecom[ipISO] )
numLevels += 1;
iso_sp[ipISO][nelem].st.init( makeChemical( nelem, nelem-ipISO ).c_str(), numLevels );
}
}
}
return;
}
| 29.574074 | 90 | 0.694427 | cloudy-astrophysics |
99afaae66e1b76aaee0613a2ad2acbc24b794242 | 5,005 | hxx | C++ | opencascade/IFSelect_SelectSignature.hxx | mgreminger/OCP | 92eacb99497cd52b419c8a4a8ab0abab2330ed42 | [
"Apache-2.0"
] | null | null | null | opencascade/IFSelect_SelectSignature.hxx | mgreminger/OCP | 92eacb99497cd52b419c8a4a8ab0abab2330ed42 | [
"Apache-2.0"
] | null | null | null | opencascade/IFSelect_SelectSignature.hxx | mgreminger/OCP | 92eacb99497cd52b419c8a4a8ab0abab2330ed42 | [
"Apache-2.0"
] | null | null | null | // Created on: 1994-04-21
// Created by: Christian CAILLET
// Copyright (c) 1994-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _IFSelect_SelectSignature_HeaderFile
#define _IFSelect_SelectSignature_HeaderFile
#include <Standard.hxx>
#include <Standard_Type.hxx>
#include <TCollection_AsciiString.hxx>
#include <Standard_Integer.hxx>
#include <TColStd_SequenceOfAsciiString.hxx>
#include <TColStd_SequenceOfInteger.hxx>
#include <IFSelect_SelectExtract.hxx>
#include <Standard_CString.hxx>
#include <Standard_Boolean.hxx>
class IFSelect_Signature;
class IFSelect_SignCounter;
class Standard_Transient;
class Interface_Graph;
class Interface_InterfaceModel;
class IFSelect_SelectSignature;
DEFINE_STANDARD_HANDLE(IFSelect_SelectSignature, IFSelect_SelectExtract)
//! A SelectSignature sorts the Entities on a Signature Matching.
//! The signature to match is given at creation time. Also, the
//! required match is given at creation time : exact (IsEqual) or
//! contains (the Type's Name must contain the criterium Text)
//!
//! Remark that no more interpretation is done, it is an
//! alpha-numeric signature : for instance, DynamicType is matched
//! as such, super-types are not considered
//!
//! Also, numeric (integer) comparisons are supported : an item
//! can be <val ou <=val or >val or >=val , val being an Integer
//!
//! A SelectSignature may also be created from a SignCounter,
//! which then just gives its LastValue as SignatureValue
class IFSelect_SelectSignature : public IFSelect_SelectExtract
{
public:
//! Creates a SelectSignature with its Signature and its Text to
//! Match.
//! <exact> if True requires exact match,
//! if False requires <signtext> to be contained in the Signature
//! of the entity (default is "exact")
Standard_EXPORT IFSelect_SelectSignature(const Handle(IFSelect_Signature)& matcher, const Standard_CString signtext, const Standard_Boolean exact = Standard_True);
//! As above with an AsciiString
Standard_EXPORT IFSelect_SelectSignature(const Handle(IFSelect_Signature)& matcher, const TCollection_AsciiString& signtext, const Standard_Boolean exact = Standard_True);
//! Creates a SelectSignature with a Counter, more precisely a
//! SelectSignature. Which is used here to just give a Signature
//! Value (by SignOnly Mode)
//! Matching is the default provided by the class Signature
Standard_EXPORT IFSelect_SelectSignature(const Handle(IFSelect_SignCounter)& matcher, const Standard_CString signtext, const Standard_Boolean exact = Standard_True);
//! Returns the used Signature, then it is possible to access it,
//! modify it as required. Can be null, hence see Counter
Standard_EXPORT Handle(IFSelect_Signature) Signature() const;
//! Returns the used SignCounter. Can be used as alternative for
//! Signature
Standard_EXPORT Handle(IFSelect_SignCounter) Counter() const;
//! Returns True for an Entity (model->Value(num)) of which the
//! signature matches the text given as creation time
//! May also work with a Counter from the Graph
Standard_EXPORT virtual Standard_Boolean SortInGraph (const Standard_Integer rank, const Handle(Standard_Transient)& ent, const Interface_Graph& G) const Standard_OVERRIDE;
//! Not called, defined only to remove a deferred method here
Standard_EXPORT Standard_Boolean Sort (const Standard_Integer rank, const Handle(Standard_Transient)& ent, const Handle(Interface_InterfaceModel)& model) const Standard_OVERRIDE;
//! Returns Text used to Sort Entity on its Signature or SignCounter
Standard_EXPORT const TCollection_AsciiString& SignatureText() const;
//! Returns True if match must be exact
Standard_EXPORT Standard_Boolean IsExact() const;
//! Returns a text defining the criterium.
//! (it refers to the text and exact flag to be matched, and is
//! qualified by the Name provided by the Signature)
Standard_EXPORT TCollection_AsciiString ExtractLabel() const Standard_OVERRIDE;
DEFINE_STANDARD_RTTIEXT(IFSelect_SelectSignature,IFSelect_SelectExtract)
protected:
private:
Handle(IFSelect_Signature) thematcher;
Handle(IFSelect_SignCounter) thecounter;
TCollection_AsciiString thesigntext;
Standard_Integer theexact;
TColStd_SequenceOfAsciiString thesignlist;
TColStd_SequenceOfInteger thesignmode;
};
#endif // _IFSelect_SelectSignature_HeaderFile
| 37.631579 | 180 | 0.783017 | mgreminger |
99b0a02606783ea16114881450000304af19e5e8 | 30,975 | hpp | C++ | public/anton/array.hpp | kociap/atl | a7dc9b35c14453040db82dbbeca3c305bb25c66e | [
"MIT"
] | null | null | null | public/anton/array.hpp | kociap/atl | a7dc9b35c14453040db82dbbeca3c305bb25c66e | [
"MIT"
] | null | null | null | public/anton/array.hpp | kociap/atl | a7dc9b35c14453040db82dbbeca3c305bb25c66e | [
"MIT"
] | null | null | null | #pragma once
#include <anton/allocator.hpp>
#include <anton/assert.hpp>
#include <anton/iterators.hpp>
#include <anton/math/math.hpp>
#include <anton/memory.hpp>
#include <anton/swap.hpp>
#include <anton/tags.hpp>
#include <anton/type_traits.hpp>
#include <anton/utility.hpp>
namespace anton {
#define ANTON_ARRAY_MIN_ALLOCATION_SIZE ((i64)64)
template<typename T, typename Allocator = Allocator>
struct Array {
public:
using value_type = T;
using allocator_type = Allocator;
using size_type = i64;
using difference_type = i64;
using iterator = T*;
using const_iterator = T const*;
Array();
explicit Array(allocator_type const& allocator);
// Construct an array with n default constructed elements
explicit Array(size_type n);
// Construct an array with n default constructed elements
explicit Array(size_type n, allocator_type const& allocator);
// Construct an array with n copies of value
explicit Array(size_type n, value_type const& value);
// Construct an array with n copies of value
explicit Array(size_type n, value_type const& value, allocator_type const& allocator);
// Construct an array with capacity to fit at least n elements
explicit Array(Reserve_Tag, size_type n);
// Construct an array with capacity to fit at least n elements
explicit Array(Reserve_Tag, size_type n, allocator_type const& allocator);
// Copies the allocator
Array(Array const& other);
Array(Array const& other, allocator_type const& allocator);
// Moves the allocator
Array(Array&& other);
Array(Array&& other, allocator_type const& allocator);
template<typename Input_Iterator>
Array(Range_Construct_Tag, Input_Iterator first, Input_Iterator last);
template<typename... Args>
Array(Variadic_Construct_Tag, Args&&...);
~Array();
Array& operator=(Array const& other);
Array& operator=(Array&& other);
[[nodiscard]] T& operator[](size_type);
[[nodiscard]] T const& operator[](size_type) const;
// back
// Accesses the last element of the array. The behaviour is undefined when the array is empty.
//
[[nodiscard]] T& back();
[[nodiscard]] T const& back() const;
[[nodiscard]] T* data();
[[nodiscard]] T const* data() const;
[[nodiscard]] iterator begin();
[[nodiscard]] iterator end();
[[nodiscard]] const_iterator begin() const;
[[nodiscard]] const_iterator end() const;
[[nodiscard]] const_iterator cbegin() const;
[[nodiscard]] const_iterator cend() const;
// size
// The number of elements contained in the array.
//
[[nodiscard]] size_type size() const;
// size_bytes
// The size of all the elements contained in the array in bytes.
// Equivalent to 'sizeof(T) * size()'.
//
[[nodiscard]] size_type size_bytes() const;
[[nodiscard]] size_type capacity() const;
[[nodiscard]] allocator_type& get_allocator();
[[nodiscard]] allocator_type const& get_allocator() const;
// resize
// Resizes the array allocating additional memory if n is greater than capacity.
// If n is greater than size, the new elements are default constructed.
// If n is less than size, the excess elements are destroyed.
//
void resize(size_type n);
// resize
// Resizes the array allocating additional memory if n is greater than capacity.
// If n is greater than size, the new elements are copy constructed from v.
// If n is less than size, the excess elements are destroyed.
//
void resize(size_type n, value_type const& v);
// ensure_capacity
// Allocates enough memory to fit requested_capacity elements of type T.
// Does nothing if requested_capacity is less than capacity().
//
void ensure_capacity(size_type requested_capacity);
// set_capacity
// Sets the capacity to exactly match n.
// If n is not equal capacity, contents are reallocated.
//
void set_capacity(size_type n);
// force_size
// Changes the size of the array to n. Useful in situations when the user
// writes to the array via external means.
//
void force_size(size_type n);
template<typename Input_Iterator>
void assign(Input_Iterator first, Input_Iterator last);
// insert
// Constructs an object directly into array at position avoiding copies or moves.
// position must be a valid iterator.
//
// Returns: iterator to the inserted element.
//
template<typename... Args>
iterator insert(Variadic_Construct_Tag, const_iterator position, Args&&... args);
// insert
// Constructs an object directly into array at position avoiding copies or moves.
// position must be an index greater than or equal 0 and less than or equal size.
//
// Returns: iterator to the inserted element.
//
template<typename... Args>
iterator insert(Variadic_Construct_Tag, size_type position, Args&&... args);
// insert
// Insert a range of elements into array at position.
// position must be a valid iterator.
//
// Returns: iterator to the first of the inserted elements.
//
template<typename Input_Iterator>
iterator insert(const_iterator position, Input_Iterator first, Input_Iterator last);
// insert
// Insert a range of elements into array at position.
// position must be an index greater than or equal 0 and less than or equal size.
//
// Returns: iterator to the first of the inserted elements.
//
template<typename Input_Iterator>
iterator insert(size_type position, Input_Iterator first, Input_Iterator last);
// insert_unsorted
// Inserts an element into array by moving the object at position to the end of the array
// and then copying value into position.
// position must be a valid iterator.
//
// Returns:
// Iterator to the inserted element.
//
iterator insert_unsorted(const_iterator position, value_type const& value);
iterator insert_unsorted(const_iterator position, value_type&& value);
// insert_unsorted
// Inserts an element into array by moving the object at position to the end of the array
// and then copying value into position.
// position must be an index greater than or equal 0 and less than or equal size.
//
// Returns:
// Iterator to the inserted element.
//
iterator insert_unsorted(size_type position, value_type const& value);
iterator insert_unsorted(size_type position, value_type&& value);
T& push_back(value_type const&);
T& push_back(value_type&&);
template<typename... Args>
T& emplace_back(Args&&... args);
iterator erase(const_iterator first, const_iterator last);
void erase_unsorted(size_type index);
void erase_unsorted_unchecked(size_type index);
iterator erase_unsorted(const_iterator first);
// iterator erase_unsorted(const_iterator first, const_iterator last);
void pop_back();
void clear();
// swap
// Exchanges the contents of the two arrays without copying,
// moving or swapping the individual elements.
// Exchanges the allocators.
//
// Parameters:
// lhs, rhs - the containers to exchange the contents of.
//
// Complexity:
// Constant.
//
friend void swap(Array& lhs, Array& rhs) {
// We do not follow the C++ Standard in its complex ways to swap containers
// and always swap both the allocator and the memory since it is a common expectation
// of the users, is much faster than copying all the elements and does not break
// the container or put it in an invalid state.
using anton::swap;
swap(lhs._allocator, rhs._allocator);
swap(lhs._capacity, rhs._capacity);
swap(lhs._size, rhs._size);
swap(lhs._data, rhs._data);
}
private:
Allocator _allocator;
size_type _capacity = 0;
size_type _size = 0;
T* _data = nullptr;
T* allocate(size_type);
void deallocate(void*, size_type);
};
} // namespace anton
namespace anton {
template<typename T, typename Allocator>
Array<T, Allocator>::Array(): _allocator() {}
template<typename T, typename Allocator>
Array<T, Allocator>::Array(allocator_type const& allocator): _allocator(allocator) {}
template<typename T, typename Allocator>
Array<T, Allocator>::Array(size_type const n): Array(n, allocator_type()) {}
template<typename T, typename Allocator>
Array<T, Allocator>::Array(size_type const n, allocator_type const& allocator): _allocator(allocator) {
_capacity = math::max(ANTON_ARRAY_MIN_ALLOCATION_SIZE, n);
_data = allocate(_capacity);
anton::uninitialized_default_construct_n(_data, n);
_size = n;
}
template<typename T, typename Allocator>
Array<T, Allocator>::Array(size_type n, value_type const& value): Array(n, value, allocator_type()) {}
template<typename T, typename Allocator>
Array<T, Allocator>::Array(size_type n, value_type const& value, allocator_type const& allocator) {
_capacity = math::max(ANTON_ARRAY_MIN_ALLOCATION_SIZE, n);
_data = allocate(_capacity);
anton::uninitialized_fill_n(_data, n, value);
_size = n;
}
template<typename T, typename Allocator>
Array<T, Allocator>::Array(Reserve_Tag, size_type const n): Array(reserve, n, allocator_type()) {}
template<typename T, typename Allocator>
Array<T, Allocator>::Array(Reserve_Tag, size_type const n, allocator_type const& allocator): _allocator(allocator) {
_capacity = math::max(ANTON_ARRAY_MIN_ALLOCATION_SIZE, n);
_data = allocate(_capacity);
}
template<typename T, typename Allocator>
Array<T, Allocator>::Array(Array const& other): _allocator(other._allocator), _capacity(other._capacity) {
if(_capacity > 0) {
_data = allocate(_capacity);
anton::uninitialized_copy_n(other._data, other._size, _data);
_size = other._size;
}
}
template<typename T, typename Allocator>
Array<T, Allocator>::Array(Array&& other): _allocator(ANTON_MOV(other._allocator)), _capacity(other._capacity), _size(other._size), _data(other._data) {
other._data = nullptr;
other._capacity = 0;
other._size = 0;
}
template<typename T, typename Allocator>
template<typename Input_Iterator>
Array<T, Allocator>::Array(Range_Construct_Tag, Input_Iterator first, Input_Iterator last) {
// TODO: Use distance?
size_type const count = last - first;
_capacity = math::max(ANTON_ARRAY_MIN_ALLOCATION_SIZE, count);
_data = allocate(_capacity);
anton::uninitialized_copy(first, last, _data);
_size = count;
}
template<typename T, typename Allocator>
template<typename... Args>
Array<T, Allocator>::Array(Variadic_Construct_Tag, Args&&... args) {
_capacity = math::max(ANTON_ARRAY_MIN_ALLOCATION_SIZE, static_cast<size_type>(sizeof...(Args)));
_data = allocate(_capacity);
anton::uninitialized_variadic_construct(_data, ANTON_FWD(args)...);
_size = static_cast<size_type>(sizeof...(Args));
}
template<typename T, typename Allocator>
Array<T, Allocator>::~Array() {
anton::destruct_n(_data, _size);
deallocate(_data, _capacity);
}
template<typename T, typename Allocator>
Array<T, Allocator>& Array<T, Allocator>::operator=(Array const& other) {
anton::destruct_n(_data, _size);
deallocate(_data, _capacity);
_capacity = other._capacity;
_size = other._size;
_allocator = other._allocator;
if(_capacity > 0) {
_data = allocate(_capacity);
anton::uninitialized_copy_n(other._data, other._size, _data);
}
return *this;
}
template<typename T, typename Allocator>
Array<T, Allocator>& Array<T, Allocator>::operator=(Array&& other) {
swap(*this, other);
return *this;
}
template<typename T, typename Allocator>
auto Array<T, Allocator>::operator[](size_type index) -> T& {
if constexpr(ANTON_ITERATOR_DEBUG) {
ANTON_FAIL(index < _size && index >= 0, u8"index out of bounds");
}
return _data[index];
}
template<typename T, typename Allocator>
auto Array<T, Allocator>::operator[](size_type index) const -> T const& {
if constexpr(ANTON_ITERATOR_DEBUG) {
ANTON_FAIL(index < _size && index >= 0, u8"index out of bounds");
}
return _data[index];
}
template<typename T, typename Allocator>
auto Array<T, Allocator>::back() -> T& {
if constexpr(ANTON_ITERATOR_DEBUG) {
ANTON_FAIL(_size > 0, u8"attempting to call back() on empty Array");
}
return _data[_size - 1];
}
template<typename T, typename Allocator>
auto Array<T, Allocator>::back() const -> T const& {
if constexpr(ANTON_ITERATOR_DEBUG) {
ANTON_FAIL(_size > 0, u8"attempting to call back() on empty Array");
}
return _data[_size - 1];
}
template<typename T, typename Allocator>
auto Array<T, Allocator>::data() -> T* {
return _data;
}
template<typename T, typename Allocator>
auto Array<T, Allocator>::data() const -> T const* {
return _data;
}
template<typename T, typename Allocator>
auto Array<T, Allocator>::begin() -> iterator {
return _data;
}
template<typename T, typename Allocator>
auto Array<T, Allocator>::end() -> iterator {
return _data + _size;
}
template<typename T, typename Allocator>
auto Array<T, Allocator>::begin() const -> const_iterator {
return _data;
}
template<typename T, typename Allocator>
auto Array<T, Allocator>::end() const -> const_iterator {
return _data + _size;
}
template<typename T, typename Allocator>
auto Array<T, Allocator>::cbegin() const -> const_iterator {
return _data;
}
template<typename T, typename Allocator>
auto Array<T, Allocator>::cend() const -> const_iterator {
return _data + _size;
}
template<typename T, typename Allocator>
auto Array<T, Allocator>::size() const -> size_type {
return _size;
}
template<typename T, typename Allocator>
auto Array<T, Allocator>::size_bytes() const -> size_type {
return _size * sizeof(T);
}
template<typename T, typename Allocator>
auto Array<T, Allocator>::capacity() const -> size_type {
return _capacity;
}
template<typename T, typename Allocator>
auto Array<T, Allocator>::get_allocator() -> allocator_type& {
return _allocator;
}
template<typename T, typename Allocator>
auto Array<T, Allocator>::get_allocator() const -> allocator_type const& {
return _allocator;
}
template<typename T, typename Allocator>
void Array<T, Allocator>::resize(size_type n, value_type const& value) {
ensure_capacity(n);
if(n > _size) {
anton::uninitialized_fill(_data + _size, _data + n, value);
} else {
anton::destruct(_data + n, _data + _size);
}
_size = n;
}
template<typename T, typename Allocator>
void Array<T, Allocator>::resize(size_type n) {
ensure_capacity(n);
if(n > _size) {
anton::uninitialized_default_construct(_data + _size, _data + n);
} else {
anton::destruct(_data + n, _data + _size);
}
_size = n;
}
template<typename T, typename Allocator>
void Array<T, Allocator>::ensure_capacity(size_type requested_capacity) {
if(requested_capacity > _capacity) {
size_type new_capacity = (_capacity > 0 ? _capacity : ANTON_ARRAY_MIN_ALLOCATION_SIZE);
while(new_capacity < requested_capacity) {
new_capacity *= 2;
}
T* new_data = allocate(new_capacity);
if constexpr(is_move_constructible<T>) {
uninitialized_move(_data, _data + _size, new_data);
} else {
uninitialized_copy(_data, _data + _size, new_data);
}
anton::destruct_n(_data, _size);
deallocate(_data, _capacity);
_data = new_data;
_capacity = new_capacity;
}
}
template<typename T, typename Allocator>
void Array<T, Allocator>::set_capacity(size_type new_capacity) {
ANTON_ASSERT(new_capacity >= 0, "capacity must be greater than or equal 0");
if(new_capacity != _capacity) {
i64 const new_size = math::min(new_capacity, _size);
T* new_data = nullptr;
if(new_capacity > 0) {
new_data = allocate(new_capacity);
}
if constexpr(is_move_constructible<T>) {
anton::uninitialized_move_n(_data, new_size, new_data);
} else {
anton::uninitialized_copy_n(_data, new_size, new_data);
}
anton::destruct_n(_data, _size);
deallocate(_data, _capacity);
_data = new_data;
_capacity = new_capacity;
_size = new_size;
}
}
template<typename T, typename Allocator>
void Array<T, Allocator>::force_size(size_type n) {
ANTON_ASSERT(n <= _capacity, u8"requested size is greater than capacity");
_size = n;
}
template<typename T, typename Allocator>
template<typename Input_Iterator>
void Array<T, Allocator>::assign(Input_Iterator first, Input_Iterator last) {
anton::destruct_n(_data, _size);
ensure_capacity(last - first);
anton::uninitialized_copy(first, last, _data);
_size = last - first;
}
template<typename T, typename Allocator>
template<typename... Args>
auto Array<T, Allocator>::insert(Variadic_Construct_Tag, const_iterator position, Args&&... args) -> iterator {
size_type const offset = static_cast<size_type>(position - begin());
return insert(variadic_construct, offset, ANTON_FWD(args)...);
}
template<typename T, typename Allocator>
template<typename... Args>
auto Array<T, Allocator>::insert(Variadic_Construct_Tag, size_type const position, Args&&... args) -> iterator {
if constexpr(ANTON_ITERATOR_DEBUG) {
ANTON_FAIL(position >= 0 && position <= _size, u8"index out of bounds");
}
if(_size == _capacity || position != _size) {
if(_size != _capacity) {
anton::uninitialized_move_n(_data + _size - 1, 1, _data + _size);
anton::move_backward(_data + position, _data + _size - 1, _data + _size);
anton::construct(_data + position, ANTON_FWD(args)...);
_size += 1;
} else {
i64 const new_capacity = (_capacity > 0 ? _capacity * 2 : ANTON_ARRAY_MIN_ALLOCATION_SIZE);
T* const new_data = allocate(new_capacity);
i64 moved = 0;
anton::uninitialized_move(_data, _data + position, new_data);
moved = position;
anton::construct(new_data + position, ANTON_FWD(args)...);
moved += 1;
anton::uninitialized_move(_data + position, _data + _size, new_data + moved);
anton::destruct_n(_data, _size);
deallocate(_data, _capacity);
_capacity = new_capacity;
_data = new_data;
_size += 1;
}
} else {
// Quick path when position points to end and we have room for one more element.
anton::construct(_data + _size, ANTON_FWD(args)...);
_size += 1;
}
return _data + position;
}
template<typename T, typename Allocator>
template<typename Input_Iterator>
auto Array<T, Allocator>::insert(const_iterator position, Input_Iterator first, Input_Iterator last) -> iterator {
size_type const offset = static_cast<size_type>(position - begin());
return insert(offset, first, last);
}
template<typename T, typename Allocator>
template<typename Input_Iterator>
auto Array<T, Allocator>::insert(size_type position, Input_Iterator first, Input_Iterator last) -> iterator {
if constexpr(ANTON_ITERATOR_DEBUG) {
ANTON_FAIL(position >= 0 && position <= _size, u8"index out of bounds");
}
// TODO: Distance and actual support for input iterators.
if(first != last) {
i64 const new_elems = last - first;
ANTON_ASSERT(new_elems > 0, "the difference of first and last must be greater than 0");
if(_size + new_elems <= _capacity && position == _size) {
// Quick path when position points to end and we have room for new_elems elements.
anton::uninitialized_copy(first, last, _data + _size);
_size += new_elems;
} else {
if(_size + new_elems <= _capacity) {
// total number of elements we want to move
i64 const total_elems = _size - position;
// when new_elems < total_elems, we have to unititialized_move min(total_elems, new_elems)
// and move_backward the rest because the target range will overlap the source range
i64 const elems_outside = math::min(total_elems, new_elems);
i64 const elems_inside = total_elems - elems_outside;
// we move the 'outside' elements to _size unless position + new_elems is greater than _size
i64 const target_offset = math::max(position + new_elems, _size);
anton::uninitialized_move_n(_data + position + elems_inside, elems_outside, _data + target_offset);
anton::move_backward(_data + position, _data + position + elems_inside, _data + position + new_elems + elems_inside);
// we always have to destruct at most total_elems and at least new_elems
// if we attempt to destruct more than total_elems, we will call destruct on uninitialized memory
anton::destruct_n(_data + position, elems_outside);
anton::uninitialized_copy(first, last, _data + position);
_size += new_elems;
} else {
i64 new_capacity = (_capacity > 0 ? _capacity : ANTON_ARRAY_MIN_ALLOCATION_SIZE);
while(new_capacity <= _size + new_elems) {
new_capacity *= 2;
}
T* const new_data = allocate(new_capacity);
i64 moved = 0;
anton::uninitialized_move(_data, _data + position, new_data);
moved = position;
anton::uninitialized_copy(first, last, new_data + moved);
moved += new_elems;
anton::uninitialized_move(_data + position, _data + _size, new_data + moved);
anton::destruct_n(_data, _size);
deallocate(_data, _capacity);
_capacity = new_capacity;
_data = new_data;
_size += new_elems;
}
}
}
return _data + position;
}
template<typename T, typename Allocator>
auto Array<T, Allocator>::insert_unsorted(const_iterator position, value_type const& value) -> iterator {
size_type const offset = static_cast<size_type>(position - begin());
return insert_unsorted(offset, value);
}
template<typename T, typename Allocator>
auto Array<T, Allocator>::insert_unsorted(const_iterator position, value_type&& value) -> iterator {
size_type const offset = static_cast<size_type>(position - begin());
return insert_unsorted(offset, ANTON_MOV(value));
}
template<typename T, typename Allocator>
auto Array<T, Allocator>::insert_unsorted(size_type position, value_type const& value) -> iterator {
if constexpr(ANTON_ITERATOR_DEBUG) {
ANTON_FAIL(position >= 0 && position <= _size, u8"index out of bounds");
}
ensure_capacity(_size + 1);
T* elem_ptr = _data + position;
if(position == _size) {
anton::construct(elem_ptr, value);
} else {
if constexpr(is_move_constructible<T>) {
anton::construct(_data + _size, ANTON_MOV(*elem_ptr));
} else {
anton::construct(_data + _size, *elem_ptr);
}
anton::destruct(elem_ptr);
anton::construct(elem_ptr, value);
}
++_size;
return elem_ptr;
}
template<typename T, typename Allocator>
auto Array<T, Allocator>::insert_unsorted(size_type position, value_type&& value) -> iterator {
if constexpr(ANTON_ITERATOR_DEBUG) {
ANTON_FAIL(position >= 0 && position <= _size, u8"index out of bounds");
}
ensure_capacity(_size + 1);
T* elem_ptr = _data + position;
if(position == _size) {
anton::construct(elem_ptr, ANTON_MOV(value));
} else {
if constexpr(is_move_constructible<T>) {
anton::construct(_data + _size, ANTON_MOV(*elem_ptr));
} else {
anton::construct(_data + _size, *elem_ptr);
}
anton::destruct(elem_ptr);
anton::construct(elem_ptr, ANTON_MOV(value));
}
++_size;
return elem_ptr;
}
template<typename T, typename Allocator>
auto Array<T, Allocator>::push_back(value_type const& value) -> T& {
ensure_capacity(_size + 1);
T* const element = _data + _size;
anton::construct(element, value);
++_size;
return *element;
}
template<typename T, typename Allocator>
auto Array<T, Allocator>::push_back(value_type&& value) -> T& {
ensure_capacity(_size + 1);
T* const element = _data + _size;
anton::construct(element, ANTON_MOV(value));
++_size;
return *element;
}
template<typename T, typename Allocator>
template<typename... Args>
auto Array<T, Allocator>::emplace_back(Args&&... args) -> T& {
ensure_capacity(_size + 1);
T* const element = _data + _size;
anton::construct(element, ANTON_FWD(args)...);
++_size;
return *element;
}
template<typename T, typename Allocator>
void Array<T, Allocator>::erase_unsorted(size_type index) {
if constexpr(ANTON_ITERATOR_DEBUG) {
ANTON_FAIL(index <= size && index >= 0, u8"index out of bounds");
}
erase_unsorted_unchecked(index);
}
template<typename T, typename Allocator>
void Array<T, Allocator>::erase_unsorted_unchecked(size_type index) {
T* const element = _data + index;
T* const last_element = _data + _size - 1;
if(element != last_element) { // Prevent self assignment
*element = ANTON_MOV(*last_element);
}
anton::destruct(last_element);
--_size;
}
template<typename T, typename Allocator>
auto Array<T, Allocator>::erase_unsorted(const_iterator iter) -> iterator {
if constexpr(ANTON_ITERATOR_DEBUG) {
ANTON_FAIL(iter - _data >= 0 && iter - _data <= _size, "iterator out of bounds");
}
T* const position = const_cast<T*>(iter);
T* const last_element = _data + _size - 1;
if(position != last_element) {
*position = ANTON_MOV(*last_element);
}
anton::destruct(last_element);
--_size;
return position;
}
// template <typename T, typename Allocator>
// auto Array<T, Allocator>::erase_unsorted(const_iterator first, const_iterator last) -> iterator {
// #if ANTON_ITERATOR_DEBUG
// #endif // ANTON_ITERATOR_DEBUG
// if (first != last) {
// auto first_last_elems = last - first;
// auto last_end_elems = end() - last;
// auto elems_till_end = math::min(first_last_elems, last_end_elems);
// move(end() - elems_till_end, end(), first);
// destruct(end() - elems_till_end, end());
// _size -= first_last_elems;
// }
// return first;
// }
template<typename T, typename Allocator>
auto Array<T, Allocator>::erase(const_iterator first, const_iterator last) -> iterator {
if constexpr(ANTON_ITERATOR_DEBUG) {
ANTON_FAIL(first - _data >= 0 && first - _data <= _size, "iterator out of bounds");
ANTON_FAIL(last - _data >= 0 && last - _data <= _size, "iterator out of bounds");
}
if(first != last) {
iterator pos = anton::move(const_cast<value_type*>(last), end(), const_cast<value_type*>(first));
anton::destruct(pos, end());
_size -= last - first;
}
return const_cast<value_type*>(first);
}
template<typename T, typename Allocator>
void Array<T, Allocator>::pop_back() {
ANTON_VERIFY(_size > 0, u8"pop_back called on an empty Array");
anton::destruct(_data + _size - 1);
--_size;
}
template<typename T, typename Allocator>
void Array<T, Allocator>::clear() {
anton::destruct(_data, _data + _size);
_size = 0;
}
template<typename T, typename Allocator>
T* Array<T, Allocator>::allocate(size_type const size) {
void* mem = _allocator.allocate(size * static_cast<isize>(sizeof(T)), static_cast<isize>(alignof(T)));
return static_cast<T*>(mem);
}
template<typename T, typename Allocator>
void Array<T, Allocator>::deallocate(void* mem, size_type const size) {
_allocator.deallocate(mem, size * static_cast<isize>(sizeof(T)), static_cast<isize>(alignof(T)));
}
} // namespace anton
| 38.478261 | 156 | 0.610944 | kociap |
99b249080f28590a7fd251531bfd8d976e60881a | 129 | cpp | C++ | boards/px4/io-v2/src/timer_config.cpp | Diksha-agg/Firmware_val | 1efc1ba06997d19df3ed9bd927cfb24401b0fe03 | [
"BSD-3-Clause"
] | null | null | null | boards/px4/io-v2/src/timer_config.cpp | Diksha-agg/Firmware_val | 1efc1ba06997d19df3ed9bd927cfb24401b0fe03 | [
"BSD-3-Clause"
] | null | null | null | boards/px4/io-v2/src/timer_config.cpp | Diksha-agg/Firmware_val | 1efc1ba06997d19df3ed9bd927cfb24401b0fe03 | [
"BSD-3-Clause"
] | null | null | null | version https://git-lfs.github.com/spec/v1
oid sha256:4bee13f1ae0dfeeb63f8afbdabf2f2c704da45573edd3063e914ae9149cba03c
size 2868
| 32.25 | 75 | 0.883721 | Diksha-agg |
99b721b83ca5028f1440627b0d71712eff9ab18b | 964 | cpp | C++ | src/abstraction/Semaphore.cpp | lythaniel/YapiBot | 724d763fc675a984c110da396ae2803a4b847100 | [
"MIT"
] | 2 | 2018-05-28T16:00:52.000Z | 2019-01-21T17:36:29.000Z | src/abstraction/Semaphore.cpp | lythaniel/YapiBot | 724d763fc675a984c110da396ae2803a4b847100 | [
"MIT"
] | null | null | null | src/abstraction/Semaphore.cpp | lythaniel/YapiBot | 724d763fc675a984c110da396ae2803a4b847100 | [
"MIT"
] | null | null | null | /*
* Semaphore.cpp
*
* Copyright (C) 2016 Cyrille Potereau
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
#include "Semaphore.h"
#include <time.h>
CSemaphore::CSemaphore (int32_t maxcount) :
m_MaxCnt(maxcount)
{
sem_init (&m_Sem, 0, 0);
}
CSemaphore::~CSemaphore ()
{
sem_destroy(&m_Sem);
}
bool CSemaphore::wait(int32_t timeout)
{
int32_t ret;
if(timeout == SEM_TIMEOUT_DONTWAIT)
{
ret = sem_trywait(&m_Sem);
}
else if (timeout == SEM_TIMEOUT_FOREVER)
{
ret = sem_wait(&m_Sem);
}
else
{
timespec t;
clock_gettime(CLOCK_REALTIME,&t);
t.tv_sec += timeout/1000;
t.tv_nsec += (timeout % 1000) * 1000000;
ret = sem_timedwait(&m_Sem, &t);
}
return (ret == 0);
}
void CSemaphore::post(void)
{
if (m_MaxCnt > 0)
{
int32_t val;
sem_getvalue(&m_Sem, &val);
if (val < m_MaxCnt)
{
sem_post(&m_Sem);
}
}
else
{
sem_post(&m_Sem);
}
}
| 14.606061 | 64 | 0.650415 | lythaniel |
99c1cfd3e2777ed3effb672764fabcd8db517c87 | 1,513 | hpp | C++ | test/unit/module/real/core/maxmag/diff/maxmag.hpp | orao/eve | a8bdc6a9cab06d905e8749354cde63776ab76846 | [
"MIT"
] | null | null | null | test/unit/module/real/core/maxmag/diff/maxmag.hpp | orao/eve | a8bdc6a9cab06d905e8749354cde63776ab76846 | [
"MIT"
] | null | null | null | test/unit/module/real/core/maxmag/diff/maxmag.hpp | orao/eve | a8bdc6a9cab06d905e8749354cde63776ab76846 | [
"MIT"
] | null | null | null | //==================================================================================================
/**
EVE - Expressive Vector Engine
Copyright : EVE Contributors & Maintainers
SPDX-License-Identifier: MIT
**/
//==================================================================================================
#include <eve/function/diff/maxmag.hpp>
#include <type_traits>
TTS_CASE_TPL("Check diff(maxmag) return type", EVE_TYPE)
{
if constexpr(eve::floating_value<T>)
{
TTS_EXPR_IS(eve::diff_nth<2>(eve::maxmag)(T(), T()), T);
TTS_EXPR_IS(eve::diff_nth<1>(eve::maxmag)(T(), T()), T);
}
else
{
TTS_PASS("Unsupported type");
}
}
TTS_CASE_TPL("Check eve::diff(eve::maxmag) behavior", EVE_TYPE)
{
if constexpr(eve::floating_value<T>)
{
TTS_EQUAL(eve::diff_1st(eve::maxmag)(T{2},T{-3}), T(0));
TTS_EQUAL(eve::diff_2nd(eve::maxmag)(T{2},T{-3}), T(1));
TTS_EQUAL(eve::diff_1st(eve::maxmag)(T{-4},T{3}), T(1));
TTS_EQUAL(eve::diff_2nd(eve::maxmag)(T{-4},T{3}), T(0));
using v_t = eve::element_type_t<T>;
TTS_EQUAL(eve::diff_1st(eve::maxmag)(T(1), T(2), T(3), T(4), T(5)),T(0));
TTS_EQUAL(eve::diff_3rd(eve::maxmag)(T(1), T(2), T(10), T(4), T(5)),T(1));
TTS_EQUAL(eve::diff_nth<3>(eve::maxmag)(T(1), T(2), T(3), T(4), T(5)),T(0));
TTS_EQUAL(eve::diff_nth<6>(eve::maxmag)(T(1), T(2), T(3), T(4), T(5)),T(0));
TTS_EQUAL(eve::diff_nth<4>(eve::maxmag)(v_t(1), T(3), T(3), T(7), T(5)),T(1));
}
else
{
TTS_PASS("Unsupported type");
}
}
| 34.386364 | 100 | 0.519498 | orao |
99c5226676409519adf175cd79556a8a9436fb1e | 3,093 | cc | C++ | src/mpc/test/mpc_flow_reactive_transport.cc | fmyuan/amanzi | edb7b815ae6c22956c8519acb9d87b92a9915ed4 | [
"RSA-MD"
] | 37 | 2017-04-26T16:27:07.000Z | 2022-03-01T07:38:57.000Z | src/mpc/test/mpc_flow_reactive_transport.cc | fmyuan/amanzi | edb7b815ae6c22956c8519acb9d87b92a9915ed4 | [
"RSA-MD"
] | 494 | 2016-09-14T02:31:13.000Z | 2022-03-13T18:57:05.000Z | src/mpc/test/mpc_flow_reactive_transport.cc | fmyuan/amanzi | edb7b815ae6c22956c8519acb9d87b92a9915ed4 | [
"RSA-MD"
] | 43 | 2016-09-26T17:58:40.000Z | 2022-03-25T02:29:59.000Z | #include <iostream>
#include "stdlib.h"
#include "math.h"
#include "UnitTest++.h"
#include <Epetra_MpiComm.h>
#include "Epetra_SerialComm.h"
#include "Teuchos_ParameterList.hpp"
#include "Teuchos_ParameterXMLFileReader.hpp"
#include "CycleDriver.hh"
#include "eos_registration.hh"
#include "Mesh.hh"
#include "MeshFactory.hh"
#include "mpc_pks_registration.hh"
#include "PK_Factory.hh"
#include "PK.hh"
#include "pks_flow_registration.hh"
#include "pks_transport_registration.hh"
#include "pks_chemistry_registration.hh"
#include "State.hh"
TEST(MPC_DRIVER_FLOW_REACTIVE_TRANSPORT) {
using namespace Amanzi;
using namespace Amanzi::AmanziMesh;
using namespace Amanzi::AmanziGeometry;
auto comm = Amanzi::getDefaultComm();
// read the main parameter list
std::string xmlInFileName = "test/mpc_flow_reactive_transport.xml";
Teuchos::ParameterXMLFileReader xmlreader(xmlInFileName);
Teuchos::ParameterList plist = xmlreader.getParameters();
// For now create one geometric model from all the regions in the spec
Teuchos::ParameterList region_list = plist.get<Teuchos::ParameterList>("regions");
Teuchos::RCP<Amanzi::AmanziGeometry::GeometricModel> gm =
Teuchos::rcp(new Amanzi::AmanziGeometry::GeometricModel(3, region_list, *comm));
// create mesh
Preference pref;
pref.clear();
pref.push_back(Framework::MSTK);
pref.push_back(Framework::STK);
MeshFactory meshfactory(comm,gm);
meshfactory.set_preference(pref);
Teuchos::RCP<Mesh> mesh = meshfactory.create(0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 100, 1, 1);
AMANZI_ASSERT(!mesh.is_null());
// create dummy observation data object
double avg1, avg2;
Amanzi::ObservationData obs_data;
Teuchos::RCP<Teuchos::ParameterList> glist = Teuchos::rcp(new Teuchos::ParameterList(plist));
Teuchos::ParameterList state_plist = glist->sublist("state");
Teuchos::RCP<Amanzi::State> S = Teuchos::rcp(new Amanzi::State(state_plist));
S->RegisterMesh("domain", mesh);
{
Amanzi::CycleDriver cycle_driver(glist, S, comm, obs_data);
try {
cycle_driver.Go();
S->GetFieldData("pressure")->MeanValue(&avg1);
} catch (...) {
CHECK(false);
}
// check observations
std::vector<std::string> labels = obs_data.observationLabels();
std::vector<ObservationData::DataQuadruple> tmp = obs_data[labels[0]];
for (int k = 1; k < tmp.size(); ++k) {
CHECK_CLOSE(tmp[k].value, -0.0006, 1.0e-5);
}
tmp = obs_data[labels[1]];
for (int k = 1; k < tmp.size(); ++k) {
CHECK_CLOSE(tmp[k].value, -0.0002, 1.0e-5);
}
}
// restart simulation and compare results
glist->sublist("cycle driver").sublist("restart").set<std::string>("file name", "chk_frt00005.h5");
S = Teuchos::null;
avg2 = 0.;
S = Teuchos::rcp(new Amanzi::State(state_plist));
S->RegisterMesh("domain", mesh);
{
Amanzi::CycleDriver cycle_driver(glist, S, comm, obs_data);
try {
cycle_driver.Go();
S->GetFieldData("pressure")->MeanValue(&avg2);
} catch (...) {
CHECK(false);
}
}
CHECK_CLOSE(avg1, avg2, 1e-5 * avg1);
}
| 29.457143 | 101 | 0.692208 | fmyuan |
99c8eaf7c16791f13dee016aff3c4348574d4d0c | 12,975 | cpp | C++ | test/ReaderTest.cpp | semirpuskarevic/serialization | f911bf5f3c04629f61fe3f3f805eebb3fd5b458a | [
"BSL-1.0"
] | null | null | null | test/ReaderTest.cpp | semirpuskarevic/serialization | f911bf5f3c04629f61fe3f3f805eebb3fd5b458a | [
"BSL-1.0"
] | null | null | null | test/ReaderTest.cpp | semirpuskarevic/serialization | f911bf5f3c04629f61fe3f3f805eebb3fd5b458a | [
"BSL-1.0"
] | null | null | null | #include <date.h>
#include <gmock/gmock.h>
#include <boost/asio/buffer.hpp>
#include <reader.hpp>
#include <writer.hpp>
#include "SerializationTestTypes.hpp"
using namespace testing;
using namespace detail;
using namespace date;
using namespace std::chrono;
namespace asio = boost::asio;
template <size_t N>
class ReaderBase : public Test {
protected:
constexpr static auto arr_size = N;
ReaderBase()
: buf_{asio::buffer(main_buf_)}, writer_{buf_}, reader_{buf_} {}
private:
std::array<char, arr_size> main_buf_;
protected:
asio::mutable_buffer buf_;
writer writer_;
reader reader_;
};
class ReaderTest : public ReaderBase<10u> {
protected:
ReaderTest() {
writer_(fourByteNum);
writer_(twoByteNum);
}
int32_t fourByteNum = 5;
uint16_t twoByteNum = 15;
};
TEST_F(ReaderTest, ReadsIntegralValueAfterWrite) {
int32_t readFourByteNum;
reader_(readFourByteNum);
ASSERT_THAT(readFourByteNum, Eq(fourByteNum));
}
TEST_F(ReaderTest, ReadsTwoConsecutiveIntegralValuesAfterWrite) {
int32_t readFourByteNum;
reader_(readFourByteNum);
uint16_t readTwoByteNum;
reader_(readTwoByteNum);
ASSERT_THAT(readTwoByteNum, Eq(twoByteNum));
}
template <typename T>
class IntegralTypeReader : public ReaderBase<1024u> {
protected:
IntegralTypeReader() { writer_(num); }
T num{5};
};
using MyIntegralTypes = ::testing::Types<char, int8_t, int16_t, int64_t,
uint8_t, uint32_t, uint64_t>;
TYPED_TEST_CASE(IntegralTypeReader, MyIntegralTypes);
TYPED_TEST(IntegralTypeReader, ReadssVariousIntegralTypes) {
TypeParam readNum;
this->reader_(readNum);
ASSERT_THAT(readNum, Eq(this->num));
}
class BooleanTypeReader : public ReaderBase<4u> {
protected:
BooleanTypeReader() {
writer_(true);
writer_(false);
}
};
TEST_F(BooleanTypeReader, ReadsBooleanValuesAfterWrite) {
bool trueValueRead;
bool falseValueRead;
reader_(trueValueRead);
reader_(falseValueRead);
ASSERT_TRUE(trueValueRead);
ASSERT_FALSE(falseValueRead);
}
class FloatingPointTypeReader : public ReaderBase<14u> {
protected:
FloatingPointTypeReader() {
writer_(e);
writer_(ePrecise);
}
float e = 2.718281;
double ePrecise = 2.718281828459;
};
TEST_F(FloatingPointTypeReader, ReadsFloatValueAfterWrite) {
float eRead;
reader_(eRead);
ASSERT_THAT(eRead, Eq(e));
}
TEST_F(FloatingPointTypeReader, ReadsDoubleValueAfterWrite) {
float eRead;
reader_(eRead);
double ePreciseRead;
reader_(ePreciseRead);
ASSERT_THAT(ePreciseRead, ePrecise);
}
class EnumTypeReader : public ReaderBase<8u> {
protected:
enum class CharEnum : char { A = 'A', B = 'B', C = 'C' };
enum class UInt32Enum : uint32_t { X, Y };
EnumTypeReader() {
writer_(CharEnum::B);
writer_(UInt32Enum::X);
}
};
TEST_F(EnumTypeReader, ReadsCharEnumValueAfterWrite) {
CharEnum readValue;
reader_(readValue);
ASSERT_THAT(readValue, Eq(CharEnum::B));
}
TEST_F(EnumTypeReader, ReadsMultipleEnumValuesAfterWrite) {
CharEnum readFirst;
reader_(readFirst);
UInt32Enum readSecond;
reader_(readSecond);
ASSERT_THAT(readSecond, Eq(UInt32Enum::X));
}
class IntegralConstantReader : public ReaderBase<32u> {
protected:
using IntConstUInt16 = std::integral_constant<uint16_t, 0xf001>;
using IntConstUInt32 = std::integral_constant<uint32_t, 0xf0010203>;
IntegralConstantReader() {
writer_(uint16Member);
writer_(regularNum);
writer_(uint32Member);
writer_(regularNum);
}
IntConstUInt16 uint16Member;
int32_t regularNum = 5;
IntConstUInt32 uint32Member;
};
TEST_F(IntegralConstantReader, ReadsUInt16IntegralConstantValueAfterWrite) {
IntConstUInt16 readUint16Member;
reader_(readUint16Member);
int32_t readRegularNum;
reader_(readRegularNum);
ASSERT_THAT(readRegularNum, Eq(5));
}
TEST_F(IntegralConstantReader, ReadsMultipleIntegralConstantValuesAfterWrite) {
IntConstUInt16 readUint16Member;
reader_(readUint16Member);
int32_t readRegularNum;
reader_(readRegularNum);
IntConstUInt32 readUint32Member;
reader_(readUint32Member);
int32_t readSedondRegularNum;
reader_(readSedondRegularNum);
ASSERT_THAT(readSedondRegularNum, Eq(5));
}
TEST_F(IntegralConstantReader,
ConfirmsThatExceptionIsGeneratedWhenConstValueDoesNotMatchReadValue) {
std::integral_constant<uint16_t, 0xf002> differentConstValue;
ASSERT_THROW(reader_(differentConstValue), std::domain_error);
}
class StringReader : public ReaderBase<20u> {
protected:
StringReader() {
writer_("ABC");
writer_("12345");
}
};
TEST_F(StringReader, ReadsStringValueAfterWrite) {
std::string readWord;
reader_(readWord);
ASSERT_THAT(readWord, Eq("ABC"));
}
TEST_F(StringReader, ReadsConsecutiveStringValuesAfterWrite) {
std::string firstWord;
reader_(firstWord);
std::string secondWord;
reader_(secondWord);
ASSERT_THAT(secondWord, Eq("12345"));
}
class VectorReader : public ReaderBase<50u> {
protected:
VectorReader() {
writer_(numbers);
writer_(words);
}
std::vector<int32_t> numbers{1, 5, 10, 15};
std::vector<std::string> words{"A", "AB", "ABC"};
};
TEST_F(VectorReader, ReadsVectorOfIntegralValuesAfterWrite) {
std::vector<int32_t> readNumbers;
reader_(readNumbers);
ASSERT_THAT(readNumbers, Eq(numbers));
}
TEST_F(VectorReader, ReadsConsecutiveVectorsOfDifferentTypeslAfterWrite) {
std::vector<int32_t> readNumbers;
reader_(readNumbers);
std::vector<std::string> readWords;
reader_(readWords);
ASSERT_THAT(readWords, Eq(words));
}
class DateTimeReader : public ReaderBase<15u> {
protected:
DateTimeReader() { writer_(microsecDateTime); }
sys_time<microseconds> microsecDateTime{sys_days(2016_y / 05 / 01) +
hours{5} + minutes{15} +
seconds{0} + microseconds{123456}};
};
TEST_F(DateTimeReader, ReadsTimePointWithMicrosecondsAfterWrite) {
sys_time<microseconds> microsecDateTimeRead;
reader_(microsecDateTimeRead);
ASSERT_THAT(microsecDateTimeRead, Eq(microsecDateTime));
}
class UnorderedMapReader : public ReaderBase<50u> {
protected:
UnorderedMapReader() {
writer_(elements);
writer_(numElements);
}
std::unordered_map<int32_t, std::string> elements{
{1, "A"}, {2, "B"}, {3, "AB"}};
std::unordered_map<int16_t, uint32_t> numElements{{1, 5}, {2, 10}, {3, 15}};
};
TEST_F(UnorderedMapReader, ReadsUnorderedMapValueAfterWrite) {
std::unordered_map<int32_t, std::string> readElements;
reader_(readElements);
ASSERT_THAT(readElements, Eq(elements));
}
TEST_F(UnorderedMapReader, ReadsMultipleUnorderedMapValuesAfterWrite) {
std::unordered_map<int32_t, std::string> readElements;
reader_(readElements);
std::unordered_map<int16_t, uint32_t> readNumElements;
reader_(readNumElements);
ASSERT_THAT(readNumElements, Eq(numElements));
}
class SimpleFusionSequenceReader : public ReaderBase<20u> {
protected:
SimpleFusionSequenceReader() { writer_(header); }
SerializationTestTypes::header_t header = {
{}, 1, SerializationTestTypes::msg_type_t::B};
};
TEST_F(SimpleFusionSequenceReader, ReadsSequenceValuesAfterWrite) {
SerializationTestTypes::header_t readHeader;
reader_(readHeader);
ASSERT_THAT(readHeader.version, Eq(header.version));
ASSERT_THAT(readHeader.msg_type, Eq(header.msg_type));
ASSERT_THAT(readHeader.seq_num, Eq(header.seq_num));
}
class NestedFusionSequenceReader : public ReaderBase<30u> {
protected:
NestedFusionSequenceReader() { writer_(msg); }
SerializationTestTypes::some_message_t msg = {{"12"}, {{"AB", "C"}}};
};
TEST_F(NestedFusionSequenceReader, ReadsNestedFusionSequenceValueAfterWrite) {
SerializationTestTypes::some_message_t readMsg;
reader_(readMsg);
ASSERT_THAT(readMsg.id, Eq(msg.id));
ASSERT_THAT(readMsg.properties.value, Eq(msg.properties.value));
}
class OptionalFieldReader : public ReaderBase<10u> {
protected:
OptionalFieldReader() {
writer_(optFieldsMask);
writer_(optIntField);
writer_(optMsg);
writer_(description);
}
SerializationTestTypes::opt_fields optFieldsMask;
SerializationTestTypes::opt_int32_field optIntField = 5;
SerializationTestTypes::opt_msg_type_t optMsg;
SerializationTestTypes::opt_string_t description = {"AB"};
};
TEST_F(OptionalFieldReader, ReadsOptionalFieldSetAndOptionalValueAfterWrite) {
SerializationTestTypes::opt_fields readOptFieldsMask;
reader_(readOptFieldsMask);
SerializationTestTypes::opt_int32_field readOptIntField;
reader_(readOptIntField);
ASSERT_THAT(*readOptIntField, Eq(*optIntField));
}
TEST_F(OptionalFieldReader, ReadsNonSetOptionalFieldValueAfterWrite) {
SerializationTestTypes::opt_fields readOptFieldsMask;
reader_(readOptFieldsMask);
SerializationTestTypes::opt_int32_field readOptIntField;
reader_(readOptIntField);
SerializationTestTypes::opt_msg_type_t readOptMsg;
reader_(readOptMsg);
ASSERT_FALSE(readOptMsg);
}
TEST_F(OptionalFieldReader, ReadsOptionalFieldValueAfterNonSetValueAfterWrite) {
SerializationTestTypes::opt_fields readOptFieldsMask;
reader_(readOptFieldsMask);
SerializationTestTypes::opt_int32_field readOptIntField;
reader_(readOptIntField);
SerializationTestTypes::opt_msg_type_t readOptMsg;
reader_(readOptMsg);
SerializationTestTypes::opt_string_t readDescription;
reader_(readDescription);
ASSERT_THAT(*readDescription, Eq(description));
}
TEST_F(OptionalFieldReader,
ConfirmsThatExceptionIsGeneratedWhenFieldIsReadBeforeFieldSet) {
SerializationTestTypes::opt_int32_field readOptIntField;
ASSERT_THROW(reader_(readOptIntField), std::domain_error);
}
TEST_F(ReaderTest, ReadsIntegralValueWithReadFunction) {
auto readFourByteNum = read<int32_t>(buf_);
auto readTwoByteNum = read<uint16_t>(readFourByteNum.second);
ASSERT_THAT(readFourByteNum.first, Eq(fourByteNum));
ASSERT_THAT(readTwoByteNum.first, Eq(twoByteNum));
}
TEST_F(EnumTypeReader, ReadsMultipleEnumValuesWithReadFunction) {
auto readFirst = read<CharEnum>(buf_);
auto readSecond = read<UInt32Enum>(readFirst.second);
ASSERT_THAT(readFirst.first, Eq(CharEnum::B));
ASSERT_THAT(readSecond.first, Eq(UInt32Enum::X));
}
TEST_F(IntegralConstantReader,
ReadsMultipleIntegralConstantValuesWithReadFunction) {
auto readUint16Member = read<IntConstUInt16>(buf_);
auto readRegularNum = read<int32_t>(readUint16Member.second);
auto readUint32Member = read<IntConstUInt32>(readRegularNum.second);
auto readSedondRegularNum = read<int32_t>(readUint32Member.second);
ASSERT_THAT(readSedondRegularNum.first, Eq(5));
}
TEST_F(StringReader, ReadsConsecutiveStringValuesWithReadFunction) {
auto firstWord = read<std::string>(buf_);
auto secondWord = read<std::string>(firstWord.second);
ASSERT_THAT(secondWord.first, Eq("12345"));
}
TEST_F(VectorReader, ReadsConsecutiveVectorsOfDifferentTypesWithReadFunction) {
auto readNumbes = read<std::vector<int32_t>>(buf_);
auto readWords = read<std::vector<std::string>>(readNumbes.second);
ASSERT_THAT(readWords.first, Eq(words));
}
TEST_F(UnorderedMapReader, ReadsMultipleUnorderedMapValuesWithReadFunction) {
auto readElements = read<std::unordered_map<int32_t, std::string>>(buf_);
auto readNumElements =
read<std::unordered_map<int16_t, uint32_t>>(readElements.second);
ASSERT_THAT(readNumElements.first, Eq(numElements));
}
TEST_F(NestedFusionSequenceReader,
ReadsNestedFusionSequenceValueWithReadFunction) {
auto readMsg = read<SerializationTestTypes::some_message_t>(buf_);
ASSERT_THAT(readMsg.first.id, Eq(msg.id));
ASSERT_THAT(readMsg.first.properties.value, Eq(msg.properties.value));
}
TEST_F(
OptionalFieldReader,
ConfirmsThatExceptionIsGeneratedWhenReadingOptionalFieldsWithReadFunction) {
auto readOptFieldsMask = read<SerializationTestTypes::opt_fields>(buf_);
ASSERT_THROW(
read<SerializationTestTypes::opt_int32_field>(readOptFieldsMask.second),
std::domain_error);
}
class FusionSequenceWithOptionalFieldReader : public ReaderBase<50u> {
protected:
FusionSequenceWithOptionalFieldReader() { writer_(msg); }
SerializationTestTypes::msg_with_opt_fields_t msg = {
{{"A", "B", "AB"}}, {}, {5}, {}};
};
TEST_F(FusionSequenceWithOptionalFieldReader,
ReadOptionalFieldsAsPartOfFusionSequenceWithReadFunction) {
auto readMsg = read<SerializationTestTypes::msg_with_opt_fields_t>(buf_);
ASSERT_THAT(readMsg.first.properties.value, Eq(msg.properties.value));
ASSERT_THAT(readMsg.first.number, Eq(5));
}
| 29.896313 | 80 | 0.734489 | semirpuskarevic |
99cf8f6cd7dd98f2362504cfdddc4dd92cad37df | 13,045 | cpp | C++ | src/IsingMCMC.cpp | liyufan1994/CS205ParallelCipher | 121e800dad149c7019d80d8d6fc4e0490b9df803 | [
"MIT"
] | null | null | null | src/IsingMCMC.cpp | liyufan1994/CS205ParallelCipher | 121e800dad149c7019d80d8d6fc4e0490b9df803 | [
"MIT"
] | null | null | null | src/IsingMCMC.cpp | liyufan1994/CS205ParallelCipher | 121e800dad149c7019d80d8d6fc4e0490b9df803 | [
"MIT"
] | null | null | null |
#include <iostream>
#include <math.h>
#include <random>
#include <vector>
#include <fstream>
#include <map>
#include <string>
#include <algorithm>
#include <mpi.h>
#include <omp.h>
#include "Randomize.h"
#include "Ising.h"
#include "ArrayUtilities.h"
/*
*
* This function runs totalS number of parallel chains each on a temperature level defined in temps.
* Each MPI process is responsible for 1 or more chains in the pool.
* Each chain is run iterNum number of iterations where each iteration consists of T number of steps
* The chains communicates via MPI send and receive. temperedChains outputs result in the result array.
*
* Function Arguments:
* iterNum: number of iterations
* totalS: total number of parallel chains (each core may run more than one chain)
* Nd: dimension of state space
* T: number of steps each iteration
* rank: rank of current MPI process
* size: number of concurrent MPI processes
*
* */
void temperedChainsIsing(int iterNum, int totalS, int Nd, int T, double *temps, int rank, int size, int kernel)
{
// Each MPI process is assigned S chains to run
int S=totalS/size;
if (rank==size-1)
{
S=totalS/size+totalS%size;
}
// Each MPI process stores results in partialresult array of S columns and iterNum rows
int **partialresult;
create2Dmemory(partialresult,iterNum,S);
// Each MPI process has a different seed
srand(unsigned(time(0))+rank);
// Each chain creates a new starting state from uniform sampling
int ***xs;
create3Dmemory(xs, S, Nd,Nd);
for (int chains=0; chains<S; ++chains)
{
for (int i=0; i<Nd; ++i)
{
for (int j=0;j<Nd; ++j)
{
if (unifrnd(0,1)<0.5)
xs[chains][i][j]=1;
else{
xs[chains][i][j]=0;
}
}
}
}
/* Define variables used in the loop */
int exchangetimes=0; // total number of exchange that occur
double originallog; // store value of log target in prev step
double proplog; // store value of log target of the proposal
int glbc1; // global idx of chain 1 to exchange
int glbc2; // global idx of chain 2 to exchange
int rank1; // processor that runs chain 1
int rank2; // processor that runs chain 2
int c1; // local idx of chain 1 to exchange
int c2; // local idx of chain 2 to exchange
double coin; // store value of coin toss
double accpt; // store value of acceptance ratio
for (int iter=0; iter<iterNum; ++iter){
for (int chains=0; chains<S; ++chains)
{
if (kernel==0)
{
oneChainIsing(xs[chains], T, Nd, temps[chains+rank*S]);
} else {
oneChainIsingChess(xs[chains], T, Nd, temps[chains+rank*S]);
}
partialresult[iter][chains]=t(xs[chains],Nd);
}
// Global index of the two chain to exchange positions
glbc1=iterNum % totalS;
glbc2=(iterNum+1) % totalS;
if (totalS==1)
{
glbc1=0;
glbc2=0;
}
// Which processors these two indexes belong to
rank1=glbc1/S;
rank2=glbc2/S;
// Current process is not involved in exchange
if ((rank1!=rank)&&(rank2!=rank))
{
continue;
}
// Both indexes to exchange belong to current process
else if (rank1==rank2){
// Convert global indexes to local indexes
c1=glbc1%S;
c2=glbc2%S;
// Compute acceptance ratio
originallog=logtargetIsing(xs[c1],Nd,temps[c1])+logtargetIsing(xs[c2],Nd,temps[c2]);
proplog=logtargetIsing(xs[c1],Nd,temps[c2])+logtargetIsing(xs[c2],Nd,temps[c1]);
accpt=exp(proplog-originallog);
// Determine if accept by toss a random coin
coin=unifrnd(0,1);
if (coin<accpt){
// We indeed accept the proposal
int **imp;
imp=xs[c1];
xs[c1]=xs[c2];
xs[c2]=imp;
exchangetimes+=1;
}
}
// Indexes to exchange occur on two different processes
else {
if (rank == rank1){
int c1=glbc1%S;
double logtgtc1c1=logtargetIsing(xs[c1],Nd,temps[glbc1]);
double logtgtc1c2=logtargetIsing(xs[c1],Nd,temps[glbc2]);
int **xsc2;
create2Dmemory(xsc2,Nd,Nd);
int xsc21D[Nd*Nd];
MPI_Recv(xsc21D,Nd*Nd,MPI_INT,rank2,0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
conv1Dto2D(xsc21D, xsc2, Nd, Nd);
double logtgtc2c2=logtargetIsing(xsc2,Nd,temps[glbc2]);
double logtgtc2c1=logtargetIsing(xsc2,Nd,temps[glbc1]);
originallog=logtgtc1c1+logtgtc2c2;
proplog=logtgtc1c2+logtgtc2c1;
accpt=exp(proplog-originallog);
coin=unifrnd(0,1);
if (coin<accpt){
// We indeed accept the proposal, notify the other chain
int accptstatus=1;
MPI_Send(&accptstatus,1,MPI_INT,rank2,0,MPI_COMM_WORLD);
int xsc11D[Nd*Nd];
conv2Dto1D(xs[c1],xsc11D,Nd,Nd);
MPI_Send(xsc11D,Nd*Nd,MPI_INT,rank2,0,MPI_COMM_WORLD);
deepcopy2Darray(xsc2,xs[c1], Nd, Nd);
exchangetimes+=1;
} else {
int accptstatus=0;
MPI_Send(&accptstatus,1,MPI_INT,rank2,0,MPI_COMM_WORLD);
}
} else {
int c2=glbc2%S;
int accptstatus;
int xsc21D[Nd*Nd];
conv2Dto1D(xs[c2],xsc21D,Nd,Nd);
MPI_Send(xsc21D,Nd*Nd,MPI_INT,rank1,0,MPI_COMM_WORLD);
MPI_Recv(&accptstatus,1,MPI_INT,rank1,0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
if (accptstatus==1)
{
int **xsc1;
create2Dmemory(xsc1,Nd,Nd);
int xsc11D[Nd*Nd];
MPI_Recv(xsc11D,Nd*Nd,MPI_INT,rank1,0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
conv1Dto2D(xsc11D,xsc1,Nd,Nd);
deepcopy2Darray(xsc1,xs[c2], Nd,Nd);
exchangetimes+=1;
}
}
}
}
print2Darray(partialresult,iterNum,S,"output"+std::to_string(rank)+".txt");
free3Dmemory(xs, S, Nd,Nd);
}
/*
* This function takes the Markov chain T steps forward. The parallelization used is
* the strip partitioning.
*
* Function Argument:
* x: pointer to the starting state;
* T: number fo steps
* Nd: side length of the Ising lattice
* temp: temperature of the Ising lattice
*
* */
void oneChainIsing(int **x, int T, int Nd, double temp)
{
#pragma omp parallel shared(x)
{
//int numthreads=2;
//for (int threadid=0; threadid<numthreads; ++threadid)
//{
for (int t=0; t<T; ++t)
{
int threadid = omp_get_thread_num();
int numthreads = omp_get_num_threads();
if (Nd/numthreads<=1)
{
throw "Too many threads! One thread must have at least 2 rows";
}
// Partition the matrix in strips
int low = Nd*threadid/numthreads;
int high=Nd*(threadid+1)/numthreads;
if (high>Nd)
{
high=Nd;
}
// The schedule now is to update everything except the last row
for(int i=low; i<high-1; ++i)
{
for(int j=0; j<Nd; ++j)
{
int leftj=j-1;
int rightj=j+1;
if (j==0)
{
leftj=Nd-1;
}
else if (j==(Nd-1))
{
rightj=0;
}
int upi=i-1;
int downi=i+1;
if (i==0)
{
upi=Nd-1;
}else if (i==Nd-1)
{
downi=0;
}
double s=x[upi][j]+x[downi][j]+x[i][leftj]+x[i][rightj];
double cond_p=exp(temp*s)/(exp(temp*s)+exp(-temp*s));
if (unifrnd(0,1)<cond_p)
{
x[i][j]=1;
} else{
x[i][j]=0;
}
}
}
// put a barrier here go ensure all threads update the last row on new values from neighboring regions
#pragma omp barrier
int i=high-1;
for (int j=0;j<Nd;++j)
{
int leftj=j-1;
int rightj=j+1;
if (j==0)
{
leftj=Nd-1;
}
else if (j==(Nd-1))
{
rightj=0;
}
int upi=i-1;
int downi=i+1;
if (i==0)
{
upi=Nd-1;
}else if (i==Nd-1)
{
downi=0;
}
double s=x[upi][j]+x[downi][j]+x[i][leftj]+x[i][rightj];
double cond_p=exp(temp*s)/(exp(temp*s)+exp(-temp*s));
if (unifrnd(0,1)<cond_p)
{
x[i][j]=1;
} else{
x[i][j]=0;
}
}
// Put a barrier here to ensure iteration is synchronized each step
#pragma omp barrier
}
//}
}
}
void oneChainIsingChess(int **x, int T, int Nd, double temp)
{
// We specify that the chess board starts first row with white
// Update all white cells
#pragma omp parallel for
for (int i=0; i<Nd; ++i)
{
int jst=0;
if (i%2==1)
{
jst=1;
}
int upi=i-1;
int downi=i+1;
if (i==0)
{
upi=Nd-1;
}else if (i==Nd-1)
{
downi=0;
}
for (int j=jst; j<Nd; j=j+2)
{
int leftj=j-1;
int rightj=j+1;
if (j==0)
{
leftj=Nd-1;
}
else if (j==(Nd-1))
{
rightj=0;
}
double s=x[upi][j]+x[downi][j]+x[i][leftj]+x[i][rightj];
double cond_p=exp(temp*s)/(exp(temp*s)+exp(-temp*s));
if (unifrnd(0,1)<cond_p)
{
x[i][j]=1;
} else{
x[i][j]=0;
}
}
}
// Update all black cells
#pragma omp parallel for
for (int i=0; i<Nd; ++i)
{
int jst=1;
if (i%2==1)
{
jst=0;
}
int upi=i-1;
int downi=i+1;
if (i==0)
{
upi=Nd-1;
}else if (i==Nd-1)
{
downi=0;
}
for (int j=jst; j<Nd; j=j+2)
{
int leftj=j-1;
int rightj=j+1;
if (j==0)
{
leftj=Nd-1;
}
else if (j==(Nd-1))
{
rightj=0;
}
double s=x[upi][j]+x[downi][j]+x[i][leftj]+x[i][rightj];
double cond_p=exp(temp*s)/(exp(temp*s)+exp(-temp*s));
if (unifrnd(0,1)<cond_p)
{
x[i][j]=1;
} else{
x[i][j]=0;
}
}
}
}
double t(int **x, int Nd)
{
double result=0;
#pragma omp parallel for reduction(+:result)
for(int i=0; i<Nd; ++i)
{
for(int j=0; j<Nd; ++j)
{
int leftj=j-1;
int rightj=j+1;
if (j==0)
{
leftj=Nd-1;
}
else if (j==(Nd-1))
{
rightj=0;
}
int upi=i-1;
int downi=i+1;
if (i==0)
{
upi=Nd-1;
}else if (i==Nd-1)
{
downi=0;
}
result+=x[i][j]*(x[upi][j]+x[downi][j]+x[i][leftj]+x[i][rightj]);
}
}
return 0.5*result;
}
double logtargetIsing(int **x, int Nd,double temp)
{
double result=0;
result=t(x,Nd);
result=exp(temp*result);
return result;
}
| 26.247485 | 118 | 0.448601 | liyufan1994 |
99d3be8c9bf582acbefe0fb98fc8bac2a2e749b1 | 12,451 | cpp | C++ | 5_System_Processes.cpp | yangminglong/FUGU-ARDUINO-MPPT-FIRMWARE | 1a378a2248a636569f5e6a19b14b9bd3b34f4106 | [
"CC0-1.0"
] | null | null | null | 5_System_Processes.cpp | yangminglong/FUGU-ARDUINO-MPPT-FIRMWARE | 1a378a2248a636569f5e6a19b14b9bd3b34f4106 | [
"CC0-1.0"
] | null | null | null | 5_System_Processes.cpp | yangminglong/FUGU-ARDUINO-MPPT-FIRMWARE | 1a378a2248a636569f5e6a19b14b9bd3b34f4106 | [
"CC0-1.0"
] | null | null | null | #include "5_System_Processes.h"
#include "defines.h"
#include <EEPROM.h>
#include "Preferences.h"
#include "nvs.h"
#include "nvs_flash.h"
#include "esp32-hal-log.h"
const char * my_nvs_errors[] = { "OTHER", "NOT_INITIALIZED", "NOT_FOUND", "TYPE_MISMATCH", "READ_ONLY", "NOT_ENOUGH_SPACE", "INVALID_NAME", "INVALID_HANDLE", "REMOVE_FAILED", "KEY_TOO_LONG", "PAGE_FULL", "INVALID_STATE", "INVALID_LENGTH"};
#define my_nvs_error(e) (((e)>ESP_ERR_NVS_BASE)? my_nvs_errors[(e)&~(ESP_ERR_NVS_BASE)]: my_nvs_errors[0])
class MyPreferences : public Preferences
{
public:
MyPreferences() : Preferences() {}
size_t myPutChar(const char* key, int8_t value){
if(!_started || !key || _readOnly){
return 0;
}
esp_err_t err = nvs_set_i8(_handle, key, value);
if(err){
log_e("nvs_set_i8 fail: %s %s", key, my_nvs_error(err));
return 0;
}
return 1;
}
size_t myPutUChar(const char* key, uint8_t value){
if(!_started || !key || _readOnly){
return 0;
}
esp_err_t err = nvs_set_u8(_handle, key, value);
if(err){
log_e("nvs_set_u8 fail: %s %s", key, my_nvs_error(err));
return 0;
}
return 1;
}
size_t myPutShort(const char* key, int16_t value){
if(!_started || !key || _readOnly){
return 0;
}
esp_err_t err = nvs_set_i16(_handle, key, value);
if(err){
log_e("nvs_set_i16 fail: %s %s", key, my_nvs_error(err));
return 0;
}
return 2;
}
size_t myPutUShort(const char* key, uint16_t value){
if(!_started || !key || _readOnly){
return 0;
}
esp_err_t err = nvs_set_u16(_handle, key, value);
if(err){
log_e("nvs_set_u16 fail: %s %s", key, my_nvs_error(err));
return 0;
}
return 2;
}
size_t myPutInt(const char* key, int32_t value){
if(!_started || !key || _readOnly){
return 0;
}
esp_err_t err = nvs_set_i32(_handle, key, value);
if(err){
log_e("nvs_set_i32 fail: %s %s", key, my_nvs_error(err));
return 0;
}
return 4;
}
size_t myPutUInt(const char* key, uint32_t value){
if(!_started || !key || _readOnly){
return 0;
}
esp_err_t err = nvs_set_u32(_handle, key, value);
if(err){
log_e("nvs_set_u32 fail: %s %s", key, my_nvs_error(err));
return 0;
}
return 4;
}
size_t myPutLong(const char* key, int32_t value){
return myPutInt(key, value);
}
size_t myPutULong(const char* key, uint32_t value){
return myPutUInt(key, value);
}
size_t myPutLong64(const char* key, int64_t value){
if(!_started || !key || _readOnly){
return 0;
}
esp_err_t err = nvs_set_i64(_handle, key, value);
if(err){
log_e("nvs_set_i64 fail: %s %s", key, my_nvs_error(err));
return 0;
}
return 8;
}
size_t myPutULong64(const char* key, uint64_t value){
if(!_started || !key || _readOnly){
return 0;
}
esp_err_t err = nvs_set_u64(_handle, key, value);
if(err){
log_e("nvs_set_u64 fail: %s %s", key, my_nvs_error(err));
return 0;
}
return 8;
}
size_t myPutFloat(const char* key, const float_t value){
return myPutBytes(key, (void*)&value, sizeof(float_t));
}
size_t myPutDouble(const char* key, const double_t value){
return myPutBytes(key, (void*)&value, sizeof(double_t));
}
size_t myPutBool(const char* key, const bool value){
return myPutUChar(key, (uint8_t) (value ? 1 : 0));
}
size_t myPutString(const char* key, const char* value){
if(!_started || !key || !value || _readOnly){
return 0;
}
esp_err_t err = nvs_set_str(_handle, key, value);
if(err){
log_e("nvs_set_str fail: %s %s", key, my_nvs_error(err));
return 0;
}
return strlen(value);
}
size_t myPutString(const char* key, const String value){
return myPutString(key, value.c_str());
}
size_t myPutBytes(const char* key, const void* value, size_t len){
if(!_started || !key || !value || !len || _readOnly){
return 0;
}
esp_err_t err = nvs_set_blob(_handle, key, value, len);
if(err){
log_e("nvs_set_blob fail: %s %s", key, my_nvs_error(err));
return 0;
}
return len;
}
void myCommit() {
esp_err_t err = nvs_commit(_handle);
if(err){
log_e("nvs_commit fail: %s", my_nvs_error(err));
return ;
}
}
};
void resetVariables(){
secondsElapsed = 0;
energySavings = 0;
daysRunning = 0;
timeOn = 0;
}
void System_Processes(){
///////////////// FAN COOLING /////////////////
if(enableFan==true){
if(enableDynamicCooling==false){ //STATIC PWM COOLING MODE (2-PIN FAN - no need for hysteresis, temp data only refreshes after 'avgCountTS' or every 500 loop cycles)
if(overrideFan==true){fanStatus=true;} //Force on fan
else if(temperature>=temperatureFan){fanStatus=1;} //Turn on fan when set fan temp reached
else if(temperature<temperatureFan){fanStatus=0;} //Turn off fan when set fan temp reached
digitalWrite(FAN,fanStatus); //Send a digital signal to the fan MOSFET
}
else{} //DYNAMIC PWM COOLING MODE (3-PIN FAN - coming soon)
}
else{digitalWrite(FAN,LOW);} //Fan Disabled
//////////// LOOP TIME STOPWATCH ////////////
loopTimeStart = micros(); //Record Start Time
loopTime = (loopTimeStart-loopTimeEnd)/1000.000; //Compute Loop Cycle Speed (mS)
loopTimeEnd = micros(); //Record End Time
///////////// AUTO DATA RESET /////////////
if(telemCounterReset==0){} //Never Reset
else if(telemCounterReset==1 && daysRunning>1) { resetVariables(); } //Daily Reset
else if(telemCounterReset==2 && daysRunning>7) { resetVariables(); } //Weekly Reset
else if(telemCounterReset==3 && daysRunning>30) { resetVariables(); } //Monthly Reset
else if(telemCounterReset==4 && daysRunning>365){ resetVariables(); } //Yearly Reset
///////////// LOW POWER MODE /////////////
if(lowPowerMode==1){}
else{}
}
MyPreferences prefe;
void setupPreferences() {
prefe.begin("MPPT");
}
void loadSettings() {
flashMemLoad = prefe.getBool("flashMemLoad", 1);
MPPT_Mode = prefe.getBool("MPPT_Mode", 1);
output_Mode = prefe.getBool("output_Mode", 1);
enableFan = prefe.getBool("enableFan", 1);
enableWiFi = prefe.getBool("enableWiFi", 1);
temperatureFan = prefe.getInt("temperatureFan", 60);
temperatureMax = prefe.getInt("temperatureMax", 90);
backlightSleepMode = prefe.getInt("backlightSleepMode", 0);
voltageBatteryMax = prefe.getFloat("voltageBatteryMax", 25.5);
voltageBatteryMin = prefe.getFloat("voltageBatteryMin", 20);
currentChargingMax = prefe.getFloat("currentChargingMax", 50);
// MPPT_Mode = EEPROM.read(0); // Load saved charging mode setting
// output_Mode = EEPROM.read(12); // Load saved charging mode setting
// voltageBatteryMax = EEPROM.read(1)+(EEPROM.read(2)*.01); // Load saved maximum battery voltage setting
// voltageBatteryMin = EEPROM.read(3)+(EEPROM.read(4)*.01); // Load saved minimum battery voltage setting
// currentChargingMax = EEPROM.read(5)+(EEPROM.read(6)*.01); // Load saved charging current setting
// enableFan = EEPROM.read(7); // Load saved fan enable settings
// temperatureFan = EEPROM.read(8); // Load saved fan temperature settings
// temperatureMax = EEPROM.read(9); // Load saved shutdown temperature settings
// enableWiFi = EEPROM.read(10); // Load saved WiFi enable settings
// flashMemLoad = EEPROM.read(11); // Load saved flash memory autoload feature
// backlightSleepMode = EEPROM.read(13); // Load saved lcd backlight sleep timer
}
void saveSettings() {
prefe.myPutBool("MPPT_Mode", MPPT_Mode);
prefe.myPutBool("output_Mode", output_Mode);
prefe.myPutBool("enableFan", enableFan);
prefe.myPutBool("enableWiFi", enableWiFi);
prefe.myPutInt("temperatureFan", temperatureFan);
prefe.myPutInt("temperatureMax", temperatureMax);
prefe.myPutInt("backlightSleepMode", backlightSleepMode);
prefe.myPutFloat("voltageBatteryMax", voltageBatteryMax);
prefe.myPutFloat("voltageBatteryMin", voltageBatteryMin);
prefe.myPutFloat("currentChargingMax", currentChargingMax);
prefe.myCommit();
// // EEPROM.write(0,MPPT_Mode); //STORE: Algorithm
// EEPROM.write(12,output_Mode); //STORE: Charge/PSU Mode Selection
// conv1 = voltageBatteryMax*100; //STORE: Maximum Battery Voltage (gets whole number)
// conv2 = conv1%100; //STORE: Maximum Battery Voltage (gets decimal number and converts to a whole number)
// EEPROM.write(1,voltageBatteryMax);
// EEPROM.write(2,conv2);
// conv1 = voltageBatteryMin*100; //STORE: Minimum Battery Voltage (gets whole number)
// conv2 = conv1%100; //STORE: Minimum Battery Voltage (gets decimal number and converts to a whole number)
// EEPROM.write(3,voltageBatteryMin);
// EEPROM.write(4,conv2);
// conv1 = currentChargingMax*100; //STORE: Charging Current
// conv2 = conv1%100;
// EEPROM.write(5,currentChargingMax);
// EEPROM.write(6,conv2);
// EEPROM.write(7,enableFan); //STORE: Fan Enable
// EEPROM.write(8,temperatureFan); //STORE: Fan Temp
// EEPROM.write(9,temperatureMax); //STORE: Shutdown Temp
// EEPROM.write(10,enableWiFi); //STORE: Enable WiFi
// //EEPROM.write(11,flashMemLoad); //STORE: Enable autoload (must be excluded from bulk save, uncomment under discretion)
// EEPROM.write(13,backlightSleepMode); //STORE: LCD backlight sleep timer
// EEPROM.commit(); //Saves setting changes to flash memory
}
void factoryReset(){
prefe.myPutBool("flashMemLoad", 1);
prefe.myPutBool("MPPT_Mode", 1);
prefe.myPutBool("output_Mode", 1);
prefe.myPutBool("enableFan", 1);
prefe.myPutBool("enableWiFi", 1);
prefe.myPutInt("temperatureFan", 60);
prefe.myPutInt("temperatureMax", 90);
prefe.myPutInt("backlightSleepMode", 0);
prefe.myPutFloat("voltageBatteryMax", 25.5);
prefe.myPutFloat("voltageBatteryMin", 20);
prefe.myPutFloat("currentChargingMax", 50);
prefe.myCommit();
// EEPROM.write(0,1); //STORE: Charging Algorithm (1 = MPPT Mode)
// EEPROM.write(12,1); //STORE: Charger/PSU Mode Selection (1 = Charger Mode)
// EEPROM.write(1,12); //STORE: Max Battery Voltage (whole)
// EEPROM.write(2,0); //STORE: Max Battery Voltage (decimal)
// EEPROM.write(3,9); //STORE: Min Battery Voltage (whole)
// EEPROM.write(4,0); //STORE: Min Battery Voltage (decimal)
// EEPROM.write(5,30); //STORE: Charging Current (whole)
// EEPROM.write(6,0); //STORE: Charging Current (decimal)
// EEPROM.write(7,1); //STORE: Fan Enable (Bool)
// EEPROM.write(8,60); //STORE: Fan Temp (Integer)
// EEPROM.write(9,90); //STORE: Shutdown Temp (Integer)
// EEPROM.write(10,1); //STORE: Enable WiFi (Boolean)
// EEPROM.write(11,1); //STORE: Enable autoload (on by default)
// // EEPROM.write(13,0); //STORE: LCD backlight sleep timer (default: 0 = never)
// EEPROM.commit();
loadSettings();
}
void saveAutoloadSettings(){
// EEPROM.write(11,flashMemLoad); //STORE: Enable autoload
// EEPROM.commit(); //Saves setting changes to flash memory
prefe.putBool("flashMemLoad", flashMemLoad);
}
void initializeFlashAutoload() {
if(disableFlashAutoLoad==0){
flashMemLoad = prefe.getBool("flashMemLoad", false);
// flashMemLoad = EEPROM.read(11); //Load saved autoload (must be excluded from bulk save, uncomment under discretion)
if(flashMemLoad==1){loadSettings();} //Load stored settings from flash memory
}
}
| 38.076453 | 239 | 0.609188 | yangminglong |
99d5de8c314b656a1a4c73cee84f77e2ea1fc44d | 1,103 | cpp | C++ | src/invoiceutil.cpp | DNotesCoin/DNotes2.0 | 5dbf99d34ecd2a939fc5306525c3b197243259ba | [
"MIT"
] | 4 | 2018-05-13T07:40:59.000Z | 2019-05-27T20:05:19.000Z | src/invoiceutil.cpp | DNotesCoin/DNotes2.0 | 5dbf99d34ecd2a939fc5306525c3b197243259ba | [
"MIT"
] | 3 | 2018-05-17T20:31:06.000Z | 2019-06-04T14:05:29.000Z | src/invoiceutil.cpp | DNotesCoin/DNotes2.0 | 5dbf99d34ecd2a939fc5306525c3b197243259ba | [
"MIT"
] | 5 | 2018-01-09T17:54:22.000Z | 2018-11-02T14:53:52.000Z |
#include "util.h"
#include "invoiceutil.h"
namespace InvoiceUtil {
bool validateInvoiceNumber(std::string input)
{
int size = input.size();
if(size > 32) {
return false;
}
for(int idx=0; idx < size; ++idx)
{
int ch = input.at(idx);
if(((ch >= '0' && ch<='9') ||
(ch >= 'a' && ch<='z') ||
(ch >= 'A' && ch<='Z') ||
(ch == '-')))
{
// Alphanumeric or -
}
else
{
return false;
}
}
return true;
}
void parseInvoiceNumberAndAddress(std::string input, std::string& outAddress, std::string& outInvoiceNumber)
{
size_t plusIndex = input.find('+');
if(plusIndex == string::npos)
{ //no +
outAddress = input;
outInvoiceNumber = "";
}
else
{ //+
outAddress = input.substr(0, plusIndex);
outInvoiceNumber = input.substr(plusIndex + 1, input.size());
}
}
} | 22.510204 | 112 | 0.426111 | DNotesCoin |
99d81f202ad5ab104644196d68071adc5887203f | 656 | cpp | C++ | cpp03/ex01/main.cpp | ndeana-21/cpp | 98932eab0c1d57a715b6deb76c7a294c1e86f2fd | [
"MIT"
] | null | null | null | cpp03/ex01/main.cpp | ndeana-21/cpp | 98932eab0c1d57a715b6deb76c7a294c1e86f2fd | [
"MIT"
] | null | null | null | cpp03/ex01/main.cpp | ndeana-21/cpp | 98932eab0c1d57a715b6deb76c7a294c1e86f2fd | [
"MIT"
] | null | null | null | #include "FragTrap.hpp"
#include "ScavTrap.hpp"
int main()
{
FragTrap frag_trap;
FragTrap R2D2("R2D2");
FragTrap test("BMO");
FragTrap BMO(test);
FragTrap test2("C-3PO");
FragTrap C_3PO = test2;
frag_trap.rangeAttack("Blue bird");
frag_trap.meleeAttack("Handsome Jack");
frag_trap.takeDamage(42);
frag_trap.takeDamage(1);
frag_trap.beRepaired(42);
frag_trap.takeDamage(200);
for (int i=0; i < 5; i++) {
BMO.vaulthunter_dot_exe("Jake the Dog");
C_3PO.vaulthunter_dot_exe("Jar Jar Binks");
R2D2.vaulthunter_dot_exe("Yoda");
}
ScavTrap scav_trap("Happy");
for (int i=0; i < 5; i++)
scav_trap.challengeNewcomer("Jojo");
return 0;
}
| 21.866667 | 45 | 0.70122 | ndeana-21 |
99dc5f6a79eaab8bcd489fc3fb5da4268b34b113 | 1,420 | cpp | C++ | src/ExecuteConfigSection.cpp | babetoduarte/EF5 | 5e469f288bce82259e85d26a3f30f7dc260547fb | [
"Unlicense"
] | 20 | 2016-09-20T15:19:54.000Z | 2021-09-04T21:53:30.000Z | src/ExecuteConfigSection.cpp | chrimerss/EF5 | c97ed83ead8fd764f7c94731fd5bf74761a0bb3d | [
"Unlicense"
] | 10 | 2016-09-20T17:13:00.000Z | 2022-03-20T12:53:37.000Z | src/ExecuteConfigSection.cpp | chrimerss/EF5 | c97ed83ead8fd764f7c94731fd5bf74761a0bb3d | [
"Unlicense"
] | 20 | 2016-12-01T21:41:40.000Z | 2021-08-07T06:11:43.000Z | #include "ExecuteConfigSection.h"
#include "Messages.h"
#include <cstdio>
#include <cstring>
ExecuteConfigSection *g_executeConfig = NULL;
ExecuteConfigSection::ExecuteConfigSection() {}
ExecuteConfigSection::~ExecuteConfigSection() {}
CONFIG_SEC_RET ExecuteConfigSection::ProcessKeyValue(char *name, char *value) {
if (strcasecmp(name, "task") == 0) {
TOLOWER(value);
std::map<std::string, TaskConfigSection *>::iterator itr =
g_taskConfigs.find(value);
if (itr == g_taskConfigs.end()) {
ERROR_LOGF("Unknown task \"%s\"!", value);
return INVALID_RESULT;
}
tasks.push_back(itr->second);
} else if (strcasecmp(name, "ensembletask") == 0) {
TOLOWER(value);
std::map<std::string, EnsTaskConfigSection *>::iterator itr =
g_ensTaskConfigs.find(value);
if (itr == g_ensTaskConfigs.end()) {
ERROR_LOGF("Unknown ensemble task \"%s\"!", value);
return INVALID_RESULT;
}
ensTasks.push_back(itr->second);
} else {
return INVALID_RESULT;
}
return VALID_RESULT;
}
CONFIG_SEC_RET ExecuteConfigSection::ValidateSection() {
if (tasks.size() == 0) {
ERROR_LOG("No tasks were defined!");
return INVALID_RESULT;
}
return VALID_RESULT;
}
std::vector<TaskConfigSection *> *ExecuteConfigSection::GetTasks() {
return &tasks;
}
std::vector<EnsTaskConfigSection *> *ExecuteConfigSection::GetEnsTasks() {
return &ensTasks;
}
| 26.296296 | 79 | 0.685211 | babetoduarte |
99dd784f7e94f145e783decf496e821a74d8fc28 | 3,990 | hpp | C++ | src/solvers/gecode/inspectors/dot.hpp | Patstrom/disUnison | 94731ad37cefa9dc3b6472de3adea8a8d5f0a44b | [
"BSD-3-Clause"
] | 6 | 2018-03-01T19:12:07.000Z | 2018-09-10T15:52:14.000Z | src/solvers/gecode/inspectors/dot.hpp | Patstrom/disUnison | 94731ad37cefa9dc3b6472de3adea8a8d5f0a44b | [
"BSD-3-Clause"
] | 56 | 2018-02-26T16:44:15.000Z | 2019-02-23T17:07:32.000Z | src/solvers/gecode/inspectors/dot.hpp | Patstrom/disUnison | 94731ad37cefa9dc3b6472de3adea8a8d5f0a44b | [
"BSD-3-Clause"
] | null | null | null | /*
* Main authors:
* Roberto Castaneda Lozano <roberto.castaneda@ri.se>
*
* This file is part of Unison, see http://unison-code.github.io
*
* Copyright (c) 2016, RISE SICS AB
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef __DOT__
#define __DOT__
#include <tuple>
#include <vector>
#include <map>
#include <QtGui>
#include <graphviz/gvc.h>
using namespace std;
typedef QString NodeId;
typedef tuple<NodeId, NodeId, int> EdgeId;
EdgeId edgeId(const NodeId& source, const NodeId& target, int instance = 0);
EdgeId edgeId(int source, int target, int instance = 0);
#define POSITION(l) (l->pos)
#define BB(g) (GD_bb(g))
#define NDNAME(n) (agnameof(n))
#define NDCOORD(n) (ND_coord(n))
#define NDHEIGHT(n) (ND_height(n))
#define NDWIDTH(n) (ND_width(n))
#define EDLABEL(e) (ED_label(e))
#define EDTAILNAME(e) (NDNAME(agtail(e)))
#define EDHEADNAME(e) (NDNAME(aghead(e)))
#define EDSPLLIST(e) (ED_spl(e)->list)
class DotNode {
public:
NodeId name;
QPointF topLeftPos;
double width, height;
QRectF rect;
vector<QRectF> rects;
};
class DotEdge {
public:
EdgeId key;
QPointF topLeftPos;
double width, height;
QPainterPath path;
QPainterPath arrow;
};
class Dot {
public:
static const double DPI;
static const double DOT2QT;
Dot();
~Dot();
void setGlobalGraphAttribute(const QString &attr, const QString &val);
void setGlobalNodeAttribute(const QString &attr, const QString &val);
void setGlobalEdgeAttribute(const QString &attr, const QString &val);
void insert(const NodeId& name);
void insert(const EdgeId& key);
void setEdgeAttribute(EdgeId key, const QString &attr, const QString &val);
void setNodeSize(const NodeId &name, double w, double h);
void setNodeAttribute(const NodeId &name,
const QString &attr, const QString &val);
void draw(void);
void dump(FILE * file);
QRectF box() const;
vector<DotNode> getNodes() const;
vector<DotEdge> getEdges() const;
QPainterPath drawArrow(QLineF line) const;
private:
GVC_t * context;
Agraph_t *graph;
map<NodeId, Agnode_t*> nodes;
map<EdgeId, Agedge_t*> edges;
static void gvSet(void *object, QString attr, QString value) {
agsafeset(object, const_cast<char *>(qPrintable(attr)),
const_cast<char *>(qPrintable(value)),
const_cast<char *>(qPrintable(value)));
}
Agnode_t * gvNode(NodeId node) {
return agnode(graph, const_cast<char *>(qPrintable(node)),1);
}
};
#endif
| 31.171875 | 80 | 0.721053 | Patstrom |
99dd8a64c549d0787a2576d47c4af8c629f25be4 | 3,422 | cpp | C++ | concurrencpp/src/threads/thread_group.cpp | HungMingWu/concurrencpp | eb4ed8fb6cd8510925738868cf57bed882005b4b | [
"MIT"
] | null | null | null | concurrencpp/src/threads/thread_group.cpp | HungMingWu/concurrencpp | eb4ed8fb6cd8510925738868cf57bed882005b4b | [
"MIT"
] | null | null | null | concurrencpp/src/threads/thread_group.cpp | HungMingWu/concurrencpp | eb4ed8fb6cd8510925738868cf57bed882005b4b | [
"MIT"
] | null | null | null | #include "thread_group.h"
#include <algorithm>
#include <cassert>
namespace concurrencpp::details {
class thread_group_worker {
private:
task m_task;
std::thread m_thread;
thread_group& m_parent_pool;
typename std::list<thread_group_worker>::iterator m_self_it;
void execute_and_retire();
public:
thread_group_worker(task& function, thread_group& parent_pool) noexcept;
~thread_group_worker() noexcept;
std::thread::id get_id() const noexcept;
std::thread::id start(std::list<thread_group_worker>::iterator self_it);
};
}
using concurrencpp::task;
using concurrencpp::details::thread_group;
using concurrencpp::details::thread_group_worker;
using concurrencpp::details::thread_pool_listener_base;
using listener_ptr = std::shared_ptr<thread_pool_listener_base>;
thread_group_worker::thread_group_worker(task& function, thread_group& parent_pool) noexcept :
m_task(std::move(function)),
m_parent_pool(parent_pool) {}
thread_group_worker::~thread_group_worker() noexcept {
m_thread.join();
}
void thread_group_worker::execute_and_retire() {
m_task();
m_task.clear();
m_parent_pool.retire_worker(m_self_it);
}
std::thread::id thread_group_worker::get_id() const noexcept {
return m_thread.get_id();
}
std::thread::id thread_group_worker::start(std::list<thread_group_worker>::iterator self_it) {
m_self_it = self_it;
m_thread = std::thread([this] { execute_and_retire(); });
return m_thread.get_id();
}
thread_group::thread_group(listener_ptr listener) :
m_listener(std::move(listener)) {}
thread_group::~thread_group() noexcept {
wait_all();
assert(m_workers.empty());
clear_last_retired(std::move(m_last_retired));
}
std::thread::id thread_group::enqueue(task callable) {
std::unique_lock<decltype(m_lock)> lock(m_lock);
auto& new_worker = m_workers.emplace_back(callable, *this);
auto worker_it = std::prev(m_workers.end());
const auto id = new_worker.start(worker_it);
const auto& listener = get_listener();
if (static_cast<bool>(listener)) {
listener->on_thread_created(id);
}
return id;
}
void concurrencpp::details::thread_group::wait_all() {
std::unique_lock<decltype(m_lock)> lock(m_lock);
m_condition.wait(lock, [this] { return m_workers.empty(); });
}
bool concurrencpp::details::thread_group::wait_all(std::chrono::milliseconds ms) {
std::unique_lock<decltype(m_lock)> lock(m_lock);
return m_condition.wait_for(lock, ms, [this] { return m_workers.empty(); });
}
const listener_ptr& thread_group::get_listener() const noexcept {
return m_listener;
}
void thread_group::clear_last_retired(std::list<thread_group_worker> last_retired) {
if (last_retired.empty()) {
return;
}
assert(last_retired.size() == 1);
const auto thread_id = last_retired.front().get_id();
last_retired.clear();
const auto& listener = get_listener();
if (static_cast<bool>(listener)) {
listener->on_thread_destroyed(thread_id);
}
}
void thread_group::retire_worker(std::list<thread_group_worker>::iterator it) {
std::list<thread_group_worker> last_retired;
const auto id = it->get_id();
std::unique_lock<decltype(m_lock)> lock(m_lock);
last_retired = std::move(m_last_retired);
m_last_retired.splice(m_last_retired.begin(), m_workers, it);
lock.unlock();
m_condition.notify_one();
const auto& listener = get_listener();
if (static_cast<bool>(listener)) {
listener->on_thread_idling(id);
}
clear_last_retired(std::move(last_retired));
} | 26.527132 | 94 | 0.753945 | HungMingWu |
99e354a0e578822703b25cedd9a6d9bc2a85e45d | 91,661 | cpp | C++ | src/observer/sql/executor/tuple.cpp | watchpoints/miniob | 3ad8dffc8f55ce66626472763bd13c4ad5205254 | [
"Apache-2.0"
] | null | null | null | src/observer/sql/executor/tuple.cpp | watchpoints/miniob | 3ad8dffc8f55ce66626472763bd13c4ad5205254 | [
"Apache-2.0"
] | null | null | null | src/observer/sql/executor/tuple.cpp | watchpoints/miniob | 3ad8dffc8f55ce66626472763bd13c4ad5205254 | [
"Apache-2.0"
] | null | null | null | /* Copyright (c) 2021 Xie Meiyi(xiemeiyi@hust.edu.cn) and OceanBase and/or its affiliates. All rights reserved.
miniob is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:
http://license.coscl.org.cn/MulanPSL2
THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details. */
//
// Created by Wangyunlai on 2021/5/14.
//
#include "sql/executor/tuple.h"
#include "storage/common/table.h"
#include "common/log/log.h"
#include <stdio.h>
#include <stdlib.h>
#include <algorithm>
Tuple::Tuple(const Tuple &other)
{
LOG_PANIC("Copy constructor of tuple is not supported");
exit(1);
}
Tuple::Tuple(Tuple &&other) noexcept : values_(std::move(other.values_))
{
selectComareIndex = -1;
}
Tuple &Tuple::operator=(Tuple &&other) noexcept
{
if (&other == this)
{
return *this;
}
values_.clear();
values_.swap(other.values_);
return *this;
}
Tuple::~Tuple()
{
}
// add (Value && value)
void Tuple::add(TupleValue *value)
{
values_.emplace_back(value);
}
void Tuple::add(const std::shared_ptr<TupleValue> &other)
{
values_.emplace_back(other);
}
void Tuple::add(int value)
{
add(new IntValue(value, 0));
}
void Tuple::add_null_value()
{
add(new NullValue());
}
void Tuple::add(float value)
{
add(new FloatValue(value, 0));
}
//按照列的名字,添加 values
void Tuple::add(const char *s, int len)
{
add(new StringValue(s, len, 0));
}
void Tuple::add_text(const char *s, int len)
{
add(new TextValue(s, len, 0));
}
void Tuple::add_date(int value)
{
add(new DateValue(value, 0));
}
////////////////////////////////////////////////////////////////////////////////
std::string TupleField::to_string() const
{
return std::string(table_name_) + "." + field_name_ + std::to_string(type_);
}
////////////////////////////////////////////////////////////////////////////////
void TupleSchema::from_table(const Table *table, TupleSchema &schema)
{
const char *table_name = table->name(); //表名字
const TableMeta &table_meta = table->table_meta(); //表结构
const int field_num = table_meta.field_num(); //字段个数
for (int i = 0; i < field_num; i++)
{
const FieldMeta *field_meta = table_meta.field(i);
if (field_meta->visible())
{
schema.add(field_meta->type(), table_name, field_meta->name(), field_meta->nullable());
}
}
}
void TupleSchema::add(AttrType type, const char *table_name, const char *field_name, int nullable)
{
fields_.emplace_back(type, table_name, field_name, nullable);
}
void TupleSchema::add(AttrType type, const char *table_name, const char *field_name)
{
fields_.emplace_back(type, table_name, field_name);
}
void TupleSchema::add(AttrType type, const char *table_name, const char *field_name, bool visible)
{
fields_.emplace_back(type, table_name, field_name, visible);
}
void TupleSchema::add_if_not_exists(AttrType type, const char *table_name, const char *field_name)
{
for (const auto &field : fields_)
{
if (0 == strcmp(field.table_name(), table_name) &&
0 == strcmp(field.field_name(), field_name))
{
LOG_INFO(">>>>>>>>>>add_if_exists. %s.%s", table_name, field_name);
return;
}
}
LOG_INFO("add_if_not_exists. %s.%s", table_name, field_name);
add(type, table_name, field_name);
}
void TupleSchema::add_if_not_exists1(AttrType type, const char *table_name, const char *field_name, int nullable)
{
for (const auto &field : fields_)
{
if (0 == strcmp(field.table_name(), table_name) &&
0 == strcmp(field.field_name(), field_name))
{
LOG_INFO(">>>>>>>>>>add_if_exists. %s.%s", table_name, field_name);
return;
}
}
// LOG_INFO("add_if_not_exists. %s.%s", table_name, field_name);
add(type, table_name, field_name, nullable);
}
void TupleSchema::add_if_not_exists(AttrType type, const char *table_name, const char *field_name, FunctionType ftype)
{
//判断列是否存在
for (const auto &field : fields_)
{
if (0 == strcmp(field.table_name(), table_name) &&
0 == strcmp(field.field_name(), field_name) &&
ftype == field.get_function_type())
{
LOG_INFO(">>>>>>>>>>add_if_exists. %s.%s", table_name, field_name);
return;
}
}
LOG_INFO("add_if_not_exists. %s.%s", table_name, field_name);
add(type, table_name, field_name, ftype);
}
void TupleSchema::append(const TupleSchema &other)
{
fields_.reserve(fields_.size() + other.fields_.size());
for (const auto &field : other.fields_)
{
fields_.emplace_back(field);
}
}
int TupleSchema::index_of_field(const char *table_name, const char *field_name) const
{
const int size = fields_.size();
for (int i = 0; i < size; i++)
{
const TupleField &field = fields_[i];
if (0 == strcmp(field.table_name(), table_name) && 0 == strcmp(field.field_name(), field_name))
{
return i;
}
}
return -1;
}
//列信息: fields_:(type_ = INTS, table_name_ = "t1", field_name_ = "id")
void TupleSchema::print(std::ostream &os) const
{
if (fields_.empty())
{
os << "No schema";
return;
}
// 判断有多张表还是只有一张表
//并不使用 table_names的数据
std::set<std::string> table_names;
for (const auto &field : fields_)
{
table_names.insert(field.table_name());
}
//单表逻辑
if (table_names.size() == 1)
{
//遍历n-1个元素.
for (std::vector<TupleField>::const_iterator iter = fields_.begin(), end = --fields_.end();
iter != end; ++iter)
{
//如果多个表:添加表名t.id
if (table_names.size() > 1 || realTabeNumber > 1)
{
os << iter->table_name() << ".";
}
if (FunctionType::FUN_COUNT_ALL == iter->get_function_type())
{
//count(1)
//if (0 == strcmp("*", iter->field_name()))
//{
//os << "count(*)"
// << " | ";
//}
//else
//{
os << "count(" << iter->field_name_count_number() << ")"
<< " | ";
//}
}
if (FunctionType::FUN_COUNT_ALL_ALl == iter->get_function_type())
{
//count(*)
os << "count(*)"
<< " | ";
}
else if (iter->get_function_type() == FunctionType::FUN_COUNT)
{
os << "count(" << iter->field_name() << ")"
<< " | ";
}
else if (iter->get_function_type() == FunctionType::FUN_MAX)
{
os << "max(" << iter->field_name() << ")"
<< " | ";
}
else if (iter->get_function_type() == FunctionType::FUN_MIN)
{
os << "min(" << iter->field_name() << ")"
<< " | ";
}
else if (iter->get_function_type() == FunctionType::FUN_AVG)
{
os << "avg(" << iter->field_name() << ")"
<< " | ";
}
else
{
//正常情况
os << iter->field_name() << " | ";
}
}
//last col
//visible
if (table_names.size() > 1 || realTabeNumber > 1)
{
os << fields_.back().table_name() << ".";
}
//id ---- 最后一个列,后面没有 |,只有名字
if (FunctionType::FUN_COUNT_ALL_ALl == fields_.back().get_function_type())
{
//count(*)
os << "count(*)" << std::endl;
}
else if (fields_.back().get_function_type() == FunctionType::FUN_COUNT_ALL)
{
//os << "count(*)" << std::endl; //select count(*) from t;
//if (0 == strcmp("*", fields_.back().field_name()))
//{
//os << "count(*)" << std::endl;
//}
//else
//{
os << "count(" << fields_.back().field_name_count_number() << ")" << std::endl;
//}
}
else if (fields_.back().get_function_type() == FunctionType::FUN_COUNT)
{
os << "count(" << fields_.back().field_name() << ")" << std::endl;
}
else if (fields_.back().get_function_type() == FunctionType::FUN_MAX)
{
os << "max(" << fields_.back().field_name() << ")" << std::endl;
}
else if (fields_.back().get_function_type() == FunctionType::FUN_MIN)
{
os << "min(" << fields_.back().field_name() << ")" << std::endl;
}
else if (fields_.back().get_function_type() == FunctionType::FUN_AVG)
{
os << "avg(" << fields_.back().field_name() << ")" << std::endl;
}
//bug1 else if ->if
else
{ //正常情况
os << fields_.back().field_name() << std::endl;
}
//单表 列逻辑 ///////////////////////////////////////// end
}
else
{
//多表逻辑///////////////////////////////////////// 开始
//https://github.com/oceanbase/miniob/blob/main/src/observer/sql/executor/tuple.cpp#123
LOG_INFO(" join query cols >>>>>>>>>>>>>>");
//删除不显示的列
/**
std::vector<TupleField> tuplefields;
for (std::vector<TupleField>::const_iterator iter = fields_.begin(), end =fields_.end();
iter != end; ++iter)
{
tuplefields.push_back(*iter);
}
for (std::vector<TupleField>::iterator iter = tuplefields.begin(), end =tuplefields.end();
iter != end; )
{
if( false ==iter->visible()){
iter = tuplefields.erase(iter);
}else{
iter++;
}
}**/
for (std::vector<TupleField>::const_iterator iter = fields_.begin(), end = --fields_.end();
iter != end; ++iter)
{
if (FunctionType::FUN_COUNT_ALL == iter->get_function_type())
{
//count(1)
os << "count(" << iter->field_name_count_number() << ")"
<< " | ";
}
else if (FunctionType::FUN_COUNT_ALL_ALl == iter->get_function_type())
{
//count(*)
os << "count(*)"
<< " | ";
}
else if (iter->get_function_type() == FunctionType::FUN_COUNT)
{
os << "count(";
if (table_names.size() > 1)
{
os << iter->table_name() << ".";
}
os << iter->field_name() << ")"
<< " | ";
}
else if (iter->get_function_type() == FunctionType::FUN_MAX)
{
os << "max(";
if (table_names.size() > 1)
{
os << iter->table_name() << ".";
}
os << iter->field_name() << ")"
<< " | ";
}
else if (iter->get_function_type() == FunctionType::FUN_MIN)
{
os << "min(";
if (table_names.size() > 1)
{
os << iter->table_name() << ".";
}
os << iter->field_name() << ")"
<< " | ";
}
else if (iter->get_function_type() == FunctionType::FUN_AVG)
{
os << "avg(";
if (table_names.size() > 1)
{
os << iter->table_name() << ".";
}
os << iter->field_name() << ")"
<< " | ";
}
else
{
//正常情况
if (table_names.size() > 1)
{
os << iter->table_name() << ".";
}
os << iter->field_name() << " | ";
}
}
//最后一列:显示
if (FunctionType::FUN_COUNT_ALL == fields_.back().get_function_type())
{
//count(1)
os << "count(" << fields_.back().field_name_count_number() << ")"
<< std::endl;
}
else if (FunctionType::FUN_COUNT_ALL_ALl == fields_.back().get_function_type())
{
//count(*)
os << "count(*)"
<< std::endl;
}
else if (fields_.back().get_function_type() == FunctionType::FUN_COUNT)
{
os << "count(";
if (table_names.size() > 1)
{
os << fields_.back().table_name() << ".";
}
os << fields_.back().field_name() << ")"
<< std::endl;
}
else if (fields_.back().get_function_type() == FunctionType::FUN_MAX)
{
os << "max(";
if (table_names.size() > 1)
{
os << fields_.back().table_name() << ".";
}
os << fields_.back().field_name() << ")"
<< std::endl;
}
else if (fields_.back().get_function_type() == FunctionType::FUN_MIN)
{
os << "min(";
if (table_names.size() > 1)
{
os << fields_.back().table_name() << ".";
}
os << fields_.back().field_name() << ")"
<< std::endl;
}
else if (fields_.back().get_function_type() == FunctionType::FUN_AVG)
{
os << "avg(";
if (table_names.size() > 1)
{
os << fields_.back().table_name() << ".";
}
os << fields_.back().field_name() << ")"
<< std::endl;
}
else
{
//正常情况,普通的字
if (table_names.size() > 1)
{
os << fields_.back().table_name() << ".";
}
os << fields_.back().field_name() << std::endl;
}
///////////////////////////end,多表逻辑////////////////////////////end
}
}
/////////////////////////////////////////////////////////////////////////////
TupleSet::TupleSet(TupleSet &&other) : tuples_(std::move(other.tuples_)), schema_(other.schema_)
{
other.schema_.clear();
realTabeNumber = other.realTabeNumber;
//push_back(std::move(TupleSet))
old_schema = other.old_schema;
commonIndex = other.commonIndex;
select_table_type = other.select_table_type;
dp = other.dp;
}
TupleSet &TupleSet::operator=(TupleSet &&other)
{
if (this == &other)
{
return *this;
}
schema_.clear();
schema_.append(other.schema_);
other.schema_.clear();
realTabeNumber = -1;
tuples_.clear();
//swap 交换
tuples_.swap(other.tuples_);
return *this;
}
void TupleSet::add(Tuple &&tuple)
{
tuples_.emplace_back(std::move(tuple));
}
void TupleSet::clear()
{
tuples_.clear();
schema_.clear();
old_schema.clear();
dp.clear();
}
//print shows
void TupleSet::print(std::ostream &os)
{
//列信息: (type_ = INTS, table_name_ = "t1", field_name_ = "id")
if (schema_.fields().empty())
{
LOG_WARN("Got empty schema");
return;
}
if (realTabeNumber > 1)
{
schema_.realTabeNumber = realTabeNumber;
}
else
{
schema_.realTabeNumber = -1;
}
schema_.print(os); //打印 列字段 (已经考虑到多个表)
// 判断有多张表还是只有一张表
std::set<std::string> table_names;
for (const auto &field : schema_.fields())
{
table_names.insert(field.table_name());
}
//一个表:
if (table_names.size() == 1)
{
//分组 group-by
if (ptr_group_selects && ptr_group_selects->attr_group_num > 0)
{
print_group_by(os);
return;
}
//单表聚合:只有一行
if (true == avg_print(os))
{
LOG_INFO("this is avg query >>>>>>>>>>>>>>>>>> ");
return;
}
//排序 order-by
int order_by_num = -1;
RelAttr *ptr_attr_order_by = nullptr;
if (ptr_group_selects && ptr_group_selects->attr_order_num > 0)
{
order_by_num = ptr_group_selects->attr_order_num;
ptr_attr_order_by = ptr_group_selects->attr_order_by;
}
int group_by_num = -1;
RelAttr *ptr_attr_group_by = nullptr;
if (ptr_group_selects && ptr_group_selects->attr_group_num > 0)
{
group_by_num = ptr_group_selects->attr_group_num;
ptr_attr_group_by = ptr_group_selects->attr_group_by;
}
if (order_by_num > 0)
{
//order by
//std::vector<Tuple> tuples_; //一个表头信息
//TupleSchema schema_; //一个表内容信息
//SELECT * FROM T_ORDER_BY ORDER BY ID, SCORE, NAME;
std::vector<int> order_index;
order_index.clear();
const std::vector<TupleField> &fields = schema_.fields();
int index = 0;
for (std::vector<TupleField>::const_iterator iter = fields.begin(), end = fields.end();
iter != end; ++iter)
{
//SELECT * FROM T_ORDER_BY ORDER BY ID, SCORE, NAME;
for (int cols = 0; cols < order_by_num; cols++)
{
if (0 == strcmp(iter->field_name(), ptr_attr_order_by[cols].attribute_name))
{
order_index.push_back(index);
LOG_INFO("题目:排序 >>>>>> index=%d,cols=%d,name=%s", index, cols, ptr_attr_order_by[cols].attribute_name);
}
}
index++;
}
if (order_by_num != order_index.size())
{
LOG_INFO("排序 order-by 失败 order_by_num != order_index.size()");
return;
}
LOG_INFO("排序 order-by 开始排序 order_index=%d", order_by_num);
auto sortRuleLambda = [=](const Tuple &s1, const Tuple &s2) -> bool {
//std::vector<std::shared_ptr<TupleValue>> values_;
std::vector<std::shared_ptr<TupleValue>> sp1;
std::vector<std::shared_ptr<TupleValue>> sp2;
//根据位置--查找value
for (int i = 0; i < order_index.size(); i++)
{
sp1.push_back(s1.get_pointer(order_index[i]));
sp2.push_back(s2.get_pointer(order_index[i]));
}
//多个字段如何比较呀?
for (int op_index = 0; op_index < order_index.size(); op_index++)
{
int op_comp = 0;
std::shared_ptr<TupleValue> sp_1 = sp1[op_index];
std::shared_ptr<TupleValue> sp_2 = sp2[op_index];
if (sp_1 && sp_2)
{
op_comp = sp_1->compare(*sp_2);
}
//不相等才比较 ,相等下一个
if (op_comp != 0)
{
int index_order = order_index.size() - op_index - 1;
if (CompOp::ORDER_ASC == ptr_attr_order_by[index_order].is_asc)
{
LOG_INFO("排序 order-by ORDER_ASC op_index=%d, order_index=%d,name=%s", op_index, order_by_num, ptr_attr_order_by[index_order].attribute_name);
return op_comp < 0; //true
}
else if (CompOp::ORDER_DESC == ptr_attr_order_by[index_order].is_asc)
{
LOG_INFO("排序 order-by ORDER_DESC op_index=%d,order_index=%d,name=%s", op_index, order_by_num, ptr_attr_order_by[index_order].attribute_name);
return op_comp > 0; //true
}
else
{
LOG_INFO("排序 order-by err err err err order_index=%d,name=%s", order_by_num, ptr_attr_order_by[index_order].attribute_name);
}
}
} ////多个字段如何比较呀?
//为什么std::sort比较函数在参数相等时返回false?
return false;
};
if (tuples_.size() > 0)
{
std::sort(tuples_.begin(), tuples_.end(), sortRuleLambda);
}
}
//rows cols
for (const Tuple &item : tuples_)
{
//第n-1列
const std::vector<std::shared_ptr<TupleValue>> &values = item.values();
for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values.begin(), end = --values.end();
iter != end; ++iter)
{
(*iter)->to_string(os);
os << " | ";
}
//最后一列
values.back()->to_string(os);
os << std::endl;
//1 | 2 | 3
}
}
else if (table_names.size() == 2)
{
////多表操作/////////////////////////////////////
//笛卡尔积算法描述
if (tuples1_.size() == 0 || tuples2_.size() == 0)
{
return;
}
//t1.rows[i][j]
//t2.rows[i][j]
for (const Tuple &item_left : tuples1_)
{
std::shared_ptr<TupleValue> sp1;
int col1 = 0;
std::stringstream os_left;
{
//std::vector<std::shared_ptr<TupleValue>> values_; 每一行 多个字段
const std::vector<std::shared_ptr<TupleValue>> &values = item_left.values();
for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values.begin(), end = values.end();
iter != end; ++iter)
{
if (is_join == true && joins_index == col1)
{
sp1 = *iter;
cout << ">>>>>>>>>>>>>join select " << endl;
}
(*iter)->to_string(os_left);
os_left << " | ";
col1++;
}
}
//b表的多行 tuples_right 多行
for (const Tuple &item_right : tuples2_)
{
std::shared_ptr<TupleValue> sp2;
int col2 = 0;
std::stringstream os_right;
{
const std::vector<std::shared_ptr<TupleValue>> &values = item_right.values();
for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values.begin(), end = --values.end();
iter != end; ++iter)
{
//笛卡尔积:查询条件
if (is_join == true && joins_index == col2)
{
sp2 = *iter;
cout << ">>>>>>>>>>>>>join select " << endl;
}
(*iter)->to_string(os_right);
os_right << " | ";
col2++;
}
//小王疑问:为啥还有最后行 不是上面遍历完毕了吗?
values.back()->to_string(os_right);
os_right << std::endl;
}
//多表:join查询
if (is_join == true)
{
LOG_INFO(" two table join select ");
if (sp1 && sp2 && 0 == sp1->compare(*sp2))
{
os << os_left.str();
os << os_right.str();
}
else
{
LOG_INFO(" not equal ");
}
}
else
{
os << os_left.str();
os << os_right.str();
}
}
}
}
else
{
LOG_INFO(" no support three table query ");
}
}
void TupleSet::set_schema(const TupleSchema &schema)
{
schema_ = schema;
}
const TupleSchema &TupleSet::get_schema() const
{
return schema_;
}
bool TupleSet::is_empty() const
{
return tuples_.empty();
}
int TupleSet::size() const
{
return tuples_.size();
}
const Tuple &TupleSet::get(int index) const
{
return tuples_[index];
}
const std::vector<Tuple> &TupleSet::tuples() const
{
return tuples_;
}
/////////////////////////////////////////////////////////////////////////////
TupleRecordConverter::TupleRecordConverter(Table *table, TupleSet &tuple_set) : table_(table), tuple_set_(tuple_set)
{
}
//record:value 开始地址
//record --->显示
void TupleRecordConverter::add_record(const char *record)
{
const TupleSchema &schema = tuple_set_.schema();
//查询条件的表信息 可能全部列 可能部分
Tuple tuple;
const TableMeta &table_meta = table_->table_meta();
for (const TupleField &field : schema.fields())
{
const FieldMeta *field_meta = table_meta.field(field.field_name());
assert(field_meta != nullptr);
int null_able = field_meta->nullable();
switch (field_meta->type())
{
case INTS:
{
if (null_able == 1)
{
const char *s = record + field_meta->offset();
if (0 == strcmp(s, "999"))
{
tuple.add_null_value();
}
else
{
int value = *(int *)(record + field_meta->offset());
//LOG_INFO(" tuple add int =%d ", value);
tuple.add(value);
}
}
else
{
int value = *(int *)(record + field_meta->offset());
// LOG_INFO(" tuple add int =%d ", value);
tuple.add(value);
}
}
break;
case FLOATS:
{
if (null_able == 1)
{
//memset 改为
const char *s = record + field_meta->offset();
if (0 == strcmp(s, "999"))
{
//LOG_INFO("99999 FLOATS");
tuple.add_null_value();
}
else
{
float value = *(float *)(record + field_meta->offset());
//LOG_INFO(" tuple add float =%d ", value);
tuple.add(value);
}
}
else
{
float value = *(float *)(record + field_meta->offset());
LOG_INFO(" tuple add float =%d ", value);
tuple.add(value);
}
}
break;
case CHARS:
{
if (null_able == 1)
{
//memset 改为
const char *s = record + field_meta->offset();
if (0 == strcmp(s, "999"))
{
//LOG_INFO("99999 FLOATS");
tuple.add_null_value();
}
else
{
const char *s = record + field_meta->offset(); // 现在当做Cstring来处理
// LOG_INFO(" tuple add string =%s ", s);
tuple.add(s, strlen(s));
}
}
else
{
const char *s = record + field_meta->offset(); // 现在当做Cstring来处理
LOG_INFO(" tuple add string =%s ", s);
tuple.add(s, strlen(s));
}
}
break;
case DATES:
{
if (null_able == 1)
{
//memset memcpy
const char *s = record + field_meta->offset();
if (0 == strcmp(s, "999"))
{
// LOG_INFO("99999 FLOATS");
tuple.add_null_value();
}
else
{
int value = *(int *)(record + field_meta->offset());
// LOG_INFO(" tuple.add_date=%d ", value);
tuple.add_date(value);
}
}
else
{
int value = *(int *)(record + field_meta->offset());
// LOG_INFO(" tuple.add_date=%d ", value);
tuple.add_date(value);
}
}
break;
case TEXTS:
{
if (null_able == 1)
{
//memset 改为
const char *s = record + field_meta->offset();
if (0 == strcmp(s, "999"))
{
//LOG_INFO("99999 FLOATS");
tuple.add_null_value();
}
else
{
const char *s = record + field_meta->offset(); // 现在当做Cstring来处理
// LOG_INFO(" tuple add string =%s ", s);
int key = *(int *)s;
if (table()->pTextMap.count(key) == 1)
{
s = table()->pTextMap[key];
LOG_INFO(" 题目 超长文本 >>>>>>>>>>>> key=%d,value=%s ", key, s);
}
else
{
LOG_INFO(" 题目 超长文本 失败 失败 失败 失败 =%s ", s);
}
tuple.add_text(s, strlen(s));
}
}
else
{
const char *s = record + field_meta->offset(); // 现在当做Cstring来处理
int key = *(int *)s;
if (table()->pTextMap.count(key) == 1)
{
s = table()->pTextMap[key];
LOG_INFO(" 题目 超长文本 >>>>>>>>>>>> key=%d,value=%s ", key, s);
}
else
{
LOG_INFO(" 题目 超长文本 失败 失败 失败 失败 key=%d,value=%s ", key, s);
}
tuple.add(s, strlen(s));
}
}
break;
default:
{
LOG_PANIC("Unsupported field type. type=%d", field_meta->type());
}
}
}
tuple_set_.add(std::move(tuple));
}
//聚合
void TupleSchema::from_table_first(const Table *table, TupleSchema &schema, FunctionType functiontype)
{
const char *table_name = table->name(); //表名字
const TableMeta &table_meta = table->table_meta(); //表结构
//const int field_num = table_meta.field_num(); //字段个数
const FieldMeta *field_meta = table_meta.field(1);
if (field_meta && field_meta->visible())
{
schema.add(field_meta->type(), table_name, field_meta->name(), functiontype, field_meta->nullable());
}
}
void TupleSchema::add(AttrType type, const char *table_name, const char *field_name, FunctionType functiontype)
{
fields_.emplace_back(type, table_name, field_name, functiontype);
}
void TupleSchema::add(AttrType type, const char *table_name, const char *field_name, FunctionType functiontype, int nullable)
{
fields_.emplace_back(type, table_name, field_name, functiontype, nullable);
}
bool TupleSet::avg_print(std::ostream &os) const
{
//步骤
//1. 遍历 属性
//2. 根据不同属性函数,做不同的计算.
//3. 返回是存在聚合
bool isWindows = false;
const std::vector<TupleField> &fields = schema_.fields();
int count = fields.size();
int index = 0;
//遍历n个元素.
for (std::vector<TupleField>::const_iterator iter = fields.begin(), end = fields.end();
iter != end; ++iter)
{
FunctionType window_function = iter->get_function_type();
if (FunctionType::FUN_COUNT_ALL_ALl == window_function || FunctionType::FUN_COUNT_ALL == window_function || FunctionType::FUN_COUNT == window_function)
{
isWindows = true;
int count = 0;
//count(*)
if (FunctionType::FUN_COUNT_ALL_ALl == window_function || FunctionType::FUN_COUNT_ALL == window_function)
{
count = tuples_.size();
}
else
{
//rows count(id)
//字段值是NULL时,比较特殊,不需要统计在内。如果是AVG,不会增加统计行数,也不需要默认值。
for (const Tuple &item : tuples_)
{
int colIndex = 0;
bool null_able = true;
//cols
const std::vector<std::shared_ptr<TupleValue>> &values = item.values();
for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values.begin(), end = values.end();
iter != end; ++iter)
{
if (colIndex == index)
{
std::shared_ptr<TupleValue> temp = *iter;
if (AttrType::NULLVALUES == temp->get_type())
{
null_able = false;
}
break;
}
colIndex++;
}
if (true == null_able)
{
count++;
}
}
} //end else
os << count;
}
else if (FunctionType::FUN_MAX == window_function)
{
//属性值类型 typedef enum { UNDEFINED, CHARS, INTS, FLOATS,DATES } AttrType;
isWindows = true;
std::shared_ptr<TupleValue> maxValue;
if (0 == tuples_.size())
{
return true;
}
for (const Tuple &item : tuples_)
{
int colIndex = 0;
//第n-1列
const std::vector<std::shared_ptr<TupleValue>> &values = item.values();
if (0 == values.size())
{
continue;
}
for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values.begin(), end = values.end();
iter != end; ++iter)
{
//(*iter)->to_string(os);
if (colIndex == index)
{
std::shared_ptr<TupleValue> temp = *iter;
//if (AttrType::NULLVALUES == temp->get_type())
//{
//不处理
//}
//else
{
if (nullptr == maxValue)
{
maxValue = temp;
}
else
{
if (maxValue->compare(*temp) < 0)
{
maxValue = temp;
}
}
}
break; //get
}
colIndex++;
}
} //end
maxValue->to_string(os);
}
else if (FunctionType::FUN_MIN == window_function)
{
//属性值类型 typedef enum { UNDEFINED, CHARS, INTS, FLOATS,DATES } AttrType;
isWindows = true;
std::shared_ptr<TupleValue> minValue;
if (0 == tuples_.size())
{
return true;
}
for (const Tuple &item : tuples_)
{
int colIndex = 0;
//列
const std::vector<std::shared_ptr<TupleValue>> &values = item.values();
if (0 == values.size())
{
continue;
}
for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values.begin(), end = values.end();
iter != end; ++iter)
{
//(*iter)->to_string(os);
if (colIndex == index)
{
std::shared_ptr<TupleValue> temp = *iter;
//if (AttrType::NULLVALUES == temp->get_type())
//{
//不处理
//}
//else
{
if (nullptr == minValue)
{
minValue = *iter;
}
else
{
std::shared_ptr<TupleValue> temp = *iter;
if (minValue->compare(*temp) > 0)
{
minValue = temp;
}
}
}
break; //get
}
colIndex++;
}
} //end
minValue->to_string(os);
}
else if (FunctionType::FUN_AVG == window_function)
{
//属性值类型 typedef enum { UNDEFINED, CHARS, INTS, FLOATS,DATES } AttrType;
isWindows = true;
std::shared_ptr<TupleValue> sumValue;
int count = 0;
bool exits_null_value = false;
if (0 == tuples_.size())
{
return true;
}
for (const Tuple &item : tuples_)
{
int colIndex = 0;
bool null_able = true;
//第n列
const std::vector<std::shared_ptr<TupleValue>> &values = item.values();
if (0 == values.size())
{
continue;
}
for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values.begin(), end = values.end();
iter != end; ++iter)
{
//(*iter)->to_string(os);
if (colIndex == index)
{
std::shared_ptr<TupleValue> temp = *iter;
if (AttrType::NULLVALUES == temp->get_type())
{
//不处理
null_able = false;
exits_null_value = true;
}
else
{
if (nullptr == sumValue)
{
sumValue = temp;
}
else
{
sumValue->add_value(*temp);
}
}
break; //get
}
colIndex++;
}
if (true == null_able)
{
count++;
}
} //end
//防溢出求平均算法
if (0 == count)
{
if (exits_null_value == true)
{
os << "NULL";
os << std::endl;
}
return true; //是聚合运算
}
sumValue->to_avg(count, os);
}
//聚合函数显示
if (FunctionType::FUN_AVG == window_function ||
FunctionType::FUN_COUNT == window_function ||
FunctionType::FUN_COUNT_ALL == window_function ||
FunctionType::FUN_COUNT_ALL_ALl == window_function ||
FunctionType::FUN_MIN == window_function ||
FunctionType::FUN_MAX == window_function)
{
if (index == count - 1)
{
//os << result.c_str();
os << std::endl;
}
else
{
//os << result.c_str();
os << " | ";
}
}
index++;
} //const std::vector<TupleField> &fields = schema_.fields();
return isWindows;
}
void TupleSchema::add_if_not_exists_visible(AttrType type, const char *table_name, const char *field_name, bool visible)
{
for (const auto &field : fields_)
{
if (0 == strcmp(field.table_name(), table_name) &&
0 == strcmp(field.field_name(), field_name))
{
LOG_INFO(">>>>>>>>>>add_if_exists. %s.%s", table_name, field_name);
return;
}
}
add(type, table_name, field_name, visible);
}
//2个表的join操作
void TupleSet::print_two(std::ostream &os)
{
//列信息: (type_ = INTS, table_name_ = "t1", field_name_ = "id")
if (schema_.fields().empty())
{
LOG_WARN("Got empty schema");
return;
}
if (old_schema.get_size() > 0)
{
old_schema.realTabeNumber = 2;
//修改old_schema成员变量, 去掉const函数
old_schema.print(os);
// 原始查询条件
//select t2.age from t1 ,t2 where t1.age=21;
}
else
{
schema_.print(os); //打印 列字段 (已经考虑到多个表)
}
// 判断有多张表还是只有一张表
std::set<std::string> table_names;
for (const auto &field : schema_.fields())
{
table_names.insert(field.table_name());
}
if (2 != table_names.size())
{
return;
}
////多表操作/////////////////////////////////////
//笛卡尔积算法描述
if (tuples1_.size() == 0 || tuples2_.size() == 0)
{
return;
}
//select t1.age,t2.age from t1 ,t2 where t1.id =t2.id;
//[id(隐藏),age] [age,id(隐藏))
std::map<int, bool> leftVisibleMap;
leftVisibleMap.clear();
int index1 = 0;
int count1 = schema1_.get_size() - 1;
for (const auto &field : schema1_.fields())
{
if (false == field.visible())
{
if (index1 == count1)
{
leftVisibleMap[index1] = true; //最后一个字段
}
else
{
leftVisibleMap[index1] = false;
}
}
index1++;
}
std::map<int, bool> rightVisibleMap;
rightVisibleMap.clear();
int index2 = 0;
int count2 = schema2_.get_size() - 1;
for (const auto &field : schema2_.fields())
{
if (false == field.visible())
{
if (index2 == count2)
{
rightVisibleMap[index2] = true;
}
else
{
rightVisibleMap[index2] = false;
}
}
index2++;
}
order_by_two();
//t1.rows[i][j]
//t2.rows[i][j]
//item_left 一行记录
//第一个表内容
for (const Tuple &item_left : tuples1_)
{
std::shared_ptr<TupleValue> sp1;
vector<std::shared_ptr<TupleValue>> left(dp.size());
//多个过滤条件
//几个过滤条件
//select t1.age,t1.id ,t2.id,t2.age from t1,t2 where t1.id=t2.id and t1.age =t2.age;
int col1 = 0;
std::stringstream os_left; //第一个表的 全部行
std::stringstream os_left1;
std::stringstream os_left2;
{
//std::vector<std::shared_ptr<TupleValue>> values_; 每一行 多个字段
const std::vector<std::shared_ptr<TupleValue>> &values = item_left.values();
for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values.begin(), end = values.end();
iter != end; ++iter)
{
if (is_join == true && joins_index == col1)
{
sp1 = *iter;
cout << ">>>>>>>>>>>>>join select " << endl;
}
if (is_join == true)
{
for (int i = 0; i < dp.size(); i++)
{
if (col1 == dp[i][0].m_index)
{
left[i] = *iter;
cout << "left " << col1 << endl;
}
}
}
//一个表:是否隐藏
if (leftVisibleMap.size() > 0 && leftVisibleMap.count(col1) == 1)
{
}
else
{
if (b_not_know == true && col1 == 1)
{
(*iter)->to_string(os_left1);
LOG_INFO("11111111111111111 left=");
}
else
{
(*iter)->to_string(os_left);
os_left << " | ";
}
}
col1++;
}
}
//b表的多行 tuples_right 多行
//第2个表内容
for (const Tuple &item_right : tuples2_)
{
std::shared_ptr<TupleValue> sp2;
vector<std::shared_ptr<TupleValue>> right(dp.size());
right.clear();
int col2 = 0;
std::stringstream os_right; //第二个表:一行记录
{
const std::vector<std::shared_ptr<TupleValue>> &values = item_right.values();
for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values.begin(), end = values.end();
iter != end; ++iter)
{
//笛卡尔积:查询条件
if (is_join == true && joins_index == col2)
{
sp2 = *iter;
}
if (is_join == true)
{
for (int ri = 0; ri < dp.size(); ri++)
{
if (col2 == dp[ri][1].m_index)
{
right[ri] = *iter;
cout << "right " << col2 << endl;
}
}
}
//判断是否最后一行
if (col2 == values.size() - 1)
{
//一个表:是否隐藏
if (rightVisibleMap.size() > 0 && rightVisibleMap.count(col2) == 1)
{
//隐藏 什么都不操作
}
else
{
if (b_not_know == true)
{
(*iter)->to_string(os_right);
os_right << " | ";
os_right << os_left1.str();
os_right << std::endl;
}
else
{
(*iter)->to_string(os_right);
os_right << std::endl;
}
}
}
else
{
if (rightVisibleMap.size() > 0 && rightVisibleMap.count(col2) == 1)
{
//隐藏 什么都不操作
}
else if (rightVisibleMap.size() > 0 && rightVisibleMap.count(col2) == 0)
{
//自己不隐藏,下一行隐藏,下一行是最后一行
////age(当前),id(隐藏)
int next = col2 + 1;
if (rightVisibleMap.count(next) == 1 && true == rightVisibleMap[next])
{
(*iter)->to_string(os_right);
os_right << std::endl;
}
}
else
{
(*iter)->to_string(os_right);
os_right << " | ";
}
}
col2++;
}
}
//多表:有join条件
if (is_join == true)
{
LOG_INFO(" two table join select ");
bool b_equal = false; //符合条件
//join条件全部相等
for (int i = 0; i < dp.size(); i++)
{
CompOp two_comp = dp[i][0].comp;
std::stringstream s1;
std::stringstream s2;
left[i]->to_string(s1);
right[i]->to_string(s2);
std::cout << " >>>>>>> left:" << s1.str() << "right:" << s2.str() << std::endl;
//"=="
if (two_comp == EQUAL_TO)
{
if (left[i] && right[i] && 0 == left[i]->compare(*right[i]))
{
b_equal = true;
}
}
else if (two_comp == GREAT_EQUAL)
{
// ">=" t1.id >=t2.id
if (left[i] && right[i] && left[i]->compare(*right[i]) >= 0)
{
b_equal = true;
}
}
else if (two_comp == GREAT_THAN)
{
// ">"
if (left[i] && right[i] && left[i]->compare(*right[i]) > 0)
{
b_equal = true;
}
}
else if (two_comp == LESS_EQUAL)
{
// "<="
if (left[i] && right[i] && left[i]->compare(*right[i]) <= 0)
{
b_equal = true;
}
}
else if (two_comp == LESS_THAN)
{
// "<"
if (left[i] && right[i] && left[i]->compare(*right[i]) < 0)
{
b_equal = true;
}
}
}
if (true == b_equal)
{
//sql: 1笛卡尔积 2 排序 3 分组 4 输出
//题目:order_by
if (ptr_group_selects && ptr_group_selects->attr_order_num > 0)
{
join_table_for_order_by(item_left, item_right);
}
else if (ptr_group_selects && ptr_group_selects->attr_group_num > 0)
{
join_table_for_group_by(item_left, item_right);
//这里不输出,哪里输出呀
}
else
{
os << os_left.str();
os << os_right.str();
}
}
}
else
{ //没有join条件
os << os_left.str();
os << os_right.str();
}
}
}
//题目:order_by
if (ptr_group_selects && ptr_group_selects->attr_order_num > 0)
{
sort_table_for_order_by();
std::stringstream ss;
join_tuples_to_print(ss);
os << ss.str();
}
else if (ptr_group_selects && ptr_group_selects->attr_group_num > 0)
{
//步骤:排序 分组 统计
//2个表合成一个表了.
print_two_table_group_by(os);
}
}
//聚合
void TupleSchema::from_table_first_count_number(const Table *table, TupleSchema &schema, FunctionType functiontype, const char *field_name_count_number)
{
const char *table_name = table->name(); //表名字
const TableMeta &table_meta = table->table_meta(); //表结构
//const int field_num = table_meta.field_num(); //字段个数
const FieldMeta *field_meta = table_meta.field(1);
if (field_meta && field_meta->visible())
{
// schema.add(field_meta->type(), table_name, field_meta->name(), functiontype);
schema.add_number(field_meta->type(), table_name, field_meta->name(), functiontype, field_name_count_number, field_meta->nullable());
}
}
void TupleSchema::add_number(AttrType type, const char *table_name, const char *field_name, FunctionType functiontype, const char *field_name_count_number, int nullable)
{
TupleField temp(type, table_name, field_name, functiontype);
temp.field_name_count_number_ = field_name_count_number;
fields_.push_back(temp);
//fields_.emplace_back(std::move(temp));
//fields_.emplace_back(type, table_name, field_name, functiontype);
}
//至少3个表
void TupleSet::print_multi_table(std::ostream &os)
{
if (schema_.fields().empty())
{
LOG_WARN(" print_multi_table Got empty schema");
return;
}
schema_.print(os); // 如果显示列有问题 请在看这里 多个表合并一个表
// 判断有多张表还是只有一张表
std::set<std::string> table_names;
for (const auto &field : schema_.fields())
{
table_names.insert(field.table_name());
}
if (3 != table_names.size())
{
return;
}
////多表操作/////////////////////////////////////
//笛卡尔积算法描述
if (tuples1_.size() == 0 || tuples2_.size() == 0 || tuples3_.size() == 0)
{
return;
}
//三次循环
for (Tuple &item_1 : tuples1_)
{
std::stringstream os_tuples_1; //node1
os_tuples_1.clear();
// std::shared_ptr<TupleValue> sp1;
item_1.sp1.reset();
item_1.selectComareIndex = commonIndex; //比较字段位置
item_1.head_table_row_string(os_tuples_1, 1);
for (Tuple &item_2 : tuples2_)
{
std::stringstream os_tuples_2; //node2
os_tuples_2.clear();
item_2.sp2.reset();
item_2.selectComareIndex = commonIndex; //比较字段位置
item_2.head_table_row_string(os_tuples_2, 2);
std::stringstream os_tuples_1_2;
os_tuples_1_2.clear();
if (select_table_type == 2)
{
LOG_WARN(" >>>>>>>>>>>>>>>>>> select_table_type =2");
if (item_1.sp1 && item_2.sp2 && 0 == item_1.sp1->compare(*item_2.sp2))
{
os_tuples_1_2 << os_tuples_1.str();
os_tuples_1_2 << os_tuples_2.str();
LOG_WARN(" >>>>>>>>>>>>>>>>>> 相等 select_table_type =2");
}
else
{
LOG_WARN(" >>>>>>>>>>>>>>>>>> 不相等 select_table_type =2");
}
}
else
{
os_tuples_1_2 << os_tuples_1.str();
os_tuples_1_2 << os_tuples_2.str();
}
for (Tuple &item_3 : tuples3_)
{
std::stringstream os_tuples_3; //node3
os_tuples_3.clear();
item_3.sp3.reset();
item_3.selectComareIndex = commonIndex; //比较字段位置
item_3.tail_table_row_string(os_tuples_3, 3);
//多表:有join条件
//select * from t1,t2,t3;
if (false == is_join)
{
//没有join条件
os << os_tuples_1_2.str();
os << os_tuples_3.str();
}
else
{
//select_table_type
//0 查询无过滤条件
//1 三表完全过滤
//2表过滤 //a ok b ok c (no)
//3 //a (no) b ok c ok
////a (no) b ok c ok
if (select_table_type == 1)
{
bool b_equal = true;
if (item_1.sp1 && item_2.sp2 && 0 == item_1.sp1->compare(*item_2.sp2))
{
}
else
{
b_equal = false;
}
if (item_1.sp1 && item_3.sp3 && 0 == item_1.sp1->compare(*item_3.sp3))
{
}
else
{
b_equal = false;
}
if (true == b_equal)
{
os << os_tuples_1_2.str();
os << os_tuples_3.str();
}
//end if 1
}
else if (select_table_type == 2)
{
//2表过滤 //a ok b ok c (no)
//组合完毕---过滤
bool b_equal = true;
if (item_1.sp1 && item_2.sp2 && 0 == item_1.sp1->compare(*item_2.sp2))
{
}
else
{
b_equal = false;
}
if (true == b_equal)
{
os << os_tuples_1_2.str();
os << os_tuples_3.str();
}
} //end select_table_type == 2
else if (select_table_type == 3)
{
//3 //a (no) b ok c ok
bool b_equal = true;
//组合完毕---过滤
if (item_2.sp2 && item_3.sp3 && 0 == item_2.sp2->compare(*item_3.sp3))
{
}
else
{
b_equal = false;
}
if (true == b_equal)
{
os << os_tuples_1_2.str();
os << os_tuples_3.str();
}
////end select_table_type == 3
}
else if (4 == select_table_type)
{
//a (ok) b (no) c ok
//组合完毕---过滤
bool b_equal = true;
if (item_1.sp1 && item_3.sp3 && 0 == item_1.sp1->compare(*item_3.sp3))
{
}
else
{
b_equal = false;
}
if (true == b_equal)
{
os << os_tuples_1_2.str();
os << os_tuples_3.str();
}
}
} //end else
}
}
}
}
void Tuple::head_table_row_string(std::ostream &os)
{
const std::vector<std::shared_ptr<TupleValue>> &values = this->values();
//int cols =0;
for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values.begin(), end = values.end();
iter != end; ++iter)
{
(*iter)->to_string(os);
os << " | ";
//if(cols ==selectComareIndex)
//{
// sp1 = *iter;
//}
//cols++;
}
}
void Tuple::tail_table_row_string(std::ostream &os)
{
size_t col2 = 0;
const std::vector<std::shared_ptr<TupleValue>> &values = this->values();
for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values.begin(), end = values.end();
iter != end; ++iter)
{
//判断是否最后一行
if (col2 == values.size() - 1)
{
(*iter)->to_string(os);
os << std::endl;
}
else
{
(*iter)->to_string(os);
os << " | ";
}
col2++;
}
}
void Tuple::head_table_row_string(std::ostream &os, int type)
{
const std::vector<std::shared_ptr<TupleValue>> &values = this->values();
int cols = 0;
for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values.begin(), end = values.end();
iter != end; ++iter)
{
(*iter)->to_string(os);
os << " | ";
//如果多个查询条件,考虑 需要更多考虑
if (cols == selectComareIndex)
{
if (1 == type)
{
sp1 = *iter;
}
else if (2 == type)
{
sp2 = *iter;
}
else if (3 == type)
{
sp3 = *iter;
}
}
cols++;
}
}
void Tuple::tail_table_row_string(std::ostream &os, int type)
{
size_t col2 = 0;
const std::vector<std::shared_ptr<TupleValue>> &values = this->values();
for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values.begin(), end = values.end();
iter != end; ++iter)
{
//判断是否最后一行
if (col2 == values.size() - 1)
{
(*iter)->to_string(os);
os << std::endl;
}
else
{
(*iter)->to_string(os);
os << " | ";
}
//如果多个查询条件,考虑 需要更多考虑
if (col2 == selectComareIndex)
{
if (1 == type)
{
sp1 = *iter;
}
else if (2 == type)
{
sp2 = *iter;
}
else if (3 == type)
{
sp3 = *iter;
}
}
col2++;
}
}
void TupleSet::order_by_two()
{
if (nullptr == ptr_group_selects || ptr_group_selects->attr_order_num < 0)
{
LOG_INFO("不需要 order by");
return;
}
//步骤01 每个表分开计算
std::vector<RelAttr> attr_order_by1;
std::vector<RelAttr> attr_order_by2;
for (int i = ptr_group_selects->attr_order_num - 1; i >= 0; i--)
{
const std::vector<TupleField> &fields = schema1_.fields();
for (std::vector<TupleField>::const_iterator iter = fields.begin(), end = fields.end();
iter != end; ++iter)
{
if (0 == strcmp(iter->field_name(), ptr_group_selects->attr_order_by[i].attribute_name) &&
0 == strcmp(iter->table_name(), ptr_group_selects->attr_order_by[i].relation_name))
{
attr_order_by1.push_back(ptr_group_selects->attr_order_by[i]);
}
}
}
for (int i = ptr_group_selects->attr_order_num - 1; i >= 0; i--)
{
const std::vector<TupleField> &fields2 = schema2_.fields();
for (std::vector<TupleField>::const_iterator iter2 = fields2.begin(), end = fields2.end();
iter2 != end; ++iter2)
{
if (0 == strcmp(iter2->field_name(), ptr_group_selects->attr_order_by[i].attribute_name) &&
0 == strcmp(iter2->table_name(), ptr_group_selects->attr_order_by[i].relation_name))
{
attr_order_by2.push_back(ptr_group_selects->attr_order_by[i]);
}
}
}
if (attr_order_by1.size() == 0 && attr_order_by2.size() == 0)
{
LOG_INFO(" 失败 ");
return;
}
//步骤2:统计排序关键字 在rows中的位置
std::vector<int> order_index1;
order_index1.clear();
std::vector<int> order_index2;
order_index2.clear();
std::map<int, int> value_key1; //index-key
std::map<int, int> value_key2; //index-key
//key --->index
for (int cols = 0; cols < attr_order_by1.size(); cols++)
{
const std::vector<TupleField> &fields = schema1_.fields();
int index1 = 0;
for (std::vector<TupleField>::const_iterator iter = fields.begin(), end = fields.end();
iter != end; ++iter)
{
if (0 == strcmp(iter->field_name(), attr_order_by1[cols].attribute_name))
{
order_index1.push_back(index1);
value_key1[index1] = cols;
LOG_INFO("题目:排序 >>>>>> cols=%d,index1=%d,name=%s", cols, index1, attr_order_by1[cols].attribute_name);
}
index1++;
}
}
//key --->index
for (int cols = 0; cols < attr_order_by2.size(); cols++)
{
const std::vector<TupleField> &fields = schema2_.fields();
int index2 = 0;
for (std::vector<TupleField>::const_iterator iter = fields.begin(), end = fields.end();
iter != end; ++iter)
{
if (0 == strcmp(iter->field_name(), attr_order_by2[cols].attribute_name))
{
order_index2.push_back(index2);
value_key2[index2] = cols;
LOG_INFO("题目:排序 >>>>>> cols=%d,index2=%d,name=%s", cols, index2, attr_order_by2[cols].attribute_name);
}
index2++;
}
}
//03 开始排序
if (order_index1.size() > 0)
{
LOG_INFO("排序 order-by1 开始排序 order_index=%d", order_index1.size());
auto sortRuleLambda1 = [=](const Tuple &s1, const Tuple &s2) -> bool {
//std::vector<std::shared_ptr<TupleValue>> values_;
std::vector<std::shared_ptr<TupleValue>> sp1;
std::vector<std::shared_ptr<TupleValue>> sp2;
//根据位置--查找value
for (int i = 0; i < order_index1.size(); i++)
{
sp1.push_back(s1.get_pointer(order_index1[i]));
sp2.push_back(s2.get_pointer(order_index1[i]));
}
//多个字段如何比较呀?
for (int op_index = 0; op_index < order_index1.size(); op_index++)
{
int op_comp = 0;
std::shared_ptr<TupleValue> sp_1 = sp1[op_index];
std::shared_ptr<TupleValue> sp_2 = sp2[op_index];
if (sp_1 && sp_2)
{
op_comp = sp_1->compare(*sp_2);
}
//不相等才比较 ,相等下一个
if (op_comp != 0)
{
int index_order = value_key1.at(order_index1[op_index]);
if (CompOp::ORDER_ASC == attr_order_by1[index_order].is_asc)
{
LOG_INFO("排序 order-by ORDER_ASC op_index=%d, order_index=%d,name=%s", op_index, order_index1.size(), attr_order_by1[index_order].attribute_name);
return op_comp < 0; //true
}
else if (CompOp::ORDER_DESC == attr_order_by1[index_order].is_asc)
{
LOG_INFO("排序 order-by ORDER_DESC op_index=%d, order_index=%d,name=%s", op_index, order_index1.size(), attr_order_by1[index_order].attribute_name);
return op_comp > 0; //true
}
else
{
LOG_INFO("排序 order-by err order op_index=%d, order_index=%d,name=%s", op_index, order_index1.size(), attr_order_by1[index_order].attribute_name);
}
}
} ////多个字段如何比较呀?
//为什么std::sort比较函数在参数相等时返回false?
return false;
};
if (tuples1_.size() > 0)
{
std::sort(tuples1_.begin(), tuples1_.end(), sortRuleLambda1);
}
}
//03 开始排序
if (order_index2.size() > 0)
{
LOG_INFO("排序 order-by2 开始排序 order_index=%d", order_index2.size());
auto sortRuleLambda2 = [=](const Tuple &s1, const Tuple &s2) -> bool {
//std::vector<std::shared_ptr<TupleValue>> values_;
std::vector<std::shared_ptr<TupleValue>> sp1;
std::vector<std::shared_ptr<TupleValue>> sp2;
//根据位置--查找value
for (int i = 0; i < order_index2.size(); i++)
{
sp1.push_back(s1.get_pointer(order_index2[i]));
sp2.push_back(s2.get_pointer(order_index2[i]));
}
//多个字段如何比较呀?
for (int op_index = 0; op_index < order_index2.size(); op_index++)
{
int op_comp = 0;
std::shared_ptr<TupleValue> sp_1 = sp1[op_index];
std::shared_ptr<TupleValue> sp_2 = sp2[op_index];
if (sp_1 && sp_2)
{
op_comp = sp_1->compare(*sp_2);
}
//不相等才比较 ,相等下一个
if (op_comp != 0)
{
//int index_order = order_index2.size() - op_index - 1;
int index_order = value_key2.at(order_index2[op_index]);
if (CompOp::ORDER_ASC == attr_order_by2[index_order].is_asc)
{
LOG_INFO("排序 order-by ORDER_ASC op_index=%d, order_index=%d,name=%s", op_index, order_index2.size(), attr_order_by2[index_order].attribute_name);
return op_comp < 0; //true
}
else if (CompOp::ORDER_DESC == attr_order_by2[index_order].is_asc)
{
LOG_INFO("排序 order-by ORDER_DESC op_index=%d, order_index=%d,name=%s", op_index, order_index2.size(), attr_order_by2[index_order].attribute_name);
return op_comp > 0; //true
}
else
{
LOG_INFO("排序 order-by err order op_index=%d, order_index=%d,name=%s", op_index, order_index2.size(), attr_order_by2[index_order].attribute_name);
}
}
} ////多个字段如何比较呀?
//为什么std::sort比较函数在参数相等时返回false?
return false;
};
if (tuples2_.size() > 0)
{
std::sort(tuples2_.begin(), tuples2_.end(), sortRuleLambda2);
}
}
}
void TupleSet::join_table_for_order_by(const Tuple &item_left, const Tuple &item_right)
{
Tuple merge;
const std::vector<std::shared_ptr<TupleValue>> &values_left = item_left.values();
for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values_left.begin(), end = values_left.end();
iter != end; ++iter)
{
merge.add(*iter);
}
const std::vector<std::shared_ptr<TupleValue>> &values_right = item_right.values();
for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values_right.begin(), end = values_right.end();
iter != end; ++iter)
{
merge.add(*iter);
}
join_tuples.push_back(std::move(merge));
}
void TupleSet::join_table_for_group_by(const Tuple &item_left, const Tuple &item_right)
{
//对Tuple深度拷贝,不能=
Tuple merge;
const std::vector<std::shared_ptr<TupleValue>> &values_left = item_left.values();
for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values_left.begin(), end = values_left.end();
iter != end; ++iter)
{
merge.add(*iter);
}
const std::vector<std::shared_ptr<TupleValue>> &values_right = item_right.values();
for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values_right.begin(), end = values_right.end();
iter != end; ++iter)
{
merge.add(*iter);
}
join_tuples_group.push_back(std::move(merge));
}
void TupleSet::sort_table_for_order_by()
{
//依赖数据结构:
//std::vector<Tuple> join_tuples; 数据
// Selects* ptr_group_selects =nullptr; 排序条件
// TupleSchema schema_; 有可能是old
//if (old_schema.get_size() > 0)
//排序 order-by
int order_by_num = -1;
RelAttr *ptr_attr_order_by = nullptr;
if (ptr_group_selects && ptr_group_selects->attr_order_num > 0)
{
order_by_num = ptr_group_selects->attr_order_num;
ptr_attr_order_by = ptr_group_selects->attr_order_by;
}
if (order_by_num > 0)
{
//order by
//std::vector<Tuple> tuples_; //一个表头信息
//TupleSchema schema_; //一个表内容信息
//SELECT * FROM T_ORDER_BY ORDER BY ID, SCORE, NAME;
//key ---index
//index ---key
std::vector<int> key_value;
std::map<int, int> value_key;
key_value.clear();
value_key.clear();
for (int i = ptr_group_selects->attr_order_num - 1; i >= 0; i--)
{
const std::vector<TupleField> &fields = schema_.fields(); //决定了value 顺序
int index = 0;
for (std::vector<TupleField>::const_iterator iter = fields.begin(), end = fields.end();
iter != end; ++iter)
{
if (ptr_group_selects->attr_order_by[i].relation_name)
{
if (0 == strcmp(iter->field_name(), ptr_group_selects->attr_order_by[i].attribute_name) &&
0 == strcmp(iter->table_name(), ptr_group_selects->attr_order_by[i].relation_name))
{
key_value.push_back(index);
value_key[index] = i;
LOG_INFO(" >>>>>order-by index=%d,table_name=%s,attribute_name=%s", index, iter->table_name(), iter->field_name());
break;
}
}
else
{
if (0 == strcmp(iter->field_name(), ptr_group_selects->attr_order_by[i].attribute_name))
{
key_value.push_back(index);
value_key[index] = i;
LOG_INFO(" >>>>>order-by index=%d,table_name=%s,attribute_name=%s", index, iter->table_name(), iter->field_name());
break;
}
}
index++;
}
}
if (order_by_num != key_value.size())
{
LOG_INFO("排序 order-by 失败 order_by_num != order_index.size()");
return;
}
auto sortRuleLambda = [=](const Tuple &s1, const Tuple &s2) -> bool {
std::vector<std::shared_ptr<TupleValue>> sp1;
std::vector<std::shared_ptr<TupleValue>> sp2;
//key -value
//SELECT * FROM T_ORDER_BY ORDER BY ID, SCORE, NAME;
// 排序数据
for (int i = 0; i < key_value.size(); i++)
{
sp1.push_back(s1.get_pointer(key_value[i]));
sp2.push_back(s2.get_pointer(key_value[i]));
//字段:ID, SCORE, NAME;
//字段之间顺序
//key_value[i]--对应rows的位置
//rows 对应的值
// i
//i -value---key-id
}
//字段之间顺序
for (int op_index = 0; op_index < key_value.size(); op_index++)
{
int op_comp = 0;
std::shared_ptr<TupleValue> sp_1 = sp1[op_index];
std::shared_ptr<TupleValue> sp_2 = sp2[op_index];
if (sp_1 && sp_2)
{
op_comp = sp_1->compare(*sp_2);
}
//不相等才比较 ,相等下一个
if (op_comp != 0)
{
int index_order = value_key.at(key_value[op_index]);
if (CompOp::ORDER_ASC == ptr_attr_order_by[index_order].is_asc)
{
LOG_INFO("排序 order-by ORDER_ASC value=%d, key=%d,name=%s", key_value[op_index], index_order, ptr_attr_order_by[index_order].attribute_name);
return op_comp < 0; //true
}
else if (CompOp::ORDER_DESC == ptr_attr_order_by[index_order].is_asc)
{
LOG_INFO("排序 order-by ORDER_DESC value=%d, key=%d,name=%s", key_value[op_index], index_order, ptr_attr_order_by[index_order].attribute_name);
return op_comp > 0; //true
}
else
{
LOG_INFO("排序 order-by err..... value=%d, key=%d,name=%s", key_value[op_index], index_order, ptr_attr_order_by[index_order].attribute_name);
}
}
} ////多个字段如何比较呀?
//为什么std::sort比较函数在参数相等时返回false?
return false;
};
if (join_tuples.size() > 0)
{
std::sort(join_tuples.begin(), join_tuples.end(), sortRuleLambda);
}
}
}
void TupleSet::join_tuples_to_print(std::ostream &os)
{
os.clear();
for (const Tuple &item : join_tuples)
{
//第n-1列
const std::vector<std::shared_ptr<TupleValue>> &values = item.values();
for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values.begin(), end = --values.end();
iter != end; ++iter)
{
(*iter)->to_string(os);
os << " | ";
}
//最后一列
values.back()->to_string(os);
os << std::endl;
}
}
void TupleSet::sort_table_for_group_by(std::vector<int> &key_value, std::map<int, int> &value_key)
{
//依赖数据结构:
// std::vector<Tuple> tuples_; //一个表头信息
// TupleSchema schema_; //一个表内容信息
// Selects* ptr_group_selects =nullptr; 排序条件
//排序 order-by
int group_by_num = -1;
RelAttr *ptr_attr_group_by = nullptr;
if (ptr_group_selects && ptr_group_selects->attr_group_num > 0)
{
group_by_num = ptr_group_selects->attr_group_num;
ptr_attr_group_by = ptr_group_selects->attr_group_by;
}
if (group_by_num > 0)
{
//SELECT * FROM T_ORDER_BY ORDER BY ID, SCORE, NAME;
//SELECT ID, AVG(SCORE) FROM T_GROUP_BY GROUP BY ID;
//key ---index
//index ---key
//std::vector<int> key_value;
//std::map<int, int> value_key;
key_value.clear();
value_key.clear();
for (int i = ptr_group_selects->attr_group_num - 1; i >= 0; i--)
{
const std::vector<TupleField> &fields = schema_.fields(); //决定了value 顺序
int index = 0;
for (std::vector<TupleField>::const_iterator iter = fields.begin(), end = fields.end();
iter != end; ++iter)
{
//有表名
if (ptr_group_selects->attr_group_by[i].relation_name)
{
if (0 == strcmp(iter->field_name(), ptr_group_selects->attr_group_by[i].attribute_name) &&
0 == strcmp(iter->table_name(), ptr_group_selects->attr_group_by[i].relation_name))
{
key_value.push_back(index);
value_key[index] = i;
LOG_INFO(" >>>>>order-by index=%d,table_name=%s,attribute_name=%s", index, iter->table_name(), iter->field_name());
break;
}
}
else
{ //无表名
if (0 == strcmp(iter->field_name(), ptr_group_selects->attr_group_by[i].attribute_name))
{
key_value.push_back(index);
value_key[index] = i;
LOG_INFO(" >>>>>order-by index=%d,table_name=%s,attribute_name=%s", index, iter->table_name(), iter->field_name());
break;
}
}
index++;
}
}
if (group_by_num != key_value.size())
{
LOG_INFO("排序 order-by 失败 order_by_num != order_index.size()");
return;
}
auto sortRuleLambda = [=](const Tuple &s1, const Tuple &s2) -> bool {
std::vector<std::shared_ptr<TupleValue>> sp1;
std::vector<std::shared_ptr<TupleValue>> sp2;
//key -value
//SELECT * FROM T_ORDER_BY ORDER BY ID, SCORE, NAME;
// 排序数据
for (int i = 0; i < key_value.size(); i++)
{
sp1.push_back(s1.get_pointer(key_value[i]));
sp2.push_back(s2.get_pointer(key_value[i]));
//字段:ID, SCORE, NAME;
//字段之间顺序
//key_value[i]--对应rows的位置
//rows 对应的值
// i
//i -value---key-id
}
//字段之间顺序
for (int op_index = 0; op_index < key_value.size(); op_index++)
{
int op_comp = 0;
std::shared_ptr<TupleValue> sp_1 = sp1[op_index];
std::shared_ptr<TupleValue> sp_2 = sp2[op_index];
if (sp_1 && sp_2)
{
op_comp = sp_1->compare(*sp_2);
}
//不相等才比较 ,相等下一个
if (op_comp != 0)
{
int index_order = value_key.at(key_value[op_index]);
if (CompOp::ORDER_ASC == ptr_attr_group_by[index_order].is_asc)
{
LOG_INFO("排序 order-by ORDER_ASC value=%d, key=%d,name=%s", key_value[op_index], index_order, ptr_attr_group_by[index_order].attribute_name);
return op_comp < 0; //true
}
else if (CompOp::ORDER_DESC == ptr_attr_group_by[index_order].is_asc)
{
LOG_INFO("排序 order-by ORDER_DESC value=%d, key=%d,name=%s", key_value[op_index], index_order, ptr_attr_group_by[index_order].attribute_name);
return op_comp > 0; //true
}
else
{
LOG_INFO("排序 order-by err..... value=%d, key=%d,name=%s", key_value[op_index], index_order, ptr_attr_group_by[index_order].attribute_name);
}
}
} ////多个字段如何比较呀?
//为什么std::sort比较函数在参数相等时返回false?
return false;
};
if (tuples_.size() > 0)
{
std::sort(tuples_.begin(), tuples_.end(), sortRuleLambda);
}
}
}
void TupleSet::sort_two_table_for_group_by(std::vector<int> &key_value, std::map<int, int> &value_key)
{
//依赖数据结构:
// std::vector<Tuple> tuples_; //一个表头信息
// TupleSchema schema_; //一个表内容信息
// Selects* ptr_group_selects =nullptr; 排序条件
//排序 order-by
LOG_INFO("sort_two_table_for_group_by begin");
int group_by_num = -1;
RelAttr *ptr_attr_group_by = nullptr;
if (ptr_group_selects && ptr_group_selects->attr_group_num > 0)
{
group_by_num = ptr_group_selects->attr_group_num;
ptr_attr_group_by = ptr_group_selects->attr_group_by;
}
if (group_by_num > 0)
{
//SELECT * FROM T_ORDER_BY ORDER BY ID, SCORE, NAME;
//SELECT ID, AVG(SCORE) FROM T_GROUP_BY GROUP BY ID;
//key ---index
//index ---key
//std::vector<int> key_value;
//std::map<int, int> value_key;
key_value.clear();
value_key.clear();
// schema_ 这是2个表的 汇总,注意观察是否正确
for (int i = ptr_group_selects->attr_group_num - 1; i >= 0; i--)
{
//const std::vector<TupleField> &fields = schema_.fields(); //决定了value 顺序
const std::vector<TupleField> &fields = old_schema.fields(); //决定了value 顺序
int index = 0;
for (std::vector<TupleField>::const_iterator iter = fields.begin(), end = fields.end();
iter != end; ++iter)
{
//有表名
if (ptr_group_selects->attr_group_by[i].relation_name)
{
if (0 == strcmp(iter->field_name(), ptr_group_selects->attr_group_by[i].attribute_name) &&
0 == strcmp(iter->table_name(), ptr_group_selects->attr_group_by[i].relation_name))
{
key_value.push_back(index);
value_key[index] = i;
LOG_INFO(" >>>>>order-by index=%d,table_name=%s,attribute_name=%s", index, iter->table_name(), iter->field_name());
break;
}
}
else
{ //无表名
if (0 == strcmp(iter->field_name(), ptr_group_selects->attr_group_by[i].attribute_name))
{
key_value.push_back(index);
value_key[index] = i;
LOG_INFO(" >>>>>order-by index=%d,table_name=%s,attribute_name=%s", index, iter->table_name(), iter->field_name());
break;
}
}
index++;
}
}
if (group_by_num != key_value.size())
{
LOG_INFO("sort_two_table_for_group_by 失败 order_by_num != order_index.size()");
return;
}
auto sortRuleLambda = [=](const Tuple &s1, const Tuple &s2) -> bool {
std::vector<std::shared_ptr<TupleValue>> sp1;
std::vector<std::shared_ptr<TupleValue>> sp2;
//key -value
//SELECT * FROM T_ORDER_BY ORDER BY ID, SCORE, NAME;
// 排序数据
for (int i = 0; i < key_value.size(); i++)
{
sp1.push_back(s1.get_pointer(key_value[i]));
sp2.push_back(s2.get_pointer(key_value[i]));
//字段:ID, SCORE, NAME;
//字段之间顺序
//key_value[i]--对应rows的位置
//rows 对应的值
// i
//i -value---key-id
}
//字段之间顺序
for (int op_index = 0; op_index < key_value.size(); op_index++)
{
int op_comp = 0;
std::shared_ptr<TupleValue> sp_1 = sp1[op_index];
std::shared_ptr<TupleValue> sp_2 = sp2[op_index];
if (sp_1 && sp_2)
{
op_comp = sp_1->compare(*sp_2);
}
//不相等才比较 ,相等下一个
if (op_comp != 0)
{
int index_order = value_key.at(key_value[op_index]);
if (CompOp::ORDER_ASC == ptr_attr_group_by[index_order].is_asc)
{
LOG_INFO("排序 order-by ORDER_ASC value=%d, key=%d,name=%s", key_value[op_index], index_order, ptr_attr_group_by[index_order].attribute_name);
return op_comp < 0; //true
}
else if (CompOp::ORDER_DESC == ptr_attr_group_by[index_order].is_asc)
{
LOG_INFO("排序 order-by ORDER_DESC value=%d, key=%d,name=%s", key_value[op_index], index_order, ptr_attr_group_by[index_order].attribute_name);
return op_comp > 0; //true
}
else
{
LOG_INFO("排序 order-by err..... value=%d, key=%d,name=%s", key_value[op_index], index_order, ptr_attr_group_by[index_order].attribute_name);
}
}
} ////多个字段如何比较呀?
//为什么std::sort比较函数在参数相等时返回false?
return false;
};
if (join_tuples_group.size() > 0)
{
std::sort(join_tuples_group.begin(), join_tuples_group.end(), sortRuleLambda);
}
}
}
//排序 分组 统计 -汇总--返回
//参数写死,新增一个参数要新增一个函数.
bool TupleSet::print_group_by(std::ostream &os)
{
//步骤:单表排序
std::vector<int> key_value;
std::map<int, int> value_key;
sort_table_for_group_by(key_value, value_key);
if (key_value.size() <= 0 || tuples_.size() <= 0)
{
LOG_INFO("分组 失败,无记录");
return false;
}
//步骤:相同的为一组
//const int cols = schema_.size();
std::vector<std::shared_ptr<TupleValue>> sp_last; //分组条件
std::vector<std::shared_ptr<TupleValue>> sp_cur; //分组条件
std::vector<Tuple> group_tuples; //对原始数据tuples_分成不同的组
std::vector<vector<string>> output; //汇总分组统计结果
//初始化 默认第一个行记录
for (int i = 0; i < key_value.size(); i++)
{
sp_last.push_back(tuples_[0].get_pointer(key_value[i]));
}
//rows
for (const Tuple &item : tuples_)
{
//cols
sp_cur.clear();
//const std::vector<std::shared_ptr<TupleValue>> &values = item.values();
for (int i = 0; i < key_value.size(); i++)
{
sp_cur.push_back(item.get_pointer(key_value[i]));
}
bool is_group = true;
for (int i = 0; i < key_value.size(); i++)
{
if (sp_last[i] && sp_cur[i] && 0 == sp_last[i]->compare(*sp_cur[i]))
{
//符合预期
}
else
{
is_group = false;
}
}
//相同就汇总
if (true == is_group)
{
LOG_INFO("同一个分组 ....add");
//constructor of tuple is not supported
//emplace_back
//深度拷贝一行数据
Tuple temp;
const std::vector<std::shared_ptr<TupleValue>> &values_copy = item.values();
for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values_copy.begin(), end = values_copy.end();
iter != end; ++iter)
{
temp.add(*iter);
}
group_tuples.emplace_back(std::move(temp));
}
else
{
LOG_INFO("新的分组 .............");
//不相同就统计
//统计
count_group_data(group_tuples, output);
//新的一组
group_tuples.clear();
group_tuples.resize(0);
Tuple temp;
const std::vector<std::shared_ptr<TupleValue>> &values_copy = item.values();
for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values_copy.begin(), end = values_copy.end();
iter != end; ++iter)
{
temp.add(*iter);
}
group_tuples.emplace_back(std::move(temp)); //
//新的分组条件
sp_last = sp_cur;
}
} //end data
//最后一个分组
if (group_tuples.size() > 0)
{
count_group_data(group_tuples, output);
}
//步骤:输出
if (output.size() == 0)
{
LOG_INFO(" 题目 分组group-by 失败,没有任何记录");
}
for (int rows = 0; rows < output.size(); rows++)
{
int cols = output[rows].size() - 1;
for (int i = 0; i <= cols; i++)
{
//最后一行
if (i == cols)
{
os << output[rows][i];
os << std::endl;
}
else
{
os << output[rows][i];
os << " | ";
}
}
}
return true;
}
//统计
void TupleSet::count_group_data(std::vector<Tuple> &group_tuples, std::vector<vector<string>> &output)
{
if (group_tuples.size() == 0)
{
LOG_INFO("group_tuples is 0");
}
LOG_INFO("count_group_data group_tuples.size=%d ", group_tuples.size());
vector<string> total; //根据schema产生一行记录
const std::vector<TupleField> &fields = schema_.fields();
int cols = 0;
//遍历n个元素.
for (std::vector<TupleField>::const_iterator iter = fields.begin(), end = fields.end();
iter != end; ++iter)
{
FunctionType window_function = iter->get_function_type();
if (FunctionType::FUN_COUNT_ALL_ALl == window_function || FunctionType::FUN_COUNT_ALL == window_function || FunctionType::FUN_COUNT == window_function)
{
//rows
std::set<std::shared_ptr<TupleValue>> count;
count.clear();
for (const Tuple &item : group_tuples)
{
const std::vector<std::shared_ptr<TupleValue>> &values = item.values();
int colIndex = 0;
//cols
for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values.begin(), end = values.end();
iter != end; ++iter)
{
//(*iter)->to_string(os);
if (colIndex == cols)
{
//std::shared_ptr<TupleValue> temp = *iter;
count.insert(*iter);
break;
}
colIndex++;
}
}
std::stringstream ss;
ss << count.size();
total.push_back(ss.str());
}
else if (FunctionType::FUN_MAX == window_function)
{
std::shared_ptr<TupleValue> maxValue;
//rows
for (const Tuple &item : group_tuples)
{
const std::vector<std::shared_ptr<TupleValue>> &values = item.values();
if (0 == values.size())
{
continue;
}
int colIndex = 0;
//cols
for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values.begin(), end = values.end();
iter != end; ++iter)
{
//(*iter)->to_string(os);
if (colIndex == cols)
{
std::shared_ptr<TupleValue> temp = *iter;
if (nullptr == maxValue)
{
maxValue = temp;
}
else
{
if (maxValue->compare(*temp) < 0)
{
maxValue = temp;
}
}
break;
}
colIndex++;
}
}
std::stringstream ss;
maxValue->to_string(ss);
total.push_back(ss.str());
}
else if (FunctionType::FUN_MIN == window_function)
{
std::shared_ptr<TupleValue> minValue;
for (const Tuple &item : group_tuples)
{
int colIndex = 0;
//列
const std::vector<std::shared_ptr<TupleValue>> &values = item.values();
if (0 == values.size())
{
continue;
}
for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values.begin(), end = values.end();
iter != end; ++iter)
{
if (colIndex == cols)
{
std::shared_ptr<TupleValue> temp = *iter;
{
if (nullptr == minValue)
{
minValue = *iter;
}
else
{
std::shared_ptr<TupleValue> temp = *iter;
if (minValue->compare(*temp) > 0)
{
minValue = temp;
}
}
}
break; //get
}
colIndex++;
}
} //end
std::stringstream ss;
minValue->to_string(ss);
total.push_back(ss.str());
}
else if (FunctionType::FUN_AVG == window_function)
{
std::shared_ptr<TupleValue> sumValue;
int count = 0;
bool exits_null_value = false;
for (const Tuple &item : group_tuples)
{
int colIndex = 0;
bool null_able = true;
//第n列
const std::vector<std::shared_ptr<TupleValue>> &values = item.values();
if (0 == values.size())
{
continue;
}
for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values.begin(), end = values.end();
iter != end; ++iter)
{
//(*iter)->to_string(os);
if (colIndex == cols)
{
std::shared_ptr<TupleValue> temp = *iter;
if (AttrType::NULLVALUES == temp->get_type())
{
//不处理
null_able = false;
exits_null_value = true;
}
else
{
if (nullptr == sumValue)
{
sumValue = temp;
}
else
{
sumValue->add_value(*temp);
}
}
break; //get
}
colIndex++;
}
if (true == null_able)
{
count++;
}
} //end
//防溢出求平均算法
if (0 == count)
{
if (exits_null_value == true)
{
total.push_back("NULL");
}
}
std::stringstream ss;
sumValue->to_avg(count, ss);
total.push_back(ss.str());
}
else if (FunctionType::FUN_NO == window_function)
{
LOG_INFO(">>>>>>FunctionType::FUN_NO =%s ", iter->field_name());
std::shared_ptr<TupleValue> itemValue;
//只读取其中的一行
if (group_tuples.size() > 0)
{
//第n列
int colIndex = 0;
const std::vector<std::shared_ptr<TupleValue>> &values = group_tuples[0].values();
for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values.begin(), end = values.end();
iter != end; ++iter)
{
//(*iter)->to_string(os);
if (colIndex == cols)
{
itemValue = *iter;
break; //get
}
colIndex++;
}
std::stringstream ss;
itemValue->to_string(ss);
total.push_back(ss.str());
}
}
else
{
LOG_INFO(">>>>>>errrrrrrrrrrrr=%s ", iter->field_name());
}
cols++;
} //const std::vector<TupleField> &fields = schema_.fields();
output.push_back(total);
}
//代码重复:前期设计不合适导致,2个一样的逻辑
//需要优化
void TupleSet::count_two_table_group_data(std::vector<Tuple> &group_tuples, std::vector<vector<string>> &output)
{
if (group_tuples.size() == 0)
{
LOG_INFO("count_two_table_group_data is 0");
}
LOG_INFO("count_two_table_group_data group_tuples.size=%d ", group_tuples.size());
vector<string> total; //根据schema产生一行记录
const std::vector<TupleField> &fields = old_schema.fields();
int cols = 0;
//遍历n个元素.
for (std::vector<TupleField>::const_iterator field_iter = fields.begin(), end = fields.end();
field_iter != end; ++field_iter)
{
if (false == field_iter->visible())
{
LOG_INFO(">>>>> group by 不可见字段 index =%d,name =%s ", cols, field_iter->field_name());
cols++;
continue;
}
FunctionType window_function = field_iter->get_function_type();
if (FunctionType::FUN_COUNT_ALL_ALl == window_function || FunctionType::FUN_COUNT_ALL == window_function || FunctionType::FUN_COUNT == window_function)
{
//rows
std::set<std::shared_ptr<TupleValue>> count;
count.clear();
for (const Tuple &item : group_tuples)
{
const std::vector<std::shared_ptr<TupleValue>> &values = item.values();
int colIndex = 0;
//cols
for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values.begin(), end = values.end();
iter != end; ++iter)
{
//(*iter)->to_string(os);
if (colIndex == cols)
{
//std::shared_ptr<TupleValue> temp = *iter;
count.insert(*iter);
break;
}
colIndex++;
}
}
std::stringstream ss;
ss << count.size();
total.push_back(ss.str());
LOG_INFO(">>>>> group by count index =%d,name =%s,value =%d ", cols, field_iter->field_name(), count.size());
}
else if (FunctionType::FUN_MAX == window_function)
{
std::shared_ptr<TupleValue> maxValue;
//rows
for (const Tuple &item : group_tuples)
{
const std::vector<std::shared_ptr<TupleValue>> &values = item.values();
if (0 == values.size())
{
continue;
}
int colIndex = 0;
//cols
for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values.begin(), end = values.end();
iter != end; ++iter)
{
//(*iter)->to_string(os);
if (colIndex == cols)
{
std::shared_ptr<TupleValue> temp = *iter;
if (nullptr == maxValue)
{
maxValue = temp;
}
else
{
if (maxValue->compare(*temp) < 0)
{
maxValue = temp;
}
}
break;
}
colIndex++;
}
}
std::stringstream ss;
maxValue->to_string(ss);
total.push_back(ss.str());
LOG_INFO(">>>>> group by max index =%d,name =%s,value =%s ", cols, field_iter->field_name(), maxValue->print_string().c_str());
}
else if (FunctionType::FUN_MIN == window_function)
{
std::shared_ptr<TupleValue> minValue;
for (const Tuple &item : group_tuples)
{
int colIndex = 0;
//列
const std::vector<std::shared_ptr<TupleValue>> &values = item.values();
if (0 == values.size())
{
continue;
}
for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values.begin(), end = values.end();
iter != end; ++iter)
{
if (colIndex == cols)
{
std::shared_ptr<TupleValue> temp = *iter;
{
if (nullptr == minValue)
{
minValue = *iter;
}
else
{
std::shared_ptr<TupleValue> temp = *iter;
if (minValue->compare(*temp) > 0)
{
minValue = temp;
}
}
}
break; //get
}
colIndex++;
}
} //end
std::stringstream ss;
minValue->to_string(ss);
total.push_back(ss.str());
LOG_INFO(">>>>> group by min index =%d,name =%s,value =%s ", cols, field_iter->field_name(), minValue->print_string().c_str());
}
else if (FunctionType::FUN_AVG == window_function)
{
std::shared_ptr<TupleValue> sumValue;
int count = 0;
for (const Tuple &item : group_tuples)
{
int colIndex = 0;
//第n列
const std::vector<std::shared_ptr<TupleValue>> &values = item.values();
for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values.begin(), end = values.end();
iter != end; ++iter)
{
//(*iter)->to_string(os);
if (colIndex == cols)
{
std::shared_ptr<TupleValue> temp = *iter;
if (nullptr == sumValue)
{
sumValue = temp;
}
else
{
sumValue->add_value(*temp);
}
break; //get
}
colIndex++;
}
count++;
} //end
//防溢出求平均算法
LOG_INFO(">>>>> group by >>>>>>>>>>>>>>>>>>>>>>> ", count);
if (0 == count)
{
total.push_back("NULL");
}
else
{
std::stringstream ss;
sumValue->to_avg(count, ss);
total.push_back(ss.str());
LOG_INFO(">>>>> group by avg index =%d,name =%s ", cols, field_iter->field_name());
}
}
else if (FunctionType::FUN_NO == window_function)
{
LOG_INFO(">>>>>> FunctionType::FUN_NO =%s ", field_iter->field_name());
std::shared_ptr<TupleValue> itemValue;
//只读取其中的一行
if (group_tuples.size() > 0)
{
//第n列
int colIndex = 0;
const std::vector<std::shared_ptr<TupleValue>> &values = group_tuples[0].values();
for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values.begin(), end = values.end();
iter != end; ++iter)
{
//(*iter)->to_string(os);
if (colIndex == cols)
{
itemValue = *iter;
// break; //get
}
colIndex++;
}
std::stringstream ss;
itemValue->to_string(ss);
total.push_back(ss.str());
LOG_INFO(">>>>> group by index =%d,name =%s,value =%s ", cols, field_iter->field_name(), itemValue->print_string().c_str());
}
}
else
{
LOG_INFO(">>>>>>errrrrrrrrrrrr=%s ", field_iter->field_name());
}
cols++;
} //const std::vector<TupleField> &fields = schema_.fields();
output.push_back(total);
}
//排序 分组 统计 -汇总--返回
//参数写死,新增一个参数要新增一个函数.
bool TupleSet::print_two_table_group_by(std::ostream &os)
{
//步骤:单表排序
std::vector<int> key_value;
std::map<int, int> value_key;
sort_two_table_for_group_by(key_value, value_key);
if (key_value.size() <= 0 || join_tuples_group.size() <= 0)
{
LOG_INFO("分组 失败,无记录");
return false;
}
//步骤:相同的为一组
//const int cols = schema_.size();
std::vector<std::shared_ptr<TupleValue>> sp_last; //分组条件
std::vector<std::shared_ptr<TupleValue>> sp_cur; //分组条件
std::vector<Tuple> onece_group_tuples; //对原始数据tuples_分成不同的组
std::vector<vector<string>> output; //汇总分组统计结果
output.clear();
onece_group_tuples.clear();
//初始化 默认第一个行记录
//std::vector<Tuple> join_tuples_group; //sql:1 笛卡尔积 2 过滤 3 排序 4 分组 5 显示。
//tuples_
for (int i = 0; i < key_value.size(); i++)
{
sp_last.push_back(join_tuples_group[0].get_pointer(key_value[i]));
}
//rows
for (const Tuple &item : join_tuples_group)
{
//cols
sp_cur.clear();
//const std::vector<std::shared_ptr<TupleValue>> &values = item.values();
for (int i = 0; i < key_value.size(); i++)
{
sp_cur.push_back(item.get_pointer(key_value[i]));
}
bool is_group = true;
for (int i = 0; i < key_value.size(); i++)
{
if (sp_last[i] && sp_cur[i] && 0 == sp_last[i]->compare(*sp_cur[i]))
{
//符合预期
}
else
{
is_group = false;
}
}
//相同就汇总
if (true == is_group)
{
LOG_INFO("同一个分组 ....add");
//constructor of tuple is not supported
//emplace_back
//深度拷贝一行数据
Tuple temp;
const std::vector<std::shared_ptr<TupleValue>> &values_copy = item.values();
for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values_copy.begin(), end = values_copy.end();
iter != end; ++iter)
{
temp.add(*iter);
}
onece_group_tuples.push_back(std::move(temp));
}
else
{
LOG_INFO("新的分组 .............");
//不相同就统计
//统计
//count_group_data(group_tuples, output);
count_two_table_group_data(onece_group_tuples, output);
//新的一组
onece_group_tuples.clear();
onece_group_tuples.resize(0);
onece_group_tuples.reserve(0);
Tuple temp;
const std::vector<std::shared_ptr<TupleValue>> &values_copy = item.values();
for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values_copy.begin(), end = values_copy.end();
iter != end; ++iter)
{
temp.add(*iter);
}
onece_group_tuples.push_back(std::move(temp)); //
//新的分组条件
sp_last = sp_cur;
}
} //end data
//最后一个分组
if (onece_group_tuples.size() > 0)
{
count_two_table_group_data(onece_group_tuples, output);
}
//步骤:输出
if (output.size() == 0)
{
LOG_INFO(" 题目 分组group-by 失败,没有任何记录");
}
for (int rows = 0; rows < output.size(); rows++)
{
int cols = output[rows].size() - 1;
for (int i = 0; i <= cols; i++)
{
//最后一行
if (i == cols)
{
os << output[rows][i];
os << std::endl;
}
else
{
os << output[rows][i];
os << " | ";
}
}
}
return true;
} | 27.525826 | 169 | 0.527694 | watchpoints |
99e97479fb174c208fe45f7df3dffd7c6b944cd5 | 6,657 | cpp | C++ | Game/Client/CEGUIFalagardEx/FalChatChannel.cpp | hackerlank/SourceCode | b702c9e0a9ca5d86933f3c827abb02a18ffc9a59 | [
"MIT"
] | 4 | 2021-07-31T13:56:01.000Z | 2021-11-13T02:55:10.000Z | Game/Client/CEGUIFalagardEx/FalChatChannel.cpp | shacojx/SourceCodeGameTLBB | e3cea615b06761c2098a05427a5f41c236b71bf7 | [
"MIT"
] | null | null | null | Game/Client/CEGUIFalagardEx/FalChatChannel.cpp | shacojx/SourceCodeGameTLBB | e3cea615b06761c2098a05427a5f41c236b71bf7 | [
"MIT"
] | 7 | 2021-08-31T14:34:23.000Z | 2022-01-19T08:25:58.000Z | #include "FalChatChannel.h"
#include "CEGUIPropertyHelper.h"
#include "falagard/CEGUIFalWidgetLookManager.h"
#include "falagard/CEGUIFalWidgetLookFeel.h"
// Start of CEGUI namespace section
namespace CEGUI
{
//===================================================================================
//
// FalagardChatChannel
//
//===================================================================================
const utf8 FalagardChatChannel::WidgetTypeName[] = "Falagard/ChatChannel";
FalagardChatChannelProperties::ItemSize FalagardChatChannel::d_itemSizeProperty;
FalagardChatChannelProperties::AnchorPosition FalagardChatChannel::d_anchorPositionProperty;
FalagardChatChannelProperties::HoverChannelBkg FalagardChatChannel::d_hoverChannelBkgProperty;
FalagardChatChannelProperties::HoverChannel FalagardChatChannel::d_hoverChannelProperty;
FalagardChatChannelProperties::HoverChannelName FalagardChatChannel::d_hoverChannelNameProperty;
FalagardChatChannel::FalagardChatChannel(const String& type, const String& name) :
Window(type, name),
d_itemSize(0.0, 0.0),
d_anchorPosition(0.0, 0.0),
d_hoverChannelBkg(0),
d_hoverChannel(-1),
d_lastHoverChannel(-1),
d_pushed(false)
{
addChatChannelProperties();
setAlwaysOnTop(true);
}
FalagardChatChannel::~FalagardChatChannel()
{
}
void FalagardChatChannel::addChatChannelProperties(void)
{
CEGUI_START_ADD_STATICPROPERTY( FalagardChatChannel )
CEGUI_ADD_STATICPROPERTY( &d_itemSizeProperty );
CEGUI_ADD_STATICPROPERTY( &d_anchorPositionProperty );
CEGUI_ADD_STATICPROPERTY( &d_hoverChannelBkgProperty );
CEGUI_ADD_STATICPROPERTY( &d_hoverChannelProperty );
CEGUI_ADD_STATICPROPERTY( &d_hoverChannelNameProperty );
CEGUI_END_ADD_STATICPROPERTY
}
void FalagardChatChannel::onMouseMove(MouseEventArgs& e)
{
// base class processing
Window::onMouseMove(e);
updateInternalState(e.position);
e.handled = true;
}
void FalagardChatChannel::updateInternalState(const Point& ptMouse)
{
Point pt(ptMouse);
pt.d_x -= windowToScreenX(0);
pt.d_y -= windowToScreenY(0);
Rect absarea(getPixelRect());
absarea.offset(Point(-absarea.d_left, -absarea.d_top));
if(absarea.isPointInRect(pt))
{
float fItemHeight = absarea.getHeight()/(int)d_allChannel.size();
d_hoverChannel = (int)(pt.d_y/fItemHeight);
if(d_lastHoverChannel != d_hoverChannel)
{
requestRedraw();
d_lastHoverChannel = d_hoverChannel;
}
}
}
void FalagardChatChannel::onMouseButtonDown(MouseEventArgs& e)
{
// default processing
Window::onMouseButtonDown(e);
if (e.button == LeftButton)
{
if (captureInput())
{
d_pushed = true;
updateInternalState(e.position);
requestRedraw();
}
// event was handled by us.
e.handled = true;
}
}
void FalagardChatChannel::onMouseButtonUp(MouseEventArgs& e)
{
// default processing
Window::onMouseButtonUp(e);
if (e.button == LeftButton)
{
releaseInput();
// event was handled by us.
e.handled = true;
}
}
void FalagardChatChannel::onMouseLeaves(MouseEventArgs& e)
{
// base class processing
Window::onMouseLeaves(e);
d_hoverChannel = -1;
d_lastHoverChannel = -1;
requestRedraw();
}
void FalagardChatChannel::populateRenderCache(void)
{
// get WidgetLookFeel for the assigned look.
const WidgetLookFeel& wlf = WidgetLookManager::getSingleton().getWidgetLook(d_lookName);
// try and get imagery for our current state
const StateImagery* imagery = &wlf.getStateImagery("Frame");
// peform the rendering operation.
imagery->render(*this);
const Rect rectIconSize(wlf.getNamedArea("IconSize").getArea().getPixelRect(*this));
const FontBase* font = getFont();
Rect absarea(getPixelRect());
absarea.offset(Point(-absarea.d_left, -absarea.d_top));
ColourRect final_cols(colour(1.0f, 1.0f, 1.0f));
float fItemHeight = absarea.getHeight()/(int)d_allChannel.size();
for(int i=0; i<(int)d_allChannel.size(); i++)
{
ChannelItem& theChannel = d_allChannel[i];
Rect rectIcon(rectIconSize);
rectIcon.offset(Point(0, (fItemHeight-rectIconSize.getHeight())/2 + fItemHeight*i));
d_renderCache.cacheImage(
*theChannel.d_headIcon, rectIcon, 0.0f, final_cols);
Rect rectText(absarea.d_left, fItemHeight*i,
absarea.d_right, fItemHeight*(i+1));
rectText.d_left += rectIcon.getWidth()+2;
if(d_hoverChannelBkg && d_hoverChannel == i)
{
d_renderCache.cacheImage(
*d_hoverChannelBkg, rectText, 0.0f, ColourRect(0xFFFF0000, 0xFFFF0000, 0xFFFF0000, 0xFFFF0000));
}
d_renderCache.cacheText(this,
theChannel.d_strName, font, (TextFormatting)WordWrapLeftAligned, rectText, 0.0f, final_cols);
}
}
void FalagardChatChannel::resizeSelf(void)
{
float fTotalHeight = d_itemSize.d_height * (int)d_allChannel.size();
setSize(Absolute,Size(d_itemSize.d_width, fTotalHeight));
float fParentHeight = d_parent->getPixelRect().getHeight();
if(d_parent->getPixelRect().getWidth() < 1024) fParentHeight += 51;
setPosition(Absolute,Point(d_anchorPosition.d_x, fParentHeight - d_anchorPosition.d_y - fTotalHeight));
}
void FalagardChatChannel::clearAllChannel(void)
{
d_allChannel.clear();
resizeSelf();
}
void FalagardChatChannel::addChannel(const String& strType, const String& strIconName, const String& strName)
{
ChannelItem newChannel;
newChannel.d_strType = strType;
newChannel.d_headIcon = PropertyHelper::stringToImage(strIconName);
if(!newChannel.d_headIcon) return;
newChannel.d_strName = strName;
d_allChannel.push_back(newChannel);
resizeSelf();
}
String FalagardChatChannel::getHoverChannel(void) const
{
if(d_hoverChannel >= 0 && d_hoverChannel < (int)d_allChannel.size())
{
return d_allChannel[d_hoverChannel].d_strType;
}
return String("");
}
String FalagardChatChannel::getHoverChannelName(void) const
{
if(d_hoverChannel >= 0 && d_hoverChannel < (int)d_allChannel.size())
{
return d_allChannel[d_hoverChannel].d_strName;
}
return String("");
}
//////////////////////////////////////////////////////////////////////////
/*************************************************************************
Factory Methods
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
Window* FalagardChatChannelFactory::createWindow(const String& name)
{
return new FalagardChatChannel(d_type, name);
}
void FalagardChatChannelFactory::destroyWindow(Window* window)
{
delete window;
}
} | 28.570815 | 110 | 0.680787 | hackerlank |
99e9bfed3ca0114396d42df21472a9a422505ccc | 3,922 | cpp | C++ | source/hougfx/test/hou/gfx/test_graphics_state.cpp | DavideCorradiDev/houzi-game-engine | d704aa9c5b024300578aafe410b7299c4af4fcec | [
"MIT"
] | 2 | 2018-04-12T20:59:20.000Z | 2018-07-26T16:04:07.000Z | source/hougfx/test/hou/gfx/test_graphics_state.cpp | DavideCorradiDev/houzi-game-engine | d704aa9c5b024300578aafe410b7299c4af4fcec | [
"MIT"
] | null | null | null | source/hougfx/test/hou/gfx/test_graphics_state.cpp | DavideCorradiDev/houzi-game-engine | d704aa9c5b024300578aafe410b7299c4af4fcec | [
"MIT"
] | null | null | null | // Houzi Game Engine
// Copyright (c) 2018 Davide Corradi
// Licensed under the MIT license.
#include "hou/gfx/test_gfx_base.hpp"
#include "hou/gfx/graphics_state.hpp"
using namespace hou;
using namespace testing;
namespace hou
{
class test_graphics_state : public test_gfx_base
{
public:
static std::vector<blending_factor> blending_factors;
static std::vector<blending_equation> blending_equations;
};
std::vector<blending_factor> test_graphics_state::blending_factors{
blending_factor::zero,
blending_factor::one,
blending_factor::src_color,
blending_factor::one_minus_src_color,
blending_factor::dst_color,
blending_factor::one_minus_dst_color,
blending_factor::src_alpha,
blending_factor::one_minus_src_alpha,
blending_factor::dst_alpha,
blending_factor::one_minus_dst_alpha,
blending_factor::constant_color,
blending_factor::one_minus_constant_color,
blending_factor::constant_alpha,
blending_factor::one_minus_constant_alpha,
};
std::vector<blending_equation> test_graphics_state::blending_equations{
blending_equation::add,
blending_equation::subtract,
blending_equation::reverse_subtract,
blending_equation::min,
blending_equation::max,
};
} // namespace hou
TEST_F(test_graphics_state, set_vsync_mode)
{
EXPECT_EQ(vsync_mode::enabled, get_vsync_mode());
EXPECT_TRUE(set_vsync_mode(vsync_mode::disabled));
EXPECT_EQ(vsync_mode::disabled, get_vsync_mode());
if(set_vsync_mode(vsync_mode::adaptive))
{
EXPECT_EQ(vsync_mode::adaptive, get_vsync_mode());
}
EXPECT_TRUE(set_vsync_mode(vsync_mode::enabled));
EXPECT_EQ(vsync_mode::enabled, get_vsync_mode());
}
TEST_F(test_graphics_state, multisampling_enabled)
{
EXPECT_TRUE(is_multisampling_enabled());
set_multisampling_enabled(true);
EXPECT_TRUE(is_multisampling_enabled());
set_multisampling_enabled(false);
EXPECT_FALSE(is_multisampling_enabled());
set_multisampling_enabled(false);
EXPECT_FALSE(is_multisampling_enabled());
set_multisampling_enabled(true);
EXPECT_TRUE(is_multisampling_enabled());
}
TEST_F(test_graphics_state, blending_enabled)
{
EXPECT_TRUE(is_blending_enabled());
set_blending_enabled(true);
EXPECT_TRUE(is_blending_enabled());
set_blending_enabled(false);
EXPECT_FALSE(is_blending_enabled());
set_blending_enabled(false);
EXPECT_FALSE(is_blending_enabled());
set_blending_enabled(true);
EXPECT_TRUE(is_blending_enabled());
}
TEST_F(test_graphics_state, source_blending_factor)
{
blending_factor dst_factor = get_destination_blending_factor();
EXPECT_EQ(blending_factor::src_alpha, get_source_blending_factor());
for(auto f : blending_factors)
{
set_source_blending_factor(f);
EXPECT_EQ(f, get_source_blending_factor());
EXPECT_EQ(dst_factor, get_destination_blending_factor());
}
set_source_blending_factor(blending_factor::src_alpha);
}
TEST_F(test_graphics_state, destination_blending_factor)
{
blending_factor src_factor = get_source_blending_factor();
EXPECT_EQ(
blending_factor::one_minus_src_alpha, get_destination_blending_factor());
for(auto f : blending_factors)
{
set_destination_blending_factor(f);
EXPECT_EQ(f, get_destination_blending_factor());
EXPECT_EQ(src_factor, get_source_blending_factor());
}
set_destination_blending_factor(blending_factor::one_minus_src_alpha);
}
TEST_F(test_graphics_state, blending_equation)
{
EXPECT_EQ(blending_equation::add, get_blending_equation());
for(auto e : blending_equations)
{
set_blending_equation(e);
EXPECT_EQ(e, get_blending_equation());
}
set_blending_equation(blending_equation::add);
}
TEST_F(test_graphics_state, blending_color)
{
EXPECT_EQ(color::transparent(), get_blending_color());
set_blending_color(color::red());
EXPECT_EQ(color::red(), get_blending_color());
set_blending_color(color::transparent());
EXPECT_EQ(color::transparent(), get_blending_color());
}
| 25.633987 | 77 | 0.789393 | DavideCorradiDev |
99ebaad6690973f182110c0ee4954177857a8d84 | 3,899 | cpp | C++ | src/duyebase/system/duye_epoll.cpp | tencupofkaiwater/duye | 72257379f91e7a0db5ffefbb7e7a74dc0a255f67 | [
"Unlicense"
] | null | null | null | src/duyebase/system/duye_epoll.cpp | tencupofkaiwater/duye | 72257379f91e7a0db5ffefbb7e7a74dc0a255f67 | [
"Unlicense"
] | null | null | null | src/duyebase/system/duye_epoll.cpp | tencupofkaiwater/duye | 72257379f91e7a0db5ffefbb7e7a74dc0a255f67 | [
"Unlicense"
] | null | null | null | /************************************************************************************
**
* @copyright (c) 2013-2100, ChengDu Duyer Technology Co., LTD. All Right Reserved.
*
*************************************************************************************/
/**
* @file duye_epoll.cpp
* @version
* @brief
* @author duye
* @date 2016-03-29
* @note
*
* 1. 2016-03-29 duye Created this file
*/
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <duye_sys.h>
#include <duye_epoll.h>
namespace duye {
static const int8* DUYE_LOG_PREFIX = "duye.system.epoll";
Epoll::Epoll() : m_epollfd(-1)
, m_maxEvents(0)
, m_sysEvents(NULL)
{
m_error.setPrefix(DUYE_LOG_PREFIX);
}
Epoll::~Epoll()
{
close();
}
bool Epoll::open(const uint32 maxEvents)
{
close();
m_maxEvents = maxEvents;
m_epollfd = epoll_create(m_maxEvents);
if (m_epollfd == -1)
{
ERROR_DUYE_LOG("%s:%d > epoll_create failed \n", __FILE__, __LINE__);
return false;
}
m_sysEvents = (struct epoll_event*)calloc(m_maxEvents, sizeof(struct epoll_event));
if (m_sysEvents == NULL) {
ERROR_DUYE_LOG("%s:%d > calloc return NULL \n", __FILE__, __LINE__);
return false;
}
return true;
}
bool Epoll::close()
{
m_maxEvents = 0;
if (m_epollfd != -1)
{
::close(m_epollfd);
m_epollfd = -1;
}
if (m_sysEvents != NULL)
{
free(m_sysEvents);
m_sysEvents = NULL;
}
return true;
}
bool Epoll::addfd(const int32 fd, const uint32 epollMode)
{
if (m_epollfd == -1) {
ERROR_DUYE_LOG("%s:%d > m_epollfd == -1", __FILE__, __LINE__);
return false;
}
struct epoll_event epollEvent;
bzero(&epollEvent, sizeof(struct epoll_event));
epollEvent.data.fd = fd;
epollEvent.events = epollMode;
int32 ret = epoll_ctl(m_epollfd, EPOLL_CTL_ADD, fd, &epollEvent);
if (ret != 0) {
ERROR_DUYE_LOG("[%s:%d] epoll_ctl() return = %d", __FILE__, __LINE__, ret);
return false;
}
return true;
}
bool Epoll::modfd(const int32 fd, const uint32 epollMode)
{
if (m_epollfd == -1) {
ERROR_DUYE_LOG("[%s:%d] m_epollfd == -1", __FILE__, __LINE__);
return false;
}
struct epoll_event epollEvent;
bzero(&epollEvent, sizeof(struct epoll_event));
epollEvent.data.fd = fd;
epollEvent.events = epollMode;
return epoll_ctl(m_epollfd, EPOLL_CTL_MOD, fd, &epollEvent) == 0 ? true : false;
}
bool Epoll::delfd(const int32 fd)
{
if (m_epollfd == -1) {
ERROR_DUYE_LOG("[%s:%d] m_epollfd == -1", __FILE__, __LINE__);
return false;
}
return epoll_ctl(m_epollfd, EPOLL_CTL_DEL, fd, NULL) == 0 ? true : false;
}
bool Epoll::wait(Epoll::EventList& eventList, const uint32 timeout)
{
if (m_epollfd == -1) {
ERROR_DUYE_LOG("[%s:%d] m_epollfd == -1", __FILE__, __LINE__);
return false;
}
int32 event_count = epoll_wait(m_epollfd, m_sysEvents, m_maxEvents, timeout);
if (event_count <= 0)
{
return false;
}
for (uint32 i = 0; i < (uint32)event_count; i++)
{
if ((m_sysEvents[i].events & EPOLLERR) ||
(m_sysEvents[i].events & EPOLLHUP))
{
ERROR_DUYE_LOG("[%s:%d] epoll error, close fd \n", __FILE__, __LINE__);
delfd(m_sysEvents[i].data.fd);
eventList.push_back(EpollEvent(m_sysEvents[i].data.fd, ERROR_FD));
continue;
}
else if (m_sysEvents[i].events & EPOLLIN)
{
eventList.push_back(EpollEvent(m_sysEvents[i].data.fd, RECV_FD));
}
else if (m_sysEvents[i].events & EPOLLOUT)
{
eventList.push_back(EpollEvent(m_sysEvents[i].data.fd, SEND_FD));
}
else
{
eventList.push_back(EpollEvent(m_sysEvents[i].data.fd, RECV_UN));
}
}
return true;
}
uint8* Epoll::error()
{
return m_error.error;
}
}
| 22.80117 | 87 | 0.583483 | tencupofkaiwater |
99ec5621b29c28164ae9d39445151b0e1ca0c522 | 1,593 | cpp | C++ | tests/test-uart.cpp | uav-router/uav_router | 8accab304fdef749009309c60d2211db5b1793ba | [
"MIT"
] | null | null | null | tests/test-uart.cpp | uav-router/uav_router | 8accab304fdef749009309c60d2211db5b1793ba | [
"MIT"
] | null | null | null | tests/test-uart.cpp | uav-router/uav_router | 8accab304fdef749009309c60d2211db5b1793ba | [
"MIT"
] | null | null | null | #include "log.h"
#include "ioloop.h"
#include <memory>
#include <iostream>
void test() {
auto loop = IOLoop::loop();
error_c ec = loop->handle_CtrlC();
if (ec) {
std::cout<<"Ctrl-C handler error "<<ec<<std::endl;
return;
}
auto uart = loop->uart("UartEndpoint");
{
std::shared_ptr<Client> endpoint;
uart->on_connect([&endpoint](std::shared_ptr<Client> cli, std::string name){
endpoint = cli;
endpoint->on_close([name, &endpoint](){
std::cout<<"Close "<<name<<std::endl;
//endpoint.reset();
});
endpoint->on_read([name](void* buf, int len){
std::cout<<"UART "<<name<<" ("<<len<<"): ";
const char* hex = "0123456789ABCDEF";
uint8_t *arr = (uint8_t*)buf;
for (int i = len; i; i--) {
uint8_t b = *arr++;
std::cout<<hex[(b>>4) & 0x0F];
std::cout<<hex[b & 0x0F]<<' ';
}
std::cout<<std::endl;
});
endpoint->on_error([](const error_c& ec) {
std::cout<<"UART cli error:"<<ec<<std::endl;
});
std::cout<<"Connect to "<<name<<std::endl;
});
uart->on_error([](const error_c& ec) {
std::cout<<"UART error:"<<ec<<std::endl;
});
uart->init("/dev/ttyUSB0",115200);
loop->run();
}
}
int main() {
Log::init();
Log::set_level(Log::Level::DEBUG,{"ioloop","uart"});
test();
return 0;
} | 31.235294 | 84 | 0.456372 | uav-router |
99f1d818541abfe201b61038d2e5d577c9006182 | 556 | cpp | C++ | pg_answer/259350e26d1d4c748446c198c9f3ca00.cpp | Guyutongxue/Introduction_to_Computation | 062f688fe3ffb8e29cfaf139223e4994edbf64d6 | [
"WTFPL"
] | 8 | 2019-10-09T14:33:42.000Z | 2020-12-03T00:49:29.000Z | pg_answer/259350e26d1d4c748446c198c9f3ca00.cpp | Guyutongxue/Introduction_to_Computation | 062f688fe3ffb8e29cfaf139223e4994edbf64d6 | [
"WTFPL"
] | null | null | null | pg_answer/259350e26d1d4c748446c198c9f3ca00.cpp | Guyutongxue/Introduction_to_Computation | 062f688fe3ffb8e29cfaf139223e4994edbf64d6 | [
"WTFPL"
] | null | null | null | #include <iostream>
int main() {
int k;
while (std::cin >> k, k) {
for (int m{k + 1}; true; m++) {
int pos{0};
int n{k * 2};
bool hasGood{false};
for (int i{1}; i <= k; i++) {
pos = (pos + m - 1) % n;
if (pos < k) {
hasGood = true;
break;
}
n--;
}
if (!hasGood) {
std::cout << m << std::endl;
break;
}
}
}
} | 23.166667 | 44 | 0.276978 | Guyutongxue |
99f2101a5f0ad596c7d346eb05aad904b7802921 | 388 | hpp | C++ | GLFramework/Game/Materials/EmissiveMaterial.hpp | Illation/GLFramework | 2b9d3d67d4e951e2ff5ace0241750a438d6e743f | [
"MIT"
] | 39 | 2016-03-23T00:39:46.000Z | 2022-02-07T21:26:05.000Z | GLFramework/Game/Materials/EmissiveMaterial.hpp | Illation/GLFramework | 2b9d3d67d4e951e2ff5ace0241750a438d6e743f | [
"MIT"
] | 1 | 2016-03-24T14:39:45.000Z | 2016-03-24T17:34:39.000Z | GLFramework/Game/Materials/EmissiveMaterial.hpp | Illation/GLFramework | 2b9d3d67d4e951e2ff5ace0241750a438d6e743f | [
"MIT"
] | 3 | 2016-08-15T01:27:13.000Z | 2021-12-29T01:37:51.000Z | #pragma once
#include "../../Graphics/Material.hpp"
class EmissiveMaterial : public Material
{
public:
EmissiveMaterial(glm::vec3 col = glm::vec3(1, 1, 1));
~EmissiveMaterial();
void SetCol(glm::vec3 col) { m_Color = col; }
private:
void LoadTextures();
void AccessShaderAttributes();
void UploadDerivedVariables();
private:
//Parameters
GLint m_uCol;
glm::vec3 m_Color;
};
| 16.869565 | 54 | 0.71134 | Illation |
99faccc599709f54020bcb9b3388e1c1380dfa74 | 6,744 | cpp | C++ | src/graphics/Primitives.cpp | PatrickDahlin/Untitled-Game | e12a0eb9b83d45727201fd47ca073e6c2530cb48 | [
"Zlib",
"MIT"
] | null | null | null | src/graphics/Primitives.cpp | PatrickDahlin/Untitled-Game | e12a0eb9b83d45727201fd47ca073e6c2530cb48 | [
"Zlib",
"MIT"
] | null | null | null | src/graphics/Primitives.cpp | PatrickDahlin/Untitled-Game | e12a0eb9b83d45727201fd47ca073e6c2530cb48 | [
"Zlib",
"MIT"
] | null | null | null | #include "graphics/Primitives.hpp"
#include <vector>
#include <glm/glm.hpp>
typedef glm::vec3 v3;
typedef glm::vec2 v2;
typedef glm::vec4 v4;
/*
p4 -- p3
| |
p1 -- p2
*/
void add_face(std::vector<v3>& v,
std::vector<v3>& n,
std::vector<v4>& c,
std::vector<v2>& t,
v3 p1,
v3 p2,
v3 p3,
v3 p4,
v3 n1,
v4 c1)
{
v.emplace_back(p1);
v.emplace_back(p2);
v.emplace_back(p3);
v.emplace_back(p1);
v.emplace_back(p3);
v.emplace_back(p4);
t.emplace_back(v2(0,0));
t.emplace_back(v2(1,0));
t.emplace_back(v2(1,1));
t.emplace_back(v2(0,0));
t.emplace_back(v2(1,1));
t.emplace_back(v2(0,1));
n.emplace_back(n1);
n.emplace_back(n1);
n.emplace_back(n1);
n.emplace_back(n1);
n.emplace_back(n1);
n.emplace_back(n1);
c.emplace_back(c1);
c.emplace_back(c1);
c.emplace_back(c1);
c.emplace_back(c1);
c.emplace_back(c1);
c.emplace_back(c1);
}
Model* Primitives::create_cube()
{
Model* model = new Model();
std::vector<v3> pos;
std::vector<v3> norm;
std::vector<v4> cols;
std::vector<v2> tex;
const float n = -0.5f;
const float p = 0.5f;
// FRONT
add_face(pos, norm, cols, tex,
v3(n,n,n),v3(p,n,n),
v3(p,p,n),v3(n,p,n),
v3(0,0,-1),v4(1,1,1,1));
// BACK
add_face(pos, norm, cols, tex,
v3(p,n,p),v3(n,n,p),
v3(n,p,p),v3(p,p,p),
v3(0,0,1),v4(1,1,1,1));
// TOP
add_face(pos, norm, cols, tex,
v3(n,p,n),v3(p,p,n),
v3(p,p,p),v3(n,p,p),
v3(0,1,0),v4(1,1,1,1));
// BOTTOM
add_face(pos, norm, cols, tex,
v3(n,n,p),v3(p,n,p),
v3(p,n,n),v3(n,n,n),
v3(0,-1,0),v4(1,1,1,1));
// LEFT
add_face(pos, norm, cols, tex,
v3(n,n,p),v3(n,n,n),
v3(n,p,n),v3(n,p,p),
v3(-1,0,0),v4(1,1,1,1));
// RIGHT
add_face(pos, norm, cols, tex,
v3(p,n,n),v3(p,n,p),
v3(p,p,p),v3(p,p,n),
v3(1,0,0),v4(1,1,1,1));
model->set_vertices(pos);
model->set_normals(norm);
model->set_colors(cols);
model->set_texcoords(tex);
return model;
}
Model* Primitives::create_quad(const float w, const float h)
{
Model* model = new Model();
std::vector<v3> pos;
std::vector<v3> norm;
std::vector<v4> cols;
std::vector<v2> tex;
add_face(pos, norm, cols, tex,
v3( -w/2.0f, -h/2.0f, 0),v3( w/2.0f, h/2.0f, 0),
v3( w/2.0f, h/2.0f, 0),v3(-w/2.0f, h/2.0f,0),
v3(0,0,-1),v4(1,1,1,1));
model->set_vertices(pos);
model->set_normals(norm);
model->set_colors(cols);
model->set_texcoords(tex);
return model;
}
/*
void make_cube(Model& model, glm::vec4 col, glm::vec3 pos, float scale)
{
float n = -0.5f;
float p = 0.5f;
std::vector<glm::vec3> verts;
std::vector<glm::vec4> colors;
std::vector<glm::vec2> texcoords;
// FRONT
verts.emplace_back(pos + glm::vec3(n,n,n) * scale);
verts.emplace_back(pos + glm::vec3(p,n,n) * scale);
verts.emplace_back(pos + glm::vec3(p,p,n) * scale);
verts.emplace_back(pos + glm::vec3(n,n,n) * scale);
verts.emplace_back(pos + glm::vec3(p,p,n) * scale);
verts.emplace_back(pos + glm::vec3(n,p,n) * scale);
colors.emplace_back(col); colors.emplace_back(col); colors.emplace_back(col);
colors.emplace_back(col); colors.emplace_back(col); colors.emplace_back(col);
texcoords.emplace_back(0,0); texcoords.emplace_back(1,0); texcoords.emplace_back(1,1);
texcoords.emplace_back(0,0); texcoords.emplace_back(1,1); texcoords.emplace_back(0,1);
// TOP
verts.emplace_back(pos + glm::vec3(n,p,n) * scale);
verts.emplace_back(pos + glm::vec3(p,p,p) * scale);
verts.emplace_back(pos + glm::vec3(p,p,n) * scale);
verts.emplace_back(pos + glm::vec3(n,p,n) * scale);
verts.emplace_back(pos + glm::vec3(p,p,p) * scale);
verts.emplace_back(pos + glm::vec3(n,p,p) * scale);
colors.emplace_back(col); colors.emplace_back(col); colors.emplace_back(col);
colors.emplace_back(col); colors.emplace_back(col); colors.emplace_back(col);
texcoords.emplace_back(0,0); texcoords.emplace_back(1,0); texcoords.emplace_back(1,1);
texcoords.emplace_back(0,0); texcoords.emplace_back(1,1); texcoords.emplace_back(0,1);
// LEFT
verts.emplace_back(pos + glm::vec3(n,n,p) * scale);
verts.emplace_back(pos + glm::vec3(n,p,n) * scale);
verts.emplace_back(pos + glm::vec3(n,n,n) * scale);
verts.emplace_back(pos + glm::vec3(n,n,p) * scale);
verts.emplace_back(pos + glm::vec3(n,p,n) * scale);
verts.emplace_back(pos + glm::vec3(n,p,p) * scale);
colors.emplace_back(col); colors.emplace_back(col); colors.emplace_back(col);
colors.emplace_back(col); colors.emplace_back(col); colors.emplace_back(col);
texcoords.emplace_back(0,0); texcoords.emplace_back(1,0); texcoords.emplace_back(1,1);
texcoords.emplace_back(0,0); texcoords.emplace_back(1,1); texcoords.emplace_back(0,1);
// RIGHT
verts.emplace_back(pos + glm::vec3(p,n,n) * scale);
verts.emplace_back(pos + glm::vec3(p,n,p) * scale);
verts.emplace_back(pos + glm::vec3(p,p,p) * scale);
verts.emplace_back(pos + glm::vec3(p,n,n) * scale);
verts.emplace_back(pos + glm::vec3(p,p,p) * scale);
verts.emplace_back(pos + glm::vec3(p,p,n) * scale);
colors.emplace_back(col); colors.emplace_back(col); colors.emplace_back(col);
colors.emplace_back(col); colors.emplace_back(col); colors.emplace_back(col);
texcoords.emplace_back(0,0); texcoords.emplace_back(1,0); texcoords.emplace_back(1,1);
texcoords.emplace_back(0,0); texcoords.emplace_back(1,1); texcoords.emplace_back(0,1);
// BOTTOM
verts.emplace_back(pos + glm::vec3(n,n,p) * scale);
verts.emplace_back(pos + glm::vec3(p,n,p) * scale);
verts.emplace_back(pos + glm::vec3(p,n,n) * scale);
verts.emplace_back(pos + glm::vec3(n,n,p) * scale);
verts.emplace_back(pos + glm::vec3(p,n,n) * scale);
verts.emplace_back(pos + glm::vec3(n,n,n) * scale);
colors.emplace_back(col); colors.emplace_back(col); colors.emplace_back(col);
colors.emplace_back(col); colors.emplace_back(col); colors.emplace_back(col);
texcoords.emplace_back(0,0); texcoords.emplace_back(1,0); texcoords.emplace_back(1,1);
texcoords.emplace_back(0,0); texcoords.emplace_back(1,1); texcoords.emplace_back(0,1);
// BACK
verts.emplace_back(pos + glm::vec3(n,n,p) * scale);
verts.emplace_back(pos + glm::vec3(p,p,p) * scale);
verts.emplace_back(pos + glm::vec3(p,n,p) * scale);
verts.emplace_back(pos + glm::vec3(n,n,p) * scale);
verts.emplace_back(pos + glm::vec3(n,p,p) * scale);
verts.emplace_back(pos + glm::vec3(p,p,p) * scale);
colors.emplace_back(col); colors.emplace_back(col); colors.emplace_back(col);
colors.emplace_back(col); colors.emplace_back(col); colors.emplace_back(col);
texcoords.emplace_back(0,0); texcoords.emplace_back(1,0); texcoords.emplace_back(1,1);
texcoords.emplace_back(0,0); texcoords.emplace_back(1,1); texcoords.emplace_back(0,1);
model.set_vertices(verts);
model.set_colors(colors);
model.set_texcoords(texcoords);
}
*/ | 27.867769 | 87 | 0.668298 | PatrickDahlin |
99fd76bb3603af515c1cebf7a7aa4e300efa562c | 17,006 | cpp | C++ | src/LevScene/LevSceneUtil.cpp | wakare/Leviathan | 8a488f014d6235c5c6e6422c9f53c82635b7ebf7 | [
"MIT"
] | 3 | 2019-03-05T13:05:30.000Z | 2019-12-16T05:56:21.000Z | src/LevScene/LevSceneUtil.cpp | wakare/Leviathan | 8a488f014d6235c5c6e6422c9f53c82635b7ebf7 | [
"MIT"
] | null | null | null | src/LevScene/LevSceneUtil.cpp | wakare/Leviathan | 8a488f014d6235c5c6e6422c9f53c82635b7ebf7 | [
"MIT"
] | null | null | null | #include "LevSceneUtil.h"
#include "LevMeshObject.h"
#include "LevSceneObject.h"
#include "LevRAttrRenderObjectAttributeBinder.h"
namespace Leviathan
{
namespace Scene
{
bool LevSceneUtil::InitSceneNodeWithMeshFile(const char * mesh_file, unsigned scene_object_mask, LSPtr<LevSceneNode>& out_scene_node)
{
LSPtr<LevMeshObject> mesh_object = new LevMeshObject;
EXIT_IF_FALSE(mesh_object->LoadMeshFile(mesh_file));
LSPtr<LevSceneObject> scene_object = new LevSceneObject(scene_object_mask);
EXIT_IF_FALSE(scene_object->SetObjectDesc(TryCast<LevMeshObject, LevSceneObjectDescription>(mesh_object)));
out_scene_node.Reset(new LevSceneNode(scene_object));
return true;
}
// TODO: Handle different bind_type
bool LevSceneUtil::BindMeshDataToRenderAttribute(LevSceneNode& node, int bind_type_mask)
{
const Scene::LevMeshObject* meshes = dynamic_cast<const Scene::LevMeshObject*>(&node.GetNodeData()->GetObjectDesc());
EXIT_IF_FALSE(meshes);
// Bind attributes
size_t primitive_vertex_count = 0;
size_t vertex_count = 0;
for (auto& mesh : meshes->GetMesh())
{
primitive_vertex_count += mesh->GetPrimitiveCount();
vertex_count += mesh->GetVertexCount();
}
LSPtr<RAIIBufferData> index_buffer = new RAIIBufferData(3 * sizeof(unsigned) * primitive_vertex_count);
LSPtr<RAIIBufferData> vertex_buffer = new RAIIBufferData(3 * sizeof(float) * vertex_count);
unsigned last_index = 0;
unsigned* index_buffer_pointer = static_cast<unsigned*>(index_buffer->GetArrayData());
float* vertex_buffer_pointer = static_cast<float*>(vertex_buffer->GetArrayData());
for (auto& mesh : meshes->GetMesh())
{
const auto sub_mesh_vertex_count = mesh->GetVertexCount();
const auto sub_mesh_index_count = mesh->GetPrimitiveCount();
const auto* vertex_array = mesh->GetVertex3DCoordArray();
memcpy(vertex_buffer_pointer, vertex_array, 3 * sizeof(float) * sub_mesh_vertex_count);
unsigned* index = mesh->GetPrimitiveIndexArray();
for (unsigned i = 0; i < 3 * sub_mesh_index_count; i++)
{
index_buffer_pointer[0] = index[i] + last_index;
index_buffer_pointer++;
}
last_index += sub_mesh_vertex_count;
vertex_buffer_pointer += 3 * sub_mesh_vertex_count;
}
LSPtr<Scene::LevRAttrRenderObjectAttributeBinder> attribute_binder = new Scene::LevRAttrRenderObjectAttributeBinder(vertex_count);
attribute_binder->BindAttribute(0, new LevRenderObjectAttribute(Scene::RenderObjectAttributeType::EROAT_FLOAT, 3 * sizeof(float), vertex_buffer));
attribute_binder->SetIndexAttribute(new LevRenderObjectAttribute(Scene::RenderObjectAttributeType::EROAT_UINT, sizeof(unsigned), index_buffer));
node.GetNodeData()->AddAttribute(TryCast<Scene::LevRAttrRenderObjectAttributeBinder, Scene::LevSceneObjectAttribute>(attribute_binder));
return true;
}
bool LevSceneUtil::GenerateEmptySceneNode(LSPtr<LevSceneNode>& out)
{
const LSPtr<LevSceneObject> empty_object = new LevSceneObject(ELSOT_EMPTY);
out.Reset(new LevSceneNode(empty_object));
return true;
}
bool LevSceneUtil::GenerateCube(const float* cube_center, float cube_length, LSPtr<LevSceneNode>& out_cube_node)
{
LSPtr<RAIIBufferData> vertices_buffer = new RAIIBufferData(8 * 3 * sizeof(float));
float* data = static_cast<float*>(vertices_buffer->GetArrayData());
LSPtr<RAIIBufferData> normal_buffer = new RAIIBufferData(8 * 3 * sizeof(float));
float* normal_data = static_cast<float*>(vertices_buffer->GetArrayData());
float _cube[] =
{
-cube_length, -cube_length, -cube_length,
-cube_length, -cube_length, cube_length,
-cube_length, cube_length, -cube_length,
-cube_length, cube_length, cube_length,
cube_length, -cube_length, -cube_length,
cube_length, -cube_length, cube_length,
cube_length, cube_length, -cube_length,
cube_length, cube_length, cube_length
};
for (unsigned i = 0; i < 8; i++)
{
_cube[3 * i] += cube_center[0];
_cube[3 * i + 1] += cube_center[1];
_cube[3 * i + 2] += cube_center[2];
}
memcpy(data, _cube, sizeof(_cube));
const float NORMAL_PART_VALUE = 0.57735f;
float _normal[] =
{
-NORMAL_PART_VALUE, -NORMAL_PART_VALUE, -NORMAL_PART_VALUE,
-NORMAL_PART_VALUE, -NORMAL_PART_VALUE, NORMAL_PART_VALUE,
-NORMAL_PART_VALUE, NORMAL_PART_VALUE, -NORMAL_PART_VALUE,
-NORMAL_PART_VALUE, NORMAL_PART_VALUE, NORMAL_PART_VALUE,
NORMAL_PART_VALUE, -NORMAL_PART_VALUE, -NORMAL_PART_VALUE,
NORMAL_PART_VALUE, -NORMAL_PART_VALUE, NORMAL_PART_VALUE,
NORMAL_PART_VALUE, NORMAL_PART_VALUE, -NORMAL_PART_VALUE,
NORMAL_PART_VALUE, NORMAL_PART_VALUE, NORMAL_PART_VALUE,
};
memcpy(normal_data, _normal, sizeof(_normal));
LSPtr<RAIIBufferData> indices_buffer = new RAIIBufferData(6 * 2 * 3 * sizeof(unsigned));
unsigned* indices_data = static_cast<unsigned*>(indices_buffer->GetArrayData());
unsigned indices[] =
{
0, 3, 1,
0, 2, 3,
0, 2, 6,
0, 6, 4,
0, 1, 5,
0, 5, 4,
7, 6, 4,
7, 4, 5,
7, 5, 1,
7, 1, 3,
7, 6, 2,
7, 2, 3
};
memcpy(indices_data, indices, sizeof(indices));
LSPtr<LevRAttrRenderObjectAttributeBinder> attribute_binder = new LevRAttrRenderObjectAttributeBinder(8);
LSPtr<LevRenderObjectAttribute> vertices_attribute = new LevRenderObjectAttribute(EROAT_FLOAT, 3 * sizeof(float), vertices_buffer);
attribute_binder->BindAttribute(0, vertices_attribute);
LSPtr<LevRenderObjectAttribute> normals_attribute = new LevRenderObjectAttribute(EROAT_FLOAT, 3 * sizeof(float), normal_buffer);
attribute_binder->BindAttribute(1, normals_attribute);
LSPtr<LevRenderObjectAttribute> index_attribute = new LevRenderObjectAttribute(EROAT_UINT, sizeof(unsigned), indices_buffer);
attribute_binder->SetIndexAttribute(index_attribute);
LSPtr<LevSceneObject> object = new LevSceneObject(ELSOT_DYNAMIC);
object->AddAttribute(TryCast<LevRAttrRenderObjectAttributeBinder, LevSceneObjectAttribute>(attribute_binder));
out_cube_node.Reset(new LevSceneNode(object));
return true;
}
bool LevSceneUtil::GenerateBallNode(const float* ball_center, float ball_radius, LSPtr<LevSceneNode>& out_ball_node)
{
constexpr float angle_delta = 15.0f * PI_FLOAT / 180.0f;
constexpr size_t step_count = 2 * PI_FLOAT / angle_delta;
Eigen::Vector3f current_scan_half_ball[step_count + 1];
// Init base scan line
for (size_t i = 0; i <= step_count; i++)
{
float coord[] = { sinf(angle_delta * i) , cosf(angle_delta * i) , 0.0f };
memcpy(current_scan_half_ball[i].data(), coord, 3 * sizeof(float));
}
// Generate step rotation matrix (Rotate with x axis)
Eigen::Matrix3f rotation_step;
float rotation[] =
{
1.0f, 0.0f, 0.0f,
0.0f, cosf(angle_delta), sinf(angle_delta),
0.0f, -sinf(angle_delta), cosf(angle_delta),
};
memcpy(rotation_step.data(), rotation, sizeof(rotation));
std::vector<Eigen::Vector3f> m_vertices;
std::vector<Eigen::Vector3f> m_normals;
std::vector<unsigned> m_indices;
unsigned current_index_offset = 0;
for (auto& vertex : current_scan_half_ball)
{
m_vertices.push_back(vertex);
}
/*
Current scan line: 0 - 1 - 2 - 3 - 4 - 5
| / | / | / | / | / |
Next scan line: 6 - 7 - 8 - 9 - 10- 11
*/
unsigned index_delta[2 * 3 * step_count];
for (size_t i = 0; i < step_count; i++)
{
unsigned* data = index_delta + 2 * 3 * i;
data[0] = i;
data[1] = i + 1;
data[2] = step_count + 1 + i;
data[3] = data[2];
data[4] = data[1];
data[5] = data[2] + 1;
}
for (size_t i = 0; i < step_count; i++)
{
Eigen::Vector3f next_scan_half_ball[step_count + 1];
for (size_t j = 0; j <= step_count; j++)
{
next_scan_half_ball[j] = rotation_step * current_scan_half_ball[j];
m_vertices.push_back(next_scan_half_ball[j]);
}
for (auto index : index_delta)
{
m_indices.push_back(index + current_index_offset);
}
memcpy(current_scan_half_ball->data(), next_scan_half_ball->data(), sizeof(next_scan_half_ball));
current_index_offset += (step_count + 1);
}
// calculate normals
size_t vertices_count = m_vertices.size();
for (size_t i = 0; i < vertices_count; i++)
{
m_normals.push_back(m_vertices[i].normalized());
}
// Do radius scale
Eigen::Vector3f ball_center_vector; memcpy(ball_center_vector.data(), ball_center, 3 * sizeof(float));
for (size_t i = 0; i < m_vertices.size(); i++)
{
auto& vertex = m_vertices[i];
vertex *= ball_radius;
vertex += ball_center_vector;
}
// Convert vertices data
LSPtr<RAIIBufferData> vertices_buffer_data = new RAIIBufferData(m_vertices.size() * 3 * sizeof(float));
float* coord_data = static_cast<float*>(vertices_buffer_data->GetArrayData());
for (size_t i = 0; i < m_vertices.size(); i++)
{
float* data = coord_data + 3 * i;
memcpy(data, m_vertices[i].data(), 3 * sizeof(float));
}
LSPtr<RAIIBufferData> normals_buffer_data = new RAIIBufferData(m_normals.size() * 3 * sizeof(float));
float* normal_data = static_cast<float*>(normals_buffer_data->GetArrayData());
for (size_t i = 0; i < m_normals.size(); i++)
{
float* data = normal_data + 3 * i;
memcpy(data, m_normals[i].data(), 3 * sizeof(float));
}
LSPtr<LevRAttrRenderObjectAttributeBinder> attribute_binder = new LevRAttrRenderObjectAttributeBinder(m_vertices.size());
LSPtr<LevRenderObjectAttribute> vertices_attribute = new LevRenderObjectAttribute(EROAT_FLOAT, 3 * sizeof(float), vertices_buffer_data);
attribute_binder->BindAttribute(0, vertices_attribute);
LSPtr<LevRenderObjectAttribute> normals_attribute = new LevRenderObjectAttribute(EROAT_FLOAT, 3 * sizeof(float), normals_buffer_data);
attribute_binder->BindAttribute(1, normals_attribute);
LSPtr<RAIIBufferData> indices_buffer_data = new RAIIBufferData(m_indices.size() * sizeof(unsigned));
unsigned* indices_data = static_cast<unsigned*>(indices_buffer_data->GetArrayData());
for (size_t i = 0; i < m_indices.size(); i++)
{
unsigned* data = indices_data + i;
*data = m_indices[i];
}
LSPtr<LevRenderObjectAttribute> index_attribute = new LevRenderObjectAttribute(EROAT_UINT, sizeof(unsigned), indices_buffer_data);
attribute_binder->SetIndexAttribute(index_attribute);
LSPtr<LevSceneObject> object = new LevSceneObject(ELSOT_DYNAMIC);
object->AddAttribute(TryCast<LevRAttrRenderObjectAttributeBinder, LevSceneObjectAttribute>(attribute_binder));
out_ball_node.Reset(new LevSceneNode(object));
return true;
}
bool LevSceneUtil::GeneratePlaneNode(const float* plane_node0, const float* plane_node1, const float* plane_node2, const float* plane_node3, LSPtr<LevSceneNode>& out_plane_node)
{
float vertices[12];
memcpy(vertices, plane_node0, 3 * sizeof(float));
memcpy(vertices + 3, plane_node1, 3 * sizeof(float));
memcpy(vertices + 6, plane_node2, 3 * sizeof(float));
memcpy(vertices + 9, plane_node3, 3 * sizeof(float));
LSPtr<RAIIBufferData> vertices_buffer_data = new RAIIBufferData(sizeof(vertices));
memcpy(vertices_buffer_data->GetArrayData(), vertices, sizeof(vertices));
/*
Calculate plane normal
*/
Eigen::Vector3f edge0;
edge0.x() = plane_node0[0] - plane_node1[0];
edge0.y() = plane_node0[1] - plane_node1[1];
edge0.z() = plane_node0[2] - plane_node1[2];
Eigen::Vector3f edge1;
edge1.x() = plane_node1[0] - plane_node2[0];
edge1.y() = plane_node1[1] - plane_node2[1];
edge1.z() = plane_node1[2] - plane_node2[2];
Eigen::Vector3f normal;
normal = edge0.cross(edge1);
normal.normalize();
LSPtr<RAIIBufferData> normals_buffer_data = new RAIIBufferData(sizeof(vertices));
float* normal_data = static_cast<float*>(normals_buffer_data->GetArrayData());
for (size_t i = 0; i < 4; i++)
{
memcpy(normal_data + 3 * i, normal.data(), 3 * sizeof(float));
}
LSPtr<LevRenderObjectAttribute> vertex_attibute = new LevRenderObjectAttribute(EROAT_FLOAT, 3 * sizeof(float), vertices_buffer_data);
LSPtr<LevRenderObjectAttribute> normal_attribute = new LevRenderObjectAttribute(EROAT_FLOAT, 3 * sizeof(float), normals_buffer_data);
unsigned indexs[6] =
{
0, 1, 2,
0, 2, 3
};
LSPtr<RAIIBufferData> index_buffer_data = new RAIIBufferData(sizeof(indexs));
memcpy(index_buffer_data->GetArrayData(), indexs, sizeof(indexs));
LSPtr<LevRenderObjectAttribute> index_attribute = new LevRenderObjectAttribute(EROAT_UINT, sizeof(unsigned), index_buffer_data);
LSPtr<LevRAttrRenderObjectAttributeBinder> attribute_binder = new LevRAttrRenderObjectAttributeBinder(4);
attribute_binder->BindAttribute(0, vertex_attibute);
attribute_binder->BindAttribute(1, normal_attribute);
attribute_binder->SetIndexAttribute(index_attribute);
LSPtr<LevSceneObject> plane_object = new LevSceneObject(ELSOT_DYNAMIC);
plane_object->AddAttribute(TryCast<LevRAttrRenderObjectAttributeBinder, LevSceneObjectAttribute>(attribute_binder));
out_plane_node.Reset(new LevSceneNode(plane_object));
return true;
}
bool LevSceneUtil::GeneratePoints(const float* vertices, const float* normals,
unsigned count, LSPtr<LevSceneNode>& out_points_node)
{
LSPtr<LevRAttrRenderObjectAttributeBinder> attribute_binder = new LevRAttrRenderObjectAttributeBinder(count);
LSPtr<RAIIBufferData> vertices_data = new RAIIBufferData(count * 3 * sizeof(float));
memcpy(vertices_data->GetArrayData(), vertices, 3 * count * sizeof(float));
LSPtr<LevRenderObjectAttribute> vertices_attribute = new LevRenderObjectAttribute(EROAT_FLOAT, 3 * sizeof(float), vertices_data);
attribute_binder->BindAttribute(0, vertices_attribute);
if (normals)
{
LSPtr<RAIIBufferData> normals_data = new RAIIBufferData(count * 3 * sizeof(float));
memcpy(normals_data->GetArrayData(), normals, 3 * count * sizeof(float));
LSPtr<LevRenderObjectAttribute> normals_attribute = new LevRenderObjectAttribute(EROAT_FLOAT, 3 * count * sizeof(float), normals_data);
attribute_binder->BindAttribute(1, normals_attribute);
}
attribute_binder->SetPrimitiveType(EROPT_POINTS);
LSPtr<LevSceneObject> point_object = new LevSceneObject(ELSOT_DYNAMIC);
point_object->AddAttribute(attribute_binder);
out_points_node.Reset(new LevSceneNode(point_object));
return true;
}
bool LevSceneUtil::GenerateIdentityMatrixUniform(const char* uniform_name, LSPtr<LevNumericalUniform>& out_uniform)
{
static float identity_matrix[] =
{
1.0f, 0.0f, 0.0f, 0.0f,
0.0f, 1.0f, 0.0f, 0.0f,
0.0f, 0.0f, 1.0f, 0.0f,
0.0f, 0.0f, 0.0f, 1.0f
};
out_uniform.Reset(new LevNumericalUniform(uniform_name, TYPE_FLOAT_MAT4));
LSPtr<RAIIBufferData> identity_matrix_buffer_data = new RAIIBufferData(sizeof(identity_matrix));
identity_matrix_buffer_data->SetArrayData(identity_matrix, sizeof(identity_matrix));
out_uniform->SetData(identity_matrix_buffer_data);
return true;
}
bool LevSceneUtil::GenerateLookAtMatrixUniform(const char* uniform_name, const float* eye, const float* target,
const float* up, LSPtr<LevNumericalUniform>& out_uniform)
{
Eigen::Vector3f N, U, V;
Eigen::Vector3f veye; memcpy(veye.data(), eye, 3 * sizeof(float));
Eigen::Vector3f vup; memcpy(vup.data(), up, 3 * sizeof(float));
Eigen::Vector3f vlookat; memcpy(vlookat.data(), target, 3 * sizeof(float));
N = vlookat - veye;
N.normalize();
U = vup.cross(N);
U.normalize();
V = N.cross(U);
V.normalize();
float data[16] =
{
U[0], U[1], U[2], 0.0f,
V[0], V[1], V[2], 0.0f,
N[0], N[1], N[2], 0.0f,
-U.dot(veye), -V.dot(veye), -N.dot(veye), 1.0f,
};
out_uniform.Reset(new LevNumericalUniform(uniform_name, TYPE_FLOAT_MAT4));
LSPtr<RAIIBufferData> identity_matrix_buffer_data = new RAIIBufferData(sizeof(data));
identity_matrix_buffer_data->SetArrayData(data, sizeof(data));
out_uniform->SetData(identity_matrix_buffer_data);
return true;
}
bool LevSceneUtil::GenerateProjectionMatrix(const char* uniform_name, float fov, float aspect, float near, float far, LSPtr<LevNumericalUniform>& out_uniform)
{
float T = tanf(fov / 2.0f);
float N = near - far;
float M = near + far;
float K = aspect * T;
float L = far * near;
float data[16] =
{
1.0f / K, 0.0f, 0.0f, 0.0f,
0.0f, 1.0f / T, 0.0f, 0.0f,
0.0f, 0.0f, -M / N, 1.0f,
0.0f, 0.0f, 2 * L / N, 0.0f
};
out_uniform.Reset(new LevNumericalUniform(uniform_name, TYPE_FLOAT_MAT4));
LSPtr<RAIIBufferData> identity_matrix_buffer_data = new RAIIBufferData(sizeof(data));
identity_matrix_buffer_data->SetArrayData(data, sizeof(data));
out_uniform->SetData(identity_matrix_buffer_data);
return true;
}
}
} | 36.730022 | 179 | 0.711043 | wakare |
8200dabecfc445f3828d119c8d6f6b47f8c17d3d | 2,409 | cpp | C++ | TileServer und Tiles/filereader.cpp | andr1312e/Russia-Tiles-Server | c1d596b84e22c170ba0f795ed6e2bfb80167eeb6 | [
"Unlicense"
] | null | null | null | TileServer und Tiles/filereader.cpp | andr1312e/Russia-Tiles-Server | c1d596b84e22c170ba0f795ed6e2bfb80167eeb6 | [
"Unlicense"
] | null | null | null | TileServer und Tiles/filereader.cpp | andr1312e/Russia-Tiles-Server | c1d596b84e22c170ba0f795ed6e2bfb80167eeb6 | [
"Unlicense"
] | null | null | null | #include "filereader.h"
ImageRotator::ImageRotator(const QString *pathToSourceSvg, const QString *pathToRendedImage, const QString *fileType, const QString *slash, const QString *svgType, QObject *parent)
: QObject(parent)
, m_file(new QFile())
, m_pathToSourceSvgFolder(pathToSourceSvg)
, m_pathToRendedImageFolder(pathToRendedImage)
, m_fileType(fileType)
, m_slash(slash)
, m_svgType(svgType)
, m_image(new QImage(497, 279, QImage::Format_RGB32))
, m_renderer(new QSvgRenderer())
, m_painter(new QPainter(m_image))
, index(100)
, m_previousCharInArray(' ')
, m_array(Q_NULLPTR)
{
m_painter->setCompositionMode(QPainter::CompositionMode_SourceOver);
m_painter->setRenderHints(QPainter::Antialiasing, true);
m_renderer->setFramesPerSecond(0);
}
ImageRotator::~ImageRotator()
{
delete m_file;
delete m_image;
delete m_renderer;
delete m_painter;
}
void ImageRotator::setParams(QString &tile, QString &azm, QString &layer, char &firstNum, char &secondNum, char &thirdNum)
{
m_pathToSource.append(*m_pathToSourceSvgFolder).append(layer).append(*m_slash).append(tile).append(*m_svgType);
m_pathToRender.append(*m_pathToRendedImageFolder).append(layer).append(*m_slash).append(azm).append(*m_slash).append(tile).append(*m_fileType);
m_firstNum=firstNum;
m_secondNum=secondNum;
m_thirdNum=thirdNum;
}
void ImageRotator::doing()
{
m_file->setFileName(m_pathToSource);
m_file->open(QIODevice::ReadOnly);
m_array=m_file->readAll();
m_file->close();
for (index; index<m_array.size()-10; index=index+1)
{
if(m_previousCharInArray=='('&&m_array.at(index)==' '&&m_array.at(index+1)==' ')
{
m_array.operator[](index+2)=m_firstNum;
m_array.operator[](index+3)=m_secondNum;
m_array.operator[](index+4)=m_thirdNum;
index=index+60;
}
m_previousCharInArray=m_array.at(index);
}
m_renderer->load(m_array);
m_renderer->render(m_painter);
m_image->save(m_pathToRender);
index=40;
// m_file->setFileName(*m_pathToSourceSvg+m_layer+ "_1"+*m_slash+m_tileName+*m_svgType);
// m_file->open(QIODevice::WriteOnly);
// m_file->write(m_array);
// m_file->flush();
// m_file->close();
m_pathToSource.clear();
m_pathToRender.clear();
m_previousCharInArray=' ';
Q_EMIT finished();
}
| 34.913043 | 180 | 0.689913 | andr1312e |
8201f063c0e7940d8b744a3f528d45a102d272c5 | 9,937 | cpp | C++ | Classes/stk-4.4.1/src/Mesh2D.cpp | jongwook/urMus | b3d22e8011253f137a3581e84db8e79accccc7a4 | [
"MIT",
"AML",
"BSD-3-Clause"
] | 1 | 2015-11-05T00:50:07.000Z | 2015-11-05T00:50:07.000Z | Classes/stk-4.4.1/src/Mesh2D.cpp | jongwook/urMus | b3d22e8011253f137a3581e84db8e79accccc7a4 | [
"MIT",
"AML",
"BSD-3-Clause"
] | null | null | null | Classes/stk-4.4.1/src/Mesh2D.cpp | jongwook/urMus | b3d22e8011253f137a3581e84db8e79accccc7a4 | [
"MIT",
"AML",
"BSD-3-Clause"
] | null | null | null | /***************************************************/
/*! \class Mesh2D
\brief Two-dimensional rectilinear waveguide mesh class.
This class implements a rectilinear,
two-dimensional digital waveguide mesh
structure. For details, see Van Duyne and
Smith, "Physical Modeling with the 2-D Digital
Waveguide Mesh", Proceedings of the 1993
International Computer Music Conference.
This is a digital waveguide model, making its
use possibly subject to patents held by Stanford
University, Yamaha, and others.
Control Change Numbers:
- X Dimension = 2
- Y Dimension = 4
- Mesh Decay = 11
- X-Y Input Position = 1
by Julius Smith, 2000 - 2002.
Revised by Gary Scavone for STK, 2002.
*/
/***************************************************/
#include "Mesh2D.h"
#include "SKINI-msg.h"
namespace stk {
Mesh2D :: Mesh2D( short nX, short nY )
{
this->setNX(nX);
this->setNY(nY);
StkFloat pole = 0.05;
short i;
for (i=0; i<NYMAX; i++) {
filterY_[i].setPole( pole );
filterY_[i].setGain( 0.99 );
}
for (i=0; i<NXMAX; i++) {
filterX_[i].setPole( pole );
filterX_[i].setGain( 0.99 );
}
this->clearMesh();
counter_=0;
xInput_ = 0;
yInput_ = 0;
}
Mesh2D :: ~Mesh2D( void )
{
}
void Mesh2D :: clear( void )
{
this->clearMesh();
short i;
for (i=0; i<NY_; i++)
filterY_[i].clear();
for (i=0; i<NX_; i++)
filterX_[i].clear();
counter_=0;
}
void Mesh2D :: clearMesh( void )
{
int x, y;
for (x=0; x<NXMAX-1; x++) {
for (y=0; y<NYMAX-1; y++) {
v_[x][y] = 0;
}
}
for (x=0; x<NXMAX; x++) {
for (y=0; y<NYMAX; y++) {
vxp_[x][y] = 0;
vxm_[x][y] = 0;
vyp_[x][y] = 0;
vym_[x][y] = 0;
vxp1_[x][y] = 0;
vxm1_[x][y] = 0;
vyp1_[x][y] = 0;
vym1_[x][y] = 0;
}
}
}
StkFloat Mesh2D :: energy( void )
{
// Return total energy contained in wave variables Note that some
// energy is also contained in any filter delay elements.
int x, y;
StkFloat t;
StkFloat e = 0;
if ( counter_ & 1 ) { // Ready for Mesh2D::tick1() to be called.
for (x=0; x<NX_; x++) {
for (y=0; y<NY_; y++) {
t = vxp1_[x][y];
e += t*t;
t = vxm1_[x][y];
e += t*t;
t = vyp1_[x][y];
e += t*t;
t = vym1_[x][y];
e += t*t;
}
}
}
else { // Ready for Mesh2D::tick0() to be called.
for (x=0; x<NX_; x++) {
for (y=0; y<NY_; y++) {
t = vxp_[x][y];
e += t*t;
t = vxm_[x][y];
e += t*t;
t = vyp_[x][y];
e += t*t;
t = vym_[x][y];
e += t*t;
}
}
}
return(e);
}
void Mesh2D :: setNX( short lenX )
{
NX_ = lenX;
if ( lenX < 2 ) {
errorString_ << "Mesh2D::setNX(" << lenX << "): Minimum length is 2!";
handleError( StkError::WARNING );
NX_ = 2;
}
else if ( lenX > NXMAX ) {
errorString_ << "Mesh2D::setNX(" << lenX << "): Maximum length is " << NXMAX << '!';;
handleError( StkError::WARNING );
NX_ = NXMAX;
}
}
void Mesh2D :: setNY( short lenY )
{
NY_ = lenY;
if ( lenY < 2 ) {
errorString_ << "Mesh2D::setNY(" << lenY << "): Minimum length is 2!";
handleError( StkError::WARNING );
NY_ = 2;
}
else if ( lenY > NYMAX ) {
errorString_ << "Mesh2D::setNY(" << lenY << "): Maximum length is " << NXMAX << '!';;
handleError( StkError::WARNING );
NY_ = NYMAX;
}
}
void Mesh2D :: setDecay( StkFloat decayFactor )
{
StkFloat gain = decayFactor;
if ( decayFactor < 0.0 ) {
errorString_ << "Mesh2D::setDecay: decayFactor value is less than 0.0!";
handleError( StkError::WARNING );
gain = 0.0;
}
else if ( decayFactor > 1.0 ) {
errorString_ << "Mesh2D::setDecay decayFactor value is greater than 1.0!";
handleError( StkError::WARNING );
gain = 1.0;
}
int i;
for (i=0; i<NYMAX; i++)
filterY_[i].setGain( gain );
for (i=0; i<NXMAX; i++)
filterX_[i].setGain( gain );
}
void Mesh2D :: setInputPosition( StkFloat xFactor, StkFloat yFactor )
{
if ( xFactor < 0.0 ) {
errorString_ << "Mesh2D::setInputPosition xFactor value is less than 0.0!";
handleError( StkError::WARNING );
xInput_ = 0;
}
else if ( xFactor > 1.0 ) {
errorString_ << "Mesh2D::setInputPosition xFactor value is greater than 1.0!";
handleError( StkError::WARNING );
xInput_ = NX_ - 1;
}
else
xInput_ = (short) (xFactor * (NX_ - 1));
if ( yFactor < 0.0 ) {
errorString_ << "Mesh2D::setInputPosition yFactor value is less than 0.0!";
handleError( StkError::WARNING );
yInput_ = 0;
}
else if ( yFactor > 1.0 ) {
errorString_ << "Mesh2D::setInputPosition yFactor value is greater than 1.0!";
handleError( StkError::WARNING );
yInput_ = NY_ - 1;
}
else
yInput_ = (short) (yFactor * (NY_ - 1));
}
void Mesh2D :: noteOn( StkFloat frequency, StkFloat amplitude )
{
// Input at corner.
if ( counter_ & 1 ) {
vxp1_[xInput_][yInput_] += amplitude;
vyp1_[xInput_][yInput_] += amplitude;
}
else {
vxp_[xInput_][yInput_] += amplitude;
vyp_[xInput_][yInput_] += amplitude;
}
#if defined(_STK_DEBUG_)
errorString_ << "Mesh2D::NoteOn: frequency = " << frequency << ", amplitude = " << amplitude << ".";
handleError( StkError::DEBUG_WARNING );
#endif
}
void Mesh2D :: noteOff( StkFloat amplitude )
{
#if defined(_STK_DEBUG_)
errorString_ << "Mesh2D::NoteOff: amplitude = " << amplitude << ".";
handleError( StkError::DEBUG_WARNING );
#endif
}
StkFloat Mesh2D :: inputTick( StkFloat input )
{
if ( counter_ & 1 ) {
vxp1_[xInput_][yInput_] += input;
vyp1_[xInput_][yInput_] += input;
lastFrame_[0] = tick1();
}
else {
vxp_[xInput_][yInput_] += input;
vyp_[xInput_][yInput_] += input;
lastFrame_[0] = tick0();
}
counter_++;
return lastFrame_[0];
}
StkFloat Mesh2D :: tick( unsigned int )
{
lastFrame_[0] = ((counter_ & 1) ? this->tick1() : this->tick0());
counter_++;
return lastFrame_[0];
}
const StkFloat VSCALE = 0.5;
StkFloat Mesh2D :: tick0( void )
{
int x, y;
StkFloat outsamp = 0;
// Update junction velocities.
for (x=0; x<NX_-1; x++) {
for (y=0; y<NY_-1; y++) {
v_[x][y] = ( vxp_[x][y] + vxm_[x+1][y] +
vyp_[x][y] + vym_[x][y+1] ) * VSCALE;
}
}
// Update junction outgoing waves, using alternate wave-variable buffers.
for (x=0; x<NX_-1; x++) {
for (y=0; y<NY_-1; y++) {
StkFloat vxy = v_[x][y];
// Update positive-going waves.
vxp1_[x+1][y] = vxy - vxm_[x+1][y];
vyp1_[x][y+1] = vxy - vym_[x][y+1];
// Update minus-going waves.
vxm1_[x][y] = vxy - vxp_[x][y];
vym1_[x][y] = vxy - vyp_[x][y];
}
}
// Loop over velocity-junction boundary faces, update edge
// reflections, with filtering. We're only filtering on one x and y
// edge here and even this could be made much sparser.
for (y=0; y<NY_-1; y++) {
vxp1_[0][y] = filterY_[y].tick(vxm_[0][y]);
vxm1_[NX_-1][y] = vxp_[NX_-1][y];
}
for (x=0; x<NX_-1; x++) {
vyp1_[x][0] = filterX_[x].tick(vym_[x][0]);
vym1_[x][NY_-1] = vyp_[x][NY_-1];
}
// Output = sum of outgoing waves at far corner. Note that the last
// index in each coordinate direction is used only with the other
// coordinate indices at their next-to-last values. This is because
// the "unit strings" attached to each velocity node to terminate
// the mesh are not themselves connected together.
outsamp = vxp_[NX_-1][NY_-2] + vyp_[NX_-2][NY_-1];
return outsamp;
}
StkFloat Mesh2D :: tick1( void )
{
int x, y;
StkFloat outsamp = 0;
// Update junction velocities.
for (x=0; x<NX_-1; x++) {
for (y=0; y<NY_-1; y++) {
v_[x][y] = ( vxp1_[x][y] + vxm1_[x+1][y] +
vyp1_[x][y] + vym1_[x][y+1] ) * VSCALE;
}
}
// Update junction outgoing waves,
// using alternate wave-variable buffers.
for (x=0; x<NX_-1; x++) {
for (y=0; y<NY_-1; y++) {
StkFloat vxy = v_[x][y];
// Update positive-going waves.
vxp_[x+1][y] = vxy - vxm1_[x+1][y];
vyp_[x][y+1] = vxy - vym1_[x][y+1];
// Update minus-going waves.
vxm_[x][y] = vxy - vxp1_[x][y];
vym_[x][y] = vxy - vyp1_[x][y];
}
}
// Loop over velocity-junction boundary faces, update edge
// reflections, with filtering. We're only filtering on one x and y
// edge here and even this could be made much sparser.
for (y=0; y<NY_-1; y++) {
vxp_[0][y] = filterY_[y].tick(vxm1_[0][y]);
vxm_[NX_-1][y] = vxp1_[NX_-1][y];
}
for (x=0; x<NX_-1; x++) {
vyp_[x][0] = filterX_[x].tick(vym1_[x][0]);
vym_[x][NY_-1] = vyp1_[x][NY_-1];
}
// Output = sum of outgoing waves at far corner.
outsamp = vxp1_[NX_-1][NY_-2] + vyp1_[NX_-2][NY_-1];
return outsamp;
}
void Mesh2D :: controlChange( int number, StkFloat value )
{
StkFloat norm = value * ONE_OVER_128;
if ( norm < 0 ) {
norm = 0.0;
errorString_ << "Mesh2D::controlChange: control value less than zero ... setting to zero!";
handleError( StkError::WARNING );
}
else if ( norm > 1.0 ) {
norm = 1.0;
errorString_ << "Mesh2D::controlChange: control value greater than 128.0 ... setting to 128.0!";
handleError( StkError::WARNING );
}
if (number == 2) // 2
this->setNX( (short) (norm * (NXMAX-2) + 2) );
else if (number == 4) // 4
this->setNY( (short) (norm * (NYMAX-2) + 2) );
else if (number == 11) // 11
this->setDecay( 0.9 + (norm * 0.1) );
else if (number == __SK_ModWheel_) // 1
this->setInputPosition( norm, norm );
else {
errorString_ << "Mesh2D::controlChange: undefined control number (" << number << ")!";
handleError( StkError::WARNING );
}
#if defined(_STK_DEBUG_)
errorString_ << "Mesh2D::controlChange: number = " << number << ", value = " << value << ".";
handleError( StkError::DEBUG_WARNING );
#endif
}
} // stk namespace
| 24.780549 | 102 | 0.564456 | jongwook |
820537e1be718f43d856f9bc9d230bb86b3198b4 | 77,729 | cc | C++ | src/Newick.cc | pgajer/MCclassifier | 5da58744a4cc58b6c854efff63534aae50c72258 | [
"Unlicense"
] | 6 | 2016-03-05T04:45:16.000Z | 2021-08-07T06:20:07.000Z | src/Newick.cc | pgajer/MCclassifier | 5da58744a4cc58b6c854efff63534aae50c72258 | [
"Unlicense"
] | 2 | 2016-09-20T18:30:27.000Z | 2016-11-08T17:35:11.000Z | src/Newick.cc | pgajer/MCclassifier | 5da58744a4cc58b6c854efff63534aae50c72258 | [
"Unlicense"
] | 2 | 2016-09-20T16:37:40.000Z | 2017-03-11T23:37:04.000Z | // Author: Adam Phillippy
/*
Copyright (C) 2016 Pawel Gajer (pgajer@gmail.com), Adam Phillippy and Jacques Ravel jravel@som.umaryland.edu
Permission to use, copy, modify, and distribute this software and its
documentation with or without modifications and for any purpose and
without fee is hereby granted, provided that any copyright notices
appear in all copies and that both those copyright notices and this
permission notice appear in supporting documentation, and that the
names of the contributors or copyright holders not be used in
advertising or publicity pertaining to distribution of the software
without specific prior permission.
THE CONTRIBUTORS AND COPYRIGHT HOLDERS OF THIS SOFTWARE DISCLAIM ALL
WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL THE
CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY SPECIAL, 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 <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <queue>
#include <deque>
#include <string>
#include "IOCUtilities.h"
#include "IOCppUtilities.hh"
#include "Newick.hh"
using namespace std;
#define DEBUG 0
//--------------------------------------------- NewickNode_t() -----
NewickNode_t::NewickNode_t(NewickNode_t * parent)
: parent_m(parent)
{
#if DEBUG
fprintf(stderr,"in NewickTree_t(parent)\t(parent==NULL)=%d\n",(int)(parent==NULL));
#endif
if (parent==NULL)
{
#if DEBUG
fprintf(stderr,"in if(parent==NULL)\n");
#endif
depth_m = -1;
}
else
{
#if DEBUG
fprintf(stderr,"in else\n");
#endif
depth_m = parent->depth_m+1;
}
#if DEBUG
fprintf(stderr,"leaving NewickTree_t(parent)\tdepth_m: %d\n", depth_m);
#endif
}
//--------------------------------------------- ~NewickNode_t() -----
NewickNode_t::~NewickNode_t()
{
// for (unsigned int i = 0; i < children_m.size(); i++)
// {
// delete children_m[i];
// }
}
//--------------------------------------------- stitch -----
// make children on the input node the children of the current node
// the children of the input node have the current node as a parent
void NewickNode_t::stitch( NewickNode_t *node )
{
#if DEBUG
fprintf(stderr,"in NewickNode_t::stitch()\n");
#endif
children_m = node->children_m;
int nChildren = children_m.size();
for ( int i = 0; i < nChildren; i++ )
{
children_m[i]->parent_m = this;
}
#if DEBUG
fprintf(stderr,"leaving NewickNode_t::stitch()\n");
#endif
}
//--------------------------------------------- addChild -----
NewickNode_t * NewickNode_t::addChild()
{
#if DEBUG
fprintf(stderr,"in addChild()\n");
#endif
NewickNode_t * child = new NewickNode_t(this);
#if DEBUG
fprintf(stderr,"before children_m.size()\n");
//fprintf(stderr,"children_m.size()=%d\n",(int)children_m.size());
#endif
children_m.push_back(child);
#if DEBUG
fprintf(stderr,"leaving addChild()\n");
#endif
return child;
}
//--------------------------------------------- NewickTree_t -----
NewickTree_t::NewickTree_t()
: root_m(NULL), nLeaves_m(0), minIdx_m(-1)
{
#if DEBUG
fprintf(stderr,"in NewickTree_t()\n");
#endif
}
//--------------------------------------------- ~NewickTree_t -----
NewickTree_t::~NewickTree_t()
{
delete root_m;
}
//--------------------------------------------- rmLeaf -----
// remove leaf with label s
void NewickTree_t::rmLeaf( string &s )
{
queue<NewickNode_t *> bfs2;
bfs2.push(root_m);
int numChildren;
NewickNode_t *pnode;
NewickNode_t *node;
bool go = true;
while ( !bfs2.empty() && go )
{
node = bfs2.front();
bfs2.pop();
numChildren = node->children_m.size();
if ( numChildren )
{
for (int i = 0; i < numChildren; i++)
{
bfs2.push(node->children_m[i]);
}
}
else if ( node->label == s )
{
pnode = node->parent_m;
// identify which element of pnode->children_m vector is s
int n = pnode->children_m.size();
for ( int i = 0; i < n; ++i )
if ( pnode->children_m[i]->label == s )
{
pnode->children_m.erase ( pnode->children_m.begin() + i );
go = false;
break;
}
}
} // end of while() loop
}
//--------------------------------------------- rmNodesWith1child -----
// remove nodes with only one child
void NewickTree_t::rmNodesWith1child()
{
queue<NewickNode_t *> bfs2;
bfs2.push(root_m);
int numChildren;
NewickNode_t *pnode;
NewickNode_t *node;
while ( !bfs2.empty() )
{
node = bfs2.front();
bfs2.pop();
while ( node->children_m.size() == 1 )
{
// finding node in a children array of the parent node
pnode = node->parent_m;
numChildren = pnode->children_m.size();
#if DEBUG_LFTT
fprintf(stderr, "\n\nNode %s has only one child %s; %s's parent is %s with %d children\n",
node->label.c_str(), node->children_m[0]->label.c_str(), node->label.c_str(),
pnode->label.c_str(), numChildren);
#endif
int i;
for ( i = 0; i < numChildren; i++)
{
if ( pnode->children_m[i] == node )
break;
}
if ( i == numChildren )
{
fprintf(stderr, "ERROR in %s at line %d: node %s cannot be found in %s\n",
__FILE__, __LINE__,(node->label).c_str(), (pnode->label).c_str());
exit(1);
}
#if DEBUG_LFTT
fprintf(stderr, "%s is the %d-th child of %s\n",
node->label.c_str(), i, pnode->label.c_str());
fprintf(stderr, "%s children BEFORE change: ", pnode->label.c_str());
for ( int j = 0; j < numChildren; j++)
fprintf(stderr, "%s ", pnode->children_m[j]->label.c_str());
#endif
node = node->children_m[0];
pnode->children_m[i] = node;
node->parent_m = pnode;
#if DEBUG_LFTT
fprintf(stderr, "\n%s children AFTER change: ", pnode->label.c_str());
for ( int j = 0; j < numChildren; j++)
fprintf(stderr, "%s ", pnode->children_m[j]->label.c_str());
#endif
}
numChildren = node->children_m.size();
if ( numChildren )
{
for (int i = 0; i < numChildren; i++)
{
bfs2.push(node->children_m[i]);
}
}
}
}
//--------------------------------------------- loadTree -----
bool NewickTree_t::loadTree(const char *file)
{
#define DEBUGLT 0
#if DEBUGLT
fprintf(stderr, "in NewickTree_t::loadTree()\n");
#endif
FILE * fp = fOpen(file, "r");
char str[256];
NewickNode_t * cur = new NewickNode_t();
int LINE = 1;
char c;
bool DONE = false;
int leafIdx = 0;
int count = 0;
while ((c = fgetc(fp)) != EOF)
{
#if DEBUGLT
fprintf(stderr,"c=|%c|\tcount=%d\t(cur==NULL)=%d\n", c, count,(int)(cur==NULL));
#endif
count++;
if (c == ';') { DONE = true;}
else if (c == '\n') { LINE++; }
else if (c == ' ') { }
else if (DONE)
{
cerr << "ERROR: Unexpected data after ; on line " << LINE << endl;
return false;
}
else if (c == '(')
{
cur = cur->addChild();
if (root_m == NULL) { root_m = cur; }
}
else if (c == ')') // '):bl,' or '):bl' or ')lable:bl'
{
c = fgetc(fp);
#if DEBUGLT
fprintf(stderr,"in ) next c=%c\n", c);
fprintf(stderr,"in ) minIdx_m=%d\n", minIdx_m);
#endif
cur->idx = minIdx_m;
minIdx_m--;
if ( c == ';' )
{
DONE = 1;
break;
}
else if ( c == ':' )
{
fscanf(fp, "%lf", &cur->branch_length);
}
else if ( isdigit(c) )
{
double bootVal;
fscanf(fp, "%lf:%lf", &bootVal, &cur->branch_length);
}
else if ( isalpha(c) ) // label:digit
{
#if DEBUGLT
fprintf(stderr,"in )alpha=%c\n", c);
#endif
char *brkt;
ungetc(c, fp);
int i = 0;
while ( isalnum(c) || c==':' || c=='.' || c=='_' || c=='-' )
{
c = fgetc(fp);
str[i++] = c;
}
str[--i] = '\0';
if (c != ',') { ungetc(c, fp); }
strtok_r(str, ":", &brkt);
cur->label = string(str);
cur->branch_length = 0; //atof(str);
#if DEBUGLT
fprintf(stderr, "label=%s\tbranch_length=%.2f\n", cur->label.c_str(), cur->branch_length);
#endif
}
else //if (c != ':' && !isdigit(c) && c !=';')
{
fprintf(stderr, "ERROR in %s at %d: Unexpected data, %c, after ')' in %s on line %d\n",
__FILE__, __LINE__, c, file, LINE);
return 0;
}
cur = cur->parent_m;
c = fgetc(fp);
if (c != ',') { ungetc(c, fp); }
}
else // 'name:bl' or 'name:bl,' - leaf
{
#if DEBUGLT
fprintf(stderr,"in name:bl=%c\n", c);
#endif
cur = cur->addChild();
nLeaves_m++;
cur->label += c;
while ((c = fgetc(fp)) != ':')
{
cur->label += c;
}
#if DEBUGLT
fprintf(stderr,"in name:bl label=%s\n", cur->label.c_str());
#endif
fscanf(fp, "%lf", &cur->branch_length);
cur->idx = leafIdx;
leafIdx++;
cur = cur->parent_m;
c = fgetc(fp);
if (c != ',') { ungetc(c, fp); }
}
} // end of while()
minIdx_m++;
if (!root_m)
{
fprintf(stderr,"ERROR in %s at line %d: Newick root is null!\n",__FILE__,__LINE__);
exit(EXIT_FAILURE);
}
return true;
}
//--------------------------------------------- writeNewickNode -----
static void writeNewickNode(NewickNode_t * node,
FILE * fp,
int depth)
{
if (!node) { return; }
int numChildren = node->children_m.size();
if (numChildren == 0)
{
if ( node->branch_length )
fprintf(fp, "%s:%0.20lf", node->label.c_str(), node->branch_length);
else
fprintf(fp, "%s:0.1", node->label.c_str());
}
else
{
//fprintf(fp, "(\n");
fprintf(fp, "(");
vector<NewickNode_t *> goodChildren;
for (int i = 0; i < numChildren; i++)
{
goodChildren.push_back(node->children_m[i]);
}
int numGoodChildren = goodChildren.size();
for (int i = 0; i < numGoodChildren; i++)
{
writeNewickNode(goodChildren[i], fp, depth+1);
if (i != numGoodChildren-1) { fprintf(fp, ","); }
//fprintf(fp, "\n");
}
//for (int i = 0; i < depth; i++) { fprintf(fp, " "); }
if ( node->label.empty() )
{
if ( node->branch_length)
fprintf(fp, "):%0.20lf", node->branch_length);
else
fprintf(fp, "):0.1");
}
else
{
if ( node->branch_length)
fprintf(fp, ")%s:%0.20lf", node->label.c_str(), node->branch_length);
else
fprintf(fp, ")%s:0.1", node->label.c_str());
}
if (depth == 0) { fprintf(fp, ";\n"); }
}
}
//--------------------------------------------- writeTree -----
void NewickTree_t::writeTree(FILE * fp)
{
if (root_m == NULL)
{
fprintf(stderr, "ERROR: Root is NULL!\n");
}
writeNewickNode(root_m, fp, 0);
fflush(fp);
}
//--------------------------------------------- writeTree -----
void NewickTree_t::writeTree(FILE * fp, NewickNode_t *node)
{
if (root_m == NULL)
{
fprintf(stderr, "ERROR: Root is NULL!\n");
}
writeNewickNode(node, fp, 0);
fflush(fp);
}
//--------------------------------------------- writeTree -----
void NewickTree_t::writeTree(FILE * fp, const string &nodeLabel)
{
if (root_m == NULL) fprintf(stderr, "ERROR: Root is NULL!\n");
queue<NewickNode_t *> bfs;
bfs.push(root_m);
NewickNode_t *node;
int numChildren;
while ( !bfs.empty() )
{
node = bfs.front();
bfs.pop();
if ( node->label==nodeLabel )
{
writeNewickNode(node, fp, 0);
fflush(fp);
break;
}
numChildren = node->children_m.size();
if ( numChildren )
{
for (int i = 0; i < numChildren; i++)
{
bfs.push(node->children_m[i]);
}
}
}
}
//--------------------------------------------- getDepth -----
// Determine the depth of a tree
int NewickTree_t::getDepth()
{
deque<NewickNode_t *> dfs;
dfs.push_front(root_m);
NewickNode_t *node;
deque<int> depth;
int maxDepth = 0;
depth.push_front(maxDepth);
while ( !dfs.empty() )
{
node = dfs.front();
dfs.pop_front();
int d = depth.front();
depth.pop_front();
if ( maxDepth < d )
maxDepth = d;
int numChildren = node->children_m.size();
if ( numChildren>0 )
{
for (int i = 0; i < numChildren; i++)
{
dfs.push_front(node->children_m[i]);
depth.push_front(d+1);
}
//if ( maxDepth < d+1 )
// maxDepth = d+1;
}
}
return maxDepth;
}
//--------------------------------------------- printTree -----
//
// prints tree to stdout with different depths at differen indentation levels
// indStr - indentation string
void NewickTree_t::printTree(bool withIdx, const char *indStr)
{
if (root_m == NULL)
{
fprintf(stderr, "ERROR: Root is NULL!\n");
}
// Determine the depth of the tree
int maxDepth = getDepth();
printf("\nmaxDepth: %d\n\n", maxDepth);
maxDepth++;
// Set up indent array of indentation strings
//const char *indStr=" ";
int indStrLen = strlen(indStr);
char **indent = (char **)malloc(maxDepth * sizeof(char*));
indent[0] = (char*)malloc(sizeof(char)); // empty string
indent[0][0] = '\0';
for ( int i = 1; i < maxDepth; i++ )
{
indent[i] = (char*)malloc(indStrLen * (i+1) * sizeof(char));
for ( int j = 0; j < i; j++ )
for ( int k = 0; k < indStrLen; k++ )
indent[i][j * indStrLen + k] = indStr[k];
indent[i][indStrLen * i] = '\0';
}
//Depth first search
deque<NewickNode_t *> dfs;
dfs.push_front(root_m);
NewickNode_t *node;
while ( !dfs.empty() )
{
node = dfs.front();
dfs.pop_front();
int numChildren = node->children_m.size();
if ( numChildren==0 ) // leaf
{
if ( withIdx )
printf("%s%s(%d)\n",indent[node->depth_m],node->label.c_str(), node->idx);
else
//printf("%s%s\n",indent[node->depth_m],node->label.c_str());
printf("(%d)%s%s\n",node->depth_m,indent[node->depth_m],node->label.c_str());
}
else
{
if ( withIdx )
{
if ( node->label.empty() )
printf("%s*(%d)\n",indent[node->depth_m],node->idx);
else
printf("%s%s(%d)\n",indent[node->depth_m],node->label.c_str(), node->idx);
}
else
{
if ( node->label.empty() )
printf("%s*\n",indent[node->depth_m]);
else
//printf("%s%s\n",indent[node->depth_m],node->label.c_str());
printf("(%d)%s%s\n",node->depth_m,indent[node->depth_m],node->label.c_str());
}
for (int i = 0; i < numChildren; i++)
dfs.push_front(node->children_m[i]);
}
}
}
#if 0
//--------------------------------------------- printTreeBFS -----
void NewickTree_t::printTreeBFS()
{
if (root_m == NULL)
{
fprintf(stderr, "ERROR: Root is NULL!\n");
}
//Breath first search
queue<NewickNode_t *> bfs;
bfs.push(root_m);
NewickNode_t *node;
while ( !bfs.empty() )
{
node = bfs.front();
bfs.pop();
int numChildren = node->children_m.size();
if ( numChildren==0 ) // leaf
{
printf("%s%s\n",indent[node->depth_m],node->label.c_str());
}
else
{
printf("%s*\n",indent[node->depth_m]);
for (int i = 0; i < numChildren; i++)
{
bfs.push(node->children_m[i]);
}
}
}
}
#endif
//--------------------------------------------- indexNewickNodes -----
void NewickTree_t::indexNewickNodes( map<int, NewickNode_t*> & idx2node)
/*
populates a hash table of <node index> => <pointer to the node>
returns number of leaves of the tree
*/
{
if ( idx2node_m.size() == 0 )
{
//Breath first search
queue<NewickNode_t *> bfs;
bfs.push(root_m);
NewickNode_t *node;
while ( !bfs.empty() )
{
node = bfs.front();
bfs.pop();
idx2node_m[node->idx] = node;
int numChildren = node->children_m.size();
if ( numChildren != 0 ) // leaf
{
for (int i = 0; i < numChildren; i++)
{
bfs.push(node->children_m[i]);
}
}
}
}
idx2node = idx2node_m;
}
//--------------------------------------------- leafLabels -----
char ** NewickTree_t::leafLabels()
{
char **leafLabel = (char**)malloc((nLeaves_m) * sizeof(char*));
queue<NewickNode_t *> bfs;
bfs.push(root_m);
NewickNode_t *node;
while ( !bfs.empty() )
{
node = bfs.front();
bfs.pop();
int numChildren = node->children_m.size();
if ( numChildren==0 ) // leaf
{
leafLabel[node->idx] = strdup((node->label).c_str());
}
else
{
for (int i = 0; i < numChildren; i++)
{
bfs.push(node->children_m[i]);
}
}
}
return leafLabel;
}
// ------------------------- assignIntNodeNames ------------------------
void NewickTree_t::assignIntNodeNames()
/*
Asssign i1, i2, i3 etc names to internal nodes, where iK label corresponds to index -K
*/
{
queue<NewickNode_t *> bfs;
bfs.push(root_m);
NewickNode_t *node;
//int negIdx; // holds negative index of a nod
char str[16]; // holds negIdx
while ( !bfs.empty() )
{
node = bfs.front();
bfs.pop();
int numChildren = node->children_m.size();
if ( numChildren ) // not leaf
{
//negIdx = -node->idx;
sprintf(str,"%d", -node->idx);
node->label = string("i") + string(str);
for (int i = 0; i < numChildren; i++)
{
bfs.push(node->children_m[i]);
}
}
}
}
// ------------------------------ saveCltrMemb ------------------------
void NewickTree_t::saveCltrMemb( const char *outFile,
vector<int> &nodeCut,
int *annIdx,
map<int, string> &idxToAnn)
/*
save clustering membership data to outFile
output file format:
<leaf ID> <cluster ID> <annotation str or NA if absent>
Parameters:
outFile - output file
nodeCut - min-node-cut
annIdx - annIdx[i] = <0-based index of the annotation string assigned to the i-th
element of data table>
annIdx[i] = -1 if the i-th element has no annotation
idxToAnn - idxToAnn[annIdx] = <annotation string associated with annIdx>
*/
{
map<int, NewickNode_t*> idx2node;
indexNewickNodes(idx2node);
FILE *file = fOpen(outFile,"w");
fprintf(file,"readId\tclstr\tannot\n");
int n = nodeCut.size();
for ( int i = 0; i < n; ++i )
{
if ( nodeCut[i] >= 0 )
{
fprintf(file,"%s\t%d\t%s\n",idx2node[nodeCut[i]]->label.c_str(),i,
idxToAnn[ annIdx[nodeCut[i]] ].c_str() );
}
else
{
queue<NewickNode_t *> bfs;
bfs.push(idx2node[nodeCut[i]]);
NewickNode_t *node;
while ( !bfs.empty() )
{
node = bfs.front();
bfs.pop();
int numChildren = node->children_m.size();
if ( numChildren==0 ) // leaf
{
fprintf(file,"%s\t%d\t%s\n",node->label.c_str(),i,
idxToAnn[ annIdx[node->idx] ].c_str() );
}
else
{
for (int i = 0; i < numChildren; i++)
{
bfs.push(node->children_m[i]);
}
}
}
}
}
fclose(file);
}
// ------------------------------ saveCltrMemb2 ------------------------
void NewickTree_t::saveCltrMemb2( const char *outFile,
vector<int> &nodeCut,
int *annIdx,
map<int, string> &idxToAnn)
/*
save clustering membership data to outFile
output file format:
<cluster_1>:
<leaf1> <annotation of leaf1>
<leaf2> <annotation of leaf2>
...
...
Parameters:
outFile - output file
nodeCut - min-node-cut
annIdx - annIdx[i] = <0-based index of the annotation string assigned to the i-th
element of data table>
annIdx[i] = -1 if the i-th element has no annotation
idxToAnn - idxToAnn[annIdx] = <annotation string associated with annIdx>
*/
{
map<int, NewickNode_t*> idx2node;
indexNewickNodes(idx2node);
FILE *file = fOpen(outFile,"w");
int n = nodeCut.size();
for ( int i = 0; i < n; ++i )
{
fprintf(file,"Cluster %d:\n",i);
if ( nodeCut[i] >= 0 )
{
fprintf(file,"\t%s\t%s\n",idx2node[nodeCut[i]]->label.c_str(),
idxToAnn[ annIdx[nodeCut[i]] ].c_str() );
}
else
{
queue<NewickNode_t *> bfs;
bfs.push(idx2node[nodeCut[i]]);
NewickNode_t *node;
while ( !bfs.empty() )
{
node = bfs.front();
bfs.pop();
int numChildren = node->children_m.size();
if ( numChildren==0 ) // leaf
{
fprintf(file,"\t%s\t%s\n",node->label.c_str(),
idxToAnn[ annIdx[node->idx] ].c_str() );
}
else
{
for (int i = 0; i < numChildren; i++)
{
bfs.push(node->children_m[i]);
}
}
}
}
}
fclose(file);
}
// this is going to be used to sort map<string,int> in saveCltrAnnStats()
class sort_map
{
public:
string key;
int val;
};
bool Sort_by(const sort_map& a ,const sort_map& b)
{
return a.val > b.val;
}
// ------------------------------ saveCltrAnnStats --------------------------------
void NewickTree_t::saveCltrAnnStats( const char *outFile,
vector<int> &nodeCut,
int *annIdx,
map<int, string> &idxToAnn)
/*
save annotation summary statistics of the clustering induced by nodeCut to outFile
output file format:
<cluster_1>:
<annotation 1,1> <count1,1> <perc1,1>
<annotation 1,2> <count1,2> <perc1,2>
...
...
<cluster_2>:
<annotation 2,1> <count2,1> <perc2,1>
<annotation 2,2> <count2,2> <perc2,2>
...
...
countX,Y is the count of leaves in cluster_X and Y-th annotation (sorted by count)
percX,Y is the percentage of these leaves in the given cluster
Parameters:
outFile - output file
nodeCut - min-node-cut
annIdx - annIdx[i] = <0-based index of the annotation string assigned to the i-th
element of data table>
annIdx[i] = -1 if the i-th element has no annotation
idxToAnn - idxToAnn[annIdx] = <annotation string associated with annIdx>
*/
{
map<int, NewickNode_t*> idx2node;
indexNewickNodes(idx2node);
FILE *file = fOpen(outFile,"w");
int n = nodeCut.size();
for ( int i = 0; i < n; ++i )
{
fprintf(file,"Cluster %d:\n",i);
if ( nodeCut[i] >= 0 )
{
fprintf(file,"\t%s\t1\t100%%\n", idxToAnn[ annIdx[nodeCut[i]] ].c_str() );
}
else
{
map<string,int> annCount; // count of a given annotation string in the subtree of a given cut-node
queue<NewickNode_t *> bfs;
bfs.push(idx2node[nodeCut[i]]);
NewickNode_t *node;
while ( !bfs.empty() )
{
node = bfs.front();
bfs.pop();
int numChildren = node->children_m.size();
if ( numChildren==0 ) // leaf
{
annCount[ idxToAnn[ annIdx[node->idx] ] ]++;
}
else
{
for (int i = 0; i < numChildren; i++)
{
bfs.push(node->children_m[i]);
}
}
}
// printing annotation counts in the order of their counts
map<string,int>::iterator it;
vector< sort_map > v;
vector< sort_map >::iterator itv;
sort_map sm;
double sum = 0;
for (it = annCount.begin(); it != annCount.end(); ++it)
{
sm.key = (*it).first;
sm.val = (*it).second;
v.push_back(sm);
sum += sm.val;
}
sort(v.begin(),v.end(),Sort_by);
for (itv = v.begin(); itv != v.end(); ++itv)
fprintf(file,"\t%s\t%d\t%.1f%%\n", ((*itv).key).c_str(), (*itv).val, 100.0 * (*itv).val / sum);
if ( v.size() > 1 )
fprintf(file,"\tTOTAL\t%d\t100%%\n", (int)sum);
}
}
fclose(file);
}
// ------------------------------ saveNAcltrAnnStats ------------------------
vector<string> NewickTree_t::saveNAcltrAnnStats( const char *outFile,
vector<int> &nodeCut,
int *annIdx,
map<int, string> &idxToAnn)
/*
It is a version of saveCltrAnnStats() that reports only clusters containig query (NA) elements.
*/
{
map<int, NewickNode_t*> idx2node;
indexNewickNodes(idx2node);
FILE *file = fOpen(outFile,"w");
vector<string> selAnn; // vector of taxons which are memembers of clusters that contain query seqeunces
int n = nodeCut.size();
for ( int i = 0; i < n; ++i )
{
if ( nodeCut[i] < 0 )
{
map<string,int> annCount; // count of a given annotation string in the subtree of a given cut-node
queue<NewickNode_t *> bfs;
bfs.push(idx2node[nodeCut[i]]);
NewickNode_t *node;
bool foundNA = false;
while ( !bfs.empty() )
{
node = bfs.front();
bfs.pop();
int numChildren = node->children_m.size();
if ( numChildren==0 ) // leaf
{
annCount[ idxToAnn[ annIdx[node->idx] ] ]++;
if ( annIdx[node->idx] == -2) foundNA = true;
}
else
{
for (int i = 0; i < numChildren; i++)
{
bfs.push(node->children_m[i]);
}
}
}
// printing annotation counts in the order of their counts
if ( foundNA )
{
map<string,int>::iterator it;
vector< sort_map > v;
vector< sort_map >::iterator itv;
sort_map sm;
double sum = 0;
for (it = annCount.begin(); it != annCount.end(); ++it)
{
sm.key = (*it).first;
sm.val = (*it).second;
selAnn.push_back(sm.key);
v.push_back(sm);
sum += sm.val;
}
sort(v.begin(),v.end(),Sort_by);
fprintf(file,"Cluster %d:\n",i);
for (itv = v.begin(); itv != v.end(); ++itv)
fprintf(file,"\t%s\t%d\t%.1f%%\n", ((*itv).key).c_str(), (*itv).val, 100.0 * (*itv).val / sum);
if ( v.size() > 1 )
fprintf(file,"\tTOTAL\t%d\t100%%\n", (int)sum);
}
}
}
fclose(file);
return selAnn;
}
// ------------------------------ saveNAcltrAnnStats ------------------------
void NewickTree_t::saveNAcltrAnnStats( const char *outFileA, // file to with cluster stats of clusters with at least minNA query sequences
const char *outFileB, // file to with cluster stats of clusters with less than minNA query sequences
const char *outFileC, // file with reference IDs of sequences for clusters in outFileA
const char *outFileD, // file with taxons, for clusters in outFileA, with the number of sequences >= minAnn
vector<int> &nodeCut,
int *annIdx,
map<int, string> &idxToAnn,
int minNA,
int minAnn)
/*
It is a version of saveCltrAnnStats() that reports only clusters containig at
least minNA query sequences to outFileA and less than minNA sequences to
outFileB.
output vector contains taxons with at least minAnn elements (in a single cluster).
*/
{
map<int, NewickNode_t*> idx2node;
indexNewickNodes(idx2node);
FILE *fileA = fOpen(outFileA,"w");
FILE *fileB = fOpen(outFileB,"w");
FILE *fileC = fOpen(outFileC,"w");
int nCltrs = 0; // number of clusters with the number of query seq's >= minNA
int nTx = 0; // number of selected taxons from the above clusters with the number of reads >= minAnn
int nRef = 0; // number of reference sequence from the above clusters with taxons with the number of reads >= minAnn
map<string,bool> selTx; // hash table of selected taxons as in nTx; nTx = number of elements in selTx
int n = nodeCut.size();
for ( int i = 0; i < n; ++i )
{
if ( nodeCut[i] < 0 ) // internal node
{
map<string,int> annCount; // count of a given annotation string in the subtree of a given cut-node
queue<NewickNode_t *> bfs;
bfs.push(idx2node[nodeCut[i]]);
NewickNode_t *node;
int naCount = 0;
while ( !bfs.empty() )
{
node = bfs.front();
bfs.pop();
int numChildren = node->children_m.size();
if ( numChildren==0 ) // leaf
{
annCount[ idxToAnn[ annIdx[node->idx] ] ]++;
if ( annIdx[node->idx] == -2) naCount++;
}
else
{
for (int i = 0; i < numChildren; i++)
{
bfs.push(node->children_m[i]);
}
}
}
// printing annotation counts in the order of their counts
if ( naCount >= minNA )
{
nCltrs++;
map<string,int>::iterator it;
vector< sort_map > v;
vector< sort_map >::iterator itv;
sort_map sm;
double sum = 0;
for (it = annCount.begin(); it != annCount.end(); ++it)
{
sm.key = (*it).first;
sm.val = (*it).second;
v.push_back(sm);
sum += sm.val;
}
sort(v.begin(),v.end(),Sort_by);
fprintf(fileA,"Cluster %d:\n",i);
for (itv = v.begin(); itv != v.end(); ++itv)
fprintf(fileA,"\t%s\t%d\t%.1f%%\n", ((*itv).key).c_str(), (*itv).val, 100.0 * (*itv).val / sum);
if ( v.size() > 1 )
fprintf(fileA,"\tTOTAL\t%d\t100%%\n", (int)sum);
// traverse the subtree again selecting sequences with annCount of the
// corresponding taxons that have at least minAnn elements to be printed
// in fileC
queue<NewickNode_t *> bfs2;
bfs2.push(idx2node[nodeCut[i]]);
NewickNode_t *node;
while ( !bfs2.empty() )
{
node = bfs2.front();
bfs2.pop();
int numChildren = node->children_m.size();
if ( numChildren==0 ) // leaf
{
if ( annCount[ idxToAnn[ annIdx[node->idx] ] ] > minAnn && idxToAnn[ annIdx[node->idx] ] != "NA" )
{
selTx[ idxToAnn[ annIdx[node->idx] ] ] = true;
nRef++;
fprintf(fileC, "%s\t%s\n",
node->label.c_str(),
idxToAnn[ annIdx[node->idx] ].c_str() );
}
}
else
{
for (int i = 0; i < numChildren; i++)
{
bfs2.push(node->children_m[i]);
}
}
}
}
else
{
map<string,int>::iterator it;
vector< sort_map > v;
vector< sort_map >::iterator itv;
sort_map sm;
double sum = 0;
for (it = annCount.begin(); it != annCount.end(); ++it)
{
sm.key = (*it).first;
sm.val = (*it).second;
v.push_back(sm);
sum += sm.val;
}
sort(v.begin(),v.end(),Sort_by);
fprintf(fileB,"Cluster %d:\n",i);
for (itv = v.begin(); itv != v.end(); ++itv)
fprintf(fileB,"\t%s\t%d\t%.1f%%\n", ((*itv).key).c_str(), (*itv).val, 100.0 * (*itv).val / sum);
if ( v.size() > 1 )
fprintf(fileB,"\tTOTAL\t%d\t100%%\n", (int)sum);
}
}
}
fclose(fileA);
fclose(fileB);
fclose(fileC);
// extracting only keys of selTx;
FILE *fileD = fOpen(outFileD,"w");
//vector<string> selTxV; // vector of taxons which are memembers of clusters that contain query seqeunces
for(map<string,bool>::iterator it = selTx.begin(); it != selTx.end(); ++it)
{
//selTxV.push_back(it->first);
fprintf(fileD,"%s\n",(it->first).c_str());
}
fclose(fileD);
nTx = selTx.size();
fprintf(stderr,"\nNumber of clusters with the number of query seq's >= %d: %d\n",minNA, nCltrs);
fprintf(stderr,"Number of selected taxons from the above clusters with the number of reads >= %d: %d\n",minAnn, nTx);
fprintf(stderr,"Number of selected reference sequence from the above clusters with taxons with the number of reads >= %d: %d\n",minAnn, nRef);
}
// comparison between integers producing descending order
bool gr (int i,int j) { return (i>j); }
// ------------------------------ saveNAtaxonomy0 ------------------------
void NewickTree_t::saveNAtaxonomy0( const char *outFile,
const char *logFile, // recording sizes of two most abundant taxa. If there is only one (besides query sequences), recording the number of elements of the dominant taxon and 0.
vector<int> &nodeCut,
int *annIdx,
map<int, string> &idxToAnn,
int minAnn,
int &nNAs,
int &nNAs_with_tx,
int &tx_changed,
int &nClades_modified)
/*
Assigning taxonomy to query sequences and modifying taxonomy of sequences with
non-monolityc clades using majority vote.
This is a special case of saveNAtaxonomy() that does taxonomy assignments of
query sequences from clusters containing at least minAnn reference
sequences. The taxonomy is based on the most abundant reference taxon.
I just extended the algorithm so that taxonomy of all elements of the given
cluster is set to the taxonomy of the cluster with the largest number of
sequences. If there are ties, that is two taxonomies are most abundant, then
there is no change.
*/
{
map<int, NewickNode_t*> idx2node;
indexNewickNodes(idx2node);
map<string,int> otuFreq; // <taxonomic rank name> => number of OTUs already assigned to it
FILE *file = fOpen(outFile,"w");
FILE *logfile = fOpen(logFile,"w");
nNAs = 0;
nNAs_with_tx = 0;
tx_changed = 0;
nClades_modified = 0;
int n = nodeCut.size();
for ( int i = 0; i < n; ++i )
{
map<string,int> annCount; // count of a given annotation string in the subtree of a given node
int naCount = 0;
queue<NewickNode_t *> bfs;
bfs.push(idx2node[nodeCut[i]]);
NewickNode_t *node;
while ( !bfs.empty() )
{
node = bfs.front();
bfs.pop();
int numChildren = node->children_m.size();
if ( numChildren==0 ) // leaf
{
//if ( i==262 )printf("\n%s\t%s", node->label.c_str(), idxToAnn[ annIdx[node->idx] ].c_str());
annCount[ idxToAnn[ annIdx[node->idx] ] ]++;
if ( annIdx[node->idx] == -2) naCount++;
if ( idxToAnn[ annIdx[node->idx] ] == "NA" ) nNAs++;
}
else
{
for (int j = 0; j < numChildren; j++)
{
bfs.push(node->children_m[j]);
}
}
}
//if ( i==262 )printf("\n\n");
//if ( naCount >= minNA && annCount.size() >= minAnn )
if ( annCount.size() >= (unsigned)minAnn ) // Assigning taxonomy to query sequences and modifying taxonomy of sequences with non-monolityc clades using majority vote
{
string cltrTx;
int maxCount = 0; // maximal count among annotated sequences in the cluster
map<string,int>::iterator it;
// Make sure there are not ties for max count
// Copying counts into a vector, sorting it and checking that the first two
// values (when sorting in the decreasing order) are not equal to each
// other.
vector<int> counts;
for (it = annCount.begin(); it != annCount.end(); ++it)
{
if ( (*it).first != "NA" )
counts.push_back((*it).second);
if ( (*it).first != "NA" && (*it).second > maxCount )
{
maxCount = (*it).second;
cltrTx = (*it).first;
}
}
sort( counts.begin(), counts.end(), gr );
#if 0
if ( i==231 )
{
fprintf(stderr,"\ncltrTx: %s\n", cltrTx.c_str());
fprintf(stderr,"\nCluster %d\nannCount\n",i);
for (it = annCount.begin(); it != annCount.end(); ++it)
{
fprintf(stderr,"\t%s\t%d\n", ((*it).first).c_str(), (*it).second);
}
fprintf(stderr,"\nsorted counts: ");
for (int j = 0; j < counts.size(); j++)
fprintf(stderr,"%d, ", counts[j]);
fprintf(stderr,"\n\n");
}
#endif
// Traverse the subtree again assigning taxonomy to all query sequences
int counts_size = counts.size();
if ( counts_size==1 || ( counts_size>1 && counts[0] > counts[1] ) )
{
nClades_modified++;
if ( counts_size > 1 )
fprintf(logfile, "%d\t%d\n", counts[0], counts[1]);
else
fprintf(logfile, "%d\t0\n", counts[0]);
queue<NewickNode_t *> bfs2;
bfs2.push(idx2node[nodeCut[i]]);
NewickNode_t *node;
while ( !bfs2.empty() )
{
node = bfs2.front();
bfs2.pop();
int numChildren = node->children_m.size();
if ( numChildren==0 ) // leaf
{
//if ( idxToAnn[ annIdx[node->idx] ] == "NA" && !cltrTx.empty() )
if ( idxToAnn[ annIdx[node->idx] ] !=cltrTx && !cltrTx.empty() )
{
//idxToAnn[ annIdx[node->idx] ] = cltrTx;
fprintf(file, "%s\t%s\n", node->label.c_str(), cltrTx.c_str());
if ( idxToAnn[ annIdx[node->idx] ] == "NA" )
nNAs_with_tx++;
else
tx_changed++;
}
}
else
{
for (int j = 0; j < numChildren; j++)
bfs2.push(node->children_m[j]);
}
} // end while ( !bfs2.empty() )
} // end if ( counts.size()==1 || ( counts.size()>1 && counts[0] > counts[1] ) )
} // end if ( naCount >= minNA && annCount.size() >= minAnn )
} // end for ( int i = 0; i < n; ++i )
fclose(file);
fclose(logfile);
}
// ------------------------------ saveNAtaxonomy ------------------------
void NewickTree_t::saveNAtaxonomy( const char *outFile,
const char *logFile,
const char *genusOTUsFile,
vector<int> &nodeCut,
int *annIdx,
map<int, string> &idxToAnn,
int minNA,
map<string, string> &txParent)
/*
Taxonomy assignments of query sequences from clusters containing either only
query sequences or query sequences with at least minNA query sequences and
minAnn reference sequences; In the last case the taxonomy is based on the most
abundant reference taxon. In the previous case, the taxonomy is determined by
the first ancestor with reference sequences. The content of reference sequences
determines taxonomy. Here are some rules.
If the ancestor contains reference sequences of the same species, then we
assign this species name to the OTU.
If the ref seq's are from the same genus, then we assign to the OTU the name of
the most abundant ref sequence. A justification for this comes from an
observation that often OTUs form a clade in the middle of which there are two
subtrees with two different species of the same genus. I hypothesize that this
is a clade of one species and the other one is an error. Therefore, the name of
the OTU should be the name of the more abundant species, and the other species
should be renamed to the other one.
Alternatively, the name could be of the form
<genus name>_<species1>.<species2>. ... .<speciesN>
where species1, ... , speciesN are species present in the ancestral node
If the ref seq's are from different genera, then we assign to the OTU a name
<tx rank>_OTUi
where tx rank is the taxonomic rank of common to all ref seq's of the ancestral subtree.
In the extreme case of Bacteria_OTU I am merging
*/
{
FILE *file = fOpen(outFile,"w");
FILE *fh = fOpen(logFile,"w");
FILE *genusFH = fOpen(genusOTUsFile,"w");
//map<string,bool> selTx; // hash table of selected taxons as in nTx; nTx = number of elements in selTx
map<int, NewickNode_t*> idx2node;
indexNewickNodes(idx2node);
map<string,int> otuFreq; // <taxonomic rank name> => number of OTUs already assigned to it
int n = nodeCut.size();
for ( int i = 0; i < n; ++i )
{
//if ( nodeCut[i] < 0 ) // internal node
{
map<string,int> annCount; // count of a given annotation string in the subtree of a given cut-node
queue<NewickNode_t *> bfs;
bfs.push(idx2node[nodeCut[i]]);
NewickNode_t *node;
int naCount = 0;
while ( !bfs.empty() )
{
node = bfs.front();
bfs.pop();
int numChildren = node->children_m.size();
if ( numChildren==0 ) // leaf
{
annCount[ idxToAnn[ annIdx[node->idx] ] ]++;
if ( annIdx[node->idx] == -2) naCount++;
}
else
{
for (int i = 0; i < numChildren; i++)
{
bfs.push(node->children_m[i]);
}
}
}
if ( naCount >= minNA )
{
string cltrTx; // = "Unclassified"; // taxonomy for all query reads of the cluster with no annotated sequences
if ( annCount.size() > 1 ) // there is at least one annotated element; setting cltrTx to annotation with the max frequency
{
int maxCount = 0; // maximal count among annotated sequences in the cluster
map<string,int>::iterator it;
for (it = annCount.begin(); it != annCount.end(); ++it)
{
if ( (*it).first != "NA" && (*it).second > maxCount )
{
maxCount = (*it).second;
cltrTx = (*it).first;
}
}
}
else // there are no annotated sequences in the cluster; we are looking for the nearest ancestral node with known taxonomy
{
node = idx2node[nodeCut[i]]; // current node
node = node->parent_m; // looking at the parent node
map<string,int> sppFreq;
int nSpp = cltrSpp(node, annIdx, idxToAnn, sppFreq); // table of species frequencies in the subtree of 'node'
while ( nSpp==0 ) // if the parent node does not have any annotation sequences
{
node = node->parent_m; // move up to its parent node
nSpp = cltrSpp(node, annIdx, idxToAnn, sppFreq);
}
// Debug
// fprintf(stderr, "\n--- i: %d\tCluster %d\n", i, node->idx);
// fprintf(stderr,"Number of species detected in the Unassigned node: %d\n",nSpp);
// besides writing frequencies I am finding taxonomic parents of each species
map<string,int> genus; // this is a map not vector so that I avoid duplication and find out frequence of a genus
map<string,int>::iterator it;
for ( it = sppFreq.begin(); it != sppFreq.end(); it++ )
{
//if ( (*it).first != "NA" )
//fprintf(fh, "%s\t%d\n", ((*it).first).c_str(), (*it).second);
if ( !txParent[(*it).first].empty() )
genus[ txParent[(*it).first] ] += (*it).second;
}
#if 0
// Checking of there is more than one genus present
// If so, we are going higher until we get only one taxonomic rank.
int nRks = genus.size();
map<string,int> txRk = genus; // taxonomic rank
map<string,int> pTxRk; // parent taxonomic rank
while ( nRks>1 )
{
for ( it = txRk.begin(); it != txRk.end(); it++ )
if ( !txParent[(*it).first].empty() )
pTxRk[ txParent[(*it).first] ]++;
// fprintf(fh, "\nTx Rank Frequencies\n");
// for ( it = pTxRk.begin(); it != pTxRk.end(); it++ )
// fprintf(fh, "%s\t%d\n", ((*it).first).c_str(), (*it).second);
nRks = pTxRk.size();
txRk = pTxRk;
pTxRk.clear();
// Debug
// fprintf(stderr,"nRks: %d\n",nRks);
}
it = txRk.begin();
string otuRank = (*it).first;
#endif
// assign OTU ID
if ( genus.size() == 1 ) // assign species name of the most frequent OTU
{
int maxCount = 0; // maximal count among annotated sequences in the cluster
map<string,int>::iterator it;
for (it = sppFreq.begin(); it != sppFreq.end(); ++it)
{
if ( (*it).first != "NA" && (*it).second > maxCount )
{
maxCount = (*it).second;
cltrTx = (*it).first;
}
}
}
else
{
// assigning the same OTU id to all OTUs with the same sppFreq profile
string sppProf;
map<string,int>::iterator it;
for (it = sppFreq.begin(); it != sppFreq.end(); ++it)
{
if ( (*it).first != "NA" )
{
sppProf += (*it).first;
}
}
int maxCount = 0; // maximal count among genera
string otuGenus;
for (it = genus.begin(); it != genus.end(); ++it)
{
if ( (*it).first != "NA" && (*it).second > maxCount )
{
maxCount = (*it).second;
otuGenus = (*it).first;
}
}
it = otuFreq.find(sppProf);
int k = 1;
if ( it != otuFreq.end() )
k = it->second + 1;
otuFreq[sppProf] = k;
char kStr[8];
sprintf(kStr,"%d",k);
cltrTx = otuGenus + string("_OTU") + string(kStr);
}
// Writing sppFreq to log file
fprintf(fh,"\n==== %s\tAncestral node ID: %d ====\n\n",cltrTx.c_str(), node->idx);
fprintf(fh, "-- Species Frequencies\n");
int totalSppLen = 0;
for ( it = sppFreq.begin(); it != sppFreq.end(); it++ )
{
fprintf(fh, "%s\t%d\n", ((*it).first).c_str(), (*it).second);
totalSppLen += ((*it).first).length();
}
// For each species of sppFreq, determine its taxonomy parent and write them to the log file
fprintf(fh, "\n-- Genus Frequencies\n");
for ( it = genus.begin(); it != genus.end(); it++ )
fprintf(fh, "%s\t%d\n", ((*it).first).c_str(), (*it).second);
if ( genus.size() == 1 ) // for genus OTUs print OTU name, ancestral node ID and species names into genusOTUsFile
{
//fprintf(stderr, "%s\t genus.size(): %d\n", cltrTx.c_str(), (int)genus.size());
// number of quary sequences in the OTU
it = sppFreq.find("NA");
if ( it == sppFreq.end() )
fprintf(stderr,"ERROR: OTU %s does not contain any quary sequences\n",cltrTx.c_str());
// OTU_ID, number of query sequences in the OTU, ID of the ancestral node that contains ref sequences
fprintf(genusFH,"%s\t%d\t%d\t",cltrTx.c_str(), (*it).second, node->idx);
int n = sppFreq.size();
char *sppStr = (char*)malloc((totalSppLen+n+1) * sizeof(char));
sppStr[0] = '\0';
int foundSpp = 0;
for ( it = sppFreq.begin(); it != sppFreq.end(); it++ )
{
if ( (*it).first != "NA" && (*it).first != "Unclassified" )
{
if ( foundSpp )
strncat(sppStr, ":",1);
strncat(sppStr, ((*it).first).c_str(), ((*it).first).length());
foundSpp = 1;
}
}
fprintf(genusFH,"%s\n", sppStr);
free(sppStr);
}
#if 0
// Higher taxonomic order frequencies
nRks = genus.size();
txRk = genus; // taxonomic rank
pTxRk.clear(); // parent taxonomic rank
while ( nRks>1 )
{
for ( it = txRk.begin(); it != txRk.end(); it++ )
if ( !txParent[(*it).first].empty() )
pTxRk[ txParent[(*it).first] ]++;
fprintf(fh, "\n-- Tx Rank Frequencies\n");
for ( it = pTxRk.begin(); it != pTxRk.end(); it++ )
fprintf(fh, "%s\t%d\n", ((*it).first).c_str(), (*it).second);
nRks = pTxRk.size();
txRk = pTxRk;
pTxRk.clear();
}
#endif
//Debugging
//fprintf(stderr,"OTU ID: %s\n",cltrTx.c_str());
} // end if ( annCount.size() > 1 )
// traverse the subtree again assigning taxonomy to all query sequences
queue<NewickNode_t *> bfs2;
bfs2.push(idx2node[nodeCut[i]]);
NewickNode_t *node;
while ( !bfs2.empty() )
{
node = bfs2.front();
bfs2.pop();
int numChildren = node->children_m.size();
if ( numChildren==0 ) // leaf
{
if ( idxToAnn[ annIdx[node->idx] ] == "NA" )
{
fprintf(file, "%s\t%s\n", node->label.c_str(), cltrTx.c_str());
}
}
else
{
for (int i = 0; i < numChildren; i++)
bfs2.push(node->children_m[i]);
}
} // end while ( !bfs2.empty() )
} // if ( naCount >= minNA )
} // end if ( nodeCut[i] < 0 ) // internal node
} // end for ( int i = 0; i < n; ++i )
fclose(fh);
fclose(genusFH);
fclose(file);
}
// ------------------------------ cltrSpp ------------------------
// Traverses the subtree of the current tree rooted at '_node' and finds
// annotation strings (taxonomies) of reference sequences present in the subtree
// (if any). sppFreq is the frequency table of found species.
//
// Returns the size of sppFreq
//
int NewickTree_t::cltrSpp(NewickNode_t *_node,
int *annIdx,
map<int, string> &idxToAnn,
map<string,int> &sppFreq)
{
queue<NewickNode_t *> bfs;
bfs.push(_node);
NewickNode_t *node;
while ( !bfs.empty() )
{
node = bfs.front();
bfs.pop();
int numChildren = node->children_m.size();
if ( numChildren==0 ) // leaf
{
sppFreq[ idxToAnn[ annIdx[node->idx] ] ]++;
}
else
{
for (int i = 0; i < numChildren; i++)
{
bfs.push(node->children_m[i]);
}
}
}
return int(sppFreq.size());
}
// ------------------------------ maxAnn ------------------------
// traverse the subtree of the current tree rooted at '_node' and find annotation
// string with max frequency Return empty string if there are no annotation
// sequences in the subtree.
string NewickTree_t::maxAnn( NewickNode_t *_node,
int *annIdx,
map<int, string> &idxToAnn)
{
map<string,int> annCount; // count of a given annotation string in the subtree of the given node
queue<NewickNode_t *> bfs;
bfs.push(_node);
NewickNode_t *node;
while ( !bfs.empty() )
{
node = bfs.front();
bfs.pop();
int numChildren = node->children_m.size();
if ( numChildren==0 ) // leaf
{
annCount[ idxToAnn[ annIdx[node->idx] ] ]++;
}
else
{
for (int i = 0; i < numChildren; i++)
{
bfs.push(node->children_m[i]);
}
}
}
string cltrTx; // = "Unclassified"; // taxonomy for all query reads of the cluster with no annotated sequences
if ( annCount.size() > 1 ) // there is at least one annotated element; setting cltrTx to annotation with the max frequency
{
int maxCount = 0; // maximal count among annotated sequences in the cluster
map<string,int>::iterator it;
for (it = annCount.begin(); it != annCount.end(); ++it)
{
if ( (*it).first != "NA" && (*it).second > maxCount )
{
maxCount = (*it).second;
cltrTx = (*it).first;
}
}
}
return cltrTx;
}
// ------------------------------ findAnnNode ------------------------
// Find a node in lable 'label'
NewickNode_t* NewickTree_t::findAnnNode(std::string label)
{
queue<NewickNode_t *> bfs;
bfs.push(root_m);
NewickNode_t *node = 0;
NewickNode_t *searchedNode = 0;
while ( !bfs.empty() )
{
node = bfs.front();
bfs.pop();
if ( node->label == label )
{
searchedNode = node;
break;
}
int numChildren = node->children_m.size();
if ( numChildren ) // not leaf
{
for (int i = 0; i < numChildren; i++)
{
bfs.push(node->children_m[i]);
}
}
}
return searchedNode;
}
// ------------------------------ printGenusTrees ------------------------
// For each genus print a subtree rooted at the root nodes of the genus
// * to each genus assign a vector of species/OTU's cut-nodes generated by vicut
// * find a node with the smallest depth (from the root)
// * walk ancestors of this node until all OTU nodes are in the subtree of that node
// * print that tree to a file
void NewickTree_t::printGenusTrees( const char *outDir,
vector<int> &nodeCut,
int *annIdx,
int minNA,
map<int, string> &idxToAnn,
map<string, string> &txParent)
{
//fprintf(stderr,"Entering printGenusTrees()\n");
char s[1024];
sprintf(s,"mkdir -p %s",outDir);
system(s);
// === Assign to each genus a vector of species/OTU nodes
map<string, vector<NewickNode_t*> > genusSpp; // <genus> => vector of OTU/species node
map<int, NewickNode_t*> idx2node;
indexNewickNodes(idx2node);
int n = nodeCut.size();
for ( int i = 0; i < n; ++i )
{
//fprintf(stderr,"i: %d\r", i);
if ( nodeCut[i] < 0 ) // internal node
{
map<string,int> annCount; // count of a given annotation string in the subtree of a given cut-node
queue<NewickNode_t *> bfs;
bfs.push(idx2node[nodeCut[i]]);
NewickNode_t *node;
int naCount = 0;
while ( !bfs.empty() )
{
node = bfs.front();
bfs.pop();
int numChildren = node->children_m.size();
if ( numChildren==0 ) // leaf
{
annCount[ idxToAnn[ annIdx[node->idx] ] ]++;
if ( annIdx[node->idx] == -2) naCount++;
}
else
{
for (int i = 0; i < numChildren; i++)
{
bfs.push(node->children_m[i]);
}
}
}
if ( naCount >= minNA )
{
string cltrTx; // taxonomy for all query reads of the cluster with no annotated sequences
if ( annCount.size() > 1 ) // there is at least one annotated element; setting cltrTx to annotation with the max frequency
{
int maxCount = 0; // maximal count among annotated sequences in the cluster
map<string,int>::iterator it;
for (it = annCount.begin(); it != annCount.end(); ++it)
{
if ( (*it).first != "NA" && (*it).second > maxCount )
{
maxCount = (*it).second;
cltrTx = (*it).first;
}
}
genusSpp[ txParent[ cltrTx ] ].push_back( idx2node[nodeCut[i]] );
}
else // there are no annotated sequences in the cluster; we are looking for the nearest ancestral node with known taxonomy
{
//fprintf(stderr, "In if ( naCount >= minNA ) else\n");
node = idx2node[nodeCut[i]]; // current node
node = node->parent_m; // looking at the parent node
map<string,int> sppFreq;
int nSpp = cltrSpp(node, annIdx, idxToAnn, sppFreq); // table of species frequencies in the subtree of 'node'
while ( nSpp==0 ) // if the parent node does not have any annotation sequences
{
node = node->parent_m; // move up to its parent node
nSpp = cltrSpp(node, annIdx, idxToAnn, sppFreq);
}
//fprintf(stderr, "nSpp: %d\n", nSpp);
map<string,int> genus; // this is a map not vector so that I avoid duplication and find out frequence of a genus
map<string,int>::iterator it;
for ( it = sppFreq.begin(); it != sppFreq.end(); it++ )
{
if ( !txParent[(*it).first].empty() )
genus[ txParent[(*it).first] ]++;
}
//fprintf(stderr, "genus.size(): %d\n", (int)genus.size());
if ( genus.size() == 1 ) //
{
it = genus.begin();
//fprintf(stderr,"genus: %s\n", (*it).first.c_str());
genusSpp[ (*it).first ].push_back( node );
}
} // end if ( annCount.size() > 1 )
} // if ( naCount >= minNA )
} // end if ( nodeCut[i] < 0 ) // internal node
} // end for ( int i = 0; i < n; ++i )
// === For each genus, find a node with the smallest depth (from the root)
// === Walk this node until all OTU nodes are in the subtree of that node
// === Print that tree to a file
map<string, vector<NewickNode_t*> >::iterator itr;
for ( itr = genusSpp.begin(); itr != genusSpp.end(); itr++ )
{
vector<NewickNode_t*> v = (*itr).second;
int vn = (int)v.size();
//Debugging
// fprintf(stderr,"%s: ", (*itr).first.c_str());
// for ( int j = 0; j < vn; j++ )
// fprintf(stderr,"(%d, %d) ", v[j]->idx, v[j]->depth_m);
// fprintf(stderr,"\n");
NewickNode_t* minDepthNode = v[0];
int minDepth = v[0]->depth_m;
for ( int j = 1; j < vn; j++ )
{
if ( v[j]->depth_m < minDepth )
{
minDepth = v[j]->depth_m;
minDepthNode = v[j];
}
}
NewickNode_t* node = minDepthNode->parent_m;
bool foundParentNode = hasSelSpp(node, v); // looking for a parent node of all elements of v
while ( foundParentNode==false )
{
node = node->parent_m; // move up to its parent node
foundParentNode = hasSelSpp(node, v);
}
// write subtree rooted in node to a file
int n1 = strlen(outDir);
int n2 = ((*itr).first).length();
char *outFile = (char*)malloc((n1+n2+1+5)*sizeof(char));
strcpy(outFile,outDir);
strcat(outFile,((*itr).first).c_str());
strcat(outFile,".tree");
FILE *fh = fOpen(outFile,"w");
writeTree(fh, node);
fclose(fh);
// write leaf labels to a file
vector<string> leaves;
leafLabels(node, leaves);
char *idsFile = (char*)malloc((n1+n2+1+5)*sizeof(char));
strcpy(idsFile,outDir);
strcat(idsFile,((*itr).first).c_str());
strcat(idsFile,".ids");
writeStrVector(idsFile, leaves);
}
}
// ------------------------------ hasSelSpp ------------------------
// Traverses the subtree of the current tree rooted at '_node'
// and checks if that tree contains all elements of v
//
// Returns true if all elements of v are in the subtree of _node
//
bool NewickTree_t::hasSelSpp(NewickNode_t *_node,
vector<NewickNode_t*> &v)
{
queue<NewickNode_t *> bfs;
bfs.push(_node);
NewickNode_t *node;
int countFoundNodes = 0; // count of nodes of v found in the subtree of _node
// table of indixes of nodes of v; return values of the table are not used
// the table is used only to find is a node is in v
map<int,bool> V;
int n = (int)v.size();
for ( int i = 0; i < n; i++ )
V[v[i]->idx] = true;
map<int,bool>::iterator it;
while ( !bfs.empty() )
{
node = bfs.front();
bfs.pop();
it = V.find(node->idx);
if ( it != V.end() )
countFoundNodes++;
int numChildren = node->children_m.size();
if ( numChildren!=0 ) // internal node
{
for (int i = 0; i < numChildren; i++)
{
bfs.push(node->children_m[i]);
}
}
}
return countFoundNodes == (int)v.size();
}
//--------------------------------------------- leafLabels -----
// Given a node in the tree, the routine gives leaf labels
// of the subtree rooted at 'node'.
void NewickTree_t::leafLabels(NewickNode_t *_node, vector<string> &leaves)
{
leaves.clear();
queue<NewickNode_t *> bfs;
bfs.push(_node);
NewickNode_t *node;
while ( !bfs.empty() )
{
node = bfs.front();
bfs.pop();
int numChildren = node->children_m.size();
if ( numChildren==0 ) // leaf
{
leaves.push_back( node->label );
}
else
{
for (int i = 0; i < numChildren; i++)
{
bfs.push(node->children_m[i]);
}
}
}
}
//--------------------------------------------- leafLabels -----
// Given a node in the tree, the routine returns a vector of pointes to leaf nodes
// of the subtree rooted at 'node'.
void NewickTree_t::leafLabels(NewickNode_t *_node, vector<NewickNode_t *> &leaves)
{
queue<NewickNode_t *> bfs;
bfs.push(_node);
NewickNode_t *node;
while ( !bfs.empty() )
{
node = bfs.front();
bfs.pop();
int numChildren = node->children_m.size();
if ( numChildren==0 ) // leaf
{
leaves.push_back( node );
}
else
{
for (int i = 0; i < numChildren; i++)
{
bfs.push(node->children_m[i]);
}
}
}
}
//--------------------------------------------- leafLabels -----
// Given a node in the tree, the routine returns a vector of pointes to leaf nodes
// (excluding a selected node) of the subtree rooted at 'node'.
void NewickTree_t::leafLabels(NewickNode_t *_node, vector<NewickNode_t *> &leaves, NewickNode_t *selNode)
{
queue<NewickNode_t *> bfs;
bfs.push(_node);
NewickNode_t *node;
while ( !bfs.empty() )
{
node = bfs.front();
bfs.pop();
int numChildren = node->children_m.size();
if ( numChildren==0 ) // leaf
{
if ( node != selNode )
leaves.push_back( node );
}
else
{
for (int i = 0; i < numChildren; i++)
{
bfs.push(node->children_m[i]);
}
}
}
}
//--------------------------------------------- leafLabels -----
// Given a node in the tree, the routine gives leaf labels
// of the subtree rooted at 'node'.
void NewickTree_t::leafLabels(NewickNode_t *_node, set<string> &leaves)
{
queue<NewickNode_t *> bfs;
bfs.push(_node);
NewickNode_t *node;
while ( !bfs.empty() )
{
node = bfs.front();
bfs.pop();
int numChildren = node->children_m.size();
if ( numChildren==0 ) // leaf
{
leaves.insert( node->label );
}
else
{
for (int i = 0; i < numChildren; i++)
{
bfs.push(node->children_m[i]);
}
}
}
}
//--------------------------------------------- getSppProfs -----
void NewickTree_t::getSppProfs( vector<sppProf_t*> &sppProfs,
vector<int> &nodeCut,
int *annIdx,
int minNA,
map<int, string> &idxToAnn,
map<string, string> &txParent)
/*
Given nodeCut + some other parameters
populate a vector of pointers to sppProf_t's
with i-th element of sppProfs corresponding to the i-th
node cut in nodeCut.
*/
{
map<int, NewickNode_t*> idx2node;
indexNewickNodes(idx2node);
int n = nodeCut.size();
for ( int i = 0; i < n; ++i )
{
map<string,int> annCount; // count of a given annotation string in the subtree of a given cut-node
queue<NewickNode_t *> bfs;
bfs.push(idx2node[nodeCut[i]]);
NewickNode_t *node;
int naCount = 0;
while ( !bfs.empty() )
{
node = bfs.front();
bfs.pop();
int numChildren = node->children_m.size();
if ( numChildren==0 ) // leaf
{
annCount[ idxToAnn[ annIdx[node->idx] ] ]++;
if ( annIdx[node->idx] == -2) naCount++;
}
else
{
for (int i = 0; i < numChildren; i++)
{
bfs.push(node->children_m[i]);
}
}
}
if ( naCount >= minNA )
{
map<string,int> sppFreq;
node = idx2node[nodeCut[i]]; // current node
NewickNode_t * ancNode;
if ( annCount.size() > 1 ) // there is at least one annotated element; setting cltrTx to annotation with the max frequency
{
cltrSpp(node, annIdx, idxToAnn, sppFreq); // table of species frequencies in the subtree of 'node'
ancNode = node;
}
else // there are no annotated sequences in the cluster; we are looking for the nearest ancestral node with known taxonomy
{
ancNode = node->parent_m; // looking at the parent node
int nSpp = cltrSpp(ancNode, annIdx, idxToAnn, sppFreq); // table of species frequencies in the subtree of 'node'
while ( nSpp==0 ) // if the parent node does not have any annotation sequences
{
ancNode = ancNode->parent_m; // move up to its parent node
nSpp = cltrSpp(ancNode, annIdx, idxToAnn, sppFreq);
}
//ancNode = ancNode->parent_m;
}
sppProf_t *sppProf = new sppProf_t();
sppProf->node = node;
sppProf->ancNode = ancNode;
sppProf->sppFreq = sppFreq;
sppProfs.push_back( sppProf );
}
}
}
#if 0
//--------------------------------------------- strMap2Set -----
set<string> NewickTree_t::strMap2Set(map<string,int> &sppFreq)
/*
Extracts keys from map<string,int> and puts them in to a set<string>
*/
{
set<string> sppSet;
map<string,int>::iterator it;
for (it = sppFreq.begin(); it != sppFreq.end(); ++it)
{
if ( (*it).first != "NA" )
{
sppSet.insert( (*it).first );
}
}
return sppSet;
}
#endif
//--------------------------------------------- strMap2Str -----
string NewickTree_t::strMap2Str(map<string,int> &sppFreq)
/*
Extracts keys from map<string,int>, sorts them and then concatenates them in to a string
*/
{
vector<string> spp;
map<string,int>::iterator it;
for (it = sppFreq.begin(); it != sppFreq.end(); ++it)
{
if ( (*it).first != "NA" )
{
spp.push_back( (*it).first );
}
}
sort (spp.begin(), spp.end());
string sppStr = spp[0];
int n = spp.size();
for ( int i = 1; i < n; i++ )
sppStr += string(".") + spp[i];
return sppStr;
}
//--------------------------------------------- getAncRoots -----
void NewickTree_t::getAncRoots(vector<sppProf_t*> &sppProfs,
vector<sppProf_t*> &ancRootProfs) // ancestral root nodes
/*
Finding root ancestral nodes, which are ancestral nodes of
sppProfs, such that on the path from the ancestral node to the root of the tree
there a no other ancestral nodes with the same species profile (excluding frequencies)
*/
{
// creating a table of indices of all ancestral nodes except those which are root_m or whose parent is root_m
// for the ease of identifying ancestral nodes on the path to the root_m
map<int, int> ancNodes;
int n = sppProfs.size();
for ( int i = 0; i < n; ++i )
{
NewickNode_t *node = sppProfs[i]->ancNode;
if ( node != root_m && node->parent_m != root_m )
{
//node = node->parent_m;
//fprintf(stderr,"i: %d\tidx: %d\r",i,node->idx);
ancNodes[ node->idx ] = i;
}
}
// iterating over all ancestral nodes and checking which of them have no other
// ancestral nodes on the path to root_m
for ( int i = 0; i < n; ++i )
{
if ( sppProfs[i]->ancNode == sppProfs[i]->node // cut node with some reference sequences in its subtree
|| sppProfs[i]->ancNode == root_m
|| (sppProfs[i]->ancNode)->parent_m == root_m )
{
ancRootProfs.push_back( sppProfs[i] );
}
else
{
NewickNode_t *node = sppProfs[i]->ancNode;
map<int,int>::iterator it;
while ( node != root_m )
{
if ( (it = ancNodes.find( node->idx )) != ancNodes.end() && // walking to the root_m, another ancestral node was found
strMap2Str(sppProfs[i]->sppFreq) == strMap2Str( sppProfs[it->second]->sppFreq ) ) // it->second is the index of the ancestral node in sppProfs that was found on the path to root_m
break;
node = node->parent_m;
}
if ( node == root_m ) // no ancestral nodes were found on the path to the root_m
ancRootProfs.push_back( sppProfs[i] );
}
}
}
//--------------------------------------------- rmTxErrors -----
void NewickTree_t::rmTxErrors( vector<sppProf_t*> &ancRootProfs,
int depth,
int *annIdx,
map<int, string> &idxToAnn)
/*
Changing taxonomic assignment in a situation when one species is contained in a
clade of another species of the same genus.
depth parameter controls how many ancestors we want to visit before making a decision.
If at the depth ancestor (going up towards the root) species frequencies are
1 (for the current node) and (depth-1) for other species of the same genus, then
sppFreq of the current node is replaced by the one of the other species nodes.
The modification are only applied to ancestral nodes with ancNode=node, because
others will have homogeneous clade structure by construction.
*/
{
int n = ancRootProfs.size();
for ( int i = 0; i < n; ++i )
{
if ( ancRootProfs[i]->ancNode == ancRootProfs[i]->node )
{
NewickNode_t *node = ancRootProfs[i]->ancNode;
for ( int j = 0; j < depth; j++ )
node = node->parent_m;
// compute sppFreq for node
map<string,int> sppFreq;
cltrSpp(node, annIdx, idxToAnn, sppFreq);
// finding max count species in the original node
// and comparing its frequency in sppFreq
//if ( sppFreq[ (ancRootProfs[i]->node)->label ] = sppFreq[
}
}
}
//--------------------------------------------- printTx -----
void NewickTree_t::printTx( const char *outFile,
vector<sppProf_t*> &ancRootProfs)
/*
Generating taxonomic assignment to all leaves of the tree.
The leaves of the subtree of a root ancestral node all have the same taxonomy
based on the majority vote at the species or genus level.
*/
{
FILE *fh = fOpen(outFile,"w");
int n = ancRootProfs.size();
for ( int i = 0; i < n; ++i )
{
NewickNode_t *node = ancRootProfs[i]->ancNode;
map<string,int> sppFreq = ancRootProfs[i]->sppFreq;
string cltrTx; // taxonomy for all query reads of the cluster with no annotated sequences
// determining taxonomy based on the majority vote
int maxCount = 0; // maximal species count
map<string,int>::iterator it;
for (it = sppFreq.begin(); it != sppFreq.end(); ++it)
{
if ( (*it).first != "NA" && (*it).second > maxCount )
{
maxCount = (*it).second;
cltrTx = (*it).first;
}
}
// propagating the taxonomy to all leaves of the subtree of the ancestral root node
vector<string> leaves;
leafLabels(node, leaves);
int m = leaves.size();
for ( int j = 0; j < m; j++ )
fprintf(fh, "%s\t%s\n", leaves[j].c_str(), cltrTx.c_str());
}
fclose(fh);
}
//---------------------------------------------------------- updateLabels ----
void NewickTree_t::updateLabels( strSet_t &tx2seqIDs )
/*
To test txSet2txTree() this routine updates tree labels so they
include the number of sequences associated with each node
*/
{
queue<NewickNode_t *> bfs;
bfs.push(root_m);
NewickNode_t *node;
strSet_t::iterator it;
char nStr[16];
while ( !bfs.empty() )
{
node = bfs.front();
bfs.pop();
if ( node != root_m )
{
it=tx2seqIDs.find( node->label );
if ( it != tx2seqIDs.end() )
{
int n = (it->second).size();
sprintf(nStr,"%d",n);
node->label += string("{") + string(nStr) + string("}");
}
else
{
fprintf(stderr,"ERROR in %s at line %d: node with label %s not found in tx2seqIDs map\n",
__FILE__,__LINE__, node->label.c_str());
exit(1);
}
}
int numChildren = node->children_m.size();
if ( numChildren )
{
for (int i = 0; i < numChildren; i++)
bfs.push(node->children_m[i]);
}
}
}
//---------------------------------------------------------- txSet2txTree ----
void NewickTree_t::txSet2txTree( strSet_t &tx2seqIDs )
/*
tx2seqIDs maps tx (assumed to be labels of the leaves of the tree) into set of
seqIDs corresponding to the given taxon, tx.
The routine extends tx2seqIDs to map also internal nodes to seqIDs associated
with the leaves of the corresponding subtree.
*/
{
queue<NewickNode_t *> bfs;
bfs.push(root_m);
NewickNode_t *node;
while ( !bfs.empty() )
{
node = bfs.front();
bfs.pop();
int numChildren = node->children_m.size();
if ( numChildren )
{
for (int i = 0; i < numChildren; i++)
{
bfs.push(node->children_m[i]);
set<string> seqIDs; // sequence IDs from all leaves of the subtree of node->children_m[i]
set<string> leaves;
leafLabels(node->children_m[i], leaves);
set<string>::iterator it;
for (it=leaves.begin(); it!=leaves.end(); it++)
{
set<string> ids = tx2seqIDs[ *it ];
set_union( seqIDs.begin(), seqIDs.end(),
ids.begin(), ids.end(),
inserter(seqIDs, seqIDs.begin()) );
}
if ( (node->children_m[i])->label.empty() )
{
cerr << "ERROR in " << __FILE__ << " at line " << __LINE__ << ": internal node is missing lable\n" << endl;
}
tx2seqIDs[ (node->children_m[i])->label ] = seqIDs;
}
}
}
}
//---------------------------------------------------------- inodeTx ----
void NewickTree_t::inodeTx( const char *fullTxFile, map<string, string> &inodeTx )
/*
Creating <interna node> => <taxonomy> table inodeTx
*/
{
// parse fullTxFile that has the following structure
// BVAB1 g_Shuttleworthia f_Lachnospiraceae o_Clostridiales c_Clostridia p_Firmicutes d_Bacteria
// BVAB2 g_Acetivibrio f_Ruminococcaceae o_Clostridiales c_Clostridia p_Firmicutes d_Bacteria
// BVAB3 g_Acetivibrio f_Ruminococcaceae o_Clostridiales c_Clostridia p_Firmicutes d_Bacteria
// Dialister_sp._type_1 g_Dialister f_Veillonellaceae o_Clostridiales c_Clostridia p_Firmicutes d_Bacteria
const int NUM_TX = 7;
char ***txTbl;
int nRows, nCols;
readCharTbl( fullTxFile, &txTbl, &nRows, &nCols );
#if 0
fprintf(stderr,"fullTxFile txTbl:\n");
printCharTbl(txTbl, 10, nCols); // test
#endif
map<string, vector<string> > fullTx; // fullTx[speciesName] = vector of the corresponding higher rank taxonomies
// for example
// BVAB1 g_Shuttleworthia f_Lachnospiraceae o_Clostridiales c_Clostridia p_Firmicutes d_Bacteria
// corresponds to
// fullTx[BVAB1] = (g_Shuttleworthia, f_Lachnospiraceae, o_Clostridiales, c_Clostridia, p_Firmicutes, d_Bacteria)
charTbl2strVect( txTbl, nRows, nCols, fullTx);
map<string, vector<string> >::iterator it1;
#if 0
map<string, vector<string> >::iterator it1;
for ( it1 = fullTx.begin(); it1 != fullTx.end(); it1++ )
{
fprintf(stderr, "%s: ", (it1->first).c_str());
vector<string> v = it1->second;
for ( int i = 0; i < (int)v.size(); i++ )
fprintf(stderr, "%s ", v[i].c_str());
fprintf(stderr, "\n");
}
for ( it1 = fullTx.begin(); it1 != fullTx.end(); it1++ )
{
vector<string> v = it1->second;
fprintf(stderr, "%s: %d\n", (it1->first).c_str(), (int)v.size());
}
fprintf(stderr, "after\n");
#endif
// traverse the tree and for each internal node find consensus taxonomic rank
// of all leaves of the corresponding subtree
queue<NewickNode_t *> bfs;
bfs.push(root_m);
NewickNode_t *node;
while ( !bfs.empty() )
{
node = bfs.front();
bfs.pop();
int numChildren = node->children_m.size();
if ( numChildren ) // internal node
{
for (int i = 0; i < numChildren; i++)
bfs.push(node->children_m[i]);
vector<string> spp;
leafLabels(node, spp);
int txIdx;
set<string> tx;
set<string>::iterator it;
for ( txIdx = 0; txIdx < NUM_TX; txIdx++ )
{
tx.erase( tx.begin(), tx.end() ); // erasing all elements of tx
int n = spp.size();
for ( int j = 0; j < n; j++ )
{
it1 = fullTx.find( spp[j] );
if ( it1==fullTx.end() )
fprintf(stderr, "%s not found in fullTx\n", spp[j].c_str());
tx.insert( fullTx[ spp[j] ][txIdx] );
}
if ( tx.size() == 1 )
break;
}
it = tx.begin(); // now it points to the first and unique element of tx
inodeTx[ node->label ] = *it;
}
}
}
//---------------------------------------------------------- modelIdx ----
// populate model_idx fields of all nodes of the tree
//
// when node labels correspond to model labels model_idx is the index of the node
// label in MarkovChains2_t's modelIds_m
void NewickTree_t::modelIdx( vector<string> &modelIds )
{
map<string, int> modelIdx;
int n = modelIds.size();
for ( int i = 0; i < n; i++ )
modelIdx[ modelIds[i] ] = i;
queue<NewickNode_t *> bfs;
bfs.push(root_m);
NewickNode_t *node;
map<string, int>::iterator it;
while ( !bfs.empty() )
{
node = bfs.front();
bfs.pop();
if ( node != root_m )
{
it = modelIdx.find( node->label );
if ( it != modelIdx.end() )
node->model_idx = modelIdx[ node->label ];
#if 0
else
fprintf(stderr, "ERROR in %s at line %d: Node label %s not found in modelIds\n",
__FILE__, __LINE__, (node->label).c_str());
#endif
}
int numChildren = node->children_m.size();
if ( numChildren ) // internal node
{
for (int i = 0; i < numChildren; i++)
bfs.push(node->children_m[i]);
}
}
}
// ----------------------------------------- readNewickNode() ---------------------------------
//
// This code was lifted/adopted from the spimap-1.1 package
// ~/devel/MCclassifier/packages/spimap-1.1/src
// http://compbio.mit.edu/spimap/
// https://academic.oup.com/mbe/article-lookup/doi/10.1093/molbev/msq189
//
float readDist( FILE *infile )
{
float dist = 0;
fscanf(infile, "%f", &dist);
return dist;
}
char readChar(FILE *stream, int &depth)
{
char chr;
do {
if (fread(&chr, sizeof(char), 1, stream) != 1) {
// indicate EOF
return '\0';
}
} while (chr == ' ' || chr == '\n');
// keep track of paren depth
if (chr == '(') depth++;
if (chr == ')') depth--;
return chr;
}
char readUntil(FILE *stream, string &token, const char *stops, int &depth)
{
char chr;
token = "";
while (true) {
chr = readChar(stream, depth);
if (!chr)
return chr;
// compare char to stop characters
for (const char *i=stops; *i; i++) {
if (chr == *i)
return chr;
}
token += chr;
}
}
string getIdent( int depth )
{
string identStr = "";
for ( int i = 0; i < depth; i++ )
{
identStr += string(" ");
}
return identStr;
}
NewickNode_t *readNewickNode(FILE *infile, NewickTree_t *tree, NewickNode_t *parent, int &depth)
{
#define DEBUG_RNN 0
#if DEBUG_RNN
string ident = getIdent( depth );
fprintf(stderr, "%sIn readNewickNode() depth: %d\n", ident.c_str(), depth);
#endif
char chr, char1;
NewickNode_t *node;
string token;
// read first character
if ( !(char1 = readChar(infile, depth)) )
{
fprintf(stderr, "\n\n\tERROR: Unexpected end of file\n\n");
exit(1);
}
if ( char1 == '(' ) // read internal node
{
int depth2 = depth;
if ( parent )
{
node = parent->addChild();
#if DEBUG_RNN
if ( depth )
{
string ident = getIdent( depth );
fprintf( stderr, "%sCurrently at depth: %d - Adding a child to a parent\n", ident.c_str(), depth );
}
else
{
fprintf( stderr, "Currently at depth: %d - Adding a child to a parent\n", depth );
}
#endif
}
else
{
node = new NewickNode_t();
tree->setRoot( node );
#if DEBUG_RNN
fprintf( stderr, "Currently at depth: %d - Creating a root\n", depth );
#endif
}
// updating node's depth
node->depth_m = depth - 1;
// read all child nodes at this depth
while ( depth == depth2 )
{
NewickNode_t *child = readNewickNode(infile, tree, node, depth);
if (!child)
return NULL;
}
// Assigning a numeric index to the node
node->idx = tree->getMinIdx();
tree->decrementMinIdx();
// read branch_length for this node
// this fragment assumes that the internal nodes do not have labels
char chr = readUntil(infile, token, "):,;", depth);
if ( !token.empty() ) // Reading node's label
{
node->label = trim(token.c_str());
#if DEBUG_RNN
string ident = getIdent( depth );
fprintf( stderr, "%sNode name: %s\n", ident.c_str(), token.c_str() );
#endif
}
if (chr == ':')
{
node->branch_length = readDist( infile );
#if DEBUG_RNN
string ident = getIdent( depth );
fprintf( stderr, "%snode->branch_length: %f\n", ident.c_str(), node->branch_length );
#endif
if ( !(chr = readUntil(infile, token, "):,;", depth)) )
return NULL;
}
//if (chr == ';' && depth == 0)
// return node;
#if DEBUG_RNN
string ident = getIdent( node->depth_m );
fprintf( stderr, "%sNode's depth: %d\n", ident.c_str(), node->depth_m );
#endif
return node;
}
else
{
// Parsing leaf
if (parent)
{
node = parent->addChild();
#if DEBUG_RNN
string ident = getIdent(depth);
fprintf( stderr, "%sCurrently at depth: %d - Found leaf: adding it as a child to a parent\n", ident.c_str(), depth );
#endif
}
else
{
fprintf( stderr, "\n\n\tERROR: Found leaf without a parent\n\n" );
exit(1);
}
// Assigning to the leaf a numeric index
node->idx = tree->leafCount();
tree->incrementLeafCount();
// updating leaf's depth
node->depth_m = depth;
// Reading leaf label
if ( !(chr = readUntil(infile, token, ":),", depth)) )
return NULL;
token = char1 + trim(token.c_str());
node->label = token;
#if DEBUG_RNN
string ident = getIdent( depth );
fprintf( stderr, "%sLeaf name: %s\tdepth: %d\tidx: %d\n", ident.c_str(), token.c_str(), node->depth_m, node->idx );
#endif
// read distance for this node
if (chr == ':')
{
node->branch_length = readDist( infile );
#if DEBUG_RNN
fprintf( stderr, "%sLeaf's branch length: %f\n", ident.c_str(), node->branch_length );
#endif
if ( !(chr = readUntil( infile, token, ":),", depth )) )
return NULL;
}
return node;
}
}
NewickTree_t *readNewickTree( const char *filename )
{
FILE *infile = fOpen(filename, "r");
int depth = 0;
NewickTree_t *tree = new NewickTree_t();
NewickNode_t * node = readNewickNode(infile, tree, NULL, depth);
tree->setRoot( node );
fclose(infile);
return tree;
}
| 26.118616 | 185 | 0.579848 | pgajer |
82065130c76b5a7180c49205b158a6d4e4d00465 | 12,525 | cpp | C++ | src/presentation.cpp | dashboardvision/aspose-php | e2931773cbb1f47ae4086d632faa3012bd952b99 | [
"MIT"
] | null | null | null | src/presentation.cpp | dashboardvision/aspose-php | e2931773cbb1f47ae4086d632faa3012bd952b99 | [
"MIT"
] | null | null | null | src/presentation.cpp | dashboardvision/aspose-php | e2931773cbb1f47ae4086d632faa3012bd952b99 | [
"MIT"
] | 1 | 2021-06-23T08:02:03.000Z | 2021-06-23T08:02:03.000Z | #include "../include/aspose.h"
#include "../include/presentation.h"
#include "../include/slide.h"
#include "../include/islide_collection.h"
#include "../include/slide_size.h"
#include <phpcpp.h>
#include <iostream>
#include "../include/master-slide-collection.h"
#include "../include/image-collection.h"
using namespace Aspose::Slides;
using namespace Aspose::Slides::Export;
using namespace System;
using namespace System::Collections::Generic;
using namespace std;
using namespace System::IO;
namespace AsposePhp {
/**
* @brief PHP Constructor
*
* @param params Path to presentation file to read. This is optional. If not defined, an empty presentation will be created.
*/
void Presentation::__construct(Php::Parameters ¶ms)
{
this->load(params);
if(params.size() > 1) {
this->loadLicense(params);
}
}
/**
* @brief Loads license file
*
* @param params Has one param, the path
*
* @throw System::ArgumentException path is invalid
* @throw System::IO::FileNotFoundException File does not exist
* @throw System::UnauthorizedAccessException Has no right access file
* @throw System::Xml::XmlException File contains invalid XML
*
*/
void Presentation::loadLicense(Php::Parameters ¶ms) {
std::string licensePath = params[1].stringValue();
try {
SharedPtr<Aspose::Slides::License> lic = MakeObject<Aspose::Slides::License>();
lic->SetLicense(String(licensePath));
if(!lic->IsLicensed()) {
throw Php::Exception("Invalid license");
}
}
catch(System::ArgumentException &e) {
throw Php::Exception(e.what());
}
catch(System::IO::FileNotFoundException &e) {
throw Php::Exception(e.what());
}
catch(System::UnauthorizedAccessException &e) {
throw Php::Exception(e.what());
}
catch(System::Xml::XmlException &e) {
throw Php::Exception(e.what());
}
catch(System::InvalidOperationException &e) {
throw Php::Exception(e.what());
}
catch(...) {
throw Php::Exception("Unknown error. Unable to loead license file..");
}
}
/**
* @brief Loads a presentation file.
*
* @param params Path to presentation to read.
*
* @throw System::ArgumentException path is invalid
* @throw System::IO::FileNotFoundException File does not exist
* @throw System::UnauthorizedAccessException Has no right access file
* @return Php::Value
*/
Php::Value Presentation::load(Php::Parameters ¶ms) {
std::string path = params[0].stringValue();
// std::string licencePath = params[1].stringValue();
const String templatePath = String(path);
SharedPtr<LoadOptions> loadOptions = MakeObject<LoadOptions>();
try {
_pres = MakeObject<Aspose::Slides::Presentation>(templatePath);
_slides = _pres->get_Slides();
SharedPtr<PresentationFactory> pFactory = PresentationFactory::get_Instance();
_slideText = pFactory->GetPresentationText(templatePath, TextExtractionArrangingMode::Unarranged)->get_SlidesText();
}
catch(System::ArgumentException &e) {
throw Php::Exception(e.what());
}
catch(System::IO::FileNotFoundException &e) {
throw Php::Exception(e.what());
}
catch(System::UnauthorizedAccessException &e) {
throw Php::Exception(e.what());
}
catch(...) {
throw Php::Exception("Uknown error. Unable to loead input file..");
}
return this;
}
/**
* @brief Writes the presentaton to disk or returns it as byte array.
*
* @param params Output path. File must not exist.
* @param params file format.
* @param params AsArray if true, byte array will be returned.
*
* @throw System::IO::IOException cannot access path
* @throw System::UnauthorizedAccessException Has no right access file
*/
Php::Value Presentation::save(Php::Parameters ¶ms) {
String outfile = String(params[0].stringValue());
std::string fmt = params[1].stringValue();
bool asArray = params[2].boolValue();
SaveFormat format = SaveFormat::Ppt;
ArrayPtr<string> formats = new Array<string>(vector<string> {"ppt", "pptx"});
if(formats->IndexOf(fmt) != -1) {
if(fmt == "ppt") {
format = SaveFormat::Ppt;
} else if(fmt == "pptx") {
format = SaveFormat::Pptx;
}
try {
if(asArray) {
SharedPtr<MemoryStream> stream = MakeObject<MemoryStream>();
_pres->Save(stream, format);
vector<uint8_t> res = stream->ToArray()->data();
return Php::Array(res);
} else {
SharedPtr<Stream> stream = MakeObject<FileStream>(outfile, FileMode::Create);
_pres->Save(stream, format);
}
}
catch(System::IO::IOException &e) {
throw Php::Exception(e.what());
}
catch(System::UnauthorizedAccessException &e) {
throw Php::Exception(e.what());
}
catch(...) {
throw Php::Exception("Uknown error. Unable to write output file..");
}
} else {
throw Php::Exception("Uknown format.");
}
return nullptr;
}
/**
* @brief Clones the slide with given index.
*
* @param params 0 based index of the slide to be cloned
*
* @throw System::ArgumentOutOfRangeException slide index does not exist
* @throw Aspose::Slides::PptxEditException PPT modification failed.
*/
void Presentation::cloneSlide(Php::Parameters ¶ms) {
int slideNo = params[0].numericValue();
try {
_slides->AddClone(_slides->idx_get(slideNo));
}
catch(System::ArgumentOutOfRangeException &e) {
throw Php::Exception("Invalid index: " + to_string(slideNo));
}
catch(Aspose::Slides::PptxEditException &e) {
throw Php::Exception(e.what());
}
catch(...) {
throw Php::Exception("Uknown error. Unable to clone slide..");
}
}
/**
* @brief Returns all text from presentation as string. Does NOT include charts and tables.
*
* @param params An array with 2 string elements: a path to the presentation file and a
* type indicating which type of text should be returned. Type can be either of the following:
* - master
* - layout
* - notes
* - all
*
* @throw System::ArgumentException path is invalid
* @throw System::IO::FileNotFoundException File does not exist
* @throw System::UnauthorizedAccessException Has no right access file
* @return Php::Value
*/
Php::Value Presentation::getPresentationText(Php::Parameters ¶ms) {
std::string path = params[0].stringValue();
std::string type = params[1].stringValue();
String templatePath = String(path);
try {
SharedPtr<PresentationFactory> pFactory = PresentationFactory::get_Instance();
ArrayPtr<SharedPtr<ISlideText>> text = pFactory->GetPresentationText(templatePath, TextExtractionArrangingMode::Unarranged)->get_SlidesText();
string texts = "";
for (int i = 0; i < text->get_Length(); i++) {
if(type == "all") {
texts += text[i]->get_Text().ToUtf8String();
} else if(type == "master") {
texts += text[i]->get_MasterText().ToUtf8String();
} else if(type == "layout") {
texts += text[i]->get_LayoutText().ToUtf8String();
} else if(type == "notes") {
texts += text[i]->get_NotesText().ToUtf8String();
}
}
return texts;
}
catch(System::ArgumentException &e) {
throw Php::Exception(e.what());
}
catch(System::IO::FileNotFoundException &e) {
throw Php::Exception(e.what());
}
catch(System::UnauthorizedAccessException &e) {
throw Php::Exception(e.what());
}
}
/**
* @brief Returns the number of slides in presentation.
*
* @return Php::Value
*/
Php::Value Presentation::getNumberOfSlides() {
return _pres->get_Slides()->get_Count();
}
/**
* @brief Returns an array of slides as Slide objects.
*
* @return Php::Value
*/
Php::Value Presentation::getSlides() {
ISlideCollection* coll = new ISlideCollection(_slides);
return Php::Object("AsposePhp\\Slides\\ISlideCollection", coll);
}
/**
* @brief Returns slide size object
*
* @return Php::Value
*/
Php::Value Presentation::get_SlideSize() {
SlideSize * size = new SlideSize(_pres->get_SlideSize());
return Php::Object("AsposePhp\\Slides\\SlideSize", size);
}
Php::Value Presentation::getSlides2() {
if(_slides == nullptr) {
_slides = _pres->get_Slides();
}
int32_t slideCount = _slides->get_Count();
int32_t slideTextCount = _slideText->get_Count();
vector<Php::Object> slideArr;
SmartPtr<ISlide> slide;
try {
for(int i = 0; i < slideCount; i++) {
slide = _slides->idx_get(i);
AsposePhp::Slide* phpSlide;
if(i >= slideTextCount) {
phpSlide = new AsposePhp::Slide(slide, "", "", "", slide->get_SlideNumber());
} else {
phpSlide = new AsposePhp::Slide(slide,
_slideText[i]->get_LayoutText().ToUtf8String(),
_slideText[i]->get_NotesText().ToUtf8String(),
_slideText[i]->get_MasterText().ToUtf8String(), slide->get_SlideNumber());
}
slideArr.push_back(Php::Object("AsposePhp\\Slides\\Slide", phpSlide));
}
return Php::Array(slideArr);
}
catch(ArgumentOutOfRangeException &e) {
return nullptr;
}
}
/**
* @brief Returns a specific slide by index.
*
* @param params The 0 based index of the slide.
*
* @throw System::ArgumentOutOfRangeException index does not exist.
* @return Php::Value
*/
Php::Value Presentation::getSlide(Php::Parameters ¶ms) {
int slideNo = params[0].numericValue();
try {
SharedPtr<ISlide> slide = _pres->get_Slides()->idx_get(slideNo);
Slide* ret = new Slide(slide,
_slideText[slideNo]->get_LayoutText().ToUtf8String(),
_slideText[slideNo]->get_NotesText().ToUtf8String(),
_slideText[slideNo]->get_MasterText().ToUtf8String(),
slide->get_SlideNumber());
return Php::Object("AsposePhp\\Slides\\Slide", ret);
}
catch(System::ArgumentOutOfRangeException &e) {
throw Php::Exception("Invalid index: " + to_string(slideNo));
}
}
/**
* @brief Returns a list of all master slides that are defined in the presentation. Read-only IMasterSlideCollection
*
* @return Php::Value
*/
Php::Value Presentation::get_Masters() {
SharedPtr<IMasterSlideCollection> items = _pres->get_Masters();
MasterSlideCollection * phpValue = new MasterSlideCollection(items);
return Php::Object("AsposePhp\\Slides\\MasterSlideCollection", phpValue);
}
/**
* @brief Returns the collection of all images in the presentation. Read-only IImageCollection
*
* @return Php::Value
*/
Php::Value Presentation::get_Images() {
SharedPtr<IImageCollection> items = _pres->get_Images();
ImageCollection * phpValue = new ImageCollection(items);
return Php::Object("AsposePhp\\Slides\\ImageCollection", phpValue);
}
}
| 33.943089 | 155 | 0.568862 | dashboardvision |
82091dab0964d78b4350f72917e686eca57d575c | 5,848 | cpp | C++ | Turso3D/Graphics/D3D11/D3D11ShaderVariation.cpp | cadaver/turso3d | 5659df48b7915b95a351dfcad382b3ed653573f2 | [
"Zlib"
] | 29 | 2015-03-21T22:35:50.000Z | 2022-01-25T04:13:46.000Z | Turso3D/Graphics/D3D11/D3D11ShaderVariation.cpp | cadaver/turso3d | 5659df48b7915b95a351dfcad382b3ed653573f2 | [
"Zlib"
] | 1 | 2016-10-23T16:20:14.000Z | 2018-04-13T13:32:13.000Z | Turso3D/Graphics/D3D11/D3D11ShaderVariation.cpp | cadaver/turso3d | 5659df48b7915b95a351dfcad382b3ed653573f2 | [
"Zlib"
] | 8 | 2015-09-28T06:26:41.000Z | 2020-12-28T14:29:51.000Z | // For conditions of distribution and use, see copyright notice in License.txt
#include "../../Debug/Log.h"
#include "../../Debug/Profiler.h"
#include "../Shader.h"
#include "D3D11Graphics.h"
#include "D3D11ShaderVariation.h"
#include "D3D11VertexBuffer.h"
#include <d3d11.h>
#include <d3dcompiler.h>
#include "../../Debug/DebugNew.h"
namespace Turso3D
{
unsigned InspectInputSignature(ID3DBlob* d3dBlob)
{
ID3D11ShaderReflection* reflection = nullptr;
D3D11_SHADER_DESC shaderDesc;
unsigned elementHash = 0;
D3DReflect(d3dBlob->GetBufferPointer(), d3dBlob->GetBufferSize(), IID_ID3D11ShaderReflection, (void**)&reflection);
if (!reflection)
{
LOGERROR("Failed to reflect vertex shader's input signature");
return elementHash;
}
reflection->GetDesc(&shaderDesc);
for (size_t i = 0; i < shaderDesc.InputParameters; ++i)
{
D3D11_SIGNATURE_PARAMETER_DESC paramDesc;
reflection->GetInputParameterDesc((unsigned)i, ¶mDesc);
for (size_t j = 0; elementSemanticNames[j]; ++j)
{
if (!String::Compare(paramDesc.SemanticName, elementSemanticNames[j]))
{
elementHash |= VertexBuffer::ElementHash(i, (ElementSemantic)j);
break;
}
}
}
reflection->Release();
return elementHash;
}
ShaderVariation::ShaderVariation(Shader* parent_, const String& defines_) :
parent(parent_),
stage(parent->Stage()),
defines(defines_),
blob(nullptr),
shader(nullptr),
elementHash(0),
compiled(false)
{
}
ShaderVariation::~ShaderVariation()
{
Release();
}
void ShaderVariation::Release()
{
if (graphics && (graphics->GetVertexShader() == this || graphics->GetPixelShader() == this))
graphics->SetShaders(nullptr, nullptr);
if (blob)
{
ID3DBlob* d3dBlob = (ID3DBlob*)blob;
d3dBlob->Release();
blob = nullptr;
}
if (shader)
{
if (stage == SHADER_VS)
{
ID3D11VertexShader* d3dShader = (ID3D11VertexShader*)shader;
d3dShader->Release();
}
else
{
ID3D11PixelShader* d3dShader = (ID3D11PixelShader*)shader;
d3dShader->Release();
}
shader = nullptr;
}
elementHash = 0;
compiled = false;
}
bool ShaderVariation::Compile()
{
if (compiled)
return shader != nullptr;
PROFILE(CompileShaderVariation);
// Do not retry without a Release() inbetween
compiled = true;
if (!graphics || !graphics->IsInitialized())
{
LOGERROR("Can not compile shader without initialized Graphics subsystem");
return false;
}
if (!parent)
{
LOGERROR("Can not compile shader without parent shader resource");
return false;
}
// Collect defines into macros
Vector<String> defineNames = defines.Split(' ');
Vector<String> defineValues;
Vector<D3D_SHADER_MACRO> macros;
for (size_t i = 0; i < defineNames.Size(); ++i)
{
size_t equalsPos = defineNames[i].Find('=');
if (equalsPos != String::NPOS)
{
defineValues.Push(defineNames[i].Substring(equalsPos + 1));
defineNames[i].Resize(equalsPos);
}
else
defineValues.Push("1");
}
for (size_t i = 0; i < defineNames.Size(); ++i)
{
D3D_SHADER_MACRO macro;
macro.Name = defineNames[i].CString();
macro.Definition = defineValues[i].CString();
macros.Push(macro);
}
D3D_SHADER_MACRO endMacro;
endMacro.Name = nullptr;
endMacro.Definition = nullptr;
macros.Push(endMacro);
/// \todo Level 3 could be used, but can lead to longer shader compile times, considering there is no binary caching yet
DWORD flags = D3DCOMPILE_OPTIMIZATION_LEVEL2 | D3DCOMPILE_PREFER_FLOW_CONTROL;
ID3DBlob* errorBlob = nullptr;
if (FAILED(D3DCompile(parent->SourceCode().CString(), parent->SourceCode().Length(), "", ¯os[0], 0, "main",
stage == SHADER_VS ? "vs_4_0" : "ps_4_0", flags, 0, (ID3DBlob**)&blob, &errorBlob)))
{
if (errorBlob)
{
LOGERRORF("Could not compile shader %s: %s", FullName().CString(), errorBlob->GetBufferPointer());
errorBlob->Release();
}
return false;
}
if (errorBlob)
{
errorBlob->Release();
errorBlob = nullptr;
}
ID3D11Device* d3dDevice = (ID3D11Device*)graphics->D3DDevice();
ID3DBlob* d3dBlob = (ID3DBlob*)blob;
#ifdef SHOW_DISASSEMBLY
ID3DBlob* asmBlob = nullptr;
D3DDisassemble(d3dBlob->GetBufferPointer(), d3dBlob->GetBufferSize(), 0, nullptr, &asmBlob);
if (asmBlob)
{
String text((const char*)asmBlob->GetBufferPointer(), asmBlob->GetBufferSize());
LOGINFOF("Shader %s disassembly: %s", FullName().CString(), text.CString());
asmBlob->Release();
}
#endif
if (stage == SHADER_VS)
{
elementHash = InspectInputSignature(d3dBlob);
d3dDevice->CreateVertexShader(d3dBlob->GetBufferPointer(), d3dBlob->GetBufferSize(), 0, (ID3D11VertexShader**)&shader);
}
else
d3dDevice->CreatePixelShader(d3dBlob->GetBufferPointer(), d3dBlob->GetBufferSize(), 0, (ID3D11PixelShader**)&shader);
if (!shader)
{
LOGERROR("Failed to create shader " + FullName());
return false;
}
else
LOGDEBUGF("Compiled shader %s bytecode size %u", FullName().CString(), (unsigned)d3dBlob->GetBufferSize());
return true;
}
Shader* ShaderVariation::Parent() const
{
return parent;
}
String ShaderVariation::FullName() const
{
if (parent)
return defines.IsEmpty() ? parent->Name() : parent->Name() + " (" + defines + ")";
else
return String::EMPTY;
}
} | 27.455399 | 127 | 0.619015 | cadaver |
820cdf3a3d77a20635d03b3abed4fc05e66f4cd5 | 18,023 | cpp | C++ | src/ConEmu/AboutDlg.cpp | clcarwin/ConEmu_lite | f7ed818f8ba52677d3787c180579558c4296f810 | [
"MIT"
] | null | null | null | src/ConEmu/AboutDlg.cpp | clcarwin/ConEmu_lite | f7ed818f8ba52677d3787c180579558c4296f810 | [
"MIT"
] | null | null | null | src/ConEmu/AboutDlg.cpp | clcarwin/ConEmu_lite | f7ed818f8ba52677d3787c180579558c4296f810 | [
"MIT"
] | null | null | null |
// WM_DRAWITEM, SS_OWNERDRAW|SS_NOTIFY, Bmp & hBmp -> global vars
// DPI resize.
/*
Copyright (c) 2014-2017 Maximus5
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 name of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''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 AUTHOR 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.
*/
#undef HIDE_USE_EXCEPTION_INFO
#define SHOWDEBUGSTR
#include "Header.h"
#include "About.h"
#include "AboutDlg.h"
#include "ConEmu.h"
#include "DpiAware.h"
#include "DynDialog.h"
#include "ImgButton.h"
#include "LngRc.h"
#include "OptionsClass.h"
#include "PushInfo.h"
#include "RealConsole.h"
#include "SearchCtrl.h"
#include "Update.h"
#include "VirtualConsole.h"
#include "VConChild.h"
#include "version.h"
#include "../common/MSetter.h"
#include "../common/WObjects.h"
#include "../common/StartupEnvEx.h"
namespace ConEmuAbout
{
void InitCommCtrls();
bool mb_CommCtrlsInitialized = false;
HWND mh_AboutDlg = NULL;
DWORD nLastCrashReported = 0;
CDpiForDialog* mp_DpiAware = NULL;
INT_PTR WINAPI aboutProc(HWND hDlg, UINT messg, WPARAM wParam, LPARAM lParam);
void searchProc(HWND hDlg, HWND hSearch, bool bReentr);
void OnInfo_DonateLink();
void OnInfo_FlattrLink();
CImgButtons* mp_ImgBtn = NULL;
static struct {LPCWSTR Title; LPCWSTR Text;} Pages[] =
{
{L"About", pAbout},
{L"ConEmu /?", pCmdLine},
{L"Tasks", pAboutTasks},
{L"-new_console", pNewConsoleHelpFull},
{L"ConEmuC /?", pConsoleHelpFull},
{L"Macro", pGuiMacro},
{L"DosBox", pDosBoxHelpFull},
{L"Contributors", pAboutContributors},
{L"License", pAboutLicense},
{L"SysInfo", L""},
};
wchar_t sLastOpenTab[32] = L"";
void TabSelected(HWND hDlg, int idx);
wchar_t* gsSysInfo = NULL;
void ReloadSysInfo();
void LogStartEnvInt(LPCWSTR asText, LPARAM lParam, bool bFirst, bool bNewLine);
DWORD nTextSelStart = 0, nTextSelEnd = 0;
};
INT_PTR WINAPI ConEmuAbout::aboutProc(HWND hDlg, UINT messg, WPARAM wParam, LPARAM lParam)
{
INT_PTR lRc = 0;
if ((mp_ImgBtn && mp_ImgBtn->Process(hDlg, messg, wParam, lParam, lRc))
|| EditIconHint_Process(hDlg, messg, wParam, lParam, lRc))
{
SetWindowLongPtr(hDlg, DWLP_MSGRESULT, lRc);
return TRUE;
}
PatchMsgBoxIcon(hDlg, messg, wParam, lParam);
switch (messg)
{
case WM_INITDIALOG:
{
gpConEmu->OnOurDialogOpened();
mh_AboutDlg = hDlg;
CDynDialog::LocalizeDialog(hDlg);
_ASSERTE(mp_ImgBtn==NULL);
SafeDelete(mp_ImgBtn);
mp_ImgBtn = new CImgButtons(hDlg, pIconCtrl, IDOK);
mp_ImgBtn->AddDonateButtons();
if (mp_DpiAware)
{
mp_DpiAware->Attach(hDlg, ghWnd, CDynDialog::GetDlgClass(hDlg));
}
CDpiAware::CenterDialog(hDlg);
if ((ghOpWnd && IsWindow(ghOpWnd)) || (WS_EX_TOPMOST & GetWindowLongPtr(ghWnd, GWL_EXSTYLE)))
{
SetWindowPos(hDlg, HWND_TOPMOST, 0,0,0,0, SWP_NOMOVE|SWP_NOSIZE);
}
LPCWSTR pszActivePage = (LPCWSTR)lParam;
LPCWSTR psStage = (ConEmuVersionStage == CEVS_STABLE) ? L"{Stable}"
: (ConEmuVersionStage == CEVS_PREVIEW) ? L"{Preview}"
: L"{Alpha}";
CEStr lsTitle(
CLngRc::getRsrc(lng_DlgAbout/*"About"*/),
L" ",
gpConEmu->GetDefaultTitle(),
L" ",
psStage,
NULL);
if (lsTitle)
{
SetWindowText(hDlg, lsTitle);
}
if (hClassIcon)
{
SendMessage(hDlg, WM_SETICON, ICON_BIG, (LPARAM)hClassIcon);
SendMessage(hDlg, WM_SETICON, ICON_SMALL, (LPARAM)CreateNullIcon());
SetClassLongPtr(hDlg, GCLP_HICON, (LONG_PTR)hClassIcon);
}
// "Console Emulation program (local terminal)"
SetDlgItemText(hDlg, stConEmuAbout, CLngRc::getRsrc(lng_AboutAppName));
SetDlgItemText(hDlg, stConEmuUrl, gsHomePage);
EditIconHint_Set(hDlg, GetDlgItem(hDlg, tAboutSearch), true,
CLngRc::getRsrc(lng_Search/*"Search"*/),
false, UM_SEARCH, IDOK);
EditIconHint_Subclass(hDlg);
wchar_t* pszLabel = GetDlgItemTextPtr(hDlg, stConEmuVersion);
if (pszLabel)
{
wchar_t* pszSet = NULL;
if (gpUpd)
{
wchar_t* pszVerInfo = gpUpd->GetCurVerInfo();
if (pszVerInfo)
{
pszSet = lstrmerge(pszLabel, L" ", pszVerInfo);
free(pszVerInfo);
}
}
if (!pszSet)
{
pszSet = lstrmerge(pszLabel, L" ", CLngRc::getRsrc(lng_PleaseCheckManually/*"Please check for updates manually"*/));
}
if (pszSet)
{
SetDlgItemText(hDlg, stConEmuVersion, pszSet);
free(pszSet);
}
free(pszLabel);
}
HWND hTab = GetDlgItem(hDlg, tbAboutTabs);
INT_PTR nPage = -1;
for (size_t i = 0; i < countof(Pages); i++)
{
TCITEM tie = {};
tie.mask = TCIF_TEXT;
tie.pszText = (LPWSTR)Pages[i].Title;
TabCtrl_InsertItem(hTab, i, &tie);
if (pszActivePage && (lstrcmpi(pszActivePage, Pages[i].Title) == 0))
nPage = i;
}
if (nPage >= 0)
{
TabSelected(hDlg, nPage);
TabCtrl_SetCurSel(hTab, (int)nPage);
}
else if (!pszActivePage)
{
TabSelected(hDlg, 0);
}
else
{
_ASSERTE(pszActivePage==NULL && "Unknown page name?");
}
SetFocus(hTab);
return FALSE;
}
case WM_CTLCOLORSTATIC:
if (GetWindowLongPtr((HWND)lParam, GWLP_ID) == stConEmuUrl)
{
SetTextColor((HDC)wParam, GetSysColor(COLOR_HOTLIGHT));
HBRUSH hBrush = GetSysColorBrush(COLOR_3DFACE);
SetBkMode((HDC)wParam, TRANSPARENT);
return (INT_PTR)hBrush;
}
else
{
SetTextColor((HDC)wParam, GetSysColor(COLOR_WINDOWTEXT));
HBRUSH hBrush = GetSysColorBrush(COLOR_3DFACE);
SetBkMode((HDC)wParam, TRANSPARENT);
return (INT_PTR)hBrush;
}
break;
case WM_SETCURSOR:
{
if (GetWindowLongPtr((HWND)wParam, GWLP_ID) == stConEmuUrl)
{
SetCursor(LoadCursor(NULL, IDC_HAND));
SetWindowLongPtr(hDlg, DWLP_MSGRESULT, TRUE);
return TRUE;
}
return FALSE;
}
break;
case WM_COMMAND:
switch (HIWORD(wParam))
{
case BN_CLICKED:
switch (LOWORD(wParam))
{
case IDOK:
case IDCANCEL:
case IDCLOSE:
aboutProc(hDlg, WM_CLOSE, 0, 0);
return 1;
case stConEmuUrl:
ConEmuAbout::OnInfo_HomePage();
return 1;
} // BN_CLICKED
break;
case EN_SETFOCUS:
switch (LOWORD(wParam))
{
case tAboutText:
{
// Do not autosel all text
HWND hEdit = (HWND)lParam;
DWORD nStart = 0, nEnd = 0;
SendMessage(hEdit, EM_GETSEL, (WPARAM)&nStart, (LPARAM)&nEnd);
if (nStart != nEnd)
{
SendMessage(hEdit, EM_SETSEL, nTextSelStart, nTextSelEnd);
}
}
break;
}
} // switch (HIWORD(wParam))
break;
case WM_NOTIFY:
{
LPNMHDR nmhdr = (LPNMHDR)lParam;
if ((nmhdr->code == TCN_SELCHANGE) && (nmhdr->idFrom == tbAboutTabs))
{
int iPage = TabCtrl_GetCurSel(nmhdr->hwndFrom);
if ((iPage >= 0) && (iPage < (int)countof(Pages)))
TabSelected(hDlg, iPage);
}
break;
}
case UM_SEARCH:
searchProc(hDlg, (HWND)lParam, false);
break;
case UM_EDIT_KILL_FOCUS:
SendMessage((HWND)lParam, EM_GETSEL, (WPARAM)&nTextSelStart, (LPARAM)&nTextSelEnd);
break;
case WM_CLOSE:
//if (ghWnd == NULL)
gpConEmu->OnOurDialogClosed();
if (mp_DpiAware)
mp_DpiAware->Detach();
EndDialog(hDlg, IDOK);
SafeDelete(mp_ImgBtn);
break;
case WM_DESTROY:
mh_AboutDlg = NULL;
break;
default:
if (mp_DpiAware && mp_DpiAware->ProcessDpiMessages(hDlg, messg, wParam, lParam))
{
return TRUE;
}
}
return FALSE;
}
void ConEmuAbout::searchProc(HWND hDlg, HWND hSearch, bool bReentr)
{
HWND hEdit = GetDlgItem(hDlg, tAboutText);
wchar_t* pszPart = GetDlgItemTextPtr(hSearch, 0);
wchar_t* pszText = GetDlgItemTextPtr(hEdit, 0);
bool bRetry = false;
if (pszPart && *pszPart && pszText && *pszText)
{
LPCWSTR pszFrom = pszText;
DWORD nStart = 0, nEnd = 0;
SendMessage(hEdit, EM_GETSEL, (WPARAM)&nStart, (LPARAM)&nEnd);
size_t cchMax = wcslen(pszText);
size_t cchFrom = max(nStart,nEnd);
if (cchMax > cchFrom)
pszFrom += cchFrom;
LPCWSTR pszFind = StrStrI(pszFrom, pszPart);
if (!pszFind && bReentr && (pszFrom != pszText))
pszFind = StrStrI(pszText, pszPart);
if (pszFind)
{
const wchar_t szBrkChars[] = L"()[]<>{}:;,.-=\\/ \t\r\n";
LPCWSTR pszEnd = wcspbrk(pszFind, szBrkChars);
INT_PTR nPartLen = wcslen(pszPart);
if (!pszEnd || ((pszEnd - pszFind) > max(nPartLen,60)))
pszEnd = pszFind + nPartLen;
while ((pszFind > pszFrom) && !wcschr(szBrkChars, *(pszFind-1)))
pszFind--;
//SetFocus(hEdit);
nTextSelStart = (DWORD)(pszEnd-pszText);
nTextSelEnd = (DWORD)(pszFind-pszText);
SendMessage(hEdit, EM_SETSEL, nTextSelStart, nTextSelEnd);
SendMessage(hEdit, EM_SCROLLCARET, 0, 0);
}
else if (!bReentr)
{
HWND hTab = GetDlgItem(hDlg, tbAboutTabs);
int iPage = TabCtrl_GetCurSel(hTab);
int iFound = -1;
for (int s = 0; (iFound == -1) && (s <= 1); s++)
{
int iFrom = (s == 0) ? (iPage+1) : 0;
int iTo = (s == 0) ? (int)countof(Pages) : (iPage-1);
for (int i = iFrom; i < iTo; i++)
{
if (StrStrI(Pages[i].Title, pszPart)
|| StrStrI(Pages[i].Text, pszPart))
{
iFound = i; break;
}
}
}
if (iFound >= 0)
{
TabSelected(hDlg, iFound);
TabCtrl_SetCurSel(hTab, iFound);
//SetFocus(hEdit);
bRetry = true;
}
}
}
SafeFree(pszPart);
SafeFree(pszText);
if (bRetry)
{
searchProc(hDlg, hSearch, true);
}
}
void ConEmuAbout::InitCommCtrls()
{
if (mb_CommCtrlsInitialized)
return;
INITCOMMONCONTROLSEX icex;
icex.dwSize = sizeof(INITCOMMONCONTROLSEX);
icex.dwICC = ICC_COOL_CLASSES|ICC_BAR_CLASSES|ICC_TAB_CLASSES|ICC_PROGRESS_CLASS; //|ICC_STANDARD_CLASSES|ICC_WIN95_CLASSES;
InitCommonControlsEx(&icex);
mb_CommCtrlsInitialized = true;
}
void ConEmuAbout::OnInfo_OnlineWiki(LPCWSTR asPageName /*= NULL*/)
{
CEStr szUrl(CEWIKIBASE, asPageName ? asPageName : L"TableOfContents", L".html");
DWORD shellRc = (DWORD)(INT_PTR)ShellExecute(ghWnd, L"open", szUrl, NULL, NULL, SW_SHOWNORMAL);
if (shellRc <= 32)
{
DisplayLastError(L"ShellExecute failed", shellRc);
}
}
void ConEmuAbout::OnInfo_Donate()
{
int nBtn = MsgBox(
L"You can show your appreciation and support future development by donating.\n\n"
L"Open ConEmu's donate web page?"
,MB_YESNO|MB_ICONINFORMATION);
if (nBtn == IDYES)
{
OnInfo_DonateLink();
//OnInfo_HomePage();
}
}
void ConEmuAbout::OnInfo_DonateLink()
{
DWORD shellRc = (DWORD)(INT_PTR)ShellExecute(ghWnd, L"open", gsDonatePage, NULL, NULL, SW_SHOWNORMAL);
if (shellRc <= 32)
{
DisplayLastError(L"ShellExecute failed", shellRc);
}
}
void ConEmuAbout::OnInfo_FlattrLink()
{
DWORD shellRc = (DWORD)(INT_PTR)ShellExecute(ghWnd, L"open", gsFlattrPage, NULL, NULL, SW_SHOWNORMAL);
if (shellRc <= 32)
{
DisplayLastError(L"ShellExecute failed", shellRc);
}
}
void ConEmuAbout::TabSelected(HWND hDlg, int idx)
{
if (idx < 0 || idx >= countof(Pages))
return;
wcscpy_c(sLastOpenTab, Pages[idx].Title);
LPCWSTR pszNewText = Pages[idx].Text;
CEStr lsTemp;
if (gpConEmu->mp_PushInfo && gpConEmu->mp_PushInfo->mp_Active && gpConEmu->mp_PushInfo->mp_Active->pszFullMessage)
{
// EDIT control requires \r\n as line endings
lsTemp = lstrmerge(gpConEmu->mp_PushInfo->mp_Active->pszFullMessage, L"\r\n\r\n\r\n", pszNewText);
pszNewText = lsTemp.ms_Val;
}
SetDlgItemText(hDlg, tAboutText, pszNewText);
}
void ConEmuAbout::LogStartEnvInt(LPCWSTR asText, LPARAM lParam, bool bFirst, bool bNewLine)
{
lstrmerge(&gsSysInfo, asText, bNewLine ? L"\r\n" : NULL);
if (bFirst && gpConEmu)
{
lstrmerge(&gsSysInfo, L" AppID: ", gpConEmu->ms_AppID, L"\r\n");
}
}
void ConEmuAbout::ReloadSysInfo()
{
if (!gpStartEnv)
return;
_ASSERTE(lstrcmp(Pages[countof(Pages)-1].Title, L"SysInfo") == 0);
SafeFree(gsSysInfo);
LoadStartupEnvEx::ToString(gpStartEnv, LogStartEnvInt, 0);
Pages[countof(Pages)-1].Text = gsSysInfo;
}
void ConEmuAbout::OnInfo_About(LPCWSTR asPageName /*= NULL*/)
{
InitCommCtrls();
bool bOk = false;
if (!asPageName && sLastOpenTab[0])
{
// Reopen last active tab
asPageName = sLastOpenTab;
}
ReloadSysInfo();
{
DontEnable de;
if (!mp_DpiAware)
mp_DpiAware = new CDpiForDialog();
HWND hParent = (ghOpWnd && IsWindowVisible(ghOpWnd)) ? ghOpWnd : ghWnd;
// Modal dialog (CreateDialog)
INT_PTR iRc = CDynDialog::ExecuteDialog(IDD_ABOUT, hParent, aboutProc, (LPARAM)asPageName);
bOk = (iRc != 0 && iRc != -1);
mh_AboutDlg = NULL;
if (mp_DpiAware)
mp_DpiAware->Detach();
#ifdef _DEBUG
// Any problems with dialog resource?
if (!bOk) DisplayLastError(L"DialogBoxParam(IDD_ABOUT) failed");
#endif
}
if (!bOk)
{
CEStr szTitle(gpConEmu->GetDefaultTitle(), L" ", CLngRc::getRsrc(lng_DlgAbout/*"About"*/));
DontEnable de;
MSGBOXPARAMS mb = {sizeof(MSGBOXPARAMS), ghWnd, g_hInstance,
pAbout,
szTitle.ms_Val,
MB_USERICON, MAKEINTRESOURCE(IMAGE_ICON), 0, NULL, LANG_NEUTRAL
};
MSetter lInCall(&gnInMsgBox);
// Use MessageBoxIndirect instead of MessageBox to show our icon instead of std ICONINFORMATION
MessageBoxIndirect(&mb);
}
}
void ConEmuAbout::OnInfo_WhatsNew(bool bLocal)
{
wchar_t sFile[MAX_PATH+80];
INT_PTR iExec = -1;
if (bLocal)
{
wcscpy_c(sFile, gpConEmu->ms_ConEmuBaseDir);
wcscat_c(sFile, L"\\WhatsNew-ConEmu.txt");
if (FileExists(sFile))
{
iExec = (INT_PTR)ShellExecute(ghWnd, L"open", sFile, NULL, NULL, SW_SHOWNORMAL);
if (iExec >= 32)
{
return;
}
}
}
wcscpy_c(sFile, gsWhatsNew);
iExec = (INT_PTR)ShellExecute(ghWnd, L"open", sFile, NULL, NULL, SW_SHOWNORMAL);
if (iExec >= 32)
{
return;
}
DisplayLastError(L"File 'WhatsNew-ConEmu.txt' not found, go to web page failed", (int)LODWORD(iExec));
}
void ConEmuAbout::OnInfo_Help()
{
static HMODULE hhctrl = NULL;
if (!hhctrl) hhctrl = GetModuleHandle(L"hhctrl.ocx");
if (!hhctrl) hhctrl = LoadLibrary(L"hhctrl.ocx");
if (hhctrl)
{
typedef BOOL (WINAPI* HTMLHelpW_t)(HWND hWnd, LPCWSTR pszFile, INT uCommand, INT dwData);
HTMLHelpW_t fHTMLHelpW = (HTMLHelpW_t)GetProcAddress(hhctrl, "HtmlHelpW");
if (fHTMLHelpW)
{
wchar_t szHelpFile[MAX_PATH*2];
lstrcpy(szHelpFile, gpConEmu->ms_ConEmuChm);
//wchar_t* pszSlash = wcsrchr(szHelpFile, L'\\');
//if (pszSlash) pszSlash++; else pszSlash = szHelpFile;
//lstrcpy(pszSlash, L"ConEmu.chm");
// lstrcat(szHelpFile, L::/Intro.htm");
#define HH_HELP_CONTEXT 0x000F
#define HH_DISPLAY_TOC 0x0001
//fHTMLHelpW(NULL /*чтобы окно не блокировалось*/, szHelpFile, HH_HELP_CONTEXT, contextID);
fHTMLHelpW(NULL /*чтобы окно не блокировалось*/, szHelpFile, HH_DISPLAY_TOC, 0);
}
}
}
void ConEmuAbout::OnInfo_HomePage()
{
DWORD shellRc = (DWORD)(INT_PTR)ShellExecute(ghWnd, L"open", gsHomePage, NULL, NULL, SW_SHOWNORMAL);
if (shellRc <= 32)
{
DisplayLastError(L"ShellExecute failed", shellRc);
}
}
void ConEmuAbout::OnInfo_DownloadPage()
{
DWORD shellRc = (DWORD)(INT_PTR)ShellExecute(ghWnd, L"open", gsDownlPage, NULL, NULL, SW_SHOWNORMAL);
if (shellRc <= 32)
{
DisplayLastError(L"ShellExecute failed", shellRc);
}
}
void ConEmuAbout::OnInfo_FirstStartPage()
{
DWORD shellRc = (DWORD)(INT_PTR)ShellExecute(ghWnd, L"open", gsFirstStart, NULL, NULL, SW_SHOWNORMAL);
if (shellRc <= 32)
{
DisplayLastError(L"ShellExecute failed", shellRc);
}
}
void ConEmuAbout::OnInfo_ReportBug()
{
DWORD shellRc = (DWORD)(INT_PTR)ShellExecute(ghWnd, L"open", gsReportBug, NULL, NULL, SW_SHOWNORMAL);
if (shellRc <= 32)
{
DisplayLastError(L"ShellExecute failed", shellRc);
}
}
void ConEmuAbout::OnInfo_ReportCrash(LPCWSTR asDumpWasCreatedMsg)
{
if (nLastCrashReported)
{
// if previous gsReportCrash was opened less than 60 sec ago
DWORD nLast = GetTickCount() - nLastCrashReported;
if (nLast < 60000)
{
// Skip this time
return;
}
}
if (asDumpWasCreatedMsg && !*asDumpWasCreatedMsg)
{
asDumpWasCreatedMsg = NULL;
}
DWORD shellRc = (DWORD)(INT_PTR)ShellExecute(ghWnd, L"open", gsReportCrash, NULL, NULL, SW_SHOWNORMAL);
if (shellRc <= 32)
{
DisplayLastError(L"ShellExecute failed", shellRc);
}
else if (asDumpWasCreatedMsg)
{
MsgBox(asDumpWasCreatedMsg, MB_OK|MB_ICONEXCLAMATION|MB_SYSTEMMODAL);
}
nLastCrashReported = GetTickCount();
}
void ConEmuAbout::OnInfo_ThrowTrapException(bool bMainThread)
{
if (bMainThread)
{
if (MsgBox(L"Are you sure?\nApplication will terminate after that!\nThrow exception in ConEmu's main thread?", MB_ICONEXCLAMATION|MB_YESNO|MB_DEFBUTTON2)==IDYES)
{
//#ifdef _DEBUG
//MyAssertTrap();
//#else
//DebugBreak();
//#endif
// -- trigger division by 0
RaiseTestException();
}
}
else
{
if (MsgBox(L"Are you sure?\nApplication will terminate after that!\nThrow exception in ConEmu's monitor thread?", MB_ICONEXCLAMATION|MB_YESNO|MB_DEFBUTTON2)==IDYES)
{
CVConGuard VCon;
if ((gpConEmu->GetActiveVCon(&VCon) >= 0) && VCon->RCon())
VCon->RCon()->MonitorAssertTrap();
}
}
}
| 25.456215 | 166 | 0.687233 | clcarwin |
8210a05e5b0d978d2b7fdfea173193ab68af5b29 | 7,142 | cpp | C++ | ext/include/osgEarthUtil/ContourMap.cpp | energonQuest/dtEarth | 47b04bb272ec8781702dea46f5ee9a03d4a22196 | [
"MIT"
] | 6 | 2015-09-26T15:33:41.000Z | 2021-06-13T13:21:50.000Z | ext/include/osgEarthUtil/ContourMap.cpp | energonQuest/dtEarth | 47b04bb272ec8781702dea46f5ee9a03d4a22196 | [
"MIT"
] | null | null | null | ext/include/osgEarthUtil/ContourMap.cpp | energonQuest/dtEarth | 47b04bb272ec8781702dea46f5ee9a03d4a22196 | [
"MIT"
] | 5 | 2015-05-04T09:02:23.000Z | 2019-06-17T11:34:12.000Z | /* -*-c++-*- */
/* osgEarth - Dynamic map generation toolkit for OpenSceneGraph
* Copyright 2008-2012 Pelican Mapping
* http://osgearth.org
*
* osgEarth is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
#include <osgEarthUtil/ContourMap>
#include <osgEarth/Registry>
#include <osgEarth/Capabilities>
#include <osgEarth/VirtualProgram>
#include <osgEarth/TerrainEngineNode>
#define LC "[ContourMap] "
using namespace osgEarth;
using namespace osgEarth::Util;
namespace
{
const char* vs =
"#version " GLSL_VERSION_STR "\n"
GLSL_DEFAULT_PRECISION_FLOAT "\n"
"attribute vec4 oe_terrain_attr; \n"
"uniform float oe_contour_min; \n"
"uniform float oe_contour_range; \n"
"varying float oe_contour_lookup; \n"
"void oe_contour_vertex(inout vec4 VertexModel) \n"
"{ \n"
" float height = oe_terrain_attr[3]; \n"
" float height_normalized = (height-oe_contour_min)/oe_contour_range; \n"
" oe_contour_lookup = clamp( height_normalized, 0.0, 1.0 ); \n"
"} \n";
const char* fs =
"#version " GLSL_VERSION_STR "\n"
GLSL_DEFAULT_PRECISION_FLOAT "\n"
"uniform sampler1D oe_contour_xfer; \n"
"uniform float oe_contour_opacity; \n"
"varying float oe_contour_lookup; \n"
"void oe_contour_fragment( inout vec4 color ) \n"
"{ \n"
" vec4 texel = texture1D( oe_contour_xfer, oe_contour_lookup ); \n"
" color.rgb = mix(color.rgb, texel.rgb, texel.a * oe_contour_opacity); \n"
"} \n";
}
ContourMap::ContourMap() :
TerrainEffect()
{
init();
}
ContourMap::ContourMap(const Config& conf) :
TerrainEffect()
{
mergeConfig(conf);
init();
}
void
ContourMap::init()
{
// negative means unset:
_unit = -1;
// uniforms we'll need:
_xferMin = new osg::Uniform(osg::Uniform::FLOAT, "oe_contour_min" );
_xferRange = new osg::Uniform(osg::Uniform::FLOAT, "oe_contour_range" );
_xferSampler = new osg::Uniform(osg::Uniform::SAMPLER_1D, "oe_contour_xfer" );
_opacityUniform = new osg::Uniform(osg::Uniform::FLOAT, "oe_contour_opacity" );
_opacityUniform->set( _opacity.getOrUse(1.0f) );
// Create a 1D texture from the transfer function's image.
_xferTexture = new osg::Texture1D();
_xferTexture->setResizeNonPowerOfTwoHint( false );
_xferTexture->setFilter( osg::Texture::MIN_FILTER, osg::Texture::LINEAR );
_xferTexture->setFilter( osg::Texture::MAG_FILTER, osg::Texture::LINEAR );
_xferTexture->setWrap( osg::Texture::WRAP_S, osg::Texture::CLAMP_TO_EDGE );
// build a default transfer function.
// TODO: think about scale/bias controls.
osg::TransferFunction1D* xfer = new osg::TransferFunction1D();
float s = 2500.0f;
xfer->setColor( -1.0000 * s, osg::Vec4f(0, 0, 0.5, 1), false);
xfer->setColor( -0.2500 * s, osg::Vec4f(0, 0, 1, 1), false);
xfer->setColor( 0.0000 * s, osg::Vec4f(0, .5, 1, 1), false);
xfer->setColor( 0.0062 * s, osg::Vec4f(.84,.84,.25,1), false);
//xfer->setColor( 0.0625 * s, osg::Vec4f(.94,.94,.25,1), false);
xfer->setColor( 0.1250 * s, osg::Vec4f(.125,.62,0,1), false);
xfer->setColor( 0.3250 * s, osg::Vec4f(.80,.70,.47,1), false);
xfer->setColor( 0.7500 * s, osg::Vec4f(.5,.5,.5,1), false);
xfer->setColor( 1.0000 * s, osg::Vec4f(1,1,1,1), false);
xfer->updateImage();
this->setTransferFunction( xfer );
}
ContourMap::~ContourMap()
{
//nop
}
void
ContourMap::setTransferFunction(osg::TransferFunction1D* xfer)
{
_xfer = xfer;
_xferTexture->setImage( _xfer->getImage() );
_xferMin->set( _xfer->getMinimum() );
_xferRange->set( _xfer->getMaximum() - _xfer->getMinimum() );
}
void
ContourMap::setOpacity(float opacity)
{
_opacity = osg::clampBetween(opacity, 0.0f, 1.0f);
_opacityUniform->set( _opacity.get() );
}
void
ContourMap::onInstall(TerrainEngineNode* engine)
{
if ( engine )
{
if ( !engine->getTextureCompositor()->reserveTextureImageUnit(_unit) )
{
OE_WARN << LC << "Failed to reserve a texture image unit; disabled." << std::endl;
return;
}
osg::StateSet* stateset = engine->getOrCreateStateSet();
// Install the texture and its sampler uniform:
stateset->setTextureAttributeAndModes( _unit, _xferTexture.get(), osg::StateAttribute::ON );
stateset->addUniform( _xferSampler.get() );
_xferSampler->set( _unit );
// (By the way: if you want to draw image layers on top of the contoured terrain,
// set the "priority" parameter to setFunction() to a negative number so that it draws
// before the terrain's layers.)
VirtualProgram* vp = VirtualProgram::getOrCreate(stateset);
vp->setFunction( "oe_contour_vertex", vs, ShaderComp::LOCATION_VERTEX_MODEL);
vp->setFunction( "oe_contour_fragment", fs, ShaderComp::LOCATION_FRAGMENT_COLORING ); //, -1.0);
// Install some uniforms that tell the shader the height range of the color map.
stateset->addUniform( _xferMin.get() );
_xferMin->set( _xfer->getMinimum() );
stateset->addUniform( _xferRange.get() );
_xferRange->set( _xfer->getMaximum() - _xfer->getMinimum() );
stateset->addUniform( _opacityUniform.get() );
}
}
void
ContourMap::onUninstall(TerrainEngineNode* engine)
{
if ( engine )
{
osg::StateSet* stateset = engine->getStateSet();
if ( stateset )
{
stateset->removeUniform( _xferMin.get() );
stateset->removeUniform( _xferRange.get() );
stateset->removeUniform( _xferSampler.get() );
stateset->removeUniform( _opacityUniform.get() );
stateset->removeTextureAttribute( _unit, osg::StateAttribute::TEXTURE );
VirtualProgram* vp = VirtualProgram::get(stateset);
if ( vp )
{
vp->removeShader( "oe_contour_vertex" );
vp->removeShader( "oe_contour_fragment" );
}
}
if ( _unit >= 0 )
{
engine->getTextureCompositor()->releaseTextureImageUnit( _unit );
_unit = -1;
}
}
}
//-------------------------------------------------------------
void
ContourMap::mergeConfig(const Config& conf)
{
conf.getIfSet("opacity", _opacity);
}
Config
ContourMap::getConfig() const
{
Config conf("contour_map");
conf.addIfSet("opacity", _opacity);
return conf;
}
| 31.462555 | 104 | 0.635536 | energonQuest |
821105fc2a223f312eedb419e6a35e528a03888a | 878 | cpp | C++ | MonoNative.Tests/mscorlib/System/Runtime/Serialization/mscorlib_System_Runtime_Serialization_IObjectReference_Fixture.cpp | brunolauze/MonoNative | 959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66 | [
"BSD-2-Clause"
] | 7 | 2015-03-10T03:36:16.000Z | 2021-11-05T01:16:58.000Z | MonoNative.Tests/mscorlib/System/Runtime/Serialization/mscorlib_System_Runtime_Serialization_IObjectReference_Fixture.cpp | brunolauze/MonoNative | 959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66 | [
"BSD-2-Clause"
] | 1 | 2020-06-23T10:02:33.000Z | 2020-06-24T02:05:47.000Z | MonoNative.Tests/mscorlib/System/Runtime/Serialization/mscorlib_System_Runtime_Serialization_IObjectReference_Fixture.cpp | brunolauze/MonoNative | 959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66 | [
"BSD-2-Clause"
] | null | null | null | // Mono Native Fixture
// Assembly: mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
// Namespace: System.Runtime.Serialization
// Name: IObjectReference
// C++ Typed Name: mscorlib::System::Runtime::Serialization::IObjectReference
#include <gtest/gtest.h>
#include <mscorlib/System/Runtime/Serialization/mscorlib_System_Runtime_Serialization_IObjectReference.h>
#include <mscorlib/System/Runtime/Serialization/mscorlib_System_Runtime_Serialization_StreamingContext.h>
namespace mscorlib
{
namespace System
{
namespace Runtime
{
namespace Serialization
{
//Public Methods Tests
// Method GetRealObject
// Signature: mscorlib::System::Runtime::Serialization::StreamingContext context
TEST(mscorlib_System_Runtime_Serialization_IObjectReference_Fixture,GetRealObject_Test)
{
}
}
}
}
}
| 23.105263 | 105 | 0.763098 | brunolauze |
8211183ac47ea4607914043950614220e8b2ee76 | 1,249 | hpp | C++ | include/opentxs/cash/DigitalCash.hpp | nopdotcom/opentxs | 140428ba8f1bd4c09654ebf0a1c1725f396efa8b | [
"MIT"
] | null | null | null | include/opentxs/cash/DigitalCash.hpp | nopdotcom/opentxs | 140428ba8f1bd4c09654ebf0a1c1725f396efa8b | [
"MIT"
] | null | null | null | include/opentxs/cash/DigitalCash.hpp | nopdotcom/opentxs | 140428ba8f1bd4c09654ebf0a1c1725f396efa8b | [
"MIT"
] | null | null | null | // Copyright (c) 2018 The Open-Transactions developers
// 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/.
#ifndef OPENTXS_CASH_DIGITALCASH_HPP
#define OPENTXS_CASH_DIGITALCASH_HPP
#include "opentxs/Forward.hpp"
#if OT_CASH
// WHICH DIGITAL CASH LIBRARY?
//
// Many algorithms may come available. We are currently using Lucre, by Ben
// Laurie,
// which is an implementation of Wagner, which is a variant of Chaum.
//
// We plan to have alternatives such as "Magic Money" by Pr0duct Cypher.
//
// Implementations for Chaum and Brands are circulating online. They could all
// be easily added here as options for Open-Transactions.
#if OT_CASH_USING_LUCRE
// IWYU pragma: begin_exports
#include <lucre/bank.h>
// IWYU pragma: end_exports
#endif
#if OT_CASH_USING_MAGIC_MONEY
#include... // someday
#endif
#include <string>
namespace opentxs
{
#if OT_CASH_USING_LUCRE
class LucreDumper
{
std::string m_str_dumpfile;
public:
LucreDumper();
~LucreDumper();
};
#endif
#if OT_CASH_USING_MAGIC_MONEY
// Todo: Someday...
#endif
} // namespace opentxs
#endif // OT_CASH
#endif
| 20.816667 | 78 | 0.740592 | nopdotcom |
821a0c662245750cd0fff195666d90a5cce302bc | 236 | cpp | C++ | spinok/source/ECS/Entity.cpp | ckgomes/projects_archive | f5282d51dd1539bbefb5c1d12d2ab35ec3d6e548 | [
"MIT"
] | 1 | 2016-06-04T14:34:23.000Z | 2016-06-04T14:34:23.000Z | spinok/source/ECS/Entity.cpp | ckgomes/projects_archive | f5282d51dd1539bbefb5c1d12d2ab35ec3d6e548 | [
"MIT"
] | null | null | null | spinok/source/ECS/Entity.cpp | ckgomes/projects_archive | f5282d51dd1539bbefb5c1d12d2ab35ec3d6e548 | [
"MIT"
] | null | null | null | #include "Entity.hpp"
void Entity::scheduleRemoval()
{
m_remove = true;
}
void Entity::update()
{
ext::for_each(m_components, [](auto* ptr)
{
if (ptr != nullptr && ptr->active)
ptr->update();
});
}
| 14.75 | 45 | 0.54661 | ckgomes |
821da146e307ca80a83fc676bdad0b0b8c66a390 | 9,164 | cc | C++ | pin/thread_start.cc | elau/graphite_pep | ddce5890f20e272c587c5caed07161db043247b2 | [
"MIT"
] | 1 | 2022-03-03T21:04:09.000Z | 2022-03-03T21:04:09.000Z | pin/thread_start.cc | trevorcarlson/Graphite | 8aeb2cb199864dbf517c4a88dfac7fb6ac7d74f4 | [
"MIT"
] | 1 | 2022-03-04T20:03:50.000Z | 2022-03-04T20:03:50.000Z | pin/thread_start.cc | elau/graphite_pep | ddce5890f20e272c587c5caed07161db043247b2 | [
"MIT"
] | null | null | null | #include <string.h>
#include <sys/mman.h>
#include "thread_start.h"
#include "log.h"
#include "core.h"
#include "simulator.h"
#include "fixed_types.h"
#include "pin_config.h"
#include "tile_manager.h"
#include "thread_manager.h"
#include "thread_support.h"
int spawnThreadSpawner(CONTEXT *ctxt)
{
int res;
IntPtr reg_eip = PIN_GetContextReg(ctxt, REG_INST_PTR);
PIN_LockClient();
AFUNPTR thread_spawner;
IMG img = IMG_FindByAddress(reg_eip);
RTN rtn = RTN_FindByName(img, "CarbonSpawnThreadSpawner");
thread_spawner = RTN_Funptr(rtn);
PIN_UnlockClient();
LOG_ASSERT_ERROR( thread_spawner != NULL, "ThreadSpawner function is null. You may not have linked to the carbon APIs correctly.");
LOG_PRINT("Starting CarbonSpawnThreadSpawner(%p)", thread_spawner);
PIN_CallApplicationFunction(ctxt,
PIN_ThreadId(),
CALLINGSTD_DEFAULT,
thread_spawner,
PIN_PARG(int), &res,
PIN_PARG_END());
LOG_PRINT("Thread spawner spawned");
LOG_ASSERT_ERROR(res == 0, "Failed to spawn Thread Spawner");
return res;
}
VOID copyStaticData(IMG& img)
{
Core* core = Sim()->getTileManager()->getCurrentCore();
LOG_ASSERT_ERROR (core != NULL, "Does not have a valid Core ID");
for (SEC sec = IMG_SecHead(img); SEC_Valid(sec); sec = SEC_Next(sec))
{
IntPtr sec_address;
// I am not sure whether we want ot copy over all the sections or just the
// sections which are relevant like the sections below: DATA, BSS, GOT
// Copy all the mapped sections except the executable section now
SEC_TYPE sec_type = SEC_Type(sec);
if (sec_type != SEC_TYPE_EXEC)
{
if (SEC_Mapped(sec))
{
sec_address = SEC_Address(sec);
LOG_PRINT ("Copying Section: %s at Address: 0x%x of Size: %u to Simulated Memory", SEC_Name(sec).c_str(), (UInt32) sec_address, (UInt32) SEC_Size(sec));
core->accessMemory(Core::NONE, Core::WRITE, sec_address, (char*) sec_address, SEC_Size(sec));
}
}
}
}
VOID copyInitialStackData(IntPtr& reg_esp, core_id_t core_id)
{
// We should not get core_id for this stack_ptr
Core* core = Sim()->getTileManager()->getCurrentCore();
LOG_ASSERT_ERROR (core != NULL, "Does not have a valid Core ID");
// 1) Command Line Arguments
// 2) Environment Variables
// 3) Auxiliary Vector Entries
SInt32 initial_stack_size = 0;
IntPtr stack_ptr_base;
IntPtr stack_ptr_top;
IntPtr params = reg_esp;
carbon_reg_t argc = * ((carbon_reg_t *) params);
char **argv = (char **) (params + sizeof(carbon_reg_t));
char **envir = argv+argc+1;
//////////////////////////////////////////////////////////////////////
// Pass 1
// Determine the Initial Stack Size
// Variables: size_argv_ptrs, size_env_ptrs, size_information_block
//////////////////////////////////////////////////////////////////////
// Write argc
initial_stack_size += sizeof(argc);
// Write argv
for (SInt32 i = 0; i < (SInt32) argc; i++)
{
// Writing argv[i]
initial_stack_size += sizeof(char*);
initial_stack_size += (strlen(argv[i]) + 1);
}
// A '0' at the end
initial_stack_size += sizeof(char*);
// We need to copy over the environmental parameters also
for (SInt32 i = 0; ; i++)
{
// Writing environ[i]
initial_stack_size += sizeof(char*);
if (envir[i] == 0)
{
break;
}
initial_stack_size += (strlen(envir[i]) + 1);
}
// Auxiliary Vector Entry
#ifdef TARGET_IA32
initial_stack_size += sizeof(Elf32_auxv_t);
#elif TARGET_X86_64
initial_stack_size += sizeof(Elf64_auxv_t);
#else
LOG_PRINT_ERROR("Unrecognized Architecture Type");
#endif
//////////////////////////////////////////////////////////////////////
// Pass 2
// Copy over the actual data
// Variables: stack_ptr_base_sim
//////////////////////////////////////////////////////////////////////
PinConfig::StackAttributes stack_attr;
PinConfig::getSingleton()->getStackAttributesFromCoreID (core_id, stack_attr);
stack_ptr_top = stack_attr.lower_limit + stack_attr.size;
stack_ptr_base = stack_ptr_top - initial_stack_size;
stack_ptr_base = (stack_ptr_base >> (sizeof(IntPtr))) << (sizeof(IntPtr));
// Assign the new ESP
reg_esp = stack_ptr_base;
// fprintf (stderr, "argc = %d\n", argc);
// Write argc
core->accessMemory(Core::NONE, Core::WRITE, stack_ptr_base, (char*) &argc, sizeof(argc));
stack_ptr_base += sizeof(argc);
LOG_PRINT("Copying Command Line Arguments to Simulated Memory");
for (SInt32 i = 0; i < (SInt32) argc; i++)
{
// Writing argv[i]
stack_ptr_top -= (strlen(argv[i]) + 1);
core->accessMemory(Core::NONE, Core::WRITE, stack_ptr_top, (char*) argv[i], strlen(argv[i])+1);
core->accessMemory(Core::NONE, Core::WRITE, stack_ptr_base, (char*) &stack_ptr_top, sizeof(stack_ptr_top));
stack_ptr_base += sizeof(stack_ptr_top);
}
// I have found this to be '0' in most cases
core->accessMemory(Core::NONE, Core::WRITE, stack_ptr_base, (char*) &argv[argc], sizeof(argv[argc]));
stack_ptr_base += sizeof(argv[argc]);
// We need to copy over the environmental parameters also
LOG_PRINT("Copying Environmental Variables to Simulated Memory");
for (SInt32 i = 0; ; i++)
{
// Writing environ[i]
if (envir[i] == 0)
{
core->accessMemory(Core::NONE, Core::WRITE, stack_ptr_base, (char*) &envir[i], sizeof(envir[i]));
stack_ptr_base += sizeof(envir[i]);
break;
}
stack_ptr_top -= (strlen(envir[i]) + 1);
core->accessMemory(Core::NONE, Core::WRITE, stack_ptr_top, (char*) envir[i], strlen(envir[i])+1);
core->accessMemory(Core::NONE, Core::WRITE, stack_ptr_base, (char*) &stack_ptr_top, sizeof(stack_ptr_top));
stack_ptr_base += sizeof(stack_ptr_top);
}
LOG_PRINT("Copying Auxiliary Vector to Simulated Memory");
#ifdef TARGET_IA32
Elf32_auxv_t auxiliary_vector_entry_null;
#elif TARGET_X86_64
Elf64_auxv_t auxiliary_vector_entry_null;
#else
LOG_PRINT_ERROR("Unrecognized architecture type");
#endif
auxiliary_vector_entry_null.a_type = AT_NULL;
auxiliary_vector_entry_null.a_un.a_val = 0;
core->accessMemory(Core::NONE, Core::WRITE, stack_ptr_base, (char*) &auxiliary_vector_entry_null, sizeof(auxiliary_vector_entry_null));
stack_ptr_base += sizeof(auxiliary_vector_entry_null);
LOG_ASSERT_ERROR(stack_ptr_base <= stack_ptr_top, "stack_ptr_base = 0x%x, stack_ptr_top = 0x%x", stack_ptr_base, stack_ptr_top);
}
VOID copySpawnedThreadStackData(IntPtr reg_esp)
{
core_id_t core_id = PinConfig::getSingleton()->getCoreIDFromStackPtr(reg_esp);
PinConfig::StackAttributes stack_attr;
PinConfig::getSingleton()->getStackAttributesFromCoreID(core_id, stack_attr);
IntPtr stack_upper_limit = stack_attr.lower_limit + stack_attr.size;
UInt32 num_bytes_to_copy = (UInt32) (stack_upper_limit - reg_esp);
Core* core = Sim()->getTileManager()->getCurrentCore();
core->accessMemory(Core::NONE, Core::WRITE, reg_esp, (char*) reg_esp, num_bytes_to_copy);
}
VOID allocateStackSpace()
{
// Note that 1 core = 1 thread currently
// We should probably get the amount of stack space per thread from a configuration parameter
// Each process allocates whatever it is responsible for !!
__attribute(__unused__) UInt32 stack_size_per_core = PinConfig::getSingleton()->getStackSizePerCore();
__attribute(__unused__) UInt32 num_tiles = Sim()->getConfig()->getNumLocalTiles();
__attribute(__unused__) IntPtr stack_base = PinConfig::getSingleton()->getStackLowerLimit();
LOG_PRINT("allocateStackSpace: stack_size_per_core = 0x%x", stack_size_per_core);
LOG_PRINT("allocateStackSpace: num_local_cores = %i", num_tiles);
LOG_PRINT("allocateStackSpace: stack_base = 0x%x", stack_base);
// TODO: Make sure that this is a multiple of the page size
// mmap() the total amount of memory needed for the stacks
LOG_ASSERT_ERROR((mmap((void*) stack_base, stack_size_per_core * num_tiles, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) == (void*) stack_base),
"mmap(%p, %u) failed: Cannot allocate stack on host machine", (void*) stack_base, stack_size_per_core * num_tiles);
}
VOID SimPthreadAttrInitOtherAttr(pthread_attr_t *attr)
{
LOG_PRINT ("In SimPthreadAttrInitOtherAttr");
//tile_id_t tile_id;
core_id_t core_id;
ThreadSpawnRequest* req = Sim()->getThreadManager()->getThreadSpawnReq();
if (req == NULL)
{
// This is the thread spawner
core_id = Sim()->getConfig()->getCurrentThreadSpawnerCoreId();
}
else
{
// This is an application thread
core_id = (core_id_t) {req->destination.tile_id, req->destination.core_type};
}
PinConfig::StackAttributes stack_attr;
PinConfig::getSingleton()->getStackAttributesFromCoreID(core_id, stack_attr);
pthread_attr_setstack(attr, (void*) stack_attr.lower_limit, stack_attr.size);
LOG_PRINT ("Done with SimPthreadAttrInitOtherAttr");
}
| 33.202899 | 164 | 0.666412 | elau |
822003dcc8852383956382623a8e11ce250f464d | 612 | cpp | C++ | examples/tree.cpp | mbrcknl/functional.cc | a9172f8ed61ac5a9aa3330bdbf1cdd52fc133632 | [
"BSL-1.0"
] | 1 | 2017-09-17T16:06:33.000Z | 2017-09-17T16:06:33.000Z | examples/tree.cpp | mbrcknl/functional.cc | a9172f8ed61ac5a9aa3330bdbf1cdd52fc133632 | [
"BSL-1.0"
] | null | null | null | examples/tree.cpp | mbrcknl/functional.cc | a9172f8ed61ac5a9aa3330bdbf1cdd52fc133632 | [
"BSL-1.0"
] | null | null | null |
// Copyright (c) Matthew Brecknell 2013.
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE.txt or a copy at http://www.boost.org/LICENSE_1_0.txt).
#include <iostream>
#include <string>
#include "tree.hpp"
typedef tree<int> tri;
int main() {
tri foo = tri(tri(tri(1), 2, tri(3)), 4, tri(tri(5), 6, tri()));
tri bar = insert(7, foo);
for (const tri & tr: {foo,bar}) {
std::cout << tr << std::endl;
}
for (const tri & tr: {foo,bar}) {
std::cout
<< map_tree<const int*>([](const int & i) { return &i; }, tr)
<< std::endl;
}
}
| 20.4 | 79 | 0.591503 | mbrcknl |
82257f436a6d072adfa04e3391aa17d50a373bbb | 3,960 | cpp | C++ | main/src/hal/amp-1.0.0/amp-leds.cpp | intentfulmotion/firmware-amp | fecd97ae3882907af10e05e7e688786110da0461 | [
"MIT"
] | null | null | null | main/src/hal/amp-1.0.0/amp-leds.cpp | intentfulmotion/firmware-amp | fecd97ae3882907af10e05e7e688786110da0461 | [
"MIT"
] | null | null | null | main/src/hal/amp-1.0.0/amp-leds.cpp | intentfulmotion/firmware-amp | fecd97ae3882907af10e05e7e688786110da0461 | [
"MIT"
] | null | null | null | #include <hal/amp-1.0.0/amp-leds.h>
FreeRTOS::Semaphore AmpLeds::ledsReady = FreeRTOS::Semaphore("leds");
void AmpLeds::init() {
// setup the status led
status = new OneWireLED(NeoPixel, STATUS_LED, 0, 1);
(*status)[0] = lightOff;
}
void AmpLeds::deinit() {
delay(50);
}
void AmpLeds::process() {
ledsReady.wait();
if (dirty) {
status->show();
for (auto pair : channels) {
if (pair.second != nullptr) {
if (pair.second->wait(5))
pair.second->show();
}
}
}
// if (statusDirty) {
// ESP_LOGV(LEDS_TAG,"Status is dirty. Re-rendering");
// status->wait();
// status->show();
// statusDirty = false;
// }
// // check the dirty bit for each
// for (auto pair : channels) {
// if (pair.second != nullptr && dirty[pair.first]) {
// ESP_LOGV(LEDS_TAG,"Channel %d is dirty. Re-rendering", pair.first);
// pair.second->wait();
// pair.second->show();
// // unset dirty bit
// dirty[pair.first] = false;
// }
// }
}
LightController* AmpLeds::addLEDStrip(LightChannel data) {
ledsReady.wait();
ledsReady.take();
ESP_LOGD(LEDS_TAG,"Adding type %d strip on channel %d with %d LEDs", data.type, data.channel, data.leds);
AddressableLED *controller = nullptr;
if (channels.find(data.channel) != channels.end()) {
// remove old controller
auto old = channels[data.channel];
delete old;
}
switch(data.type) {
case LEDType::NeoPixel:
case LEDType::WS2813:
case LEDType::SK6812:
controller = new OneWireLED(data.type, lightMap[data.channel], data.channel, data.leds);
break;
case LEDType::SK6812_RGBW:
controller = new OneWireLED(data.type, lightMap[data.channel], data.channel, data.leds, PixelOrder::GRBW);
break;
case LEDType::DotStar:
controller = new TwoWireLED(HSPI_HOST, data.leds, lightMap[data.channel], lightMap[data.channel + 4]);
break;
default:
return nullptr;
}
for (uint16_t i = 0; i < data.leds; i++)
(*controller)[i] = lightOff;
channels[data.channel] = controller;
leds[data.channel] = data.leds;
// dirty[data.channel] = true;
ledsReady.give();
return controller;
}
void AmpLeds::setStatus(Color color) {
(*status)[0] = gammaCorrected(color);
dirty = true;
// statusDirty = true;
}
void AmpLeds::render(bool all, int8_t channel) {
dirty = true;
// statusDirty = true;
// // set all dirty bits
// if (all) {
// for (auto pair : dirty)
// dirty[pair.first] = true;
// }
// else if (channel != -1 && channel >= 1 && channel <= 8)
// dirty[channel] = true;
}
Color AmpLeds::gammaCorrected(Color color) {
return Color(gamma8[color.r], gamma8[color.g], gamma8[color.b]);
}
void AmpLeds::setPixel(uint8_t channelNumber, Color color, uint16_t index) {
ledsReady.wait();
if (index >= leds[channelNumber]) {
ESP_LOGE(LEDS_TAG, "Pixel %d exceeds channel %d led count (%d)", index, channelNumber, leds[channelNumber]);
return;
}
auto controller = channels[channelNumber];
if (controller == nullptr)
return;
(*controller)[index] = color;
}
Color AmpLeds::getPixel(uint8_t channelNumber, uint16_t index) {
ledsReady.wait();
if (index >= leds[channelNumber]) {
ESP_LOGE(LEDS_TAG, "Pixel %d exceeds channel %d led count (%d)", index, channelNumber, leds[channelNumber]);
return lightOff;
}
auto controller = channels[channelNumber];
if (controller == nullptr)
return lightOff;
return (*controller)[index];
}
void AmpLeds::setPixels(uint8_t channelNumber, Color color, uint16_t start, uint16_t end) {
ledsReady.wait();
auto controller = channels[channelNumber];
if (controller == nullptr)
return;
for (uint16_t i = start; i < end; i++) {
if (i < leds[channelNumber])
(*controller)[i] = color;
else
ESP_LOGE(LEDS_TAG, "Pixel %d exceeds channel %d led count (%d)", i, channelNumber, leds[channelNumber]);
}
} | 26.577181 | 112 | 0.636364 | intentfulmotion |
8229ebaa6d032ab38129b40f5e0a11ed33b674d4 | 2,405 | cpp | C++ | src/nanoFramework.System.Collections/nf_system_collections_System_Collections_Queue.cpp | TIPConsulting/nf-interpreter | d5407872f4705d6177e1ee5a2e966bd02fd476e4 | [
"MIT"
] | null | null | null | src/nanoFramework.System.Collections/nf_system_collections_System_Collections_Queue.cpp | TIPConsulting/nf-interpreter | d5407872f4705d6177e1ee5a2e966bd02fd476e4 | [
"MIT"
] | 1 | 2021-02-22T07:54:30.000Z | 2021-02-22T07:54:30.000Z | src/nanoFramework.System.Collections/nf_system_collections_System_Collections_Queue.cpp | TIPConsulting/nf-interpreter | d5407872f4705d6177e1ee5a2e966bd02fd476e4 | [
"MIT"
] | null | null | null | //
// Copyright (c) .NET Foundation and Contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
#include "nf_system_collections.h"
HRESULT Library_nf_system_collections_System_Collections_Queue::CopyTo___VOID__SystemArray__I4( CLR_RT_StackFrame& stack )
{
NATIVE_PROFILE_CLR_CORE();
NANOCLR_HEADER();
CLR_RT_HeapBlock_Queue* pThis;
CLR_RT_HeapBlock_Array* array;
CLR_INT32 index;
pThis = (CLR_RT_HeapBlock_Queue*)stack.This(); FAULT_ON_NULL(pThis);
array = stack.Arg1().DereferenceArray(); FAULT_ON_NULL_ARG(array);
index = stack.Arg2().NumericByRef().s4;
NANOCLR_SET_AND_LEAVE(pThis->CopyTo( array, index ));
NANOCLR_NOCLEANUP();
}
HRESULT Library_nf_system_collections_System_Collections_Queue::Clear___VOID( CLR_RT_StackFrame& stack )
{
NATIVE_PROFILE_CLR_CORE();
NANOCLR_HEADER();
CLR_RT_HeapBlock_Queue* pThis = (CLR_RT_HeapBlock_Queue*)stack.This(); FAULT_ON_NULL(pThis);
NANOCLR_SET_AND_LEAVE(pThis->Clear());
NANOCLR_NOCLEANUP();
}
HRESULT Library_nf_system_collections_System_Collections_Queue::Enqueue___VOID__OBJECT( CLR_RT_StackFrame& stack )
{
NATIVE_PROFILE_CLR_CORE();
NANOCLR_HEADER();
CLR_RT_HeapBlock_Queue* pThis = (CLR_RT_HeapBlock_Queue*)stack.This(); FAULT_ON_NULL(pThis);
NANOCLR_SET_AND_LEAVE(pThis->Enqueue( stack.Arg1().Dereference() ));
NANOCLR_NOCLEANUP();
}
HRESULT Library_nf_system_collections_System_Collections_Queue::Dequeue___OBJECT( CLR_RT_StackFrame& stack )
{
NATIVE_PROFILE_CLR_CORE();
NANOCLR_HEADER();
CLR_RT_HeapBlock_Queue* pThis = (CLR_RT_HeapBlock_Queue*)stack.This(); FAULT_ON_NULL(pThis);
CLR_RT_HeapBlock* value;
NANOCLR_CHECK_HRESULT(pThis->Dequeue( value ));
stack.SetResult_Object( value );
NANOCLR_NOCLEANUP();
}
HRESULT Library_nf_system_collections_System_Collections_Queue::Peek___OBJECT( CLR_RT_StackFrame& stack )
{
NATIVE_PROFILE_CLR_CORE();
NANOCLR_HEADER();
CLR_RT_HeapBlock_Queue* pThis = (CLR_RT_HeapBlock_Queue*)stack.This(); FAULT_ON_NULL(pThis);
CLR_RT_HeapBlock* value;
NANOCLR_CHECK_HRESULT(pThis->Peek( value ));
stack.SetResult_Object( value );
NANOCLR_NOCLEANUP();
}
| 29.691358 | 123 | 0.729314 | TIPConsulting |
822a33bd8dd25acd61eb9e4d90992818da114355 | 9,367 | cpp | C++ | src/main.cpp | MaGetzUb/SoftwareRenderer | e1d6242617863a1d9fdc272c1011a3938d1dbbc9 | [
"BSD-2-Clause"
] | 1 | 2020-01-01T12:07:07.000Z | 2020-01-01T12:07:07.000Z | src/main.cpp | MaGetzUb/SoftwareRenderer | e1d6242617863a1d9fdc272c1011a3938d1dbbc9 | [
"BSD-2-Clause"
] | null | null | null | src/main.cpp | MaGetzUb/SoftwareRenderer | e1d6242617863a1d9fdc272c1011a3938d1dbbc9 | [
"BSD-2-Clause"
] | 1 | 2018-07-20T07:51:06.000Z | 2018-07-20T07:51:06.000Z | /*
Copyright © 2018, Marko Ranta
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 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 COPYRIGHT HOLDER 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 "System/window.hpp"
#include "Renderer/canvas.hpp"
#include "System/inputmanager.hpp"
#include "System/timer.hpp"
#include <string>
#include <iostream>
#include <regex> //MEH
#include "Renderer/rendercontext.hpp"
#include "Renderer/mesh.hpp"
#include "starfield.hpp"
#include "Math/quat.hpp"
#define NONE 0
#define STARFIELD 1
#define RENDERCONTEXT 2
#define TEST RENDERCONTEXT
#ifdef NDEBUG
int CALLBACK WinMain(
HINSTANCE /*hInstance*/,
HINSTANCE /*hPrevInstance*/,
LPSTR /*lpCmdLine*/,
int /*nCmdShow*/
)
#else
int main()
#endif
{
int screenWidth = 640, screenHeight = 480;
int canvasWidth = 512, canvasHeight = 384;
std::fstream settings;
settings.open("settings.ini", std::ios::in);
if(!settings.is_open()) {
settings.open("settings.ini", std::ios::out);
settings << "Modify these values at your own risk." << std::endl;
settings << "ScreenWidth = " << screenWidth << std::endl;
settings << "ScreenHeight = " << screenHeight << std::endl;
settings << "CanvasWidth = " << canvasWidth << std::endl;
settings << "CanvasHeight = " << canvasHeight << std::endl;
settings.close();
} else {
std::string line;
std::string var, value;
std::regex match("(\\w+)\\s*=(\\d+)\\s*");
while(std::getline(settings, line)) {
std::smatch subMatches;
if(std::regex_match(line, subMatches, match)) {
if(subMatches.size() == 3) {
var = subMatches[1].str();
value = subMatches[2].str();
}
}
if(var == "ScreenWidth") screenWidth = stoi(value);
if(var == "ScreenHeight") screenHeight = stoi(value);
if(var == "CanvasWidth") canvasWidth = stoi(value);
if(var == "CanvasHeight") canvasHeight = stoi(value);
}
settings.close();
}
Window window;
window.initialize(screenWidth, screenHeight, "Software Renderer");
Canvas canvas(window);
canvas.resize(canvasWidth, canvasHeight);
float aRatio = 4.0f / 3.0f;
InputManager inputs;
inputs.setCustomMessageCallback([&aRatio](Window& window, UINT msg, WPARAM wparam, LPARAM lparam)->LRESULT {
switch(msg) {
case WM_SIZE: {
float w = GET_X_LPARAM(lparam);
float h = GET_Y_LPARAM(lparam);
aRatio = w / h;
} break;
}
return window.defaultWindowProc(msg, wparam, lparam);
});
window.setMessageCallback(inputs.callbackProcessor());
#if TEST == STARFIELD
Starfield starfield(canvas);
#endif
#if TEST == RENDERCONTEXT
RenderContext rc(canvas);
Texture texture1;
texture1.load("res/texture1.png");
Texture texture2;
texture2.load("res/texture2.png");
Mesh mesh1;
mesh1.load("res/suzanne.obj");
Mesh mesh2;
mesh2.load("res/terrain.obj");
Mesh mesh3;
mesh3.load("res/cube.obj");
#endif
auto prevtime = Timer();
double deltaTime = 0.0f;
float ang = 0.0f;
#ifdef TEXT_INPUT_TEST
std::string input;
auto eraseTime = Timer();
#endif
//TL---TR
//| |
//| |
//BL---BR
Vertex vertices[] = {
{-1.0f, -1.0f}, //Bottom left
{-1.0f, 1.0f}, //Top left
{ 1.0f, 1.0f}, //Top right
{ 1.0f, -1.0f} //Bottom right
};
vertices[0].setColor({ 1.0f, 0.0f, 0.0f, 1.0 });
vertices[1].setColor({ 1.0f, 1.0f, 0.0f, 1.0 });
vertices[2].setColor({ 0.0f, 0.0f, 1.0f, 1.0 });
vertices[3].setColor({ 0.0f, 1.0f, 1.0f, 1.0 });
vertices[0].setTexCoord({ 0.0f, 1.0f });
vertices[1].setTexCoord({ 0.0f, 0.0f });
vertices[2].setTexCoord({ 1.0f, 0.0f });
vertices[3].setTexCoord({ 1.0f, 1.0f });
int frames = 0, fps = 0;
float z = -2.0f;
double fpsTime = 0.0f;
float cameraYaw = 0.0f;
float cameraPitch = 0.0f;
vec3 cameraPosition;
float suzanneAngle = 0.f;
rc.setSamplingMode(Texture::Sampling::CubicHermite);
rc.setTextureWrapingMode(Texture::Wraping::Repeat);
rc.enableLighting(true);
rc.setAmbientColor({0.2f, 0.1f, 0.6f});
rc.setAmbientIntensity(0.3f);
rc.setSunColor({ 1.f, 0.6f, 0.2f });
rc.setSunIntensity(4.f);
rc.setSunPosition(vec3(16.f, 3.f, 8.f));
while(!window.isClosed()) {
window.pollEvents();
rc.reset();
canvas.clearCheckerboard(rc.checkerBoard(), rc.ambientColor()*rc.ambientIntensity());
if(!rc.checkerBoard()) {
rc.clearDepthBuffer();
}
#if TEST == STARFIELD
starfield.updateAndDraw(deltaTime);
#endif
#if TEST == RENDERCONTEXT
mat4 mat;
if(inputs.isMouseHit(0)) ShowCursor(FALSE);
if(inputs.isMouseUp(0)) ShowCursor(TRUE);
if(inputs.isMouseDown(0)) {
RECT rct;
GetClientRect(window.handle(), &rct);
POINT p;
p.x = (rct.right - rct.left) / 2;
p.y = (rct.bottom - rct.top) / 2;
float mx = (p.x - inputs.mouseX());
float my = (p.y - inputs.mouseY());
cameraPitch += mx * deltaTime;
cameraYaw += my * deltaTime;
ClientToScreen(window.handle(), &p);
SetCursorPos(p.x, p.y);
}
mat4 rotation = mat4::Rotation(cameraYaw, 1.0f, 0.0f, 0.0f)*mat4::Rotation(cameraPitch, 0.0f, 1.0f, 0.0f);
vec3 dir = rotation.transposed() * vec3(0.f, 0.f, 1.f);
vec3 right = cross(dir, vec3(0.f, 1.f, 0.f));
right = reorthogonalize(right, dir);
if(inputs.isKeyHit('C')) rc.setTextureWrapingMode(Texture::Wraping::Clamp);
if(inputs.isKeyHit('R')) rc.setTextureWrapingMode(Texture::Wraping::Repeat);
if(inputs.isKeyHit(0x31)) rc.setSamplingMode(Texture::Sampling::None);
if(inputs.isKeyHit(0x32)) rc.setSamplingMode(Texture::Sampling::Linear);
if(inputs.isKeyHit(0x33)) rc.setSamplingMode(Texture::Sampling::CubicHermite);
if(inputs.isKeyDown('W')) cameraPosition += dir*5.f * deltaTime;
if(inputs.isKeyDown('S')) cameraPosition -= dir*5.f * deltaTime;
if(inputs.isKeyDown('D')) cameraPosition += right*5.f * deltaTime;
if(inputs.isKeyDown('A')) cameraPosition -= right*5.f * deltaTime;
/*
if(inputs.isKeyHit(VK_SPACE)) {
rc.testMipmap(!rc.isMipMapTesting());
}
if(rc.isMipMapTesting()) {
rc.setMipMapLevel(rc.mipMapLevel() + (inputs.isKeyHit(VK_UP) - inputs.isKeyHit(VK_DOWN)));
}*/
mat4 viewProjection = mat4::Perspective(aRatio, 90.0f, .01f, 100.f) * rotation * mat4::Translate(cameraPosition);
z -= (float)(inputs.isKeyDown(VK_UP) - inputs.isKeyDown(VK_DOWN)) * deltaTime;
mat4 suzanneRotation = mat4::Rotation(QMod(suzanneAngle, 360.0f), 0.f, 1.f, 0.f);
mat4 model = mat4::Translate(0.0f, 0.0f, -2.0f) * suzanneRotation;
mat = viewProjection * model;
rc.drawMesh(mesh1, mat, texture1, suzanneRotation);
suzanneAngle += deltaTime*20.f;
model = mat4::Translate(0.0f, -4.0f, 0.0f);
mat = viewProjection * model;
rc.drawMesh(mesh2, mat, texture2);
model = mat4::Translate(0.0f, -2.0f, -2.0f);
mat = viewProjection * model;
rc.drawMesh(mesh3, mat);
#endif
#ifdef NDEBUG
std::cout << inputs.mouseX() << ", " << inputs.mouseY() << '\r';
#endif
canvas.swapBuffers();
rc.advanceCheckerboard();
#ifdef TEXT_INPUT_TEST
RECT rct = { 0, 0, 800, 300 };
unsigned int ch;
if(inputs.isTextInput(ch)) {
if(isprint(ch)) {
input += ((char)ch);
}
}
if((inputs.isKeyHit(8) || (inputs.isKeyDown(8) && eraseTime > 1000)) && !input.empty()) {
eraseTime = Timer()/10 - eraseTime;
input.pop_back();
}
rct.top += 20;
DrawTextA(window.dc(), input.c_str(), -1, &rct, 0);
#endif
auto tp = Timer();
deltaTime = (double)(tp - prevtime) / (double)TIMER_PRECISION;
//Cap the FPS, so movement won't become too slow.
if(deltaTime < (1.0 / 120.0)) {
Sleep((int)1000.0*(1.0 / 120.0));
}
//Calculate FPS
prevtime = tp;
frames++;
fpsTime += (double)deltaTime;
if(fpsTime > 1.0) {
fps = frames;
frames = 0;
fpsTime = 0;
}
window.setTitle("Software Rendering | FPS: " + std::to_string(fps) + " | Triangles: "+std::to_string(rc.renderedTriangles()) /*+ (rc.isMipMapTesting() ? " | MipMap testing! " + std::to_string(rc.mipMapLevel()) : "")*/);
inputs.update();
}
return 0;
}
| 27.229651 | 222 | 0.645564 | MaGetzUb |
822b8a4f8aa4df4e7e225d0191f8d4b56ccf6f98 | 1,282 | cpp | C++ | benchmarks/distances_b.cpp | ssciwr/geolib4d | dd79a746559235e47c2cb5e7c7ba71ef3ae21e29 | [
"MIT"
] | 3 | 2022-01-28T14:18:05.000Z | 2022-03-02T21:52:43.000Z | benchmarks/distances_b.cpp | ssciwr/geolib4d | dd79a746559235e47c2cb5e7c7ba71ef3ae21e29 | [
"MIT"
] | 104 | 2021-06-18T14:10:37.000Z | 2022-03-04T06:12:58.000Z | benchmarks/distances_b.cpp | ssciwr/py4dgeo | dd79a746559235e47c2cb5e7c7ba71ef3ae21e29 | [
"MIT"
] | null | null | null | #include "testsetup.hpp"
#include <py4dgeo/compute.hpp>
#include <py4dgeo/epoch.hpp>
#include <benchmark/benchmark.h>
using namespace py4dgeo;
static void
distances_benchmark(benchmark::State& state)
{
auto [cloud, corepoints] = ahk_benchcloud();
Epoch epoch(*cloud);
epoch.kdtree.build_tree(10);
std::vector<double> scales{ 1.0 };
EigenNormalSet directions(corepoints->rows(), 3);
EigenNormalSet orientation(1, 3);
orientation << 0, 0, 1;
// Precompute the multiscale directions
compute_multiscale_directions(
epoch, *corepoints, scales, orientation, directions);
// We try to test all callback combinations
auto wsfinder = radius_workingset_finder;
auto uncertaintymeasure = standard_deviation_uncertainty;
for (auto _ : state) {
// Calculate the distances
DistanceVector distances;
UncertaintyVector uncertainties;
compute_distances(*corepoints,
2.0,
epoch,
epoch,
directions,
0.0,
distances,
uncertainties,
wsfinder,
uncertaintymeasure);
}
}
BENCHMARK(distances_benchmark)->Unit(benchmark::kMillisecond);
BENCHMARK_MAIN();
| 26.163265 | 62 | 0.634165 | ssciwr |
822f0e3b530cb767804478225c1aad7bb89ce441 | 917 | inl | C++ | src/binder/inc/bindinglog.inl | CyberSys/coreclr-mono | 83b2cb83b32faa45b4f790237b5c5e259692294a | [
"MIT"
] | 10 | 2015-11-03T16:35:25.000Z | 2021-07-31T16:36:29.000Z | src/binder/inc/bindinglog.inl | CyberSys/coreclr-mono | 83b2cb83b32faa45b4f790237b5c5e259692294a | [
"MIT"
] | 1 | 2019-03-05T18:50:09.000Z | 2019-03-05T18:50:09.000Z | src/binder/inc/bindinglog.inl | CyberSys/coreclr-mono | 83b2cb83b32faa45b4f790237b5c5e259692294a | [
"MIT"
] | 4 | 2015-10-28T12:26:26.000Z | 2021-09-04T11:36:04.000Z | //
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
// ============================================================
//
// BindingLog.inl
//
//
// Implements inlined methods of BindingLog
//
// ============================================================
#ifndef __BINDER__BINDING_LOG_INL__
#define __BINDER__BINDING_LOG_INL__
BOOL BindingLog::CanLog()
{
return (m_pCDebugLog != NULL);
}
CDebugLog *BindingLog::GetDebugLog()
{
_ASSERTE(m_pCDebugLog != NULL);
return m_pCDebugLog;
}
HRESULT BindingLog::Log(LPCWSTR pwzInfo)
{
PathString info(pwzInfo);
return BindingLog::Log(info);
}
HRESULT BindingLog::Log(LPCWSTR pwzPrefix,
SString &info)
{
PathString message;
message.Append(pwzPrefix);
message.Append(info);
return Log(message);
}
#endif
| 19.104167 | 101 | 0.597601 | CyberSys |
43619168bbe67d887c4410779ccafd0308947c90 | 1,014 | hpp | C++ | include/pdmath/util.hpp | pdm-pcb/pdmath | 6c8ac4288c68bbe547e71f5bb7d1e44d3f1e35ab | [
"MIT"
] | null | null | null | include/pdmath/util.hpp | pdm-pcb/pdmath | 6c8ac4288c68bbe547e71f5bb7d1e44d3f1e35ab | [
"MIT"
] | null | null | null | include/pdmath/util.hpp | pdm-pcb/pdmath | 6c8ac4288c68bbe547e71f5bb7d1e44d3f1e35ab | [
"MIT"
] | null | null | null | #ifndef PDMATH_UTIL_HPP
#define PDMATH_UTIL_HPP
#include <cstdint>
#include <utility>
namespace pdm {
static constexpr uint8_t float_precision = 7;
static constexpr float float_epsilon = 1.0e-6f;
static float clamp(const float val, const float min, const float max) {
if(val > max) {
return max;
}
if(val < min) {
return min;
}
return val;
}
static float clamp(const float val, const std::pair<float, float> &min_max) {
if(val > min_max.second) {
return min_max.second;
}
if(val < min_max.first) {
return min_max.first;
}
return val;
}
static bool overlap(const std::pair<float, float> &a,
const std::pair<float, float> &b) {
return (a.second >= b.first) && (a.first <= b.second);
}
static bool overlap(const float a_min, const float a_max,
const float b_min, const float b_max) {
return (a_max >= b_min) && (a_min <= b_max);
}
} //namespace pdm
#endif // PDMATH_UTIL_HPP | 22.043478 | 77 | 0.616371 | pdm-pcb |
43635ffd74fb3e438de90879c7b7a1a68b5cf4ad | 734 | cpp | C++ | src/main.cpp | KentaKawamata/load_params | 98204612fccc301f92fa183fbbdec7381d70534a | [
"MIT"
] | null | null | null | src/main.cpp | KentaKawamata/load_params | 98204612fccc301f92fa183fbbdec7381d70534a | [
"MIT"
] | null | null | null | src/main.cpp | KentaKawamata/load_params | 98204612fccc301f92fa183fbbdec7381d70534a | [
"MIT"
] | null | null | null | #include <iostream>
#include "./../include/loadParams.hpp"
int main(int argc, char* argv[])
{
LoadParams *load;
load = new LoadParams();
float test_num = 0;
double test_double = 0;
//char test_error = 0;
std::string test_str;
bool test_bool = true;
load->get_param<float>("test3", test_num);
load->get_param<double>("test4", test_double);
//load->get_param<char>("test4", test_error);
load->get_param<std::string>("set_string", test_str);
load->get_param<bool>("set_bool", test_bool);
load->get_param<bool>("error_bool", test_bool);
std::cout << test_num << std::endl;
std::cout << test_double << std::endl;
std::cout << test_str << std::endl;
std::cout << test_bool << std::endl;
return 0;
}
| 25.310345 | 55 | 0.658038 | KentaKawamata |
436545db17f286d4dba949dc416e0433a9f6f77f | 1,058 | cpp | C++ | KetaminRudwolf/src/game/scene/SceneMenu.cpp | Vasile2k/KetaminRudwolf | 8e1703a2737c2ff914380a14c71f679e27786a10 | [
"Apache-2.0"
] | 5 | 2019-01-13T09:53:05.000Z | 2021-01-25T11:02:12.000Z | KetaminRudwolf/src/game/scene/SceneMenu.cpp | Vasile2k/KetaminRudwolf | 8e1703a2737c2ff914380a14c71f679e27786a10 | [
"Apache-2.0"
] | null | null | null | KetaminRudwolf/src/game/scene/SceneMenu.cpp | Vasile2k/KetaminRudwolf | 8e1703a2737c2ff914380a14c71f679e27786a10 | [
"Apache-2.0"
] | null | null | null | #include "SceneMenu.hpp"
#include "SceneOptions.hpp"
#include "SceneGame.hpp"
#include "../Game.hpp"
SceneMenu::SceneMenu(Scene*& currentScene) : currentScene(currentScene) {
}
SceneMenu::~SceneMenu() {
}
void SceneMenu::onUpdate(std::chrono::milliseconds deltaTime) {
}
void SceneMenu::onRender(Renderer* renderer) {
renderer->clear();
renderer->clearColor(0.176470588F, 0.176470588F, 0.176470588F, 1.0F);
}
void SceneMenu::onGUIRender(GUIRenderer* guiRenderer) {
guiRenderer->begin("Game", (float)Game::getInstance()->getWindow()->getWidth() / 2.0F - 100.0F, 100.0F, 200.0F, 300.0F);
guiRenderer->row(15, 1);
guiRenderer->row(70, 1);
if (guiRenderer->button("Play")) {
currentScene = new SceneGame();
}
guiRenderer->row(15, 1);
guiRenderer->row(70, 1);
if (guiRenderer->button("Options")) {
currentScene = new SceneOptions();
}
guiRenderer->row(15, 1);
guiRenderer->row(70, 1);
if (guiRenderer->button("Exit")) {
done = true;
}
guiRenderer->end();
}
void SceneMenu::onMouseButton(int button, int action, int modifiers) {
}
| 22.510638 | 121 | 0.694707 | Vasile2k |
436e7faa816efb828719d2e5174d8dc74b5b13a6 | 1,152 | cpp | C++ | src/pipeline/node/EdgeDetector.cpp | SpectacularAI/depthai-core | 7516ca0d179c5f0769ecdab0020ac3a6de09cab9 | [
"MIT"
] | 112 | 2020-09-05T01:56:31.000Z | 2022-03-27T15:20:07.000Z | src/pipeline/node/EdgeDetector.cpp | SpectacularAI/depthai-core | 7516ca0d179c5f0769ecdab0020ac3a6de09cab9 | [
"MIT"
] | 226 | 2020-06-12T11:14:17.000Z | 2022-03-31T13:32:36.000Z | src/pipeline/node/EdgeDetector.cpp | SpectacularAI/depthai-core | 7516ca0d179c5f0769ecdab0020ac3a6de09cab9 | [
"MIT"
] | 66 | 2020-09-06T03:22:27.000Z | 2022-03-30T09:01:29.000Z | #include "depthai/pipeline/node/EdgeDetector.hpp"
#include "spdlog/fmt/fmt.h"
namespace dai {
namespace node {
EdgeDetector::EdgeDetector(const std::shared_ptr<PipelineImpl>& par, int64_t nodeId)
: Node(par, nodeId), rawConfig(std::make_shared<RawEdgeDetectorConfig>()), initialConfig(rawConfig) {
inputs = {&inputConfig, &inputImage};
outputs = {&outputImage, &passthroughInputImage};
}
std::string EdgeDetector::getName() const {
return "EdgeDetector";
}
nlohmann::json EdgeDetector::getProperties() {
nlohmann::json j;
properties.initialConfig = *rawConfig;
nlohmann::to_json(j, properties);
return j;
}
// Node properties configuration
void EdgeDetector::setWaitForConfigInput(bool wait) {
properties.inputConfigSync = wait;
}
void EdgeDetector::setNumFramesPool(int numFramesPool) {
properties.numFramesPool = numFramesPool;
}
void EdgeDetector::setMaxOutputFrameSize(int maxFrameSize) {
properties.outputFrameSize = maxFrameSize;
}
std::shared_ptr<Node> EdgeDetector::clone() {
return std::make_shared<std::decay<decltype(*this)>::type>(*this);
}
} // namespace node
} // namespace dai
| 26.181818 | 105 | 0.736111 | SpectacularAI |
4370630b80632664eaa5738c62caa6c199609e2e | 26,711 | hpp | C++ | include/RAJA/policy/tensor/arch/cuda/cuda_warp.hpp | andrewcorrigan/RAJA | a326fad43321eadaebf75cb264461d3889ee6942 | [
"BSD-3-Clause"
] | null | null | null | include/RAJA/policy/tensor/arch/cuda/cuda_warp.hpp | andrewcorrigan/RAJA | a326fad43321eadaebf75cb264461d3889ee6942 | [
"BSD-3-Clause"
] | null | null | null | include/RAJA/policy/tensor/arch/cuda/cuda_warp.hpp | andrewcorrigan/RAJA | a326fad43321eadaebf75cb264461d3889ee6942 | [
"BSD-3-Clause"
] | null | null | null | /*!
******************************************************************************
*
* \file
*
* \brief Header file containing SIMT distrubuted register abstractions for
* CUDA
*
******************************************************************************
*/
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// Copyright (c) 2016-22, Lawrence Livermore National Security, LLC
// and RAJA project contributors. See the RAJA/LICENSE file for details.
//
// SPDX-License-Identifier: (BSD-3-Clause)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
#include "RAJA/config.hpp"
#include "RAJA/util/macros.hpp"
#include "RAJA/pattern/tensor/internal/RegisterBase.hpp"
#include "RAJA/util/macros.hpp"
#include "RAJA/util/Operators.hpp"
#ifdef RAJA_ENABLE_CUDA
#include "RAJA/policy/cuda/reduce.hpp"
#ifndef RAJA_policy_tensor_arch_cuda_cuda_warp_register_HPP
#define RAJA_policy_tensor_arch_cuda_cuda_warp_register_HPP
namespace RAJA
{
namespace expt
{
template<typename ELEMENT_TYPE>
class Register<ELEMENT_TYPE, cuda_warp_register> :
public internal::expt::RegisterBase<Register<ELEMENT_TYPE, cuda_warp_register>>
{
public:
using base_type = internal::expt::RegisterBase<Register<ELEMENT_TYPE, cuda_warp_register>>;
using register_policy = cuda_warp_register;
using self_type = Register<ELEMENT_TYPE, cuda_warp_register>;
using element_type = ELEMENT_TYPE;
using register_type = ELEMENT_TYPE;
using int_vector_type = Register<int64_t, cuda_warp_register>;
private:
element_type m_value;
public:
static constexpr int s_num_elem = 32;
/*!
* @brief Default constructor, zeros register contents
*/
RAJA_INLINE
RAJA_DEVICE
constexpr
Register() : base_type(), m_value(0) {
}
/*!
* @brief Copy constructor from raw value
*/
RAJA_INLINE
RAJA_DEVICE
constexpr
Register(element_type c) : base_type(), m_value(c) {}
/*!
* @brief Copy constructor
*/
RAJA_INLINE
RAJA_DEVICE
constexpr
Register(self_type const &c) : base_type(), m_value(c.m_value) {}
/*!
* @brief Copy assignment operator
*/
RAJA_INLINE
RAJA_DEVICE
self_type &operator=(self_type const &c){
m_value = c.m_value;
return *this;
}
RAJA_INLINE
RAJA_DEVICE
self_type &operator=(element_type c){
m_value = c;
return *this;
}
/*!
* @brief Gets our warp lane
*/
RAJA_INLINE
RAJA_DEVICE
constexpr
static
int get_lane() {
return threadIdx.x;
}
RAJA_DEVICE
RAJA_INLINE
constexpr
element_type const &get_raw_value() const {
return m_value;
}
RAJA_DEVICE
RAJA_INLINE
element_type &get_raw_value() {
return m_value;
}
RAJA_DEVICE
RAJA_INLINE
static
constexpr
bool is_root() {
return get_lane() == 0;
}
/*!
* @brief Load a full register from a stride-one memory location
*
*/
RAJA_INLINE
RAJA_DEVICE
self_type &load_packed(element_type const *ptr){
auto lane = get_lane();
m_value = ptr[lane];
return *this;
}
/*!
* @brief Partially load a register from a stride-one memory location given
* a run-time number of elements.
*
*/
RAJA_INLINE
RAJA_DEVICE
self_type &load_packed_n(element_type const *ptr, int N){
auto lane = get_lane();
if(lane < N){
m_value = ptr[lane];
}
else{
m_value = element_type(0);
}
return *this;
}
/*!
* @brief Gather a full register from a strided memory location
*
*/
RAJA_INLINE
RAJA_DEVICE
self_type &load_strided(element_type const *ptr, int stride){
auto lane = get_lane();
m_value = ptr[stride*lane];
return *this;
}
/*!
* @brief Partially load a register from a stride-one memory location given
* a run-time number of elements.
*
*/
RAJA_INLINE
RAJA_DEVICE
self_type &load_strided_n(element_type const *ptr, int stride, int N){
auto lane = get_lane();
if(lane < N){
m_value = ptr[stride*lane];
}
else{
m_value = element_type(0);
}
return *this;
}
/*!
* @brief Generic gather operation for full vector.
*
* Must provide another register containing offsets of all values
* to be loaded relative to supplied pointer.
*
* Offsets are element-wise, not byte-wise.
*
*/
RAJA_INLINE
RAJA_DEVICE
self_type &gather(element_type const *ptr, int_vector_type offsets){
m_value = ptr[offsets.get_raw_value()];
return *this;
}
/*!
* @brief Generic gather operation for n-length subvector.
*
* Must provide another register containing offsets of all values
* to be loaded relative to supplied pointer.
*
* Offsets are element-wise, not byte-wise.
*
*/
RAJA_INLINE
RAJA_DEVICE
self_type &gather_n(element_type const *ptr, int_vector_type offsets, camp::idx_t N){
if(get_lane() < N){
m_value = ptr[offsets.get_raw_value()];
}
else{
m_value = element_type(0);
}
return *this;
}
/*!
* @brief Generic segmented load operation used for loading sub-matrices
* from larger arrays.
*
* The default operation combines the s_segmented_offsets and gather
* operations.
*
*
*/
RAJA_DEVICE
RAJA_INLINE
self_type &segmented_load(element_type const *ptr, camp::idx_t segbits, camp::idx_t stride_inner, camp::idx_t stride_outer){
auto lane = get_lane();
// compute segment and segment_size
auto seg = lane >> segbits;
auto i = lane & ((1<<segbits)-1);
m_value = ptr[seg*stride_outer + i*stride_inner];
return *this;
}
/*!
* @brief Generic segmented load operation used for loading sub-matrices
* from larger arrays where we load partial segments.
*
*
*
*/
RAJA_DEVICE
RAJA_INLINE
self_type &segmented_load_nm(element_type const *ptr, camp::idx_t segbits,
camp::idx_t stride_inner, camp::idx_t stride_outer,
camp::idx_t num_inner, camp::idx_t num_outer)
{
auto lane = get_lane();
// compute segment and segment_size
auto seg = lane >> segbits;
auto i = lane & ((1<<segbits)-1);
if(seg >= num_outer || i >= num_inner){
m_value = element_type(0);
}
else{
m_value = ptr[seg*stride_outer + i*stride_inner];
}
return *this;
}
/*!
* @brief Store entire register to consecutive memory locations
*
*/
RAJA_INLINE
RAJA_DEVICE
self_type const &store_packed(element_type *ptr) const{
auto lane = get_lane();
ptr[lane] = m_value;
return *this;
}
/*!
* @brief Store entire register to consecutive memory locations
*
*/
RAJA_INLINE
RAJA_DEVICE
self_type const &store_packed_n(element_type *ptr, int N) const{
auto lane = get_lane();
if(lane < N){
ptr[lane] = m_value;
}
return *this;
}
/*!
* @brief Store entire register to consecutive memory locations
*
*/
RAJA_INLINE
RAJA_DEVICE
self_type const &store_strided(element_type *ptr, int stride) const{
auto lane = get_lane();
ptr[lane*stride] = m_value;
return *this;
}
/*!
* @brief Store partial register to consecutive memory locations
*
*/
RAJA_INLINE
RAJA_DEVICE
self_type const &store_strided_n(element_type *ptr, int stride, int N) const{
auto lane = get_lane();
if(lane < N){
ptr[lane*stride] = m_value;
}
return *this;
}
/*!
* @brief Generic scatter operation for full vector.
*
* Must provide another register containing offsets of all values
* to be stored relative to supplied pointer.
*
* Offsets are element-wise, not byte-wise.
*
*/
template<typename T2>
RAJA_DEVICE
RAJA_INLINE
self_type const &scatter(element_type *ptr, T2 const &offsets) const {
ptr[offsets.get_raw_value()] = m_value;
return *this;
}
/*!
* @brief Generic scatter operation for n-length subvector.
*
* Must provide another register containing offsets of all values
* to be stored relative to supplied pointer.
*
* Offsets are element-wise, not byte-wise.
*
*/
template<typename T2>
RAJA_DEVICE
RAJA_INLINE
self_type const &scatter_n(element_type *ptr, T2 const &offsets, camp::idx_t N) const {
if(get_lane() < N){
ptr[offsets.get_raw_value()] = m_value;
}
return *this;
}
/*!
* @brief Generic segmented store operation used for storing sub-matrices
* to larger arrays.
*
*/
RAJA_DEVICE
RAJA_INLINE
self_type const &segmented_store(element_type *ptr, camp::idx_t segbits, camp::idx_t stride_inner, camp::idx_t stride_outer) const {
auto lane = get_lane();
// compute segment and segment_size
auto seg = lane >> segbits;
auto i = lane & ((1<<segbits)-1);
ptr[seg*stride_outer + i*stride_inner] = m_value;
return *this;
}
/*!
* @brief Generic segmented store operation used for storing sub-matrices
* to larger arrays where we store partial segments.
*
*/
RAJA_DEVICE
RAJA_INLINE
self_type const &segmented_store_nm(element_type *ptr, camp::idx_t segbits,
camp::idx_t stride_inner, camp::idx_t stride_outer,
camp::idx_t num_inner, camp::idx_t num_outer) const
{
auto lane = get_lane();
// compute segment and segment_size
auto seg = lane >> segbits;
auto i = lane & ((1<<segbits)-1);
if(seg >= num_outer || i >= num_inner){
// nop
}
else{
ptr[seg*stride_outer + i*stride_inner] = m_value;
}
return *this;
}
/*!
* @brief Get scalar value from vector register
* @param i Offset of scalar to get
* @return Returns scalar value at i
*/
constexpr
RAJA_INLINE
RAJA_DEVICE
element_type get(int i) const
{
return __shfl_sync(0xffffffff, m_value, i, 32);
}
/*!
* @brief Set scalar value in vector register
* @param i Offset of scalar to set
* @param value Value of scalar to set
*/
RAJA_INLINE
RAJA_DEVICE
self_type &set(element_type value, int i)
{
auto lane = get_lane();
if(lane == i){
m_value = value;
}
return *this;
}
RAJA_DEVICE
RAJA_INLINE
self_type &broadcast(element_type const &a){
m_value = a;
return *this;
}
/*!
* @brief Extracts a scalar value and broadcasts to a new register
*/
RAJA_DEVICE
RAJA_INLINE
self_type get_and_broadcast(int i) const {
self_type x;
x.m_value = __shfl_sync(0xffffffff, m_value, i, 32);
return x;
}
RAJA_DEVICE
RAJA_INLINE
self_type ©(self_type const &src){
m_value = src.m_value;
return *this;
}
RAJA_DEVICE
RAJA_INLINE
self_type add(self_type const &b) const {
return self_type(m_value + b.m_value);
}
RAJA_DEVICE
RAJA_INLINE
self_type subtract(self_type const &b) const {
return self_type(m_value - b.m_value);
}
RAJA_DEVICE
RAJA_INLINE
self_type multiply(self_type const &b) const {
return self_type(m_value * b.m_value);
}
RAJA_DEVICE
RAJA_INLINE
self_type divide(self_type const &b) const {
return self_type(m_value / b.m_value);
}
RAJA_DEVICE
RAJA_INLINE
self_type divide_n(self_type const &b, int N) const {
return get_lane() < N ? self_type(m_value / b.m_value) : self_type(element_type(0));
}
/**
* floats and doubles use the CUDA instrinsic FMA
*/
template<typename RETURN_TYPE = self_type>
RAJA_DEVICE
RAJA_INLINE
typename std::enable_if<!std::numeric_limits<element_type>::is_integer,
RETURN_TYPE>::type
multiply_add(self_type const &b, self_type const &c) const
{
return self_type(fma(m_value, b.m_value, c.m_value));
}
/**
* int32 and int64 don't have a CUDA intrinsic FMA, do unfused ops
*/
template<typename RETURN_TYPE = self_type>
RAJA_DEVICE
RAJA_INLINE
typename std::enable_if<std::numeric_limits<element_type>::is_integer,
RETURN_TYPE>::type
multiply_add(self_type const &b, self_type const &c) const
{
return self_type(m_value * b.m_value + c.m_value);
}
/**
* floats and doubles use the CUDA instrinsic FMS
*/
template<typename RETURN_TYPE = self_type>
RAJA_DEVICE
RAJA_INLINE
typename std::enable_if<!std::numeric_limits<element_type>::is_integer,
RETURN_TYPE>::type
multiply_subtract(self_type const &b, self_type const &c) const
{
return self_type(fma(m_value, b.m_value, -c.m_value));
}
/**
* int32 and int64 don't have a CUDA intrinsic FMS, do unfused ops
*/
template<typename RETURN_TYPE = self_type>
RAJA_DEVICE
RAJA_INLINE
typename std::enable_if<std::numeric_limits<element_type>::is_integer,
RETURN_TYPE>::type
multiply_subtract(self_type const &b, self_type const &c) const
{
return self_type(m_value * b.m_value - c.m_value);
}
/*!
* @brief Sum the elements of this vector
* @return Sum of the values of the vectors scalar elements
*/
RAJA_INLINE
RAJA_DEVICE
element_type sum() const
{
// Allreduce sum
using combiner_t = RAJA::reduce::detail::op_adapter<element_type, RAJA::operators::plus>;
return RAJA::cuda::impl::warp_allreduce<combiner_t, element_type>(m_value);
}
/*!
* @brief Returns the largest element
* @return The largest scalar element in the register
*/
RAJA_INLINE
RAJA_DEVICE
element_type max() const
{
// Allreduce maximum
using combiner_t = RAJA::reduce::detail::op_adapter<element_type, RAJA::operators::maximum>;
return RAJA::cuda::impl::warp_allreduce<combiner_t, element_type>(m_value);
}
/*!
* @brief Returns the largest element
* @return The largest scalar element in the register
*/
RAJA_INLINE
RAJA_DEVICE
element_type max_n(int N) const
{
// Allreduce maximum
using combiner_t = RAJA::reduce::detail::op_adapter<element_type, RAJA::operators::maximum>;
auto ident = RAJA::operators::limits<element_type>::min();
auto lane = get_lane();
auto value = lane < N ? m_value : ident;
return RAJA::cuda::impl::warp_allreduce<combiner_t, element_type>(value);
}
/*!
* @brief Returns element-wise largest values
* @return Vector of the element-wise max values
*/
RAJA_INLINE
RAJA_DEVICE
self_type vmax(self_type a) const
{
return self_type{RAJA::max<element_type>(m_value, a.m_value)};
}
/*!
* @brief Returns the largest element
* @return The largest scalar element in the register
*/
RAJA_INLINE
RAJA_DEVICE
element_type min() const
{
// Allreduce minimum
using combiner_t = RAJA::reduce::detail::op_adapter<element_type, RAJA::operators::minimum>;
return RAJA::cuda::impl::warp_allreduce<combiner_t, element_type>(m_value);
}
/*!
* @brief Returns the largest element from first N lanes
* @return The largest scalar element in the register
*/
RAJA_INLINE
RAJA_DEVICE
element_type min_n(int N) const
{
// Allreduce minimum
using combiner_t = RAJA::reduce::detail::op_adapter<element_type, RAJA::operators::minimum>;
auto ident = RAJA::operators::limits<element_type>::max();
auto lane = get_lane();
auto value = lane < N ? m_value : ident;
return RAJA::cuda::impl::warp_allreduce<combiner_t, element_type>(value);
}
/*!
* @brief Returns element-wise largest values
* @return Vector of the element-wise max values
*/
RAJA_INLINE
RAJA_DEVICE
self_type vmin(self_type a) const
{
return self_type{RAJA::min<element_type>(m_value, a.m_value)};
}
/*!
* Provides gather/scatter indices for segmented loads and stores
*
* THe number of segment bits (segbits) is specified, as well as the
* stride between elements in a segment (stride_inner),
* and the stride between segments (stride_outer)
*/
RAJA_INLINE
RAJA_DEVICE
static
int_vector_type s_segmented_offsets(camp::idx_t segbits, camp::idx_t stride_inner, camp::idx_t stride_outer)
{
int_vector_type result;
auto lane = get_lane();
// compute segment and segment_size
auto seg = lane >> segbits;
auto i = lane & ((1<<segbits)-1);
result.get_raw_value() = seg*stride_outer + i*stride_inner;
return result;
}
/*!
* Sum elements within each segment, with segment size defined by segbits.
* Stores each segments sum consecutively, but shifed to the
* corresponding output_segment slot.
*
* Note: segment size is 1<<segbits elements
* number of segments is s_num_elem>>seg_bits
*
*
*
*
* Example:
*
* Given input vector X = x0, x1, x2, x3, x4, x5, x6, x7
*
* segbits=0 is equivalent to the input vector, since there are 8
* outputs, there is only 1 output segment
*
* Result= x0, x1, x2, x3, x4, x5, x6, x7
*
* segbits=1 sums neighboring pairs of values. There are 4 output,
* so there are possible output segments.
*
* output_segment=0:
* Result= x0+x1, x2+x3, x4+x5, x6+x7, 0, 0, 0, 0
*
* output_segment=1:
* Result= 0, 0, 0, 0, x0+x1, x2+x3, x4+x5, x6+x7
*
* and so on up to segbits=3, which is a full sum of x0..x7, and the
* output_segment denotes the vector position of the sum
*
*/
RAJA_INLINE
RAJA_DEVICE
self_type segmented_sum_inner(camp::idx_t segbits, camp::idx_t output_segment) const
{
// First: tree reduce values within each segment
element_type x = m_value;
RAJA_UNROLL
for(int delta = 1;delta < 1<<segbits;delta = delta<<1){
// tree shuffle
element_type y = __shfl_sync(0xffffffff, x, get_lane()+delta);
// reduce
x += y;
}
// Second: send result to output segment lanes
self_type result;
result.get_raw_value() = __shfl_sync(0xffffffff, x, get_lane()<<segbits);
// Third: mask off everything but output_segment
// this is because all output segments are valid at this point
// (5-segbits), the 5 is since the warp-width is 32 == 1<<5
int our_output_segment = get_lane()>>(5-segbits);
bool in_output_segment = our_output_segment == output_segment;
if(!in_output_segment){
result.get_raw_value() = 0;
}
return result;
}
/*!
* Sum across segments, with segment size defined by segbits
*
* Note: segment size is 1<<segbits elements
* number of segments is s_num_elem>>seg_bits
*
*
*
*
* Example:
*
* Given input vector X = x0, x1, x2, x3, x4, x5, x6, x7
*
* segbits=0 is equivalent to the input vector, since there are 8
* outputs, there is only 1 output segment
*
* Result= x0, x1, x2, x3, x4, x5, x6, x7
*
* segbits=1 sums strided pairs of values. There are 4 output,
* so there are possible output segments.
*
* output_segment=0:
* Result= x0+x4, x1+x5, x2+x6, x3+x7, 0, 0, 0, 0
*
* output_segment=1:
* Result= 0, 0, 0, 0, x0+x4, x1+x5, x2+x6, x3+x7
*
* and so on up to segbits=3, which is a full sum of x0..x7, and the
* output_segment denotes the vector position of the sum
*
*/
RAJA_INLINE
RAJA_DEVICE
self_type segmented_sum_outer(camp::idx_t segbits, camp::idx_t output_segment) const
{
// First: tree reduce values within each segment
element_type x = m_value;
RAJA_UNROLL
for(int i = 0;i < 5-segbits; ++ i){
// tree shuffle
int delta = s_num_elem >> (i+1);
element_type y = __shfl_sync(0xffffffff, x, get_lane()+delta);
// reduce
x += y;
}
// Second: send result to output segment lanes
self_type result;
int get_from = get_lane()&( (1<<segbits)-1);
result.get_raw_value() = __shfl_sync(0xffffffff, x, get_from);
int mask = (get_lane()>>segbits) == output_segment;
// Third: mask off everything but output_segment
if(!mask){
result.get_raw_value() = 0;
}
return result;
}
RAJA_INLINE
RAJA_DEVICE
self_type segmented_divide_nm(self_type den, camp::idx_t segbits, camp::idx_t num_inner, camp::idx_t num_outer) const
{
self_type result;
auto lane = get_lane();
// compute segment and segment_size
auto seg = lane >> segbits;
auto i = lane & ((1<<segbits)-1);
if(seg >= num_outer || i >= num_inner){
// nop
}
else{
result.get_raw_value() = m_value / den.get_raw_value();
}
return result;
}
/*!
* Segmented broadcast copies a segment to all output segments of a vector
*
* Note: segment size is 1<<segbits elements
* number of segments is s_num_elem>>seg_bits
*
*
* Example:
*
* Given input vector X = x0, x1, x2, x3, x4, x5, x6, x7
*
* segbits=0 means the input segment size is 1, so this selects the
* value at x[input_segmnet] and broadcasts it to the rest of the
* vector
*
* input segments allowed are from 0 to 7, inclusive
*
* input_segment=0
* Result= x0, x0, x0, x0, x0, x0, x0, x0
*
* input_segment=5
* Result= x5, x5, x5, x5, x5, x5, x5, x5
*
* segbits=1 means that the input segments are each pair of x values:
*
* input segments allowed are from 0 to 3, inclusive
*
* output_segment=0:
* Result= x0, x1, x0, x1, x0, x1, x0, x1
*
* output_segment=1:
* Result= x2, x3, x2, x3, x2, x3, x2, x3
*
* output_segment=3:
* Result= x6, x7, x6, x7, x6, x7, x6, x7
*
* and so on up to segbits=2, the input segments are 4 wide:
*
* input segments allowed are from 0 or 1
*
* output_segment=0:
* Result= x0, x1, x2, x3, x0, x1, x2, x3
*
* output_segment=1:
* Result= x4, x5, x6, x7, x4, x5, x6, x7
*
*/
RAJA_INLINE
RAJA_DEVICE
self_type segmented_broadcast_inner(camp::idx_t segbits, camp::idx_t input_segment) const
{
self_type result;
camp::idx_t mask = (1<<segbits)-1;
camp::idx_t offset = input_segment << segbits;
camp::idx_t i = (get_lane()&mask) + offset;
result.get_raw_value() = __shfl_sync(0xffffffff, m_value, i);
return result;
}
/*!
* Segmented broadcast spreads a segment to all output segments of a vector
*
* Note: segment size is 1<<segbits elements
* number of segments is s_num_elem>>seg_bits
*
*
* Example:
*
* Given input vector X = x0, x1, x2, x3, x4, x5, x6, x7
*
* segbits=0 means the input segment size is 1, so this selects the
* value at x[input_segmnet] and broadcasts it to the rest of the
* vector
*
* input segments allowed are from 0 to 7, inclusive
*
* input_segment=0
* Result= x0, x0, x0, x0, x0, x0, x0, x0
*
* input_segment=5
* Result= x5, x5, x5, x5, x5, x5, x5, x5
*
* segbits=1 means that the input segments are each pair of x values:
*
* input segments allowed are from 0 to 3, inclusive
*
* output_segment=0:
* Result= x0, x0, x0, x0, x1, x1, x1, x1
*
* output_segment=1:
* Result= x2, x2, x2, x2, x3, x3, x3, x3
*
* output_segment=3:
* Result= x6, x6, x6, x6, x7, x7, x7, x7
*/
RAJA_INLINE
RAJA_DEVICE
self_type segmented_broadcast_outer(camp::idx_t segbits, camp::idx_t input_segment) const
{
self_type result;
camp::idx_t offset = input_segment * (self_type::s_num_elem >> segbits);
camp::idx_t i = (get_lane() >> segbits) + offset;
result.get_raw_value() = __shfl_sync(0xffffffff, m_value, i);
return result;
}
};
} // namespace expt
} // namespace RAJA
#endif // Guard
#endif // CUDA
| 26.420376 | 138 | 0.565759 | andrewcorrigan |
43753501b3b17c99027017e4ac6f742120260517 | 4,172 | cpp | C++ | tests/async/StaticThreadPoolTests.cpp | MichaelE1000/libazul | 4a18c5d9d71722b09e04ab5d837d5f012ae4e8b0 | [
"MIT"
] | 3 | 2019-01-29T09:18:48.000Z | 2019-01-29T15:08:06.000Z | tests/async/StaticThreadPoolTests.cpp | MichaelE1000/libimpulso | 4a18c5d9d71722b09e04ab5d837d5f012ae4e8b0 | [
"MIT"
] | 1 | 2020-11-29T01:54:33.000Z | 2020-12-10T06:48:30.000Z | tests/async/StaticThreadPoolTests.cpp | MichaelE1000/libimpulso | 4a18c5d9d71722b09e04ab5d837d5f012ae4e8b0 | [
"MIT"
] | null | null | null | #include <gmock/gmock.h>
#include <azul/async/StaticThreadPool.hpp>
#include <thread>
class StaticThreadPoolTestFixture : public testing::Test
{
};
TEST_F(StaticThreadPoolTestFixture, Execute_EmptyTask_FutureReady)
{
azul::async::StaticThreadPool threadPool(1);
auto result = threadPool.Execute([](){});
result.Wait();
ASSERT_TRUE(result.IsReady());
ASSERT_NO_THROW(result.Get());
}
TEST_F(StaticThreadPoolTestFixture, Execute_TaskEnqueued_Success)
{
azul::async::StaticThreadPool executor(1);
auto result = executor.Execute([](){ return 42; });
ASSERT_EQ(42, result.Get());
}
TEST_F(StaticThreadPoolTestFixture, Execute_TaskThrowsException_ExceptionForwarded)
{
azul::async::StaticThreadPool executor(1);
auto result = executor.Execute([](){ throw std::invalid_argument(""); });
ASSERT_THROW(result.Get(), std::invalid_argument);
}
TEST_F(StaticThreadPoolTestFixture, Execute_MultipleTasksAndThreads_Success)
{
azul::async::StaticThreadPool executor(4);
std::vector<azul::async::Future<int>> results;
const int tasksToExecute = 100;
for (int i = 0; i < tasksToExecute; ++i)
{
auto result = executor.Execute([i](){ return i; });
results.emplace_back(std::move(result));
}
for (int i = 0; i < tasksToExecute; ++i)
{
ASSERT_EQ(i, results[i].Get());
}
}
TEST_F(StaticThreadPoolTestFixture, Execute_OneDependency_ExecutedInOrder)
{
azul::async::StaticThreadPool executor(2);
const auto firstTaskId = 1;
const auto secondTaskId = 2;
std::vector<int> ids;
auto action1 = [&]() { std::this_thread::sleep_for(std::chrono::milliseconds(50)); ids.push_back(firstTaskId); };
auto action2 = [&]() { ids.push_back(secondTaskId); };
auto future1 = executor.Execute(action1);
auto future2 = executor.Execute(action2, future1);
ASSERT_NO_THROW(future1.Get());
ASSERT_NO_THROW(future2.Get());
ASSERT_EQ(firstTaskId, ids[0]);
ASSERT_EQ(secondTaskId, ids[1]);
}
TEST_F(StaticThreadPoolTestFixture, Execute_DependencyThrowingException_FollowingTaskStillExecuted)
{
azul::async::StaticThreadPool executor(2);
auto action1 = [&]() { throw std::runtime_error(""); };
auto action2 = [&]() { };
auto future1 = executor.Execute(action1);
auto future2 = executor.Execute(action2, future1);
ASSERT_THROW(future1.Get(), std::runtime_error);
ASSERT_NO_THROW(future2.Get());
}
TEST_F(StaticThreadPoolTestFixture, Execute_MultipleDependencies_ValidExecutionOrder)
{
std::vector<int> executedTasks;
std::mutex mutex;
auto log_task_id = [&mutex, &executedTasks](const int id) mutable {
std::lock_guard<std::mutex> lock(mutex);
executedTasks.push_back(id);
};
azul::async::StaticThreadPool executor(2);
// dependency graph:
// task1 <---- task3 <------ task4
// task2 <-----------------|
auto future1 = executor.Execute(std::bind(log_task_id, 1));
auto future2 = executor.Execute(std::bind(log_task_id, 2));
auto future3 = executor.Execute(std::bind(log_task_id, 3), future1);
auto future4 = executor.Execute(std::bind(log_task_id, 4), future3, future2);
ASSERT_NO_THROW(future4.Get());
ASSERT_EQ(3, executedTasks[2]);
ASSERT_EQ(4, executedTasks[3]);
}
TEST_F(StaticThreadPoolTestFixture, Execute_MultipleTasksNoDependencies_AllThreadsOccupied)
{
std::vector<std::thread::id> utlizedThreadIds;
std::mutex mutex;
auto logThreadId = [&mutex, &utlizedThreadIds]() mutable {
std::lock_guard<std::mutex> lock(mutex);
utlizedThreadIds.push_back(std::this_thread::get_id());
};
azul::async::StaticThreadPool executor(4);
auto action = [&logThreadId](){
logThreadId();
std::this_thread::sleep_for(std::chrono::milliseconds(50));
};
std::vector<azul::async::Future<void>> futures;
for (std::size_t i = 0; i < executor.ThreadCount(); ++i)
{
futures.emplace_back(executor.Execute(action));
}
std::for_each(futures.begin(), futures.end(), [](auto f){ f.Wait(); });
ASSERT_EQ(utlizedThreadIds.size(), executor.ThreadCount());
}
| 28.972222 | 117 | 0.68001 | MichaelE1000 |
43792eec702b1dfe3031e6f480458443889048d9 | 3,065 | hpp | C++ | jigtest/src/application/characterobject.hpp | Ludophonic/JigLib | 541ec63b345ccf01e58cce49eb2f73c21eaf6aa6 | [
"Zlib"
] | 10 | 2016-06-01T12:54:45.000Z | 2021-09-07T17:34:37.000Z | jigtest/src/application/characterobject.hpp | Ludophonic/JigLib | 541ec63b345ccf01e58cce49eb2f73c21eaf6aa6 | [
"Zlib"
] | null | null | null | jigtest/src/application/characterobject.hpp | Ludophonic/JigLib | 541ec63b345ccf01e58cce49eb2f73c21eaf6aa6 | [
"Zlib"
] | 4 | 2017-05-03T14:03:03.000Z | 2021-01-04T04:31:15.000Z | //==============================================================
// Copyright (C) 2004 Danny Chapman
// danny@rowlhouse.freeserve.co.uk
//--------------------------------------------------------------
//
/// @file characterobject.hpp
//
//==============================================================
#ifndef CHARACTEROBJECT_HPP
#define CHARACTEROBJECT_HPP
#include "object.hpp"
#include "graphics.hpp"
#include "jiglib.hpp"
/// This is a game-object - i.e. a character that can be rendered.
class tCharacterObject : public tObject
{
public:
tCharacterObject(JigLib::tScalar radius, JigLib::tScalar height);
~tCharacterObject();
void SetProperties(JigLib::tScalar elasticity,
JigLib::tScalar staticFriction,
JigLib::tScalar dynamicFriction);
void SetDensity(JigLib::tScalar density, JigLib::tPrimitive::tPrimitiveProperties::tMassDistribution massDistribution = JigLib::tPrimitive::tPrimitiveProperties::SOLID);
void SetMass(JigLib::tScalar mass, JigLib::tPrimitive::tPrimitiveProperties::tMassDistribution massDistribution = JigLib::tPrimitive::tPrimitiveProperties::SOLID);
// inherited from tObject
JigLib::tBody * GetBody() {return &mBody;}
// inherited from tObject - interpolated between the physics old and
// current positions.
void SetRenderPosition(JigLib::tScalar renderFraction);
// inherited from tRenderObject
void Render(tRenderType renderType);
const JigLib::tSphere & GetRenderBoundingSphere() const;
const JigLib::tVector3 & GetRenderPosition() const;
const JigLib::tMatrix33 & GetRenderOrientation() const;
/// If start, then set control to be forward, else stop going forward
void ControlFwd(bool start);
void ControlBack(bool start);
void ControlLeft(bool start);
void ControlRight(bool start);
void ControlJump();
private:
class tCharacterBody : public JigLib::tBody
{
public:
virtual void PostPhysics(JigLib::tScalar dt);
JigLib::tScalar mDesiredFwdSpeed;
JigLib::tScalar mDesiredLeftSpeed;
JigLib::tScalar mJumpSpeed;
// used for smoothing
JigLib::tScalar mFwdSpeed;
JigLib::tScalar mLeftSpeed;
JigLib::tScalar mFwdSpeedRate;
JigLib::tScalar mLeftSpeedRate;
JigLib::tScalar mTimescale;
};
void UpdateControl();
tCharacterBody mBody;
JigLib::tCollisionSkin mCollisionSkin;
JigLib::tVector3 mLookDir;
JigLib::tVector3 mRenderPosition;
JigLib::tMatrix33 mRenderOrientation;
GLuint mDisplayListNum;
enum tMoveDir {MOVE_NONE = 1 << 0,
MOVE_FWD = 1 << 1,
MOVE_BACK = 1 << 2,
MOVE_LEFT = 1 << 3,
MOVE_RIGHT = 1 << 4};
/// bitmask from tMoveDir
unsigned mMoveDir;
JigLib::tScalar mBodyAngle; ///< in degrees - rotation around z
JigLib::tScalar mLookUpAngle; ///< in Degrees
JigLib::tScalar mMoveFwdSpeed;
JigLib::tScalar mMoveBackSpeed;
JigLib::tScalar mMoveSideSpeed;
JigLib::tScalar mJumpSpeed;
bool mDoJump;
};
#endif
| 30.959596 | 171 | 0.655791 | Ludophonic |
437c26dfb215bd0edcb62df9777a61c1a1158bf2 | 3,717 | hpp | C++ | global/test/TestCwd.hpp | AvciRecep/chaste_2019 | 1d46cdac647820d5c5030f8a9ea3a1019f6651c1 | [
"Apache-2.0",
"BSD-3-Clause"
] | 1 | 2020-04-05T12:11:54.000Z | 2020-04-05T12:11:54.000Z | global/test/TestCwd.hpp | AvciRecep/chaste_2019 | 1d46cdac647820d5c5030f8a9ea3a1019f6651c1 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | global/test/TestCwd.hpp | AvciRecep/chaste_2019 | 1d46cdac647820d5c5030f8a9ea3a1019f6651c1 | [
"Apache-2.0",
"BSD-3-Clause"
] | 2 | 2020-04-05T14:26:13.000Z | 2021-03-09T08:18:17.000Z | /*
Copyright (c) 2005-2019, University of Oxford.
All rights reserved.
University of Oxford means the Chancellor, Masters and Scholars of the
University of Oxford, having an administrative office at Wellington
Square, Oxford OX1 2JD, UK.
This file is part of Chaste.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the University of Oxford nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef _TESTCWD_HPP_
#define _TESTCWD_HPP_
#include <cxxtest/TestSuite.h>
#include <cstdlib>
#include <climits>
#include "FakePetscSetup.hpp"
#include "ChasteBuildRoot.hpp"
#include "GetCurrentWorkingDirectory.hpp"
#include "BoostFilesystem.hpp"
#include "IsNan.hpp"
/**
* Test for a strange 'feature' of Debian sarge systems, where the
* current working directory changes on PETSc initialisation. There
* is now code in PetscSetupUtils::CommonSetup() to work around this.
*/
class TestCwd : public CxxTest::TestSuite
{
public:
void TestShowCwd()
{
std::string chaste_source_root(ChasteSourceRootDir());
fs::path chaste_source_root_path(chaste_source_root);
fs::path cwd(GetCurrentWorkingDirectory()+"/");
TS_ASSERT(fs::equivalent(cwd,chaste_source_root));
}
void TestDivideOneByZero()
{
double one = 1.0;
double zero = 0.0;
double ans;
#ifdef TEST_FOR_FPE
// If we are testing for divide-by-zero, then this will throw an exception
//TS_ASSERT_THROWS_ANYTHING(ans = one / zero);
ans=zero*one;//otherwise compiler would complain
ans=ans*zero;//otherwise compiler would complain
#else
// If we aren't testing for it, then there will be no exception
TS_ASSERT_THROWS_NOTHING(ans = one / zero);
double negative_infinity = std::numeric_limits<double>::infinity();
TS_ASSERT_EQUALS(ans, negative_infinity);
#endif
}
void TestDivideZeroByZero()
{
double zero = 0.0;
double ans;
#ifdef TEST_FOR_FPE
// If we are testing for divide-by-zero, then this will throw an exception
//TS_ASSERT_THROWS_ANYTHING(ans = zero / zero);
ans=zero;//otherwise compiler would complain
ans=ans*zero;//otherwise compiler would complain
#else
// If we aren't testing for it, then there will be no exception
TS_ASSERT_THROWS_NOTHING(ans = zero / zero);
TS_ASSERT(std::isnan(ans));
#endif
}
};
#endif /*_TESTCWD_HPP_*/
| 36.441176 | 79 | 0.744149 | AvciRecep |
437ea4e95b0b958443b50b4fce650b1d03bb6792 | 10,121 | cpp | C++ | roomedit/source/lprogdlg.cpp | Darkman-M59/Meridian59_115 | 671b7ebe9fa2b1f40c8bd453652d596042291b90 | [
"FSFAP"
] | 1 | 2021-05-19T02:13:59.000Z | 2021-05-19T02:13:59.000Z | roomedit/source/lprogdlg.cpp | siwithaneye/Meridian59 | 9dc8df728d41ba354c9b11574484da5b3e013a87 | [
"FSFAP"
] | null | null | null | roomedit/source/lprogdlg.cpp | siwithaneye/Meridian59 | 9dc8df728d41ba354c9b11574484da5b3e013a87 | [
"FSFAP"
] | null | null | null | /*----------------------------------------------------------------------------*
| This file is part of WinDEU, the port of DEU to Windows. |
| WinDEU was created by the DEU team: |
| Renaud Paquay, Raphael Quinet, Brendon Wyber and others... |
| |
| DEU is an open project: if you think that you can contribute, please join |
| the DEU team. You will be credited for any code (or ideas) included in |
| the next version of the program. |
| |
| If you want to make any modifications and re-distribute them on your own, |
| you must follow the conditions of the WinDEU license. Read the file |
| LICENSE or README.TXT in the top directory. If do not have a copy of |
| these files, you can request them from any member of the DEU team, or by |
| mail: Raphael Quinet, Rue des Martyrs 9, B-4550 Nandrin (Belgium). |
| |
| This program comes with absolutely no warranty. Use it at your own risks! |
*----------------------------------------------------------------------------*
Project WinDEU
DEU team
Jul-Dec 1994, Jan-Mar 1995
FILE: lprogdlg.cpp
OVERVIEW
========
Source file for implementation of TLevelProgressDialog (TDialog).
*/
#include "common.h"
#pragma hdrstop
#ifndef __lprogdlg_h
#include "lprogdlg.h"
#endif
#ifndef __levels_h
#include "levels.h"
#endif
#ifndef __objects_h
#include "objects.h"
#endif
//
// Build a response table for all messages/commands handled
// by the application.
//
DEFINE_RESPONSE_TABLE1(TLevelProgressDialog, TDialog)
//{{TLevelProgressDialogRSP_TBL_BEGIN}}
EV_WM_SIZE,
EV_WM_PAINT,
//{{TLevelProgressDialogRSP_TBL_END}}
END_RESPONSE_TABLE;
//{{TLevelProgressDialog Implementation}}
///////////////////////////////////////////////////////////////
// TLevelProgressDialog
// --------------------
//
TLevelProgressDialog::TLevelProgressDialog (TWindow* parent, TResId resId,
TModule* module) :
TDialog(parent, resId, module)
{
Minimized = FALSE;
//
// Create interface object for NODES building
//
pNodesText = new TStatic (this, IDC_BUILD_NODES);
pNodesGauge = new TGauge (this, "%d%%", 200,
/*pNodesText->Attr.X,
pNodesText->Attr.Y+10,
pNodesText->Attr.W,
pNodesText->Attr.H*/
10, 20, 100, 10);
pNodesGauge->SetRange (0, 100);
pNodesGauge->SetValue (0);
pVertexesStatic = new TStatic (this, IDC_VERTEXES);
pSideDefsStatic = new TStatic (this, IDC_SIDEDEFS);
pSegsStatic = new TStatic (this, IDC_SEGS);
pSSectorsStatic = new TStatic (this, IDC_SSECTORS);
//
// Create interface object for REJECT building
//
pRejectFrame = new TStatic (this, IDC_FRAME_REJECT);
// pRejectFrame->Attr.Style &= ~(WS_VISIBLE);
pRejectText = new TStatic (this, IDC_BUILD_REJECT);
// pRejectText->Attr.Style &= ~(WS_VISIBLE);
pRejectGauge = new TGauge (this, "%d%%", 201,
/* pRejectText->Attr.X,
pRejectText->Attr.Y+10,
pRejectText->Attr.W,
pRejectText->Attr.H*/
10, 50, 100, 10);
// pRejectGauge->Attr.Style &= ~(WS_VISIBLE);
pRejectGauge->SetRange (0, 100);
pRejectGauge->SetValue (0);
//
// Create interface object for BLOCKMAP building
//
pBlockmapFrame = new TStatic (this, IDC_FRAME_BLOCKMAP);
// pBlockmapFrame->Attr.Style &= ~(WS_VISIBLE);
pBlockmapText = new TStatic (this, IDC_BUILD_BLOCKMAP);
// pBlockmapText->Attr.Style &= ~(WS_VISIBLE);
pBlockmapGauge = new TGauge (this, "%d%%", 202,
/* pBlockmapText->Attr.X,
pBlockmapText->Attr.Y+10,
pBlockmapText->Attr.W,
pBlockmapText->Attr.H*/
10, 80, 100, 10);
// pBlockmapGauge->Attr.Style &= ~(WS_VISIBLE);
pBlockmapGauge->SetRange (0, 100);
pBlockmapGauge->SetValue (0);
}
///////////////////////////////////////////////////////////////
// TLevelProgressDialog
// --------------------
//
TLevelProgressDialog::~TLevelProgressDialog ()
{
Destroy();
}
///////////////////////////////////////////////////////////////
// TLevelProgressDialog
// --------------------
//
void TLevelProgressDialog::SetupWindow ()
{
TRect wRect, cRect;
TPoint TopLeft ;
TDialog::SetupWindow();
::CenterWindow (this);
// Setup size and pos. of NODES gauge window
pNodesText->GetClientRect(cRect);
pNodesText->GetWindowRect(wRect);
TopLeft = TPoint(wRect.left, wRect.top);
ScreenToClient (TopLeft);
pNodesGauge->MoveWindow (TopLeft.x, TopLeft.y + 16,
cRect.right, 20, TRUE);
// Setup size and pos. of REJECT gauge window
pRejectText->GetClientRect(cRect);
pRejectText->GetWindowRect(wRect);
TopLeft = TPoint(wRect.left, wRect.top);
ScreenToClient (TopLeft);
pRejectGauge->MoveWindow (TopLeft.x, TopLeft.y + 16,
cRect.right, 20, TRUE);
// Setup size and pos. of BLOCKMAP gauge window
pBlockmapText->GetClientRect(cRect);
pBlockmapText->GetWindowRect(wRect);
TopLeft = TPoint(wRect.left, wRect.top);
ScreenToClient (TopLeft);
pBlockmapGauge->MoveWindow (TopLeft.x, TopLeft.y + 16,
cRect.right, 20, TRUE);
/*
pRejectText->ShowWindow (SW_HIDE);
pRejectFrame->ShowWindow (SW_HIDE);
pRejectGauge->ShowWindow (SW_HIDE);
*/
/*
pBlockmapText->ShowWindow (SW_HIDE);
pBlockmapFrame->ShowWindow (SW_HIDE);
pBlockmapGauge->ShowWindow (SW_HIDE);
*/
}
///////////////////////////////////////////////////////////////
// TLevelProgressDialog
// --------------------
//
void TLevelProgressDialog::ShowNodesProgress (int objtype)
{
static int SavedNumVertexes = 0;
char msg[10] ;
switch (objtype)
{
case OBJ_VERTEXES:
wsprintf (msg, "%d", NumVertexes);
pVertexesStatic->SetText (msg);
break;
case OBJ_SIDEDEFS:
wsprintf (msg, "%d", NumSideDefs);
pSideDefsStatic->SetText (msg);
SavedNumVertexes = NumVertexes;
break;
case OBJ_SSECTORS:
wsprintf (msg, "%d", NumSegs);
pSegsStatic->SetText (msg);
wsprintf (msg, "%d", NumSectors);
pSSectorsStatic->SetText (msg);
//BUG: We must test the division, because of empty levels
//
if (NumSideDefs + NumVertexes - SavedNumVertexes > 0 )
{
pNodesGauge->SetValue (100.0 * ((float) NumSegs /
(float) (NumSideDefs + NumVertexes -
SavedNumVertexes)));
}
else
pNodesGauge->SetValue (100);
// If minimized, we must paint the icon, else we paint the gauge
if ( Minimized )
{
Invalidate(FALSE); // Don't repaint background
UpdateWindow();
}
else
pNodesGauge->UpdateWindow();
break;
}
}
///////////////////////////////////////////////////////////////
// TLevelProgressDialog
// --------------------
//
void TLevelProgressDialog::ShowRejectControls ()
{
/*
pRejectFrame->ShowWindow (SW_SHOW);
pRejectText->ShowWindow (SW_SHOW);
pRejectGauge->ShowWindow (SW_SHOW);
*/
}
///////////////////////////////////////////////////////////////
// TLevelProgressDialog
// --------------------
//
void TLevelProgressDialog::ShowRejectProgress (int value)
{
pRejectGauge->SetValue (value);
// If minimized, we must paint the icon, else we paint the gauge
if ( Minimized )
{
Invalidate(FALSE); // Don't repaint background
UpdateWindow();
}
else
pRejectGauge->UpdateWindow ();
}
///////////////////////////////////////////////////////////////
// TLevelProgressDialog
// --------------------
//
void TLevelProgressDialog::ShowBlockmapControls ()
{
/*
pBlockmapFrame->ShowWindow (SW_SHOW);
pBlockmapText->ShowWindow (SW_SHOW);
pBlockmapGauge->ShowWindow (SW_SHOW);
*/
}
///////////////////////////////////////////////////////////////
// TLevelProgressDialog
// --------------------
//
void TLevelProgressDialog::ShowBlockmapProgress (int value)
{
pBlockmapGauge->SetValue (value);
// If minimized, we must paint the icon, else we paint the gauge
if ( Minimized )
{
Invalidate(FALSE); // Don't repaint background
UpdateWindow();
}
else
pBlockmapGauge->UpdateWindow ();
}
///////////////////////////////////////////////////////////////
// TLevelProgressDialog
// --------------------
//
void TLevelProgressDialog::EvSize (UINT sizeType, TSize& size)
{
if ( sizeType == SIZE_MINIMIZED )
{
Minimized = TRUE;
Parent->ShowWindow(SW_HIDE);
}
else if ( sizeType == SIZE_RESTORED )
{
Parent->ShowWindow(SW_SHOW);
Minimized = FALSE;
}
else
{
Minimized = FALSE;
TDialog::EvSize(sizeType, size);
}
}
///////////////////////////////////////////////////////////////
// TLevelProgressDialog
// --------------------
//
void DrawIconicGauge(TDC &dc, int yPosition, int Width, int Height, int Value)
{
TBrush BleueBrush(TColor(0,0,255));
TPen BleuePen (TColor(0,0,255));
// TBrush GrayBrush (TColor(200,200,200));
TPen WhitePen (TColor(255,255,255));
TPen GrayPen (TColor(100,100,100));
// TPen GrayPen (TColor(0,0,0));
// Draw upper left white border
dc.SelectObject(GrayPen);
dc.MoveTo(0, yPosition + Height - 1);
dc.LineTo(0, yPosition);
dc.LineTo(Width - 1, yPosition);
// Draw lower right border
dc.SelectObject(WhitePen);
dc.LineTo(Width - 1, yPosition + Height - 1);
dc.LineTo(0, yPosition + Height - 1);
// Draw gauge
dc.SelectObject(BleueBrush);
dc.SelectObject(BleuePen);
dc.Rectangle(1, yPosition + 1, (Width - 1) * Value / 100, yPosition + Height - 1);
dc.RestoreObjects();
}
///////////////////////////////////////////////////////////////
// TLevelProgressDialog
// --------------------
//
void TLevelProgressDialog::EvPaint ()
{
if ( Minimized )
{
TPaintDC dc(*this);
TRect ClientRect;
// Get size of iconic window
GetClientRect(ClientRect);
int Width = ClientRect.Width();
int Height = ClientRect.Height();
DrawIconicGauge (dc, 0,
Width, Height / 3, pNodesGauge->GetValue());
DrawIconicGauge (dc, Height / 3,
Width, Height / 3, pRejectGauge->GetValue());
DrawIconicGauge (dc, 2 * Height / 3,
Width, Height / 3, pBlockmapGauge->GetValue());
}
else
TDialog::EvPaint();
}
| 25.753181 | 83 | 0.590159 | Darkman-M59 |
438032ae65eb3f62d471f9f1951683f94f3378a9 | 531 | hpp | C++ | blocker/blockerd/Clouds/icloud.hpp | TheKuko/blocker | c19839ff65f7e31b3a428f902ce3c7cdf5ec46ab | [
"MIT"
] | null | null | null | blocker/blockerd/Clouds/icloud.hpp | TheKuko/blocker | c19839ff65f7e31b3a428f902ce3c7cdf5ec46ab | [
"MIT"
] | null | null | null | blocker/blockerd/Clouds/icloud.hpp | TheKuko/blocker | c19839ff65f7e31b3a428f902ce3c7cdf5ec46ab | [
"MIT"
] | null | null | null | //
// icloud.hpp
// blockerd
//
// Created by Jozef on 05/06/2020.
//
#ifndef icloud_hpp
#define icloud_hpp
#include "base.hpp"
struct ICloud : public CloudProvider
{
ICloud(const BlockLevel Bl, const std::vector<std::string> &Paths) {
id = CloudProviderId::ICLOUD;
bl = Bl;
paths = Paths;
allowedBundleIds = {
"com.apple.bird",
};
};
~ICloud() = default;
static std::vector<std::string> FindPaths(const std::string &homePath);
};
#endif /* icloud_hpp */
| 18.310345 | 75 | 0.596987 | TheKuko |
438641da74ef46a7b1fcdfb4a60cba87ea114d2e | 185 | cpp | C++ | Math.cpp | sknjpn/Math | 85de8d696f4f1ea212e998a076ee0c4dbd3956fa | [
"MIT"
] | null | null | null | Math.cpp | sknjpn/Math | 85de8d696f4f1ea212e998a076ee0c4dbd3956fa | [
"MIT"
] | null | null | null | Math.cpp | sknjpn/Math | 85de8d696f4f1ea212e998a076ee0c4dbd3956fa | [
"MIT"
] | null | null | null | #include "Math.hpp"
Vector2 operator*(float s, const Vector2& v) { return { v.x * s, v.y * s }; }
Vector3 operator*(float s, const Vector3& v) { return { v.x * s, v.y * s, v.z * s }; } | 46.25 | 86 | 0.589189 | sknjpn |
43883be75c6646f89c0b16b8e7648ffaae05e65c | 632 | inl | C++ | package/win32/android/gameplay/src/PhysicsConstraint.inl | sharkpp/openhsp | 0d412fd8f79a6ccae1d33c13addc06fb623fb1fe | [
"BSD-3-Clause"
] | 1 | 2021-06-17T02:16:22.000Z | 2021-06-17T02:16:22.000Z | package/win32/android/gameplay/src/PhysicsConstraint.inl | sharkpp/openhsp | 0d412fd8f79a6ccae1d33c13addc06fb623fb1fe | [
"BSD-3-Clause"
] | null | null | null | package/win32/android/gameplay/src/PhysicsConstraint.inl | sharkpp/openhsp | 0d412fd8f79a6ccae1d33c13addc06fb623fb1fe | [
"BSD-3-Clause"
] | 1 | 2021-04-06T14:58:08.000Z | 2021-04-06T14:58:08.000Z | #include "PhysicsConstraint.h"
namespace gameplay
{
inline float PhysicsConstraint::getBreakingImpulse() const
{
GP_ASSERT(_constraint);
return _constraint->getBreakingImpulseThreshold();
}
inline void PhysicsConstraint::setBreakingImpulse(float impulse)
{
GP_ASSERT(_constraint);
_constraint->setBreakingImpulseThreshold(impulse);
}
inline bool PhysicsConstraint::isEnabled() const
{
GP_ASSERT(_constraint);
return _constraint->isEnabled();
}
inline void PhysicsConstraint::setEnabled(bool enabled)
{
GP_ASSERT(_constraint);
_constraint->setEnabled(enabled);
}
}
| 20.387097 | 65 | 0.731013 | sharkpp |
438e255560f37998bb483abf87bface559867087 | 849 | cpp | C++ | CFB_Cursos/QT/Qtimer/Qtime/mainwindow.cpp | marcospontoexe/Cpp | d640be32fda2a25f871271e024efef727e7890c1 | [
"MIT"
] | null | null | null | CFB_Cursos/QT/Qtimer/Qtime/mainwindow.cpp | marcospontoexe/Cpp | d640be32fda2a25f871271e024efef727e7890c1 | [
"MIT"
] | null | null | null | CFB_Cursos/QT/Qtimer/Qtime/mainwindow.cpp | marcospontoexe/Cpp | d640be32fda2a25f871271e024efef727e7890c1 | [
"MIT"
] | null | null | null | #include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDateTime> //biblioteca para trabalhar com da e hora
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
tempo = new QTimer(this); //instanciando o objeto 'tempo'
connect(tempo, SIGNAL(timeout()), this, SLOT(relogio())); //conxão entr um sinal e um slot
tempo->start(1000); //dispara o sinal 'tempo' a cada 1 segundo, executando a função 'funcaoTempo'.
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::relogio()
{
QTime tempoatual = QTime::currentTime(); //retorna o tempo do sistema operacional
QString data = tempoatual.toString("hh:mm:ss"); //converte de QString para QString
ui->textEdit->setText(data);
}
| 30.321429 | 118 | 0.640754 | marcospontoexe |
43905339e20daf104fb8ad1aa63423c9a409019e | 7,832 | cpp | C++ | modules/unitest/core/test_perf_calculator.cpp | 7956968/CNStream | bcf746676c137bc6f21ab7ae3523c7ddf71737d0 | [
"Apache-2.0"
] | null | null | null | modules/unitest/core/test_perf_calculator.cpp | 7956968/CNStream | bcf746676c137bc6f21ab7ae3523c7ddf71737d0 | [
"Apache-2.0"
] | null | null | null | modules/unitest/core/test_perf_calculator.cpp | 7956968/CNStream | bcf746676c137bc6f21ab7ae3523c7ddf71737d0 | [
"Apache-2.0"
] | 1 | 2021-02-24T03:24:14.000Z | 2021-02-24T03:24:14.000Z | /*************************************************************************
* Copyright (C) [2019] by Cambricon, Inc. All rights reserved
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 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 <glog/logging.h>
#include <gtest/gtest.h>
#include <cmath>
#include <memory>
#include <string>
#include <vector>
#include "cnstream_time_utility.hpp"
#include "sqlite_db.hpp"
#include "perf_calculator.hpp"
#include "perf_manager.hpp"
namespace cnstream {
extern bool CreateDir(std::string path);
extern std::string gTestPerfDir;
extern std::string gTestPerfFile;
TEST(PerfCalculator, PrintLatency) {
PerfStats stats = {10100, 20010, 1600, 100.5};
PrintLatency(stats);
}
TEST(PerfCalculator, PrintThroughput) {
PerfStats stats = {10100, 20010, 1600, 100.5};
PrintThroughput(stats);
}
TEST(PerfCalculator, PrintPerfStats) {
PerfStats stats = {10123, 20001, 1600, 100.526};
PrintPerfStats(stats);
}
TEST(PerfCalculator, Construct) {
PerfCalculator perf_cal;
EXPECT_EQ(perf_cal.pre_time_, unsigned(0));
}
TEST(PerfCalculator, CalcLatency) {
CreateDir(gTestPerfDir);
remove(gTestPerfFile.c_str());
PerfCalculator perf_cal;
auto sql = std::make_shared<Sqlite>(gTestPerfFile);
std::string table_name = "TEST";
sql->Connect();
std::vector<std::string> keys = {"a", "b"};
sql->CreateTable(table_name, "ID", keys);
size_t total = 0;
size_t max = 0;
uint32_t data_num = 10;
for (uint32_t i = 0; i < data_num; i++) {
size_t start = TimeStamp::Current();
std::this_thread::sleep_for(std::chrono::microseconds(10 + i));
size_t end = TimeStamp::Current();
sql->Insert(table_name, "ID,a,b", std::to_string(i) + ","+ std::to_string(start) + "," + std::to_string(end));
size_t duration = end - start;
total += duration;
if (duration > max) max = duration;
}
PerfStats stats = perf_cal.CalcLatency(sql, table_name, keys[0], keys[1]);
#ifdef HAVE_SQLITE
EXPECT_EQ(stats.latency_avg, total / data_num);
EXPECT_EQ(stats.latency_max, max);
EXPECT_EQ(stats.frame_cnt, data_num);
EXPECT_EQ(perf_cal.GetLatency().latency_avg, total / data_num);
EXPECT_EQ(perf_cal.GetLatency().latency_max, max);
EXPECT_EQ(perf_cal.GetLatency().frame_cnt, data_num);
#else
EXPECT_EQ(stats.latency_avg, (unsigned)0);
EXPECT_EQ(stats.latency_max, (unsigned)0);
EXPECT_EQ(stats.frame_cnt, (unsigned)0);
#endif
remove(gTestPerfFile.c_str());
}
void CheckForZeroLatency(PerfStats stats, uint32_t line) {
EXPECT_EQ(stats.latency_avg, (unsigned)0) << "wrong line = " << line;
EXPECT_EQ(stats.latency_max, (unsigned)0) << "wrong line = " << line;
EXPECT_EQ(stats.frame_cnt, (unsigned)0) << "wrong line = " << line;
}
TEST(PerfCalculator, CalcLatencyFailedCase) {
CreateDir(gTestPerfDir);
remove(gTestPerfFile.c_str());
PerfCalculator perf_cal;
PerfStats stats = perf_cal.CalcLatency(nullptr, "", "", "");
CheckForZeroLatency(stats, __LINE__);
auto sql = std::make_shared<Sqlite>(gTestPerfFile);
std::string table_name = "TEST";
sql->Connect();
std::vector<std::string> keys = {"a", "b"};
sql->CreateTable(table_name, "ID", keys);
stats = perf_cal.CalcLatency(sql, "", "", "");
CheckForZeroLatency(stats, __LINE__);
// no start and end time
stats = perf_cal.CalcLatency(sql, table_name, keys[0], keys[1]);
CheckForZeroLatency(stats, __LINE__);
// no start, but only end time
size_t end = TimeStamp::Current();
sql->Insert(table_name, "ID,b", "0,"+ std::to_string(end));
stats = perf_cal.CalcLatency(sql, table_name, keys[0], keys[1]);
CheckForZeroLatency(stats, __LINE__);
std::this_thread::sleep_for(std::chrono::microseconds(10));
size_t start = TimeStamp::Current();
sql->Update(table_name, "a", std::to_string(start), "ID", "0");
// end - start is negtive
stats = perf_cal.CalcLatency(sql, table_name, keys[0], keys[1]);
CheckForZeroLatency(stats, __LINE__);
remove(gTestPerfFile.c_str());
}
TEST(PerfCalculator, CalcThroughputByTotalTime) {
CreateDir(gTestPerfDir);
remove(gTestPerfFile.c_str());
PerfCalculator perf_cal;
auto sql = std::make_shared<Sqlite>(gTestPerfFile);
std::string table_name = "TEST";
sql->Connect();
std::vector<std::string> keys = {"a", "b"};
sql->CreateTable(table_name, "ID", keys);
uint32_t data_num = 10;
size_t start = TimeStamp::Current();
sql->Insert(table_name, "ID,a,b", "0,"+ std::to_string(start) + "," + std::to_string(TimeStamp::Current()));
for (uint32_t i = 1; i < data_num - 1; i++) {
size_t s = TimeStamp::Current();
std::this_thread::sleep_for(std::chrono::microseconds(10 + i));
size_t e = TimeStamp::Current();
sql->Insert(table_name, "ID,a,b", std::to_string(i) + ","+ std::to_string(s) + "," + std::to_string(e));
}
size_t end = TimeStamp::Current();
sql->Insert(table_name, "ID,a,b", std::to_string(data_num - 1) + "," + std::to_string(TimeStamp::Current()) +
"," + std::to_string(end));
PerfStats stats = perf_cal.CalcThroughputByTotalTime(sql, table_name, keys[0], keys[1]);
#ifdef HAVE_SQLITE
EXPECT_EQ(stats.frame_cnt, data_num);
EXPECT_DOUBLE_EQ(stats.fps, ceil(static_cast<double>(data_num) * 1e7 / (end -start)) / 10.0);
#else
EXPECT_EQ(stats.frame_cnt, (unsigned)0);
EXPECT_DOUBLE_EQ(stats.fps, 0);
#endif
EXPECT_DOUBLE_EQ(stats.fps, perf_cal.GetThroughput().fps);
remove(gTestPerfFile.c_str());
}
TEST(PerfCalculator, CalcThroughputByTotalTimeFailedCase) {
CreateDir(gTestPerfDir);
remove(gTestPerfFile.c_str());
PerfCalculator perf_cal;
PerfStats stats = perf_cal.CalcThroughputByTotalTime(nullptr, "", "", "");
CheckForZeroLatency(stats, __LINE__);
auto sql = std::make_shared<Sqlite>(gTestPerfFile);
std::string table_name = "TEST";
sql->Connect();
std::vector<std::string> keys = {"a", "b"};
sql->CreateTable(table_name, "ID", keys);
stats = perf_cal.CalcThroughputByTotalTime(sql, "", "", "");
CheckForZeroLatency(stats, __LINE__);
// no start and end time
stats = perf_cal.CalcThroughputByTotalTime(sql, table_name, keys[0], keys[1]);
CheckForZeroLatency(stats, __LINE__);
// no start, but only end time
size_t end = TimeStamp::Current();
sql->Insert(table_name, "ID,b", "0,"+ std::to_string(end));
stats = perf_cal.CalcThroughputByTotalTime(sql, table_name, keys[0], keys[1]);
CheckForZeroLatency(stats, __LINE__);
std::this_thread::sleep_for(std::chrono::microseconds(10));
size_t start = TimeStamp::Current();
sql->Update(table_name, "a", std::to_string(start), "ID", "0");
// end - start is negtive
stats = perf_cal.CalcThroughputByTotalTime(sql, table_name, keys[0], keys[1]);
CheckForZeroLatency(stats, __LINE__);
// no end, but only start time
sql->Delete(table_name, "ID", "0");
sql->Insert(table_name, "ID,a", "0,"+ std::to_string(start));
stats = perf_cal.CalcThroughputByTotalTime(sql, table_name, keys[0], keys[1]);
CheckForZeroLatency(stats, __LINE__);
remove(gTestPerfFile.c_str());
}
} // namespace cnstream
| 36.943396 | 114 | 0.689479 | 7956968 |
43939f54f22cdeaf48879c39dcc06fe7c76f053f | 982 | hpp | C++ | src/stan/lang/ast/type/cholesky_factor_cov_block_type.hpp | ludkinm/stan | c318114f875266f22c98cf0bebfff928653727cb | [
"CC-BY-3.0",
"BSD-3-Clause"
] | null | null | null | src/stan/lang/ast/type/cholesky_factor_cov_block_type.hpp | ludkinm/stan | c318114f875266f22c98cf0bebfff928653727cb | [
"CC-BY-3.0",
"BSD-3-Clause"
] | null | null | null | src/stan/lang/ast/type/cholesky_factor_cov_block_type.hpp | ludkinm/stan | c318114f875266f22c98cf0bebfff928653727cb | [
"CC-BY-3.0",
"BSD-3-Clause"
] | null | null | null | #ifndef STAN_LANG_AST_CHOLESKY_FACTOR_COV_BLOCK_TYPE_HPP
#define STAN_LANG_AST_CHOLESKY_FACTOR_COV_BLOCK_TYPE_HPP
#include <stan/lang/ast/node/expression.hpp>
namespace stan {
namespace lang {
/**
* Cholesky factor for covariance matrix block var type.
*
* Note: no 1-arg constructor for square matrix;
* both row and column dimensions always required.
*/
struct cholesky_factor_cov_block_type {
/**
* Number of rows.
*/
expression M_;
/**
* Number of columns.
*/
expression N_;
/**
* Construct a block var type with default values.
*/
cholesky_factor_cov_block_type();
/**
* Construct a block var type with specified values.
*
* @param M num rows
* @param N num columns
*/
cholesky_factor_cov_block_type(const expression& M, const expression& N);
/**
* Get M (num rows).
*/
expression M() const;
/**
* Get N (num cols).
*/
expression N() const;
};
} // namespace lang
} // namespace stan
#endif
| 18.528302 | 75 | 0.675153 | ludkinm |
4395318524735808268a8d6502e3eaf914f4bf26 | 400 | hxx | C++ | sourceCode/dotNet4.6/wpf/src/Shared/inc/utils.hxx | csoap/csoap.github.io | 2a8db44eb63425deff147652b65c5912f065334e | [
"Apache-2.0"
] | 5 | 2017-03-03T02:13:16.000Z | 2021-08-18T09:59:56.000Z | sourceCode/dotNet4.6/wpf/src/Shared/inc/utils.hxx | 295007712/295007712.github.io | 25241dbf774427545c3ece6534be6667848a6faf | [
"Apache-2.0"
] | null | null | null | sourceCode/dotNet4.6/wpf/src/Shared/inc/utils.hxx | 295007712/295007712.github.io | 25241dbf774427545c3ece6534be6667848a6faf | [
"Apache-2.0"
] | 4 | 2016-11-15T05:20:12.000Z | 2021-11-13T16:32:11.000Z | #pragma once
#include <sal.h>
#include <codeanalysis/sourceannotations.h> // TEMPORARY INCLUDE
#include <Windows.h>
namespace WPFUtils {
LONG ReadRegistryString(__in HKEY rootKey, __in LPCWSTR keyName, __in LPCWSTR valueName,
__out LPWSTR value, size_t cchMax);
HRESULT GetWPFInstallPath(__out_ecount(cchMaxPath) LPWSTR pszPath, size_t cchMaxPath);
}
| 28.571429 | 92 | 0.71 | csoap |
4399b0c7d5ea94cc879f4d6cdfd02ef4c5ed5a9d | 6,283 | cpp | C++ | src/eepp/math/transform.cpp | jayrulez/eepp | 09c5c1b6b4c0306bb0a188474778c6949b5df3a7 | [
"MIT"
] | 37 | 2020-01-20T06:21:24.000Z | 2022-03-21T17:44:50.000Z | src/eepp/math/transform.cpp | jayrulez/eepp | 09c5c1b6b4c0306bb0a188474778c6949b5df3a7 | [
"MIT"
] | null | null | null | src/eepp/math/transform.cpp | jayrulez/eepp | 09c5c1b6b4c0306bb0a188474778c6949b5df3a7 | [
"MIT"
] | 9 | 2019-03-22T00:33:07.000Z | 2022-03-01T01:35:59.000Z | #include <cmath>
#include <eepp/math/transform.hpp>
namespace EE { namespace Math {
const Transform Transform::Identity;
Transform::Transform() {
// Identity matrix
mMatrix[0] = 1.f;
mMatrix[4] = 0.f;
mMatrix[8] = 0.f;
mMatrix[12] = 0.f;
mMatrix[1] = 0.f;
mMatrix[5] = 1.f;
mMatrix[9] = 0.f;
mMatrix[13] = 0.f;
mMatrix[2] = 0.f;
mMatrix[6] = 0.f;
mMatrix[10] = 1.f;
mMatrix[14] = 0.f;
mMatrix[3] = 0.f;
mMatrix[7] = 0.f;
mMatrix[11] = 0.f;
mMatrix[15] = 1.f;
}
Transform::Transform( float a00, float a01, float a02, float a10, float a11, float a12, float a20,
float a21, float a22 ) {
mMatrix[0] = a00;
mMatrix[4] = a01;
mMatrix[8] = 0.f;
mMatrix[12] = a02;
mMatrix[1] = a10;
mMatrix[5] = a11;
mMatrix[9] = 0.f;
mMatrix[13] = a12;
mMatrix[2] = 0.f;
mMatrix[6] = 0.f;
mMatrix[10] = 1.f;
mMatrix[14] = 0.f;
mMatrix[3] = a20;
mMatrix[7] = a21;
mMatrix[11] = 0.f;
mMatrix[15] = a22;
}
const float* Transform::getMatrix() const {
return mMatrix;
}
Transform Transform::getInverse() const {
// Compute the determinant
float det = mMatrix[0] * ( mMatrix[15] * mMatrix[5] - mMatrix[7] * mMatrix[13] ) -
mMatrix[1] * ( mMatrix[15] * mMatrix[4] - mMatrix[7] * mMatrix[12] ) +
mMatrix[3] * ( mMatrix[13] * mMatrix[4] - mMatrix[5] * mMatrix[12] );
// Compute the inverse if the determinant is not zero
// (don't use an epsilon because the determinant may *really* be tiny)
if ( det != 0.f ) {
return Transform( ( mMatrix[15] * mMatrix[5] - mMatrix[7] * mMatrix[13] ) / det,
-( mMatrix[15] * mMatrix[4] - mMatrix[7] * mMatrix[12] ) / det,
( mMatrix[13] * mMatrix[4] - mMatrix[5] * mMatrix[12] ) / det,
-( mMatrix[15] * mMatrix[1] - mMatrix[3] * mMatrix[13] ) / det,
( mMatrix[15] * mMatrix[0] - mMatrix[3] * mMatrix[12] ) / det,
-( mMatrix[13] * mMatrix[0] - mMatrix[1] * mMatrix[12] ) / det,
( mMatrix[7] * mMatrix[1] - mMatrix[3] * mMatrix[5] ) / det,
-( mMatrix[7] * mMatrix[0] - mMatrix[3] * mMatrix[4] ) / det,
( mMatrix[5] * mMatrix[0] - mMatrix[1] * mMatrix[4] ) / det );
} else {
return Identity;
}
}
Vector2f Transform::transformPoint( float x, float y ) const {
return Vector2f( mMatrix[0] * x + mMatrix[4] * y + mMatrix[12],
mMatrix[1] * x + mMatrix[5] * y + mMatrix[13] );
}
Vector2f Transform::transformPoint( const Vector2f& point ) const {
return transformPoint( point.x, point.y );
}
Rectf Transform::transformRect( const Rectf& rectangle ) const {
// Transform the 4 corners of the rectangle
const Vector2f points[] = {
transformPoint( rectangle.Left, rectangle.Top ),
transformPoint( rectangle.Left, rectangle.Top + rectangle.Bottom ),
transformPoint( rectangle.Left + rectangle.Right, rectangle.Top ),
transformPoint( rectangle.Left + rectangle.Right, rectangle.Top + rectangle.Bottom )};
// Compute the bounding rectangle of the transformed points
float left = points[0].x;
float top = points[0].y;
float right = points[0].x;
float bottom = points[0].y;
for ( int i = 1; i < 4; ++i ) {
if ( points[i].x < left )
left = points[i].x;
else if ( points[i].x > right )
right = points[i].x;
if ( points[i].y < top )
top = points[i].y;
else if ( points[i].y > bottom )
bottom = points[i].y;
}
return Rectf( left, top, right - left, bottom - top );
}
Transform& Transform::combine( const Transform& transform ) {
const float* a = mMatrix;
const float* b = transform.mMatrix;
*this = Transform(
a[0] * b[0] + a[4] * b[1] + a[12] * b[3], a[0] * b[4] + a[4] * b[5] + a[12] * b[7],
a[0] * b[12] + a[4] * b[13] + a[12] * b[15], a[1] * b[0] + a[5] * b[1] + a[13] * b[3],
a[1] * b[4] + a[5] * b[5] + a[13] * b[7], a[1] * b[12] + a[5] * b[13] + a[13] * b[15],
a[3] * b[0] + a[7] * b[1] + a[15] * b[3], a[3] * b[4] + a[7] * b[5] + a[15] * b[7],
a[3] * b[12] + a[7] * b[13] + a[15] * b[15] );
return *this;
}
Transform& Transform::translate( float x, float y ) {
Transform translation( 1, 0, x, 0, 1, y, 0, 0, 1 );
return combine( translation );
}
Transform& Transform::translate( const Vector2f& offset ) {
return translate( offset.x, offset.y );
}
Transform& Transform::rotate( float angle ) {
float rad = angle * 3.141592654f / 180.f;
float cos = std::cos( rad );
float sin = std::sin( rad );
Transform rotation( cos, -sin, 0, sin, cos, 0, 0, 0, 1 );
return combine( rotation );
}
Transform& Transform::rotate( float angle, float centerX, float centerY ) {
float rad = angle * 3.141592654f / 180.f;
float cos = std::cos( rad );
float sin = std::sin( rad );
Transform rotation( cos, -sin, centerX * ( 1 - cos ) + centerY * sin, sin, cos,
centerY * ( 1 - cos ) - centerX * sin, 0, 0, 1 );
return combine( rotation );
}
Transform& Transform::rotate( float angle, const Vector2f& center ) {
return rotate( angle, center.x, center.y );
}
Transform& Transform::scale( float scaleX, float scaleY ) {
Transform scaling( scaleX, 0, 0, 0, scaleY, 0, 0, 0, 1 );
return combine( scaling );
}
Transform& Transform::scale( float scaleX, float scaleY, float centerX, float centerY ) {
Transform scaling( scaleX, 0, centerX * ( 1 - scaleX ), 0, scaleY, centerY * ( 1 - scaleY ), 0,
0, 1 );
return combine( scaling );
}
Transform& Transform::scale( const Vector2f& factors ) {
return scale( factors.x, factors.y );
}
Transform& Transform::scale( const Vector2f& factors, const Vector2f& center ) {
return scale( factors.x, factors.y, center.x, center.y );
}
Transform operator*( const Transform& left, const Transform& right ) {
return Transform( left ).combine( right );
}
Transform& operator*=( Transform& left, const Transform& right ) {
return left.combine( right );
}
Vector2f operator*( const Transform& left, const Vector2f& right ) {
return left.transformPoint( right );
}
bool operator==( const Transform& left, const Transform& right ) {
const float* a = left.getMatrix();
const float* b = right.getMatrix();
return ( ( a[0] == b[0] ) && ( a[1] == b[1] ) && ( a[3] == b[3] ) && ( a[4] == b[4] ) &&
( a[5] == b[5] ) && ( a[7] == b[7] ) && ( a[12] == b[12] ) && ( a[13] == b[13] ) &&
( a[15] == b[15] ) );
}
bool operator!=( const Transform& left, const Transform& right ) {
return !( left == right );
}
}} // namespace EE::Math
| 30.352657 | 98 | 0.604488 | jayrulez |
439b2012e979640ea1aaa0bdaf7f644278b03299 | 10,721 | cpp | C++ | src/modules/processes/ImageIntegration/HDRCompositionParameters.cpp | GeorgViehoever/PCL | c4a4390185db3ccb04471f845d92917cc1bc1113 | [
"JasPer-2.0"
] | null | null | null | src/modules/processes/ImageIntegration/HDRCompositionParameters.cpp | GeorgViehoever/PCL | c4a4390185db3ccb04471f845d92917cc1bc1113 | [
"JasPer-2.0"
] | null | null | null | src/modules/processes/ImageIntegration/HDRCompositionParameters.cpp | GeorgViehoever/PCL | c4a4390185db3ccb04471f845d92917cc1bc1113 | [
"JasPer-2.0"
] | null | null | null | // ____ ______ __
// / __ \ / ____// /
// / /_/ // / / /
// / ____// /___ / /___ PixInsight Class Library
// /_/ \____//_____/ PCL 02.01.01.0784
// ----------------------------------------------------------------------------
// Standard ImageIntegration Process Module Version 01.09.04.0322
// ----------------------------------------------------------------------------
// HDRCompositionParameters.cpp - Released 2016/02/21 20:22:43 UTC
// ----------------------------------------------------------------------------
// This file is part of the standard ImageIntegration PixInsight module.
//
// Copyright (c) 2003-2016 Pleiades Astrophoto S.L. All Rights Reserved.
//
// Redistribution and use in both source and binary forms, with or without
// modification, is permitted provided that the following conditions are met:
//
// 1. All redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. All 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 names "PixInsight" and "Pleiades Astrophoto", nor the names
// of their contributors, may be used to endorse or promote products derived
// from this software without specific prior written permission. For written
// permission, please contact info@pixinsight.com.
//
// 4. All products derived from this software, in any form whatsoever, must
// reproduce the following acknowledgment in the end-user documentation
// and/or other materials provided with the product:
//
// "This product is based on software from the PixInsight project, developed
// by Pleiades Astrophoto and its contributors (http://pixinsight.com/)."
//
// Alternatively, if that is where third-party acknowledgments normally
// appear, this acknowledgment must be reproduced in the product itself.
//
// THIS SOFTWARE IS PROVIDED BY PLEIADES ASTROPHOTO 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 PLEIADES ASTROPHOTO OR ITS
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, BUSINESS
// INTERRUPTION; PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; AND LOSS OF USE,
// DATA OR PROFITS) 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 "HDRCompositionParameters.h"
namespace pcl
{
// ----------------------------------------------------------------------------
HCImages* TheHCImagesParameter = 0;
HCImageEnabled* TheHCImageEnabledParameter = 0;
HCImagePath* TheHCImagePathParameter = 0;
HCInputHints* TheHCInputHintsParameter = 0;
HCMaskBinarizingThreshold* TheHCMaskBinarizingThresholdParameter = 0;
HCMaskSmoothness* TheHCMaskSmoothnessParameter = 0;
HCMaskGrowth* TheHCMaskGrowthParameter = 0;
HCAutoExposures* TheHCAutoExposuresParameter = 0;
HCRejectBlack* TheHCRejectBlackParameter = 0;
HCUseFittingRegion* TheHCUseFittingRegionParameter = 0;
HCFittingRectX0* TheHCFittingRectX0Parameter = 0;
HCFittingRectY0* TheHCFittingRectY0Parameter = 0;
HCFittingRectX1* TheHCFittingRectX1Parameter = 0;
HCFittingRectY1* TheHCFittingRectY1Parameter = 0;
HCGenerate64BitResult* TheHCGenerate64BitResultParameter = 0;
HCOutputMasks* TheHCOutputMasksParameter = 0;
HCClosePreviousImages* TheHCClosePreviousImagesParameter = 0;
// ----------------------------------------------------------------------------
HCImages::HCImages( MetaProcess* P ) : MetaTable( P )
{
TheHCImagesParameter = this;
}
IsoString HCImages::Id() const
{
return "images";
}
// ----------------------------------------------------------------------------
HCImageEnabled::HCImageEnabled( MetaTable* T ) : MetaBoolean( T )
{
TheHCImageEnabledParameter = this;
}
IsoString HCImageEnabled::Id() const
{
return "enabled";
}
bool HCImageEnabled::DefaultValue() const
{
return true;
}
// ----------------------------------------------------------------------------
HCImagePath::HCImagePath( MetaTable* T ) : MetaString( T )
{
TheHCImagePathParameter = this;
}
IsoString HCImagePath::Id() const
{
return "path";
}
// ----------------------------------------------------------------------------
HCInputHints::HCInputHints( MetaProcess* P ) : MetaString( P )
{
TheHCInputHintsParameter = this;
}
IsoString HCInputHints::Id() const
{
return "inputHints";
}
// ----------------------------------------------------------------------------
HCMaskBinarizingThreshold::HCMaskBinarizingThreshold( MetaProcess* P ) : MetaFloat( P )
{
TheHCMaskBinarizingThresholdParameter = this;
}
IsoString HCMaskBinarizingThreshold::Id() const
{
return "maskBinarizingThreshold";
}
int HCMaskBinarizingThreshold::Precision() const
{
return 4;
}
double HCMaskBinarizingThreshold::DefaultValue() const
{
return 0.8;
}
double HCMaskBinarizingThreshold::MinimumValue() const
{
return 0;
}
double HCMaskBinarizingThreshold::MaximumValue() const
{
return 1;
}
// ----------------------------------------------------------------------------
HCMaskSmoothness::HCMaskSmoothness( MetaProcess* P ) : MetaInt32( P )
{
TheHCMaskSmoothnessParameter = this;
}
IsoString HCMaskSmoothness::Id() const
{
return "maskSmoothness";
}
double HCMaskSmoothness::DefaultValue() const
{
return 7;
}
double HCMaskSmoothness::MinimumValue() const
{
return 1;
}
double HCMaskSmoothness::MaximumValue() const
{
return 25;
}
// ----------------------------------------------------------------------------
HCMaskGrowth::HCMaskGrowth( MetaProcess* P ) : MetaInt32( P )
{
TheHCMaskGrowthParameter = this;
}
IsoString HCMaskGrowth::Id() const
{
return "maskGrowth";
}
double HCMaskGrowth::DefaultValue() const
{
return 1;
}
double HCMaskGrowth::MinimumValue() const
{
return 0;
}
double HCMaskGrowth::MaximumValue() const
{
return 15;
}
// ----------------------------------------------------------------------------
HCAutoExposures::HCAutoExposures( MetaProcess* P ) : MetaBoolean( P )
{
TheHCAutoExposuresParameter = this;
}
IsoString HCAutoExposures::Id() const
{
return "autoExposures";
}
bool HCAutoExposures::DefaultValue() const
{
return true;
}
// ----------------------------------------------------------------------------
HCRejectBlack::HCRejectBlack( MetaProcess* P ) : MetaBoolean( P )
{
TheHCRejectBlackParameter = this;
}
IsoString HCRejectBlack::Id() const
{
return "rejectBlack";
}
bool HCRejectBlack::DefaultValue() const
{
return true;
}
// ----------------------------------------------------------------------------
HCUseFittingRegion::HCUseFittingRegion( MetaProcess* P ) : MetaBoolean( P )
{
TheHCUseFittingRegionParameter = this;
}
IsoString HCUseFittingRegion::Id() const
{
return "useFittingRegion";
}
bool HCUseFittingRegion::DefaultValue() const
{
return false;
}
// ----------------------------------------------------------------------------
HCFittingRectX0::HCFittingRectX0( MetaProcess* P ) : MetaInt32( P )
{
TheHCFittingRectX0Parameter = this;
}
IsoString HCFittingRectX0::Id() const
{
return "fittingRectX0";
}
double HCFittingRectX0::DefaultValue() const
{
return 0;
}
double HCFittingRectX0::MinimumValue() const
{
return 0;
}
double HCFittingRectX0::MaximumValue() const
{
return int32_max;
}
// ----------------------------------------------------------------------------
HCFittingRectY0::HCFittingRectY0( MetaProcess* P ) : MetaInt32( P )
{
TheHCFittingRectY0Parameter = this;
}
IsoString HCFittingRectY0::Id() const
{
return "fittingRectY0";
}
double HCFittingRectY0::DefaultValue() const
{
return 0;
}
double HCFittingRectY0::MinimumValue() const
{
return 0;
}
double HCFittingRectY0::MaximumValue() const
{
return int32_max;
}
// ----------------------------------------------------------------------------
HCFittingRectX1::HCFittingRectX1( MetaProcess* P ) : MetaInt32( P )
{
TheHCFittingRectX1Parameter = this;
}
IsoString HCFittingRectX1::Id() const
{
return "fittingRectX1";
}
double HCFittingRectX1::DefaultValue() const
{
return 0;
}
double HCFittingRectX1::MinimumValue() const
{
return 0;
}
double HCFittingRectX1::MaximumValue() const
{
return int32_max;
}
// ----------------------------------------------------------------------------
HCFittingRectY1::HCFittingRectY1( MetaProcess* P ) : MetaInt32( P )
{
TheHCFittingRectY1Parameter = this;
}
IsoString HCFittingRectY1::Id() const
{
return "fittingRectY1";
}
double HCFittingRectY1::DefaultValue() const
{
return 0;
}
double HCFittingRectY1::MinimumValue() const
{
return 0;
}
double HCFittingRectY1::MaximumValue() const
{
return int32_max;
}
// ----------------------------------------------------------------------------
HCGenerate64BitResult::HCGenerate64BitResult( MetaProcess* P ) : MetaBoolean( P )
{
TheHCGenerate64BitResultParameter = this;
}
IsoString HCGenerate64BitResult::Id() const
{
return "generate64BitResult";
}
bool HCGenerate64BitResult::DefaultValue() const
{
return true;
}
// ----------------------------------------------------------------------------
HCOutputMasks::HCOutputMasks( MetaProcess* P ) : MetaBoolean( P )
{
TheHCOutputMasksParameter = this;
}
IsoString HCOutputMasks::Id() const
{
return "outputMasks";
}
bool HCOutputMasks::DefaultValue() const
{
return true;
}
// ----------------------------------------------------------------------------
HCClosePreviousImages::HCClosePreviousImages( MetaProcess* P ) : MetaBoolean( P )
{
TheHCClosePreviousImagesParameter = this;
}
IsoString HCClosePreviousImages::Id() const
{
return "closePreviousImages";
}
bool HCClosePreviousImages::DefaultValue() const
{
return false;
}
// ----------------------------------------------------------------------------
} // pcl
// ----------------------------------------------------------------------------
// EOF HDRCompositionParameters.cpp - Released 2016/02/21 20:22:43 UTC
| 24.759815 | 87 | 0.60125 | GeorgViehoever |
439b73ee9ce3bafe529940f35a3d499901dfd0ed | 3,468 | cpp | C++ | src/infra/Files.cpp | dim-lang/dim | 372c4f92030028621ddea9561364ea44a78b4671 | [
"Apache-2.0"
] | null | null | null | src/infra/Files.cpp | dim-lang/dim | 372c4f92030028621ddea9561364ea44a78b4671 | [
"Apache-2.0"
] | null | null | null | src/infra/Files.cpp | dim-lang/dim | 372c4f92030028621ddea9561364ea44a78b4671 | [
"Apache-2.0"
] | 4 | 2021-01-12T09:19:27.000Z | 2021-01-14T01:12:46.000Z | // Copyright 2019- <dim-lang>
// Apache License Version 2.0
#include "infra/Files.h"
#include "infra/Log.h"
#include <cerrno>
#include <cstdio>
#define BUF_SIZE 4096
namespace detail {
FileInfo::FileInfo(const Cowstr &fileName)
: fileName_(fileName), fp_(nullptr) {}
FileInfo::~FileInfo() {
if (fp_) {
std::fclose(fp_);
fp_ = nullptr;
}
}
const Cowstr &FileInfo::fileName() const { return fileName_; }
FileWriterImpl::FileWriterImpl(const Cowstr &fileName) : FileInfo(fileName) {}
FileWriterImpl::~FileWriterImpl() { flush(); }
void FileWriterImpl::reset(int offset) { std::fseek(fp_, offset, SEEK_SET); }
int FileWriterImpl::flush() {
if (buffer_.size() > 0) {
buffer_.writefile(fp_);
}
return std::fflush(fp_) ? errno : 0;
}
int FileWriterImpl::write(const Cowstr &buf) {
int r = buffer_.read(buf.rawstr(), buf.length());
if (buffer_.size() >= BUF_SIZE) {
buffer_.writefile(fp_, BUF_SIZE);
}
return r;
}
int FileWriterImpl::writeln(const Cowstr &buf) {
return write(buf) + write("\n");
}
} // namespace detail
FileReader::FileReader(const Cowstr &fileName) : detail::FileInfo(fileName) {
fp_ = std::fopen(fileName.rawstr(), "r");
LOG_ASSERT(fp_, "fp_ is null, open fileName {} failed", fileName);
}
FileMode FileReader::mode() const { return FileMode::Read; }
void FileReader::reset(int offset) { std::fseek(fp_, offset, SEEK_SET); }
void FileReader::prepareFor(int n) {
if (n <= 0) {
return;
}
if (buffer_.size() < n) {
int c = 0;
do {
c = buffer_.readfile(fp_, BUF_SIZE);
if (buffer_.size() >= n) {
break;
}
} while (c > 0);
}
}
Cowstr FileReader::read(int n) {
if (n <= 0) {
return "";
}
prepareFor(n);
char *buf = new char[n + 1];
std::memset(buf, 0, n + 1);
int c = buffer_.write(buf, n);
Cowstr r(buf, c);
delete[] buf;
return r;
}
Cowstr FileReader::readall() {
buffer_.readfile(fp_);
char *buf = new char[buffer_.size() + 1];
std::memset(buf, 0, buffer_.size() + 1);
int c = buffer_.write(buf, buffer_.size());
Cowstr r(buf, c);
delete[] buf;
return r;
}
Cowstr FileReader::readc() {
prepareFor(1);
char buf;
int c = buffer_.write(&buf, 1);
Cowstr r(&buf, c);
return r;
}
char *FileReader::prepareUntil(char c) {
char *linepos = nullptr;
int n = 0;
do {
n = buffer_.readfile(fp_, BUF_SIZE);
linepos = buffer_.search(c);
if (linepos) {
break;
}
} while (n > 0);
return linepos;
}
Cowstr FileReader::readln() {
char *linepos = prepareUntil('\n');
if (!linepos) {
return "";
}
int len = linepos - buffer_.begin() + 1;
char *buf = new char[len + 1];
std::memset(buf, 0, len + 1);
int c = buffer_.write(buf, len);
Cowstr r(buf, c);
delete[] buf;
return r;
}
FileWriter::FileWriter(const Cowstr &fileName)
: detail::FileWriterImpl(fileName) {
fp_ = std::fopen(fileName.rawstr(), "w");
ASSERT(fp_, "error: cannot open file {}", fileName);
}
FileMode FileWriter::mode() const { return FileMode::Write; }
void FileWriter::reset(int offset) { detail::FileWriterImpl::reset(offset); }
FileAppender::FileAppender(const Cowstr &fileName)
: detail::FileWriterImpl(fileName) {
fp_ = std::fopen(fileName.rawstr(), "a");
LOG_ASSERT(fp_, "fp_ is null, open fileName {} failed", fileName);
}
void FileAppender::reset(int offset) { detail::FileWriterImpl::reset(offset); }
FileMode FileAppender::mode() const { return FileMode::Append; }
| 22.666667 | 79 | 0.636678 | dim-lang |
439ee7bad86587b44ef2f6ff6d4144a80ddd2af8 | 3,146 | cpp | C++ | src/forced-random-dither.cpp | GhostatSpirit/hdrview | 61596f8ba45554db23ae1b214354ab40da065638 | [
"MIT"
] | 94 | 2021-04-23T03:31:15.000Z | 2022-03-29T08:20:26.000Z | src/forced-random-dither.cpp | GhostatSpirit/hdrview | 61596f8ba45554db23ae1b214354ab40da065638 | [
"MIT"
] | 64 | 2021-05-05T21:51:15.000Z | 2022-02-08T17:06:52.000Z | src/forced-random-dither.cpp | GhostatSpirit/hdrview | 61596f8ba45554db23ae1b214354ab40da065638 | [
"MIT"
] | 3 | 2021-07-06T04:58:27.000Z | 2022-02-08T16:53:48.000Z | /*!
force-random-dither.cpp -- Generate a dither matrix using the force-random-dither method from:
W. Purgathofer, R. F. Tobler and M. Geiler.
"Forced random dithering: improved threshold matrices for ordered dithering"
Image Processing, 1994. Proceedings. ICIP-94., IEEE International Conference,
Austin, TX, 1994, pp. 1032-1035 vol.2.
doi: 10.1109/ICIP.1994.413512
*/
//
// Copyright (C) Wojciech Jarosz <wjarosz@gmail.com>. All rights reserved.
// Use of this source code is governed by a BSD-style license that can
// be found in the LICENSE.txt file.
//
#include <iostream>
#include "array2d.h"
#include <nanogui/vector.h>
#include <vector>
#include <random>
#include <algorithm> // std::random_shuffle
#include <ctime> // std::time
#include <cstdlib> // std::rand, std::srand
using nanogui::Vector2i;
using namespace std;
const int Sm = 128;
const int Smk = Sm*Sm;
double toroidalMinimumDistance(const Vector2i & a, const Vector2i & b)
{
int x0 = min(a.x(), b.x());
int x1 = max(a.x(), b.x());
int y0 = min(a.y(), b.y());
int y1 = max(a.y(), b.y());
double deltaX = min(x1-x0, x0+Sm-x1);
double deltaY = min(y1-y0, y0+Sm-y1);
return sqrt(deltaX*deltaX + deltaY*deltaY);
}
double force(double r)
{
return exp(-sqrt(2*r));
}
int main(int, char **)
{
srand(unsigned ( std::time(0) ) );
std::mt19937 g_rand(unsigned ( std::time(0) ) );
vector<Vector2i> freeLocations;
Array2Dd M = Array2Dd(Sm,Sm,0.0);
Array2Dd forceField = Array2Dd(Sm,Sm,0.0);
// initialize free locations
for (int y = 0; y < Sm; ++y)
for (int x = 0; x < Sm; ++x)
freeLocations.push_back(Vector2i(x,y));
for (int ditherValue = 0; ditherValue < Smk; ++ditherValue)
{
shuffle(freeLocations.begin(), freeLocations.end(), g_rand);
double minimum = 1e20f;
Vector2i minimumLocation(0,0);
// int halfP = freeLocations.size();
int halfP = min(max(1, (int)sqrt(freeLocations.size()*3/4)), (int)freeLocations.size());
// int halfP = min(10, (int)freeLocations.size());
for (int i = 0; i < halfP; ++i)
{
const Vector2i & location = freeLocations[i];
if (forceField(location.x(), location.y()) < minimum)
{
minimum = forceField(location.x(), location.y());
minimumLocation = location;
}
}
Vector2i cell(0,0);
for (cell.y() = 0; cell.y() < Sm; ++cell.y())
for (cell.x() = 0; cell.x() < Sm; ++cell.x())
{
double r = toroidalMinimumDistance(cell, minimumLocation);
forceField(cell.x(), cell.y()) += force(r);
}
freeLocations.erase(remove(freeLocations.begin(), freeLocations.end(), minimumLocation), freeLocations.end());
M(minimumLocation.x(), minimumLocation.y()) = ditherValue;
// if (ditherValue % 16 == 0)
// {
// std::stringstream ss;
// ss << ditherValue;
// writeEXR("forceField-" + ss.str() + ".exr", forceField/(ditherValue+1));
// }
}
// std::cout << M << std::endl;
cout << "unsigned dither_matrix[" << Smk << "] = \n{\n ";
printf("%5d", (int)M(0));
for (int i = 1; i < M.size(); ++i)
{
cout << ", ";
if (i % Sm == 0)
cout << endl << " ";
printf("%5d", (int)M(i));
}
cout << "\n};" << endl;
return 0;
} | 26.888889 | 112 | 0.625238 | GhostatSpirit |
439efd4836183372aa61c81b4f9b78f67cab60ba | 1,656 | cc | C++ | dcmdata/libsrc/dcrledrg.cc | trice-imaging/dcmtk | 60b158654dc7215d938a9ddba92ef5e93ded298d | [
"Apache-2.0"
] | 29 | 2020-02-13T17:40:16.000Z | 2022-03-12T14:58:22.000Z | dcmdata/libsrc/dcrledrg.cc | trice-imaging/dcmtk | 60b158654dc7215d938a9ddba92ef5e93ded298d | [
"Apache-2.0"
] | 20 | 2020-03-20T18:06:31.000Z | 2022-02-25T08:38:08.000Z | dcmdata/libsrc/dcrledrg.cc | trice-imaging/dcmtk | 60b158654dc7215d938a9ddba92ef5e93ded298d | [
"Apache-2.0"
] | 9 | 2020-03-20T17:29:55.000Z | 2022-02-14T10:15:33.000Z | /*
*
* Copyright (C) 1994-2010, OFFIS e.V.
* All rights reserved. See COPYRIGHT file for details.
*
* This software and supporting documentation were developed by
*
* OFFIS e.V.
* R&D Division Health
* Escherweg 2
* D-26121 Oldenburg, Germany
*
*
* Module: dcmdata
*
* Author: Marco Eichelberg
*
* Purpose: singleton class that registers RLE decoder.
*
*/
#include "dcmtk/config/osconfig.h"
#include "dcmtk/dcmdata/dcrledrg.h"
#include "dcmtk/dcmdata/dccodec.h" /* for DcmCodecStruct */
#include "dcmtk/dcmdata/dcrleccd.h" /* for class DcmRLECodecDecoder */
#include "dcmtk/dcmdata/dcrlecp.h" /* for class DcmRLECodecParameter */
// initialization of static members
OFBool DcmRLEDecoderRegistration::registered = OFFalse;
DcmRLECodecParameter *DcmRLEDecoderRegistration::cp = NULL;
DcmRLECodecDecoder *DcmRLEDecoderRegistration::codec = NULL;
void DcmRLEDecoderRegistration::registerCodecs(
OFBool pCreateSOPInstanceUID,
OFBool pReverseDecompressionByteOrder)
{
if (! registered)
{
cp = new DcmRLECodecParameter(
pCreateSOPInstanceUID,
0, OFTrue, OFFalse,
pReverseDecompressionByteOrder);
if (cp)
{
codec = new DcmRLECodecDecoder();
if (codec) DcmCodecList::registerCodec(codec, NULL, cp);
registered = OFTrue;
}
}
}
void DcmRLEDecoderRegistration::cleanup()
{
if (registered)
{
DcmCodecList::deregisterCodec(codec);
delete codec;
delete cp;
registered = OFFalse;
#ifdef DEBUG
// not needed but useful for debugging purposes
codec = NULL;
cp = NULL;
#endif
}
}
| 24 | 72 | 0.67814 | trice-imaging |
43a573f202ee17d44a7fddeeca7e8de732f2eada | 355 | cpp | C++ | source/slang/slang-emit-precedence.cpp | KostasAndrianos/slang | 6cbc3929a54d37bd23cb5efa8e3320ba02f78b2f | [
"MIT"
] | null | null | null | source/slang/slang-emit-precedence.cpp | KostasAndrianos/slang | 6cbc3929a54d37bd23cb5efa8e3320ba02f78b2f | [
"MIT"
] | null | null | null | source/slang/slang-emit-precedence.cpp | KostasAndrianos/slang | 6cbc3929a54d37bd23cb5efa8e3320ba02f78b2f | [
"MIT"
] | null | null | null | // slang-emit-precedence.cpp
#include "slang-emit-precedence.h"
namespace Slang {
#define SLANG_OP_INFO_EXPAND(op, name, precedence) {name, kEPrecedence_##precedence##_Left, kEPrecedence_##precedence##_Right, },
/* static */const EmitOpInfo EmitOpInfo::s_infos[int(EmitOp::CountOf)] =
{
SLANG_OP_INFO(SLANG_OP_INFO_EXPAND)
};
} // namespace Slang
| 25.357143 | 129 | 0.752113 | KostasAndrianos |
43a94cbb80e5f92ae7af3af3af7dbec74132d904 | 27 | cpp | C++ | rtcsupport/I2CBuffer.cpp | jakesays/raspberrypi | 99192a56c097a79f45e2291110ebaa0dcb464ba8 | [
"MIT"
] | null | null | null | rtcsupport/I2CBuffer.cpp | jakesays/raspberrypi | 99192a56c097a79f45e2291110ebaa0dcb464ba8 | [
"MIT"
] | null | null | null | rtcsupport/I2CBuffer.cpp | jakesays/raspberrypi | 99192a56c097a79f45e2291110ebaa0dcb464ba8 | [
"MIT"
] | null | null | null | #include "I2CBuffer.h"
| 9 | 24 | 0.62963 | jakesays |
43ac354d931e7287bd01efed1ba0c56709ae637f | 988 | cpp | C++ | core/runtime/binaryen/module/wasm_module_instance_impl.cpp | igor-egorov/kagome | b2a77061791aa7c1eea174246ddc02ef5be1b605 | [
"Apache-2.0"
] | null | null | null | core/runtime/binaryen/module/wasm_module_instance_impl.cpp | igor-egorov/kagome | b2a77061791aa7c1eea174246ddc02ef5be1b605 | [
"Apache-2.0"
] | null | null | null | core/runtime/binaryen/module/wasm_module_instance_impl.cpp | igor-egorov/kagome | b2a77061791aa7c1eea174246ddc02ef5be1b605 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright Soramitsu Co., Ltd. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
#include "runtime/binaryen/module/wasm_module_instance_impl.hpp"
#include <binaryen/wasm.h>
namespace kagome::runtime::binaryen {
WasmModuleInstanceImpl::WasmModuleInstanceImpl(
std::shared_ptr<wasm::Module> parent,
const std::shared_ptr<RuntimeExternalInterface> &rei)
: parent_{std::move(parent)},
rei_{rei},
module_instance_{
std::make_unique<wasm::ModuleInstance>(*parent_, rei.get())} {
BOOST_ASSERT(parent_);
BOOST_ASSERT(rei_);
BOOST_ASSERT(module_instance_);
}
wasm::Literal WasmModuleInstanceImpl::callExportFunction(
wasm::Name name, const wasm::LiteralList &arguments) {
return module_instance_->callExport(name, arguments);
}
wasm::Literal WasmModuleInstanceImpl::getExportGlobal(wasm::Name name) {
return module_instance_->getExport(name);
}
} // namespace kagome::runtime::binaryen
| 29.939394 | 74 | 0.714575 | igor-egorov |
43ac64f6f5d0df2355e942b0ff46179e5ec85c7a | 575 | hpp | C++ | fileid/document/excel/records/ContinueRecord.hpp | DBHeise/fileid | 3e3bacf859445020999d0fc30301ac86973c3737 | [
"MIT"
] | 13 | 2016-03-13T17:57:46.000Z | 2021-12-21T12:11:41.000Z | fileid/document/excel/records/ContinueRecord.hpp | DBHeise/fileid | 3e3bacf859445020999d0fc30301ac86973c3737 | [
"MIT"
] | 9 | 2016-04-07T13:07:58.000Z | 2020-05-30T13:31:59.000Z | fileid/document/excel/records/ContinueRecord.hpp | DBHeise/fileid | 3e3bacf859445020999d0fc30301ac86973c3737 | [
"MIT"
] | 5 | 2017-04-20T14:47:55.000Z | 2021-03-08T03:27:17.000Z | #pragma once
#include "Record.hpp"
namespace oless {
namespace excel {
namespace records {
class ContinueRecord : public Record {
public:
ContinueRecord(IRecordParser* p, unsigned short type, std::vector<uint8_t> data) : Record(type, data) {
Record* r = p->GetPrevRecordNotOfType(type);
r->Data.insert(r->Data.end(), data.begin(), data.end());
//TODO: it is problematic to do this during parsing....need a better way
//if (IReParseable* pr = dynamic_cast<IReParseable*>(r)) {
// pr->ReParse(p);
//}
}
};
}
}
}
| 21.296296 | 107 | 0.626087 | DBHeise |
43ad4f10d88e55988d96738286fbc561964d48b8 | 140 | hxx | C++ | src/Providers/UNIXProviders/VLANEndpointSettingData/UNIX_VLANEndpointSettingData_AIX.hxx | brunolauze/openpegasus-providers-old | b00f1aad575bae144b8538bf57ba5fd5582a4ec7 | [
"MIT"
] | 1 | 2020-10-12T09:00:09.000Z | 2020-10-12T09:00:09.000Z | src/Providers/UNIXProviders/VLANEndpointSettingData/UNIX_VLANEndpointSettingData_AIX.hxx | brunolauze/openpegasus-providers-old | b00f1aad575bae144b8538bf57ba5fd5582a4ec7 | [
"MIT"
] | null | null | null | src/Providers/UNIXProviders/VLANEndpointSettingData/UNIX_VLANEndpointSettingData_AIX.hxx | brunolauze/openpegasus-providers-old | b00f1aad575bae144b8538bf57ba5fd5582a4ec7 | [
"MIT"
] | null | null | null | #ifdef PEGASUS_OS_AIX
#ifndef __UNIX_VLANENDPOINTSETTINGDATA_PRIVATE_H
#define __UNIX_VLANENDPOINTSETTINGDATA_PRIVATE_H
#endif
#endif
| 11.666667 | 48 | 0.864286 | brunolauze |
43ade173a48bf93b83f4c3593768397894cfe511 | 11,814 | cpp | C++ | Library/DS3231/Tests/main.cpp | JVKran/IPASS | 721cf7d481319bf6bd42f4a6b992658591f8a036 | [
"BSL-1.0"
] | 4 | 2019-07-04T17:38:11.000Z | 2021-04-24T19:50:36.000Z | Library/DS3231/Tests/main.cpp | JVKran/IPASS | 721cf7d481319bf6bd42f4a6b992658591f8a036 | [
"BSL-1.0"
] | 2 | 2020-04-08T18:10:06.000Z | 2020-04-08T19:11:50.000Z | Library/DS3231/Tests/main.cpp | JVKran/IPASS | 721cf7d481319bf6bd42f4a6b992658591f8a036 | [
"BSL-1.0"
] | null | null | null | /// @file
#include "hwlib.hpp"
#include "DS3231.hpp"
/// \brief
/// Test
/// \details
/// This program tests most of the functionality of the DS3231 Real Time clock.
int main( void ){
namespace target = hwlib::target;
auto scl = target::pin_oc( target::pins::d8 );
auto sda = target::pin_oc( target::pins::d9 );
auto i2c_bus = hwlib::i2c_bus_bit_banged_scl_sda(scl, sda);
auto clock = DS3231(i2c_bus);
auto time = timeData(15, 20, 10);
auto lastTime = timeData(5, 30);
auto bigTime = timeData(50, 60, 80);
//Uncomment is time is allowed to get overwritten
//clock.setTime(14, 20);
//clock.setDate(5, 7, 7, 2019);
hwlib::wait_ms(1000);
hwlib::cout << "---------------------------------TIME------------------------------" << hwlib::endl << hwlib::endl;
hwlib::cout << hwlib::left << hwlib::boolalpha << hwlib::setw(45) << "Initialization: " << ((time.getHours() == 15) && time.getMinutes() == 20 && time.getSeconds() == 10) << hwlib::endl;
hwlib::cout << hwlib::left << hwlib::setw(45) << "Too Large Initialization Handling: " << ((bigTime.getHours() == 0) && bigTime.getMinutes() == 0 && bigTime.getSeconds() == 0) << hwlib::endl;
time.setTime(11, 40, 55);
hwlib::cout << hwlib::left << hwlib::setw(45) << "Setting: " << ((time.getHours() == 11) && time.getMinutes() == 40 && time.getSeconds() == 55) << hwlib::endl;
time.setTime(80, 90, 100);
hwlib::cout << hwlib::left << hwlib::setw(45) << "Too Large Setting Handling: " << (time == timeData(0, 0, 0)) << hwlib::endl;
time.setTime(10, 30);
hwlib::cout << hwlib::endl << hwlib::left << hwlib::setw(45) << "Addition: " << time << " + " << lastTime << " = " << (time + lastTime) << hwlib::boolalpha << " " << ((time + lastTime) == timeData(16, 0, 0)) << hwlib::endl;
lastTime.setHours(18);
lastTime.setMinutes(15);
lastTime.setSeconds(55);
hwlib::cout << hwlib::left << hwlib::setw(45) << "Addition: " << time << " + " << lastTime << " = " << (time + lastTime) << hwlib::boolalpha << " " << ((time + lastTime) == timeData(4, 45, 55)) << hwlib::endl;
hwlib::cout << hwlib::left << hwlib::setw(45) << "Addition: " << timeData(0, 0) << " + " << timeData(0, 0) << " = " << (timeData(0+0, 0+0)) << " true" << hwlib::endl;
hwlib::cout << hwlib::left << hwlib::setw(45) << "Addition: " << timeData(23, 59) << " + " << timeData(23, 59) << " = " << (timeData(23, 59) + timeData(23, 59)) << " true" << hwlib::endl;
lastTime.setTime(5, 30);
time.setTime(10, 30);
hwlib::cout << hwlib::endl << hwlib::left << hwlib::setw(45) << "Setting and Substraction: " << time << " - " << lastTime << " = " << (time - lastTime) << hwlib::boolalpha << " " << ((time - lastTime) == timeData(5, 0, 0)) << hwlib::endl;
hwlib::cout << hwlib::left << hwlib::setw(45) << "Substraction: " << lastTime << " - " << time << " = " << (lastTime - time) << hwlib::boolalpha << " " << ((lastTime - time) == timeData(19, 0, 0)) << hwlib::endl;
hwlib::cout << hwlib::left << hwlib::setw(45) << "Substraction: " << timeData(23, 59) << " - " << timeData(23, 59) << " = " << (timeData(23, 59) - timeData(23, 59)) << " true" << hwlib::endl;
hwlib::cout << hwlib::left << hwlib::setw(45) << "Substraction: " << timeData(0, 15) << " - " << timeData(0, 30) << " = " << (timeData(0, 15) - timeData(0, 30)) << " true" << hwlib::endl;
lastTime.setTime(5, 30);
time.setTime(10, 30);
hwlib::cout << hwlib::endl << hwlib::left << hwlib::setw(45) << "Comparison: " << time << " < " << lastTime << " = " << (time < lastTime) << hwlib::endl;
hwlib::cout << hwlib::left << hwlib::setw(45) << "Comparison: " << timeData(11, 30) << " < " << timeData(11, 30, 10) << " = " << (timeData(11, 30) < timeData(11, 30, 10)) << hwlib::endl;
hwlib::cout << hwlib::left << hwlib::setw(45) << "Comparison: " << time << " <= " << lastTime << " = " << (time <= lastTime) << hwlib::endl;
hwlib::cout << hwlib::left << hwlib::setw(45) << "Comparison: " << time << " > " << lastTime << " = " << (time > lastTime) << hwlib::endl;
hwlib::cout << hwlib::left << hwlib::setw(45) << "Comparison: " << time << " >= " << lastTime << " = " << (time >= lastTime) << hwlib::endl;
hwlib::cout << hwlib::left << hwlib::setw(45) << "Comparison: " << timeData(11, 30) << " >= " << timeData(11, 30) << " = " << (timeData(11, 30) >= timeData(11, 30)) << hwlib::endl;
hwlib::cout << hwlib::left << hwlib::setw(45) << "Comparison: " << timeData(11, 30) << " <= " << timeData(11, 30) << " = " << (timeData(11, 30) <= timeData(11, 30)) << hwlib::endl;
hwlib::cout << hwlib::endl << hwlib::left << hwlib::setw(45) << "Equality: " << time << " == " << lastTime << " = " << (time == lastTime) << hwlib::endl;
hwlib::cout << hwlib::left << hwlib::setw(45) << "Unequality: " << lastTime << " != " << time << " = " << (lastTime != time) << hwlib::endl << hwlib::endl;
hwlib::cout << "---------------------------------DATE------------------------------" << hwlib::endl << hwlib::endl;
auto date = dateData(7, 30, 6, 2019);
auto lastDate = dateData(10, 35, 14, 2019);
hwlib::cout << hwlib::left << hwlib::setw(45) << "Initialization: " << (date.getWeekDay() == 7 && date.getMonthDay() == 30 && date.getMonth() == 6 && date.getYear() == 2019) << hwlib::endl;
hwlib::cout << hwlib::left << hwlib::setw(45) << "Too Large Initialization Handling: " << (lastDate.getWeekDay() == 1 && lastDate.getMonthDay() == 1 && lastDate.getMonth() == 1 && lastDate.getYear() == 2019) << hwlib::endl;
lastDate.setDate(7, 30, 6, 2019);
hwlib::cout << hwlib::left << hwlib::setw(45) << "Setting: " << (lastDate.getWeekDay() == 7 && lastDate.getMonthDay() == 30 && lastDate.getMonth() == 6 && lastDate.getYear() == 2019) << hwlib::endl;
lastDate.setDate(80, 90, 100, 2019);
hwlib::cout << hwlib::left << hwlib::setw(45) << "Too Large Setting Handling: " << (lastDate.getWeekDay() == 1 && lastDate.getMonthDay() == 1 && lastDate.getMonth() == 1 && lastDate.getYear() == 2019) << hwlib::endl;
date.setDate(1, 1, 1, 2019);
lastDate.setDate(7, 30, 6, 0);
hwlib::cout << hwlib::endl << hwlib::left << hwlib::setw(45) << "Addition: " << date.getWeekDay() << ", " << date << " + " << lastDate.getWeekDay() << ", " << lastDate << " = " << (date + lastDate) << hwlib::boolalpha << " " << ((date + lastDate) == dateData(1, 1, 8, 2019)) << hwlib::endl;
lastDate.setWeekDay(5);
lastDate.setMonthDay(15);
lastDate.setMonth(8);
lastDate.setYear(2000);
hwlib::cout << hwlib::left << hwlib::setw(45) << "Setting and Addition: " << date.getWeekDay() << ", " << date << " + " << lastDate.getWeekDay() << ", " << lastDate << " = " << (date + lastDate) << hwlib::boolalpha << " " << ((date + lastDate) == dateData(6, 16, 9, 4019)) << hwlib::endl;
hwlib::cout << hwlib::left << hwlib::setw(45) << "Addition: " << dateData(6, 20, 12, 2019) << " + " << dateData(6, 20, 5, 0) << " = " << (dateData(6, 20, 5, 0) + dateData(6, 20, 12, 2019)) << hwlib::boolalpha << " true" << hwlib::endl;
hwlib::cout << hwlib::left << hwlib::setw(45) << "Addition: " << dateData(1, 1, 1, 2000) << " + " << dateData(1, 1, 1, 0) << " = " << (dateData(1, 1, 1, 2000) + dateData(1, 1, 1, 0)) << hwlib::boolalpha << " true" << hwlib::endl;
date.setDate(5, 8, 10, 2019);
lastDate.setDate(4, 30, 8, 2000);
hwlib::cout << hwlib::endl << hwlib::left << hwlib::setw(45) << "Setting and Substraction: " << date.getWeekDay() << ", " << date << " - " << lastDate.getWeekDay() << ", " << lastDate << " = " << (date - lastDate) << hwlib::boolalpha << " " << ((date - lastDate) == dateData(1, 8, 1, 19)) << hwlib::endl;
hwlib::cout << hwlib::left << hwlib::setw(45) << "Substraction: " << lastDate.getWeekDay() << ", " << lastDate << " - " << date.getWeekDay() << ", " << date << " = " << (lastDate - date) << hwlib::boolalpha << " " << ((lastDate - date) == dateData(6, 22, 10, 0)) << hwlib::endl;
hwlib::cout << hwlib::left << hwlib::setw(45) << "Substraction: " << dateData(6, 20, 12, 2019) << " - " << dateData(6, 20, 5, 0) << " = " << (dateData(6, 20, 12, 0) - dateData(6, 20, 5, 2019)) << hwlib::boolalpha << " true" << hwlib::endl;
hwlib::cout << hwlib::left << hwlib::setw(45) << "Substraction: " << dateData(6, 1, 1, 2019) << " - " << dateData(6, 6, 6, 0) << " = " << (dateData(6, 1, 1, 2019) - dateData(6, 6, 6, 0)) << hwlib::boolalpha << " true" << hwlib::endl;
lastTime.setTime(5, 30);
time.setTime(10, 30);
hwlib::cout << hwlib::endl << hwlib::left << hwlib::setw(45) << "Comparison: " << date << " < " << lastDate << " = " << (date < lastDate) << hwlib::endl;
hwlib::cout << hwlib::left << hwlib::setw(45) << "Comparison: " << date << " <= " << lastDate << " = " << (date <= lastDate) << hwlib::endl;
hwlib::cout << hwlib::left << hwlib::setw(45) << "Comparison: " << dateData(1, 1, 12, 2019) << " <= " << dateData(1, 1, 12, 2019) << " = " << (dateData(1, 1, 12, 2019) <= dateData(1, 1, 12, 2019)) << hwlib::endl;
hwlib::cout << hwlib::left << hwlib::setw(45) << "Comparison: " << date << " > " << lastDate << " = " << (date > lastDate) << hwlib::endl;
hwlib::cout << hwlib::left << hwlib::setw(45) << "Comparison: " << dateData(1, 1, 12, 2019) << " > " << dateData(1, 1, 12, 2019) << " = " << (dateData(1, 1, 12, 2019) > dateData(1, 1, 12, 2019)) << hwlib::endl;
hwlib::cout << hwlib::left << hwlib::setw(45) << "Comparison: " << date << " >= " << lastDate << " = " << (date >= lastDate) << hwlib::endl;
hwlib::cout << hwlib::left << hwlib::setw(45) << "Comparison: " << dateData(1, 1, 12, 2019) << " > " << dateData(1, 1, 12, 2019) << " = " << (dateData(1, 1, 12, 2019) > dateData(1, 1, 12, 2019)) << hwlib::endl;
hwlib::cout << hwlib::endl << hwlib::left << hwlib::setw(45) << "Equality: " << date.getWeekDay() << ", " << date << " == " << lastDate.getWeekDay() << ", " << lastDate << " = " << (date == lastDate) << hwlib::endl;
hwlib::cout << hwlib::left << hwlib::setw(45) << "Unequality: " << date.getWeekDay() << ", " << date << " != " << lastDate.getWeekDay() << ", " << lastDate << " = " << (date != lastDate) << hwlib::endl << hwlib::endl;
hwlib::cout << "-------------------------------DS3231--------------------------------" << hwlib::endl << hwlib::endl;
hwlib::cout << hwlib::left << hwlib::setw(45) << "Initialization: " << (clock.getAddress() == 0x68) << hwlib::endl;
hwlib::cout << hwlib::endl;
for(unsigned int i = 0; i < 3; i++){
time = clock.getTime();
date = clock.getDate();
hwlib::cout << "Time: " << clock.getTime() << hwlib::endl;
hwlib::cout << "Temperature: " << int(clock.getTemperature() * 10) << hwlib::endl;
hwlib::cout << "Date: " << clock.getDate() << hwlib::endl << hwlib::endl;
hwlib::wait_ms(3000);
}
hwlib::cout << hwlib::endl;
//Uncomment if time is allowed to get lost. You'll have to set it again later.
//hwlib::cout << hwlib::left << hwlib::setw(45) << "Set time to 0:0:0 : ";
//clock.setTime(0, 0, 0);
//hwlib::cout << (clock.getTime() == timeData(0, 0, 0)) << hwlib::endl;
auto curTime = timeData();
for(unsigned int i = 0; i < 3; i++){
hwlib::cout << "Time: " << clock.getTime() << hwlib::endl;
hwlib::cout << "Temperature: " << int(clock.getTemperature() * 10) << hwlib::endl;
hwlib::cout << "Date: " << clock.getDate() << hwlib::endl << hwlib::endl;
curTime = clock.getTime();
curTime.setSeconds(curTime.getSeconds() + 10);
hwlib::cout << "Time to Trigger: " << curTime << hwlib::endl;
clock.clearAlarm(1);
clock.changeFirstAlarm(curTime, dateData(0, 0, 1, 2019));
clock.setFirstAlarm(14);
hwlib::cout << "Alarm set, should go in 10 seconds: ";
hwlib::wait_ms(30);
while(clock.checkAlarms() == 0){
hwlib::wait_ms(1000);
hwlib::cout << clock.getTime() << hwlib::endl;
}
hwlib::cout << "Triggered!" << hwlib::endl;
}
}
| 71.6 | 308 | 0.543592 | JVKran |
43ae71157c2744dcfbb201ee8af41a1373cb3232 | 1,047 | cpp | C++ | PopSyn/IPF_Setup.cpp | kravitz/transims4 | ea0848bf3dc71440d54724bb3ecba3947b982215 | [
"NASA-1.3"
] | 2 | 2018-04-27T11:07:02.000Z | 2020-04-24T06:53:21.000Z | PopSyn/IPF_Setup.cpp | idkravitz/transims4 | ea0848bf3dc71440d54724bb3ecba3947b982215 | [
"NASA-1.3"
] | null | null | null | PopSyn/IPF_Setup.cpp | idkravitz/transims4 | ea0848bf3dc71440d54724bb3ecba3947b982215 | [
"NASA-1.3"
] | null | null | null | //*********************************************************
// IPF_Setup.cpp - initialize the IPF classes
//*********************************************************
#include "PopSyn.hpp"
//---------------------------------------------------------
// IPF_Setup
//---------------------------------------------------------
void PopSyn::IPF_Setup (Household_Model *model_ptr)
{
int i, attributes;
Attribute_Type *at_ptr;
//---- clear memory ----
ipf_data.Clear ();
//---- copy the attribute types ----
attributes = model_ptr->Num_Attributes ();
for (i=1; i <= attributes; i++) {
at_ptr = model_ptr->Attribute (i);
if (!ipf_data.Add_Attribute (at_ptr->Num_Types ())) {
Error ("Adding IPF Attribute");
}
}
//---- set data cells ----
if (!ipf_data.Set_Cells ()) {
Error ("Creating IPF Cells");
}
//---- initialize the stage2 process ----
if (!stage2_data.Set_Stage_Two (&ipf_data)) {
Error ("Creating Stage2 Data");
}
//---- sum the zone targets and normalize the weights ----
model_ptr->Sum_Targets ();
}
| 20.94 | 59 | 0.489016 | kravitz |
43b0da23ae953e9de1c7a2e8e22ee0f8fe18e17f | 2,799 | cpp | C++ | libs/utils/src/console.cpp | suilteam/spark-xy | d07dc98c12c8842af0f11bf27d59161cb80f99b0 | [
"MIT"
] | null | null | null | libs/utils/src/console.cpp | suilteam/spark-xy | d07dc98c12c8842af0f11bf27d59161cb80f99b0 | [
"MIT"
] | null | null | null | libs/utils/src/console.cpp | suilteam/spark-xy | d07dc98c12c8842af0f11bf27d59161cb80f99b0 | [
"MIT"
] | null | null | null | /**
* Copyright (c) 2022 Suilteam, Carter Mbotho
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the MIT license. See LICENSE for details.
*
* @author Carter
* @date 2022-03-12
*/
#include "suil/utils/console.hpp"
namespace suil::Console {
void cprint(uint8_t color, int bold, const char *str) {
if (color >= 0 && color <= CYAN)
printf("\033[%s3%dm", (bold ? "1;" : ""), color);
(void) printf("%s", str);
printf("\033[0m");
}
void cprintv(uint8_t color, int bold, const char *fmt, va_list args) {
if (color > 0 && color <= CYAN)
printf("\033[%s3%dm", (bold ? "1;" : ""), color);
(void) vprintf(fmt, args);
printf("\033[0m");
}
void cprintf(uint8_t color, int bold, const char *fmt, ...) {
va_list args;
va_start(args, fmt);
cprintv(color, bold, fmt, args);
va_end(args);
}
void println(const char *fmt, ...) {
va_list args;
va_start(args, fmt);
vprintf(fmt, args);
va_end(args);
printf("\n");
}
void red(const char *fmt, ...) {
va_list args;
va_start(args, fmt);
cprintv(RED, 0, fmt, args);
va_end(args);
}
void blue(const char *fmt, ...) {
va_list args;
va_start(args, fmt);
cprintv(BLUE, 0, fmt, args);
va_end(args);
}
void green(const char *fmt, ...) {
va_list args;
va_start(args, fmt);
cprintv(GREEN, 0, fmt, args);
va_end(args);
}
void yellow(const char *fmt, ...) {
va_list args;
va_start(args, fmt);
cprintv(YELLOW, 0, fmt, args);
va_end(args);
}
void magenta(const char *fmt, ...) {
va_list args;
va_start(args, fmt);
cprintv(MAGENTA, 0, fmt, args);
va_end(args);
}
void cyan(const char *fmt, ...) {
va_list args;
va_start(args, fmt);
cprintv(CYAN, 0, fmt, args);
va_end(args);
}
void log(const char *fmt, ...) {
va_list args;
va_start(args, fmt);
printf(fmt, args);
printf("\n");
printf("\n");
va_end(args);
}
void info(const char *fmt, ...) {
va_list args;
va_start(args, fmt);
cprintv(GREEN, 0, fmt, args);
printf("\n");
va_end(args);
}
void error(const char *fmt, ...) {
va_list args;
va_start(args, fmt);
cprintv(RED, 0, fmt, args);
printf("\n");
va_end(args);
}
void warn(const char *fmt, ...) {
va_list args;
va_start(args, fmt);
cprintv(YELLOW, 0, fmt, args);
printf("\n");
va_end(args);
}
} | 23.521008 | 74 | 0.503751 | suilteam |
43b3b9423a191557cb0ae25d6443cbdaa270c3b2 | 734 | cpp | C++ | pronto/core/entities/cylinder.cpp | MgBag/pronto | c10827e094726d8dc285c3da68c9c03be42d9a32 | [
"MIT"
] | null | null | null | pronto/core/entities/cylinder.cpp | MgBag/pronto | c10827e094726d8dc285c3da68c9c03be42d9a32 | [
"MIT"
] | null | null | null | pronto/core/entities/cylinder.cpp | MgBag/pronto | c10827e094726d8dc285c3da68c9c03be42d9a32 | [
"MIT"
] | null | null | null | #include "Cylinder.h"
#include "core/world.h"
#include "core/application.h"
#include "core/components/model.h"
#include "platform/resource.h"
#include "platform/renderer.h"
#include "core/components/fps_controller.h"
#include "core/components/directional_light.h"
#include <glm/gtc/quaternion.hpp>
namespace pronto
{
//-----------------------------------------------------------------------------------------------
Cylinder::Cylinder(World* world) :
Entity(world),
model_(nullptr)
{
model_ = AddComponent<Model>();
model_->SetModel("resource/cylinder/scene.gltf");
transform()->SetScale(glm::vec3(0.05f));
AddComponent<DirectionalLight>();
}
void Cylinder::Update()
{
Entity::Update();
}
}
| 25.310345 | 99 | 0.606267 | MgBag |
43b56f7d53d26c6d64609fc80f79bf135632d154 | 3,680 | hpp | C++ | src/tools/lvr2_dmc_reconstruction/Options.hpp | uos/lvr | 9bb03a30441b027c39db967318877e03725112d5 | [
"BSD-3-Clause"
] | 38 | 2019-06-19T15:10:35.000Z | 2022-02-16T03:08:24.000Z | src/tools/lvr2_dmc_reconstruction/Options.hpp | uos/lvr | 9bb03a30441b027c39db967318877e03725112d5 | [
"BSD-3-Clause"
] | 9 | 2019-06-19T16:19:51.000Z | 2021-09-17T08:31:25.000Z | src/tools/lvr2_dmc_reconstruction/Options.hpp | uos/lvr | 9bb03a30441b027c39db967318877e03725112d5 | [
"BSD-3-Clause"
] | 13 | 2019-04-16T11:50:32.000Z | 2020-11-26T07:47:44.000Z | /**
* Copyright (c) 2018, University Osnabrück
* 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 University Osnabrück 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 University Osnabrück 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.
*/
/*
* OptionsDMC.hpp
*
* Created on: May 13, 2020
* Author: Benedikt SChumacher
*/
#ifndef OPTIONSDMC_H_
#define OPTIONSDMC_H_
#include "lvr2/config/BaseOption.hpp"
#include <boost/program_options.hpp>
#include <float.h>
#include <iostream>
#include <string>
#include <vector>
using std::cout;
using std::endl;
using std::ostream;
using std::string;
using std::vector;
using namespace lvr2;
namespace dmc_reconstruction
{
class Options : public BaseOption
{
public:
Options(int argc, char** argv);
virtual ~Options();
string getInputFileName() const;
int getMaxLevel() const;
float getMaxError() const;
/*
* prints information about needed command-line-inputs e.g: input-file (ply)
*/
bool printUsage() const;
int getKd() const;
int getKn() const;
int getKi() const;
int getNumThreads() const;
string getPCM() const;
bool useRansac() const;
string getScanPoseFile() const;
private:
/// The maximum allows octree level
int m_maxLevel;
/// The max allowed error between points and surfaces in an octree cell
float m_maxError;
/// The number of neighbors for distance function evaluation
int m_kd;
/// The number of neighbors for normal estimation
int m_kn;
/// The number of neighbors for normal interpolation
int m_ki;
/// The number of threads to use
int m_numThreads;
/// The used point cloud manager
string m_pcm;
};
/// Output the Options - overloaded output Operator
inline ostream& operator<<(ostream& os, const Options& o)
{
// o.printTransformation(os);
cout << "##### InputFile-Name: " << o.getInputFileName() << endl;
cout << "##### Max Level: " << o.getMaxLevel() << endl;
cout << "##### Max Error: " << o.getMaxError() << endl;
cout << "##### PCM: " << o.getPCM() << endl;
cout << "##### KD: " << o.getKd() << endl;
cout << "##### KI: " << o.getKi() << endl;
cout << "##### KN: " << o.getKn() << endl;
return os;
}
} // namespace dmc_reconstruction
#endif // OPTIONSDMC_H_
| 28.307692 | 82 | 0.685598 | uos |
43b696e347eb74bffb556bdda893267b36551bae | 2,558 | cpp | C++ | archived/polint.cpp | HiTMonitor/ginan | f348e2683507cfeca65bb58880b3abc2f9c36bcf | [
"Apache-2.0"
] | 1 | 2022-03-31T15:16:19.000Z | 2022-03-31T15:16:19.000Z | archived/polint.cpp | hqy123-cmyk/ginan | b69593b584f75e03238c1c667796e2030391fbed | [
"Apache-2.0"
] | null | null | null | archived/polint.cpp | hqy123-cmyk/ginan | b69593b584f75e03238c1c667796e2030391fbed | [
"Apache-2.0"
] | null | null | null | // /* Slightly modified versions of the "polint" routine from
// * Press, William H., Brian P. Flannery, Saul A. Teukolsky and
// * William T. Vetterling, 1986, "Numerical Recipes: The Art of
// * Scientific Computing" (Fortran), Cambrigde University Press,
// * pp. 80-82.
// */
//
// #include <stdio.h>
// #include <malloc.h>
// #include <math.h>
//
// void polint( double *xa, double *ya, int n, double x, double *y, double *dy );
//
// void polint( double *xa, double *ya, int n, double x, double *y, double *dy )
// {
// double *c = NULL;
// double *d = NULL;
// double den;
// double dif;
// double dift;
// double ho;
// double hp;
// double w;
//
// int i;
// int m;
// int ns;
//
// if( (c = (double *)malloc( n * sizeof( double ) )) == NULL ||
// (d = (double *)malloc( n * sizeof( double ) )) == NULL ) {
// fprintf( stderr, "polint error: allocating workspace\n" );
// fprintf( stderr, "polint error: setting y = 0 and dy = 1e9\n" );
// *y = 0.0;
// *dy = 1.e9;
//
// if( c != NULL )
// free( c );
// if( d != NULL )
// free( d );
// return;
// }
//
// ns = 0;
// dif = fabs(x-xa[0]);
// for( i = 0; i < n; ++i ) {
// dift = fabs( x-xa[i] );
// if( dift < dif ) {
// ns = i;
// dif = dift;
// }
// c[i] = ya[i];
// d[i] = ya[i];
// }
// *y = ya[ns];
// ns = ns-1;
// for( m = 0; m < n-1; ++m ) {
// for( i = 0; i < n-m-1; ++i ) {
// ho = xa[i]-x;
// hp = xa[i+m+1]-x;
// w = c[i+1]-d[i];
// den = ho-hp;
// if( den == 0 ) {
// fprintf( stderr, "polint error: den = 0\n" );
// fprintf( stderr, "polint error: setting y = 0 and dy = 1e9\n" );
// *y = 0.0;
// *dy = 1.e9;
//
// if( c != NULL )
// free( c );
// if( d != NULL )
// free( d );
// return;
// }
// den = w/den;
// d[i] = hp*den;
// c[i] = ho*den;
// }
// if( 2*(ns+1) < n-m-1 ) {
// *dy = c[ns+1];
// } else {
// *dy = d[ns];
// ns = ns-1;
// }
// *y = (*y)+(*dy);
// }
//
//
// if( c != NULL )
// free( c );
// if( d != NULL )
// free( d );
// return;
// }
| 27.212766 | 83 | 0.361611 | HiTMonitor |
43b95c45f8b50309059b953bb60226a52c18dc93 | 910 | hpp | C++ | testsuite/src/MacroCommandTestVO.hpp | roversun/puremvc-cpp-multicore-framework | 3e80412d5049a427637c6130a9bf6dbf029bf4bb | [
"CC-BY-3.0",
"BSD-3-Clause"
] | 2 | 2019-09-04T09:34:13.000Z | 2019-09-04T09:34:16.000Z | testsuite/src/MacroCommandTestVO.hpp | roversun/puremvc-cpp-multicore-framework | 3e80412d5049a427637c6130a9bf6dbf029bf4bb | [
"CC-BY-3.0",
"BSD-3-Clause"
] | null | null | null | testsuite/src/MacroCommandTestVO.hpp | roversun/puremvc-cpp-multicore-framework | 3e80412d5049a427637c6130a9bf6dbf029bf4bb | [
"CC-BY-3.0",
"BSD-3-Clause"
] | null | null | null | // MacroCommandTestVO.hpp
// PureMVC_C++ Test suite
//
// PureMVC Port to C++ by Tang Khai Phuong <phuong.tang@puremvc.org>
// PureMVC - Copyright(c) 2006-2011 Futurescale, Inc., Some rights reserved.
// Your reuse is governed by the Creative Commons Attribution 3.0 License
//
#if !defined(MACRO_COMMAND_TEST_VO_HPP)
#define MACRO_COMMAND_TEST_VO_HPP
namespace data
{
/**
* A utility class used by MacroCommandTest.
*/
struct MacroCommandTestVO
{
int input;
int result1;
int result2;
/**
* Constructor.
*
* @param input the number to be fed to the MacroCommandTestCommand
*/
MacroCommandTestVO(int input)
{
this->input = input;
this->result1 = 0;
this->result2 = 0;
}
};
}
#endif /* MACRO_COMMAND_TEST_VO_HPP */
| 24.594595 | 78 | 0.581319 | roversun |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.